2025-04-02 22:08:17 +01:00

2 lines
7.7 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*! For license information please see callComposite.js.LICENSE.txt */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.callComposite=t():e.callComposite=t()}(self,(()=>(()=>{var e,t,i={2222:(e,t,i)=>{"use strict";var n=i(2900),r={"text/plain":"Text","text/html":"Url",default:"Text"};e.exports=function(e,t){var i,s,a,o,l,c,d=!1;t||(t={}),i=t.debug||!1;try{if(a=n(),o=document.createRange(),l=document.getSelection(),(c=document.createElement("span")).textContent=e,c.ariaHidden="true",c.style.all="unset",c.style.position="fixed",c.style.top=0,c.style.clip="rect(0, 0, 0, 0)",c.style.whiteSpace="pre",c.style.webkitUserSelect="text",c.style.MozUserSelect="text",c.style.msUserSelect="text",c.style.userSelect="text",c.addEventListener("copy",(function(n){if(n.stopPropagation(),t.format)if(n.preventDefault(),void 0===n.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var s=r[t.format]||r.default;window.clipboardData.setData(s,e)}else n.clipboardData.clearData(),n.clipboardData.setData(t.format,e);t.onCopy&&(n.preventDefault(),t.onCopy(n.clipboardData))})),document.body.appendChild(c),o.selectNodeContents(c),l.addRange(o),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");d=!0}catch(n){i&&console.error("unable to copy using execCommand: ",n),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(t.format||"text",e),t.onCopy&&t.onCopy(window.clipboardData),d=!0}catch(n){i&&console.error("unable to copy using clipboardData: ",n),i&&console.error("falling back to prompt"),s=function(e){var t=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return e.replace(/#{\s*key\s*}/g,t)}("message"in t?t.message:"Copy to clipboard: #{key}, Enter"),window.prompt(s,e)}}finally{l&&("function"==typeof l.removeRange?l.removeRange(o):l.removeAllRanges()),c&&document.body.removeChild(c),a()}return d}},8156:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,n=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,r)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var r,s,a,c;if(o(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=l(e))>0&&a.length>r&&!a.warned){a.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,c=d,console&&console.warn&&console.warn(c)}return e}function d(){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 u(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=d.bind(n);return r.listener=i,n.wrapFn=r,r}function h(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function g(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)n(l,this,t);else{var c=l.length,d=p(l,c);for(i=0;i<c;++i)n(d[i],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,r,s,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},s.prototype.listenerCount=g,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},7669:(e,t,i)=>{"use strict";var n=i(538),r=i(2300);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,i=1;i<arguments.length;i++)t+="&args[]="+encodeURIComponent(arguments[i]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var a=new Set,o={};function l(e,t){c(e,t),c(e+"Capture",t)}function c(e,t){for(o[e]=t,e=0;e<t.length;e++)a.add(t[e])}var d=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),u=Object.prototype.hasOwnProperty,h=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,g={},p={};function m(e,t,i,n,r,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=r,this.mustUseProperty=i,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var f={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){f[e]=new m(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];f[t]=new m(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){f[e]=new m(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){f[e]=new m(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){f[e]=new m(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){f[e]=new m(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){f[e]=new m(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){f[e]=new m(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){f[e]=new m(e,5,!1,e.toLowerCase(),null,!1,!1)}));var v=/[\-:]([a-z])/g;function S(e){return e[1].toUpperCase()}function y(e,t,i,n){var r=f.hasOwnProperty(t)?f[t]:null;(null!==r?0!==r.type:n||!(2<t.length)||"o"!==t[0]&&"O"!==t[0]||"n"!==t[1]&&"N"!==t[1])&&(function(e,t,i,n){if(null==t||function(e,t,i,n){if(null!==i&&0===i.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!n&&(null!==i?!i.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,i,n))return!0;if(n)return!1;if(null!==i)switch(i.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,i,r,n)&&(i=null),n||null===r?function(e){return!!u.call(p,e)||!u.call(g,e)&&(h.test(e)?p[e]=!0:(g[e]=!0,!1))}(t)&&(null===i?e.removeAttribute(t):e.setAttribute(t,""+i)):r.mustUseProperty?e[r.propertyName]=null===i?3!==r.type&&"":i:(t=r.attributeName,n=r.attributeNamespace,null===i?e.removeAttribute(t):(i=3===(r=r.type)||4===r&&!0===i?"":""+i,n?e.setAttributeNS(n,t,i):e.setAttribute(t,i))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){f[e]=new m(e,1,!1,e.toLowerCase(),null,!1,!1)})),f.xlinkHref=new m("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){f[e]=new m(e,1,!1,e.toLowerCase(),null,!0,!0)}));var C=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,T=Symbol.for("react.element"),E=Symbol.for("react.portal"),b=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),w=Symbol.for("react.provider"),A=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),D=Symbol.for("react.memo"),k=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var O=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var N=Symbol.iterator;function L(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=N&&e[N]||e["@@iterator"])?e:null}var x,F=Object.assign;function U(e){if(void 0===x)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);x=t&&t[1]||""}return"\n"+x+e}var B=!1;function V(e,t){if(!e||B)return"";B=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(e){var n=e}Reflect.construct(e,[],t)}else{try{t.call()}catch(e){n=e}e.call(t.prototype)}else{try{throw Error()}catch(e){n=e}e()}}catch(t){if(t&&n&&"string"==typeof t.stack){for(var r=t.stack.split("\n"),s=n.stack.split("\n"),a=r.length-1,o=s.length-1;1<=a&&0<=o&&r[a]!==s[o];)o--;for(;1<=a&&0<=o;a--,o--)if(r[a]!==s[o]){if(1!==a||1!==o)do{if(a--,0>--o||r[a]!==s[o]){var l="\n"+r[a].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}}while(1<=a&&0<=o);break}}}finally{B=!1,Error.prepareStackTrace=i}return(e=e?e.displayName||e.name:"")?U(e):""}function H(e){switch(e.tag){case 5:return U(e.type);case 16:return U("Lazy");case 13:return U("Suspense");case 19:return U("SuspenseList");case 0:case 2:case 15:return V(e.type,!1);case 11:return V(e.type.render,!1);case 1:return V(e.type,!0);default:return""}}function $(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case b:return"Fragment";case E:return"Portal";case I:return"Profiler";case _:return"StrictMode";case R:return"Suspense";case M:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case A:return(e.displayName||"Context")+".Consumer";case w:return(e._context.displayName||"Context")+".Provider";case P:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case D:return null!==(t=e.displayName||null)?t:$(e.type)||"Memo";case k:t=e._payload,e=e._init;try{return $(e(t))}catch(e){}}return null}function j(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=t.render).displayName||e.name||"",t.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return $(t);case 8:return t===_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof t)return t.displayName||t.name||null;if("string"==typeof t)return t}return null}function G(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function q(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function z(e){e._valueTracker||(e._valueTracker=function(e){var t=q(e)?"checked":"value",i=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var r=i.get,s=i.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return r.call(this)},set:function(e){n=""+e,s.call(this,e)}}),Object.defineProperty(e,t,{enumerable:i.enumerable}),{getValue:function(){return n},setValue:function(e){n=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function W(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),n="";return e&&(n=q(e)?e.checked?"true":"false":e.value),(e=n)!==i&&(t.setValue(e),!0)}function K(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function J(e,t){var i=t.checked;return F({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=i?i:e._wrapperState.initialChecked})}function Y(e,t){var i=null==t.defaultValue?"":t.defaultValue,n=null!=t.checked?t.checked:t.defaultChecked;i=G(null!=t.value?t.value:i),e._wrapperState={initialChecked:n,initialValue:i,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function Q(e,t){null!=(t=t.checked)&&y(e,"checked",t,!1)}function Z(e,t){Q(e,t);var i=G(t.value),n=t.type;if(null!=i)"number"===n?(0===i&&""===e.value||e.value!=i)&&(e.value=""+i):e.value!==""+i&&(e.value=""+i);else if("submit"===n||"reset"===n)return void e.removeAttribute("value");t.hasOwnProperty("value")?ee(e,t.type,i):t.hasOwnProperty("defaultValue")&&ee(e,t.type,G(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function X(e,t,i){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!("submit"!==n&&"reset"!==n||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,i||t===e.value||(e.value=t),e.defaultValue=t}""!==(i=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==i&&(e.name=i)}function ee(e,t,i){"number"===t&&K(e.ownerDocument)===e||(null==i?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+i&&(e.defaultValue=""+i))}var te=Array.isArray;function ie(e,t,i,n){if(e=e.options,t){t={};for(var r=0;r<i.length;r++)t["$"+i[r]]=!0;for(i=0;i<e.length;i++)r=t.hasOwnProperty("$"+e[i].value),e[i].selected!==r&&(e[i].selected=r),r&&n&&(e[i].defaultSelected=!0)}else{for(i=""+G(i),t=null,r=0;r<e.length;r++){if(e[r].value===i)return e[r].selected=!0,void(n&&(e[r].defaultSelected=!0));null!==t||e[r].disabled||(t=e[r])}null!==t&&(t.selected=!0)}}function ne(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(s(91));return F({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function re(e,t){var i=t.value;if(null==i){if(i=t.children,t=t.defaultValue,null!=i){if(null!=t)throw Error(s(92));if(te(i)){if(1<i.length)throw Error(s(93));i=i[0]}t=i}null==t&&(t=""),i=t}e._wrapperState={initialValue:G(i)}}function se(e,t){var i=G(t.value),n=G(t.defaultValue);null!=i&&((i=""+i)!==e.value&&(e.value=i),null==t.defaultValue&&e.defaultValue!==i&&(e.defaultValue=i)),null!=n&&(e.defaultValue=""+n)}function ae(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}function oe(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function le(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?oe(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var ce,de,ue=(de=function(e,t){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=t;else{for((ce=ce||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ce.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,i,n){MSApp.execUnsafeLocalFunction((function(){return de(e,t)}))}:de);function he(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&3===i.nodeType)return void(i.nodeValue=t)}e.textContent=t}var ge={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},pe=["Webkit","ms","Moz","O"];function me(e,t,i){return null==t||"boolean"==typeof t||""===t?"":i||"number"!=typeof t||0===t||ge.hasOwnProperty(e)&&ge[e]?(""+t).trim():t+"px"}function fe(e,t){for(var i in e=e.style,t)if(t.hasOwnProperty(i)){var n=0===i.indexOf("--"),r=me(i,t[i],n);"float"===i&&(i="cssFloat"),n?e.setProperty(i,r):e[i]=r}}Object.keys(ge).forEach((function(e){pe.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ge[t]=ge[e]}))}));var ve=F({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Se(e,t){if(t){if(ve[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(s(137,e));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(s(60));if("object"!=typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(s(61))}if(null!=t.style&&"object"!=typeof t.style)throw Error(s(62))}}function ye(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ce=null;function Te(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var Ee=null,be=null,_e=null;function Ie(e){if(e=yr(e)){if("function"!=typeof Ee)throw Error(s(280));var t=e.stateNode;t&&(t=Tr(t),Ee(e.stateNode,e.type,t))}}function we(e){be?_e?_e.push(e):_e=[e]:be=e}function Ae(){if(be){var e=be,t=_e;if(_e=be=null,Ie(e),t)for(e=0;e<t.length;e++)Ie(t[e])}}function Pe(e,t){return e(t)}function Re(){}var Me=!1;function De(e,t,i){if(Me)return e(t,i);Me=!0;try{return Pe(e,t,i)}finally{Me=!1,(null!==be||null!==_e)&&(Re(),Ae())}}function ke(e,t){var i=e.stateNode;if(null===i)return null;var n=Tr(i);if(null===n)return null;i=n[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(n=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!n;break e;default:e=!1}if(e)return null;if(i&&"function"!=typeof i)throw Error(s(231,t,typeof i));return i}var Oe=!1;if(d)try{var Ne={};Object.defineProperty(Ne,"passive",{get:function(){Oe=!0}}),window.addEventListener("test",Ne,Ne),window.removeEventListener("test",Ne,Ne)}catch(de){Oe=!1}function Le(e,t,i,n,r,s,a,o,l){var c=Array.prototype.slice.call(arguments,3);try{t.apply(i,c)}catch(e){this.onError(e)}}var xe=!1,Fe=null,Ue=!1,Be=null,Ve={onError:function(e){xe=!0,Fe=e}};function He(e,t,i,n,r,s,a,o,l){xe=!1,Fe=null,Le.apply(Ve,arguments)}function $e(e){var t=e,i=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{!!(4098&(t=e).flags)&&(i=t.return),e=t.return}while(e)}return 3===t.tag?i:null}function je(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&null!==(e=e.alternate)&&(t=e.memoizedState),null!==t)return t.dehydrated}return null}function Ge(e){if($e(e)!==e)throw Error(s(188))}function qe(e){return null!==(e=function(e){var t=e.alternate;if(!t){if(null===(t=$e(e)))throw Error(s(188));return t!==e?null:e}for(var i=e,n=t;;){var r=i.return;if(null===r)break;var a=r.alternate;if(null===a){if(null!==(n=r.return)){i=n;continue}break}if(r.child===a.child){for(a=r.child;a;){if(a===i)return Ge(r),e;if(a===n)return Ge(r),t;a=a.sibling}throw Error(s(188))}if(i.return!==n.return)i=r,n=a;else{for(var o=!1,l=r.child;l;){if(l===i){o=!0,i=r,n=a;break}if(l===n){o=!0,n=r,i=a;break}l=l.sibling}if(!o){for(l=a.child;l;){if(l===i){o=!0,i=a,n=r;break}if(l===n){o=!0,n=a,i=r;break}l=l.sibling}if(!o)throw Error(s(189))}}if(i.alternate!==n)throw Error(s(190))}if(3!==i.tag)throw Error(s(188));return i.stateNode.current===i?e:t}(e))?ze(e):null}function ze(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var t=ze(e);if(null!==t)return t;e=e.sibling}return null}var We=r.unstable_scheduleCallback,Ke=r.unstable_cancelCallback,Je=r.unstable_shouldYield,Ye=r.unstable_requestPaint,Qe=r.unstable_now,Ze=r.unstable_getCurrentPriorityLevel,Xe=r.unstable_ImmediatePriority,et=r.unstable_UserBlockingPriority,tt=r.unstable_NormalPriority,it=r.unstable_LowPriority,nt=r.unstable_IdlePriority,rt=null,st=null,at=Math.clz32?Math.clz32:function(e){return 0===(e>>>=0)?32:31-(ot(e)/lt|0)|0},ot=Math.log,lt=Math.LN2,ct=64,dt=4194304;function ut(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ht(e,t){var i=e.pendingLanes;if(0===i)return 0;var n=0,r=e.suspendedLanes,s=e.pingedLanes,a=268435455&i;if(0!==a){var o=a&~r;0!==o?n=ut(o):0!=(s&=a)&&(n=ut(s))}else 0!=(a=i&~r)?n=ut(a):0!==s&&(n=ut(s));if(0===n)return 0;if(0!==t&&t!==n&&!(t&r)&&((r=n&-n)>=(s=t&-t)||16===r&&4194240&s))return t;if(4&n&&(n|=16&i),0!==(t=e.entangledLanes))for(e=e.entanglements,t&=n;0<t;)r=1<<(i=31-at(t)),n|=e[i],t&=~r;return n}function gt(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function pt(e){return 0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function mt(){var e=ct;return!(4194240&(ct<<=1))&&(ct=64),e}function ft(e){for(var t=[],i=0;31>i;i++)t.push(e);return t}function vt(e,t,i){e.pendingLanes|=t,536870912!==t&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[t=31-at(t)]=i}function St(e,t){var i=e.entangledLanes|=t;for(e=e.entanglements;i;){var n=31-at(i),r=1<<n;r&t|e[n]&t&&(e[n]|=t),i&=~r}}var yt=0;function Ct(e){return 1<(e&=-e)?4<e?268435455&e?16:536870912:4:1}var Tt,Et,bt,_t,It,wt=!1,At=[],Pt=null,Rt=null,Mt=null,Dt=new Map,kt=new Map,Ot=[],Nt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lt(e,t){switch(e){case"focusin":case"focusout":Pt=null;break;case"dragenter":case"dragleave":Rt=null;break;case"mouseover":case"mouseout":Mt=null;break;case"pointerover":case"pointerout":Dt.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":kt.delete(t.pointerId)}}function xt(e,t,i,n,r,s){return null===e||e.nativeEvent!==s?(e={blockedOn:t,domEventName:i,eventSystemFlags:n,nativeEvent:s,targetContainers:[r]},null!==t&&null!==(t=yr(t))&&Et(t),e):(e.eventSystemFlags|=n,t=e.targetContainers,null!==r&&-1===t.indexOf(r)&&t.push(r),e)}function Ft(e){var t=Sr(e.target);if(null!==t){var i=$e(t);if(null!==i)if(13===(t=i.tag)){if(null!==(t=je(i)))return e.blockedOn=t,void It(e.priority,(function(){bt(i)}))}else if(3===t&&i.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===i.tag?i.stateNode.containerInfo:null)}e.blockedOn=null}function Ut(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var i=Jt(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==i)return null!==(t=yr(i))&&Et(t),e.blockedOn=i,!1;var n=new(i=e.nativeEvent).constructor(i.type,i);Ce=n,i.target.dispatchEvent(n),Ce=null,t.shift()}return!0}function Bt(e,t,i){Ut(e)&&i.delete(t)}function Vt(){wt=!1,null!==Pt&&Ut(Pt)&&(Pt=null),null!==Rt&&Ut(Rt)&&(Rt=null),null!==Mt&&Ut(Mt)&&(Mt=null),Dt.forEach(Bt),kt.forEach(Bt)}function Ht(e,t){e.blockedOn===t&&(e.blockedOn=null,wt||(wt=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Vt)))}function $t(e){function t(t){return Ht(t,e)}if(0<At.length){Ht(At[0],e);for(var i=1;i<At.length;i++){var n=At[i];n.blockedOn===e&&(n.blockedOn=null)}}for(null!==Pt&&Ht(Pt,e),null!==Rt&&Ht(Rt,e),null!==Mt&&Ht(Mt,e),Dt.forEach(t),kt.forEach(t),i=0;i<Ot.length;i++)(n=Ot[i]).blockedOn===e&&(n.blockedOn=null);for(;0<Ot.length&&null===(i=Ot[0]).blockedOn;)Ft(i),null===i.blockedOn&&Ot.shift()}var jt=C.ReactCurrentBatchConfig,Gt=!0;function qt(e,t,i,n){var r=yt,s=jt.transition;jt.transition=null;try{yt=1,Wt(e,t,i,n)}finally{yt=r,jt.transition=s}}function zt(e,t,i,n){var r=yt,s=jt.transition;jt.transition=null;try{yt=4,Wt(e,t,i,n)}finally{yt=r,jt.transition=s}}function Wt(e,t,i,n){if(Gt){var r=Jt(e,t,i,n);if(null===r)Gn(e,t,n,Kt,i),Lt(e,n);else if(function(e,t,i,n,r){switch(t){case"focusin":return Pt=xt(Pt,e,t,i,n,r),!0;case"dragenter":return Rt=xt(Rt,e,t,i,n,r),!0;case"mouseover":return Mt=xt(Mt,e,t,i,n,r),!0;case"pointerover":var s=r.pointerId;return Dt.set(s,xt(Dt.get(s)||null,e,t,i,n,r)),!0;case"gotpointercapture":return s=r.pointerId,kt.set(s,xt(kt.get(s)||null,e,t,i,n,r)),!0}return!1}(r,e,t,i,n))n.stopPropagation();else if(Lt(e,n),4&t&&-1<Nt.indexOf(e)){for(;null!==r;){var s=yr(r);if(null!==s&&Tt(s),null===(s=Jt(e,t,i,n))&&Gn(e,t,n,Kt,i),s===r)break;r=s}null!==r&&n.stopPropagation()}else Gn(e,t,n,null,i)}}var Kt=null;function Jt(e,t,i,n){if(Kt=null,null!==(e=Sr(e=Te(n))))if(null===(t=$e(e)))e=null;else if(13===(i=t.tag)){if(null!==(e=je(t)))return e;e=null}else if(3===i){if(t.stateNode.current.memoizedState.isDehydrated)return 3===t.tag?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Kt=e,null}function Yt(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Ze()){case Xe:return 1;case et:return 4;case tt:case it:return 16;case nt:return 536870912;default:return 16}default:return 16}}var Qt=null,Zt=null,Xt=null;function ei(){if(Xt)return Xt;var e,t,i=Zt,n=i.length,r="value"in Qt?Qt.value:Qt.textContent,s=r.length;for(e=0;e<n&&i[e]===r[e];e++);var a=n-e;for(t=1;t<=a&&i[n-t]===r[s-t];t++);return Xt=r.slice(e,1<t?1-t:void 0)}function ti(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function ii(){return!0}function ni(){return!1}function ri(e){function t(t,i,n,r,s){for(var a in this._reactName=t,this._targetInst=n,this.type=i,this.nativeEvent=r,this.target=s,this.currentTarget=null,e)e.hasOwnProperty(a)&&(t=e[a],this[a]=t?t(r):r[a]);return this.isDefaultPrevented=(null!=r.defaultPrevented?r.defaultPrevented:!1===r.returnValue)?ii:ni,this.isPropagationStopped=ni,this}return F(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ii)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ii)},persist:function(){},isPersistent:ii}),t}var si,ai,oi,li={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ci=ri(li),di=F({},li,{view:0,detail:0}),ui=ri(di),hi=F({},di,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:_i,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==oi&&(oi&&"mousemove"===e.type?(si=e.screenX-oi.screenX,ai=e.screenY-oi.screenY):ai=si=0,oi=e),si)},movementY:function(e){return"movementY"in e?e.movementY:ai}}),gi=ri(hi),pi=ri(F({},hi,{dataTransfer:0})),mi=ri(F({},di,{relatedTarget:0})),fi=ri(F({},li,{animationName:0,elapsedTime:0,pseudoElement:0})),vi=F({},li,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Si=ri(vi),yi=ri(F({},li,{data:0})),Ci={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ti={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Ei={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function bi(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Ei[e])&&!!t[e]}function _i(){return bi}var Ii=F({},di,{key:function(e){if(e.key){var t=Ci[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=ti(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?Ti[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:_i,charCode:function(e){return"keypress"===e.type?ti(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ti(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),wi=ri(Ii),Ai=ri(F({},hi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Pi=ri(F({},di,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:_i})),Ri=ri(F({},li,{propertyName:0,elapsedTime:0,pseudoElement:0})),Mi=F({},hi,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Di=ri(Mi),ki=[9,13,27,32],Oi=d&&"CompositionEvent"in window,Ni=null;d&&"documentMode"in document&&(Ni=document.documentMode);var Li=d&&"TextEvent"in window&&!Ni,xi=d&&(!Oi||Ni&&8<Ni&&11>=Ni),Fi=String.fromCharCode(32),Ui=!1;function Bi(e,t){switch(e){case"keyup":return-1!==ki.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vi(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Hi=!1,$i={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ji(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!$i[e.type]:"textarea"===t}function Gi(e,t,i,n){we(n),0<(t=zn(t,"onChange")).length&&(i=new ci("onChange","change",null,i,n),e.push({event:i,listeners:t}))}var qi=null,zi=null;function Wi(e){Un(e,0)}function Ki(e){if(W(Cr(e)))return e}function Ji(e,t){if("change"===e)return t}var Yi=!1;if(d){var Qi;if(d){var Zi="oninput"in document;if(!Zi){var Xi=document.createElement("div");Xi.setAttribute("oninput","return;"),Zi="function"==typeof Xi.oninput}Qi=Zi}else Qi=!1;Yi=Qi&&(!document.documentMode||9<document.documentMode)}function en(){qi&&(qi.detachEvent("onpropertychange",tn),zi=qi=null)}function tn(e){if("value"===e.propertyName&&Ki(zi)){var t=[];Gi(t,zi,e,Te(e)),De(Wi,t)}}function nn(e,t,i){"focusin"===e?(en(),zi=i,(qi=t).attachEvent("onpropertychange",tn)):"focusout"===e&&en()}function rn(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Ki(zi)}function sn(e,t){if("click"===e)return Ki(t)}function an(e,t){if("input"===e||"change"===e)return Ki(t)}var on="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t};function ln(e,t){if(on(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(n=0;n<i.length;n++){var r=i[n];if(!u.call(t,r)||!on(e[r],t[r]))return!1}return!0}function cn(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function dn(e,t){var i,n=cn(e);for(e=0;n;){if(3===n.nodeType){if(i=e+n.textContent.length,e<=t&&i>=t)return{node:n,offset:t-e};e=i}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cn(n)}}function un(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?un(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function hn(){for(var e=window,t=K();t instanceof e.HTMLIFrameElement;){try{var i="string"==typeof t.contentWindow.location.href}catch(e){i=!1}if(!i)break;t=K((e=t.contentWindow).document)}return t}function gn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function pn(e){var t=hn(),i=e.focusedElem,n=e.selectionRange;if(t!==i&&i&&i.ownerDocument&&un(i.ownerDocument.documentElement,i)){if(null!==n&&gn(i))if(t=n.start,void 0===(e=n.end)&&(e=t),"selectionStart"in i)i.selectionStart=t,i.selectionEnd=Math.min(e,i.value.length);else if((e=(t=i.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var r=i.textContent.length,s=Math.min(n.start,r);n=void 0===n.end?s:Math.min(n.end,r),!e.extend&&s>n&&(r=n,n=s,s=r),r=dn(i,s);var a=dn(i,n);r&&a&&(1!==e.rangeCount||e.anchorNode!==r.node||e.anchorOffset!==r.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&((t=t.createRange()).setStart(r.node,r.offset),e.removeAllRanges(),s>n?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}for(t=[],e=i;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i<t.length;i++)(e=t[i]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var mn=d&&"documentMode"in document&&11>=document.documentMode,fn=null,vn=null,Sn=null,yn=!1;function Cn(e,t,i){var n=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;yn||null==fn||fn!==K(n)||(n="selectionStart"in(n=fn)&&gn(n)?{start:n.selectionStart,end:n.selectionEnd}:{anchorNode:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset},Sn&&ln(Sn,n)||(Sn=n,0<(n=zn(vn,"onSelect")).length&&(t=new ci("onSelect","select",null,t,i),e.push({event:t,listeners:n}),t.target=fn)))}function Tn(e,t){var i={};return i[e.toLowerCase()]=t.toLowerCase(),i["Webkit"+e]="webkit"+t,i["Moz"+e]="moz"+t,i}var En={animationend:Tn("Animation","AnimationEnd"),animationiteration:Tn("Animation","AnimationIteration"),animationstart:Tn("Animation","AnimationStart"),transitionend:Tn("Transition","TransitionEnd")},bn={},_n={};function In(e){if(bn[e])return bn[e];if(!En[e])return e;var t,i=En[e];for(t in i)if(i.hasOwnProperty(t)&&t in _n)return bn[e]=i[t];return e}d&&(_n=document.createElement("div").style,"AnimationEvent"in window||(delete En.animationend.animation,delete En.animationiteration.animation,delete En.animationstart.animation),"TransitionEvent"in window||delete En.transitionend.transition);var wn=In("animationend"),An=In("animationiteration"),Pn=In("animationstart"),Rn=In("transitionend"),Mn=new Map,Dn="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function kn(e,t){Mn.set(e,t),l(t,[e])}for(var On=0;On<Dn.length;On++){var Nn=Dn[On];kn(Nn.toLowerCase(),"on"+(Nn[0].toUpperCase()+Nn.slice(1)))}kn(wn,"onAnimationEnd"),kn(An,"onAnimationIteration"),kn(Pn,"onAnimationStart"),kn("dblclick","onDoubleClick"),kn("focusin","onFocus"),kn("focusout","onBlur"),kn(Rn,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ln="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),xn=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ln));function Fn(e,t,i){var n=e.type||"unknown-event";e.currentTarget=i,function(e,t,i,n,r,a,o,l,c){if(He.apply(this,arguments),xe){if(!xe)throw Error(s(198));var d=Fe;xe=!1,Fe=null,Ue||(Ue=!0,Be=d)}}(n,t,void 0,e),e.currentTarget=null}function Un(e,t){t=!!(4&t);for(var i=0;i<e.length;i++){var n=e[i],r=n.event;n=n.listeners;e:{var s=void 0;if(t)for(var a=n.length-1;0<=a;a--){var o=n[a],l=o.instance,c=o.currentTarget;if(o=o.listener,l!==s&&r.isPropagationStopped())break e;Fn(r,o,c),s=l}else for(a=0;a<n.length;a++){if(l=(o=n[a]).instance,c=o.currentTarget,o=o.listener,l!==s&&r.isPropagationStopped())break e;Fn(r,o,c),s=l}}}if(Ue)throw e=Be,Ue=!1,Be=null,e}function Bn(e,t){var i=t[mr];void 0===i&&(i=t[mr]=new Set);var n=e+"__bubble";i.has(n)||(jn(t,e,2,!1),i.add(n))}function Vn(e,t,i){var n=0;t&&(n|=4),jn(i,e,n,t)}var Hn="_reactListening"+Math.random().toString(36).slice(2);function $n(e){if(!e[Hn]){e[Hn]=!0,a.forEach((function(t){"selectionchange"!==t&&(xn.has(t)||Vn(t,!1,e),Vn(t,!0,e))}));var t=9===e.nodeType?e:e.ownerDocument;null===t||t[Hn]||(t[Hn]=!0,Vn("selectionchange",!1,t))}}function jn(e,t,i,n){switch(Yt(t)){case 1:var r=qt;break;case 4:r=zt;break;default:r=Wt}i=r.bind(null,t,i,e),r=void 0,!Oe||"touchstart"!==t&&"touchmove"!==t&&"wheel"!==t||(r=!0),n?void 0!==r?e.addEventListener(t,i,{capture:!0,passive:r}):e.addEventListener(t,i,!0):void 0!==r?e.addEventListener(t,i,{passive:r}):e.addEventListener(t,i,!1)}function Gn(e,t,i,n,r){var s=n;if(!(1&t||2&t||null===n))e:for(;;){if(null===n)return;var a=n.tag;if(3===a||4===a){var o=n.stateNode.containerInfo;if(o===r||8===o.nodeType&&o.parentNode===r)break;if(4===a)for(a=n.return;null!==a;){var l=a.tag;if((3===l||4===l)&&((l=a.stateNode.containerInfo)===r||8===l.nodeType&&l.parentNode===r))return;a=a.return}for(;null!==o;){if(null===(a=Sr(o)))return;if(5===(l=a.tag)||6===l){n=s=a;continue e}o=o.parentNode}}n=n.return}De((function(){var n=s,r=Te(i),a=[];e:{var o=Mn.get(e);if(void 0!==o){var l=ci,c=e;switch(e){case"keypress":if(0===ti(i))break e;case"keydown":case"keyup":l=wi;break;case"focusin":c="focus",l=mi;break;case"focusout":c="blur",l=mi;break;case"beforeblur":case"afterblur":l=mi;break;case"click":if(2===i.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":l=gi;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":l=pi;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":l=Pi;break;case wn:case An:case Pn:l=fi;break;case Rn:l=Ri;break;case"scroll":l=ui;break;case"wheel":l=Di;break;case"copy":case"cut":case"paste":l=Si;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":l=Ai}var d=!!(4&t),u=!d&&"scroll"===e,h=d?null!==o?o+"Capture":null:o;d=[];for(var g,p=n;null!==p;){var m=(g=p).stateNode;if(5===g.tag&&null!==m&&(g=m,null!==h&&null!=(m=ke(p,h))&&d.push(qn(p,m,g))),u)break;p=p.return}0<d.length&&(o=new l(o,c,null,i,r),a.push({event:o,listeners:d}))}}if(!(7&t)){if(l="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||i===Ce||!(c=i.relatedTarget||i.fromElement)||!Sr(c)&&!c[pr])&&(l||o)&&(o=r.window===r?r:(o=r.ownerDocument)?o.defaultView||o.parentWindow:window,l?(l=n,null!==(c=(c=i.relatedTarget||i.toElement)?Sr(c):null)&&(c!==(u=$e(c))||5!==c.tag&&6!==c.tag)&&(c=null)):(l=null,c=n),l!==c)){if(d=gi,m="onMouseLeave",h="onMouseEnter",p="mouse","pointerout"!==e&&"pointerover"!==e||(d=Ai,m="onPointerLeave",h="onPointerEnter",p="pointer"),u=null==l?o:Cr(l),g=null==c?o:Cr(c),(o=new d(m,p+"leave",l,i,r)).target=u,o.relatedTarget=g,m=null,Sr(r)===n&&((d=new d(h,p+"enter",c,i,r)).target=g,d.relatedTarget=u,m=d),u=m,l&&c)e:{for(h=c,p=0,g=d=l;g;g=Wn(g))p++;for(g=0,m=h;m;m=Wn(m))g++;for(;0<p-g;)d=Wn(d),p--;for(;0<g-p;)h=Wn(h),g--;for(;p--;){if(d===h||null!==h&&d===h.alternate)break e;d=Wn(d),h=Wn(h)}d=null}else d=null;null!==l&&Kn(a,o,l,d,!1),null!==c&&null!==u&&Kn(a,u,c,d,!0)}if("select"===(l=(o=n?Cr(n):window).nodeName&&o.nodeName.toLowerCase())||"input"===l&&"file"===o.type)var f=Ji;else if(ji(o))if(Yi)f=an;else{f=rn;var v=nn}else(l=o.nodeName)&&"input"===l.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(f=sn);switch(f&&(f=f(e,n))?Gi(a,f,i,r):(v&&v(e,o,n),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&ee(o,"number",o.value)),v=n?Cr(n):window,e){case"focusin":(ji(v)||"true"===v.contentEditable)&&(fn=v,vn=n,Sn=null);break;case"focusout":Sn=vn=fn=null;break;case"mousedown":yn=!0;break;case"contextmenu":case"mouseup":case"dragend":yn=!1,Cn(a,i,r);break;case"selectionchange":if(mn)break;case"keydown":case"keyup":Cn(a,i,r)}var S;if(Oi)e:{switch(e){case"compositionstart":var y="onCompositionStart";break e;case"compositionend":y="onCompositionEnd";break e;case"compositionupdate":y="onCompositionUpdate";break e}y=void 0}else Hi?Bi(e,i)&&(y="onCompositionEnd"):"keydown"===e&&229===i.keyCode&&(y="onCompositionStart");y&&(xi&&"ko"!==i.locale&&(Hi||"onCompositionStart"!==y?"onCompositionEnd"===y&&Hi&&(S=ei()):(Zt="value"in(Qt=r)?Qt.value:Qt.textContent,Hi=!0)),0<(v=zn(n,y)).length&&(y=new yi(y,e,null,i,r),a.push({event:y,listeners:v}),(S||null!==(S=Vi(i)))&&(y.data=S))),(S=Li?function(e,t){switch(e){case"compositionend":return Vi(t);case"keypress":return 32!==t.which?null:(Ui=!0,Fi);case"textInput":return(e=t.data)===Fi&&Ui?null:e;default:return null}}(e,i):function(e,t){if(Hi)return"compositionend"===e||!Oi&&Bi(e,t)?(e=ei(),Xt=Zt=Qt=null,Hi=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return xi&&"ko"!==t.locale?null:t.data}}(e,i))&&0<(n=zn(n,"onBeforeInput")).length&&(r=new yi("onBeforeInput","beforeinput",null,i,r),a.push({event:r,listeners:n}),r.data=S)}Un(a,t)}))}function qn(e,t,i){return{instance:e,listener:t,currentTarget:i}}function zn(e,t){for(var i=t+"Capture",n=[];null!==e;){var r=e,s=r.stateNode;5===r.tag&&null!==s&&(r=s,null!=(s=ke(e,i))&&n.unshift(qn(e,s,r)),null!=(s=ke(e,t))&&n.push(qn(e,s,r))),e=e.return}return n}function Wn(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function Kn(e,t,i,n,r){for(var s=t._reactName,a=[];null!==i&&i!==n;){var o=i,l=o.alternate,c=o.stateNode;if(null!==l&&l===n)break;5===o.tag&&null!==c&&(o=c,r?null!=(l=ke(i,s))&&a.unshift(qn(i,l,o)):r||null!=(l=ke(i,s))&&a.push(qn(i,l,o))),i=i.return}0!==a.length&&e.push({event:t,listeners:a})}var Jn=/\r\n?/g,Yn=/\u0000|\uFFFD/g;function Qn(e){return("string"==typeof e?e:""+e).replace(Jn,"\n").replace(Yn,"")}function Zn(e,t,i){if(t=Qn(t),Qn(e)!==t&&i)throw Error(s(425))}function Xn(){}var er=null,tr=null;function ir(e,t){return"textarea"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var nr="function"==typeof setTimeout?setTimeout:void 0,rr="function"==typeof clearTimeout?clearTimeout:void 0,sr="function"==typeof Promise?Promise:void 0,ar="function"==typeof queueMicrotask?queueMicrotask:void 0!==sr?function(e){return sr.resolve(null).then(e).catch(or)}:nr;function or(e){setTimeout((function(){throw e}))}function lr(e,t){var i=t,n=0;do{var r=i.nextSibling;if(e.removeChild(i),r&&8===r.nodeType)if("/$"===(i=r.data)){if(0===n)return e.removeChild(r),void $t(t);n--}else"$"!==i&&"$?"!==i&&"$!"!==i||n++;i=r}while(i);$t(t)}function cr(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break;if(8===t){if("$"===(t=e.data)||"$!"===t||"$?"===t)break;if("/$"===t)return null}}return e}function dr(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var i=e.data;if("$"===i||"$!"===i||"$?"===i){if(0===t)return e;t--}else"/$"===i&&t++}e=e.previousSibling}return null}var ur=Math.random().toString(36).slice(2),hr="__reactFiber$"+ur,gr="__reactProps$"+ur,pr="__reactContainer$"+ur,mr="__reactEvents$"+ur,fr="__reactListeners$"+ur,vr="__reactHandles$"+ur;function Sr(e){var t=e[hr];if(t)return t;for(var i=e.parentNode;i;){if(t=i[pr]||i[hr]){if(i=t.alternate,null!==t.child||null!==i&&null!==i.child)for(e=dr(e);null!==e;){if(i=e[hr])return i;e=dr(e)}return t}i=(e=i).parentNode}return null}function yr(e){return!(e=e[hr]||e[pr])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function Cr(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(s(33))}function Tr(e){return e[gr]||null}var Er=[],br=-1;function _r(e){return{current:e}}function Ir(e){0>br||(e.current=Er[br],Er[br]=null,br--)}function wr(e,t){br++,Er[br]=e.current,e.current=t}var Ar={},Pr=_r(Ar),Rr=_r(!1),Mr=Ar;function Dr(e,t){var i=e.type.contextTypes;if(!i)return Ar;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var r,s={};for(r in i)s[r]=t[r];return n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function kr(e){return null!=e.childContextTypes}function Or(){Ir(Rr),Ir(Pr)}function Nr(e,t,i){if(Pr.current!==Ar)throw Error(s(168));wr(Pr,t),wr(Rr,i)}function Lr(e,t,i){var n=e.stateNode;if(t=t.childContextTypes,"function"!=typeof n.getChildContext)return i;for(var r in n=n.getChildContext())if(!(r in t))throw Error(s(108,j(e)||"Unknown",r));return F({},i,n)}function xr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ar,Mr=Pr.current,wr(Pr,e),wr(Rr,Rr.current),!0}function Fr(e,t,i){var n=e.stateNode;if(!n)throw Error(s(169));i?(e=Lr(e,t,Mr),n.__reactInternalMemoizedMergedChildContext=e,Ir(Rr),Ir(Pr),wr(Pr,e)):Ir(Rr),wr(Rr,i)}var Ur=null,Br=!1,Vr=!1;function Hr(e){null===Ur?Ur=[e]:Ur.push(e)}function $r(){if(!Vr&&null!==Ur){Vr=!0;var e=0,t=yt;try{var i=Ur;for(yt=1;e<i.length;e++){var n=i[e];do{n=n(!0)}while(null!==n)}Ur=null,Br=!1}catch(t){throw null!==Ur&&(Ur=Ur.slice(e+1)),We(Xe,$r),t}finally{yt=t,Vr=!1}}return null}var jr=[],Gr=0,qr=null,zr=0,Wr=[],Kr=0,Jr=null,Yr=1,Qr="";function Zr(e,t){jr[Gr++]=zr,jr[Gr++]=qr,qr=e,zr=t}function Xr(e,t,i){Wr[Kr++]=Yr,Wr[Kr++]=Qr,Wr[Kr++]=Jr,Jr=e;var n=Yr;e=Qr;var r=32-at(n)-1;n&=~(1<<r),i+=1;var s=32-at(t)+r;if(30<s){var a=r-r%5;s=(n&(1<<a)-1).toString(32),n>>=a,r-=a,Yr=1<<32-at(t)+r|i<<r|n,Qr=s+e}else Yr=1<<s|i<<r|n,Qr=e}function es(e){null!==e.return&&(Zr(e,1),Xr(e,1,0))}function ts(e){for(;e===qr;)qr=jr[--Gr],jr[Gr]=null,zr=jr[--Gr],jr[Gr]=null;for(;e===Jr;)Jr=Wr[--Kr],Wr[Kr]=null,Qr=Wr[--Kr],Wr[Kr]=null,Yr=Wr[--Kr],Wr[Kr]=null}var is=null,ns=null,rs=!1,ss=null;function as(e,t){var i=Dc(5,null,null,0);i.elementType="DELETED",i.stateNode=t,i.return=e,null===(t=e.deletions)?(e.deletions=[i],e.flags|=16):t.push(i)}function os(e,t){switch(e.tag){case 5:var i=e.type;return null!==(t=1!==t.nodeType||i.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,is=e,ns=cr(t.firstChild),!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,is=e,ns=null,!0);case 13:return null!==(t=8!==t.nodeType?null:t)&&(i=null!==Jr?{id:Yr,overflow:Qr}:null,e.memoizedState={dehydrated:t,treeContext:i,retryLane:1073741824},(i=Dc(18,null,null,0)).stateNode=t,i.return=e,e.child=i,is=e,ns=null,!0);default:return!1}}function ls(e){return!(!(1&e.mode)||128&e.flags)}function cs(e){if(rs){var t=ns;if(t){var i=t;if(!os(e,t)){if(ls(e))throw Error(s(418));t=cr(i.nextSibling);var n=is;t&&os(e,t)?as(n,i):(e.flags=-4097&e.flags|2,rs=!1,is=e)}}else{if(ls(e))throw Error(s(418));e.flags=-4097&e.flags|2,rs=!1,is=e}}}function ds(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;is=e}function us(e){if(e!==is)return!1;if(!rs)return ds(e),rs=!0,!1;var t;if((t=3!==e.tag)&&!(t=5!==e.tag)&&(t="head"!==(t=e.type)&&"body"!==t&&!ir(e.type,e.memoizedProps)),t&&(t=ns)){if(ls(e))throw hs(),Error(s(418));for(;t;)as(e,t),t=cr(t.nextSibling)}if(ds(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(s(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var i=e.data;if("/$"===i){if(0===t){ns=cr(e.nextSibling);break e}t--}else"$"!==i&&"$!"!==i&&"$?"!==i||t++}e=e.nextSibling}ns=null}}else ns=is?cr(e.stateNode.nextSibling):null;return!0}function hs(){for(var e=ns;e;)e=cr(e.nextSibling)}function gs(){ns=is=null,rs=!1}function ps(e){null===ss?ss=[e]:ss.push(e)}var ms=C.ReactCurrentBatchConfig;function fs(e,t,i){if(null!==(e=i.ref)&&"function"!=typeof e&&"object"!=typeof e){if(i._owner){if(i=i._owner){if(1!==i.tag)throw Error(s(309));var n=i.stateNode}if(!n)throw Error(s(147,e));var r=n,a=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===a?t.ref:(t=function(e){var t=r.refs;null===e?delete t[a]:t[a]=e},t._stringRef=a,t)}if("string"!=typeof e)throw Error(s(284));if(!i._owner)throw Error(s(290,e))}return e}function vs(e,t){throw e=Object.prototype.toString.call(t),Error(s(31,"[object Object]"===e?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Ss(e){return(0,e._init)(e._payload)}function ys(e){function t(t,i){if(e){var n=t.deletions;null===n?(t.deletions=[i],t.flags|=16):n.push(i)}}function i(i,n){if(!e)return null;for(;null!==n;)t(i,n),n=n.sibling;return null}function n(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function r(e,t){return(e=Oc(e,t)).index=0,e.sibling=null,e}function a(t,i,n){return t.index=n,e?null!==(n=t.alternate)?(n=n.index)<i?(t.flags|=2,i):n:(t.flags|=2,i):(t.flags|=1048576,i)}function o(t){return e&&null===t.alternate&&(t.flags|=2),t}function l(e,t,i,n){return null===t||6!==t.tag?((t=Fc(i,e.mode,n)).return=e,t):((t=r(t,i)).return=e,t)}function c(e,t,i,n){var s=i.type;return s===b?u(e,t,i.props.children,n,i.key):null!==t&&(t.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===k&&Ss(s)===t.type)?((n=r(t,i.props)).ref=fs(e,t,i),n.return=e,n):((n=Nc(i.type,i.key,i.props,null,e.mode,n)).ref=fs(e,t,i),n.return=e,n)}function d(e,t,i,n){return null===t||4!==t.tag||t.stateNode.containerInfo!==i.containerInfo||t.stateNode.implementation!==i.implementation?((t=Uc(i,e.mode,n)).return=e,t):((t=r(t,i.children||[])).return=e,t)}function u(e,t,i,n,s){return null===t||7!==t.tag?((t=Lc(i,e.mode,n,s)).return=e,t):((t=r(t,i)).return=e,t)}function h(e,t,i){if("string"==typeof t&&""!==t||"number"==typeof t)return(t=Fc(""+t,e.mode,i)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case T:return(i=Nc(t.type,t.key,t.props,null,e.mode,i)).ref=fs(e,null,t),i.return=e,i;case E:return(t=Uc(t,e.mode,i)).return=e,t;case k:return h(e,(0,t._init)(t._payload),i)}if(te(t)||L(t))return(t=Lc(t,e.mode,i,null)).return=e,t;vs(e,t)}return null}function g(e,t,i,n){var r=null!==t?t.key:null;if("string"==typeof i&&""!==i||"number"==typeof i)return null!==r?null:l(e,t,""+i,n);if("object"==typeof i&&null!==i){switch(i.$$typeof){case T:return i.key===r?c(e,t,i,n):null;case E:return i.key===r?d(e,t,i,n):null;case k:return g(e,t,(r=i._init)(i._payload),n)}if(te(i)||L(i))return null!==r?null:u(e,t,i,n,null);vs(e,i)}return null}function p(e,t,i,n,r){if("string"==typeof n&&""!==n||"number"==typeof n)return l(t,e=e.get(i)||null,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case T:return c(t,e=e.get(null===n.key?i:n.key)||null,n,r);case E:return d(t,e=e.get(null===n.key?i:n.key)||null,n,r);case k:return p(e,t,i,(0,n._init)(n._payload),r)}if(te(n)||L(n))return u(t,e=e.get(i)||null,n,r,null);vs(t,n)}return null}function m(r,s,o,l){for(var c=null,d=null,u=s,m=s=0,f=null;null!==u&&m<o.length;m++){u.index>m?(f=u,u=null):f=u.sibling;var v=g(r,u,o[m],l);if(null===v){null===u&&(u=f);break}e&&u&&null===v.alternate&&t(r,u),s=a(v,s,m),null===d?c=v:d.sibling=v,d=v,u=f}if(m===o.length)return i(r,u),rs&&Zr(r,m),c;if(null===u){for(;m<o.length;m++)null!==(u=h(r,o[m],l))&&(s=a(u,s,m),null===d?c=u:d.sibling=u,d=u);return rs&&Zr(r,m),c}for(u=n(r,u);m<o.length;m++)null!==(f=p(u,r,m,o[m],l))&&(e&&null!==f.alternate&&u.delete(null===f.key?m:f.key),s=a(f,s,m),null===d?c=f:d.sibling=f,d=f);return e&&u.forEach((function(e){return t(r,e)})),rs&&Zr(r,m),c}function f(r,o,l,c){var d=L(l);if("function"!=typeof d)throw Error(s(150));if(null==(l=d.call(l)))throw Error(s(151));for(var u=d=null,m=o,f=o=0,v=null,S=l.next();null!==m&&!S.done;f++,S=l.next()){m.index>f?(v=m,m=null):v=m.sibling;var y=g(r,m,S.value,c);if(null===y){null===m&&(m=v);break}e&&m&&null===y.alternate&&t(r,m),o=a(y,o,f),null===u?d=y:u.sibling=y,u=y,m=v}if(S.done)return i(r,m),rs&&Zr(r,f),d;if(null===m){for(;!S.done;f++,S=l.next())null!==(S=h(r,S.value,c))&&(o=a(S,o,f),null===u?d=S:u.sibling=S,u=S);return rs&&Zr(r,f),d}for(m=n(r,m);!S.done;f++,S=l.next())null!==(S=p(m,r,f,S.value,c))&&(e&&null!==S.alternate&&m.delete(null===S.key?f:S.key),o=a(S,o,f),null===u?d=S:u.sibling=S,u=S);return e&&m.forEach((function(e){return t(r,e)})),rs&&Zr(r,f),d}return function e(n,s,a,l){if("object"==typeof a&&null!==a&&a.type===b&&null===a.key&&(a=a.props.children),"object"==typeof a&&null!==a){switch(a.$$typeof){case T:e:{for(var c=a.key,d=s;null!==d;){if(d.key===c){if((c=a.type)===b){if(7===d.tag){i(n,d.sibling),(s=r(d,a.props.children)).return=n,n=s;break e}}else if(d.elementType===c||"object"==typeof c&&null!==c&&c.$$typeof===k&&Ss(c)===d.type){i(n,d.sibling),(s=r(d,a.props)).ref=fs(n,d,a),s.return=n,n=s;break e}i(n,d);break}t(n,d),d=d.sibling}a.type===b?((s=Lc(a.props.children,n.mode,l,a.key)).return=n,n=s):((l=Nc(a.type,a.key,a.props,null,n.mode,l)).ref=fs(n,s,a),l.return=n,n=l)}return o(n);case E:e:{for(d=a.key;null!==s;){if(s.key===d){if(4===s.tag&&s.stateNode.containerInfo===a.containerInfo&&s.stateNode.implementation===a.implementation){i(n,s.sibling),(s=r(s,a.children||[])).return=n,n=s;break e}i(n,s);break}t(n,s),s=s.sibling}(s=Uc(a,n.mode,l)).return=n,n=s}return o(n);case k:return e(n,s,(d=a._init)(a._payload),l)}if(te(a))return m(n,s,a,l);if(L(a))return f(n,s,a,l);vs(n,a)}return"string"==typeof a&&""!==a||"number"==typeof a?(a=""+a,null!==s&&6===s.tag?(i(n,s.sibling),(s=r(s,a)).return=n,n=s):(i(n,s),(s=Fc(a,n.mode,l)).return=n,n=s),o(n)):i(n,s)}}var Cs=ys(!0),Ts=ys(!1),Es=_r(null),bs=null,_s=null,Is=null;function ws(){Is=_s=bs=null}function As(e){var t=Es.current;Ir(Es),e._currentValue=t}function Ps(e,t,i){for(;null!==e;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==n&&(n.childLanes|=t)):null!==n&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===i)break;e=e.return}}function Rs(e,t){bs=e,Is=_s=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(!!(e.lanes&t)&&(yo=!0),e.firstContext=null)}function Ms(e){var t=e._currentValue;if(Is!==e)if(e={context:e,memoizedValue:t,next:null},null===_s){if(null===bs)throw Error(s(308));_s=e,bs.dependencies={lanes:0,firstContext:e}}else _s=_s.next=e;return t}var Ds=null;function ks(e){null===Ds?Ds=[e]:Ds.push(e)}function Os(e,t,i,n){var r=t.interleaved;return null===r?(i.next=i,ks(t)):(i.next=r.next,r.next=i),t.interleaved=i,Ns(e,n)}function Ns(e,t){e.lanes|=t;var i=e.alternate;for(null!==i&&(i.lanes|=t),i=e,e=e.return;null!==e;)e.childLanes|=t,null!==(i=e.alternate)&&(i.childLanes|=t),i=e,e=e.return;return 3===i.tag?i.stateNode:null}var Ls=!1;function xs(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Fs(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Us(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Bs(e,t,i){var n=e.updateQueue;if(null===n)return null;if(n=n.shared,2&Pl){var r=n.pending;return null===r?t.next=t:(t.next=r.next,r.next=t),n.pending=t,Ns(e,i)}return null===(r=n.interleaved)?(t.next=t,ks(n)):(t.next=r.next,r.next=t),n.interleaved=t,Ns(e,i)}function Vs(e,t,i){if(null!==(t=t.updateQueue)&&(t=t.shared,4194240&i)){var n=t.lanes;i|=n&=e.pendingLanes,t.lanes=i,St(e,i)}}function Hs(e,t){var i=e.updateQueue,n=e.alternate;if(null!==n&&i===(n=n.updateQueue)){var r=null,s=null;if(null!==(i=i.firstBaseUpdate)){do{var a={eventTime:i.eventTime,lane:i.lane,tag:i.tag,payload:i.payload,callback:i.callback,next:null};null===s?r=s=a:s=s.next=a,i=i.next}while(null!==i);null===s?r=s=t:s=s.next=t}else r=s=t;return i={baseState:n.baseState,firstBaseUpdate:r,lastBaseUpdate:s,shared:n.shared,effects:n.effects},void(e.updateQueue=i)}null===(e=i.lastBaseUpdate)?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}function $s(e,t,i,n){var r=e.updateQueue;Ls=!1;var s=r.firstBaseUpdate,a=r.lastBaseUpdate,o=r.shared.pending;if(null!==o){r.shared.pending=null;var l=o,c=l.next;l.next=null,null===a?s=c:a.next=c,a=l;var d=e.alternate;null!==d&&(o=(d=d.updateQueue).lastBaseUpdate)!==a&&(null===o?d.firstBaseUpdate=c:o.next=c,d.lastBaseUpdate=l)}if(null!==s){var u=r.baseState;for(a=0,d=c=l=null,o=s;;){var h=o.lane,g=o.eventTime;if((n&h)===h){null!==d&&(d=d.next={eventTime:g,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var p=e,m=o;switch(h=t,g=i,m.tag){case 1:if("function"==typeof(p=m.payload)){u=p.call(g,u,h);break e}u=p;break e;case 3:p.flags=-65537&p.flags|128;case 0:if(null==(h="function"==typeof(p=m.payload)?p.call(g,u,h):p))break e;u=F({},u,h);break e;case 2:Ls=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(h=r.effects)?r.effects=[o]:h.push(o))}else g={eventTime:g,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===d?(c=d=g,l=u):d=d.next=g,a|=h;if(null===(o=o.next)){if(null===(o=r.shared.pending))break;o=(h=o).next,h.next=null,r.lastBaseUpdate=h,r.shared.pending=null}}if(null===d&&(l=u),r.baseState=l,r.firstBaseUpdate=c,r.lastBaseUpdate=d,null!==(t=r.shared.interleaved)){r=t;do{a|=r.lane,r=r.next}while(r!==t)}else null===s&&(r.shared.lanes=0);xl|=a,e.lanes=a,e.memoizedState=u}}function js(e,t,i){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var n=e[t],r=n.callback;if(null!==r){if(n.callback=null,n=i,"function"!=typeof r)throw Error(s(191,r));r.call(n)}}}var Gs={},qs=_r(Gs),zs=_r(Gs),Ws=_r(Gs);function Ks(e){if(e===Gs)throw Error(s(174));return e}function Js(e,t){switch(wr(Ws,t),wr(zs,e),wr(qs,Gs),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:le(null,"");break;default:t=le(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}Ir(qs),wr(qs,t)}function Ys(){Ir(qs),Ir(zs),Ir(Ws)}function Qs(e){Ks(Ws.current);var t=Ks(qs.current),i=le(t,e.type);t!==i&&(wr(zs,e),wr(qs,i))}function Zs(e){zs.current===e&&(Ir(qs),Ir(zs))}var Xs=_r(0);function ea(e){for(var t=e;null!==t;){if(13===t.tag){var i=t.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(128&t.flags)return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ta=[];function ia(){for(var e=0;e<ta.length;e++)ta[e]._workInProgressVersionPrimary=null;ta.length=0}var na=C.ReactCurrentDispatcher,ra=C.ReactCurrentBatchConfig,sa=0,aa=null,oa=null,la=null,ca=!1,da=!1,ua=0,ha=0;function ga(){throw Error(s(321))}function pa(e,t){if(null===t)return!1;for(var i=0;i<t.length&&i<e.length;i++)if(!on(e[i],t[i]))return!1;return!0}function ma(e,t,i,n,r,a){if(sa=a,aa=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,na.current=null===e||null===e.memoizedState?Za:Xa,e=i(n,r),da){a=0;do{if(da=!1,ua=0,25<=a)throw Error(s(301));a+=1,la=oa=null,t.updateQueue=null,na.current=eo,e=i(n,r)}while(da)}if(na.current=Qa,t=null!==oa&&null!==oa.next,sa=0,la=oa=aa=null,ca=!1,t)throw Error(s(300));return e}function fa(){var e=0!==ua;return ua=0,e}function va(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===la?aa.memoizedState=la=e:la=la.next=e,la}function Sa(){if(null===oa){var e=aa.alternate;e=null!==e?e.memoizedState:null}else e=oa.next;var t=null===la?aa.memoizedState:la.next;if(null!==t)la=t,oa=e;else{if(null===e)throw Error(s(310));e={memoizedState:(oa=e).memoizedState,baseState:oa.baseState,baseQueue:oa.baseQueue,queue:oa.queue,next:null},null===la?aa.memoizedState=la=e:la=la.next=e}return la}function ya(e,t){return"function"==typeof t?t(e):t}function Ca(e){var t=Sa(),i=t.queue;if(null===i)throw Error(s(311));i.lastRenderedReducer=e;var n=oa,r=n.baseQueue,a=i.pending;if(null!==a){if(null!==r){var o=r.next;r.next=a.next,a.next=o}n.baseQueue=r=a,i.pending=null}if(null!==r){a=r.next,n=n.baseState;var l=o=null,c=null,d=a;do{var u=d.lane;if((sa&u)===u)null!==c&&(c=c.next={lane:0,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null}),n=d.hasEagerState?d.eagerState:e(n,d.action);else{var h={lane:u,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null};null===c?(l=c=h,o=n):c=c.next=h,aa.lanes|=u,xl|=u}d=d.next}while(null!==d&&d!==a);null===c?o=n:c.next=l,on(n,t.memoizedState)||(yo=!0),t.memoizedState=n,t.baseState=o,t.baseQueue=c,i.lastRenderedState=n}if(null!==(e=i.interleaved)){r=e;do{a=r.lane,aa.lanes|=a,xl|=a,r=r.next}while(r!==e)}else null===r&&(i.lanes=0);return[t.memoizedState,i.dispatch]}function Ta(e){var t=Sa(),i=t.queue;if(null===i)throw Error(s(311));i.lastRenderedReducer=e;var n=i.dispatch,r=i.pending,a=t.memoizedState;if(null!==r){i.pending=null;var o=r=r.next;do{a=e(a,o.action),o=o.next}while(o!==r);on(a,t.memoizedState)||(yo=!0),t.memoizedState=a,null===t.baseQueue&&(t.baseState=a),i.lastRenderedState=a}return[a,n]}function Ea(){}function ba(e,t){var i=aa,n=Sa(),r=t(),a=!on(n.memoizedState,r);if(a&&(n.memoizedState=r,yo=!0),n=n.queue,La(wa.bind(null,i,n,e),[e]),n.getSnapshot!==t||a||null!==la&&1&la.memoizedState.tag){if(i.flags|=2048,Ma(9,Ia.bind(null,i,n,r,t),void 0,null),null===Rl)throw Error(s(349));30&sa||_a(i,t,r)}return r}function _a(e,t,i){e.flags|=16384,e={getSnapshot:t,value:i},null===(t=aa.updateQueue)?(t={lastEffect:null,stores:null},aa.updateQueue=t,t.stores=[e]):null===(i=t.stores)?t.stores=[e]:i.push(e)}function Ia(e,t,i,n){t.value=i,t.getSnapshot=n,Aa(t)&&Pa(e)}function wa(e,t,i){return i((function(){Aa(t)&&Pa(e)}))}function Aa(e){var t=e.getSnapshot;e=e.value;try{var i=t();return!on(e,i)}catch(e){return!0}}function Pa(e){var t=Ns(e,1);null!==t&&ic(t,e,1,-1)}function Ra(e){var t=va();return"function"==typeof e&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ya,lastRenderedState:e},t.queue=e,e=e.dispatch=Wa.bind(null,aa,e),[t.memoizedState,e]}function Ma(e,t,i,n){return e={tag:e,create:t,destroy:i,deps:n,next:null},null===(t=aa.updateQueue)?(t={lastEffect:null,stores:null},aa.updateQueue=t,t.lastEffect=e.next=e):null===(i=t.lastEffect)?t.lastEffect=e.next=e:(n=i.next,i.next=e,e.next=n,t.lastEffect=e),e}function Da(){return Sa().memoizedState}function ka(e,t,i,n){var r=va();aa.flags|=e,r.memoizedState=Ma(1|t,i,void 0,void 0===n?null:n)}function Oa(e,t,i,n){var r=Sa();n=void 0===n?null:n;var s=void 0;if(null!==oa){var a=oa.memoizedState;if(s=a.destroy,null!==n&&pa(n,a.deps))return void(r.memoizedState=Ma(t,i,s,n))}aa.flags|=e,r.memoizedState=Ma(1|t,i,s,n)}function Na(e,t){return ka(8390656,8,e,t)}function La(e,t){return Oa(2048,8,e,t)}function xa(e,t){return Oa(4,2,e,t)}function Fa(e,t){return Oa(4,4,e,t)}function Ua(e,t){return"function"==typeof t?(e=e(),t(e),function(){t(null)}):null!=t?(e=e(),t.current=e,function(){t.current=null}):void 0}function Ba(e,t,i){return i=null!=i?i.concat([e]):null,Oa(4,4,Ua.bind(null,t,e),i)}function Va(){}function Ha(e,t){var i=Sa();t=void 0===t?null:t;var n=i.memoizedState;return null!==n&&null!==t&&pa(t,n[1])?n[0]:(i.memoizedState=[e,t],e)}function $a(e,t){var i=Sa();t=void 0===t?null:t;var n=i.memoizedState;return null!==n&&null!==t&&pa(t,n[1])?n[0]:(e=e(),i.memoizedState=[e,t],e)}function ja(e,t,i){return 21&sa?(on(i,t)||(i=mt(),aa.lanes|=i,xl|=i,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,yo=!0),e.memoizedState=i)}function Ga(e,t){var i=yt;yt=0!==i&&4>i?i:4,e(!0);var n=ra.transition;ra.transition={};try{e(!1),t()}finally{yt=i,ra.transition=n}}function qa(){return Sa().memoizedState}function za(e,t,i){var n=tc(e);i={lane:n,action:i,hasEagerState:!1,eagerState:null,next:null},Ka(e)?Ja(t,i):null!==(i=Os(e,t,i,n))&&(ic(i,e,n,ec()),Ya(i,t,n))}function Wa(e,t,i){var n=tc(e),r={lane:n,action:i,hasEagerState:!1,eagerState:null,next:null};if(Ka(e))Ja(t,r);else{var s=e.alternate;if(0===e.lanes&&(null===s||0===s.lanes)&&null!==(s=t.lastRenderedReducer))try{var a=t.lastRenderedState,o=s(a,i);if(r.hasEagerState=!0,r.eagerState=o,on(o,a)){var l=t.interleaved;return null===l?(r.next=r,ks(t)):(r.next=l.next,l.next=r),void(t.interleaved=r)}}catch(e){}null!==(i=Os(e,t,r,n))&&(ic(i,e,n,r=ec()),Ya(i,t,n))}}function Ka(e){var t=e.alternate;return e===aa||null!==t&&t===aa}function Ja(e,t){da=ca=!0;var i=e.pending;null===i?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function Ya(e,t,i){if(4194240&i){var n=t.lanes;i|=n&=e.pendingLanes,t.lanes=i,St(e,i)}}var Qa={readContext:Ms,useCallback:ga,useContext:ga,useEffect:ga,useImperativeHandle:ga,useInsertionEffect:ga,useLayoutEffect:ga,useMemo:ga,useReducer:ga,useRef:ga,useState:ga,useDebugValue:ga,useDeferredValue:ga,useTransition:ga,useMutableSource:ga,useSyncExternalStore:ga,useId:ga,unstable_isNewReconciler:!1},Za={readContext:Ms,useCallback:function(e,t){return va().memoizedState=[e,void 0===t?null:t],e},useContext:Ms,useEffect:Na,useImperativeHandle:function(e,t,i){return i=null!=i?i.concat([e]):null,ka(4194308,4,Ua.bind(null,t,e),i)},useLayoutEffect:function(e,t){return ka(4194308,4,e,t)},useInsertionEffect:function(e,t){return ka(4,2,e,t)},useMemo:function(e,t){var i=va();return t=void 0===t?null:t,e=e(),i.memoizedState=[e,t],e},useReducer:function(e,t,i){var n=va();return t=void 0!==i?i(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=za.bind(null,aa,e),[n.memoizedState,e]},useRef:function(e){return e={current:e},va().memoizedState=e},useState:Ra,useDebugValue:Va,useDeferredValue:function(e){return va().memoizedState=e},useTransition:function(){var e=Ra(!1),t=e[0];return e=Ga.bind(null,e[1]),va().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,i){var n=aa,r=va();if(rs){if(void 0===i)throw Error(s(407));i=i()}else{if(i=t(),null===Rl)throw Error(s(349));30&sa||_a(n,t,i)}r.memoizedState=i;var a={value:i,getSnapshot:t};return r.queue=a,Na(wa.bind(null,n,a,e),[e]),n.flags|=2048,Ma(9,Ia.bind(null,n,a,i,t),void 0,null),i},useId:function(){var e=va(),t=Rl.identifierPrefix;if(rs){var i=Qr;t=":"+t+"R"+(i=(Yr&~(1<<32-at(Yr)-1)).toString(32)+i),0<(i=ua++)&&(t+="H"+i.toString(32)),t+=":"}else t=":"+t+"r"+(i=ha++).toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},Xa={readContext:Ms,useCallback:Ha,useContext:Ms,useEffect:La,useImperativeHandle:Ba,useInsertionEffect:xa,useLayoutEffect:Fa,useMemo:$a,useReducer:Ca,useRef:Da,useState:function(){return Ca(ya)},useDebugValue:Va,useDeferredValue:function(e){return ja(Sa(),oa.memoizedState,e)},useTransition:function(){return[Ca(ya)[0],Sa().memoizedState]},useMutableSource:Ea,useSyncExternalStore:ba,useId:qa,unstable_isNewReconciler:!1},eo={readContext:Ms,useCallback:Ha,useContext:Ms,useEffect:La,useImperativeHandle:Ba,useInsertionEffect:xa,useLayoutEffect:Fa,useMemo:$a,useReducer:Ta,useRef:Da,useState:function(){return Ta(ya)},useDebugValue:Va,useDeferredValue:function(e){var t=Sa();return null===oa?t.memoizedState=e:ja(t,oa.memoizedState,e)},useTransition:function(){return[Ta(ya)[0],Sa().memoizedState]},useMutableSource:Ea,useSyncExternalStore:ba,useId:qa,unstable_isNewReconciler:!1};function to(e,t){if(e&&e.defaultProps){for(var i in t=F({},t),e=e.defaultProps)void 0===t[i]&&(t[i]=e[i]);return t}return t}function io(e,t,i,n){i=null==(i=i(n,t=e.memoizedState))?t:F({},t,i),e.memoizedState=i,0===e.lanes&&(e.updateQueue.baseState=i)}var no={isMounted:function(e){return!!(e=e._reactInternals)&&$e(e)===e},enqueueSetState:function(e,t,i){e=e._reactInternals;var n=ec(),r=tc(e),s=Us(n,r);s.payload=t,null!=i&&(s.callback=i),null!==(t=Bs(e,s,r))&&(ic(t,e,r,n),Vs(t,e,r))},enqueueReplaceState:function(e,t,i){e=e._reactInternals;var n=ec(),r=tc(e),s=Us(n,r);s.tag=1,s.payload=t,null!=i&&(s.callback=i),null!==(t=Bs(e,s,r))&&(ic(t,e,r,n),Vs(t,e,r))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var i=ec(),n=tc(e),r=Us(i,n);r.tag=2,null!=t&&(r.callback=t),null!==(t=Bs(e,r,n))&&(ic(t,e,n,i),Vs(t,e,n))}};function ro(e,t,i,n,r,s,a){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(n,s,a):!(t.prototype&&t.prototype.isPureReactComponent&&ln(i,n)&&ln(r,s))}function so(e,t,i){var n=!1,r=Ar,s=t.contextType;return"object"==typeof s&&null!==s?s=Ms(s):(r=kr(t)?Mr:Pr.current,s=(n=null!=(n=t.contextTypes))?Dr(e,r):Ar),t=new t(i,s),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=no,e.stateNode=t,t._reactInternals=e,n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=r,e.__reactInternalMemoizedMaskedChildContext=s),t}function ao(e,t,i,n){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(i,n),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(i,n),t.state!==e&&no.enqueueReplaceState(t,t.state,null)}function oo(e,t,i,n){var r=e.stateNode;r.props=i,r.state=e.memoizedState,r.refs={},xs(e);var s=t.contextType;"object"==typeof s&&null!==s?r.context=Ms(s):(s=kr(t)?Mr:Pr.current,r.context=Dr(e,s)),r.state=e.memoizedState,"function"==typeof(s=t.getDerivedStateFromProps)&&(io(e,t,s,i),r.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof r.getSnapshotBeforeUpdate||"function"!=typeof r.UNSAFE_componentWillMount&&"function"!=typeof r.componentWillMount||(t=r.state,"function"==typeof r.componentWillMount&&r.componentWillMount(),"function"==typeof r.UNSAFE_componentWillMount&&r.UNSAFE_componentWillMount(),t!==r.state&&no.enqueueReplaceState(r,r.state,null),$s(e,i,r,n),r.state=e.memoizedState),"function"==typeof r.componentDidMount&&(e.flags|=4194308)}function lo(e,t){try{var i="",n=t;do{i+=H(n),n=n.return}while(n);var r=i}catch(e){r="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:t,stack:r,digest:null}}function co(e,t,i){return{value:e,source:null,stack:null!=i?i:null,digest:null!=t?t:null}}function uo(e,t){try{console.error(t.value)}catch(e){setTimeout((function(){throw e}))}}var ho="function"==typeof WeakMap?WeakMap:Map;function go(e,t,i){(i=Us(-1,i)).tag=3,i.payload={element:null};var n=t.value;return i.callback=function(){Gl||(Gl=!0,ql=n),uo(0,t)},i}function po(e,t,i){(i=Us(-1,i)).tag=3;var n=e.type.getDerivedStateFromError;if("function"==typeof n){var r=t.value;i.payload=function(){return n(r)},i.callback=function(){uo(0,t)}}var s=e.stateNode;return null!==s&&"function"==typeof s.componentDidCatch&&(i.callback=function(){uo(0,t),"function"!=typeof n&&(null===zl?zl=new Set([this]):zl.add(this));var e=t.stack;this.componentDidCatch(t.value,{componentStack:null!==e?e:""})}),i}function mo(e,t,i){var n=e.pingCache;if(null===n){n=e.pingCache=new ho;var r=new Set;n.set(t,r)}else void 0===(r=n.get(t))&&(r=new Set,n.set(t,r));r.has(i)||(r.add(i),e=Ic.bind(null,e,t,i),t.then(e,e))}function fo(e){do{var t;if((t=13===e.tag)&&(t=null===(t=e.memoizedState)||null!==t.dehydrated),t)return e;e=e.return}while(null!==e);return null}function vo(e,t,i,n,r){return 1&e.mode?(e.flags|=65536,e.lanes=r,e):(e===t?e.flags|=65536:(e.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((t=Us(-1,1)).tag=2,Bs(i,t,1))),i.lanes|=1),e)}var So=C.ReactCurrentOwner,yo=!1;function Co(e,t,i,n){t.child=null===e?Ts(t,null,i,n):Cs(t,e.child,i,n)}function To(e,t,i,n,r){i=i.render;var s=t.ref;return Rs(t,r),n=ma(e,t,i,n,s,r),i=fa(),null===e||yo?(rs&&i&&es(t),t.flags|=1,Co(e,t,n,r),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~r,Go(e,t,r))}function Eo(e,t,i,n,r){if(null===e){var s=i.type;return"function"!=typeof s||kc(s)||void 0!==s.defaultProps||null!==i.compare||void 0!==i.defaultProps?((e=Nc(i.type,null,n,t,t.mode,r)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=s,bo(e,t,s,n,r))}if(s=e.child,!(e.lanes&r)){var a=s.memoizedProps;if((i=null!==(i=i.compare)?i:ln)(a,n)&&e.ref===t.ref)return Go(e,t,r)}return t.flags|=1,(e=Oc(s,n)).ref=t.ref,e.return=t,t.child=e}function bo(e,t,i,n,r){if(null!==e){var s=e.memoizedProps;if(ln(s,n)&&e.ref===t.ref){if(yo=!1,t.pendingProps=n=s,!(e.lanes&r))return t.lanes=e.lanes,Go(e,t,r);131072&e.flags&&(yo=!0)}}return wo(e,t,i,n,r)}function _o(e,t,i){var n=t.pendingProps,r=n.children,s=null!==e?e.memoizedState:null;if("hidden"===n.mode)if(1&t.mode){if(!(1073741824&i))return e=null!==s?s.baseLanes|i:i,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,wr(Ol,kl),kl|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=null!==s?s.baseLanes:i,wr(Ol,kl),kl|=n}else t.memoizedState={baseLanes:0,cachePool:null,transitions:null},wr(Ol,kl),kl|=i;else null!==s?(n=s.baseLanes|i,t.memoizedState=null):n=i,wr(Ol,kl),kl|=n;return Co(e,t,r,i),t.child}function Io(e,t){var i=t.ref;(null===e&&null!==i||null!==e&&e.ref!==i)&&(t.flags|=512,t.flags|=2097152)}function wo(e,t,i,n,r){var s=kr(i)?Mr:Pr.current;return s=Dr(t,s),Rs(t,r),i=ma(e,t,i,n,s,r),n=fa(),null===e||yo?(rs&&n&&es(t),t.flags|=1,Co(e,t,i,r),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~r,Go(e,t,r))}function Ao(e,t,i,n,r){if(kr(i)){var s=!0;xr(t)}else s=!1;if(Rs(t,r),null===t.stateNode)jo(e,t),so(t,i,n),oo(t,i,n,r),n=!0;else if(null===e){var a=t.stateNode,o=t.memoizedProps;a.props=o;var l=a.context,c=i.contextType;c="object"==typeof c&&null!==c?Ms(c):Dr(t,c=kr(i)?Mr:Pr.current);var d=i.getDerivedStateFromProps,u="function"==typeof d||"function"==typeof a.getSnapshotBeforeUpdate;u||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(o!==n||l!==c)&&ao(t,a,n,c),Ls=!1;var h=t.memoizedState;a.state=h,$s(t,n,a,r),l=t.memoizedState,o!==n||h!==l||Rr.current||Ls?("function"==typeof d&&(io(t,i,d,n),l=t.memoizedState),(o=Ls||ro(t,i,o,n,h,l,c))?(u||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||("function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"==typeof a.componentDidMount&&(t.flags|=4194308)):("function"==typeof a.componentDidMount&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=l),a.props=n,a.state=l,a.context=c,n=o):("function"==typeof a.componentDidMount&&(t.flags|=4194308),n=!1)}else{a=t.stateNode,Fs(e,t),o=t.memoizedProps,c=t.type===t.elementType?o:to(t.type,o),a.props=c,u=t.pendingProps,h=a.context,l="object"==typeof(l=i.contextType)&&null!==l?Ms(l):Dr(t,l=kr(i)?Mr:Pr.current);var g=i.getDerivedStateFromProps;(d="function"==typeof g||"function"==typeof a.getSnapshotBeforeUpdate)||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(o!==u||h!==l)&&ao(t,a,n,l),Ls=!1,h=t.memoizedState,a.state=h,$s(t,n,a,r);var p=t.memoizedState;o!==u||h!==p||Rr.current||Ls?("function"==typeof g&&(io(t,i,g,n),p=t.memoizedState),(c=Ls||ro(t,i,c,n,h,p,l)||!1)?(d||"function"!=typeof a.UNSAFE_componentWillUpdate&&"function"!=typeof a.componentWillUpdate||("function"==typeof a.componentWillUpdate&&a.componentWillUpdate(n,p,l),"function"==typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(n,p,l)),"function"==typeof a.componentDidUpdate&&(t.flags|=4),"function"==typeof a.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!=typeof a.componentDidUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),"function"!=typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=n,t.memoizedState=p),a.props=n,a.state=p,a.context=l,n=c):("function"!=typeof a.componentDidUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),"function"!=typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),n=!1)}return Po(e,t,i,n,s,r)}function Po(e,t,i,n,r,s){Io(e,t);var a=!!(128&t.flags);if(!n&&!a)return r&&Fr(t,i,!1),Go(e,t,s);n=t.stateNode,So.current=t;var o=a&&"function"!=typeof i.getDerivedStateFromError?null:n.render();return t.flags|=1,null!==e&&a?(t.child=Cs(t,e.child,null,s),t.child=Cs(t,null,o,s)):Co(e,t,o,s),t.memoizedState=n.state,r&&Fr(t,i,!0),t.child}function Ro(e){var t=e.stateNode;t.pendingContext?Nr(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Nr(0,t.context,!1),Js(e,t.containerInfo)}function Mo(e,t,i,n,r){return gs(),ps(r),t.flags|=256,Co(e,t,i,n),t.child}var Do,ko,Oo,No,Lo={dehydrated:null,treeContext:null,retryLane:0};function xo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Fo(e,t,i){var n,r=t.pendingProps,a=Xs.current,o=!1,l=!!(128&t.flags);if((n=l)||(n=(null===e||null!==e.memoizedState)&&!!(2&a)),n?(o=!0,t.flags&=-129):null!==e&&null===e.memoizedState||(a|=1),wr(Xs,1&a),null===e)return cs(t),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated)?(1&t.mode?"$!"===e.data?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(l=r.children,e=r.fallback,o?(r=t.mode,o=t.child,l={mode:"hidden",children:l},1&r||null===o?o=xc(l,r,0,null):(o.childLanes=0,o.pendingProps=l),e=Lc(e,r,i,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=xo(i),t.memoizedState=Lo,e):Uo(t,l));if(null!==(a=e.memoizedState)&&null!==(n=a.dehydrated))return function(e,t,i,n,r,a,o){if(i)return 256&t.flags?(t.flags&=-257,Bo(e,t,o,n=co(Error(s(422))))):null!==t.memoizedState?(t.child=e.child,t.flags|=128,null):(a=n.fallback,r=t.mode,n=xc({mode:"visible",children:n.children},r,0,null),(a=Lc(a,r,o,null)).flags|=2,n.return=t,a.return=t,n.sibling=a,t.child=n,1&t.mode&&Cs(t,e.child,null,o),t.child.memoizedState=xo(o),t.memoizedState=Lo,a);if(!(1&t.mode))return Bo(e,t,o,null);if("$!"===r.data){if(n=r.nextSibling&&r.nextSibling.dataset)var l=n.dgst;return n=l,Bo(e,t,o,n=co(a=Error(s(419)),n,void 0))}if(l=!!(o&e.childLanes),yo||l){if(null!==(n=Rl)){switch(o&-o){case 4:r=2;break;case 16:r=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:r=32;break;case 536870912:r=268435456;break;default:r=0}0!==(r=r&(n.suspendedLanes|o)?0:r)&&r!==a.retryLane&&(a.retryLane=r,Ns(e,r),ic(n,e,r,-1))}return mc(),Bo(e,t,o,n=co(Error(s(421))))}return"$?"===r.data?(t.flags|=128,t.child=e.child,t=Ac.bind(null,e),r._reactRetry=t,null):(e=a.treeContext,ns=cr(r.nextSibling),is=t,rs=!0,ss=null,null!==e&&(Wr[Kr++]=Yr,Wr[Kr++]=Qr,Wr[Kr++]=Jr,Yr=e.id,Qr=e.overflow,Jr=t),(t=Uo(t,n.children)).flags|=4096,t)}(e,t,l,r,n,a,i);if(o){o=r.fallback,l=t.mode,n=(a=e.child).sibling;var c={mode:"hidden",children:r.children};return 1&l||t.child===a?(r=Oc(a,c)).subtreeFlags=14680064&a.subtreeFlags:((r=t.child).childLanes=0,r.pendingProps=c,t.deletions=null),null!==n?o=Oc(n,o):(o=Lc(o,l,i,null)).flags|=2,o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,l=null===(l=e.child.memoizedState)?xo(i):{baseLanes:l.baseLanes|i,cachePool:null,transitions:l.transitions},o.memoizedState=l,o.childLanes=e.childLanes&~i,t.memoizedState=Lo,r}return e=(o=e.child).sibling,r=Oc(o,{mode:"visible",children:r.children}),!(1&t.mode)&&(r.lanes=i),r.return=t,r.sibling=null,null!==e&&(null===(i=t.deletions)?(t.deletions=[e],t.flags|=16):i.push(e)),t.child=r,t.memoizedState=null,r}function Uo(e,t){return(t=xc({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function Bo(e,t,i,n){return null!==n&&ps(n),Cs(t,e.child,null,i),(e=Uo(t,t.pendingProps.children)).flags|=2,t.memoizedState=null,e}function Vo(e,t,i){e.lanes|=t;var n=e.alternate;null!==n&&(n.lanes|=t),Ps(e.return,t,i)}function Ho(e,t,i,n,r){var s=e.memoizedState;null===s?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:i,tailMode:r}:(s.isBackwards=t,s.rendering=null,s.renderingStartTime=0,s.last=n,s.tail=i,s.tailMode=r)}function $o(e,t,i){var n=t.pendingProps,r=n.revealOrder,s=n.tail;if(Co(e,t,n.children,i),2&(n=Xs.current))n=1&n|2,t.flags|=128;else{if(null!==e&&128&e.flags)e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Vo(e,i,t);else if(19===e.tag)Vo(e,i,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(wr(Xs,n),1&t.mode)switch(r){case"forwards":for(i=t.child,r=null;null!==i;)null!==(e=i.alternate)&&null===ea(e)&&(r=i),i=i.sibling;null===(i=r)?(r=t.child,t.child=null):(r=i.sibling,i.sibling=null),Ho(t,!1,r,i,s);break;case"backwards":for(i=null,r=t.child,t.child=null;null!==r;){if(null!==(e=r.alternate)&&null===ea(e)){t.child=r;break}e=r.sibling,r.sibling=i,i=r,r=e}Ho(t,!0,i,null,s);break;case"together":Ho(t,!1,null,null,void 0);break;default:t.memoizedState=null}else t.memoizedState=null;return t.child}function jo(e,t){!(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Go(e,t,i){if(null!==e&&(t.dependencies=e.dependencies),xl|=t.lanes,!(i&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(s(153));if(null!==t.child){for(i=Oc(e=t.child,e.pendingProps),t.child=i,i.return=t;null!==e.sibling;)e=e.sibling,(i=i.sibling=Oc(e,e.pendingProps)).return=t;i.sibling=null}return t.child}function qo(e,t){if(!rs)switch(e.tailMode){case"hidden":t=e.tail;for(var i=null;null!==t;)null!==t.alternate&&(i=t),t=t.sibling;null===i?e.tail=null:i.sibling=null;break;case"collapsed":i=e.tail;for(var n=null;null!==i;)null!==i.alternate&&(n=i),i=i.sibling;null===n?t||null===e.tail?e.tail=null:e.tail.sibling=null:n.sibling=null}}function zo(e){var t=null!==e.alternate&&e.alternate.child===e.child,i=0,n=0;if(t)for(var r=e.child;null!==r;)i|=r.lanes|r.childLanes,n|=14680064&r.subtreeFlags,n|=14680064&r.flags,r.return=e,r=r.sibling;else for(r=e.child;null!==r;)i|=r.lanes|r.childLanes,n|=r.subtreeFlags,n|=r.flags,r.return=e,r=r.sibling;return e.subtreeFlags|=n,e.childLanes=i,t}function Wo(e,t,i){var n=t.pendingProps;switch(ts(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return zo(t),null;case 1:case 17:return kr(t.type)&&Or(),zo(t),null;case 3:return n=t.stateNode,Ys(),Ir(Rr),Ir(Pr),ia(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),null!==e&&null!==e.child||(us(t)?t.flags|=4:null===e||e.memoizedState.isDehydrated&&!(256&t.flags)||(t.flags|=1024,null!==ss&&(ac(ss),ss=null))),ko(e,t),zo(t),null;case 5:Zs(t);var r=Ks(Ws.current);if(i=t.type,null!==e&&null!=t.stateNode)Oo(e,t,i,n,r),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!n){if(null===t.stateNode)throw Error(s(166));return zo(t),null}if(e=Ks(qs.current),us(t)){n=t.stateNode,i=t.type;var a=t.memoizedProps;switch(n[hr]=t,n[gr]=a,e=!!(1&t.mode),i){case"dialog":Bn("cancel",n),Bn("close",n);break;case"iframe":case"object":case"embed":Bn("load",n);break;case"video":case"audio":for(r=0;r<Ln.length;r++)Bn(Ln[r],n);break;case"source":Bn("error",n);break;case"img":case"image":case"link":Bn("error",n),Bn("load",n);break;case"details":Bn("toggle",n);break;case"input":Y(n,a),Bn("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!a.multiple},Bn("invalid",n);break;case"textarea":re(n,a),Bn("invalid",n)}for(var l in Se(i,a),r=null,a)if(a.hasOwnProperty(l)){var c=a[l];"children"===l?"string"==typeof c?n.textContent!==c&&(!0!==a.suppressHydrationWarning&&Zn(n.textContent,c,e),r=["children",c]):"number"==typeof c&&n.textContent!==""+c&&(!0!==a.suppressHydrationWarning&&Zn(n.textContent,c,e),r=["children",""+c]):o.hasOwnProperty(l)&&null!=c&&"onScroll"===l&&Bn("scroll",n)}switch(i){case"input":z(n),X(n,a,!0);break;case"textarea":z(n),ae(n);break;case"select":case"option":break;default:"function"==typeof a.onClick&&(n.onclick=Xn)}n=r,t.updateQueue=n,null!==n&&(t.flags|=4)}else{l=9===r.nodeType?r:r.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=oe(i)),"http://www.w3.org/1999/xhtml"===e?"script"===i?((e=l.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"==typeof n.is?e=l.createElement(i,{is:n.is}):(e=l.createElement(i),"select"===i&&(l=e,n.multiple?l.multiple=!0:n.size&&(l.size=n.size))):e=l.createElementNS(e,i),e[hr]=t,e[gr]=n,Do(e,t,!1,!1),t.stateNode=e;e:{switch(l=ye(i,n),i){case"dialog":Bn("cancel",e),Bn("close",e),r=n;break;case"iframe":case"object":case"embed":Bn("load",e),r=n;break;case"video":case"audio":for(r=0;r<Ln.length;r++)Bn(Ln[r],e);r=n;break;case"source":Bn("error",e),r=n;break;case"img":case"image":case"link":Bn("error",e),Bn("load",e),r=n;break;case"details":Bn("toggle",e),r=n;break;case"input":Y(e,n),r=J(e,n),Bn("invalid",e);break;case"option":default:r=n;break;case"select":e._wrapperState={wasMultiple:!!n.multiple},r=F({},n,{value:void 0}),Bn("invalid",e);break;case"textarea":re(e,n),r=ne(e,n),Bn("invalid",e)}for(a in Se(i,r),c=r)if(c.hasOwnProperty(a)){var d=c[a];"style"===a?fe(e,d):"dangerouslySetInnerHTML"===a?null!=(d=d?d.__html:void 0)&&ue(e,d):"children"===a?"string"==typeof d?("textarea"!==i||""!==d)&&he(e,d):"number"==typeof d&&he(e,""+d):"suppressContentEditableWarning"!==a&&"suppressHydrationWarning"!==a&&"autoFocus"!==a&&(o.hasOwnProperty(a)?null!=d&&"onScroll"===a&&Bn("scroll",e):null!=d&&y(e,a,d,l))}switch(i){case"input":z(e),X(e,n,!1);break;case"textarea":z(e),ae(e);break;case"option":null!=n.value&&e.setAttribute("value",""+G(n.value));break;case"select":e.multiple=!!n.multiple,null!=(a=n.value)?ie(e,!!n.multiple,a,!1):null!=n.defaultValue&&ie(e,!!n.multiple,n.defaultValue,!0);break;default:"function"==typeof r.onClick&&(e.onclick=Xn)}switch(i){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(t.flags|=4)}null!==t.ref&&(t.flags|=512,t.flags|=2097152)}return zo(t),null;case 6:if(e&&null!=t.stateNode)No(e,t,e.memoizedProps,n);else{if("string"!=typeof n&&null===t.stateNode)throw Error(s(166));if(i=Ks(Ws.current),Ks(qs.current),us(t)){if(n=t.stateNode,i=t.memoizedProps,n[hr]=t,(a=n.nodeValue!==i)&&null!==(e=is))switch(e.tag){case 3:Zn(n.nodeValue,i,!!(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&Zn(n.nodeValue,i,!!(1&e.mode))}a&&(t.flags|=4)}else(n=(9===i.nodeType?i:i.ownerDocument).createTextNode(n))[hr]=t,t.stateNode=n}return zo(t),null;case 13:if(Ir(Xs),n=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(rs&&null!==ns&&1&t.mode&&!(128&t.flags))hs(),gs(),t.flags|=98560,a=!1;else if(a=us(t),null!==n&&null!==n.dehydrated){if(null===e){if(!a)throw Error(s(318));if(!(a=null!==(a=t.memoizedState)?a.dehydrated:null))throw Error(s(317));a[hr]=t}else gs(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;zo(t),a=!1}else null!==ss&&(ac(ss),ss=null),a=!0;if(!a)return 65536&t.flags?t:null}return 128&t.flags?(t.lanes=i,t):((n=null!==n)!=(null!==e&&null!==e.memoizedState)&&n&&(t.child.flags|=8192,1&t.mode&&(null===e||1&Xs.current?0===Nl&&(Nl=3):mc())),null!==t.updateQueue&&(t.flags|=4),zo(t),null);case 4:return Ys(),ko(e,t),null===e&&$n(t.stateNode.containerInfo),zo(t),null;case 10:return As(t.type._context),zo(t),null;case 19:if(Ir(Xs),null===(a=t.memoizedState))return zo(t),null;if(n=!!(128&t.flags),null===(l=a.rendering))if(n)qo(a,!1);else{if(0!==Nl||null!==e&&128&e.flags)for(e=t.child;null!==e;){if(null!==(l=ea(e))){for(t.flags|=128,qo(a,!1),null!==(n=l.updateQueue)&&(t.updateQueue=n,t.flags|=4),t.subtreeFlags=0,n=i,i=t.child;null!==i;)e=n,(a=i).flags&=14680066,null===(l=a.alternate)?(a.childLanes=0,a.lanes=e,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=l.childLanes,a.lanes=l.lanes,a.child=l.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=l.memoizedProps,a.memoizedState=l.memoizedState,a.updateQueue=l.updateQueue,a.type=l.type,e=l.dependencies,a.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),i=i.sibling;return wr(Xs,1&Xs.current|2),t.child}e=e.sibling}null!==a.tail&&Qe()>$l&&(t.flags|=128,n=!0,qo(a,!1),t.lanes=4194304)}else{if(!n)if(null!==(e=ea(l))){if(t.flags|=128,n=!0,null!==(i=e.updateQueue)&&(t.updateQueue=i,t.flags|=4),qo(a,!0),null===a.tail&&"hidden"===a.tailMode&&!l.alternate&&!rs)return zo(t),null}else 2*Qe()-a.renderingStartTime>$l&&1073741824!==i&&(t.flags|=128,n=!0,qo(a,!1),t.lanes=4194304);a.isBackwards?(l.sibling=t.child,t.child=l):(null!==(i=a.last)?i.sibling=l:t.child=l,a.last=l)}return null!==a.tail?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=Qe(),t.sibling=null,i=Xs.current,wr(Xs,n?1&i|2:1&i),t):(zo(t),null);case 22:case 23:return uc(),n=null!==t.memoizedState,null!==e&&null!==e.memoizedState!==n&&(t.flags|=8192),n&&1&t.mode?!!(1073741824&kl)&&(zo(t),6&t.subtreeFlags&&(t.flags|=8192)):zo(t),null;case 24:case 25:return null}throw Error(s(156,t.tag))}function Ko(e,t){switch(ts(t),t.tag){case 1:return kr(t.type)&&Or(),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return Ys(),Ir(Rr),Ir(Pr),ia(),65536&(e=t.flags)&&!(128&e)?(t.flags=-65537&e|128,t):null;case 5:return Zs(t),null;case 13:if(Ir(Xs),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(s(340));gs()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return Ir(Xs),null;case 4:return Ys(),null;case 10:return As(t.type._context),null;case 22:case 23:return uc(),null;default:return null}}Do=function(e,t){for(var i=t.child;null!==i;){if(5===i.tag||6===i.tag)e.appendChild(i.stateNode);else if(4!==i.tag&&null!==i.child){i.child.return=i,i=i.child;continue}if(i===t)break;for(;null===i.sibling;){if(null===i.return||i.return===t)return;i=i.return}i.sibling.return=i.return,i=i.sibling}},ko=function(){},Oo=function(e,t,i,n){var r=e.memoizedProps;if(r!==n){e=t.stateNode,Ks(qs.current);var s,a=null;switch(i){case"input":r=J(e,r),n=J(e,n),a=[];break;case"select":r=F({},r,{value:void 0}),n=F({},n,{value:void 0}),a=[];break;case"textarea":r=ne(e,r),n=ne(e,n),a=[];break;default:"function"!=typeof r.onClick&&"function"==typeof n.onClick&&(e.onclick=Xn)}for(d in Se(i,n),i=null,r)if(!n.hasOwnProperty(d)&&r.hasOwnProperty(d)&&null!=r[d])if("style"===d){var l=r[d];for(s in l)l.hasOwnProperty(s)&&(i||(i={}),i[s]="")}else"dangerouslySetInnerHTML"!==d&&"children"!==d&&"suppressContentEditableWarning"!==d&&"suppressHydrationWarning"!==d&&"autoFocus"!==d&&(o.hasOwnProperty(d)?a||(a=[]):(a=a||[]).push(d,null));for(d in n){var c=n[d];if(l=null!=r?r[d]:void 0,n.hasOwnProperty(d)&&c!==l&&(null!=c||null!=l))if("style"===d)if(l){for(s in l)!l.hasOwnProperty(s)||c&&c.hasOwnProperty(s)||(i||(i={}),i[s]="");for(s in c)c.hasOwnProperty(s)&&l[s]!==c[s]&&(i||(i={}),i[s]=c[s])}else i||(a||(a=[]),a.push(d,i)),i=c;else"dangerouslySetInnerHTML"===d?(c=c?c.__html:void 0,l=l?l.__html:void 0,null!=c&&l!==c&&(a=a||[]).push(d,c)):"children"===d?"string"!=typeof c&&"number"!=typeof c||(a=a||[]).push(d,""+c):"suppressContentEditableWarning"!==d&&"suppressHydrationWarning"!==d&&(o.hasOwnProperty(d)?(null!=c&&"onScroll"===d&&Bn("scroll",e),a||l===c||(a=[])):(a=a||[]).push(d,c))}i&&(a=a||[]).push("style",i);var d=a;(t.updateQueue=d)&&(t.flags|=4)}},No=function(e,t,i,n){i!==n&&(t.flags|=4)};var Jo=!1,Yo=!1,Qo="function"==typeof WeakSet?WeakSet:Set,Zo=null;function Xo(e,t){var i=e.ref;if(null!==i)if("function"==typeof i)try{i(null)}catch(i){_c(e,t,i)}else i.current=null}function el(e,t,i){try{i()}catch(i){_c(e,t,i)}}var tl=!1;function il(e,t,i){var n=t.updateQueue;if(null!==(n=null!==n?n.lastEffect:null)){var r=n=n.next;do{if((r.tag&e)===e){var s=r.destroy;r.destroy=void 0,void 0!==s&&el(t,i,s)}r=r.next}while(r!==n)}}function nl(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var i=t=t.next;do{if((i.tag&e)===e){var n=i.create;i.destroy=n()}i=i.next}while(i!==t)}}function rl(e){var t=e.ref;if(null!==t){var i=e.stateNode;e.tag,e=i,"function"==typeof t?t(e):t.current=e}}function sl(e){var t=e.alternate;null!==t&&(e.alternate=null,sl(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(t=e.stateNode)&&(delete t[hr],delete t[gr],delete t[mr],delete t[fr],delete t[vr]),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function al(e){return 5===e.tag||3===e.tag||4===e.tag}function ol(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||al(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function ll(e,t,i){var n=e.tag;if(5===n||6===n)e=e.stateNode,t?8===i.nodeType?i.parentNode.insertBefore(e,t):i.insertBefore(e,t):(8===i.nodeType?(t=i.parentNode).insertBefore(e,i):(t=i).appendChild(e),null!=(i=i._reactRootContainer)||null!==t.onclick||(t.onclick=Xn));else if(4!==n&&null!==(e=e.child))for(ll(e,t,i),e=e.sibling;null!==e;)ll(e,t,i),e=e.sibling}function cl(e,t,i){var n=e.tag;if(5===n||6===n)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(4!==n&&null!==(e=e.child))for(cl(e,t,i),e=e.sibling;null!==e;)cl(e,t,i),e=e.sibling}var dl=null,ul=!1;function hl(e,t,i){for(i=i.child;null!==i;)gl(e,t,i),i=i.sibling}function gl(e,t,i){if(st&&"function"==typeof st.onCommitFiberUnmount)try{st.onCommitFiberUnmount(rt,i)}catch(e){}switch(i.tag){case 5:Yo||Xo(i,t);case 6:var n=dl,r=ul;dl=null,hl(e,t,i),ul=r,null!==(dl=n)&&(ul?(e=dl,i=i.stateNode,8===e.nodeType?e.parentNode.removeChild(i):e.removeChild(i)):dl.removeChild(i.stateNode));break;case 18:null!==dl&&(ul?(e=dl,i=i.stateNode,8===e.nodeType?lr(e.parentNode,i):1===e.nodeType&&lr(e,i),$t(e)):lr(dl,i.stateNode));break;case 4:n=dl,r=ul,dl=i.stateNode.containerInfo,ul=!0,hl(e,t,i),dl=n,ul=r;break;case 0:case 11:case 14:case 15:if(!Yo&&null!==(n=i.updateQueue)&&null!==(n=n.lastEffect)){r=n=n.next;do{var s=r,a=s.destroy;s=s.tag,void 0!==a&&(2&s||4&s)&&el(i,t,a),r=r.next}while(r!==n)}hl(e,t,i);break;case 1:if(!Yo&&(Xo(i,t),"function"==typeof(n=i.stateNode).componentWillUnmount))try{n.props=i.memoizedProps,n.state=i.memoizedState,n.componentWillUnmount()}catch(e){_c(i,t,e)}hl(e,t,i);break;case 21:hl(e,t,i);break;case 22:1&i.mode?(Yo=(n=Yo)||null!==i.memoizedState,hl(e,t,i),Yo=n):hl(e,t,i);break;default:hl(e,t,i)}}function pl(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var i=e.stateNode;null===i&&(i=e.stateNode=new Qo),t.forEach((function(t){var n=Pc.bind(null,e,t);i.has(t)||(i.add(t),t.then(n,n))}))}}function ml(e,t){var i=t.deletions;if(null!==i)for(var n=0;n<i.length;n++){var r=i[n];try{var a=e,o=t,l=o;e:for(;null!==l;){switch(l.tag){case 5:dl=l.stateNode,ul=!1;break e;case 3:case 4:dl=l.stateNode.containerInfo,ul=!0;break e}l=l.return}if(null===dl)throw Error(s(160));gl(a,o,r),dl=null,ul=!1;var c=r.alternate;null!==c&&(c.return=null),r.return=null}catch(e){_c(r,t,e)}}if(12854&t.subtreeFlags)for(t=t.child;null!==t;)fl(t,e),t=t.sibling}function fl(e,t){var i=e.alternate,n=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(ml(t,e),vl(e),4&n){try{il(3,e,e.return),nl(3,e)}catch(t){_c(e,e.return,t)}try{il(5,e,e.return)}catch(t){_c(e,e.return,t)}}break;case 1:ml(t,e),vl(e),512&n&&null!==i&&Xo(i,i.return);break;case 5:if(ml(t,e),vl(e),512&n&&null!==i&&Xo(i,i.return),32&e.flags){var r=e.stateNode;try{he(r,"")}catch(t){_c(e,e.return,t)}}if(4&n&&null!=(r=e.stateNode)){var a=e.memoizedProps,o=null!==i?i.memoizedProps:a,l=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===l&&"radio"===a.type&&null!=a.name&&Q(r,a),ye(l,o);var d=ye(l,a);for(o=0;o<c.length;o+=2){var u=c[o],h=c[o+1];"style"===u?fe(r,h):"dangerouslySetInnerHTML"===u?ue(r,h):"children"===u?he(r,h):y(r,u,h,d)}switch(l){case"input":Z(r,a);break;case"textarea":se(r,a);break;case"select":var g=r._wrapperState.wasMultiple;r._wrapperState.wasMultiple=!!a.multiple;var p=a.value;null!=p?ie(r,!!a.multiple,p,!1):g!==!!a.multiple&&(null!=a.defaultValue?ie(r,!!a.multiple,a.defaultValue,!0):ie(r,!!a.multiple,a.multiple?[]:"",!1))}r[gr]=a}catch(t){_c(e,e.return,t)}}break;case 6:if(ml(t,e),vl(e),4&n){if(null===e.stateNode)throw Error(s(162));r=e.stateNode,a=e.memoizedProps;try{r.nodeValue=a}catch(t){_c(e,e.return,t)}}break;case 3:if(ml(t,e),vl(e),4&n&&null!==i&&i.memoizedState.isDehydrated)try{$t(t.containerInfo)}catch(t){_c(e,e.return,t)}break;case 4:default:ml(t,e),vl(e);break;case 13:ml(t,e),vl(e),8192&(r=e.child).flags&&(a=null!==r.memoizedState,r.stateNode.isHidden=a,!a||null!==r.alternate&&null!==r.alternate.memoizedState||(Hl=Qe())),4&n&&pl(e);break;case 22:if(u=null!==i&&null!==i.memoizedState,1&e.mode?(Yo=(d=Yo)||u,ml(t,e),Yo=d):ml(t,e),vl(e),8192&n){if(d=null!==e.memoizedState,(e.stateNode.isHidden=d)&&!u&&1&e.mode)for(Zo=e,u=e.child;null!==u;){for(h=Zo=u;null!==Zo;){switch(p=(g=Zo).child,g.tag){case 0:case 11:case 14:case 15:il(4,g,g.return);break;case 1:Xo(g,g.return);var m=g.stateNode;if("function"==typeof m.componentWillUnmount){n=g,i=g.return;try{t=n,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(e){_c(n,i,e)}}break;case 5:Xo(g,g.return);break;case 22:if(null!==g.memoizedState){Tl(h);continue}}null!==p?(p.return=g,Zo=p):Tl(h)}u=u.sibling}e:for(u=null,h=e;;){if(5===h.tag){if(null===u){u=h;try{r=h.stateNode,d?"function"==typeof(a=r.style).setProperty?a.setProperty("display","none","important"):a.display="none":(l=h.stateNode,o=null!=(c=h.memoizedProps.style)&&c.hasOwnProperty("display")?c.display:null,l.style.display=me("display",o))}catch(t){_c(e,e.return,t)}}}else if(6===h.tag){if(null===u)try{h.stateNode.nodeValue=d?"":h.memoizedProps}catch(t){_c(e,e.return,t)}}else if((22!==h.tag&&23!==h.tag||null===h.memoizedState||h===e)&&null!==h.child){h.child.return=h,h=h.child;continue}if(h===e)break e;for(;null===h.sibling;){if(null===h.return||h.return===e)break e;u===h&&(u=null),h=h.return}u===h&&(u=null),h.sibling.return=h.return,h=h.sibling}}break;case 19:ml(t,e),vl(e),4&n&&pl(e);case 21:}}function vl(e){var t=e.flags;if(2&t){try{e:{for(var i=e.return;null!==i;){if(al(i)){var n=i;break e}i=i.return}throw Error(s(160))}switch(n.tag){case 5:var r=n.stateNode;32&n.flags&&(he(r,""),n.flags&=-33),cl(e,ol(e),r);break;case 3:case 4:var a=n.stateNode.containerInfo;ll(e,ol(e),a);break;default:throw Error(s(161))}}catch(t){_c(e,e.return,t)}e.flags&=-3}4096&t&&(e.flags&=-4097)}function Sl(e,t,i){Zo=e,yl(e,t,i)}function yl(e,t,i){for(var n=!!(1&e.mode);null!==Zo;){var r=Zo,s=r.child;if(22===r.tag&&n){var a=null!==r.memoizedState||Jo;if(!a){var o=r.alternate,l=null!==o&&null!==o.memoizedState||Yo;o=Jo;var c=Yo;if(Jo=a,(Yo=l)&&!c)for(Zo=r;null!==Zo;)l=(a=Zo).child,22===a.tag&&null!==a.memoizedState?El(r):null!==l?(l.return=a,Zo=l):El(r);for(;null!==s;)Zo=s,yl(s,t,i),s=s.sibling;Zo=r,Jo=o,Yo=c}Cl(e)}else 8772&r.subtreeFlags&&null!==s?(s.return=r,Zo=s):Cl(e)}}function Cl(e){for(;null!==Zo;){var t=Zo;if(8772&t.flags){var i=t.alternate;try{if(8772&t.flags)switch(t.tag){case 0:case 11:case 15:Yo||nl(5,t);break;case 1:var n=t.stateNode;if(4&t.flags&&!Yo)if(null===i)n.componentDidMount();else{var r=t.elementType===t.type?i.memoizedProps:to(t.type,i.memoizedProps);n.componentDidUpdate(r,i.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var a=t.updateQueue;null!==a&&js(t,a,n);break;case 3:var o=t.updateQueue;if(null!==o){if(i=null,null!==t.child)switch(t.child.tag){case 5:case 1:i=t.child.stateNode}js(t,o,i)}break;case 5:var l=t.stateNode;if(null===i&&4&t.flags){i=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&i.focus();break;case"img":c.src&&(i.src=c.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===t.memoizedState){var d=t.alternate;if(null!==d){var u=d.memoizedState;if(null!==u){var h=u.dehydrated;null!==h&&$t(h)}}}break;default:throw Error(s(163))}Yo||512&t.flags&&rl(t)}catch(e){_c(t,t.return,e)}}if(t===e){Zo=null;break}if(null!==(i=t.sibling)){i.return=t.return,Zo=i;break}Zo=t.return}}function Tl(e){for(;null!==Zo;){var t=Zo;if(t===e){Zo=null;break}var i=t.sibling;if(null!==i){i.return=t.return,Zo=i;break}Zo=t.return}}function El(e){for(;null!==Zo;){var t=Zo;try{switch(t.tag){case 0:case 11:case 15:var i=t.return;try{nl(4,t)}catch(e){_c(t,i,e)}break;case 1:var n=t.stateNode;if("function"==typeof n.componentDidMount){var r=t.return;try{n.componentDidMount()}catch(e){_c(t,r,e)}}var s=t.return;try{rl(t)}catch(e){_c(t,s,e)}break;case 5:var a=t.return;try{rl(t)}catch(e){_c(t,a,e)}}}catch(e){_c(t,t.return,e)}if(t===e){Zo=null;break}var o=t.sibling;if(null!==o){o.return=t.return,Zo=o;break}Zo=t.return}}var bl,_l=Math.ceil,Il=C.ReactCurrentDispatcher,wl=C.ReactCurrentOwner,Al=C.ReactCurrentBatchConfig,Pl=0,Rl=null,Ml=null,Dl=0,kl=0,Ol=_r(0),Nl=0,Ll=null,xl=0,Fl=0,Ul=0,Bl=null,Vl=null,Hl=0,$l=1/0,jl=null,Gl=!1,ql=null,zl=null,Wl=!1,Kl=null,Jl=0,Yl=0,Ql=null,Zl=-1,Xl=0;function ec(){return 6&Pl?Qe():-1!==Zl?Zl:Zl=Qe()}function tc(e){return 1&e.mode?2&Pl&&0!==Dl?Dl&-Dl:null!==ms.transition?(0===Xl&&(Xl=mt()),Xl):0!==(e=yt)?e:e=void 0===(e=window.event)?16:Yt(e.type):1}function ic(e,t,i,n){if(50<Yl)throw Yl=0,Ql=null,Error(s(185));vt(e,i,n),2&Pl&&e===Rl||(e===Rl&&(!(2&Pl)&&(Fl|=i),4===Nl&&oc(e,Dl)),nc(e,n),1===i&&0===Pl&&!(1&t.mode)&&($l=Qe()+500,Br&&$r()))}function nc(e,t){var i=e.callbackNode;!function(e,t){for(var i=e.suspendedLanes,n=e.pingedLanes,r=e.expirationTimes,s=e.pendingLanes;0<s;){var a=31-at(s),o=1<<a,l=r[a];-1===l?o&i&&!(o&n)||(r[a]=gt(o,t)):l<=t&&(e.expiredLanes|=o),s&=~o}}(e,t);var n=ht(e,e===Rl?Dl:0);if(0===n)null!==i&&Ke(i),e.callbackNode=null,e.callbackPriority=0;else if(t=n&-n,e.callbackPriority!==t){if(null!=i&&Ke(i),1===t)0===e.tag?function(e){Br=!0,Hr(e)}(lc.bind(null,e)):Hr(lc.bind(null,e)),ar((function(){!(6&Pl)&&$r()})),i=null;else{switch(Ct(n)){case 1:i=Xe;break;case 4:i=et;break;case 16:default:i=tt;break;case 536870912:i=nt}i=Rc(i,rc.bind(null,e))}e.callbackPriority=t,e.callbackNode=i}}function rc(e,t){if(Zl=-1,Xl=0,6&Pl)throw Error(s(327));var i=e.callbackNode;if(Ec()&&e.callbackNode!==i)return null;var n=ht(e,e===Rl?Dl:0);if(0===n)return null;if(30&n||n&e.expiredLanes||t)t=fc(e,n);else{t=n;var r=Pl;Pl|=2;var a=pc();for(Rl===e&&Dl===t||(jl=null,$l=Qe()+500,hc(e,t));;)try{Sc();break}catch(t){gc(e,t)}ws(),Il.current=a,Pl=r,null!==Ml?t=0:(Rl=null,Dl=0,t=Nl)}if(0!==t){if(2===t&&0!==(r=pt(e))&&(n=r,t=sc(e,r)),1===t)throw i=Ll,hc(e,0),oc(e,n),nc(e,Qe()),i;if(6===t)oc(e,n);else{if(r=e.current.alternate,!(30&n||function(e){for(var t=e;;){if(16384&t.flags){var i=t.updateQueue;if(null!==i&&null!==(i=i.stores))for(var n=0;n<i.length;n++){var r=i[n],s=r.getSnapshot;r=r.value;try{if(!on(s(),r))return!1}catch(e){return!1}}}if(i=t.child,16384&t.subtreeFlags&&null!==i)i.return=t,t=i;else{if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}(r)||(t=fc(e,n),2===t&&(a=pt(e),0!==a&&(n=a,t=sc(e,a))),1!==t)))throw i=Ll,hc(e,0),oc(e,n),nc(e,Qe()),i;switch(e.finishedWork=r,e.finishedLanes=n,t){case 0:case 1:throw Error(s(345));case 2:case 5:Tc(e,Vl,jl);break;case 3:if(oc(e,n),(130023424&n)===n&&10<(t=Hl+500-Qe())){if(0!==ht(e,0))break;if(((r=e.suspendedLanes)&n)!==n){ec(),e.pingedLanes|=e.suspendedLanes&r;break}e.timeoutHandle=nr(Tc.bind(null,e,Vl,jl),t);break}Tc(e,Vl,jl);break;case 4:if(oc(e,n),(4194240&n)===n)break;for(t=e.eventTimes,r=-1;0<n;){var o=31-at(n);a=1<<o,(o=t[o])>r&&(r=o),n&=~a}if(n=r,10<(n=(120>(n=Qe()-n)?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*_l(n/1960))-n)){e.timeoutHandle=nr(Tc.bind(null,e,Vl,jl),n);break}Tc(e,Vl,jl);break;default:throw Error(s(329))}}}return nc(e,Qe()),e.callbackNode===i?rc.bind(null,e):null}function sc(e,t){var i=Bl;return e.current.memoizedState.isDehydrated&&(hc(e,t).flags|=256),2!==(e=fc(e,t))&&(t=Vl,Vl=i,null!==t&&ac(t)),e}function ac(e){null===Vl?Vl=e:Vl.push.apply(Vl,e)}function oc(e,t){for(t&=~Ul,t&=~Fl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var i=31-at(t),n=1<<i;e[i]=-1,t&=~n}}function lc(e){if(6&Pl)throw Error(s(327));Ec();var t=ht(e,0);if(!(1&t))return nc(e,Qe()),null;var i=fc(e,t);if(0!==e.tag&&2===i){var n=pt(e);0!==n&&(t=n,i=sc(e,n))}if(1===i)throw i=Ll,hc(e,0),oc(e,t),nc(e,Qe()),i;if(6===i)throw Error(s(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Tc(e,Vl,jl),nc(e,Qe()),null}function cc(e,t){var i=Pl;Pl|=1;try{return e(t)}finally{0===(Pl=i)&&($l=Qe()+500,Br&&$r())}}function dc(e){null!==Kl&&0===Kl.tag&&!(6&Pl)&&Ec();var t=Pl;Pl|=1;var i=Al.transition,n=yt;try{if(Al.transition=null,yt=1,e)return e()}finally{yt=n,Al.transition=i,!(6&(Pl=t))&&$r()}}function uc(){kl=Ol.current,Ir(Ol)}function hc(e,t){e.finishedWork=null,e.finishedLanes=0;var i=e.timeoutHandle;if(-1!==i&&(e.timeoutHandle=-1,rr(i)),null!==Ml)for(i=Ml.return;null!==i;){var n=i;switch(ts(n),n.tag){case 1:null!=(n=n.type.childContextTypes)&&Or();break;case 3:Ys(),Ir(Rr),Ir(Pr),ia();break;case 5:Zs(n);break;case 4:Ys();break;case 13:case 19:Ir(Xs);break;case 10:As(n.type._context);break;case 22:case 23:uc()}i=i.return}if(Rl=e,Ml=e=Oc(e.current,null),Dl=kl=t,Nl=0,Ll=null,Ul=Fl=xl=0,Vl=Bl=null,null!==Ds){for(t=0;t<Ds.length;t++)if(null!==(n=(i=Ds[t]).interleaved)){i.interleaved=null;var r=n.next,s=i.pending;if(null!==s){var a=s.next;s.next=r,n.next=a}i.pending=n}Ds=null}return e}function gc(e,t){for(;;){var i=Ml;try{if(ws(),na.current=Qa,ca){for(var n=aa.memoizedState;null!==n;){var r=n.queue;null!==r&&(r.pending=null),n=n.next}ca=!1}if(sa=0,la=oa=aa=null,da=!1,ua=0,wl.current=null,null===i||null===i.return){Nl=1,Ll=t,Ml=null;break}e:{var a=e,o=i.return,l=i,c=t;if(t=Dl,l.flags|=32768,null!==c&&"object"==typeof c&&"function"==typeof c.then){var d=c,u=l,h=u.tag;if(!(1&u.mode||0!==h&&11!==h&&15!==h)){var g=u.alternate;g?(u.updateQueue=g.updateQueue,u.memoizedState=g.memoizedState,u.lanes=g.lanes):(u.updateQueue=null,u.memoizedState=null)}var p=fo(o);if(null!==p){p.flags&=-257,vo(p,o,l,0,t),1&p.mode&&mo(a,d,t),c=d;var m=(t=p).updateQueue;if(null===m){var f=new Set;f.add(c),t.updateQueue=f}else m.add(c);break e}if(!(1&t)){mo(a,d,t),mc();break e}c=Error(s(426))}else if(rs&&1&l.mode){var v=fo(o);if(null!==v){!(65536&v.flags)&&(v.flags|=256),vo(v,o,l,0,t),ps(lo(c,l));break e}}a=c=lo(c,l),4!==Nl&&(Nl=2),null===Bl?Bl=[a]:Bl.push(a),a=o;do{switch(a.tag){case 3:a.flags|=65536,t&=-t,a.lanes|=t,Hs(a,go(0,c,t));break e;case 1:l=c;var S=a.type,y=a.stateNode;if(!(128&a.flags||"function"!=typeof S.getDerivedStateFromError&&(null===y||"function"!=typeof y.componentDidCatch||null!==zl&&zl.has(y)))){a.flags|=65536,t&=-t,a.lanes|=t,Hs(a,po(a,l,t));break e}}a=a.return}while(null!==a)}Cc(i)}catch(e){t=e,Ml===i&&null!==i&&(Ml=i=i.return);continue}break}}function pc(){var e=Il.current;return Il.current=Qa,null===e?Qa:e}function mc(){0!==Nl&&3!==Nl&&2!==Nl||(Nl=4),null===Rl||!(268435455&xl)&&!(268435455&Fl)||oc(Rl,Dl)}function fc(e,t){var i=Pl;Pl|=2;var n=pc();for(Rl===e&&Dl===t||(jl=null,hc(e,t));;)try{vc();break}catch(t){gc(e,t)}if(ws(),Pl=i,Il.current=n,null!==Ml)throw Error(s(261));return Rl=null,Dl=0,Nl}function vc(){for(;null!==Ml;)yc(Ml)}function Sc(){for(;null!==Ml&&!Je();)yc(Ml)}function yc(e){var t=bl(e.alternate,e,kl);e.memoizedProps=e.pendingProps,null===t?Cc(e):Ml=t,wl.current=null}function Cc(e){var t=e;do{var i=t.alternate;if(e=t.return,32768&t.flags){if(null!==(i=Ko(i,t)))return i.flags&=32767,void(Ml=i);if(null===e)return Nl=6,void(Ml=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}else if(null!==(i=Wo(i,t,kl)))return void(Ml=i);if(null!==(t=t.sibling))return void(Ml=t);Ml=t=e}while(null!==t);0===Nl&&(Nl=5)}function Tc(e,t,i){var n=yt,r=Al.transition;try{Al.transition=null,yt=1,function(e,t,i,n){do{Ec()}while(null!==Kl);if(6&Pl)throw Error(s(327));i=e.finishedWork;var r=e.finishedLanes;if(null===i)return null;if(e.finishedWork=null,e.finishedLanes=0,i===e.current)throw Error(s(177));e.callbackNode=null,e.callbackPriority=0;var a=i.lanes|i.childLanes;if(function(e,t){var i=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0<i;){var r=31-at(i),s=1<<r;t[r]=0,n[r]=-1,e[r]=-1,i&=~s}}(e,a),e===Rl&&(Ml=Rl=null,Dl=0),!(2064&i.subtreeFlags)&&!(2064&i.flags)||Wl||(Wl=!0,Rc(tt,(function(){return Ec(),null}))),a=!!(15990&i.flags),15990&i.subtreeFlags||a){a=Al.transition,Al.transition=null;var o=yt;yt=1;var l=Pl;Pl|=4,wl.current=null,function(e,t){if(er=Gt,gn(e=hn())){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{var n=(i=(i=e.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(n&&0!==n.rangeCount){i=n.anchorNode;var r=n.anchorOffset,a=n.focusNode;n=n.focusOffset;try{i.nodeType,a.nodeType}catch(e){i=null;break e}var o=0,l=-1,c=-1,d=0,u=0,h=e,g=null;t:for(;;){for(var p;h!==i||0!==r&&3!==h.nodeType||(l=o+r),h!==a||0!==n&&3!==h.nodeType||(c=o+n),3===h.nodeType&&(o+=h.nodeValue.length),null!==(p=h.firstChild);)g=h,h=p;for(;;){if(h===e)break t;if(g===i&&++d===r&&(l=o),g===a&&++u===n&&(c=o),null!==(p=h.nextSibling))break;g=(h=g).parentNode}h=p}i=-1===l||-1===c?null:{start:l,end:c}}else i=null}i=i||{start:0,end:0}}else i=null;for(tr={focusedElem:e,selectionRange:i},Gt=!1,Zo=t;null!==Zo;)if(e=(t=Zo).child,1028&t.subtreeFlags&&null!==e)e.return=t,Zo=e;else for(;null!==Zo;){t=Zo;try{var m=t.alternate;if(1024&t.flags)switch(t.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==m){var f=m.memoizedProps,v=m.memoizedState,S=t.stateNode,y=S.getSnapshotBeforeUpdate(t.elementType===t.type?f:to(t.type,f),v);S.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var C=t.stateNode.containerInfo;1===C.nodeType?C.textContent="":9===C.nodeType&&C.documentElement&&C.removeChild(C.documentElement);break;default:throw Error(s(163))}}catch(e){_c(t,t.return,e)}if(null!==(e=t.sibling)){e.return=t.return,Zo=e;break}Zo=t.return}m=tl,tl=!1}(e,i),fl(i,e),pn(tr),Gt=!!er,tr=er=null,e.current=i,Sl(i,e,r),Ye(),Pl=l,yt=o,Al.transition=a}else e.current=i;if(Wl&&(Wl=!1,Kl=e,Jl=r),0===(a=e.pendingLanes)&&(zl=null),function(e){if(st&&"function"==typeof st.onCommitFiberRoot)try{st.onCommitFiberRoot(rt,e,void 0,!(128&~e.current.flags))}catch(e){}}(i.stateNode),nc(e,Qe()),null!==t)for(n=e.onRecoverableError,i=0;i<t.length;i++)n((r=t[i]).value,{componentStack:r.stack,digest:r.digest});if(Gl)throw Gl=!1,e=ql,ql=null,e;!!(1&Jl)&&0!==e.tag&&Ec(),1&(a=e.pendingLanes)?e===Ql?Yl++:(Yl=0,Ql=e):Yl=0,$r()}(e,t,i,n)}finally{Al.transition=r,yt=n}return null}function Ec(){if(null!==Kl){var e=Ct(Jl),t=Al.transition,i=yt;try{if(Al.transition=null,yt=16>e?16:e,null===Kl)var n=!1;else{if(e=Kl,Kl=null,Jl=0,6&Pl)throw Error(s(331));var r=Pl;for(Pl|=4,Zo=e.current;null!==Zo;){var a=Zo,o=a.child;if(16&Zo.flags){var l=a.deletions;if(null!==l){for(var c=0;c<l.length;c++){var d=l[c];for(Zo=d;null!==Zo;){var u=Zo;switch(u.tag){case 0:case 11:case 15:il(8,u,a)}var h=u.child;if(null!==h)h.return=u,Zo=h;else for(;null!==Zo;){var g=(u=Zo).sibling,p=u.return;if(sl(u),u===d){Zo=null;break}if(null!==g){g.return=p,Zo=g;break}Zo=p}}}var m=a.alternate;if(null!==m){var f=m.child;if(null!==f){m.child=null;do{var v=f.sibling;f.sibling=null,f=v}while(null!==f)}}Zo=a}}if(2064&a.subtreeFlags&&null!==o)o.return=a,Zo=o;else e:for(;null!==Zo;){if(2048&(a=Zo).flags)switch(a.tag){case 0:case 11:case 15:il(9,a,a.return)}var S=a.sibling;if(null!==S){S.return=a.return,Zo=S;break e}Zo=a.return}}var y=e.current;for(Zo=y;null!==Zo;){var C=(o=Zo).child;if(2064&o.subtreeFlags&&null!==C)C.return=o,Zo=C;else e:for(o=y;null!==Zo;){if(2048&(l=Zo).flags)try{switch(l.tag){case 0:case 11:case 15:nl(9,l)}}catch(e){_c(l,l.return,e)}if(l===o){Zo=null;break e}var T=l.sibling;if(null!==T){T.return=l.return,Zo=T;break e}Zo=l.return}}if(Pl=r,$r(),st&&"function"==typeof st.onPostCommitFiberRoot)try{st.onPostCommitFiberRoot(rt,e)}catch(e){}n=!0}return n}finally{yt=i,Al.transition=t}}return!1}function bc(e,t,i){e=Bs(e,t=go(0,t=lo(i,t),1),1),t=ec(),null!==e&&(vt(e,1,t),nc(e,t))}function _c(e,t,i){if(3===e.tag)bc(e,e,i);else for(;null!==t;){if(3===t.tag){bc(t,e,i);break}if(1===t.tag){var n=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof n.componentDidCatch&&(null===zl||!zl.has(n))){t=Bs(t,e=po(t,e=lo(i,e),1),1),e=ec(),null!==t&&(vt(t,1,e),nc(t,e));break}}t=t.return}}function Ic(e,t,i){var n=e.pingCache;null!==n&&n.delete(t),t=ec(),e.pingedLanes|=e.suspendedLanes&i,Rl===e&&(Dl&i)===i&&(4===Nl||3===Nl&&(130023424&Dl)===Dl&&500>Qe()-Hl?hc(e,0):Ul|=i),nc(e,t)}function wc(e,t){0===t&&(1&e.mode?(t=dt,!(130023424&(dt<<=1))&&(dt=4194304)):t=1);var i=ec();null!==(e=Ns(e,t))&&(vt(e,t,i),nc(e,i))}function Ac(e){var t=e.memoizedState,i=0;null!==t&&(i=t.retryLane),wc(e,i)}function Pc(e,t){var i=0;switch(e.tag){case 13:var n=e.stateNode,r=e.memoizedState;null!==r&&(i=r.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(s(314))}null!==n&&n.delete(t),wc(e,i)}function Rc(e,t){return We(e,t)}function Mc(e,t,i,n){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dc(e,t,i,n){return new Mc(e,t,i,n)}function kc(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Oc(e,t){var i=e.alternate;return null===i?((i=Dc(e.tag,t,e.key,e.mode)).elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=14680064&e.flags,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i}function Nc(e,t,i,n,r,a){var o=2;if(n=e,"function"==typeof e)kc(e)&&(o=1);else if("string"==typeof e)o=5;else e:switch(e){case b:return Lc(i.children,r,a,t);case _:o=8,r|=8;break;case I:return(e=Dc(12,i,t,2|r)).elementType=I,e.lanes=a,e;case R:return(e=Dc(13,i,t,r)).elementType=R,e.lanes=a,e;case M:return(e=Dc(19,i,t,r)).elementType=M,e.lanes=a,e;case O:return xc(i,r,a,t);default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case w:o=10;break e;case A:o=9;break e;case P:o=11;break e;case D:o=14;break e;case k:o=16,n=null;break e}throw Error(s(130,null==e?e:typeof e,""))}return(t=Dc(o,i,t,r)).elementType=e,t.type=n,t.lanes=a,t}function Lc(e,t,i,n){return(e=Dc(7,e,n,t)).lanes=i,e}function xc(e,t,i,n){return(e=Dc(22,e,n,t)).elementType=O,e.lanes=i,e.stateNode={isHidden:!1},e}function Fc(e,t,i){return(e=Dc(6,e,null,t)).lanes=i,e}function Uc(e,t,i){return(t=Dc(4,null!==e.children?e.children:[],e.key,t)).lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Bc(e,t,i,n,r){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ft(0),this.expirationTimes=ft(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ft(0),this.identifierPrefix=n,this.onRecoverableError=r,this.mutableSourceEagerHydrationData=null}function Vc(e,t,i,n,r,s,a,o,l){return e=new Bc(e,t,i,o,l),1===t?(t=1,!0===s&&(t|=8)):t=0,s=Dc(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:n,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},xs(s),e}function Hc(e){if(!e)return Ar;e:{if($e(e=e._reactInternals)!==e||1!==e.tag)throw Error(s(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(kr(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(s(171))}if(1===e.tag){var i=e.type;if(kr(i))return Lr(e,i,t)}return t}function $c(e,t,i,n,r,s,a,o,l){return(e=Vc(i,n,!0,e,0,s,0,o,l)).context=Hc(null),i=e.current,(s=Us(n=ec(),r=tc(i))).callback=null!=t?t:null,Bs(i,s,r),e.current.lanes=r,vt(e,r,n),nc(e,n),e}function jc(e,t,i,n){var r=t.current,s=ec(),a=tc(r);return i=Hc(i),null===t.context?t.context=i:t.pendingContext=i,(t=Us(s,a)).payload={element:e},null!==(n=void 0===n?null:n)&&(t.callback=n),null!==(e=Bs(r,t,a))&&(ic(e,r,a,s),Vs(e,r,a)),a}function Gc(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function qc(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var i=e.retryLane;e.retryLane=0!==i&&i<t?i:t}}function zc(e,t){qc(e,t),(e=e.alternate)&&qc(e,t)}bl=function(e,t,i){if(null!==e)if(e.memoizedProps!==t.pendingProps||Rr.current)yo=!0;else{if(!(e.lanes&i||128&t.flags))return yo=!1,function(e,t,i){switch(t.tag){case 3:Ro(t),gs();break;case 5:Qs(t);break;case 1:kr(t.type)&&xr(t);break;case 4:Js(t,t.stateNode.containerInfo);break;case 10:var n=t.type._context,r=t.memoizedProps.value;wr(Es,n._currentValue),n._currentValue=r;break;case 13:if(null!==(n=t.memoizedState))return null!==n.dehydrated?(wr(Xs,1&Xs.current),t.flags|=128,null):i&t.child.childLanes?Fo(e,t,i):(wr(Xs,1&Xs.current),null!==(e=Go(e,t,i))?e.sibling:null);wr(Xs,1&Xs.current);break;case 19:if(n=!!(i&t.childLanes),128&e.flags){if(n)return $o(e,t,i);t.flags|=128}if(null!==(r=t.memoizedState)&&(r.rendering=null,r.tail=null,r.lastEffect=null),wr(Xs,Xs.current),n)break;return null;case 22:case 23:return t.lanes=0,_o(e,t,i)}return Go(e,t,i)}(e,t,i);yo=!!(131072&e.flags)}else yo=!1,rs&&1048576&t.flags&&Xr(t,zr,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;jo(e,t),e=t.pendingProps;var r=Dr(t,Pr.current);Rs(t,i),r=ma(null,t,n,e,r,i);var a=fa();return t.flags|=1,"object"==typeof r&&null!==r&&"function"==typeof r.render&&void 0===r.$$typeof?(t.tag=1,t.memoizedState=null,t.updateQueue=null,kr(n)?(a=!0,xr(t)):a=!1,t.memoizedState=null!==r.state&&void 0!==r.state?r.state:null,xs(t),r.updater=no,t.stateNode=r,r._reactInternals=t,oo(t,n,e,i),t=Po(null,t,n,!0,a,i)):(t.tag=0,rs&&a&&es(t),Co(null,t,r,i),t=t.child),t;case 16:n=t.elementType;e:{switch(jo(e,t),e=t.pendingProps,n=(r=n._init)(n._payload),t.type=n,r=t.tag=function(e){if("function"==typeof e)return kc(e)?1:0;if(null!=e){if((e=e.$$typeof)===P)return 11;if(e===D)return 14}return 2}(n),e=to(n,e),r){case 0:t=wo(null,t,n,e,i);break e;case 1:t=Ao(null,t,n,e,i);break e;case 11:t=To(null,t,n,e,i);break e;case 14:t=Eo(null,t,n,to(n.type,e),i);break e}throw Error(s(306,n,""))}return t;case 0:return n=t.type,r=t.pendingProps,wo(e,t,n,r=t.elementType===n?r:to(n,r),i);case 1:return n=t.type,r=t.pendingProps,Ao(e,t,n,r=t.elementType===n?r:to(n,r),i);case 3:e:{if(Ro(t),null===e)throw Error(s(387));n=t.pendingProps,r=(a=t.memoizedState).element,Fs(e,t),$s(t,n,null,i);var o=t.memoizedState;if(n=o.element,a.isDehydrated){if(a={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=a,t.memoizedState=a,256&t.flags){t=Mo(e,t,n,i,r=lo(Error(s(423)),t));break e}if(n!==r){t=Mo(e,t,n,i,r=lo(Error(s(424)),t));break e}for(ns=cr(t.stateNode.containerInfo.firstChild),is=t,rs=!0,ss=null,i=Ts(t,null,n,i),t.child=i;i;)i.flags=-3&i.flags|4096,i=i.sibling}else{if(gs(),n===r){t=Go(e,t,i);break e}Co(e,t,n,i)}t=t.child}return t;case 5:return Qs(t),null===e&&cs(t),n=t.type,r=t.pendingProps,a=null!==e?e.memoizedProps:null,o=r.children,ir(n,r)?o=null:null!==a&&ir(n,a)&&(t.flags|=32),Io(e,t),Co(e,t,o,i),t.child;case 6:return null===e&&cs(t),null;case 13:return Fo(e,t,i);case 4:return Js(t,t.stateNode.containerInfo),n=t.pendingProps,null===e?t.child=Cs(t,null,n,i):Co(e,t,n,i),t.child;case 11:return n=t.type,r=t.pendingProps,To(e,t,n,r=t.elementType===n?r:to(n,r),i);case 7:return Co(e,t,t.pendingProps,i),t.child;case 8:case 12:return Co(e,t,t.pendingProps.children,i),t.child;case 10:e:{if(n=t.type._context,r=t.pendingProps,a=t.memoizedProps,o=r.value,wr(Es,n._currentValue),n._currentValue=o,null!==a)if(on(a.value,o)){if(a.children===r.children&&!Rr.current){t=Go(e,t,i);break e}}else for(null!==(a=t.child)&&(a.return=t);null!==a;){var l=a.dependencies;if(null!==l){o=a.child;for(var c=l.firstContext;null!==c;){if(c.context===n){if(1===a.tag){(c=Us(-1,i&-i)).tag=2;var d=a.updateQueue;if(null!==d){var u=(d=d.shared).pending;null===u?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}a.lanes|=i,null!==(c=a.alternate)&&(c.lanes|=i),Ps(a.return,i,t),l.lanes|=i;break}c=c.next}}else if(10===a.tag)o=a.type===t.type?null:a.child;else if(18===a.tag){if(null===(o=a.return))throw Error(s(341));o.lanes|=i,null!==(l=o.alternate)&&(l.lanes|=i),Ps(o,i,t),o=a.sibling}else o=a.child;if(null!==o)o.return=a;else for(o=a;null!==o;){if(o===t){o=null;break}if(null!==(a=o.sibling)){a.return=o.return,o=a;break}o=o.return}a=o}Co(e,t,r.children,i),t=t.child}return t;case 9:return r=t.type,n=t.pendingProps.children,Rs(t,i),n=n(r=Ms(r)),t.flags|=1,Co(e,t,n,i),t.child;case 14:return r=to(n=t.type,t.pendingProps),Eo(e,t,n,r=to(n.type,r),i);case 15:return bo(e,t,t.type,t.pendingProps,i);case 17:return n=t.type,r=t.pendingProps,r=t.elementType===n?r:to(n,r),jo(e,t),t.tag=1,kr(n)?(e=!0,xr(t)):e=!1,Rs(t,i),so(t,n,r),oo(t,n,r,i),Po(null,t,n,!0,e,i);case 19:return $o(e,t,i);case 22:return _o(e,t,i)}throw Error(s(156,t.tag))};var Wc="function"==typeof reportError?reportError:function(e){console.error(e)};function Kc(e){this._internalRoot=e}function Jc(e){this._internalRoot=e}function Yc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Qc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Zc(){}function Xc(e,t,i,n,r){var s=i._reactRootContainer;if(s){var a=s;if("function"==typeof r){var o=r;r=function(){var e=Gc(a);o.call(e)}}jc(t,a,e,r)}else a=function(e,t,i,n,r){if(r){if("function"==typeof n){var s=n;n=function(){var e=Gc(a);s.call(e)}}var a=$c(t,n,e,0,null,!1,0,"",Zc);return e._reactRootContainer=a,e[pr]=a.current,$n(8===e.nodeType?e.parentNode:e),dc(),a}for(;r=e.lastChild;)e.removeChild(r);if("function"==typeof n){var o=n;n=function(){var e=Gc(l);o.call(e)}}var l=Vc(e,0,!1,null,0,!1,0,"",Zc);return e._reactRootContainer=l,e[pr]=l.current,$n(8===e.nodeType?e.parentNode:e),dc((function(){jc(t,l,i,n)})),l}(i,t,e,r,n);return Gc(a)}Jc.prototype.render=Kc.prototype.render=function(e){var t=this._internalRoot;if(null===t)throw Error(s(409));jc(e,t,null,null)},Jc.prototype.unmount=Kc.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var t=e.containerInfo;dc((function(){jc(null,e,null,null)})),t[pr]=null}},Jc.prototype.unstable_scheduleHydration=function(e){if(e){var t=_t();e={blockedOn:null,target:e,priority:t};for(var i=0;i<Ot.length&&0!==t&&t<Ot[i].priority;i++);Ot.splice(i,0,e),0===i&&Ft(e)}},Tt=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var i=ut(t.pendingLanes);0!==i&&(St(t,1|i),nc(t,Qe()),!(6&Pl)&&($l=Qe()+500,$r()))}break;case 13:dc((function(){var t=Ns(e,1);if(null!==t){var i=ec();ic(t,e,1,i)}})),zc(e,1)}},Et=function(e){if(13===e.tag){var t=Ns(e,134217728);null!==t&&ic(t,e,134217728,ec()),zc(e,134217728)}},bt=function(e){if(13===e.tag){var t=tc(e),i=Ns(e,t);null!==i&&ic(i,e,t,ec()),zc(e,t)}},_t=function(){return yt},It=function(e,t){var i=yt;try{return yt=e,t()}finally{yt=i}},Ee=function(e,t,i){switch(t){case"input":if(Z(e,i),t=i.name,"radio"===i.type&&null!=t){for(i=e;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<i.length;t++){var n=i[t];if(n!==e&&n.form===e.form){var r=Tr(n);if(!r)throw Error(s(90));W(n),Z(n,r)}}}break;case"textarea":se(e,i);break;case"select":null!=(t=i.value)&&ie(e,!!i.multiple,t,!1)}},Pe=cc,Re=dc;var ed={usingClientEntryPoint:!1,Events:[yr,Cr,Tr,we,Ae,cc]},td={findFiberByHostInstance:Sr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},id={bundleType:td.bundleType,version:td.version,rendererPackageName:td.rendererPackageName,rendererConfig:td.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:C.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=qe(e))?null:e.stateNode},findFiberByHostInstance:td.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var nd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!nd.isDisabled&&nd.supportsFiber)try{rt=nd.inject(id),st=nd}catch(de){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ed,t.createPortal=function(e,t){var i=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Yc(t))throw Error(s(200));return function(e,t,i){var n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:E,key:null==n?null:""+n,children:e,containerInfo:t,implementation:i}}(e,t,null,i)},t.createRoot=function(e,t){if(!Yc(e))throw Error(s(299));var i=!1,n="",r=Wc;return null!=t&&(!0===t.unstable_strictMode&&(i=!0),void 0!==t.identifierPrefix&&(n=t.identifierPrefix),void 0!==t.onRecoverableError&&(r=t.onRecoverableError)),t=Vc(e,1,!1,null,0,i,0,n,r),e[pr]=t.current,$n(8===e.nodeType?e.parentNode:e),new Kc(t)},t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"==typeof e.render)throw Error(s(188));throw e=Object.keys(e).join(","),Error(s(268,e))}return null===(e=qe(t))?null:e.stateNode},t.flushSync=function(e){return dc(e)},t.hydrate=function(e,t,i){if(!Qc(t))throw Error(s(200));return Xc(null,e,t,!0,i)},t.hydrateRoot=function(e,t,i){if(!Yc(e))throw Error(s(405));var n=null!=i&&i.hydratedSources||null,r=!1,a="",o=Wc;if(null!=i&&(!0===i.unstable_strictMode&&(r=!0),void 0!==i.identifierPrefix&&(a=i.identifierPrefix),void 0!==i.onRecoverableError&&(o=i.onRecoverableError)),t=$c(t,null,e,1,null!=i?i:null,r,0,a,o),e[pr]=t.current,$n(e),n)for(e=0;e<n.length;e++)r=(r=(i=n[e])._getVersion)(i._source),null==t.mutableSourceEagerHydrationData?t.mutableSourceEagerHydrationData=[i,r]:t.mutableSourceEagerHydrationData.push(i,r);return new Jc(t)},t.render=function(e,t,i){if(!Qc(t))throw Error(s(200));return Xc(null,e,t,!1,i)},t.unmountComponentAtNode=function(e){if(!Qc(e))throw Error(s(40));return!!e._reactRootContainer&&(dc((function(){Xc(null,null,e,!1,(function(){e._reactRootContainer=null,e[pr]=null}))})),!0)},t.unstable_batchedUpdates=cc,t.unstable_renderSubtreeIntoContainer=function(e,t,i,n){if(!Qc(i))throw Error(s(200));if(null==e||void 0===e._reactInternals)throw Error(s(38));return Xc(e,t,i,!1,n)},t.version="18.3.1-next-f1338f8080-20240426"},7004:(e,t,i)=>{"use strict";var n=i(5491);t.H=n.createRoot,n.hydrateRoot},5491:(e,t,i)=>{"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=i(7669)},6517:(e,t)=>{"use strict";var i=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),g=Symbol.iterator,p={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,f={};function v(e,t,i){this.props=e,this.context=t,this.refs=f,this.updater=i||p}function S(){}function y(e,t,i){this.props=e,this.context=t,this.refs=f,this.updater=i||p}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},S.prototype=v.prototype;var C=y.prototype=new S;C.constructor=y,m(C,v.prototype),C.isPureReactComponent=!0;var T=Array.isArray,E=Object.prototype.hasOwnProperty,b={current:null},_={key:!0,ref:!0,__self:!0,__source:!0};function I(e,t,n){var r,s={},a=null,o=null;if(null!=t)for(r in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(a=""+t.key),t)E.call(t,r)&&!_.hasOwnProperty(r)&&(s[r]=t[r]);var l=arguments.length-2;if(1===l)s.children=n;else if(1<l){for(var c=Array(l),d=0;d<l;d++)c[d]=arguments[d+2];s.children=c}if(e&&e.defaultProps)for(r in l=e.defaultProps)void 0===s[r]&&(s[r]=l[r]);return{$$typeof:i,type:e,key:a,ref:o,props:s,_owner:b.current}}function w(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}var A=/\/+/g;function P(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function R(e,t,r,s,a){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var l=!1;if(null===e)l=!0;else switch(o){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case i:case n:l=!0}}if(l)return a=a(l=e),e=""===s?"."+P(l,0):s,T(a)?(r="",null!=e&&(r=e.replace(A,"$&/")+"/"),R(a,t,r,"",(function(e){return e}))):null!=a&&(w(a)&&(a=function(e,t){return{$$typeof:i,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(a,r+(!a.key||l&&l.key===a.key?"":(""+a.key).replace(A,"$&/")+"/")+e)),t.push(a)),1;if(l=0,s=""===s?".":s+":",T(e))for(var c=0;c<e.length;c++){var d=s+P(o=e[c],c);l+=R(o,t,r,d,a)}else if(d=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=g&&e[g]||e["@@iterator"])?e:null}(e),"function"==typeof d)for(e=d.call(e),c=0;!(o=e.next()).done;)l+=R(o=o.value,t,r,d=s+P(o,c++),a);else if("object"===o)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function M(e,t,i){if(null==e)return e;var n=[],r=0;return R(e,n,"","",(function(e){return t.call(i,e,r++)})),n}function D(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var k={current:null},O={transition:null},N={ReactCurrentDispatcher:k,ReactCurrentBatchConfig:O,ReactCurrentOwner:b};function L(){throw Error("act(...) is not supported in production builds of React.")}t.Children={map:M,forEach:function(e,t,i){M(e,(function(){t.apply(this,arguments)}),i)},count:function(e){var t=0;return M(e,(function(){t++})),t},toArray:function(e){return M(e,(function(e){return e}))||[]},only:function(e){if(!w(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},t.Component=v,t.Fragment=r,t.Profiler=a,t.PureComponent=y,t.StrictMode=s,t.Suspense=d,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=N,t.act=L,t.cloneElement=function(e,t,n){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=m({},e.props),s=e.key,a=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(a=t.ref,o=b.current),void 0!==t.key&&(s=""+t.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(c in t)E.call(t,c)&&!_.hasOwnProperty(c)&&(r[c]=void 0===t[c]&&void 0!==l?l[c]:t[c])}var c=arguments.length-2;if(1===c)r.children=n;else if(1<c){l=Array(c);for(var d=0;d<c;d++)l[d]=arguments[d+2];r.children=l}return{$$typeof:i,type:e.type,key:s,ref:a,props:r,_owner:o}},t.createContext=function(e){return(e={$$typeof:l,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},t.createElement=I,t.createFactory=function(e){var t=I.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:c,render:e}},t.isValidElement=w,t.lazy=function(e){return{$$typeof:h,_payload:{_status:-1,_result:e},_init:D}},t.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},t.startTransition=function(e){var t=O.transition;O.transition={};try{e()}finally{O.transition=t}},t.unstable_act=L,t.useCallback=function(e,t){return k.current.useCallback(e,t)},t.useContext=function(e){return k.current.useContext(e)},t.useDebugValue=function(){},t.useDeferredValue=function(e){return k.current.useDeferredValue(e)},t.useEffect=function(e,t){return k.current.useEffect(e,t)},t.useId=function(){return k.current.useId()},t.useImperativeHandle=function(e,t,i){return k.current.useImperativeHandle(e,t,i)},t.useInsertionEffect=function(e,t){return k.current.useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return k.current.useLayoutEffect(e,t)},t.useMemo=function(e,t){return k.current.useMemo(e,t)},t.useReducer=function(e,t,i){return k.current.useReducer(e,t,i)},t.useRef=function(e){return k.current.useRef(e)},t.useState=function(e){return k.current.useState(e)},t.useSyncExternalStore=function(e,t,i){return k.current.useSyncExternalStore(e,t,i)},t.useTransition=function(){return k.current.useTransition()},t.version="18.3.1"},538:(e,t,i)=>{"use strict";e.exports=i(6517)},4577:(e,t)=>{"use strict";function i(e,t){var i=e.length;e.push(t);e:for(;0<i;){var n=i-1>>>1,r=e[n];if(!(0<s(r,t)))break e;e[n]=t,e[i]=r,i=n}}function n(e){return 0===e.length?null:e[0]}function r(e){if(0===e.length)return null;var t=e[0],i=e.pop();if(i!==t){e[0]=i;e:for(var n=0,r=e.length,a=r>>>1;n<a;){var o=2*(n+1)-1,l=e[o],c=o+1,d=e[c];if(0>s(l,i))c<r&&0>s(d,l)?(e[n]=d,e[c]=i,n=c):(e[n]=l,e[o]=i,n=o);else{if(!(c<r&&0>s(d,i)))break e;e[n]=d,e[c]=i,n=c}}}return t}function s(e,t){var i=e.sortIndex-t.sortIndex;return 0!==i?i:e.id-t.id}if("object"==typeof performance&&"function"==typeof performance.now){var a=performance;t.unstable_now=function(){return a.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],d=[],u=1,h=null,g=3,p=!1,m=!1,f=!1,v="function"==typeof setTimeout?setTimeout:null,S="function"==typeof clearTimeout?clearTimeout:null,y="undefined"!=typeof setImmediate?setImmediate:null;function C(e){for(var t=n(d);null!==t;){if(null===t.callback)r(d);else{if(!(t.startTime<=e))break;r(d),t.sortIndex=t.expirationTime,i(c,t)}t=n(d)}}function T(e){if(f=!1,C(e),!m)if(null!==n(c))m=!0,O(E);else{var t=n(d);null!==t&&N(T,t.startTime-e)}}function E(e,i){m=!1,f&&(f=!1,S(w),w=-1),p=!0;var s=g;try{for(C(i),h=n(c);null!==h&&(!(h.expirationTime>i)||e&&!R());){var a=h.callback;if("function"==typeof a){h.callback=null,g=h.priorityLevel;var o=a(h.expirationTime<=i);i=t.unstable_now(),"function"==typeof o?h.callback=o:h===n(c)&&r(c),C(i)}else r(c);h=n(c)}if(null!==h)var l=!0;else{var u=n(d);null!==u&&N(T,u.startTime-i),l=!1}return l}finally{h=null,g=s,p=!1}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var b,_=!1,I=null,w=-1,A=5,P=-1;function R(){return!(t.unstable_now()-P<A)}function M(){if(null!==I){var e=t.unstable_now();P=e;var i=!0;try{i=I(!0,e)}finally{i?b():(_=!1,I=null)}}else _=!1}if("function"==typeof y)b=function(){y(M)};else if("undefined"!=typeof MessageChannel){var D=new MessageChannel,k=D.port2;D.port1.onmessage=M,b=function(){k.postMessage(null)}}else b=function(){v(M,0)};function O(e){I=e,_||(_=!0,b())}function N(e,i){w=v((function(){e(t.unstable_now())}),i)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){m||p||(m=!0,O(E))},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):A=0<e?Math.floor(1e3/e):5},t.unstable_getCurrentPriorityLevel=function(){return g},t.unstable_getFirstCallbackNode=function(){return n(c)},t.unstable_next=function(e){switch(g){case 1:case 2:case 3:var t=3;break;default:t=g}var i=g;g=t;try{return e()}finally{g=i}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var i=g;g=e;try{return t()}finally{g=i}},t.unstable_scheduleCallback=function(e,r,s){var a=t.unstable_now();switch(s="object"==typeof s&&null!==s&&"number"==typeof(s=s.delay)&&0<s?a+s:a,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:u++,callback:r,priorityLevel:e,startTime:s,expirationTime:o=s+o,sortIndex:-1},s>a?(e.sortIndex=s,i(d,e),null===n(c)&&e===n(d)&&(f?(S(w),w=-1):f=!0,N(T,s-a))):(e.sortIndex=o,i(c,e),m||p||(m=!0,O(E))),e},t.unstable_shouldYield=R,t.unstable_wrapCallback=function(e){var t=g;return function(){var i=g;g=t;try{return e.apply(this,arguments)}finally{g=i}}}},2300:(e,t,i)=>{"use strict";e.exports=i(4577)},2900:e=>{e.exports=function(){var e=document.getSelection();if(!e.rangeCount)return function(){};for(var t=document.activeElement,i=[],n=0;n<e.rangeCount;n++)i.push(e.getRangeAt(n));switch(t.tagName.toUpperCase()){case"INPUT":case"TEXTAREA":t.blur();break;default:t=null}return e.removeAllRanges(),function(){"Caret"===e.type&&e.removeAllRanges(),e.rangeCount||i.forEach((function(t){e.addRange(t)})),t&&t.focus()}}},1408:e=>{"use strict";e.exports="1.26.0-beta.1"}},n={};function r(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={exports:{}};return i[e](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(i,n){if(1&n&&(i=this(i)),8&n)return i;if("object"==typeof i&&i){if(4&n&&i.__esModule)return i;if(16&n&&"function"==typeof i.then)return i}var s=Object.create(null);r.r(s);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&i;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>a[e]=()=>i[e]));return a.default=()=>i,r.d(s,a),s},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";r.r(s),r.d(s,{loadCallComposite:()=>Goe});var e=r(538),t=r.t(e,2),i=r(7004);class n extends Error{}n.prototype.name="InvalidTokenError";const a=e=>{const{exp:t}=function(e,t){if("string"!=typeof e)throw new n("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,r=e.split(".")[i];if("string"!=typeof r)throw new n(`Invalid token specified: missing part #${i+1}`);let s;try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return atob(t)}}(r)}catch(e){throw new n(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new n(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e);return{token:e,expiresOnTimestamp:1e3*t}},o={token:"",expiresOnTimestamp:-10};class l{constructor(e){this.expiringSoonIntervalInMs=6e5,this.refreshAfterLifetimePercentage=.5,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.disposed=!1;const{tokenRefresher:t,token:i,refreshProactively:n}=e;this.refresh=t,this.currentToken=i?a(i):o,this.refreshProactively=null!=n&&n,this.refreshProactively&&this.scheduleRefresh()}async getToken(e){if(!this.isTokenExpiringSoon(this.currentToken))return this.currentToken;if(!this.isTokenValid(this.currentToken)){const t=this.updateTokenAndReschedule(null==e?void 0:e.abortSignal);await t}return this.currentToken}dispose(){this.disposed=!0,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.currentToken=o,this.activeTimeout&&clearTimeout(this.activeTimeout)}async updateTokenAndReschedule(e){if(this.activeTokenUpdating)return this.activeTokenUpdating;this.activeTokenUpdating=this.refreshTokenAndReschedule(e);try{await this.activeTokenUpdating}finally{this.activeTokenUpdating=null}}async refreshTokenAndReschedule(e){const t=await this.refreshToken(e);if(!this.isTokenValid(t))throw new Error("The token returned from the tokenRefresher is expired.");this.currentToken=t,this.refreshProactively&&this.scheduleRefresh()}async refreshToken(e){try{return this.activeTokenFetching||(this.activeTokenFetching=this.refresh(e)),a(await this.activeTokenFetching)}finally{this.activeTokenFetching=null}}scheduleRefresh(){if(this.disposed)return;this.activeTimeout&&clearTimeout(this.activeTimeout);const e=this.currentToken.expiresOnTimestamp-Date.now();let t=null;t=this.isTokenExpiringSoon(this.currentToken)?e*this.refreshAfterLifetimePercentage:e-this.expiringSoonIntervalInMs,this.activeTimeout=setTimeout((()=>this.updateTokenAndReschedule()),t)}isTokenValid(e){return e&&Date.now()<e.expiresOnTimestamp}isTokenExpiringSoon(e){return!e||Date.now()>=e.expiresOnTimestamp-this.expiringSoonIntervalInMs}}class c{constructor(e){this.token=e}async getToken(){return this.token}dispose(){}}class d{constructor(e){this.disposed=!1,this.tokenCredential="string"==typeof e?new c(a(e)):new l(e)}async getToken(e){this.throwIfDisposed();const t=await this.tokenCredential.getToken(e);return this.throwIfDisposed(),t}dispose(){this.disposed=!0,this.tokenCredential.dispose()}throwIfDisposed(){if(this.disposed)throw new Error("User credential is disposed")}}const u="undefined"!=typeof process&&process.env&&process.env.DEBUG||void 0;let h,g=[],p=[];const m=[];u&&v(u);const f=Object.assign((e=>y(e)),{enable:v,enabled:S,disable:function(){const e=h||"";return v(""),e},log:function(...e){if(e.length>0){const t=String(e[0]);t.includes(":error")?console.error(...e):t.includes(":warning")?console.warn(...e):t.includes(":info")?console.info(...e):(t.includes(":verbose"),console.debug(...e))}}});function v(e){h=e,g=[],p=[];const t=/\*/g,i=e.split(",").map((e=>e.trim().replace(t,".*?")));for(const e of i)e.startsWith("-")?p.push(new RegExp(`^${e.substr(1)}$`)):g.push(new RegExp(`^${e}$`));for(const e of m)e.enabled=S(e.namespace)}function S(e){if(e.endsWith("*"))return!0;for(const t of p)if(t.test(e))return!1;for(const t of g)if(t.test(e))return!0;return!1}function y(e){const t=Object.assign((function(...i){t.enabled&&(i.length>0&&(i[0]=`${e} ${i[0]}`),t.log(...i))}),{enabled:S(e),destroy:C,log:f.log,namespace:e,extend:T});return m.push(t),t}function C(){const e=m.indexOf(this);return e>=0&&(m.splice(e,1),!0)}function T(e){const t=y(`${this.namespace}:${e}`);return t.log=this.log,t}const E=f,b=new Set,_="undefined"!=typeof process&&process.env&&process.env.AZURE_LOG_LEVEL||void 0;let I;const w=E("azure");w.log=(...e)=>{E.log(...e)};const A=["verbose","info","warning","error"];_&&(O(_)?function(e){if(e&&!O(e))throw new Error(`Unknown log level '${e}'. Acceptable values: ${A.join(",")}`);I=e;const t=[];for(const e of b)k(e)&&t.push(e.namespace);E.enable(t.join(","))}(_):console.error(`AZURE_LOG_LEVEL set to unknown log level '${_}'; logging is not enabled. Acceptable values: ${A.join(", ")}.`));const P={verbose:400,info:300,warning:200,error:100};function R(e){const t=w.extend(e);return M(w,t),{error:D(t,"error"),warning:D(t,"warning"),info:D(t,"info"),verbose:D(t,"verbose")}}function M(e,t){t.log=(...t)=>{e.log(...t)}}function D(e,t){const i=Object.assign(e.extend(t),{level:t});if(M(e,i),k(i)){const e=E.disable();E.enable(e+","+i.namespace)}return b.add(i),i}function k(e){return Boolean(I&&P[e.level]<=P[I])}function O(e){return A.includes(e)}const N=R("communication-react:composite"),L=e=>"string"==typeof e.communicationUserId,x=e=>"string"==typeof e.phoneNumber,F=e=>"string"==typeof e.microsoftTeamsUserId,U=e=>"string"==typeof e.teamsAppId,B=e=>L(e)?Object.assign(Object.assign({},e),{kind:"communicationUser"}):x(e)?Object.assign(Object.assign({},e),{kind:"phoneNumber"}):F(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsUser"}):U(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsApp"}):Object.assign(Object.assign({},e),{kind:"unknown"}),V=e=>{const t=B(e);switch(t.kind){case"communicationUser":return t.communicationUserId;case"microsoftTeamsUser":{const{microsoftTeamsUserId:e,rawId:i,cloud:n,isAnonymous:r}=t;if(i)return i;if(r)return`8:teamsvisitor:${e}`;switch(n){case"dod":return`8:dod:${e}`;case"gcch":return`8:gcch:${e}`;case"public":return`8:orgid:${e}`}return`8:orgid:${e}`}case"microsoftTeamsApp":{const{teamsAppId:e,rawId:i,cloud:n}=t;if(i)return i;switch(n){case"dod":return`28:dod:${e}`;case"gcch":return`28:gcch:${e}`}return`28:orgid:${e}`}case"phoneNumber":{const{phoneNumber:e,rawId:i}=t;return i||`4:${e}`}case"unknown":return t.id}};var H,$,j="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self?self:{};function G(e,t,i){return e(i={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&i.path)}},i.exports),i.exports}$=H||(H={}),function(){var e="object"==typeof j?j:"object"==typeof self?self:"object"==typeof this?this:Function("return this;")(),t=i($);function i(e,t){return function(i,n){"function"!=typeof e[i]&&Object.defineProperty(e,i,{configurable:!0,writable:!0,value:n}),t&&t(i,n)}}void 0===e.Reflect?e.Reflect=$:t=i(e.Reflect,t),function(e){var t=Object.prototype.hasOwnProperty,i="function"==typeof Symbol,n=i&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",r=i&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",s="function"==typeof Object.create,a={__proto__:[]}instanceof Array,o=!s&&!a,l={create:s?function(){return F(Object.create(null))}:a?function(){return F({__proto__:null})}:function(){return F({})},has:o?function(e,i){return t.call(e,i)}:function(e,t){return t in e},get:o?function(e,i){return t.call(e,i)?e[i]:void 0}:function(e,t){return e[t]}},c=Object.getPrototypeOf(Function),d="object"==typeof process&&process.env&&"true"===process.env.REFLECT_METADATA_USE_MAP_POLYFILL,u=d||"function"!=typeof Map||"function"!=typeof Map.prototype.entries?function(){var e={},t=[],i=function(){function e(e,t,i){this._index=0,this._keys=e,this._values=t,this._selector=i}return e.prototype["@@iterator"]=function(){return this},e.prototype[r]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var i=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var i=this._find(e,!0);return this._values[i]=t,this},t.prototype.delete=function(t){var i=this._find(t,!1);if(i>=0){for(var n=this._keys.length,r=i+1;r<n;r++)this._keys[r-1]=this._keys[r],this._values[r-1]=this._values[r];return this._keys.length--,this._values.length--,t===this._cacheKey&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new i(this._keys,this._values,n)},t.prototype.values=function(){return new i(this._keys,this._values,s)},t.prototype.entries=function(){return new i(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[r]=function(){return this.entries()},t.prototype._find=function(e,t){return this._cacheKey!==e&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=e)),this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function n(e,t){return e}function s(e,t){return t}function a(e,t){return[e,t]}}():Map,h=d||"function"!=typeof Set||"function"!=typeof Set.prototype.entries?function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.values()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[r]=function(){return this.keys()},e}():Set,g=new(d||"function"!=typeof WeakMap?function(){var e=l.create(),i=n();return function(){function e(){this._key=n()}return e.prototype.has=function(e){var t=r(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=r(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return r(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=r(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=n()},e}();function n(){var t;do{t="@@WeakMap@@"+a()}while(l.has(e,t));return e[t]=!0,t}function r(e,n){if(!t.call(e,i)){if(!n)return;Object.defineProperty(e,i,{value:l.create()})}return e[i]}function s(e,t){for(var i=0;i<t;++i)e[i]=255*Math.random()|0;return e}function a(){var e=function(e){return"function"==typeof Uint8Array?"undefined"!=typeof crypto?crypto.getRandomValues(new Uint8Array(e)):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(new Uint8Array(e)):s(new Uint8Array(e),e):s(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",i=0;i<16;++i){var n=e[i];4!==i&&6!==i&&8!==i||(t+="-"),n<16&&(t+="0"),t+=n.toString(16).toLowerCase()}return t}}():WeakMap);function p(e,t,i){var n=g.get(e);if(b(n)){if(!i)return;n=new u,g.set(e,n)}var r=n.get(t);if(b(r)){if(!i)return;r=new u,n.set(t,r)}return r}function m(e,t,i){if(f(e,t,i))return!0;var n=x(t);return!_(n)&&m(e,n,i)}function f(e,t,i){var n=p(t,i,!1);return!b(n)&&function(e){return!!e}(n.has(e))}function v(e,t,i){if(f(e,t,i))return S(e,t,i);var n=x(t);return _(n)?void 0:v(e,n,i)}function S(e,t,i){var n=p(t,i,!1);if(!b(n))return n.get(e)}function y(e,t,i,n){p(i,n,!0).set(e,t)}function C(e,t){var i=T(e,t),n=x(e);if(null===n)return i;var r=C(n,t);if(r.length<=0)return i;if(i.length<=0)return r;for(var s=new h,a=[],o=0,l=i;o<l.length;o++){var c=l[o];s.has(c)||(s.add(c),a.push(c))}for(var d=0,u=r;d<u.length;d++)c=u[d],s.has(c)||(s.add(c),a.push(c));return a}function T(e,t){var i=[],n=p(e,t,!1);if(b(n))return i;for(var r=k(n.keys()),s=0;;){var a=N(r);if(!a)return i.length=s,i;var o=O(a);try{i[s]=o}catch(e){try{L(r)}finally{throw e}}s++}}function E(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function b(e){return void 0===e}function _(e){return null===e}function I(e){return"object"==typeof e?null!==e:"function"==typeof e}function w(e,t){switch(E(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var i=3===t?"string":5===t?"number":"default",r=D(e,n);if(void 0!==r){var s=r.call(e,i);if(I(s))throw new TypeError;return s}return function(e,t){if("string"===t){var i=e.toString;if(R(i)&&!I(r=i.call(e)))return r;if(R(n=e.valueOf)&&!I(r=n.call(e)))return r}else{var n;if(R(n=e.valueOf)&&!I(r=n.call(e)))return r;var r,s=e.toString;if(R(s)&&!I(r=s.call(e)))return r}throw new TypeError}(e,"default"===i?"number":i)}function A(e){var t=w(e,3);return function(e){return"symbol"==typeof e}(t)?t:function(e){return""+e}(t)}function P(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function R(e){return"function"==typeof e}function M(e){return"function"==typeof e}function D(e,t){var i=e[t];if(null!=i){if(!R(i))throw new TypeError;return i}}function k(e){var t=D(e,r);if(!R(t))throw new TypeError;var i=t.call(e);if(!I(i))throw new TypeError;return i}function O(e){return e.value}function N(e){var t=e.next();return!t.done&&t}function L(e){var t=e.return;t&&t.call(e)}function x(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===c)return t;if(t!==c)return t;var i=e.prototype,n=i&&Object.getPrototypeOf(i);if(null==n||n===Object.prototype)return t;var r=n.constructor;return"function"!=typeof r||r===e?t:r}function F(e){return e.__=void 0,delete e.__,e}e("decorate",(function(e,t,i,n){if(b(i)){if(!P(e))throw new TypeError;if(!M(t))throw new TypeError;return function(e,t){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t);if(!b(n)&&!_(n)){if(!M(n))throw new TypeError;t=n}}return t}(e,t)}if(!P(e))throw new TypeError;if(!I(t))throw new TypeError;if(!I(n)&&!b(n)&&!_(n))throw new TypeError;return _(n)&&(n=void 0),function(e,t,i,n){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t,i,n);if(!b(s)&&!_(s)){if(!I(s))throw new TypeError;n=s}}return n}(e,t,i=A(i),n)})),e("metadata",(function(e,t){return function(i,n){if(!I(i))throw new TypeError;if(!b(n)&&!function(e){switch(E(e)){case 3:case 4:return!0;default:return!1}}(n))throw new TypeError;y(e,t,i,n)}})),e("defineMetadata",(function(e,t,i,n){if(!I(i))throw new TypeError;return b(n)||(n=A(n)),y(e,t,i,n)})),e("hasMetadata",(function(e,t,i){if(!I(t))throw new TypeError;return b(i)||(i=A(i)),m(e,t,i)})),e("hasOwnMetadata",(function(e,t,i){if(!I(t))throw new TypeError;return b(i)||(i=A(i)),f(e,t,i)})),e("getMetadata",(function(e,t,i){if(!I(t))throw new TypeError;return b(i)||(i=A(i)),v(e,t,i)})),e("getOwnMetadata",(function(e,t,i){if(!I(t))throw new TypeError;return b(i)||(i=A(i)),S(e,t,i)})),e("getMetadataKeys",(function(e,t){if(!I(e))throw new TypeError;return b(t)||(t=A(t)),C(e,t)})),e("getOwnMetadataKeys",(function(e,t){if(!I(e))throw new TypeError;return b(t)||(t=A(t)),T(e,t)})),e("deleteMetadata",(function(e,t,i){if(!I(t))throw new TypeError;b(i)||(i=A(i));var n=p(t,i,!1);if(b(n))return!1;if(!n.delete(e))return!1;if(n.size>0)return!0;var r=g.get(t);return r.delete(i),r.size>0||g.delete(t),!0}))}(t)}();var q=G((function(e,t){function i(e,t){var i=0;return e.replace(/%[dixs%]/g,(function(e){var n=0;if("%"!==e[n++])return"";var r=e[n++];return"%"===r?"%":"s"===r||"d"===r||"i"===r?t[i++]:"x"===r?t[i++].toString(16):e}))}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Trace=10]="Trace",e[e.Debug6=16]="Debug6",e[e.Debug5=18]="Debug5",e[e.Debug4=20]="Debug4",e[e.Debug3=30]="Debug3",e[e.Debug2=40]="Debug2",e[e.Debug1=50]="Debug1",e[e.Warning=60]="Warning",e[e.Error=70]="Error",e[e.Fatal=80]="Fatal",e[e.MetaData=90]="MetaData"}(t.LogLevel||(t.LogLevel={})),function(e){e[e.UseDefault=0]="UseDefault",e[e.Compress=1]="Compress",e[e.Disabled=2]="Disabled"}(t.LogFileCompression||(t.LogFileCompression={})),function(e){e[e.Raw=0]="Raw",e[e.Base64=1]="Base64"}(t.LogFileEncoding||(t.LogFileEncoding={})),function(e){e[e.Unencrypted=0]="Unencrypted",e[e.Encrypted=1]="Encrypted"}(t.LogFileEncryption||(t.LogFileEncryption={})),function(e){e[e.PEM=0]="PEM",e[e.DER=1]="DER",e[e.BER=2]="BER"}(t.CertStoreFormat||(t.CertStoreFormat={})),function(e){e[e.InsertFront=8]="InsertFront"}(t.AppenderFlags||(t.AppenderFlags={})),t.vsprintf=i,t.sprintf=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return i(e,t)}})),z=G((function(e,t){var i,n,r=j&&j.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});function s(e){if(null===e)return-1;for(var t=0,i=e.length-1;i>=0;i--)t=37*t+e.charCodeAt(i)|0;for(i=13;i>=0;i--)t=37*t+"__auf_literal:".charCodeAt(i)|0;return t}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Unsafe=0]="Unsafe",e[e.Safe=1]="Safe",e[e.Inherited_Unsafe=2]="Inherited_Unsafe",e[e.Inherited_Safe=3]="Inherited_Safe",e[e.Blacklisted_Unsafe=4]="Blacklisted_Unsafe"}(n||(n={}));var a,o=function(){function e(e,t){this._level=q.LogLevel.Debug4,this._threshold=255,this._safe=n.Inherited_Unsafe,this._name=e,t&&(this._level=t.level(),this._safe=t.safe()?n.Inherited_Safe:n.Inherited_Unsafe,this._extendedInfo=t.extendedInfo())}return e.prototype.name=function(){return this._name},e.prototype.safe=function(){return this._safe===n.Safe||this._safe===n.Inherited_Safe},e.prototype.safety=function(){return this._safe},e.prototype.setSafety=function(e){this._safe=e},e.prototype.description=function(){return this._desc},e.prototype.setDescription=function(e){this._desc=e},e.prototype.level=function(){return this._level},e.prototype.setLevel=function(e){a.setLevel(this,e)},e.prototype._setLevel=function(e){this._level=e},e.prototype._setThreshold=function(e){this._threshold=e},e.prototype.isEnabled=function(e){return this._threshold<=e},e.prototype.setExtendedInfo=function(e){this._extendedInfo=e},e.prototype.extendedInfo=function(){return this._extendedInfo},e.prototype.trace=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Trace,s(e),e].concat(t))},e.prototype.debug6=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug6,s(e),e].concat(t))},e.prototype.debug5=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug5,s(e),e].concat(t))},e.prototype.debug4=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug4,s(e),e].concat(t))},e.prototype.debug3=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug3,s(e),e].concat(t))},e.prototype.debug2=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug2,s(e),e].concat(t))},e.prototype.debug1=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Debug1,s(e),e].concat(t))},e.prototype.warn=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Warning,s(e),e].concat(t))},e.prototype.error=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Error,s(e),e].concat(t))},e.prototype.fatal=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.Fatal,s(e),e].concat(t))},e.prototype.meta=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];a.log.apply(a,[this,q.LogLevel.MetaData,s(e),e].concat(t))},e}(),l=function(){function e(){}return e.instance=function(){return a},e.levelToString=function(e){return e<=q.LogLevel.Trace?"TRACE":e<=q.LogLevel.Debug6?"DEBUG6":e<=q.LogLevel.Debug5?"DEBUG5":e<=q.LogLevel.Debug4?"DEBUG4":e<=q.LogLevel.Debug3?"DEBUG3":e<=q.LogLevel.Debug2?"DEBUG2":e<=q.LogLevel.Debug1?"DEBUG1":e<=q.LogLevel.Warning?"WARN":e<=q.LogLevel.Error?"ERROR":e<=q.LogLevel.Fatal?"FATAL":(q.LogLevel.MetaData,"META")},e.levelFromString=function(e){return this._levelFromString[e]||parseInt(e,10)},e}();function c(e,t){for(var i=t.name();i.length>0;){if(e[i])return e[i];var n=i.lastIndexOf(".");i=n<0?"":i.substr(0,n)}return e[""]?e[""]:q.LogLevel.Debug4}function d(e,t){var i=255;return t.forEach((function(t){var n=255;t.appender.levels()?n=Math.min(n,c(t.appender.levels(),e)):t.appender.receiveAll()||(n=Math.min(n,e.level())),i=Math.min(i,n)})),i}l._levelFromString={TRACE:q.LogLevel.Trace,DEBUG6:q.LogLevel.Debug6,DEBUG5:q.LogLevel.Debug5,DEBUG4:q.LogLevel.Debug4,DEBUG3:q.LogLevel.Debug3,DEBUG2:q.LogLevel.Debug2,DEBUG1:q.LogLevel.Debug1,WARN:q.LogLevel.Warning,ERROR:q.LogLevel.Error,FATAL:q.LogLevel.Fatal,META:q.LogLevel.MetaData},t.LogFactory=l;var u=function(e){function t(){var t=e.call(this)||this;return t._nextId=0,t._appenders=[],t._components={},t._componentBlacklist=[],t._components[""]=new o("",null),t}return r(t,e),t.prototype.toHex=function(e){return(4294967296+e).toString(16).substr(-8)},t.prototype.addAppender=function(e,t){void 0===t&&(t=0);var i=this._nextId++;return t&q.AppenderFlags.InsertFront?this._appenders.unshift({appender:e,handle:i}):this._appenders.push({appender:e,handle:i}),this.recalcComponentThresholds(),i},t.prototype.removeAppender=function(e){for(var t=0;t<this._appenders.length;t++)if(this._appenders[t].handle===e){this._appenders.splice(t,1);break}this.recalcComponentThresholds()},t.prototype.log=function(e,t,i,n){for(var r=[],s=4;s<arguments.length;s++)r[s-4]=arguments[s];try{if(e.isEnabled(t)){var a={timestamp:(new Date).getTime(),component:e,level:t};this._appenders.forEach((function(s){(function(e,t,i){return!!e.appender.receiveAll()||(e.appender.levels()?i>=c(e.appender.levels(),t):i>=t.level())})(s,e,t)&&s.appender.log(a,i,n,r)}))}}catch(e){}},t.prototype.parent=function(e){for(;;){var t=e.lastIndexOf(".");if(e=t>=0?e.substr(0,t):"",this._components[e])return this._components[e]}},t.prototype.children=function(e){var t=[];for(var i in this._components)this.parent(i).name()===e&&t.push(this._components[i]);return t},t.prototype.component=function(e){if(this._components[e])return this._components[e];var t=new o(e,this.parent(e));this._components[e]=t;var i=d(t,this._appenders);return t._setThreshold(i),t},t.prototype.rootComponent=function(){return this.component("")},t.prototype.setSafetyRecursive=function(e,t){var i=this;this.children(e).forEach((function(e){e.safety()!==n.Inherited_Safe&&e.safety()!==n.Inherited_Unsafe||(e.setSafety(t),i.setSafetyRecursive(e.name(),t))}))},t.prototype.declareComponentSafe=function(e,t){var i=this.component(e);-1!==this._componentBlacklist.indexOf(i.name())?i.setSafety(n.Blacklisted_Unsafe):i.setSafety(t?n.Safe:n.Unsafe),this.setSafetyRecursive(e,t?n.Inherited_Safe:n.Inherited_Unsafe)},t.prototype.declareComponentDescription=function(e,t){this.component(e).setDescription(t)},t.prototype.setExtendedInfoRecursive=function(e,t){var i=this;this.children(e).forEach((function(e){void 0===e.extendedInfo()&&(e.setExtendedInfo(t),i.setExtendedInfoRecursive(e.name(),t))}))},t.prototype.declareComponentExtendedInfo=function(e,t){var i=this.component(e);i.setExtendedInfo(t),this.setExtendedInfoRecursive(i.name(),t)},t.prototype.recalcComponentThresholds=function(){for(var e in this._components){var t=this._components[e],i=d(t,this._appenders);t._setThreshold(i)}},t.prototype.setLevel=function(e,t){if(""===e.name())for(var i in this._components){(s=this._components[i])._setLevel(t);var n=d(s,this._appenders);s._setThreshold(n)}else{var r=e.name()+".";for(var i in e._setLevel(t),n=d(e,this._appenders),e._setThreshold(n),this._components){var s;if((s=this._components[i]).name().substr(0,r.length)===r){s._setLevel(t);var a=d(s,this._appenders);s._setThreshold(a)}}}},t.prototype.setComponentBlacklist=function(e){for(var t in this._componentBlacklist=e,this._components){var i=this._components[t];-1!==this._componentBlacklist.indexOf(i.name())&&i.setSafety(n.Blacklisted_Unsafe)}},t}(l);a=new u})),W=G((function(e,t){function i(e){return null!=e&&"function"==typeof e.then}function n(e){return null!=e&&"function"==typeof e.cancel}function r(e,i){if(!t.config.catchExceptions)return e();try{return e()}catch(e){return i(e)}}Object.defineProperty(t,"__esModule",{value:!0}),t.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(e){throw e}},t.fromThenable=function(e){var t=d();return e.then((function(e){t.resolve(e)}),(function(e){t.reject(e)})),t.promise().thenAsync((function(e){return e}))};var s,a=[],o="undefined"!=typeof setImmediate;function l(e){a.push(e),1===a.length&&(o?setImmediate(c):setTimeout(c,0))}function c(){var e=a;a=[];for(var t=0;t<e.length;t++)e[t]()}function d(){return new s.SyncTask}function u(e){return(new s.SyncTask).resolve(e).promise()}function h(e){var t=d(),r=!1;return t.onCancel((function(t){e.forEach((function(e){n(e)&&s.SyncTask.cancelOtherInternal(e,t)}))})),e.forEach((function(e){i(e)?e.then((function(e){r||(r=!0,t.resolve(e))}),(function(e){r||(r=!0,t.reject(e))})):r||(r=!0,t.resolve(e))})),t.promise()}t.asyncCallback=l,function(e){var s=function(){function e(){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 e.prototype._addCallbackSet=function(t,i){var n=this,r=new e;return r.onCancel((function(e){t.wasCanceled=!0,t.cancelContext=e,n._cancelInternal(e)})),t.task=r,this._storedCallbackSets.push(t),i?this._mustHandleError=!1:r._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),r.promise()},e.prototype.onCancel=function(e){return this._completedSuccess||this._completedFail||(this._wasCanceled?e(this._cancelContext):this._cancelCallbacks.push(e)),this},e.prototype.then=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t},!0)},e.prototype.thenAsync=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t,asyncCallback:!0},!0)},e.prototype.catch=function(e){return this._addCallbackSet({failFunc:e},!0)},e.prototype.always=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!0)},e.prototype.setTracingEnabled=function(e){return this._traceEnabled=e,this},e.prototype.finally=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!1),this},e.prototype.done=function(e){return this._addCallbackSet({successFunc:e},!1),this},e.prototype.fail=function(e){return this._addCallbackSet({failFunc:e},!1),this},e.prototype.resolve=function(e){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=e,this._cancelCallbacks=[],this._resolveSuccesses(),this},e.prototype.reject=function(t){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=t,this._cancelCallbacks=[],this._resolveFailures(),e._enforceErrorHandled(this),this},e.prototype._checkState=function(e){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var i="Failed to "+(e?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(i)}(t.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},e._enforceErrorHandled=function(i){i._mustHandleError&&(e._rejectedTasks.push(i),e._enforceErrorHandledTimer||(e._enforceErrorHandledTimer=setTimeout((function(){e._enforceErrorHandledTimer=void 0;var i=e._rejectedTasks;e._rejectedTasks=[],i.forEach((function(e,i){e._mustHandleError&&t.config.unhandledErrorHandler(e._storedErrResolution)}))}),0)))},e.prototype.cancel=function(e){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(e)},e.prototype._cancelInternal=function(e){var t=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=e;var i=this._cancelCallbacks;this._cancelCallbacks=[],i.length>0&&i.forEach((function(e){t._completedSuccess||t._completedFail||e(t._cancelContext)}))}},e.cancelOtherInternal=function(e,t){var i=e;i._storedCallbackSets&&i._cancelInternal?i._cancelInternal(t):e.cancel(t)},e.prototype.promise=function(){return this},e.prototype._resolveSuccesses=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?l((function(){return e._resolveSuccessCallback(t)})):e._resolveSuccessCallback(t)}))}this._resolving=!1},e.prototype._resolveSuccessCallback=function(t){var s=this;t.successFunc?r((function(){var r=t.successFunc(s._storedResolution);n(r)&&(t.wasCanceled?e.cancelOtherInternal(r,t.cancelContext):t.task.onCancel((function(t){return e.cancelOtherInternal(r,t)}))),i(r)?r.then((function(e){t.task.resolve(e)}),(function(e){t.task.reject(e)})):t.task.resolve(r)}),(function(e){s._handleException(e,"SyncTask caught exception in success block: "+e.toString()),t.task.reject(e)})):t.task.resolve(this._storedResolution)},e.prototype._resolveFailures=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?l((function(){return e._resolveFailureCallback(t)})):e._resolveFailureCallback(t)}))}this._resolving=!1},e.prototype._resolveFailureCallback=function(t){var s=this;t.failFunc?r((function(){var r=t.failFunc(s._storedErrResolution);n(r)&&(t.wasCanceled?e.cancelOtherInternal(r,t.cancelContext):t.task.onCancel((function(t){return e.cancelOtherInternal(r,t)}))),i(r)?r.then((function(e){t.task.resolve(e)}),(function(e){t.task.reject(e)})):t.task.resolve(r)}),(function(e){s._handleException(e,"SyncTask caught exception in failure block: "+e.toString()),t.task.reject(e)})):t.task.reject(this._storedErrResolution)},e.prototype._handleException=function(e,i){t.config.exceptionsToConsole&&console.error(i),t.config.exceptionHandler&&t.config.exceptionHandler(e)},e.prototype.toEs6Promise=function(){var e=this;return new Promise((function(t,i){return e.then(t,i)}))},e._rejectedTasks=[],e}();e.SyncTask=s}(s||(s={})),t.all=function(e){if(0===e.length)return u([]);var t,r=d(),a=e.length,o=Array(e.length);r.onCancel((function(t){e.forEach((function(e){n(e)&&s.SyncTask.cancelOtherInternal(e,t)}))}));var l=function(){0==--a&&(void 0!==t?r.reject(t):r.resolve(o))};return e.forEach((function(e,n){i(e)?e.then((function(e){o[n]=e,l()}),(function(e){void 0===t&&(t=void 0===e||e),l()})):(o[n]=e,l())})),r.promise()},t.Defer=d,t.Resolved=u,t.Rejected=function(e){return(new s.SyncTask).reject(e).promise()},t.race=h,t.raceTimer=function(e,t){var i=d(),n=setTimeout((function(){i.resolve({timedOut:!0})}),t);return h([e.then((function(e){return clearTimeout(n),{timedOut:!1,result:e}})),i.promise()])}})),K=G((function(e,t){var i,n=j&&j.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r,s=function(){function e(e){this._formatter=e||new l}return e.prototype.formatter=function(){return this._formatter},e.prototype.receiveAll=function(){return!1},e.prototype.levels=function(){return null},e}();function a(e){return(4294967296+e).toString(16).substr(-8)}function o(e,t){return(1e12+e).toString(10).substr(-t)}t.AbstractLogAppender=s,function(e){e[e.Timestamp=1]="Timestamp",e[e.Component=4]="Component",e[e.Level=8]="Level",e[e.FullDate=32]="FullDate",e[e.LogId=64]="LogId"}(r=t.SLF_Flags||(t.SLF_Flags={}));var l=function(){function e(e){void 0===e&&(e=4294967295),this._flags=e}return e.prototype.format=function(e,t,i,n){var s="";if(this._flags&r.FullDate)s+=new Date(e.timestamp).toISOString()+" ";else if(this._flags&r.Timestamp){var l=new Date(e.timestamp);s+=o(l.getHours(),2)+":"+o(l.getMinutes(),2)+":"+o(l.getSeconds(),2)+"."+o(l.getMilliseconds(),2)+" "}return this._flags&r.LogId&&(s+="[#"+a(t)+"-"+(e.component.safe()?"S":"u")+"] "),this._flags&r.Level&&(s+="["+z.LogFactory.levelToString(e.level)+"] "),this._flags&r.Component&&(s+="["+e.component.name()+"] "),i||""===i?s+q.vsprintf(i,n):s+a(t)+": "+n.join(" ")},e}();t.StandardLogFormatter=l;var c=console,d=console.log||function(){},u=console.info||d,h=console.warn||u,g=console.error||h,p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n(t,e),t.prototype.log=function(e,t,i,n){n=n.slice(0);var r=e.level<=q.LogLevel.Debug3?d:e.level<=q.LogLevel.Debug1?u:e.level<=q.LogLevel.Warning?h:g;if(-1===t){var s=this.formatter().format(e,t,"",[]);"string"==typeof n[0]&&(s+=n.shift()),r.apply(c,[s].concat(n))}else{for(var a=void 0,o=[];a=i.match(/\s*%@\s*$/);)i=i.substr(0,i.length-a[0].length),o.unshift(n.pop());s=this.formatter().format(e,t,i,n),r.apply(c,[s].concat(o))}},t}(s);t.ConsoleAppender=p;var m=function(){function e(e){this._chained=e}return e.prototype.log=function(e,t,i,n){this._chained.log(e,t,i,n)},e.prototype.receiveAll=function(){return this._chained.receiveAll()},e.prototype.levels=function(){return this._chained.levels()},e}();t.ChainedLogAppender=m;var f=function(e){function t(t,i){var n=e.call(this,t)||this;return n._levels=i,n}return n(t,e),t.prototype.levels=function(){return this._levels},t}(m);t.wrapAppenderWithLogLevels=function(e,t){return new f(e,t)}})),J=G((function(e,t){var i,n=j&&j.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r,s=z.LogFactory.instance().component("RootToolsManager");z.LogFactory.instance().declareComponentSafe("RootToolsManager",!0),function(e){e[e.InternalBuild=0]="InternalBuild",e[e.PublicBuild=1]="PublicBuild"}(r=t.BuildType||(t.BuildType={}));var a=r.InternalBuild;function o(e){return(4294967296+e).toString(16).substr(-8)}function l(e,t){var i=[];for(var n in e)i.push(t(n,e[n]));return i}function c(e,t,i){if(null==e)return null==t||0===t.length;if(null==t)return null==e||0===e.length;if(e.length===t.length){for(var n=0;n<e.length;n++)if(!i(e[n],t[n]))return!1;return!0}return!1}function d(e,t){return null==e?null==t:null==t?null==e:e.arg===t.arg&&e.op===t.op&&e.value===t.value}function u(e,t){return null==e?null==t||0===t.logId:null==t?null==e||0===e.logId:e.logId===t.logId&&e.name===t.name&&c(e.matchers,t.matchers,d)}function h(e,t){return null==e?null==t:null==t?null==e:e.component===t.component&&e.parsedLevel===t.level}function g(e,t){return null==e?null==t:null==t?null==e:e.component===t.component&&e.level===t.level}function p(e){for(var t=[],i=0;i<e.length;i++)"string"==typeof e[i]||"number"==typeof e[i]?t.push(e[i]):t.push(JSON.stringify(e[i]));return t}t.setBuildType=function(e){var t=a;return a=e,t};var m=function(e){function t(t,i,n){var r=e.call(this)||this;return r._unmetConditions=[],r._rtMan=t,r._triggerCallback=i,r._ecsConfig=n,r.resetConditions(),r}return n(t,e),t.prototype.config=function(){return this._ecsConfig},t.prototype.configEquals=function(e){return this._ecsConfig.includeUnsafe===e.includeUnsafe&&this._ecsConfig.mutualSubmissionType===e.mutualSubmissionType&&this._ecsConfig.name===e.name&&this._ecsConfig.reenableAfterTriggering===e.reenableAfterTriggering&&this._ecsConfig.experimentTarget===e.experimentTarget&&u(this._ecsConfig.resetCondition,e.resetCondition)&&c(this._ecsConfig.conditions,e.conditions,u)&&c(this._ecsConfig.filters,e.filters,g)},t.prototype.nativeConfigEquals=function(e){return this._ecsConfig.includeUnsafe===e.includeUnsafe&&this._ecsConfig.name===e.name&&this._ecsConfig.reenableAfterTriggering===e.reenableAfterTriggering&&u(this._ecsConfig.resetCondition,e.resetCondition)&&c(this._ecsConfig.conditions,e.conditions,u)&&c(this._ecsConfig.filters,e.filters,h)},t.prototype.needReset=function(e){return!this.configEquals(e)},t.prototype.resetConditions=function(){this._unmetConditions=[];for(var e=0;e<this._ecsConfig.conditions.length;e++)this._unmetConditions.push(e)},t.prototype.matcherMatches=function(e,t){if(e.arg>=t.length)return!1;var i=t[e.arg],n="string"==typeof i?e.value:parseInt(e.value,10);return"="===e.op||"=="===e.op?i===n:"!="===e.op?i!==n:"<"===e.op?i<n:"<="===e.op?i<=n:">"===e.op?i>n:">="===e.op?i>=n:"CONTAINS"===e.op.toUpperCase()&&(""+i).indexOf(e.value)>=0},t.prototype.conditionMatches=function(e,t,i){if(t!==e.logId)return!1;if(e.matchers)for(var n=0;n<e.matchers.length;n++)if(!this.matcherMatches(e.matchers[n],i))return!1;return!0},t.prototype.log=function(e,t,i,n){if(0!==this._unmetConditions.length&&e.component!==s){var r=this._ecsConfig;r.resetCondition&&this.conditionMatches(r.resetCondition,t,n)&&(s.debug4("LogTrigger %s: resetCondition met",r.name),this.resetConditions());for(var a=0;a<this._unmetConditions.length;a++){var o=this._unmetConditions[a];if(this.conditionMatches(r.conditions[o],t,n)){s.debug4("LogTrigger %s: condition %s met",r.name,r.conditions[o].name),this._unmetConditions.splice(a,1);break}}0===this._unmetConditions.length&&(s.debug1("LogTrigger %s has triggered, trying to send the log",r.name),this._triggerCallback.call(this._rtMan,r),r.reenableAfterTriggering&&this.resetConditions())}},t.prototype.receiveAll=function(){return!0},t}(K.AbstractLogAppender),f=function(e){function t(t,i,n){var r=e.call(this)||this;return r._circularBuffer=[],r._circularBufferMaxSize=0,r._onBufferOverflow=null,r._circularBuffer=[],r._circularBufferMaxSize=i,r._includeUnsafe=t,r._onBufferOverflow=n||function(){return r._circularBuffer.shift()},r}return n(t,e),t.prototype.log=function(e,t,i,n){if((this._includeUnsafe||e.component.safe())&&!(this._circularBuffer.length>this._circularBufferMaxSize)){var r={md:e,logId:t,messages:p(n)};this._circularBuffer.push(r),this._circularBuffer.length>this._circularBufferMaxSize&&this._onBufferOverflow()}},t.prototype.visitReverseOrder=function(e){for(var t=this._circularBuffer.length-1;t>=0;t--){var i=this._circularBuffer[t];if(!e(i.md,i.logId,i.messages))return}},t.prototype.visitForwardOrder=function(e){for(var t=0;t<this._circularBuffer.length;t++){var i=this._circularBuffer[t];if(!e(i.md,i.logId,i.messages))return}},t.prototype.needReset=function(e,t){return e!==this._includeUnsafe||t!==this._circularBufferMaxSize},t.prototype.dumpLogBuffer=function(e,t,i){var n=this,r=new v(e.reverse),s=e.filter.map((function(e){return{component:"root"===e.component?"":e.component,parsedLevel:e.level}})),a=i||{matchedLines:0,totalLines:0};return(e.reverse?this.visitReverseOrder:this.visitForwardOrder).apply(this,[function(e,i,o){return a.totalLines++,n.filterMatches(e,i,o,s)&&(a.matchedLines++,r.log(e.component,e.timestamp,e.level,i,o)),!t||r._data.length<t}]),r.close(),r.data()},t.prototype.filterMatches=function(e,t,i,n){for(var r=0;r<n.length;r++)if((""===n[r].component||e.component.name()===n[r].component||e.component.name().substr(0,n[r].component.length)===n[r].component&&"."===e.component.name().charAt(n[r].component.length))&&e.level>=n[r].parsedLevel)return!0;return!1},t.prototype.clear=function(){this._circularBuffer=[]},t.prototype.size=function(){return this._circularBuffer.length},t.prototype.empty=function(){return 0===this.size()},t.prototype.capacity=function(){return this._circularBufferMaxSize},t}(K.AbstractLogAppender);t.CircularBuffer=f;var v=function(){function e(e){this._reverse=e,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+=e?String.fromCharCode(34):String.fromCharCode(32),this._data+=String.fromCharCode(32)}return e.prototype._add8=function(e){if(this._pending.push(255&e),3===this._pending.length){var t=(this._pending[0]<<16)+(this._pending[1]<<8)+(0|this._pending[2]),i=this._base64chars[t>>18&63]+this._base64chars[t>>12&63]+this._base64chars[t>>6&63]+this._base64chars[63&t];this._data+=i,this._pending=[]}},e.prototype._add16=function(e){this._add8(e>>8&255),this._add8(255&e)},e.prototype._add32=function(e){this._add8(e>>24&255),this._add8(e>>16&255),this._add8(e>>8&255),this._add8(255&e)},e.prototype._add64=function(e){this._add32(e/4294967296|0),this._add32(0|e)},e.prototype._addS=function(e){for(var t=0;t<e.length;t++)this._add8(e.charCodeAt(t));this._add8(0)},e.prototype._close=function(){for(;this._pending.length;)this._add8(0)},e.prototype.log=function(e,t,i,n,r){var s=this._components[e.name()];s||(s=++this._componentCount,this._components[e.name()]=s,this._add8(2),this._add16(s),this._addS(e.name()),this._addS(""),this._addS(""),this._add8(e.safe()?1:0));var a=128;this._first&&(a|=2);var o=t-this._lastts;this._lastts=t,o>-128&&o<128&&(a|=1),this._add8(a),1&a?this._add8(o):this._add64(1e3*t),this._first&&(this._add32(1),this._add8(0),this._add16(0)),this._add16(s),this._add8(i),this._add32(n),this._add8(r.length);for(var l=0;l<r.length;l++)this._add8(8),this._addS(""+r[l]);this._first=!1},e.prototype.close=function(){this._add8(7),this._close()},e.prototype.data=function(){return this._data},e.prototype.empty=function(){return this._first},e}(),S=function(e){function t(t,i,n,r){var s=e.call(this)||this;return s._capacity=t,s._onBufferOverflow=i,s._enableThrottling=n,s._maxVerbosityLevel=r,s._outputFormatter=new v(!1),s._linesStored=0,s._throttling=!1,s._linesThrottled=0,s}return n(t,e),t.prototype.log=function(e,t,i,n){this._maxVerbosityLevel&&e.level<this._maxVerbosityLevel||(this._throttling?this._linesThrottled++:(this._linesStored++,this._outputFormatter.log(e.component,e.timestamp,e.level,t,p(n))),this._linesStored>this._capacity&&(this._enableThrottling?this._throttling||(this._throttling=!0):this._onBufferOverflow()))},t.prototype.dumpAndReset=function(){if(this._outputFormatter.empty())return"";this._linesThrottled>0&&this._outputFormatter.log(s,(new Date).getTime(),q.LogLevel.Fatal,-1,["RooToolsManager: Log buffer overflow! "+this._linesThrottled+" lines thrown away"]),this._outputFormatter.close();var e=this._outputFormatter.data();return this.clearBuffer(),e},t.prototype.empty=function(){return this._outputFormatter.empty()},t.prototype.clearBuffer=function(){this._outputFormatter=new v(!1),this._linesStored=0,this._linesThrottled=0,this._throttling=!1},t.prototype.capacity=function(){return this._capacity},t.prototype.throttlingEnabled=function(){return this._enableThrottling},t.prototype.size=function(){return this._linesStored},t.prototype.maxVerbosityLevel=function(){return this._maxVerbosityLevel},t}(K.AbstractLogAppender);function y(e){return"Native"===e||"JavaScript"===e||"Mixed"===e}t.DumperBuffer=S;var C=function(){function e(){this._maxUploadSize=0,this._jsToNativeBuffer=null,this._jsToNativeBufferHandle=null,this._jsToNativeFlushTimer=null,this._jsToNativeFlushInterval=0,this._triggers={},this._defaultBuffers=[{size:2097152,level:q.LogLevel.Debug4}],this._defaultKillswitch={blacklist:[],whitelist:[]},this._defaultBlacklists={component:[],logline:[]},this._localLogLevels={},this._defaultExperimentTarget="Mixed",this._BRBCallback=null}return e.prototype.setDelegate=function(e){this._glue=e,this.registerListeners()},e.prototype.isDelegateSet=function(){return null!=this._glue},e.prototype.setNativeFunctions=function(e){this._native&&this._native.log_config.removeLogTriggerListener(this),this._native=e,this._native&&this._native.log_config.addLogTriggerListener(this)},e.prototype.applyLogLevels=function(){var e={};for(var t in this._localLogLevels)e[t]=this._localLogLevels[t];e[""]=e.root||q.LogLevel.Debug4,delete e.root;var i=l(e,(function(e,t){return{component:e,level:t}}));i.sort((function(e,t){return e.component.length-t.component.length})),i.forEach((function(e){return z.LogFactory.instance().component(e.component).setLevel(e.level)})),this._native&&this._native.log_config.setLogLevelConfig(i)},e.prototype.setLocalLogLevelConfig=function(e){this._localLogLevels=e,this.applyLogLevels()},e.prototype.parseMatcher=function(e){return null==e||null==e.arg||null==e.op||null==e.value?null:{arg:e.arg,op:e.op,value:e.value}},e.prototype.parseCondition=function(e){if(null==e||null==e.logId)return null;if(e.matchers&&!(e.matchers instanceof Array))return null;var t={name:e.name||o(e.logId),logId:e.logId,matchers:[]};if(e.matchers&&e.matchers.length)for(var i=0,n=e.matchers;i<n.length;i++){var r=n[i],s=this.parseMatcher(r);s&&t.matchers.push(s)}return t},e.prototype.parseFilter=function(e){return null==e||null==e.component||0===e.component.length?null:{component:e.component,level:e.level,parsedLevel:z.LogFactory.levelFromString(e.level)}},e.prototype.parseConfig=function(e,t,i){if(null==e)return null;if(!(e.conditions instanceof Array)||0==e.conditions.length)return null;if(!(e.filters instanceof Array)||0==e.filters.length)return null;if(e.resetCondition&&!this.parseCondition(e.resetCondition))return null;for(var n={name:e.name||t+"->"+i,ecsNs:t,reenableAfterTriggering:e.reenableAfterTriggering||!1,mutualSubmissionType:e.mutualSubmissionType||"",includeUnsafe:a!==r.PublicBuild&&(e.includeUnsafe||!1),experimentTarget:y(e.experimentTarget)&&e.experimentTarget||this._defaultExperimentTarget,conditions:[],resetCondition:null==e.resetCondition?e.resetCondition:this.parseCondition(e.resetCondition),filters:[]},s=0,o=e.conditions;s<o.length;s++){var l=o[s],c=this.parseCondition(l);c&&n.conditions.push(c)}for(var d=0,u=e.filters;d<u.length;d++){var h=u[d],g=this.parseFilter(h);g&&n.filters.push(g)}return 0===n.conditions.length?null:n},e.prototype.isExperimentListed=function(e,t,i,n){return!!e&&(!(!n||!e.some((function(e){return"*"===e.namespace})))||e.some((function(e){return e.namespace===t&&(e.experiment===i||"*"==e.experiment)})))},e.prototype.isExperimentAllowed=function(e,t,i){return!this.isExperimentListed(e.blacklist,t,i,!0)||this.isExperimentListed(e.whitelist,t,i,!1)},e.prototype.findTrigger=function(e,t){for(var i in e)if(e[i].configEquals(t))return i;return null},e.prototype.findTriggerByNativeConfig=function(e,t){for(var i in e)if(e[i].nativeConfigEquals(t))return i;return null},e.prototype.OnEcsChange=function(){var e=this;function t(e,i,n){return i<e.length?n(e[i]).then((function(){return t(e,i+1,n)})):W.Resolved()}return null==this._glue?W.Resolved():this._glue.fetchEcsConfig("SkypeRootTools","ULBaseline").then((function(i){s.debug4("Reloading ULBaseline config - new config: %@",i),i||(s.warn("No ULBaseline config"),i={}),e._maxUploadSize=i.logUpload&&i.logUpload.maxSize||1024;var n=[],r=e._triggers;e._triggers={};var a=(i.logUpload&&i.logUpload.maxSize||1024)/100,o=i.circularBuffer&&i.circularBuffer.enabled,c=i.circularBuffer&&i.circularBuffer.buffers||e._defaultBuffers,d=i.circularBuffer&&i.circularBuffer.storeUnsafe;e._defaultExperimentTarget=y(i.defaultExperimentTarget)&&i.defaultExperimentTarget||"Mixed";var u=i.killswitch||e._defaultKillswitch,h=i.blacklists||e._defaultBlacklists;h.component.length>0&&z.LogFactory.instance().setComponentBlacklist(h.component);var g={};(i.componentLevels||[]).forEach((function(e){return g[e.component]=e.level})),t(i.configPaths||[],0,(function(t){return e._glue.fetchEcsConfig(t.ns,t.key).then((function(i){var a=i instanceof Array?i:[i];s.debug4("Reloading ECS config for %s->%s - new config: %@",t.ns,t.key,a);for(var l=0,c=a;l<c.length;l++){var h=c[l];if(null!=h){var p=e.parseConfig(h,t.ns,t.key);if(null!=p)if("JavaScript"===p.experimentTarget||"Mixed"===p.experimentTarget)if(s.debug2("Parsed ECS config for %s->%s - %@",t.ns,t.key,p),e.isExperimentAllowed(u,t.ns,p.name)){s.debug2("Allowing %s->%s:%s according to killswitch",t.ns,t.key,p.name),o=!0;var m=e.findTrigger(r,p);null!=m?(s.debug2("Triggers updated, keeping trigger %s",p.name),e._triggers[m]=r[m],delete r[m]):n.push(p),p.filters&&p.filters.forEach((function(e){return g[e.component]=Math.min(g[e.component]||255,e.parsedLevel)})),p.includeUnsafe&&(d=!0)}else s.debug2("Disallowing %s->%s according to killswitch",t.ns,t.key);else s.debug4("Skipping %s->%s, targeted for %s",t.ns,t.key,p);else s.error("Failed to parse ECS config for %s->%s",t.ns,t.key)}}}))})).always((function(){for(var t in e.applyLogLevels(),r)s.debug2("Triggers updated, removing trigger %s",r[t].config().name),z.LogFactory.instance().removeAppender(+t);if(n.forEach((function(t){s.debug2("Triggers updated, adding trigger %s",t.name);var i=new m(e,e._triggered,t),n=z.LogFactory.instance().addAppender(i);e._triggers[String(n)]=i})),g[""]=g.root||q.LogLevel.Debug4,delete g.root,!e._circularBuffer||o&&!e._circularBuffer.needReset(d,a)?e._circularBuffer&&(Object.keys(r).length>0||n.length>0?(s.debug2("Buffer updated, reapplying log levels, removing log levels wrapper"),z.LogFactory.instance().removeAppender(e._circularBufferHandle),e._circularBufferHandle=null):s.debug2("Buffer updated, no change")):(s.debug2("Buffer updated, removing existing buffer"),z.LogFactory.instance().removeAppender(e._circularBufferHandle),e._circularBuffer=null,e._circularBufferHandle=null),o&&(e._circularBuffer||(s.debug2("Buffer updated, adding new buffer (storeUnsafe=%d,maxSize=%s)",d,a),e._circularBuffer=new f(d,a)),null==e._circularBufferHandle&&(s.debug2("Creating log level wrapper"),e._circularBufferHandle=z.LogFactory.instance().addAppender(K.wrapAppenderWithLogLevels(e._circularBuffer,g),q.AppenderFlags.InsertFront))),e._native){var i=l(g,(function(e,t){return{component:e,level:t}}));i.sort((function(e,t){return e.component.length-t.component.length})),e._native.log_config.setLogBufferConfig(o,{storeUnsafe:d,buffers:c},i);var u=[];for(var h in e._triggers){var p=e._triggers[h].config();u.push({name:p.name,ecsNs:p.ecsNs,conditions:p.conditions,resetCondition:p.resetCondition,includeUnsafe:p.includeUnsafe,reenableAfterTriggering:p.reenableAfterTriggering,filters:p.filters.map((function(e){return{component:e.component,level:e.parsedLevel}})),dumpFile:!1,metadata:{}})}e._native.log_config.setLogTriggerConfig(u,{})}}))}))},e.prototype._send=function(e,t){null!=this._glue&&(this._glue.sendTelemetry("638b8ba2bae14e07aa5d73ddb5d5e5c5-297b8412-5df3-4a83-83c4-7b76c6c5d3f0-7104",{logTriggerName:e.name,logEcsNs:e.ecsNs,logdata:t}),s.debug4("LogSender::send, sent %d bytes",t.length))},e.prototype.triggered=function(e,t){},e.prototype.triggeredPartially=function(e,t,i,n,r){var s=this.findTriggerByNativeConfig(this._triggers,e);if(s){var a={level:t.level,component:z.LogFactory.instance().component(t.component),timestamp:t.timestamp};this._triggers[s].log(a,i,n,r)}},e.prototype.reset=function(e){var t=this.findTriggerByNativeConfig(this._triggers,e);t&&this._triggers[t].resetConditions()},e.prototype.dumpLogBuffer=function(e,t){if(this._circularBuffer){var i={matchedLines:0,totalLines:0},n=this._circularBuffer.dumpLogBuffer(e,this._maxUploadSize,i);if(s.debug4("dumpLogBuffer: dumped %d of %d lines, size of payload: %d",i.matchedLines,i.totalLines,null!=n?n.length:0),this._native){var r=W.Defer();return this._native.log_config.mergeAndDumpLogBuffer(n,e,t,(function(e){return r.resolve(e)})),r.promise()}return W.Resolved(n)}return s.warn("dumpLogBuffer: no log buffer enabled"),W.Rejected()},e.prototype._triggered=function(e){var t=this,i={compression:q.LogFileCompression.Compress,encoding:q.LogFileEncoding.Base64,encryption:q.LogFileEncryption.Encrypted,maxRotations:0,maxSize:this._maxUploadSize,reverse:!0},n={includeUnsafe:e.includeUnsafe,filter:e.filters.map((function(e){return{component:e.component,level:e.parsedLevel}})),reverse:!0};this.dumpLogBuffer(n,i).then((function(i){return t._send(e,i)}))},e.prototype.sendBRBEvent=function(e,t){try{if(s.debug2("sendBRBEvent %s",JSON.stringify(e)),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var i={eventType:"uploadBRB",mutualSubmissionType:"call",payload:e},n=void 0!==t?JSON.stringify({userIds:t}):"";this._glue.sendLoggingEventToNative(JSON.stringify(i),n)}}catch(e){s.error("sendBRBEvent %s: %s",e.name,e.message)}},e.prototype.setBRBCallback=function(e){s.debug2("setBRBCallback"),null!=this._glue?"function"==typeof this._glue.setNativeLoggingEventCallback?this._BRBCallback=e:s.warn("setBRBCallback: RootToolsManagerDelegate missing setNativeLoggingEventCallback method"):s.warn("setBRBCallback: RootToolsManagerDelegate is not set")},e.prototype.registerListeners=function(){var e=this;null!=this._glue&&"function"==typeof this._glue.setNativeLoggingEventCallback?this._glue.setNativeLoggingEventCallback((function(t,i){return e.handleNativeLoggingEvent(t,i)})):s.warn("registerListeners: RootToolsManagerDelegate missing setNativeLoggingEventCallback method")},e.prototype.handleNativeLoggingEvent=function(e,t){try{s.debug2("Native Log event message: %s aux: %s",e,t);var i=JSON.parse(e);if(i.eventType&&"uploadBRB"===i.eventType){if("function"!=typeof this._BRBCallback)return void s.warn("BRBCallback not set, ignoring native event");s.debug4("Sending BRB callback: %@",i.payload),this._BRBCallback(i.payload)}else i.eventType&&"jsLogFileConfiguration"===i.eventType&&this.handleLogFileConfigEvent(i)}catch(e){s.error("handleNativeLoggingEvent %s: %s",e.name,e.message)}},e.prototype.handleLogFileConfigEvent=function(e){if(e.payload){var t=e.payload;if(t.enabled){if(t.chunkSize&&t.flushInterval){var i={chunkSize:t.chunkSize,flushInterval:t.flushInterval,enableThrottling:t.enableThrottling,maxVerbosityLevel:t.maxVerbosityLevel};this.startJsToNativeLogging(i)}}else this.flushDisableJsToNativeLogging()}},e.prototype.logExternalForDDL=function(e,t){try{if(s.debug2("logExternalForDDL %s %s",e,t),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var i={eventType:"logInSClog",payload:{message:e,parameters:t}};this._glue.sendLoggingEventToNative(JSON.stringify(i),"")}else s.warn("ignoring logExternalForDDL, delegate misconfigured")}catch(e){s.error("logExternalForDDL %s: %s",e.name,e.message)}},e.prototype.startJsToNativeLogging=function(e){var t=this,i=e.chunkSize,n=e.flushInterval,r=e.enableThrottling,a=this._getVerbosityLevelFromConfig(e.maxVerbosityLevel);if(this._jsToNativeBuffer){if(this._jsToNativeBuffer.capacity()===i&&this._jsToNativeFlushInterval===n&&this._jsToNativeBuffer.throttlingEnabled()===r&&this._jsToNativeBuffer.maxVerbosityLevel()===a)return void s.debug1("Same JS2Native settings received - doing nothing");s.debug1("Reapplying js to native settings"),this.flushDisableJsToNativeLogging()}this._jsToNativeBuffer=new S(i,(function(){t.onJsToNativeBufferReady(t._jsToNativeBuffer)}),r,a),this.setJsToNativeFlushTimeout(n),this._jsToNativeFlushInterval=n,this._jsToNativeBufferHandle=z.LogFactory.instance().addAppender(this._jsToNativeBuffer)},e.prototype._getVerbosityLevelFromConfig=function(e){return e?z.LogFactory.levelFromString(e):null},e.prototype.flushDisableJsToNativeLogging=function(){this._jsToNativeBuffer&&this.onJsToNativeBufferReady(this._jsToNativeBuffer),this.plainDisableJsToNativeLogging()},e.prototype.plainDisableJsToNativeLogging=function(){this.clearJsToNativeFlushTimeout(),this._jsToNativeBufferHandle&&(z.LogFactory.instance().removeAppender(this._jsToNativeBufferHandle),this._jsToNativeBufferHandle=0,this._jsToNativeBuffer=null,s.debug1("Disabling forwarding JS logs to native"))},e.prototype.onJsToNativeBufferReady=function(e){null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative?(this.clearJsToNativeFlushTimeout(),this.dumpJsToNativeBuffer(e),this.setJsToNativeFlushTimeout(this._jsToNativeFlushInterval)):this.plainDisableJsToNativeLogging()},e.prototype.dumpJsToNativeBuffer=function(e){if(!e.empty()){var t=e.dumpAndReset();this._glue.sendLoggingEventToNative(JSON.stringify({eventType:"writeLogData"}),t)}},e.prototype.clearJsToNativeFlushTimeout=function(){this._jsToNativeFlushTimer&&(clearTimeout(this._jsToNativeFlushTimer),this._jsToNativeFlushTimer=null)},e.prototype.setJsToNativeFlushTimeout=function(e){var t=this;!this._jsToNativeFlushTimer&&e&&(this._jsToNativeFlushTimer=setTimeout((function(){t._jsToNativeFlushTimer=null,t.onJsToNativeBufferReady(t._jsToNativeBuffer)}),e))},e.prototype.stopAsyncOperations=function(){this.flushDisableJsToNativeLogging()},e}();t.RootToolsManager=new C})),Y=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(e){return e},r=!0,s=n,a={},o=0,l=/^([0-9][0-9]?):([^<>\*\{\}&'\"\/\\?^`|~\s]+)$/;!function(e){e[e.MSA=1]="MSA",e[e.S4B_Bridge=2]="S4B_Bridge",e[e.PSTN=4]="PSTN",e[e.SkypeId=8]="SkypeId",e[e.Thread=19]="Thread",e[e.LegacyShortCircuit=20]="LegacyShortCircuit",e[e.OneToOneTextMessage=21]="OneToOneTextMessage",e[e.GroupTextMessage=22]="GroupTextMessage",e[e.Bot=28]="Bot",e[e.InternalSkype=48]="InternalSkype"}(i||(i={}));var c=[i.Thread,i.InternalSkype];t.enableAnonymization=function(e){r=e},t.useTagger=function(e){s=e||n},function(e){function t(e){return r?e?a[e]||function(e){return a[e]="u"+ ++o}(e):null:e}e.UserName=function(e){var i=t(e);return s(i)},e.Mri=function(e){var i,n=e.match(l);if(n){var r=Number(n[1]),a=n[2];i=-1!=c.indexOf(r)?e:r+":"+t(a)}else i=t(e);return s(i)},e.Omit=function(e){var t;return t=r?"number"==typeof e?19229:"string"==typeof e?e.charAt(0)+"...":null:e,s(t)}}(t.pii||(t.pii={}))})),Q=G((function(e,t){function i(e){for(var i in e)t.hasOwnProperty(i)||(t[i]=e[i])}Object.defineProperty(t,"__esModule",{value:!0}),i(q),i(z),i(J),i(K),i(Y)})),Z=G((function(e,t){(function(){var i,n="Expected a function",r="__lodash_hash_undefined__",s="__lodash_placeholder__",a=32,o=128,l=1/0,c=9007199254740991,d=NaN,u=4294967295,h=u-1,g=u>>>1,p=[["ary",o],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",a],["partialRight",64],["rearg",256]],m="[object Arguments]",f="[object Array]",v="[object Boolean]",S="[object Date]",y="[object Error]",C="[object Function]",T="[object GeneratorFunction]",E="[object Map]",b="[object Number]",_="[object Object]",I="[object Promise]",w="[object RegExp]",A="[object Set]",P="[object String]",R="[object Symbol]",M="[object WeakMap]",D="[object ArrayBuffer]",k="[object DataView]",O="[object Float32Array]",N="[object Float64Array]",L="[object Int8Array]",x="[object Int16Array]",F="[object Int32Array]",U="[object Uint8Array]",B="[object Uint8ClampedArray]",V="[object Uint16Array]",H="[object Uint32Array]",$=/\b__p \+= '';/g,G=/\b(__p \+=) '' \+/g,q=/(__e\(.*?\)|\b__t\)) \+\n'';/g,z=/&(?:amp|lt|gt|quot|#39);/g,W=/[&<>"']/g,K=RegExp(z.source),J=RegExp(W.source),Y=/<%-([\s\S]+?)%>/g,Q=/<%([\s\S]+?)%>/g,Z=/<%=([\s\S]+?)%>/g,X=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ee=/^\w*$/,te=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ie=/[\\^$.*+?()[\]{}|]/g,ne=RegExp(ie.source),re=/^\s+/,se=/\s/,ae=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,oe=/\{\n\/\* \[wrapped with (.+)\] \*/,le=/,? & /,ce=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,de=/[()=,{}\[\]\/\s]/,ue=/\\(\\)?/g,he=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ge=/\w*$/,pe=/^[-+]0x[0-9a-f]+$/i,me=/^0b[01]+$/i,fe=/^\[object .+?Constructor\]$/,ve=/^0o[0-7]+$/i,Se=/^(?:0|[1-9]\d*)$/,ye=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ce=/($^)/,Te=/['\n\r\u2028\u2029\\]/g,Ee="\\ud800-\\udfff",be="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",_e="\\u2700-\\u27bf",Ie="a-z\\xdf-\\xf6\\xf8-\\xff",we="A-Z\\xc0-\\xd6\\xd8-\\xde",Ae="\\ufe0e\\ufe0f",Pe="\\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",Re="["+Ee+"]",Me="["+Pe+"]",De="["+be+"]",ke="\\d+",Oe="["+_e+"]",Ne="["+Ie+"]",Le="[^"+Ee+Pe+ke+_e+Ie+we+"]",xe="\\ud83c[\\udffb-\\udfff]",Fe="[^"+Ee+"]",Ue="(?:\\ud83c[\\udde6-\\uddff]){2}",Be="[\\ud800-\\udbff][\\udc00-\\udfff]",Ve="["+we+"]",He="\\u200d",$e="(?:"+Ne+"|"+Le+")",je="(?:"+Ve+"|"+Le+")",Ge="(?:['](?:d|ll|m|re|s|t|ve))?",qe="(?:['](?:D|LL|M|RE|S|T|VE))?",ze="(?:"+De+"|"+xe+")?",We="["+Ae+"]?",Ke=We+ze+"(?:"+He+"(?:"+[Fe,Ue,Be].join("|")+")"+We+ze+")*",Je="(?:"+[Oe,Ue,Be].join("|")+")"+Ke,Ye="(?:"+[Fe+De+"?",De,Ue,Be,Re].join("|")+")",Qe=RegExp("[']","g"),Ze=RegExp(De,"g"),Xe=RegExp(xe+"(?="+xe+")|"+Ye+Ke,"g"),et=RegExp([Ve+"?"+Ne+"+"+Ge+"(?="+[Me,Ve,"$"].join("|")+")",je+"+"+qe+"(?="+[Me,Ve+$e,"$"].join("|")+")",Ve+"?"+$e+"+"+Ge,Ve+"+"+qe,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",ke,Je].join("|"),"g"),tt=RegExp("["+He+Ee+be+Ae+"]"),it=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,nt=["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"],rt=-1,st={};st[O]=st[N]=st[L]=st[x]=st[F]=st[U]=st[B]=st[V]=st[H]=!0,st[m]=st[f]=st[D]=st[v]=st[k]=st[S]=st[y]=st[C]=st[E]=st[b]=st[_]=st[w]=st[A]=st[P]=st[M]=!1;var at={};at[m]=at[f]=at[D]=at[k]=at[v]=at[S]=at[O]=at[N]=at[L]=at[x]=at[F]=at[E]=at[b]=at[_]=at[w]=at[A]=at[P]=at[R]=at[U]=at[B]=at[V]=at[H]=!0,at[y]=at[C]=at[M]=!1;var ot={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},lt=parseFloat,ct=parseInt,dt="object"==typeof j&&j&&j.Object===Object&&j,ut="object"==typeof self&&self&&self.Object===Object&&self,ht=dt||ut||Function("return this")(),gt=t&&!t.nodeType&&t,pt=gt&&e&&!e.nodeType&&e,mt=pt&&pt.exports===gt,ft=mt&&dt.process,vt=function(){try{return pt&&pt.require&&pt.require("util").types||ft&&ft.binding&&ft.binding("util")}catch(e){}}(),St=vt&&vt.isArrayBuffer,yt=vt&&vt.isDate,Ct=vt&&vt.isMap,Tt=vt&&vt.isRegExp,Et=vt&&vt.isSet,bt=vt&&vt.isTypedArray;function _t(e,t,i){switch(i.length){case 0:return e.call(t);case 1:return e.call(t,i[0]);case 2:return e.call(t,i[0],i[1]);case 3:return e.call(t,i[0],i[1],i[2])}return e.apply(t,i)}function It(e,t,i,n){for(var r=-1,s=null==e?0:e.length;++r<s;){var a=e[r];t(n,a,i(a),e)}return n}function wt(e,t){for(var i=-1,n=null==e?0:e.length;++i<n&&!1!==t(e[i],i,e););return e}function At(e,t){for(var i=null==e?0:e.length;i--&&!1!==t(e[i],i,e););return e}function Pt(e,t){for(var i=-1,n=null==e?0:e.length;++i<n;)if(!t(e[i],i,e))return!1;return!0}function Rt(e,t){for(var i=-1,n=null==e?0:e.length,r=0,s=[];++i<n;){var a=e[i];t(a,i,e)&&(s[r++]=a)}return s}function Mt(e,t){return!(null==e||!e.length)&&Ht(e,t,0)>-1}function Dt(e,t,i){for(var n=-1,r=null==e?0:e.length;++n<r;)if(i(t,e[n]))return!0;return!1}function kt(e,t){for(var i=-1,n=null==e?0:e.length,r=Array(n);++i<n;)r[i]=t(e[i],i,e);return r}function Ot(e,t){for(var i=-1,n=t.length,r=e.length;++i<n;)e[r+i]=t[i];return e}function Nt(e,t,i,n){var r=-1,s=null==e?0:e.length;for(n&&s&&(i=e[++r]);++r<s;)i=t(i,e[r],r,e);return i}function Lt(e,t,i,n){var r=null==e?0:e.length;for(n&&r&&(i=e[--r]);r--;)i=t(i,e[r],r,e);return i}function xt(e,t){for(var i=-1,n=null==e?0:e.length;++i<n;)if(t(e[i],i,e))return!0;return!1}var Ft=qt("length");function Ut(e){return e.match(ce)||[]}function Bt(e,t,i){var n;return i(e,(function(e,i,r){if(t(e,i,r))return n=i,!1})),n}function Vt(e,t,i,n){for(var r=e.length,s=i+(n?1:-1);n?s--:++s<r;)if(t(e[s],s,e))return s;return-1}function Ht(e,t,i){return t==t?function(e,t,i){for(var n=i-1,r=e.length;++n<r;)if(e[n]===t)return n;return-1}(e,t,i):Vt(e,jt,i)}function $t(e,t,i,n){for(var r=i-1,s=e.length;++r<s;)if(n(e[r],t))return r;return-1}function jt(e){return e!=e}function Gt(e,t){var i=null==e?0:e.length;return i?Kt(e,t)/i:d}function qt(e){return function(t){return null==t?i:t[e]}}function zt(e){return function(t){return null==e?i:e[t]}}function Wt(e,t,i,n,r){return r(e,(function(e,r,s){i=n?(n=!1,e):t(i,e,r,s)})),i}function Kt(e,t){for(var n,r=-1,s=e.length;++r<s;){var a=t(e[r]);a!==i&&(n=n===i?a:n+a)}return n}function Jt(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n}function Yt(e){return e?e.slice(0,gi(e)+1).replace(re,""):e}function Qt(e){return function(t){return e(t)}}function Zt(e,t){return kt(t,(function(t){return e[t]}))}function Xt(e,t){return e.has(t)}function ei(e,t){for(var i=-1,n=e.length;++i<n&&Ht(t,e[i],0)>-1;);return i}function ti(e,t){for(var i=e.length;i--&&Ht(t,e[i],0)>-1;);return i}var ii=zt({À:"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",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),ni=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function ri(e){return"\\"+ot[e]}function si(e){return tt.test(e)}function ai(e){return it.test(e)}function oi(e){var t=-1,i=Array(e.size);return e.forEach((function(e,n){i[++t]=[n,e]})),i}function li(e,t){return function(i){return e(t(i))}}function ci(e,t){for(var i=-1,n=e.length,r=0,a=[];++i<n;){var o=e[i];o!==t&&o!==s||(e[i]=s,a[r++]=i)}return a}function di(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}function ui(e){return si(e)?function(e){for(var t=Xe.lastIndex=0;Xe.test(e);)++t;return t}(e):Ft(e)}function hi(e){return si(e)?function(e){return e.match(Xe)||[]}(e):function(e){return e.split("")}(e)}function gi(e){for(var t=e.length;t--&&se.test(e.charAt(t)););return t}var pi=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});function mi(e){return e.match(et)||[]}var fi=function e(t){var j,se=(t=null==t?ht:fi.defaults(ht.Object(),t,fi.pick(ht,nt))).Array,ce=t.Date,Ee=t.Error,be=t.Function,_e=t.Math,Ie=t.Object,we=t.RegExp,Ae=t.String,Pe=t.TypeError,Re=se.prototype,Me=be.prototype,De=Ie.prototype,ke=t["__core-js_shared__"],Oe=Me.toString,Ne=De.hasOwnProperty,Le=0,xe=(j=/[^.]+$/.exec(ke&&ke.keys&&ke.keys.IE_PROTO||""))?"Symbol(src)_1."+j:"",Fe=De.toString,Ue=Oe.call(Ie),Be=ht._,Ve=we("^"+Oe.call(Ne).replace(ie,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),He=mt?t.Buffer:i,$e=t.Symbol,je=t.Uint8Array,Ge=He?He.allocUnsafe:i,qe=li(Ie.getPrototypeOf,Ie),ze=Ie.create,We=De.propertyIsEnumerable,Ke=Re.splice,Je=$e?$e.isConcatSpreadable:i,Ye=$e?$e.iterator:i,Xe=$e?$e.toStringTag:i,et=function(){try{var e=gs(Ie,"defineProperty");return e({},"",{}),e}catch(e){}}(),tt=t.clearTimeout!==ht.clearTimeout&&t.clearTimeout,it=ce&&ce.now!==ht.Date.now&&ce.now,ot=t.setTimeout!==ht.setTimeout&&t.setTimeout,dt=_e.ceil,ut=_e.floor,gt=Ie.getOwnPropertySymbols,pt=He?He.isBuffer:i,ft=t.isFinite,vt=Re.join,Ft=li(Ie.keys,Ie),zt=_e.max,vi=_e.min,Si=ce.now,yi=t.parseInt,Ci=_e.random,Ti=Re.reverse,Ei=gs(t,"DataView"),bi=gs(t,"Map"),_i=gs(t,"Promise"),Ii=gs(t,"Set"),wi=gs(t,"WeakMap"),Ai=gs(Ie,"create"),Pi=wi&&new wi,Ri={},Mi=Hs(Ei),Di=Hs(bi),ki=Hs(_i),Oi=Hs(Ii),Ni=Hs(wi),Li=$e?$e.prototype:i,xi=Li?Li.valueOf:i,Fi=Li?Li.toString:i;function Ui(e){if(ro(e)&&!Wa(e)&&!(e instanceof $i)){if(e instanceof Hi)return e;if(Ne.call(e,"__wrapped__"))return $s(e)}return new Hi(e)}var Bi=function(){function e(){}return function(t){if(!no(t))return{};if(ze)return ze(t);e.prototype=t;var n=new e;return e.prototype=i,n}}();function Vi(){}function Hi(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=i}function $i(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=u,this.__views__=[]}function ji(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Gi(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function qi(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function zi(e){var t=-1,i=null==e?0:e.length;for(this.__data__=new qi;++t<i;)this.add(e[t])}function Wi(e){var t=this.__data__=new Gi(e);this.size=t.size}function Ki(e,t){var i=Wa(e),n=!i&&za(e),r=!i&&!n&&Qa(e),s=!i&&!n&&!r&&go(e),a=i||n||r||s,o=a?Jt(e.length,Ae):[],l=o.length;for(var c in e)!t&&!Ne.call(e,c)||a&&("length"==c||r&&("offset"==c||"parent"==c)||s&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Cs(c,l))||o.push(c);return o}function Ji(e){var t=e.length;return t?e[Wn(0,t-1)]:i}function Yi(e,t){return Us(Pr(e),an(t,0,e.length))}function Qi(e){return Us(Pr(e))}function Zi(e,t,n){(n!==i&&!ja(e[t],n)||n===i&&!(t in e))&&rn(e,t,n)}function Xi(e,t,n){var r=e[t];Ne.call(e,t)&&ja(r,n)&&(n!==i||t in e)||rn(e,t,n)}function en(e,t){for(var i=e.length;i--;)if(ja(e[i][0],t))return i;return-1}function tn(e,t,i,n){return un(e,(function(e,r,s){t(n,e,i(e),s)})),n}function nn(e,t){return e&&Rr(t,Lo(t),e)}function rn(e,t,i){"__proto__"==t&&et?et(e,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):e[t]=i}function sn(e,t){for(var n=-1,r=t.length,s=se(r),a=null==e;++n<r;)s[n]=a?i:Mo(e,t[n]);return s}function an(e,t,n){return e==e&&(n!==i&&(e=e<=n?e:n),t!==i&&(e=e>=t?e:t)),e}function on(e,t,n,r,s,a){var o,l=1&t,c=2&t,d=4&t;if(n&&(o=s?n(e,r,s,a):n(e)),o!==i)return o;if(!no(e))return e;var u=Wa(e);if(u){if(o=function(e){var t=e.length,i=new e.constructor(t);return t&&"string"==typeof e[0]&&Ne.call(e,"index")&&(i.index=e.index,i.input=e.input),i}(e),!l)return Pr(e,o)}else{var h=fs(e),g=h==C||h==T;if(Qa(e))return Er(e,l);if(h==_||h==m||g&&!s){if(o=c||g?{}:Ss(e),!l)return c?function(e,t){return Rr(e,ms(e),t)}(e,function(e,t){return e&&Rr(t,xo(t),e)}(o,e)):function(e,t){return Rr(e,ps(e),t)}(e,nn(o,e))}else{if(!at[h])return s?e:{};o=function(e,t,i){var n=e.constructor;switch(t){case D:return br(e);case v:case S:return new n(+e);case k:return function(e,t){var i=t?br(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.byteLength)}(e,i);case O:case N:case L:case x:case F:case U:case B:case V:case H:return _r(e,i);case E:return new n;case b:case P:return new n(e);case w:return function(e){var t=new e.constructor(e.source,ge.exec(e));return t.lastIndex=e.lastIndex,t}(e);case A:return new n;case R:return function(e){return xi?Ie(xi.call(e)):{}}(e)}}(e,h,l)}}a||(a=new Wi);var p=a.get(e);if(p)return p;a.set(e,o),co(e)?e.forEach((function(i){o.add(on(i,t,n,i,e,a))})):so(e)&&e.forEach((function(i,r){o.set(r,on(i,t,n,r,e,a))}));var f=u?i:(d?c?as:ss:c?xo:Lo)(e);return wt(f||e,(function(i,r){f&&(i=e[r=i]),Xi(o,r,on(i,t,n,r,e,a))})),o}function ln(e,t,n){var r=n.length;if(null==e)return!r;for(e=Ie(e);r--;){var s=n[r],a=t[s],o=e[s];if(o===i&&!(s in e)||!a(o))return!1}return!0}function cn(e,t,r){if("function"!=typeof e)throw new Pe(n);return Ns((function(){e.apply(i,r)}),t)}function dn(e,t,i,n){var r=-1,s=Mt,a=!0,o=e.length,l=[],c=t.length;if(!o)return l;i&&(t=kt(t,Qt(i))),n?(s=Dt,a=!1):t.length>=200&&(s=Xt,a=!1,t=new zi(t));e:for(;++r<o;){var d=e[r],u=null==i?d:i(d);if(d=n||0!==d?d:0,a&&u==u){for(var h=c;h--;)if(t[h]===u)continue e;l.push(d)}else s(t,u,n)||l.push(d)}return l}Ui.templateSettings={escape:Y,evaluate:Q,interpolate:Z,variable:"",imports:{_:Ui}},Ui.prototype=Vi.prototype,Ui.prototype.constructor=Ui,Hi.prototype=Bi(Vi.prototype),Hi.prototype.constructor=Hi,$i.prototype=Bi(Vi.prototype),$i.prototype.constructor=$i,ji.prototype.clear=function(){this.__data__=Ai?Ai(null):{},this.size=0},ji.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},ji.prototype.get=function(e){var t=this.__data__;if(Ai){var n=t[e];return n===r?i:n}return Ne.call(t,e)?t[e]:i},ji.prototype.has=function(e){var t=this.__data__;return Ai?t[e]!==i:Ne.call(t,e)},ji.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ai&&t===i?r:t,this},Gi.prototype.clear=function(){this.__data__=[],this.size=0},Gi.prototype.delete=function(e){var t=this.__data__,i=en(t,e);return!(i<0||(i==t.length-1?t.pop():Ke.call(t,i,1),--this.size,0))},Gi.prototype.get=function(e){var t=this.__data__,n=en(t,e);return n<0?i:t[n][1]},Gi.prototype.has=function(e){return en(this.__data__,e)>-1},Gi.prototype.set=function(e,t){var i=this.__data__,n=en(i,e);return n<0?(++this.size,i.push([e,t])):i[n][1]=t,this},qi.prototype.clear=function(){this.size=0,this.__data__={hash:new ji,map:new(bi||Gi),string:new ji}},qi.prototype.delete=function(e){var t=us(this,e).delete(e);return this.size-=t?1:0,t},qi.prototype.get=function(e){return us(this,e).get(e)},qi.prototype.has=function(e){return us(this,e).has(e)},qi.prototype.set=function(e,t){var i=us(this,e),n=i.size;return i.set(e,t),this.size+=i.size==n?0:1,this},zi.prototype.add=zi.prototype.push=function(e){return this.__data__.set(e,r),this},zi.prototype.has=function(e){return this.__data__.has(e)},Wi.prototype.clear=function(){this.__data__=new Gi,this.size=0},Wi.prototype.delete=function(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i},Wi.prototype.get=function(e){return this.__data__.get(e)},Wi.prototype.has=function(e){return this.__data__.has(e)},Wi.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Gi){var n=i.__data__;if(!bi||n.length<199)return n.push([e,t]),this.size=++i.size,this;i=this.__data__=new qi(n)}return i.set(e,t),this.size=i.size,this};var un=kr(Cn),hn=kr(Tn,!0);function gn(e,t){var i=!0;return un(e,(function(e,n,r){return i=!!t(e,n,r)})),i}function pn(e,t,n){for(var r=-1,s=e.length;++r<s;){var a=e[r],o=t(a);if(null!=o&&(l===i?o==o&&!ho(o):n(o,l)))var l=o,c=a}return c}function mn(e,t,n,r){var s=e.length;for((n=So(n))<0&&(n=-n>s?0:s+n),(r=r===i||r>s?s:So(r))<0&&(r+=s),r=n>r?0:yo(r);n<r;)e[n++]=t;return e}function fn(e,t){var i=[];return un(e,(function(e,n,r){t(e,n,r)&&i.push(e)})),i}function vn(e,t,i,n,r){var s=-1,a=e.length;for(i||(i=ys),r||(r=[]);++s<a;){var o=e[s];t>0&&i(o)?t>1?vn(o,t-1,i,n,r):Ot(r,o):n||(r[r.length]=o)}return r}var Sn=Or(),yn=Or(!0);function Cn(e,t){return e&&Sn(e,t,Lo)}function Tn(e,t){return e&&yn(e,t,Lo)}function En(e,t){return Rt(t,(function(t){return eo(e[t])}))}function bn(e,t){for(var n=0,r=(t=Sr(t,e)).length;null!=e&&n<r;)e=e[Vs(t[n++])];return n&&n==r?e:i}function _n(e,t,i){var n=t(e);return Wa(e)?n:Ot(n,i(e))}function In(e){return null==e?e===i?"[object Undefined]":"[object Null]":Xe&&Xe in Ie(e)?function(e){var t=Ne.call(e,Xe),n=e[Xe];try{e[Xe]=i;var r=!0}catch(e){}var s=Fe.call(e);return r&&(t?e[Xe]=n:delete e[Xe]),s}(e):function(e){return Fe.call(e)}(e)}function wn(e,t){return e>t}function An(e,t){return null!=e&&Ne.call(e,t)}function Pn(e,t){return null!=e&&t in Ie(e)}function Rn(e,t,n){for(var r=n?Dt:Mt,s=e[0].length,a=e.length,o=a,l=se(a),c=1/0,d=[];o--;){var u=e[o];o&&t&&(u=kt(u,Qt(t))),c=vi(u.length,c),l[o]=!n&&(t||s>=120&&u.length>=120)?new zi(o&&u):i}u=e[0];var h=-1,g=l[0];e:for(;++h<s&&d.length<c;){var p=u[h],m=t?t(p):p;if(p=n||0!==p?p:0,!(g?Xt(g,m):r(d,m,n))){for(o=a;--o;){var f=l[o];if(!(f?Xt(f,m):r(e[o],m,n)))continue e}g&&g.push(m),d.push(p)}}return d}function Mn(e,t,n){var r=null==(e=Ms(e,t=Sr(t,e)))?e:e[Vs(Xs(t))];return null==r?i:_t(r,e,n)}function Dn(e){return ro(e)&&In(e)==m}function kn(e,t,i,n,r){return e===t||(null==e||null==t||!ro(e)&&!ro(t)?e!=e&&t!=t:function(e,t,i,n,r,s){var a=Wa(e),o=Wa(t),l=a?f:fs(e),c=o?f:fs(t),d=(l=l==m?_:l)==_,u=(c=c==m?_:c)==_,h=l==c;if(h&&Qa(e)){if(!Qa(t))return!1;a=!0,d=!1}if(h&&!d)return s||(s=new Wi),a||go(e)?is(e,t,i,n,r,s):function(e,t,i,n,r,s,a){switch(i){case k:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case D:return!(e.byteLength!=t.byteLength||!s(new je(e),new je(t)));case v:case S:case b:return ja(+e,+t);case y:return e.name==t.name&&e.message==t.message;case w:case P:return e==t+"";case E:var o=oi;case A:var l=1&n;if(o||(o=di),e.size!=t.size&&!l)return!1;var c=a.get(e);if(c)return c==t;n|=2,a.set(e,t);var d=is(o(e),o(t),n,r,s,a);return a.delete(e),d;case R:if(xi)return xi.call(e)==xi.call(t)}return!1}(e,t,l,i,n,r,s);if(!(1&i)){var g=d&&Ne.call(e,"__wrapped__"),p=u&&Ne.call(t,"__wrapped__");if(g||p){var C=g?e.value():e,T=p?t.value():t;return s||(s=new Wi),r(C,T,i,n,s)}}return!!h&&(s||(s=new Wi),ns(e,t,i,n,r,s))}(e,t,i,n,kn,r))}function On(e,t,n,r){var s=n.length,a=s,o=!r;if(null==e)return!a;for(e=Ie(e);s--;){var l=n[s];if(o&&l[2]?l[1]!==e[l[0]]:!(l[0]in e))return!1}for(;++s<a;){var c=(l=n[s])[0],d=e[c],u=l[1];if(o&&l[2]){if(d===i&&!(c in e))return!1}else{var h=new Wi;if(r)var g=r(d,u,c,e,t,h);if(!(g===i?kn(u,d,3,r,h):g))return!1}}return!0}function Nn(e){return!(!no(e)||function(e){return!!xe&&xe in e}(e))&&(eo(e)?Ve:fe).test(Hs(e))}function Ln(e){return"function"==typeof e?e:null==e?ol:"object"==typeof e?Wa(e)?Vn(e[0],e[1]):Bn(e):fl(e)}function xn(e){if(!Is(e))return Ft(e);var t=[];for(var i in Ie(e))Ne.call(e,i)&&"constructor"!=i&&t.push(i);return t}function Fn(e,t){return e<t}function Un(e,t){var i=-1,n=Ja(e)?se(e.length):[];return un(e,(function(e,r,s){n[++i]=t(e,r,s)})),n}function Bn(e){var t=hs(e);return 1==t.length&&t[0][2]?As(t[0][0],t[0][1]):function(i){return i===e||On(i,e,t)}}function Vn(e,t){return Es(e)&&ws(t)?As(Vs(e),t):function(n){var r=Mo(n,e);return r===i&&r===t?Do(n,e):kn(t,r,3)}}function Hn(e,t,n,r,s){e!==t&&Sn(t,(function(a,o){if(s||(s=new Wi),no(a))!function(e,t,n,r,s,a,o){var l=ks(e,n),c=ks(t,n),d=o.get(c);if(d)Zi(e,n,d);else{var u=a?a(l,c,n+"",e,t,o):i,h=u===i;if(h){var g=Wa(c),p=!g&&Qa(c),m=!g&&!p&&go(c);u=c,g||p||m?Wa(l)?u=l:Ya(l)?u=Pr(l):p?(h=!1,u=Er(c,!0)):m?(h=!1,u=_r(c,!0)):u=[]:oo(c)||za(c)?(u=l,za(l)?u=To(l):no(l)&&!eo(l)||(u=Ss(c))):h=!1}h&&(o.set(c,u),s(u,c,r,a,o),o.delete(c)),Zi(e,n,u)}}(e,t,o,n,Hn,r,s);else{var l=r?r(ks(e,o),a,o+"",e,t,s):i;l===i&&(l=a),Zi(e,o,l)}}),xo)}function $n(e,t){var n=e.length;if(n)return Cs(t+=t<0?n:0,n)?e[t]:i}function jn(e,t,i){t=t.length?kt(t,(function(e){return Wa(e)?function(t){return bn(t,1===e.length?e[0]:e)}:e})):[ol];var n=-1;t=kt(t,Qt(ds()));var r=Un(e,(function(e,i,r){var s=kt(t,(function(t){return t(e)}));return{criteria:s,index:++n,value:e}}));return function(e,t){var i=e.length;for(e.sort(t);i--;)e[i]=e[i].value;return e}(r,(function(e,t){return function(e,t,i){for(var n=-1,r=e.criteria,s=t.criteria,a=r.length,o=i.length;++n<a;){var l=Ir(r[n],s[n]);if(l)return n>=o?l:l*("desc"==i[n]?-1:1)}return e.index-t.index}(e,t,i)}))}function Gn(e,t,i){for(var n=-1,r=t.length,s={};++n<r;){var a=t[n],o=bn(e,a);i(o,a)&&Zn(s,Sr(a,e),o)}return s}function qn(e,t,i,n){var r=n?$t:Ht,s=-1,a=t.length,o=e;for(e===t&&(t=Pr(t)),i&&(o=kt(e,Qt(i)));++s<a;)for(var l=0,c=t[s],d=i?i(c):c;(l=r(o,d,l,n))>-1;)o!==e&&Ke.call(o,l,1),Ke.call(e,l,1);return e}function zn(e,t){for(var i=e?t.length:0,n=i-1;i--;){var r=t[i];if(i==n||r!==s){var s=r;Cs(r)?Ke.call(e,r,1):dr(e,r)}}return e}function Wn(e,t){return e+ut(Ci()*(t-e+1))}function Kn(e,t){var i="";if(!e||t<1||t>c)return i;do{t%2&&(i+=e),(t=ut(t/2))&&(e+=e)}while(t);return i}function Jn(e,t){return Ls(Rs(e,t,ol),e+"")}function Yn(e){return Ji(Go(e))}function Qn(e,t){var i=Go(e);return Us(i,an(t,0,i.length))}function Zn(e,t,n,r){if(!no(e))return e;for(var s=-1,a=(t=Sr(t,e)).length,o=a-1,l=e;null!=l&&++s<a;){var c=Vs(t[s]),d=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return e;if(s!=o){var u=l[c];(d=r?r(u,c,l):i)===i&&(d=no(u)?u:Cs(t[s+1])?[]:{})}Xi(l,c,d),l=l[c]}return e}var Xn=Pi?function(e,t){return Pi.set(e,t),e}:ol,er=et?function(e,t){return et(e,"toString",{configurable:!0,enumerable:!1,value:rl(t),writable:!0})}:ol;function tr(e){return Us(Go(e))}function ir(e,t,i){var n=-1,r=e.length;t<0&&(t=-t>r?0:r+t),(i=i>r?r:i)<0&&(i+=r),r=t>i?0:i-t>>>0,t>>>=0;for(var s=se(r);++n<r;)s[n]=e[n+t];return s}function nr(e,t){var i;return un(e,(function(e,n,r){return!(i=t(e,n,r))})),!!i}function rr(e,t,i){var n=0,r=null==e?n:e.length;if("number"==typeof t&&t==t&&r<=g){for(;n<r;){var s=n+r>>>1,a=e[s];null!==a&&!ho(a)&&(i?a<=t:a<t)?n=s+1:r=s}return r}return sr(e,t,ol,i)}function sr(e,t,n,r){var s=0,a=null==e?0:e.length;if(0===a)return 0;for(var o=(t=n(t))!=t,l=null===t,c=ho(t),d=t===i;s<a;){var u=ut((s+a)/2),g=n(e[u]),p=g!==i,m=null===g,f=g==g,v=ho(g);if(o)var S=r||f;else S=d?f&&(r||p):l?f&&p&&(r||!m):c?f&&p&&!m&&(r||!v):!m&&!v&&(r?g<=t:g<t);S?s=u+1:a=u}return vi(a,h)}function ar(e,t){for(var i=-1,n=e.length,r=0,s=[];++i<n;){var a=e[i],o=t?t(a):a;if(!i||!ja(o,l)){var l=o;s[r++]=0===a?0:a}}return s}function or(e){return"number"==typeof e?e:ho(e)?d:+e}function lr(e){if("string"==typeof e)return e;if(Wa(e))return kt(e,lr)+"";if(ho(e))return Fi?Fi.call(e):"";var t=e+"";return"0"==t&&1/e==-l?"-0":t}function cr(e,t,i){var n=-1,r=Mt,s=e.length,a=!0,o=[],l=o;if(i)a=!1,r=Dt;else if(s>=200){var c=t?null:Yr(e);if(c)return di(c);a=!1,r=Xt,l=new zi}else l=t?[]:o;e:for(;++n<s;){var d=e[n],u=t?t(d):d;if(d=i||0!==d?d:0,a&&u==u){for(var h=l.length;h--;)if(l[h]===u)continue e;t&&l.push(u),o.push(d)}else r(l,u,i)||(l!==o&&l.push(u),o.push(d))}return o}function dr(e,t){return null==(e=Ms(e,t=Sr(t,e)))||delete e[Vs(Xs(t))]}function ur(e,t,i,n){return Zn(e,t,i(bn(e,t)),n)}function hr(e,t,i,n){for(var r=e.length,s=n?r:-1;(n?s--:++s<r)&&t(e[s],s,e););return i?ir(e,n?0:s,n?s+1:r):ir(e,n?s+1:0,n?r:s)}function gr(e,t){var i=e;return i instanceof $i&&(i=i.value()),Nt(t,(function(e,t){return t.func.apply(t.thisArg,Ot([e],t.args))}),i)}function pr(e,t,i){var n=e.length;if(n<2)return n?cr(e[0]):[];for(var r=-1,s=se(n);++r<n;)for(var a=e[r],o=-1;++o<n;)o!=r&&(s[r]=dn(s[r]||a,e[o],t,i));return cr(vn(s,1),t,i)}function mr(e,t,n){for(var r=-1,s=e.length,a=t.length,o={};++r<s;){var l=r<a?t[r]:i;n(o,e[r],l)}return o}function fr(e){return Ya(e)?e:[]}function vr(e){return"function"==typeof e?e:ol}function Sr(e,t){return Wa(e)?e:Es(e,t)?[e]:Bs(Eo(e))}var yr=Jn;function Cr(e,t,n){var r=e.length;return n=n===i?r:n,!t&&n>=r?e:ir(e,t,n)}var Tr=tt||function(e){return ht.clearTimeout(e)};function Er(e,t){if(t)return e.slice();var i=e.length,n=Ge?Ge(i):new e.constructor(i);return e.copy(n),n}function br(e){var t=new e.constructor(e.byteLength);return new je(t).set(new je(e)),t}function _r(e,t){var i=t?br(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)}function Ir(e,t){if(e!==t){var n=e!==i,r=null===e,s=e==e,a=ho(e),o=t!==i,l=null===t,c=t==t,d=ho(t);if(!l&&!d&&!a&&e>t||a&&o&&c&&!l&&!d||r&&o&&c||!n&&c||!s)return 1;if(!r&&!a&&!d&&e<t||d&&n&&s&&!r&&!a||l&&n&&s||!o&&s||!c)return-1}return 0}function wr(e,t,i,n){for(var r=-1,s=e.length,a=i.length,o=-1,l=t.length,c=zt(s-a,0),d=se(l+c),u=!n;++o<l;)d[o]=t[o];for(;++r<a;)(u||r<s)&&(d[i[r]]=e[r]);for(;c--;)d[o++]=e[r++];return d}function Ar(e,t,i,n){for(var r=-1,s=e.length,a=-1,o=i.length,l=-1,c=t.length,d=zt(s-o,0),u=se(d+c),h=!n;++r<d;)u[r]=e[r];for(var g=r;++l<c;)u[g+l]=t[l];for(;++a<o;)(h||r<s)&&(u[g+i[a]]=e[r++]);return u}function Pr(e,t){var i=-1,n=e.length;for(t||(t=se(n));++i<n;)t[i]=e[i];return t}function Rr(e,t,n,r){var s=!n;n||(n={});for(var a=-1,o=t.length;++a<o;){var l=t[a],c=r?r(n[l],e[l],l,n,e):i;c===i&&(c=e[l]),s?rn(n,l,c):Xi(n,l,c)}return n}function Mr(e,t){return function(i,n){var r=Wa(i)?It:tn,s=t?t():{};return r(i,e,ds(n,2),s)}}function Dr(e){return Jn((function(t,n){var r=-1,s=n.length,a=s>1?n[s-1]:i,o=s>2?n[2]:i;for(a=e.length>3&&"function"==typeof a?(s--,a):i,o&&Ts(n[0],n[1],o)&&(a=s<3?i:a,s=1),t=Ie(t);++r<s;){var l=n[r];l&&e(t,l,r,a)}return t}))}function kr(e,t){return function(i,n){if(null==i)return i;if(!Ja(i))return e(i,n);for(var r=i.length,s=t?r:-1,a=Ie(i);(t?s--:++s<r)&&!1!==n(a[s],s,a););return i}}function Or(e){return function(t,i,n){for(var r=-1,s=Ie(t),a=n(t),o=a.length;o--;){var l=a[e?o:++r];if(!1===i(s[l],l,s))break}return t}}function Nr(e){return function(t){var n=si(t=Eo(t))?hi(t):i,r=n?n[0]:t.charAt(0),s=n?Cr(n,1).join(""):t.slice(1);return r[e]()+s}}function Lr(e){return function(t){return Nt(tl(Wo(t).replace(Qe,"")),e,"")}}function xr(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var i=Bi(e.prototype),n=e.apply(i,t);return no(n)?n:i}}function Fr(e,t,n){var r=xr(e);return function s(){for(var a=arguments.length,o=se(a),l=a,c=cs(s);l--;)o[l]=arguments[l];var d=a<3&&o[0]!==c&&o[a-1]!==c?[]:ci(o,c);return(a-=d.length)<n?Kr(e,t,Vr,s.placeholder,i,o,d,i,i,n-a):_t(this&&this!==ht&&this instanceof s?r:e,this,o)}}function Ur(e){return function(t,n,r){var s=Ie(t);if(!Ja(t)){var a=ds(n,3);t=Lo(t),n=function(e){return a(s[e],e,s)}}var o=e(t,n,r);return o>-1?s[a?t[o]:o]:i}}function Br(e){return rs((function(t){var r=t.length,s=r,a=Hi.prototype.thru;for(e&&t.reverse();s--;){var o=t[s];if("function"!=typeof o)throw new Pe(n);if(a&&!l&&"wrapper"==ls(o))var l=new Hi([],!0)}for(s=l?s:r;++s<r;){var c=ls(o=t[s]),d="wrapper"==c?os(o):i;l=d&&bs(d[0])&&424==d[1]&&!d[4].length&&1==d[9]?l[ls(d[0])].apply(l,d[3]):1==o.length&&bs(o)?l[c]():l.thru(o)}return function(){var e=arguments,i=e[0];if(l&&1==e.length&&Wa(i))return l.plant(i).value();for(var n=0,s=r?t[n].apply(this,e):i;++n<r;)s=t[n].call(this,s);return s}}))}function Vr(e,t,n,r,s,a,l,c,d,u){var h=t&o,g=1&t,p=2&t,m=24&t,f=512&t,v=p?i:xr(e);return function i(){for(var o=arguments.length,S=se(o),y=o;y--;)S[y]=arguments[y];if(m)var C=cs(i),T=function(e,t){for(var i=e.length,n=0;i--;)e[i]===t&&++n;return n}(S,C);if(r&&(S=wr(S,r,s,m)),a&&(S=Ar(S,a,l,m)),o-=T,m&&o<u){var E=ci(S,C);return Kr(e,t,Vr,i.placeholder,n,S,E,c,d,u-o)}var b=g?n:this,_=p?b[e]:e;return o=S.length,c?S=Ds(S,c):f&&o>1&&S.reverse(),h&&d<o&&(S.length=d),this&&this!==ht&&this instanceof i&&(_=v||xr(_)),_.apply(b,S)}}function Hr(e,t){return function(i,n){return function(e,t,i,n){return Cn(e,(function(e,r,s){t(n,i(e),r,s)})),n}(i,e,t(n),{})}}function $r(e,t){return function(n,r){var s;if(n===i&&r===i)return t;if(n!==i&&(s=n),r!==i){if(s===i)return r;"string"==typeof n||"string"==typeof r?(n=lr(n),r=lr(r)):(n=or(n),r=or(r)),s=e(n,r)}return s}}function jr(e){return rs((function(t){return t=kt(t,Qt(ds())),Jn((function(i){var n=this;return e(t,(function(e){return _t(e,n,i)}))}))}))}function Gr(e,t){var n=(t=t===i?" ":lr(t)).length;if(n<2)return n?Kn(t,e):t;var r=Kn(t,dt(e/ui(t)));return si(t)?Cr(hi(r),0,e).join(""):r.slice(0,e)}function qr(e,t,i,n){var r=1&t,s=xr(e);return function t(){for(var a=-1,o=arguments.length,l=-1,c=n.length,d=se(c+o),u=this&&this!==ht&&this instanceof t?s:e;++l<c;)d[l]=n[l];for(;o--;)d[l++]=arguments[++a];return _t(u,r?i:this,d)}}function zr(e){return function(t,n,r){return r&&"number"!=typeof r&&Ts(t,n,r)&&(n=r=i),t=vo(t),n===i?(n=t,t=0):n=vo(n),function(e,t,i,n){for(var r=-1,s=zt(dt((t-e)/(i||1)),0),a=se(s);s--;)a[n?s:++r]=e,e+=i;return a}(t,n,r=r===i?t<n?1:-1:vo(r),e)}}function Wr(e){return function(t,i){return"string"==typeof t&&"string"==typeof i||(t=Co(t),i=Co(i)),e(t,i)}}function Kr(e,t,n,r,s,o,l,c,d,u){var h=8&t;t|=h?a:64,4&(t&=~(h?64:a))||(t&=-4);var g=[e,t,s,h?o:i,h?l:i,h?i:o,h?i:l,c,d,u],p=n.apply(i,g);return bs(e)&&Os(p,g),p.placeholder=r,xs(p,e,t)}function Jr(e){var t=_e[e];return function(e,i){if(e=Co(e),(i=null==i?0:vi(So(i),292))&&ft(e)){var n=(Eo(e)+"e").split("e");return+((n=(Eo(t(n[0]+"e"+(+n[1]+i)))+"e").split("e"))[0]+"e"+(+n[1]-i))}return t(e)}}var Yr=Ii&&1/di(new Ii([,-0]))[1]==l?function(e){return new Ii(e)}:hl;function Qr(e){return function(t){var i=fs(t);return i==E?oi(t):i==A?function(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=[e,e]})),i}(t):function(e,t){return kt(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function Zr(e,t,r,s,o,l,c,d){var u=2&t;if(!u&&"function"!=typeof e)throw new Pe(n);var h=s?s.length:0;if(h||(t&=-97,s=o=i),c=c===i?c:zt(So(c),0),d=d===i?d:So(d),h-=o?o.length:0,64&t){var g=s,p=o;s=o=i}var m=u?i:os(e),f=[e,t,r,s,o,g,p,l,c,d];if(m&&Ps(f,m),e=f[0],t=f[1],r=f[2],s=f[3],o=f[4],!(d=f[9]=f[9]===i?u?0:e.length:zt(f[9]-h,0))&&24&t&&(t&=-25),t&&1!=t)v=8==t||16==t?Fr(e,t,d):t!=a&&33!=t||o.length?Vr.apply(i,f):qr(e,t,r,s);else var v=function(e,t,i){var n=1&t,r=xr(e);return function t(){return(this&&this!==ht&&this instanceof t?r:e).apply(n?i:this,arguments)}}(e,t,r);return xs((m?Xn:Os)(v,f),e,t)}function Xr(e,t,n,r){return e===i||ja(e,De[n])&&!Ne.call(r,n)?t:e}function es(e,t,n,r,s,a){return no(e)&&no(t)&&(a.set(t,e),Hn(e,t,i,es,a),a.delete(t)),e}function ts(e){return oo(e)?i:e}function is(e,t,n,r,s,a){var o=1&n,l=e.length,c=t.length;if(l!=c&&!(o&&c>l))return!1;var d=a.get(e),u=a.get(t);if(d&&u)return d==t&&u==e;var h=-1,g=!0,p=2&n?new zi:i;for(a.set(e,t),a.set(t,e);++h<l;){var m=e[h],f=t[h];if(r)var v=o?r(f,m,h,t,e,a):r(m,f,h,e,t,a);if(v!==i){if(v)continue;g=!1;break}if(p){if(!xt(t,(function(e,t){if(!Xt(p,t)&&(m===e||s(m,e,n,r,a)))return p.push(t)}))){g=!1;break}}else if(m!==f&&!s(m,f,n,r,a)){g=!1;break}}return a.delete(e),a.delete(t),g}function ns(e,t,n,r,s,a){var o=1&n,l=ss(e),c=l.length;if(c!=ss(t).length&&!o)return!1;for(var d=c;d--;){var u=l[d];if(!(o?u in t:Ne.call(t,u)))return!1}var h=a.get(e),g=a.get(t);if(h&&g)return h==t&&g==e;var p=!0;a.set(e,t),a.set(t,e);for(var m=o;++d<c;){var f=e[u=l[d]],v=t[u];if(r)var S=o?r(v,f,u,t,e,a):r(f,v,u,e,t,a);if(!(S===i?f===v||s(f,v,n,r,a):S)){p=!1;break}m||(m="constructor"==u)}if(p&&!m){var y=e.constructor,C=t.constructor;y==C||!("constructor"in e)||!("constructor"in t)||"function"==typeof y&&y instanceof y&&"function"==typeof C&&C instanceof C||(p=!1)}return a.delete(e),a.delete(t),p}function rs(e){return Ls(Rs(e,i,Ks),e+"")}function ss(e){return _n(e,Lo,ps)}function as(e){return _n(e,xo,ms)}var os=Pi?function(e){return Pi.get(e)}:hl;function ls(e){for(var t=e.name+"",i=Ri[t],n=Ne.call(Ri,t)?i.length:0;n--;){var r=i[n],s=r.func;if(null==s||s==e)return r.name}return t}function cs(e){return(Ne.call(Ui,"placeholder")?Ui:e).placeholder}function ds(){var e=Ui.iteratee||ll;return e=e===ll?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function us(e,t){var i=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?i["string"==typeof t?"string":"hash"]:i.map}function hs(e){for(var t=Lo(e),i=t.length;i--;){var n=t[i],r=e[n];t[i]=[n,r,ws(r)]}return t}function gs(e,t){var n=function(e,t){return null==e?i:e[t]}(e,t);return Nn(n)?n:i}var ps=gt?function(e){return null==e?[]:(e=Ie(e),Rt(gt(e),(function(t){return We.call(e,t)})))}:yl,ms=gt?function(e){for(var t=[];e;)Ot(t,ps(e)),e=qe(e);return t}:yl,fs=In;function vs(e,t,i){for(var n=-1,r=(t=Sr(t,e)).length,s=!1;++n<r;){var a=Vs(t[n]);if(!(s=null!=e&&i(e,a)))break;e=e[a]}return s||++n!=r?s:!!(r=null==e?0:e.length)&&io(r)&&Cs(a,r)&&(Wa(e)||za(e))}function Ss(e){return"function"!=typeof e.constructor||Is(e)?{}:Bi(qe(e))}function ys(e){return Wa(e)||za(e)||!!(Je&&e&&e[Je])}function Cs(e,t){var i=typeof e;return!!(t=null==t?c:t)&&("number"==i||"symbol"!=i&&Se.test(e))&&e>-1&&e%1==0&&e<t}function Ts(e,t,i){if(!no(i))return!1;var n=typeof t;return!!("number"==n?Ja(i)&&Cs(t,i.length):"string"==n&&t in i)&&ja(i[t],e)}function Es(e,t){if(Wa(e))return!1;var i=typeof e;return!("number"!=i&&"symbol"!=i&&"boolean"!=i&&null!=e&&!ho(e))||ee.test(e)||!X.test(e)||null!=t&&e in Ie(t)}function bs(e){var t=ls(e),i=Ui[t];if("function"!=typeof i||!(t in $i.prototype))return!1;if(e===i)return!0;var n=os(i);return!!n&&e===n[0]}(Ei&&fs(new Ei(new ArrayBuffer(1)))!=k||bi&&fs(new bi)!=E||_i&&fs(_i.resolve())!=I||Ii&&fs(new Ii)!=A||wi&&fs(new wi)!=M)&&(fs=function(e){var t=In(e),n=t==_?e.constructor:i,r=n?Hs(n):"";if(r)switch(r){case Mi:return k;case Di:return E;case ki:return I;case Oi:return A;case Ni:return M}return t});var _s=ke?eo:Cl;function Is(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||De)}function ws(e){return e==e&&!no(e)}function As(e,t){return function(n){return null!=n&&n[e]===t&&(t!==i||e in Ie(n))}}function Ps(e,t){var i=e[1],n=t[1],r=i|n,a=r<131,l=n==o&&8==i||n==o&&256==i&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==i;if(!a&&!l)return e;1&n&&(e[2]=t[2],r|=1&i?0:4);var c=t[3];if(c){var d=e[3];e[3]=d?wr(d,c,t[4]):c,e[4]=d?ci(e[3],s):t[4]}return(c=t[5])&&(d=e[5],e[5]=d?Ar(d,c,t[6]):c,e[6]=d?ci(e[5],s):t[6]),(c=t[7])&&(e[7]=c),n&o&&(e[8]=null==e[8]?t[8]:vi(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=r,e}function Rs(e,t,n){return t=zt(t===i?e.length-1:t,0),function(){for(var i=arguments,r=-1,s=zt(i.length-t,0),a=se(s);++r<s;)a[r]=i[t+r];r=-1;for(var o=se(t+1);++r<t;)o[r]=i[r];return o[t]=n(a),_t(e,this,o)}}function Ms(e,t){return t.length<2?e:bn(e,ir(t,0,-1))}function Ds(e,t){for(var n=e.length,r=vi(t.length,n),s=Pr(e);r--;){var a=t[r];e[r]=Cs(a,n)?s[a]:i}return e}function ks(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Os=Fs(Xn),Ns=ot||function(e,t){return ht.setTimeout(e,t)},Ls=Fs(er);function xs(e,t,i){var n=t+"";return Ls(e,function(e,t){var i=t.length;if(!i)return e;var n=i-1;return t[n]=(i>1?"& ":"")+t[n],t=t.join(i>2?", ":" "),e.replace(ae,"{\n/* [wrapped with "+t+"] */\n")}(n,function(e,t){return wt(p,(function(i){var n="_."+i[0];t&i[1]&&!Mt(e,n)&&e.push(n)})),e.sort()}(function(e){var t=e.match(oe);return t?t[1].split(le):[]}(n),i)))}function Fs(e){var t=0,n=0;return function(){var r=Si(),s=16-(r-n);if(n=r,s>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(i,arguments)}}function Us(e,t){var n=-1,r=e.length,s=r-1;for(t=t===i?r:t;++n<t;){var a=Wn(n,s),o=e[a];e[a]=e[n],e[n]=o}return e.length=t,e}var Bs=function(){var e=Fa((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(te,(function(e,i,n,r){t.push(n?r.replace(ue,"$1"):i||e)})),t}),(function(e){return 500===t.size&&t.clear(),e})),t=e.cache;return e}();function Vs(e){if("string"==typeof e||ho(e))return e;var t=e+"";return"0"==t&&1/e==-l?"-0":t}function Hs(e){if(null!=e){try{return Oe.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function $s(e){if(e instanceof $i)return e.clone();var t=new Hi(e.__wrapped__,e.__chain__);return t.__actions__=Pr(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var js=Jn((function(e,t){return Ya(e)?dn(e,vn(t,1,Ya,!0)):[]})),Gs=Jn((function(e,t){var n=Xs(t);return Ya(n)&&(n=i),Ya(e)?dn(e,vn(t,1,Ya,!0),ds(n,2)):[]})),qs=Jn((function(e,t){var n=Xs(t);return Ya(n)&&(n=i),Ya(e)?dn(e,vn(t,1,Ya,!0),i,n):[]}));function zs(e,t,i){var n=null==e?0:e.length;if(!n)return-1;var r=null==i?0:So(i);return r<0&&(r=zt(n+r,0)),Vt(e,ds(t,3),r)}function Ws(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var s=r-1;return n!==i&&(s=So(n),s=n<0?zt(r+s,0):vi(s,r-1)),Vt(e,ds(t,3),s,!0)}function Ks(e){return null!=e&&e.length?vn(e,1):[]}function Js(e){return e&&e.length?e[0]:i}var Ys=Jn((function(e){var t=kt(e,fr);return t.length&&t[0]===e[0]?Rn(t):[]})),Qs=Jn((function(e){var t=Xs(e),n=kt(e,fr);return t===Xs(n)?t=i:n.pop(),n.length&&n[0]===e[0]?Rn(n,ds(t,2)):[]})),Zs=Jn((function(e){var t=Xs(e),n=kt(e,fr);return(t="function"==typeof t?t:i)&&n.pop(),n.length&&n[0]===e[0]?Rn(n,i,t):[]}));function Xs(e){var t=null==e?0:e.length;return t?e[t-1]:i}var ea=Jn(ta);function ta(e,t){return e&&e.length&&t&&t.length?qn(e,t):e}var ia=rs((function(e,t){var i=null==e?0:e.length,n=sn(e,t);return zn(e,kt(t,(function(e){return Cs(e,i)?+e:e})).sort(Ir)),n}));function na(e){return null==e?e:Ti.call(e)}var ra=Jn((function(e){return cr(vn(e,1,Ya,!0))})),sa=Jn((function(e){var t=Xs(e);return Ya(t)&&(t=i),cr(vn(e,1,Ya,!0),ds(t,2))})),aa=Jn((function(e){var t=Xs(e);return t="function"==typeof t?t:i,cr(vn(e,1,Ya,!0),i,t)}));function oa(e){if(!e||!e.length)return[];var t=0;return e=Rt(e,(function(e){if(Ya(e))return t=zt(e.length,t),!0})),Jt(t,(function(t){return kt(e,qt(t))}))}function la(e,t){if(!e||!e.length)return[];var n=oa(e);return null==t?n:kt(n,(function(e){return _t(t,i,e)}))}var ca=Jn((function(e,t){return Ya(e)?dn(e,t):[]})),da=Jn((function(e){return pr(Rt(e,Ya))})),ua=Jn((function(e){var t=Xs(e);return Ya(t)&&(t=i),pr(Rt(e,Ya),ds(t,2))})),ha=Jn((function(e){var t=Xs(e);return t="function"==typeof t?t:i,pr(Rt(e,Ya),i,t)})),ga=Jn(oa),pa=Jn((function(e){var t=e.length,n=t>1?e[t-1]:i;return n="function"==typeof n?(e.pop(),n):i,la(e,n)}));function ma(e){var t=Ui(e);return t.__chain__=!0,t}function fa(e,t){return t(e)}var va=rs((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,s=function(t){return sn(t,e)};return!(t>1||this.__actions__.length)&&r instanceof $i&&Cs(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:fa,args:[s],thisArg:i}),new Hi(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(i),e}))):this.thru(s)})),Sa=Mr((function(e,t,i){Ne.call(e,i)?++e[i]:rn(e,i,1)})),ya=Ur(zs),Ca=Ur(Ws);function Ta(e,t){return(Wa(e)?wt:un)(e,ds(t,3))}function Ea(e,t){return(Wa(e)?At:hn)(e,ds(t,3))}var ba=Mr((function(e,t,i){Ne.call(e,i)?e[i].push(t):rn(e,i,[t])})),_a=Jn((function(e,t,i){var n=-1,r="function"==typeof t,s=Ja(e)?se(e.length):[];return un(e,(function(e){s[++n]=r?_t(t,e,i):Mn(e,t,i)})),s})),Ia=Mr((function(e,t,i){rn(e,i,t)}));function wa(e,t){return(Wa(e)?kt:Un)(e,ds(t,3))}var Aa=Mr((function(e,t,i){e[i?0:1].push(t)}),(function(){return[[],[]]})),Pa=Jn((function(e,t){if(null==e)return[];var i=t.length;return i>1&&Ts(e,t[0],t[1])?t=[]:i>2&&Ts(t[0],t[1],t[2])&&(t=[t[0]]),jn(e,vn(t,1),[])})),Ra=it||function(){return ht.Date.now()};function Ma(e,t,n){return t=n?i:t,t=e&&null==t?e.length:t,Zr(e,o,i,i,i,i,t)}function Da(e,t){var r;if("function"!=typeof t)throw new Pe(n);return e=So(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=i),r}}var ka=Jn((function(e,t,i){var n=1;if(i.length){var r=ci(i,cs(ka));n|=a}return Zr(e,n,t,i,r)})),Oa=Jn((function(e,t,i){var n=3;if(i.length){var r=ci(i,cs(Oa));n|=a}return Zr(t,n,e,i,r)}));function Na(e,t,r){var s,a,o,l,c,d,u=0,h=!1,g=!1,p=!0;if("function"!=typeof e)throw new Pe(n);function m(t){var n=s,r=a;return s=a=i,u=t,l=e.apply(r,n)}function f(e){var n=e-d;return d===i||n>=t||n<0||g&&e-u>=o}function v(){var e=Ra();if(f(e))return S(e);c=Ns(v,function(e){var i=t-(e-d);return g?vi(i,o-(e-u)):i}(e))}function S(e){return c=i,p&&s?m(e):(s=a=i,l)}function y(){var e=Ra(),n=f(e);if(s=arguments,a=this,d=e,n){if(c===i)return function(e){return u=e,c=Ns(v,t),h?m(e):l}(d);if(g)return Tr(c),c=Ns(v,t),m(d)}return c===i&&(c=Ns(v,t)),l}return t=Co(t)||0,no(r)&&(h=!!r.leading,o=(g="maxWait"in r)?zt(Co(r.maxWait)||0,t):o,p="trailing"in r?!!r.trailing:p),y.cancel=function(){c!==i&&Tr(c),u=0,s=d=a=c=i},y.flush=function(){return c===i?l:S(Ra())},y}var La=Jn((function(e,t){return cn(e,1,t)})),xa=Jn((function(e,t,i){return cn(e,Co(t)||0,i)}));function Fa(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Pe(n);var i=function(){var n=arguments,r=t?t.apply(this,n):n[0],s=i.cache;if(s.has(r))return s.get(r);var a=e.apply(this,n);return i.cache=s.set(r,a)||s,a};return i.cache=new(Fa.Cache||qi),i}function Ua(e){if("function"!=typeof e)throw new Pe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Fa.Cache=qi;var Ba=yr((function(e,t){var i=(t=1==t.length&&Wa(t[0])?kt(t[0],Qt(ds())):kt(vn(t,1),Qt(ds()))).length;return Jn((function(n){for(var r=-1,s=vi(n.length,i);++r<s;)n[r]=t[r].call(this,n[r]);return _t(e,this,n)}))})),Va=Jn((function(e,t){var n=ci(t,cs(Va));return Zr(e,a,i,t,n)})),Ha=Jn((function(e,t){var n=ci(t,cs(Ha));return Zr(e,64,i,t,n)})),$a=rs((function(e,t){return Zr(e,256,i,i,i,t)}));function ja(e,t){return e===t||e!=e&&t!=t}var Ga=Wr(wn),qa=Wr((function(e,t){return e>=t})),za=Dn(function(){return arguments}())?Dn:function(e){return ro(e)&&Ne.call(e,"callee")&&!We.call(e,"callee")},Wa=se.isArray,Ka=St?Qt(St):function(e){return ro(e)&&In(e)==D};function Ja(e){return null!=e&&io(e.length)&&!eo(e)}function Ya(e){return ro(e)&&Ja(e)}var Qa=pt||Cl,Za=yt?Qt(yt):function(e){return ro(e)&&In(e)==S};function Xa(e){if(!ro(e))return!1;var t=In(e);return t==y||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!oo(e)}function eo(e){if(!no(e))return!1;var t=In(e);return t==C||t==T||"[object AsyncFunction]"==t||"[object Proxy]"==t}function to(e){return"number"==typeof e&&e==So(e)}function io(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=c}function no(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ro(e){return null!=e&&"object"==typeof e}var so=Ct?Qt(Ct):function(e){return ro(e)&&fs(e)==E};function ao(e){return"number"==typeof e||ro(e)&&In(e)==b}function oo(e){if(!ro(e)||In(e)!=_)return!1;var t=qe(e);if(null===t)return!0;var i=Ne.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Oe.call(i)==Ue}var lo=Tt?Qt(Tt):function(e){return ro(e)&&In(e)==w},co=Et?Qt(Et):function(e){return ro(e)&&fs(e)==A};function uo(e){return"string"==typeof e||!Wa(e)&&ro(e)&&In(e)==P}function ho(e){return"symbol"==typeof e||ro(e)&&In(e)==R}var go=bt?Qt(bt):function(e){return ro(e)&&io(e.length)&&!!st[In(e)]},po=Wr(Fn),mo=Wr((function(e,t){return e<=t}));function fo(e){if(!e)return[];if(Ja(e))return uo(e)?hi(e):Pr(e);if(Ye&&e[Ye])return function(e){for(var t,i=[];!(t=e.next()).done;)i.push(t.value);return i}(e[Ye]());var t=fs(e);return(t==E?oi:t==A?di:Go)(e)}function vo(e){return e?(e=Co(e))===l||e===-l?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function So(e){var t=vo(e),i=t%1;return t==t?i?t-i:t:0}function yo(e){return e?an(So(e),0,u):0}function Co(e){if("number"==typeof e)return e;if(ho(e))return d;if(no(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=no(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Yt(e);var i=me.test(e);return i||ve.test(e)?ct(e.slice(2),i?2:8):pe.test(e)?d:+e}function To(e){return Rr(e,xo(e))}function Eo(e){return null==e?"":lr(e)}var bo=Dr((function(e,t){if(Is(t)||Ja(t))Rr(t,Lo(t),e);else for(var i in t)Ne.call(t,i)&&Xi(e,i,t[i])})),_o=Dr((function(e,t){Rr(t,xo(t),e)})),Io=Dr((function(e,t,i,n){Rr(t,xo(t),e,n)})),wo=Dr((function(e,t,i,n){Rr(t,Lo(t),e,n)})),Ao=rs(sn),Po=Jn((function(e,t){e=Ie(e);var n=-1,r=t.length,s=r>2?t[2]:i;for(s&&Ts(t[0],t[1],s)&&(r=1);++n<r;)for(var a=t[n],o=xo(a),l=-1,c=o.length;++l<c;){var d=o[l],u=e[d];(u===i||ja(u,De[d])&&!Ne.call(e,d))&&(e[d]=a[d])}return e})),Ro=Jn((function(e){return e.push(i,es),_t(Uo,i,e)}));function Mo(e,t,n){var r=null==e?i:bn(e,t);return r===i?n:r}function Do(e,t){return null!=e&&vs(e,t,Pn)}var ko=Hr((function(e,t,i){null!=t&&"function"!=typeof t.toString&&(t=Fe.call(t)),e[t]=i}),rl(ol)),Oo=Hr((function(e,t,i){null!=t&&"function"!=typeof t.toString&&(t=Fe.call(t)),Ne.call(e,t)?e[t].push(i):e[t]=[i]}),ds),No=Jn(Mn);function Lo(e){return Ja(e)?Ki(e):xn(e)}function xo(e){return Ja(e)?Ki(e,!0):function(e){if(!no(e))return function(e){var t=[];if(null!=e)for(var i in Ie(e))t.push(i);return t}(e);var t=Is(e),i=[];for(var n in e)("constructor"!=n||!t&&Ne.call(e,n))&&i.push(n);return i}(e)}var Fo=Dr((function(e,t,i){Hn(e,t,i)})),Uo=Dr((function(e,t,i,n){Hn(e,t,i,n)})),Bo=rs((function(e,t){var i={};if(null==e)return i;var n=!1;t=kt(t,(function(t){return t=Sr(t,e),n||(n=t.length>1),t})),Rr(e,as(e),i),n&&(i=on(i,7,ts));for(var r=t.length;r--;)dr(i,t[r]);return i})),Vo=rs((function(e,t){return null==e?{}:function(e,t){return Gn(e,t,(function(t,i){return Do(e,i)}))}(e,t)}));function Ho(e,t){if(null==e)return{};var i=kt(as(e),(function(e){return[e]}));return t=ds(t),Gn(e,i,(function(e,i){return t(e,i[0])}))}var $o=Qr(Lo),jo=Qr(xo);function Go(e){return null==e?[]:Zt(e,Lo(e))}var qo=Lr((function(e,t,i){return t=t.toLowerCase(),e+(i?zo(t):t)}));function zo(e){return el(Eo(e).toLowerCase())}function Wo(e){return(e=Eo(e))&&e.replace(ye,ii).replace(Ze,"")}var Ko=Lr((function(e,t,i){return e+(i?"-":"")+t.toLowerCase()})),Jo=Lr((function(e,t,i){return e+(i?" ":"")+t.toLowerCase()})),Yo=Nr("toLowerCase"),Qo=Lr((function(e,t,i){return e+(i?"_":"")+t.toLowerCase()})),Zo=Lr((function(e,t,i){return e+(i?" ":"")+el(t)})),Xo=Lr((function(e,t,i){return e+(i?" ":"")+t.toUpperCase()})),el=Nr("toUpperCase");function tl(e,t,n){return e=Eo(e),(t=n?i:t)===i?ai(e)?mi(e):Ut(e):e.match(t)||[]}var il=Jn((function(e,t){try{return _t(e,i,t)}catch(e){return Xa(e)?e:new Ee(e)}})),nl=rs((function(e,t){return wt(t,(function(t){t=Vs(t),rn(e,t,ka(e[t],e))})),e}));function rl(e){return function(){return e}}var sl=Br(),al=Br(!0);function ol(e){return e}function ll(e){return Ln("function"==typeof e?e:on(e,1))}var cl=Jn((function(e,t){return function(i){return Mn(i,e,t)}})),dl=Jn((function(e,t){return function(i){return Mn(e,i,t)}}));function ul(e,t,i){var n=Lo(t),r=En(t,n);null!=i||no(t)&&(r.length||!n.length)||(i=t,t=e,e=this,r=En(t,Lo(t)));var s=!(no(i)&&"chain"in i&&!i.chain),a=eo(e);return wt(r,(function(i){var n=t[i];e[i]=n,a&&(e.prototype[i]=function(){var t=this.__chain__;if(s||t){var i=e(this.__wrapped__);return(i.__actions__=Pr(this.__actions__)).push({func:n,args:arguments,thisArg:e}),i.__chain__=t,i}return n.apply(e,Ot([this.value()],arguments))})})),e}function hl(){}var gl=jr(kt),pl=jr(Pt),ml=jr(xt);function fl(e){return Es(e)?qt(Vs(e)):function(e){return function(t){return bn(t,e)}}(e)}var vl=zr(),Sl=zr(!0);function yl(){return[]}function Cl(){return!1}var Tl,El=$r((function(e,t){return e+t}),0),bl=Jr("ceil"),_l=$r((function(e,t){return e/t}),1),Il=Jr("floor"),wl=$r((function(e,t){return e*t}),1),Al=Jr("round"),Pl=$r((function(e,t){return e-t}),0);return Ui.after=function(e,t){if("function"!=typeof t)throw new Pe(n);return e=So(e),function(){if(--e<1)return t.apply(this,arguments)}},Ui.ary=Ma,Ui.assign=bo,Ui.assignIn=_o,Ui.assignInWith=Io,Ui.assignWith=wo,Ui.at=Ao,Ui.before=Da,Ui.bind=ka,Ui.bindAll=nl,Ui.bindKey=Oa,Ui.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Wa(e)?e:[e]},Ui.chain=ma,Ui.chunk=function(e,t,n){t=(n?Ts(e,t,n):t===i)?1:zt(So(t),0);var r=null==e?0:e.length;if(!r||t<1)return[];for(var s=0,a=0,o=se(dt(r/t));s<r;)o[a++]=ir(e,s,s+=t);return o},Ui.compact=function(e){for(var t=-1,i=null==e?0:e.length,n=0,r=[];++t<i;){var s=e[t];s&&(r[n++]=s)}return r},Ui.concat=function(){var e=arguments.length;if(!e)return[];for(var t=se(e-1),i=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Ot(Wa(i)?Pr(i):[i],vn(t,1))},Ui.cond=function(e){var t=null==e?0:e.length,i=ds();return e=t?kt(e,(function(e){if("function"!=typeof e[1])throw new Pe(n);return[i(e[0]),e[1]]})):[],Jn((function(i){for(var n=-1;++n<t;){var r=e[n];if(_t(r[0],this,i))return _t(r[1],this,i)}}))},Ui.conforms=function(e){return function(e){var t=Lo(e);return function(i){return ln(i,e,t)}}(on(e,1))},Ui.constant=rl,Ui.countBy=Sa,Ui.create=function(e,t){var i=Bi(e);return null==t?i:nn(i,t)},Ui.curry=function e(t,n,r){var s=Zr(t,8,i,i,i,i,i,n=r?i:n);return s.placeholder=e.placeholder,s},Ui.curryRight=function e(t,n,r){var s=Zr(t,16,i,i,i,i,i,n=r?i:n);return s.placeholder=e.placeholder,s},Ui.debounce=Na,Ui.defaults=Po,Ui.defaultsDeep=Ro,Ui.defer=La,Ui.delay=xa,Ui.difference=js,Ui.differenceBy=Gs,Ui.differenceWith=qs,Ui.drop=function(e,t,n){var r=null==e?0:e.length;return r?ir(e,(t=n||t===i?1:So(t))<0?0:t,r):[]},Ui.dropRight=function(e,t,n){var r=null==e?0:e.length;return r?ir(e,0,(t=r-(t=n||t===i?1:So(t)))<0?0:t):[]},Ui.dropRightWhile=function(e,t){return e&&e.length?hr(e,ds(t,3),!0,!0):[]},Ui.dropWhile=function(e,t){return e&&e.length?hr(e,ds(t,3),!0):[]},Ui.fill=function(e,t,i,n){var r=null==e?0:e.length;return r?(i&&"number"!=typeof i&&Ts(e,t,i)&&(i=0,n=r),mn(e,t,i,n)):[]},Ui.filter=function(e,t){return(Wa(e)?Rt:fn)(e,ds(t,3))},Ui.flatMap=function(e,t){return vn(wa(e,t),1)},Ui.flatMapDeep=function(e,t){return vn(wa(e,t),l)},Ui.flatMapDepth=function(e,t,n){return n=n===i?1:So(n),vn(wa(e,t),n)},Ui.flatten=Ks,Ui.flattenDeep=function(e){return null!=e&&e.length?vn(e,l):[]},Ui.flattenDepth=function(e,t){return null!=e&&e.length?vn(e,t=t===i?1:So(t)):[]},Ui.flip=function(e){return Zr(e,512)},Ui.flow=sl,Ui.flowRight=al,Ui.fromPairs=function(e){for(var t=-1,i=null==e?0:e.length,n={};++t<i;){var r=e[t];n[r[0]]=r[1]}return n},Ui.functions=function(e){return null==e?[]:En(e,Lo(e))},Ui.functionsIn=function(e){return null==e?[]:En(e,xo(e))},Ui.groupBy=ba,Ui.initial=function(e){return null!=e&&e.length?ir(e,0,-1):[]},Ui.intersection=Ys,Ui.intersectionBy=Qs,Ui.intersectionWith=Zs,Ui.invert=ko,Ui.invertBy=Oo,Ui.invokeMap=_a,Ui.iteratee=ll,Ui.keyBy=Ia,Ui.keys=Lo,Ui.keysIn=xo,Ui.map=wa,Ui.mapKeys=function(e,t){var i={};return t=ds(t,3),Cn(e,(function(e,n,r){rn(i,t(e,n,r),e)})),i},Ui.mapValues=function(e,t){var i={};return t=ds(t,3),Cn(e,(function(e,n,r){rn(i,n,t(e,n,r))})),i},Ui.matches=function(e){return Bn(on(e,1))},Ui.matchesProperty=function(e,t){return Vn(e,on(t,1))},Ui.memoize=Fa,Ui.merge=Fo,Ui.mergeWith=Uo,Ui.method=cl,Ui.methodOf=dl,Ui.mixin=ul,Ui.negate=Ua,Ui.nthArg=function(e){return e=So(e),Jn((function(t){return $n(t,e)}))},Ui.omit=Bo,Ui.omitBy=function(e,t){return Ho(e,Ua(ds(t)))},Ui.once=function(e){return Da(2,e)},Ui.orderBy=function(e,t,n,r){return null==e?[]:(Wa(t)||(t=null==t?[]:[t]),Wa(n=r?i:n)||(n=null==n?[]:[n]),jn(e,t,n))},Ui.over=gl,Ui.overArgs=Ba,Ui.overEvery=pl,Ui.overSome=ml,Ui.partial=Va,Ui.partialRight=Ha,Ui.partition=Aa,Ui.pick=Vo,Ui.pickBy=Ho,Ui.property=fl,Ui.propertyOf=function(e){return function(t){return null==e?i:bn(e,t)}},Ui.pull=ea,Ui.pullAll=ta,Ui.pullAllBy=function(e,t,i){return e&&e.length&&t&&t.length?qn(e,t,ds(i,2)):e},Ui.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?qn(e,t,i,n):e},Ui.pullAt=ia,Ui.range=vl,Ui.rangeRight=Sl,Ui.rearg=$a,Ui.reject=function(e,t){return(Wa(e)?Rt:fn)(e,Ua(ds(t,3)))},Ui.remove=function(e,t){var i=[];if(!e||!e.length)return i;var n=-1,r=[],s=e.length;for(t=ds(t,3);++n<s;){var a=e[n];t(a,n,e)&&(i.push(a),r.push(n))}return zn(e,r),i},Ui.rest=function(e,t){if("function"!=typeof e)throw new Pe(n);return Jn(e,t=t===i?t:So(t))},Ui.reverse=na,Ui.sampleSize=function(e,t,n){return t=(n?Ts(e,t,n):t===i)?1:So(t),(Wa(e)?Yi:Qn)(e,t)},Ui.set=function(e,t,i){return null==e?e:Zn(e,t,i)},Ui.setWith=function(e,t,n,r){return r="function"==typeof r?r:i,null==e?e:Zn(e,t,n,r)},Ui.shuffle=function(e){return(Wa(e)?Qi:tr)(e)},Ui.slice=function(e,t,n){var r=null==e?0:e.length;return r?(n&&"number"!=typeof n&&Ts(e,t,n)?(t=0,n=r):(t=null==t?0:So(t),n=n===i?r:So(n)),ir(e,t,n)):[]},Ui.sortBy=Pa,Ui.sortedUniq=function(e){return e&&e.length?ar(e):[]},Ui.sortedUniqBy=function(e,t){return e&&e.length?ar(e,ds(t,2)):[]},Ui.split=function(e,t,n){return n&&"number"!=typeof n&&Ts(e,t,n)&&(t=n=i),(n=n===i?u:n>>>0)?(e=Eo(e))&&("string"==typeof t||null!=t&&!lo(t))&&!(t=lr(t))&&si(e)?Cr(hi(e),0,n):e.split(t,n):[]},Ui.spread=function(e,t){if("function"!=typeof e)throw new Pe(n);return t=null==t?0:zt(So(t),0),Jn((function(i){var n=i[t],r=Cr(i,0,t);return n&&Ot(r,n),_t(e,this,r)}))},Ui.tail=function(e){var t=null==e?0:e.length;return t?ir(e,1,t):[]},Ui.take=function(e,t,n){return e&&e.length?ir(e,0,(t=n||t===i?1:So(t))<0?0:t):[]},Ui.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?ir(e,(t=r-(t=n||t===i?1:So(t)))<0?0:t,r):[]},Ui.takeRightWhile=function(e,t){return e&&e.length?hr(e,ds(t,3),!1,!0):[]},Ui.takeWhile=function(e,t){return e&&e.length?hr(e,ds(t,3)):[]},Ui.tap=function(e,t){return t(e),e},Ui.throttle=function(e,t,i){var r=!0,s=!0;if("function"!=typeof e)throw new Pe(n);return no(i)&&(r="leading"in i?!!i.leading:r,s="trailing"in i?!!i.trailing:s),Na(e,t,{leading:r,maxWait:t,trailing:s})},Ui.thru=fa,Ui.toArray=fo,Ui.toPairs=$o,Ui.toPairsIn=jo,Ui.toPath=function(e){return Wa(e)?kt(e,Vs):ho(e)?[e]:Pr(Bs(Eo(e)))},Ui.toPlainObject=To,Ui.transform=function(e,t,i){var n=Wa(e),r=n||Qa(e)||go(e);if(t=ds(t,4),null==i){var s=e&&e.constructor;i=r?n?new s:[]:no(e)&&eo(s)?Bi(qe(e)):{}}return(r?wt:Cn)(e,(function(e,n,r){return t(i,e,n,r)})),i},Ui.unary=function(e){return Ma(e,1)},Ui.union=ra,Ui.unionBy=sa,Ui.unionWith=aa,Ui.uniq=function(e){return e&&e.length?cr(e):[]},Ui.uniqBy=function(e,t){return e&&e.length?cr(e,ds(t,2)):[]},Ui.uniqWith=function(e,t){return t="function"==typeof t?t:i,e&&e.length?cr(e,i,t):[]},Ui.unset=function(e,t){return null==e||dr(e,t)},Ui.unzip=oa,Ui.unzipWith=la,Ui.update=function(e,t,i){return null==e?e:ur(e,t,vr(i))},Ui.updateWith=function(e,t,n,r){return r="function"==typeof r?r:i,null==e?e:ur(e,t,vr(n),r)},Ui.values=Go,Ui.valuesIn=function(e){return null==e?[]:Zt(e,xo(e))},Ui.without=ca,Ui.words=tl,Ui.wrap=function(e,t){return Va(vr(t),e)},Ui.xor=da,Ui.xorBy=ua,Ui.xorWith=ha,Ui.zip=ga,Ui.zipObject=function(e,t){return mr(e||[],t||[],Xi)},Ui.zipObjectDeep=function(e,t){return mr(e||[],t||[],Zn)},Ui.zipWith=pa,Ui.entries=$o,Ui.entriesIn=jo,Ui.extend=_o,Ui.extendWith=Io,ul(Ui,Ui),Ui.add=El,Ui.attempt=il,Ui.camelCase=qo,Ui.capitalize=zo,Ui.ceil=bl,Ui.clamp=function(e,t,n){return n===i&&(n=t,t=i),n!==i&&(n=(n=Co(n))==n?n:0),t!==i&&(t=(t=Co(t))==t?t:0),an(Co(e),t,n)},Ui.clone=function(e){return on(e,4)},Ui.cloneDeep=function(e){return on(e,5)},Ui.cloneDeepWith=function(e,t){return on(e,5,t="function"==typeof t?t:i)},Ui.cloneWith=function(e,t){return on(e,4,t="function"==typeof t?t:i)},Ui.conformsTo=function(e,t){return null==t||ln(e,t,Lo(t))},Ui.deburr=Wo,Ui.defaultTo=function(e,t){return null==e||e!=e?t:e},Ui.divide=_l,Ui.endsWith=function(e,t,n){e=Eo(e),t=lr(t);var r=e.length,s=n=n===i?r:an(So(n),0,r);return(n-=t.length)>=0&&e.slice(n,s)==t},Ui.eq=ja,Ui.escape=function(e){return(e=Eo(e))&&J.test(e)?e.replace(W,ni):e},Ui.escapeRegExp=function(e){return(e=Eo(e))&&ne.test(e)?e.replace(ie,"\\$&"):e},Ui.every=function(e,t,n){var r=Wa(e)?Pt:gn;return n&&Ts(e,t,n)&&(t=i),r(e,ds(t,3))},Ui.find=ya,Ui.findIndex=zs,Ui.findKey=function(e,t){return Bt(e,ds(t,3),Cn)},Ui.findLast=Ca,Ui.findLastIndex=Ws,Ui.findLastKey=function(e,t){return Bt(e,ds(t,3),Tn)},Ui.floor=Il,Ui.forEach=Ta,Ui.forEachRight=Ea,Ui.forIn=function(e,t){return null==e?e:Sn(e,ds(t,3),xo)},Ui.forInRight=function(e,t){return null==e?e:yn(e,ds(t,3),xo)},Ui.forOwn=function(e,t){return e&&Cn(e,ds(t,3))},Ui.forOwnRight=function(e,t){return e&&Tn(e,ds(t,3))},Ui.get=Mo,Ui.gt=Ga,Ui.gte=qa,Ui.has=function(e,t){return null!=e&&vs(e,t,An)},Ui.hasIn=Do,Ui.head=Js,Ui.identity=ol,Ui.includes=function(e,t,i,n){e=Ja(e)?e:Go(e),i=i&&!n?So(i):0;var r=e.length;return i<0&&(i=zt(r+i,0)),uo(e)?i<=r&&e.indexOf(t,i)>-1:!!r&&Ht(e,t,i)>-1},Ui.indexOf=function(e,t,i){var n=null==e?0:e.length;if(!n)return-1;var r=null==i?0:So(i);return r<0&&(r=zt(n+r,0)),Ht(e,t,r)},Ui.inRange=function(e,t,n){return t=vo(t),n===i?(n=t,t=0):n=vo(n),function(e,t,i){return e>=vi(t,i)&&e<zt(t,i)}(e=Co(e),t,n)},Ui.invoke=No,Ui.isArguments=za,Ui.isArray=Wa,Ui.isArrayBuffer=Ka,Ui.isArrayLike=Ja,Ui.isArrayLikeObject=Ya,Ui.isBoolean=function(e){return!0===e||!1===e||ro(e)&&In(e)==v},Ui.isBuffer=Qa,Ui.isDate=Za,Ui.isElement=function(e){return ro(e)&&1===e.nodeType&&!oo(e)},Ui.isEmpty=function(e){if(null==e)return!0;if(Ja(e)&&(Wa(e)||"string"==typeof e||"function"==typeof e.splice||Qa(e)||go(e)||za(e)))return!e.length;var t=fs(e);if(t==E||t==A)return!e.size;if(Is(e))return!xn(e).length;for(var i in e)if(Ne.call(e,i))return!1;return!0},Ui.isEqual=function(e,t){return kn(e,t)},Ui.isEqualWith=function(e,t,n){var r=(n="function"==typeof n?n:i)?n(e,t):i;return r===i?kn(e,t,i,n):!!r},Ui.isError=Xa,Ui.isFinite=function(e){return"number"==typeof e&&ft(e)},Ui.isFunction=eo,Ui.isInteger=to,Ui.isLength=io,Ui.isMap=so,Ui.isMatch=function(e,t){return e===t||On(e,t,hs(t))},Ui.isMatchWith=function(e,t,n){return n="function"==typeof n?n:i,On(e,t,hs(t),n)},Ui.isNaN=function(e){return ao(e)&&e!=+e},Ui.isNative=function(e){if(_s(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Nn(e)},Ui.isNil=function(e){return null==e},Ui.isNull=function(e){return null===e},Ui.isNumber=ao,Ui.isObject=no,Ui.isObjectLike=ro,Ui.isPlainObject=oo,Ui.isRegExp=lo,Ui.isSafeInteger=function(e){return to(e)&&e>=-c&&e<=c},Ui.isSet=co,Ui.isString=uo,Ui.isSymbol=ho,Ui.isTypedArray=go,Ui.isUndefined=function(e){return e===i},Ui.isWeakMap=function(e){return ro(e)&&fs(e)==M},Ui.isWeakSet=function(e){return ro(e)&&"[object WeakSet]"==In(e)},Ui.join=function(e,t){return null==e?"":vt.call(e,t)},Ui.kebabCase=Ko,Ui.last=Xs,Ui.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var s=r;return n!==i&&(s=(s=So(n))<0?zt(r+s,0):vi(s,r-1)),t==t?function(e,t,i){for(var n=i+1;n--;)if(e[n]===t)return n;return n}(e,t,s):Vt(e,jt,s,!0)},Ui.lowerCase=Jo,Ui.lowerFirst=Yo,Ui.lt=po,Ui.lte=mo,Ui.max=function(e){return e&&e.length?pn(e,ol,wn):i},Ui.maxBy=function(e,t){return e&&e.length?pn(e,ds(t,2),wn):i},Ui.mean=function(e){return Gt(e,ol)},Ui.meanBy=function(e,t){return Gt(e,ds(t,2))},Ui.min=function(e){return e&&e.length?pn(e,ol,Fn):i},Ui.minBy=function(e,t){return e&&e.length?pn(e,ds(t,2),Fn):i},Ui.stubArray=yl,Ui.stubFalse=Cl,Ui.stubObject=function(){return{}},Ui.stubString=function(){return""},Ui.stubTrue=function(){return!0},Ui.multiply=wl,Ui.nth=function(e,t){return e&&e.length?$n(e,So(t)):i},Ui.noConflict=function(){return ht._===this&&(ht._=Be),this},Ui.noop=hl,Ui.now=Ra,Ui.pad=function(e,t,i){e=Eo(e);var n=(t=So(t))?ui(e):0;if(!t||n>=t)return e;var r=(t-n)/2;return Gr(ut(r),i)+e+Gr(dt(r),i)},Ui.padEnd=function(e,t,i){e=Eo(e);var n=(t=So(t))?ui(e):0;return t&&n<t?e+Gr(t-n,i):e},Ui.padStart=function(e,t,i){e=Eo(e);var n=(t=So(t))?ui(e):0;return t&&n<t?Gr(t-n,i)+e:e},Ui.parseInt=function(e,t,i){return i||null==t?t=0:t&&(t=+t),yi(Eo(e).replace(re,""),t||0)},Ui.random=function(e,t,n){if(n&&"boolean"!=typeof n&&Ts(e,t,n)&&(t=n=i),n===i&&("boolean"==typeof t?(n=t,t=i):"boolean"==typeof e&&(n=e,e=i)),e===i&&t===i?(e=0,t=1):(e=vo(e),t===i?(t=e,e=0):t=vo(t)),e>t){var r=e;e=t,t=r}if(n||e%1||t%1){var s=Ci();return vi(e+s*(t-e+lt("1e-"+((s+"").length-1))),t)}return Wn(e,t)},Ui.reduce=function(e,t,i){var n=Wa(e)?Nt:Wt,r=arguments.length<3;return n(e,ds(t,4),i,r,un)},Ui.reduceRight=function(e,t,i){var n=Wa(e)?Lt:Wt,r=arguments.length<3;return n(e,ds(t,4),i,r,hn)},Ui.repeat=function(e,t,n){return t=(n?Ts(e,t,n):t===i)?1:So(t),Kn(Eo(e),t)},Ui.replace=function(){var e=arguments,t=Eo(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Ui.result=function(e,t,n){var r=-1,s=(t=Sr(t,e)).length;for(s||(s=1,e=i);++r<s;){var a=null==e?i:e[Vs(t[r])];a===i&&(r=s,a=n),e=eo(a)?a.call(e):a}return e},Ui.round=Al,Ui.runInContext=e,Ui.sample=function(e){return(Wa(e)?Ji:Yn)(e)},Ui.size=function(e){if(null==e)return 0;if(Ja(e))return uo(e)?ui(e):e.length;var t=fs(e);return t==E||t==A?e.size:xn(e).length},Ui.snakeCase=Qo,Ui.some=function(e,t,n){var r=Wa(e)?xt:nr;return n&&Ts(e,t,n)&&(t=i),r(e,ds(t,3))},Ui.sortedIndex=function(e,t){return rr(e,t)},Ui.sortedIndexBy=function(e,t,i){return sr(e,t,ds(i,2))},Ui.sortedIndexOf=function(e,t){var i=null==e?0:e.length;if(i){var n=rr(e,t);if(n<i&&ja(e[n],t))return n}return-1},Ui.sortedLastIndex=function(e,t){return rr(e,t,!0)},Ui.sortedLastIndexBy=function(e,t,i){return sr(e,t,ds(i,2),!0)},Ui.sortedLastIndexOf=function(e,t){if(null!=e&&e.length){var i=rr(e,t,!0)-1;if(ja(e[i],t))return i}return-1},Ui.startCase=Zo,Ui.startsWith=function(e,t,i){return e=Eo(e),i=null==i?0:an(So(i),0,e.length),t=lr(t),e.slice(i,i+t.length)==t},Ui.subtract=Pl,Ui.sum=function(e){return e&&e.length?Kt(e,ol):0},Ui.sumBy=function(e,t){return e&&e.length?Kt(e,ds(t,2)):0},Ui.template=function(e,t,n){var r=Ui.templateSettings;n&&Ts(e,t,n)&&(t=i),e=Eo(e),t=Io({},t,r,Xr);var s,a,o=Io({},t.imports,r.imports,Xr),l=Lo(o),c=Zt(o,l),d=0,u=t.interpolate||Ce,h="__p += '",g=we((t.escape||Ce).source+"|"+u.source+"|"+(u===Z?he:Ce).source+"|"+(t.evaluate||Ce).source+"|$","g"),p="//# sourceURL="+(Ne.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++rt+"]")+"\n";e.replace(g,(function(t,i,n,r,o,l){return n||(n=r),h+=e.slice(d,l).replace(Te,ri),i&&(s=!0,h+="' +\n__e("+i+") +\n'"),o&&(a=!0,h+="';\n"+o+";\n__p += '"),n&&(h+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),d=l+t.length,t})),h+="';\n";var m=Ne.call(t,"variable")&&t.variable;if(m){if(de.test(m))throw new Ee("Invalid `variable` option passed into `_.template`")}else h="with (obj) {\n"+h+"\n}\n";h=(a?h.replace($,""):h).replace(G,"$1").replace(q,"$1;"),h="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(s?", __e = _.escape":"")+(a?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var f=il((function(){return be(l,p+"return "+h).apply(i,c)}));if(f.source=h,Xa(f))throw f;return f},Ui.times=function(e,t){if((e=So(e))<1||e>c)return[];var i=u,n=vi(e,u);t=ds(t),e-=u;for(var r=Jt(n,t);++i<e;)t(i);return r},Ui.toFinite=vo,Ui.toInteger=So,Ui.toLength=yo,Ui.toLower=function(e){return Eo(e).toLowerCase()},Ui.toNumber=Co,Ui.toSafeInteger=function(e){return e?an(So(e),-c,c):0===e?e:0},Ui.toString=Eo,Ui.toUpper=function(e){return Eo(e).toUpperCase()},Ui.trim=function(e,t,n){if((e=Eo(e))&&(n||t===i))return Yt(e);if(!e||!(t=lr(t)))return e;var r=hi(e),s=hi(t);return Cr(r,ei(r,s),ti(r,s)+1).join("")},Ui.trimEnd=function(e,t,n){if((e=Eo(e))&&(n||t===i))return e.slice(0,gi(e)+1);if(!e||!(t=lr(t)))return e;var r=hi(e);return Cr(r,0,ti(r,hi(t))+1).join("")},Ui.trimStart=function(e,t,n){if((e=Eo(e))&&(n||t===i))return e.replace(re,"");if(!e||!(t=lr(t)))return e;var r=hi(e);return Cr(r,ei(r,hi(t))).join("")},Ui.truncate=function(e,t){var n=30,r="...";if(no(t)){var s="separator"in t?t.separator:s;n="length"in t?So(t.length):n,r="omission"in t?lr(t.omission):r}var a=(e=Eo(e)).length;if(si(e)){var o=hi(e);a=o.length}if(n>=a)return e;var l=n-ui(r);if(l<1)return r;var c=o?Cr(o,0,l).join(""):e.slice(0,l);if(s===i)return c+r;if(o&&(l+=c.length-l),lo(s)){if(e.slice(l).search(s)){var d,u=c;for(s.global||(s=we(s.source,Eo(ge.exec(s))+"g")),s.lastIndex=0;d=s.exec(u);)var h=d.index;c=c.slice(0,h===i?l:h)}}else if(e.indexOf(lr(s),l)!=l){var g=c.lastIndexOf(s);g>-1&&(c=c.slice(0,g))}return c+r},Ui.unescape=function(e){return(e=Eo(e))&&K.test(e)?e.replace(z,pi):e},Ui.uniqueId=function(e){var t=++Le;return Eo(e)+t},Ui.upperCase=Xo,Ui.upperFirst=el,Ui.each=Ta,Ui.eachRight=Ea,Ui.first=Js,ul(Ui,(Tl={},Cn(Ui,(function(e,t){Ne.call(Ui.prototype,t)||(Tl[t]=e)})),Tl),{chain:!1}),Ui.VERSION="4.17.21",wt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Ui[e].placeholder=Ui})),wt(["drop","take"],(function(e,t){$i.prototype[e]=function(n){n=n===i?1:zt(So(n),0);var r=this.__filtered__&&!t?new $i(this):this.clone();return r.__filtered__?r.__takeCount__=vi(n,r.__takeCount__):r.__views__.push({size:vi(n,u),type:e+(r.__dir__<0?"Right":"")}),r},$i.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),wt(["filter","map","takeWhile"],(function(e,t){var i=t+1,n=1==i||3==i;$i.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:ds(e,3),type:i}),t.__filtered__=t.__filtered__||n,t}})),wt(["head","last"],(function(e,t){var i="take"+(t?"Right":"");$i.prototype[e]=function(){return this[i](1).value()[0]}})),wt(["initial","tail"],(function(e,t){var i="drop"+(t?"":"Right");$i.prototype[e]=function(){return this.__filtered__?new $i(this):this[i](1)}})),$i.prototype.compact=function(){return this.filter(ol)},$i.prototype.find=function(e){return this.filter(e).head()},$i.prototype.findLast=function(e){return this.reverse().find(e)},$i.prototype.invokeMap=Jn((function(e,t){return"function"==typeof e?new $i(this):this.map((function(i){return Mn(i,e,t)}))})),$i.prototype.reject=function(e){return this.filter(Ua(ds(e)))},$i.prototype.slice=function(e,t){e=So(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $i(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==i&&(n=(t=So(t))<0?n.dropRight(-t):n.take(t-e)),n)},$i.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$i.prototype.toArray=function(){return this.take(u)},Cn($i.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),s=Ui[r?"take"+("last"==t?"Right":""):t],a=r||/^find/.test(t);s&&(Ui.prototype[t]=function(){var t=this.__wrapped__,o=r?[1]:arguments,l=t instanceof $i,c=o[0],d=l||Wa(t),u=function(e){var t=s.apply(Ui,Ot([e],o));return r&&h?t[0]:t};d&&n&&"function"==typeof c&&1!=c.length&&(l=d=!1);var h=this.__chain__,g=!!this.__actions__.length,p=a&&!h,m=l&&!g;if(!a&&d){t=m?t:new $i(this);var f=e.apply(t,o);return f.__actions__.push({func:fa,args:[u],thisArg:i}),new Hi(f,h)}return p&&m?e.apply(this,o):(f=this.thru(u),p?r?f.value()[0]:f.value():f)})})),wt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Re[e],i=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Ui.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var r=this.value();return t.apply(Wa(r)?r:[],e)}return this[i]((function(i){return t.apply(Wa(i)?i:[],e)}))}})),Cn($i.prototype,(function(e,t){var i=Ui[t];if(i){var n=i.name+"";Ne.call(Ri,n)||(Ri[n]=[]),Ri[n].push({name:t,func:i})}})),Ri[Vr(i,2).name]=[{name:"wrapper",func:i}],$i.prototype.clone=function(){var e=new $i(this.__wrapped__);return e.__actions__=Pr(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Pr(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Pr(this.__views__),e},$i.prototype.reverse=function(){if(this.__filtered__){var e=new $i(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$i.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,i=Wa(e),n=t<0,r=i?e.length:0,s=function(e,t,i){for(var n=-1,r=i.length;++n<r;){var s=i[n],a=s.size;switch(s.type){case"drop":e+=a;break;case"dropRight":t-=a;break;case"take":t=vi(t,e+a);break;case"takeRight":e=zt(e,t-a)}}return{start:e,end:t}}(0,r,this.__views__),a=s.start,o=s.end,l=o-a,c=n?o:a-1,d=this.__iteratees__,u=d.length,h=0,g=vi(l,this.__takeCount__);if(!i||!n&&r==l&&g==l)return gr(e,this.__actions__);var p=[];e:for(;l--&&h<g;){for(var m=-1,f=e[c+=t];++m<u;){var v=d[m],S=v.iteratee,y=v.type,C=S(f);if(2==y)f=C;else if(!C){if(1==y)continue e;break e}}p[h++]=f}return p},Ui.prototype.at=va,Ui.prototype.chain=function(){return ma(this)},Ui.prototype.commit=function(){return new Hi(this.value(),this.__chain__)},Ui.prototype.next=function(){this.__values__===i&&(this.__values__=fo(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?i:this.__values__[this.__index__++]}},Ui.prototype.plant=function(e){for(var t,n=this;n instanceof Vi;){var r=$s(n);r.__index__=0,r.__values__=i,t?s.__wrapped__=r:t=r;var s=r;n=n.__wrapped__}return s.__wrapped__=e,t},Ui.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $i){var t=e;return this.__actions__.length&&(t=new $i(this)),(t=t.reverse()).__actions__.push({func:fa,args:[na],thisArg:i}),new Hi(t,this.__chain__)}return this.thru(na)},Ui.prototype.toJSON=Ui.prototype.valueOf=Ui.prototype.value=function(){return gr(this.__wrapped__,this.__actions__)},Ui.prototype.first=Ui.prototype.head,Ye&&(Ui.prototype[Ye]=function(){return this}),Ui}();pt?((pt.exports=fi)._=fi,gt._=fi):ht._=fi}).call(j)})),X=G((function(e,t){var i=window;!function(t,i){e.exports=i()}(0,((e,t)=>{var n={},r={exports:n},s=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,c=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[l(e)[0]])((t={exports:{}}).exports,t),t.exports},h=(e,t)=>{for(var i in t)a(e,i,{get:t[i],enumerable:!0})},g=(e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of l(t))d.call(e,r)||r===i||a(e,r,{get:()=>t[r],enumerable:!(n=o(t,r))||n.enumerable});return e},p=(e,t,i)=>(i=null!=e?s(c(e)):{},g(!t&&e&&e.__esModule?i:a(i,"default",{value:e,enumerable:!0}),e)),m=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?o(t,i):t,l=e.length-1;l>=0;l--)(r=e[l])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&a(t,i,s),s},f=(e,t)=>(i,n)=>t(i,n,e),v=u({"../node_modules/axios/lib/helpers/bind.js"(e,t){t.exports=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}}}}),S=u({"../node_modules/axios/lib/utils.js"(e,t){var i=v(),n=Object.prototype.toString;function r(e){return"[object Array]"===n.call(e)}function s(e){return void 0===e}function a(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===n.call(e)}function l(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),r(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}t.exports={isArray:r,isArrayBuffer:function(e){return"[object ArrayBuffer]"===n.call(e)},isBuffer:function(e){return null!==e&&!s(e)&&null!==e.constructor&&!s(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:a,isUndefined:s,isDate:function(e){return"[object Date]"===n.call(e)},isFile:function(e){return"[object File]"===n.call(e)},isBlob:function(e){return"[object Blob]"===n.call(e)},isFunction:o,isStream:function(e){return a(e)&&o(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:l,merge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]=i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},deepMerge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]="object"==typeof i?e({},i):i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},extend:function(e,t,n){return l(t,(function(t,r){e[r]=n&&"function"==typeof t?i(t,n):t})),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}}}}),y=u({"../node_modules/axios/lib/helpers/buildURL.js"(e,t){var i=S();function n(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(e,t,r){if(!t)return e;var s;if(r)s=r(t);else if(i.isURLSearchParams(t))s=t.toString();else{var a=[];i.forEach(t,(function(e,t){null!=e&&(i.isArray(e)?t+="[]":e=[e],i.forEach(e,(function(e){i.isDate(e)?e=e.toISOString():i.isObject(e)&&(e=JSON.stringify(e)),a.push(n(t)+"="+n(e))})))})),s=a.join("&")}if(s){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}}}),C=u({"../node_modules/axios/lib/core/InterceptorManager.js"(e,t){var i=S();function n(){this.handlers=[]}n.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},n.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},n.prototype.forEach=function(e){i.forEach(this.handlers,(function(t){null!==t&&e(t)}))},t.exports=n}}),T=u({"../node_modules/axios/lib/core/transformData.js"(e,t){var i=S();t.exports=function(e,t,n){return i.forEach(n,(function(i){e=i(e,t)})),e}}}),E=u({"../node_modules/axios/lib/cancel/isCancel.js"(e,t){t.exports=function(e){return!(!e||!e.__CANCEL__)}}}),b=u({"../node_modules/axios/lib/helpers/normalizeHeaderName.js"(e,t){var i=S();t.exports=function(e,t){i.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))}}}),_=u({"../node_modules/axios/lib/core/enhanceError.js"(e,t){t.exports=function(e,t,i,n,r){return e.config=t,i&&(e.code=i),e.request=n,e.response=r,e.isAxiosError=!0,e.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}},e}}}),I=u({"../node_modules/axios/lib/core/createError.js"(e,t){var i=_();t.exports=function(e,t,n,r,s){var a=new Error(e);return i(a,t,n,r,s)}}}),w=u({"../node_modules/axios/lib/core/settle.js"(e,t){var i=I();t.exports=function(e,t,n){var r=n.config.validateStatus;!r||r(n.status)?e(n):t(i("Request failed with status code "+n.status,n.config,null,n.request,n))}}}),A=u({"../node_modules/axios/lib/helpers/isAbsoluteURL.js"(e,t){t.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}}}),P=u({"../node_modules/axios/lib/helpers/combineURLs.js"(e,t){t.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}}}),R=u({"../node_modules/axios/lib/core/buildFullPath.js"(e,t){var i=A(),n=P();t.exports=function(e,t){return e&&!i(t)?n(e,t):t}}}),M=u({"../node_modules/axios/lib/helpers/parseHeaders.js"(e,t){var i=S(),n=["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"];t.exports=function(e){var t,r,s,a={};return e?(i.forEach(e.split("\n"),(function(e){if(s=e.indexOf(":"),t=i.trim(e.substr(0,s)).toLowerCase(),r=i.trim(e.substr(s+1)),t){if(a[t]&&n.indexOf(t)>=0)return;a[t]="set-cookie"===t?(a[t]?a[t]:[]).concat([r]):a[t]?a[t]+", "+r:r}})),a):a}}}),D=u({"../node_modules/axios/lib/helpers/isValidXss.js"(e,t){t.exports=function(e){return/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi.test(e)}}}),k=u({"../node_modules/axios/lib/helpers/isURLSameOrigin.js"(e,t){var i=S(),n=D();t.exports=i.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function s(e){var i=e;if(n(e))throw new Error("URL contains XSS injection attempt");return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=s(window.location.href),function(t){var n=i.isString(t)?s(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}}}),O=u({"../node_modules/axios/lib/helpers/cookies.js"(e,t){var i=S();t.exports=i.isStandardBrowserEnv()?{write:function(e,t,n,r,s,a){var o=[];o.push(e+"="+encodeURIComponent(t)),i.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),i.isString(r)&&o.push("path="+r),i.isString(s)&&o.push("domain="+s),!0===a&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}}),N=u({"../node_modules/axios/lib/adapters/xhr.js"(e,t){var i=S(),n=w(),r=y(),s=R(),a=M(),o=k(),l=I();t.exports=function(e){return new Promise((function(t,c){var d=e.data,u=e.headers;i.isFormData(d)&&delete u["Content-Type"];var h=new XMLHttpRequest;if(e.auth){var g=e.auth.username||"",p=e.auth.password||"";u.Authorization="Basic "+btoa(g+":"+p)}var m=s(e.baseURL,e.url);if(h.open(e.method.toUpperCase(),r(m,e.params,e.paramsSerializer),!0),h.timeout=e.timeout,h.onreadystatechange=function(){if(h&&4===h.readyState&&(0!==h.status||h.responseURL&&0===h.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in h?a(h.getAllResponseHeaders()):null,r={data:e.responseType&&"text"!==e.responseType?h.response:h.responseText,status:h.status,statusText:h.statusText,headers:i,config:e,request:h};n(t,c,r),h=null}},h.onabort=function(){h&&(c(l("Request aborted",e,"ECONNABORTED",h)),h=null)},h.onerror=function(){c(l("Network Error",e,null,h)),h=null},h.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),c(l(t,e,"ECONNABORTED",h)),h=null},i.isStandardBrowserEnv()){var f=O(),v=(e.withCredentials||o(m))&&e.xsrfCookieName?f.read(e.xsrfCookieName):void 0;v&&(u[e.xsrfHeaderName]=v)}if("setRequestHeader"in h&&i.forEach(u,(function(e,t){void 0===d&&"content-type"===t.toLowerCase()?delete u[t]:h.setRequestHeader(t,e)})),i.isUndefined(e.withCredentials)||(h.withCredentials=!!e.withCredentials),e.responseType)try{h.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&h.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&h.upload&&h.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){h&&(h.abort(),c(e),h=null)})),void 0===d&&(d=null),h.send(d)}))}}}),L=u({"../node_modules/axios/lib/defaults.js"(e,t){var i=S(),n=b(),r={"Content-Type":"application/x-www-form-urlencoded"};function s(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var a={adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=N()),e}(),transformRequest:[function(e,t){return n(t,"Accept"),n(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(s(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(s(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};i.forEach(["delete","get","head"],(function(e){a.headers[e]={}})),i.forEach(["post","put","patch"],(function(e){a.headers[e]=i.merge(r)})),t.exports=a}}),x=u({"../node_modules/axios/lib/core/dispatchRequest.js"(e,t){var i=S(),n=T(),r=E(),s=L();function a(e){e.cancelToken&&e.cancelToken.throwIfRequested()}t.exports=function(e){return a(e),e.headers=e.headers||{},e.data=n(e.data,e.headers,e.transformRequest),e.headers=i.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),i.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||s.adapter)(e).then((function(t){return a(e),t.data=n(t.data,t.headers,e.transformResponse),t}),(function(t){return r(t)||(a(e),t&&t.response&&(t.response.data=n(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))}}}),F=u({"../node_modules/axios/lib/core/mergeConfig.js"(e,t){var i=S();t.exports=function(e,t){t=t||{};var n={},r=["url","method","params","data"],s=["headers","auth","proxy"],a=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];i.forEach(r,(function(e){void 0!==t[e]&&(n[e]=t[e])})),i.forEach(s,(function(r){i.isObject(t[r])?n[r]=i.deepMerge(e[r],t[r]):void 0!==t[r]?n[r]=t[r]:i.isObject(e[r])?n[r]=i.deepMerge(e[r]):void 0!==e[r]&&(n[r]=e[r])})),i.forEach(a,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])}));var o=r.concat(s).concat(a),l=Object.keys(t).filter((function(e){return-1===o.indexOf(e)}));return i.forEach(l,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])})),n}}}),U=u({"../node_modules/axios/lib/core/Axios.js"(e,t){var i=S(),n=y(),r=C(),s=x(),a=F();function o(e){this.defaults=e,this.interceptors={request:new r,response:new r}}o.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=a(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=[s,void 0],i=Promise.resolve(e);for(this.interceptors.request.forEach((function(e){t.unshift(e.fulfilled,e.rejected)})),this.interceptors.response.forEach((function(e){t.push(e.fulfilled,e.rejected)}));t.length;)i=i.then(t.shift(),t.shift());return i},o.prototype.getUri=function(e){return e=a(this.defaults,e),n(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},i.forEach(["delete","get","head","options"],(function(e){o.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}})),i.forEach(["post","put","patch"],(function(e){o.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}})),t.exports=o}}),B=u({"../node_modules/axios/lib/cancel/Cancel.js"(e,t){function i(e){this.message=e}i.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},i.prototype.__CANCEL__=!0,t.exports=i}}),V=u({"../node_modules/axios/lib/cancel/CancelToken.js"(e,t){var i=B();function n(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;e((function(e){n.reason||(n.reason=new i(e),t(n.reason))}))}n.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},n.source=function(){var e;return{token:new n((function(t){e=t})),cancel:e}},t.exports=n}}),H=u({"../node_modules/axios/lib/helpers/spread.js"(e,t){t.exports=function(e){return function(t){return e.apply(null,t)}}}}),$=u({"../node_modules/axios/lib/axios.js"(e,t){var i=S(),n=v(),r=U(),s=F();function a(e){var t=new r(e),s=n(r.prototype.request,t);return i.extend(s,r.prototype,t),i.extend(s,t),s}var o=a(L());o.Axios=r,o.create=function(e){return a(s(o.defaults,e))},o.Cancel=B(),o.CancelToken=V(),o.isCancel=E(),o.all=function(e){return Promise.all(e)},o.spread=H(),t.exports=o,t.exports.default=o}}),j=u({"../node_modules/axios/index.js"(e,t){t.exports=$()}}),G=u({"../node_modules/ua-parser-js/src/ua-parser.js"(e,t){!function(i,n){var r="function",s="undefined",a="object",o="string",l="major",c="model",d="name",u="type",h="vendor",g="version",p="architecture",m="console",f="mobile",v="tablet",S="smarttv",y="wearable",C="embedded",T="Amazon",E="Apple",b="ASUS",_="BlackBerry",I="Browser",w="Chrome",A="Firefox",P="Google",R="Huawei",M="LG",D="Microsoft",k="Motorola",O="Opera",N="Samsung",L="Sharp",x="Sony",F="Xiaomi",U="Zebra",B="Facebook",V="Chromium OS",H="Mac OS",$=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},j=function(e,t){return typeof e===o&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},q=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},z=function(e,t){for(var i,s,o,l,c,d,u=0;u<t.length&&!c;){var h=t[u],g=t[u+1];for(i=s=0;i<h.length&&!c&&h[i];)if(c=h[i++].exec(e))for(o=0;o<g.length;o++)d=c[++s],typeof(l=g[o])===a&&l.length>0?2===l.length?typeof l[1]==r?this[l[0]]=l[1].call(this,d):this[l[0]]=l[1]:3===l.length?typeof l[1]!==r||l[1].exec&&l[1].test?this[l[0]]=d?d.replace(l[1],l[2]):n:this[l[0]]=d?l[1].call(this,d,l[2]):n:4===l.length&&(this[l[0]]=d?l[3].call(this,d.replace(l[1],l[2])):n):this[l]=d||n;u+=2}},W=function(e,t){for(var i in t)if(typeof t[i]===a&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(j(t[i][r],e))return"?"===i?n:i}else if(j(t[i],e))return"?"===i?n:i;return e},K={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"},J={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,g],[/opios[\/ ]+([\w\.]+)/i],[g,[d,O+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[g,[d,O+" GX"]],[/\bopr\/([\w\.]+)/i],[g,[d,O]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[g,[d,"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],[d,g],[/\bddg\/([\w\.]+)/i],[g,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[g,[d,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[g,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[g,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[g,[d,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+I],g],[/\bfocus\/([\w\.]+)/i],[g,[d,A+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[d,O+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[d,O+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[d,"MIUI "+I]],[/fxios\/([-\w\.]+)/i],[g,[d,A]],[/\bqihu|(qi?ho?o?|360)browser/i],[[d,"360 "+I]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1 "+I],g],[/samsungbrowser\/([\w\.]+)/i],[g,[d,N+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[d,/_/g," "],g],[/metasr[\/ ]?([\d\.]+)/i],[g,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[d,g],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,B],g],[/(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],[d,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[g,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[d,w+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,w+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[d,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,g],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[g,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[g,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[g,W,{"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],[d,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[d,A+" 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],[d,g],[/(cobalt)\/([\w\.]+)/i],[d,[g,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,G]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,G]]],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],[c,[h,N],[u,v]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[c,[h,N],[u,f]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[c,[h,E],[u,f]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[c,[h,E],[u,v]],[/(macintosh);/i],[c,[h,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[c,[h,L],[u,f]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[c,[h,R],[u,v]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[c,[h,R],[u,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],[[c,/_/g," "],[h,F],[u,f]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[c,/_/g," "],[h,F],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[c,[h,"OPPO"],[u,f]],[/\b(opd2\d{3}a?) bui/i],[c,[h,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[c,[h,"Vivo"],[u,f]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[c,[h,"Realme"],[u,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],[c,[h,k],[u,f]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[c,[h,k],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[c,[h,M],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[c,[h,M],[u,f]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[c,[h,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[c,/_/g," "],[h,"Nokia"],[u,f]],[/(pixel c)\b/i],[c,[h,P],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[c,[h,P],[u,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],[c,[h,x],[u,f]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[c,"Xperia Tablet"],[h,x],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[c,[h,"OnePlus"],[u,f]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[c,[h,T],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[c,/(.+)/g,"Fire Phone $1"],[h,T],[u,f]],[/(playbook);[-\w\),; ]+(rim)/i],[c,h,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[c,[h,_],[u,f]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[c,[h,b],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[c,[h,b],[u,f]],[/(nexus 9)/i],[c,[h,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[c,/_/g," "],[u,f]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[c,[h,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[c,[h,"Meizu"],[u,f]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[c,[h,"Ulefone"],[u,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],[h,c,[u,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],[h,c,[u,v]],[/(surface duo)/i],[c,[h,D],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[c,[h,"Fairphone"],[u,f]],[/(u304aa)/i],[c,[h,"AT&T"],[u,f]],[/\bsie-(\w*)/i],[c,[h,"Siemens"],[u,f]],[/\b(rct\w+) b/i],[c,[h,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[c,[h,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[c,[h,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[c,[h,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[c,[h,"NuVision"],[u,v]],[/\b(k88) b/i],[c,[h,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[c,[h,"ZTE"],[u,f]],[/\b(gen\d{3}) b.+49h/i],[c,[h,"Swiss"],[u,f]],[/\b(zur\d{3}) b/i],[c,[h,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[c,[h,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],c,[u,v]],[/\b(ns-?\w{0,9}) b/i],[c,[h,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[c,[h,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],c,[u,f]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],c,[u,f]],[/\b(ph-1) /i],[c,[h,"Essential"],[u,f]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[c,[h,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[c,[h,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[c,[h,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[c,[h,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[h,c,[u,f]],[/(kin\.[onetw]{3})/i],[[c,/\./g," "],[h,D],[u,f]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[c,[h,U],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[c,[h,U],[u,f]],[/smart-tv.+(samsung)/i],[h,[u,S]],[/hbbtv.+maple;(\d+)/i],[[c,/^/,"SmartTV"],[h,N],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,M],[u,S]],[/(apple) ?tv/i],[h,[c,E+" TV"],[u,S]],[/crkey/i],[[c,w+"cast"],[h,P],[u,S]],[/droid.+aft(\w+)( bui|\))/i],[c,[h,T],[u,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[c,[h,L],[u,S]],[/(bravia[\w ]+)( bui|\))/i],[c,[h,x],[u,S]],[/(mitv-\w{5}) bui/i],[c,[h,F],[u,S]],[/Hbbtv.*(technisat) (.*);/i],[h,c,[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,q],[c,q],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,c,[u,m]],[/droid.+; (shield) bui/i],[c,[h,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[c,[h,x],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[c,[h,D],[u,m]],[/((pebble))app/i],[h,c,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[c,[h,E],[u,y]],[/droid.+; (glass) \d/i],[c,[h,P],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[c,[h,U],[u,y]],[/(quest( \d| pro)?)/i],[c,[h,B],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,C]],[/(aeobc)\b/i],[c,[h,T],[u,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[c,[u,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[c,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,f]],[/(android[-\w\. ]{0,9});.+buil/i],[c,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[d,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[d,"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],[d,g],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,g],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[g,W,K]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,W,K],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,H],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[g,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,g],[/\(bb(10);/i],[g,[d,_]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[g,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[g,[d,A+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[g,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[g,[d,w+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,V],g],[/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],[d,g],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],g],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,g]]},Y=function(e,t){if(typeof e===a&&(t=e,e=n),!(this instanceof Y))return new Y(e,t).getResult();var m=typeof i!==s&&i.navigator?i.navigator:n,S=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:n,C=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(J,t):J,T=m&&m.userAgent==S;return this.getBrowser=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.browser),e[l]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[g]),T&&m&&m.brave&&typeof m.brave.isBrave==r&&(e[d]="Brave"),e},this.getCPU=function(){var e={};return e[p]=n,z.call(e,S,C.cpu),e},this.getDevice=function(){var e={};return e[h]=n,e[c]=n,e[u]=n,z.call(e,S,C.device),T&&!e[u]&&y&&y.mobile&&(e[u]=f),T&&"Macintosh"==e[c]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[c]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.engine),e},this.getOS=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.os),T&&!e[d]&&y&&y.platform&&"Unknown"!=y.platform&&(e[d]=y.platform.replace(/chrome os/i,V).replace(/macos/i,H)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=typeof e===o&&e.length>500?q(e,500):e,this},this.setUA(S),this};Y.VERSION="1.0.38",Y.BROWSER=$([d,g,l]),Y.CPU=$([p]),Y.DEVICE=$([c,h,u,m,f,S,v,y,C]),Y.ENGINE=Y.OS=$([d,g]),typeof e!==s?(typeof t!==s&&t.exports&&(e=t.exports=Y),e.UAParser=Y):typeof i!==s&&(i.UAParser=Y);var Q=typeof i!==s&&(i.jQuery||i.Zepto);if(Q&&!Q.ua){var Z=new Y;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:e)}}),q=u({"../node_modules/@skype/hydra_player_sdk/hydra_player_sdk_bundle.js"(e,t){var i,n;i=e,n=function(){return e={103:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(){var e,t;return{promise:new Promise((function(i,n){e=i,t=n})),resolve:e,reject:t}}},457:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.iframeConfigDefault=void 0,t.iframeConfigDefault={scriptSrcDownload:!1,allowSameOrigin:!1}},1:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.liveStreamStatisticConfigDefault=void 0,t.liveStreamStatisticConfigDefault={maxUserInitiatedEventCount:100}},318:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.logSupportedCodecsConfigDefault=void 0,t.logSupportedCodecsConfigDefault={logSupportedCodecs:!1}},508:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.webRtcIceCandidateCollectorConfigDefault=void 0,t.webRtcIceCandidateCollectorConfigDefault={WebRtcIceCandidateCollectorDelayAfterCompleteMs:2500,WebRtcIceCandidateCollectorDelayAfterErrorMs:1e3,WebRtcIceCandidateCollectorMaxRetriesMs:5,WebRtcIceCandidateCollectorRetryDelayMs:100,WebRtcIceCandidateCollectorMaxCollectionTimeMs:6e4,WebRtcIceCandidateCollectorDisableCollection:!1}},10:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}},171:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},a=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LiveStreamStatistic=t.PlayerScenario=void 0;var o=i(346),l=i(963),c=i(1),d=i(534),u=i(318),h=function(){function e(e,t,i){this.name=e,this.details=t,this.failReason=i,this.timeStamp=Date.now()}return e.prototype.getName=function(){return this.name},e.prototype.getFailReason=function(){return this.failReason},e.prototype.getDetails=function(){return this.details},e.prototype.getTimeStamp=function(){return this.timeStamp},e}();t.PlayerScenario=h;var g=function(){function e(e,t,i,n){this.config=e,this.logFn=t,this.playerDiagnosticsLog=i,this.playerMetadata=n,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=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=e.maxPlayerExperimentalEvents||100,this.maxUserInitiatedEventCount=d.getECSSetting(this.config,"maxUserInitiatedEventCount",c.liveStreamStatisticConfigDefault.maxUserInitiatedEventCount),this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener(),d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs)&&this.populateSupportedCodecs()}return e.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e.prototype.setHydraInitResult=function(e){this.hydraInitResult=e},e.prototype.registerStatsUpdated=function(e){var t=this;this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((function(i){var n,r=i,s=null!==(n=t.playerDiagnosticsLog[i])&&void 0!==n?n:[];if(Array.isArray(s)){s.push(e[r]);var a="memoryLog"===r&&s.length>t.maxPlayerMemoryTraceLogCount,o="memoryLog"!==r&&s.length>t.maxPlayerDiagnosticsCount;(a||o)&&s.splice(0,1)}else t.playerDiagnosticsLog[i]=e[r]}))},e.prototype.registerEventLoadAttempt=function(e,t){this.registerScenario(e,t)},e.prototype.registerEventLoadFailed=function(e,t){this.completeScenario(e,t)},e.prototype.registerEventLoadSucceeded=function(e,t){this.completeScenario(e,void 0,t),e===l.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e.prototype.registerSdnPluginLoadAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginLoad,void 0,e)},e.prototype.registerSdnPluginInitializeAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginInitialize,e)},e.prototype.registerSdnPluginInitializeFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginInitialize,e)},e.prototype.registerSdnPluginInitializeSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginInitialize,void 0,e)},e.prototype.registerSdnPluginSetSourceAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginSetSource,e)},e.prototype.registerSdnPluginSetSourceFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginSetSource,e)},e.prototype.registerSdnPluginSetSourceSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginSetSource,void 0,e)},e.prototype.registerStreamConnectionAttempt=function(e){this.registerScenario(l.PlayerScenarioType.StreamConnection,{streamUrl:e})},e.prototype.registerStreamConnectionSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.StreamConnection,void 0,{result:d.stringifyObject(e)})},e.prototype.registerStreamConnectionFailed=function(e,t){this.completeScenario(l.PlayerScenarioType.StreamConnection,e,{result:d.stringifyObject(t)})},e.prototype.registerSetSourceAttempt=function(e,t,i){var n=e||"";i&&(n={src:e||"",isPrimary:d.stringifyObject(t),reason:i}),this.registerScenario(l.PlayerScenarioType.SetSource,n)},e.prototype.registerSetSourceSucceeded=function(e,t,i,n,r){this.completeScenario(l.PlayerScenarioType.SetSource,void 0,{src:e,isPrimary:d.stringifyObject(t),switchingDiagnostics:d.stringifyObject(i),stepDuration:d.stringifyObject(n),initialSeekToLiveEdge:d.stringifyObject(r)})},e.prototype.registerSetSourceFailed=function(e,t,i,n,r){this.completeScenario(l.PlayerScenarioType.SetSource,e,{src:d.stringifyObject(t),isPrimary:d.stringifyObject(i),switchingDiagnostics:d.stringifyObject(n),stepDuration:d.stringifyObject(r)})},e.prototype.registerPlayerDestroyed=function(e){this.registerScenario(l.PlayerScenarioType.Destroyed,e),this.completeScenario(l.PlayerScenarioType.Destroyed)},e.prototype.registerPlaybackStateChanged=function(e,t){var i,n,r,s,a,c;if(e!==o.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp){if(e===o.HydraPlayerPlaybackState.Playing){if(this.firstPlayingState||(this.firstPlayingState={timestamp:Date.now()},t&&(t.edgeLatency&&(this.firstPlayingState.edgeLatency=t.edgeLatency),t.bufferLength&&(this.firstPlayingState.bufferLength=t.bufferLength))),this.userInitiatedSeekEvents.length>0){var d=this.userInitiatedSeekEvents[this.userInitiatedSeekEvents.length-1];this.modifyTelemetryEventPayload(d,{playingStatePosition:null!==(n=null===(i=this.currentPlayerDiagnosticSnapshot)||void 0===i?void 0:i.currentPlayPosition)&&void 0!==n?n:-1,playingStateTimestamp:Date.now()},!1)}if(this.userInitiatedPlayEvents.length>0){var u=this.userInitiatedPlayEvents[this.userInitiatedPlayEvents.length-1];this.modifyTelemetryEventPayload(u,{playingStatePosition:null!==(s=null===(r=this.currentPlayerDiagnosticSnapshot)||void 0===r?void 0:r.currentPlayPosition)&&void 0!==s?s:-1,playingStateTimestamp:Date.now()},!1)}}else if(e===o.HydraPlayerPlaybackState.Pause&&this.userInitiatedPauseEvents.length>0){var h=this.userInitiatedPauseEvents[this.userInitiatedPauseEvents.length-1];this.modifyTelemetryEventPayload(h,{pauseStatePosition:null!==(c=null===(a=this.currentPlayerDiagnosticSnapshot)||void 0===a?void 0:a.currentPlayPosition)&&void 0!==c?c:-1,pauseStateTimestamp:Date.now()},!1)}}else this.firstReadyStateTimestamp=Date.now();this.registerPlaybackEvent(l.TelemetryEventType.StateChanged,e)},e.prototype.registerCapabilitiesUpdated=function(e){this.registerPlaybackEvent(l.TelemetryEventType.CapabilitiesUpdated,e)},e.prototype.registerHydraInputStateChanged=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.HydraInputStateChanged,e,t)},e.prototype.registerHydraOutputStateChanged=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.HydraOutputStateChanged,e,t)},e.prototype.registerPlaybackBuffering=function(e){this.registerPlaybackEvent(l.TelemetryEventType.Buffering,e)},e.prototype.registerSdnPluginEvent=function(e){var t=this.createTelemetryEvent(l.TelemetryEventType.EcdnPluginEvents,e);this.ecdnPluginEvents.push(t),this.ecdnPluginEvents.length>this.maxPlayerPlaybackEventCount&&this.ecdnPluginEvents.splice(0,1),this.logTelemetryEvent(t)},e.prototype.registerPlaybackError=function(e,t,i,n){this.registerPlaybackEvent(l.TelemetryEventType.Error,{errorType:e,details:t,errorSource:i,errorReason:n}),this.latestErrorReason=n},e.prototype.registerIgnoredPlaybackError=function(e){this.registerPlaybackEvent(l.TelemetryEventType.IgnoredError,e)},e.prototype.registerDownloadBitrateChanged=function(e){this.registerPlaybackEvent(l.TelemetryEventType.BitrateChangedDownload,e)},e.prototype.registerStreamOptionsConfigured=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.StreamOptionsConfigured,e,t)},e.prototype.registerPlaybackBitrateChanged=function(e){this.registerPlaybackEvent(l.TelemetryEventType.BitrateChangedPlayback,e)},e.prototype.registerVolumeChange=function(e){this.registerPlaybackEvent(l.TelemetryEventType.Volume,e)},e.prototype.getSnapshotReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),r=this.playbackEvents,s={};this.currentPlayerDiagnosticSnapshot&&(s=this.filterAndPrepareTelemetry());var a=d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs);return n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),a?{supportedCodecs:d.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),s)},e.prototype.getReport=function(){var e,t,i,r,s=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),a=this.playbackEvents,o=d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs);return n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(s)),this.getHydraInternalReport(a)),this.getPlaybackReport(a)),this.getBitrateReport(a)),this.getStreamConnectionReport(s)),this.getSdnReport(s)),this.getSetSourceReport(s)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),o?{supportedCodecs:d.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog()),{eventId:(null===(i=this.currentPlayerDiagnosticSnapshot)||void 0===i?void 0:i.eventId)||"",templateId:(null===(r=this.currentPlayerDiagnosticSnapshot)||void 0===r?void 0:r.templateId)||""})},e.prototype.buildCompleteTelemetryEvent=function(){this.playerEvents.sort((function(e,t){return e.getName()!==t.getName()?Object.keys(l.PlayerScenarioType).indexOf(e.getName())-Object.keys(l.PlayerScenarioType).indexOf(t.getName()):e.getTimeStamp()-t.getTimeStamp()}));for(var e,t,i,r,s,a=[],o=0,c=this.playerEvents;o<c.length;o++){var d=c[o],u=a[a.length-1];a.length&&d.getName()===u.name&&0===u.duration?a[a.length-1]=(e=u,i=(t=d).getFailReason()?{failReason:t.getFailReason()}:{},r=t.getDetails()?{details:t.getDetails()}:{},s={name:e.name,startTime:e.startTime,duration:t.getTimeStamp()>e.startTime?t.getTimeStamp()-e.startTime:e.duration},n(n(n({},s),i),r)):a.push({name:l.PlayerScenarioType[d.getName()],startTime:d.getTimeStamp(),duration:0})}return a},e.prototype.getHydraLoadEvent=function(){var e,t,i,n={name:l.PlayerScenarioType.LoadHydra,startTime:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initStartTime)||-1,duration:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initDuration)||0};(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)&&(n.failReason=this.hydraInitResult.errorMsg);var r=this.getHydraRuntimeDownloadDetails();return r&&(n.details=r),n},e.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var e=[],t=0,i=this.hydraInitResult.runtimeDownloadResults;t<i.length;t++){var n=i[t],r={success:n.success,url:n.url,startTime:n.startTime,duration:n.duration,trackingReference:n.trackingReference,timeTakenToDownloadScript:n.timeTakenToDownloadScript};n.errorMsg&&(r.errorMsg=n.errorMsg),e.push(r)}return d.stringifyObject(e)}return null},e.prototype.getTotalLoadEvent=function(){var e,t,i,n=this.getScenario(l.PlayerScenarioType.LoadPlayer),r=(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initDuration)||0,s=n.length>0?n[n.length-1].getTimeStamp()-n[0].getTimeStamp():0,a=n.length>0?n[n.length-1].getFailReason():void 0,o={name:l.PlayerScenarioType.Load,startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,duration:r+s};return(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)?o.failReason=this.hydraInitResult.errorMsg:a&&(o.failReason=a),o},e.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}},e.prototype.registerPlaybackEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);e===l.TelemetryEventType.Error&&(null==t?void 0:t.errorType)!==o.HydraPlayerPlaybackErrorType.PlaybackRetried&&(n.fatal=!0,this.callDropped=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getPlayerDiagnosticLog=function(){var e=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var t=this.currentPlayerDiagnosticSnapshot,i=this.playerDiagnosticsLog,r=n(n({},t),i),s={};return Object.keys(r).forEach((function(t){s["player_".concat(t)]=e.prepareForTelemetry(r[t])})),s},e.prototype.getHydraInitializationReport=function(){var e,t,i,n;return{hydraInit_succeeded:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initSucceeded)||!1,hydraInit_startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,hydraInit_errorMessage:(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)||"",hydraInit_duration:(null===(n=this.hydraInitResult)||void 0===n?void 0:n.initDuration)||0}},e.prototype.getPlayerInitializationReport=function(e){var t,i=e.find((function(e){return e.name===l.PlayerScenarioType.Load})),n=this.playerEvents.find((function(e){return e.getName()===l.PlayerScenarioType.StreamConnection})),r={init_timeLoadToStreamConnectionEstablished:(i&&n?n.getTimeStamp()-i.startTime:-1)||-1,init_timeLoadToReady:(i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(i&&(null===(t=this.firstPlayingState)||void 0===t?void 0:t.timestamp)?this.firstPlayingState.timestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)};return this.firstPlayingState&&(r.init_firstPlayingStateStatistics=this.prepareForTelemetry(this.firstPlayingState)),r},e.prototype.getHydraInternalReport=function(e){var t=e.filter((function(e){return e.eventType===l.TelemetryEventType.HydraInputStateChanged})),i=e.filter((function(e){return e.eventType===l.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(t),hydra_outputStateChangeEvents:this.prepareForTelemetry(i)}},e.prototype.getPlaybackReport=function(e){var t=e.filter((function(e){return e.eventType===l.TelemetryEventType.StateChanged})),i=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.CanPlayThrough})),n=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Play})),r=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Start})),s=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Playing})),a=null!=i&&null!=n?n.timestamp-i.timestamp:-1,c=null!=n&&null!=r?r.timestamp-n.timestamp:-1,d=null!=r&&null!=s?s.timestamp-r.timestamp:-1,u=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Seeked})),h=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Seeking})),g=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Pause})),p=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Waiting})),m=[l.TelemetryEventType.BitrateChangedDownload,l.TelemetryEventType.BitrateChangedPlayback,l.TelemetryEventType.Error,l.TelemetryEventType.Mute,l.TelemetryEventType.StateChanged,l.TelemetryEventType.Volume,l.TelemetryEventType.StreamOptionsConfigured,l.TelemetryEventType.IgnoredError],f=e.filter((function(e){return e.eventType===l.TelemetryEventType.Error})),v=e.filter((function(e){return e.eventType===l.TelemetryEventType.IgnoredError})),S=e.filter((function(e){return e.eventType===l.TelemetryEventType.Volume||e.eventType===l.TelemetryEventType.Mute})),y=e.filter((function(e){return e.eventType===l.TelemetryEventType.StreamOptionsConfigured})),C=e.filter((function(e){return!m.includes(e.eventType)}));return{playback_timeReadyToPlay:a,playback_timePlayToStart:c,playback_timeStartToPlaying:d,playback_bufferingEvents:this.prepareForTelemetry(p),playback_errorEvents:this.prepareForTelemetry(f),playback_ignoredErrorEvents:this.prepareForTelemetry(v),playback_pauseEvents:this.prepareForTelemetry(g),playback_otherEvents:this.prepareForTelemetry(C),playback_seekedEvents:this.prepareForTelemetry(u),playback_seekingEvents:this.prepareForTelemetry(h),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(S),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(y),playback_latestErrorReason:this.latestErrorReason||""}},e.prototype.getBitrateReport=function(e){var t,i,r,s,a=e.filter((function(e){return e.eventType===l.TelemetryEventType.BitrateChangedDownload})),o=a.sort((function(e){return Number(e.payload)})),c=a.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(a),bitrate_downloadChangeCount:a.length>0||-1,bitrate_downloadMin:(null===(t=o[0])||void 0===t?void 0:t.payload)||-1,bitrate_downloadMax:(null===(i=o[o.length-1])||void 0===i?void 0:i.payload)||-1}:{},d=e.filter((function(e){return e.eventType===l.TelemetryEventType.BitrateChangedPlayback})),u=d.sort((function(e){return Number(e.payload)})),h=d.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(d),bitrate_playbackChangeCount:d.length>0||-1,bitrate_playbackMin:(null===(r=u[0])||void 0===r?void 0:r.payload)||-1,bitrate_playbackMax:(null===(s=u[u.length-1])||void 0===s?void 0:s.payload)||-1}:{};return n(n({},c),h)},e.prototype.addNetworkTypeEventListener=function(){var e,t,i,n,r=this;(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)&&(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n||n.addEventListener("change",(function(){r.updateClientNetworkType()})))},e.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e.prototype.getClientNetworkType=function(){var e,t,i,n;if(void 0===this.clientNetworkType){var r="Unknown";if(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)switch(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n?void 0:n.type){case"cellular":r="WWAN";break;case"ethernet":r="Wired";break;case"wifi":r="Wireless";break;default:r="Unknown"}this.clientNetworkType=r}return this.clientNetworkType},e.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}}]},e.prototype.getAudioVideoCodecsSupported=function(e){return r(this,void 0,void 0,(function(){var t,i,n=this;return s(this,(function(a){switch(a.label){case 0:return t=[],"mediaCapabilities"in navigator?(i=e.map((function(e){return r(n,void 0,void 0,(function(){var i,n;return s(this,(function(r){switch(r.label){case 0:i=e,r.label=1;case 1:return r.trys.push([1,3,,4]),[4,navigator.mediaCapabilities.decodingInfo(i)];case 2:return(n=r.sent()).supported&&(e.video?t.push({codec:e.video.contentType,supported:n.supported,smooth:n.smooth,powerEfficient:n.powerEfficient,resolution:e.video.height,framerate:e.video.framerate}):e.audio&&t.push({codec:e.audio.contentType,supported:n.supported,smooth:n.smooth,powerEfficient:n.powerEfficient})),[3,4];case 3:return r.sent(),[3,4];case 4:return[2]}}))}))})),[4,Promise.allSettled(i)]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2,t]}}))}))},e.prototype.populateSupportedCodecs=function(){var e=this;void 0===this.supportedCodecs&&this.getAudioVideoCodecsSupported(this.getCodecList()).then((function(t){e.supportedCodecs=t}))},e.prototype.getSdnReport=function(e){var t,i=e.filter((function(e){return[l.PlayerScenarioType.SdnPluginLoad,l.PlayerScenarioType.SdnPluginInitialize,l.PlayerScenarioType.SdnPluginSetSource].includes(e.name)})),n=a(a([],i,!0),this.ecdnPluginEvents,!0),r=i.filter((function(e){return void 0!==e.failReason})),s=i.filter((function(e){return e.name===l.PlayerScenarioType.SdnPluginLoad})).sort((function(e,t){return t.startTime-e.startTime}))[0];return{sdn_loaded:!(null==s||void 0!==s.failReason),sdn_details:null!==(t=null==s?void 0:s.details)&&void 0!==t?t:"",sdn_error:r.length>0&&r[r.length-1].failReason||"",sdn_events:this.prepareForTelemetry(n)}},e.prototype.getStreamConnectionReport=function(e){var t=e.filter((function(e){return e.name===l.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(t)}},e.prototype.getSetSourceReport=function(e){var t=e.filter((function(e){return e.name===l.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(t)}},e.prototype.registerScenario=function(e,t){this.playerEvents.push(new h(e,t))},e.prototype.completeScenario=function(e,t,i){this.playerEvents.push(new h(e,i,t))},e.prototype.logTelemetryEvent=function(e){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(e))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e.prototype.filterAndPrepareTelemetry=function(){var e=this,t=new Set;t.add("serviceLatencyCdg"),t.add("endToEndLatencyCdg"),t.add("videoEdgeLatencyCdg"),t.add("eventId"),t.add("templateId");var i={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(n){t.has(n)||(i["player_".concat(n)]=e.prepareForTelemetry(e.currentPlayerDiagnosticSnapshot[n]))})),i},e.prototype.prepareForTelemetry=function(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?null!=e?e:-1:JSON.stringify(e)},e.prototype.getScenario=function(e){return this.playerEvents.filter((function(t){return t.getName()===e}))},e.prototype.createTelemetryEvent=function(e,t,i){var n,r,s={eventType:e,timestamp:Date.now(),currentPlayPosition:null!==(r=null===(n=this.currentPlayerDiagnosticSnapshot)||void 0===n?void 0:n.currentPlayPosition)&&void 0!==r?r:-1};return void 0!==t&&(s.payload=this.prepareForTelemetry(t)),s.message=i,s},e.prototype.modifyTelemetryEventPayload=function(e,t,i){try{if(e.payload){var r=JSON.parse(e.payload);r=i?n(n({},r),t):n(n({},t),r),e.payload=this.prepareForTelemetry(r)}else e.payload=this.prepareForTelemetry(t)}catch(t){this.logFn("error","Failed to modify payload for event: ".concat(d.stringifyObject(e),", error: ").concat(t))}},e.prototype.registerExperimentalEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e.prototype.registerUserInitiatedSeek=function(e){var t,i,n={newCurrentPlayPosition:e,seekForward:(null!==(i=null===(t=this.currentPlayerDiagnosticSnapshot)||void 0===t?void 0:t.currentPlayPosition)&&void 0!==i?i:-1)<e},r=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedSeek,n);this.userInitiatedSeekEvents.push(r),this.userInitiatedSeekEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedSeekEvents.splice(0,1)},e.prototype.registerUserInitiatedPlay=function(){var e=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedPlay);this.userInitiatedPlayEvents.push(e),this.userInitiatedPlayEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPlayEvents.splice(0,1)},e.prototype.registerUserInitiatedPause=function(){var e=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedPause);this.userInitiatedPauseEvents.push(e),this.userInitiatedPauseEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPauseEvents.splice(0,1)},e.prototype.getUserInitiatedSeekEvents=function(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents),playback_userInitiatedPlayEvents:this.prepareForTelemetry(this.userInitiatedPlayEvents),playback_userInitiatedPauseEvents:this.prepareForTelemetry(this.userInitiatedPauseEvents)}},e.prototype.registerPlayBlocked=function(e){this.registerScenario(l.PlayerScenarioType.PlayAttemptBlocked,"Called video element play() but it failed with error: ".concat(e)),this.completeScenario(l.PlayerScenarioType.PlayAttemptBlocked)},e}();t.LiveStreamStatistic=g},42:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Spinner=void 0;var i=function(){function e(e){this.container=e,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var t=this.container.ownerDocument.getElementById(this.spinnerId);if(t)return this.spinner=t,void this.show();var i=this.container.ownerDocument.createElement("style");i.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(i),this.container.style.position="relative";var n=this.container.ownerDocument.createElement("div");n.classList.add("ml-player-spinner-container"),this.container.appendChild(n),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,n.appendChild(this.spinner);var r=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");r.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(r);var s=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");s.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(s),this.show()}return Object.defineProperty(e.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var e=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];e.hideTimestamp||(e.displayDuration=Date.now()-e.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e.prototype.show=function(){var e=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=e),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:e,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e.prototype.hide=function(){var e=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=e),this.spinnerInfoHistory.length>0){var t=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];t.hideTimestamp||(t.hideTimestamp=e,t.displayDuration=e-t.showTimestamp)}this.spinner.style.display="none"},e.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e}();t.Spinner=i},378:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageType=void 0,(n=i||(t.MessageType=i={})).Command="Command",n.CommandSuccessResult="CommandSuccessResult",n.CommandFailureResult="CommandFailureResult",n.PlayerEvent="PlayerEvent",n.InternalPlayerEvent="InternalPlayerEvent"},963:function(e,t){var i,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.PlayerScenarioType=t.TelemetryEventType=void 0,(r=i||(t.TelemetryEventType=i={})).BitrateChangedDownload="BitrateChangedDownload",r.StreamOptionsConfigured="StreamOptionsConfigured",r.BitrateChangedPlayback="BitrateChangedPlayback",r.CaptionsToggled="CaptionsToggled",r.Error="Error",r.IgnoredError="IgnoredError",r.FullscreenChanged="FullscreenChanged",r.Mute="Mute",r.PotentialMediaFreeze="PotentialMediaFreeze",r.StateChanged="StateChanged",r.HydraInputStateChanged="HydraInputStateChanged",r.HydraOutputStateChanged="HydraOutputStateChanged",r.Volume="Volume",r.Buffering="Buffering",r.Online="Online",r.Offline="Offline",r.NetworkChange="NetworkChange",r.HlsEvents="HlsEvents",r.EcdnPluginEvents="EcdnPluginEvents",r.UserInitiatedSeek="UserInitiatedSeek",r.UserInitiatedPlay="UserInitiatedPlay",r.UserInitiatedPause="UserInitiatedPause",r.CapabilitiesUpdated="CapabilitiesUpdated",function(e){e.LoadHydra="LoadHydra",e.LoadHlsScript="LoadHlsScript",e.LoadPlayer="LoadPlayer",e.Load="Load",e.LoadHlsAuthCookie="LoadHlsAuthCookie",e.HlsManifestLoad="HlsManifestLoad",e.HlsKeyLoad="HlsKeyLoad",e.LoadHlsFirstFragment="LoadHlsFirstFragment",e.SetSource="SetSource",e.SdnPluginLoad="SdnPluginLoad",e.ThaPluginLoad="ThaPluginLoad",e.HydraPipelineInitialization="HydraPipelineInitialization",e.Destroyed="Destroyed",e.Setup="Setup",e.StreamConnection="StreamConnection",e.SdnPluginInitialize="SdnPluginInitialize",e.SdnPluginSetSource="SdnPluginSetSource",e.PlayAttemptBlocked="PlayAttemptBlocked"}(n||(t.PlayerScenarioType=n={}))},176:function(e,t){var i,n,r,s,a,o,l,c;Object.defineProperty(t,"__esModule",{value:!0}),t.MobileInteractionType=t.HydraSupportedSDN=t.HydraPlayerDestroyedReason=t.HydraOutputState=t.HydraInputState=t.HydraPlayerPlaybackErrorSource=t.PlaybackMode=void 0,(c=i||(t.PlaybackMode=i={})).Live="Live",c.DVR="DVR",function(e){e.Stream="Stream",e.HydraPipeline="HydraPipeline",e.VideoPlayer="VideoPlayer"}(n||(t.HydraPlayerPlaybackErrorSource=n={})),function(e){e.Idle="Idle",e.Started="Started",e.BufferReceived="BufferReceived",e.Ended="Ended",e.Stopped="Stopped",e.Destroyed="Destroyed"}(r||(t.HydraInputState=r={})),function(e){e.Idle="Idle",e.Attached="Attached",e.Starting="Starting",e.Started="Started",e.BufferReceived="BufferReceived",e.BufferAppended="BufferAppended",e.Stopped="Stopped",e.Destroyed="Destroyed"}(s||(t.HydraOutputState=s={})),function(e){e.PlayerStopped="PlayerStopped",e.PlaybackError="PlaybackError"}(a||(t.HydraPlayerDestroyedReason=a={})),function(e){e.Hive="hive",e.Kollective="kollective",e.Ramp="ramp",e.Peer5="peer5",e.Microsoft="microsoft"}(o||(t.HydraSupportedSDN=o={})),function(e){e[e.DoublePress3Fingers=0]="DoublePress3Fingers"}(l||(t.MobileInteractionType=l={}))},346:function(e,t){var i,n,r,s,a,o,l,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.HttpFetchErrorReason=t.IframeMessages=t.HydraPlayerType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=t.HydraStreamingEventType=void 0,(d=i||(t.HydraStreamingEventType=i={})).TLE="TLE",d.Overflow="Overflow",d.TownHallBasic="TownHall_Basic",d.TownHallPremium="TownHall_Premium",d.TownHall="TownHall",function(e){e.AMS="AMS",e.HLS="MiddleLaneHttpLiveStreaming",e.Ums="MiddleLaneUltraLowLatency"}(n||(t.HydraStreamDeliveryPipeline=n={})),function(e){e.MultiplePlayerLoad="MultiplePlayerLoad",e.PlayerInitializationFailed="PlayerInitializationFailed",e.InvalidStream="InvalidStream",e.SetSourceFailed="SetSourceFailed"}(r||(t.HydraPlayerSetupErrorType=r={})),function(e){e.LoadStart="loadstart",e.LoadedData="loadeddata",e.LoadedMetadata="loadedmetadata",e.Start="start",e.CanPlayThrough="canplaythrough",e.Play="play",e.Playing="playing",e.Pause="pause",e.Waiting="waiting",e.Seeking="seeking",e.Seeked="seeked",e.Ended="ended",e.Error="error",e.Destroyed="destroyed",e.Initialized="initialized",e.Stalled="stalled",e.VolumeChange="volumechange",e.PlaybackBitrateChanged="playbackbitratechanged",e.DownloadBitrateChanged="downloadbitratechanged",e.TimeUpdate="timeupdate",e.DurationChange="durationchange",e.HlsKeyLoading="hlsKeyLoading",e.HlsKeyLoaded="hlsKeyLoaded",e.HlsKeyLoadedFailed="hlsKeyLoadedFailed",e.HlsManifestLoading="hlsManifestLoading",e.HlsManifestLoaded="hlsManifestLoaded",e.HlsManifestLoadedFailed="hlsManifestLoadedFailed",e.HlsFirstFragmentLoading="hlsFragLoading",e.HlsFirstFragmentBuffered="hlsFragBuffered",e.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",e.HlsFragmentChanged="hlsFragmentChanged",e.Online="online",e.Offline="offline",e.NetworkChange="networkChange"}(s||(t.HydraPlayerPlaybackState=s={})),function(e){e.UnsupportedPlatform="UnsupportedPlatform",e.NetworkError="NetworkError",e.PlaybackRetried="PlaybackRetried",e.PlaybackError="PlaybackError",e.Unknown="Unknown",e.MediaTimeout="MediaTimeout",e.NoMediaFlow="NoMediaFlow"}(a||(t.HydraPlayerPlaybackErrorType=a={})),function(e){e[e.Hls=1]="Hls",e[e.Ums=2]="Ums"}(o||(t.HydraPlayerType=o={})),function(e){e.RequestIceCandidates="RequestIceCandidates"}(l||(t.IframeMessages=l={})),function(e){e.Unknown="Unknown",e.ClientNetwork="ClientNetwork",e.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",e.ServerNetwork="ServerNetwork",e.ClientAuthIssue="ClientAuthIssue",e.ServerResourceNotFound="ServerResourceNotFound"}(c||(t.HttpFetchErrorReason=c={}))},534:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaybackStoppingState=t.tryCallVideoElementPlay=t.sanitizeForFormatSpecifiers=t.addEvent=t.TimeRanges=t.NO_OP_BUFFERED=t.getHttpFetchErrorReason=t.createVideoPlayButton=t.createVideoElement=t.createVideoElementDiv=t.showPlayerControls=t.repeatUntilCancel=t.wait=t.stringifyError=t.stringifyObject=t.getRandomHexString=t.getPlayerSetting=t.getECSSetting=t.retry=t.createIFrame=t.getMajorFromVersion=void 0;var s=i(346),a=i(457);function o(e,t,i,s,a,o,l){return n(this,void 0,void 0,(function(){var d,u,g,p,m,f=this;return r(this,(function(v){switch(v.label){case 0:return d=100,u=Date.now(),[4,c(i,g={trackingRef:"",timeTakenToDownloadScript:-1},a,o,l).catch((function(e){return n(f,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return t="Failed to get IFrame source: ".concat(h(e)),s.push({success:!1,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript,errorMsg:t}),s.length>d&&s.shift(),[4,Promise.reject(new Error(t))];case 1:return[2,n.sent()]}}))}))}))];case 1:return p=v.sent(),t.srcdoc=p,m=new Promise((function(e,n){t.onload=function(){s.push({success:!0,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript}),s.length>d&&s.shift(),e()},t.onerror=function(e){var t="Failed to load HydraPlayer IFrame: ".concat(h(e));s.push({success:!1,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript,errorMsg:t}),s.length>d&&s.shift(),n(new Error(t))}})),e.appendChild(t),[4,m];case 2:return v.sent(),[2]}}))}))}function l(e){return n(this,arguments,void 0,(function(e,t,i){var s=this;return void 0===t&&(t=5),void 0===i&&(i=200),r(this,(function(a){switch(a.label){case 0:return[4,e(t).catch((function(a){return n(s,void 0,void 0,(function(){var s=this;return r(this,(function(o){switch(o.label){case 0:return 0!=--t?[3,2]:[4,Promise.reject(new Error("[retry] retries exhausted: ".concat(g(a))))];case 1:case 3:return[2,o.sent()];case 2:return[4,new Promise((function(o){return setTimeout((function(){o(l(e,t,i).catch((function(e){return n(s,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(new Error("".concat(g(a)).concat(", ",g(e))))];case 1:return[2,t.sent()]}}))}))})))}),i)}))]}}))}))}))];case 1:return[2,a.sent()]}}))}))}function c(e,t,i,s,a){return n(this,void 0,void 0,(function(){var o,l,c,u=this;return r(this,(function(h){switch(h.label){case 0:return o=Date.now(),i?(l='<script src="'.concat(e,'"></script')+">",[3,3]):[3,1];case 1:return[4,d(e,t,s).catch((function(e){return n(u,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(e)];case 1:return[2,t.sent()]}}))}))}))];case 2:c=h.sent(),l=a?'<script nonce="'.concat(a,'">').concat(c,"</script")+">":"<script>".concat(c,"</script")+">",h.label=3;case 3:return t.timeTakenToDownloadScript=Date.now()-o,[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(l,"\n </body>\n </html>\n ")]}}))}))}function d(e,t,i){return n(this,void 0,void 0,(function(){var s,a,o,l=this;return r(this,(function(c){switch(c.label){case 0:return s=function(e,t){var i,n;return t.includes("vz")?null!==(n=e.headers.get("uuid"))&&void 0!==n?n:"":null!==(i=e.headers.get("X-Azure-Ref"))&&void 0!==i?i:""},i?(a=new AbortController,o=setTimeout((function(){a.abort()}),i),[4,fetch(e,{signal:a.signal,cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return clearTimeout(o),i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=s(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return[4,t.text().then((function(s){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return s?[2,s]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,s.sent()]}}))}))})).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){throw clearTimeout(o),e}))}))}))]):[3,2];case 1:case 3:return[2,c.sent()];case 2:return[4,fetch(e,{cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=s(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return[4,t.text().then((function(s){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return s?[2,s]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,s.sent()]}}))}))}))]}}))}))}function u(e,t,i){var n,r=i,s=null===(n=e.ecsSettings)||void 0===n?void 0:n[t];return typeof s==typeof r&&(r=s),r}function h(e){try{if(!e)return"".concat(e);if(e instanceof Map)return i={},e.forEach((function(e,t){i[t.toString()]=e})),JSON.stringify(i);var t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}catch(e){return""}var i}function g(e){return e instanceof Error?e.message:h(e)}function p(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){return setTimeout(t,e)}))];case 1:return t.sent(),[2]}}))}))}function m(e){return e?e.replace(/%[a-zA-Z]/g,""):e}t.getMajorFromVersion=function(e){var t=e.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return t?t[1]:null},t.createIFrame=function(e,t,i){return n(this,void 0,void 0,(function(){var s,c,d,g,p,m,f,v,S,y,C=this;return r(this,(function(T){switch(T.label){case 0:return s=u(i,"scriptSrcDownload",a.iframeConfigDefault.scriptSrcDownload),c=u(i,"allowSameOrigin",a.iframeConfigDefault.allowSameOrigin),d=i.maxRetryCountForLoadingResources,g=i.disableSandbox,p=i.hydraRuntimeFetchTimeout,m=[],(f=e.ownerDocument.createElement("iframe")).id="player-iframe",g||(c?null===(S=f.sandbox)||void 0===S||S.add("allow-scripts","allow-same-origin"):null===(y=f.sandbox)||void 0===y||y.add("allow-scripts")),f.allowFullscreen=!0,f.allow="camera; microphone; autoplay",f.style.height="100%",f.style.width="100%",f.style.border="none",v=function(e){return t[e%t.length]},[4,l((function(t){return n(C,void 0,void 0,(function(){var n,a,l;return r(this,(function(r){switch(r.label){case 0:return n=v(t),a=null!==(l=i.nonce)&&void 0!==l?l:"",[4,o(e,f,n,m,s,p,a)];case 1:return r.sent(),[2]}}))}))}),d).then((function(){return{iframe:f,initResult:{isSuccess:!0,runtimeDownloadResults:m}}})).catch((function(e){return n(C,void 0,void 0,(function(){var i;return r(this,(function(n){return i="Failed to load Hydra player runtime scripts, src: ",t.forEach((function(e){return i=i.concat(e,", ")})),i+="errors: ".concat(h(e)),[2,{initResult:{isSuccess:!1,runtimeDownloadResults:m,errorMsg:i}}]}))}))}))];case 1:return[2,T.sent()]}}))}))},t.retry=l,t.getECSSetting=u,t.getPlayerSetting=function(e,t){var i;return void 0!==(null===(i=e.ecsSettings)||void 0===i?void 0:i[t])?e.ecsSettings[t]:e[t]},t.getRandomHexString=function(e){return Array.from(Array(e)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},t.stringifyObject=h,t.stringifyError=g,t.wait=p,t.repeatUntilCancel=function(e,t,i,s){var a=!1,o=s||console.log,l=m(e);return o("RepeatUntilCancel starting task: ".concat(l)),n(this,void 0,void 0,(function(){var e,n,s;return r(this,(function(r){switch(r.label){case 0:return a?[3,2]:(e=new Date,t(),n=(new Date).getTime()-e.getTime(),(s=i-n)<0&&(s=i+s%i,o("Skipping execution for ".concat(l,", last execution took: ").concat(n," ms, delayMs: ").concat(i),"warn")),[4,p(s)]);case 1:return r.sent(),[3,0];case 2:return[2]}}))})),function(){o("RepeatUntilCancel stopping task: ".concat(l)),a=!0}},t.showPlayerControls=function(e){return void 0!==e.allowPlayerControls?e.allowPlayerControls:e.streamingEventType===s.HydraStreamingEventType.TLE},t.createVideoElementDiv=function(e,t,i){i("createVideoElementDiv started");var n=t.ownerDocument.createElement("div");return n.id=e,n.style.position="relative",n.style.width="100%",n.style.height="100%",t.appendChild(n),i("createVideoElementDiv done"),n},t.createVideoElement=function(e,t,i,n,r){r("createVideoElement started");var s=t.ownerDocument.createElement("video");s.controls=n,s.id=e,s.setAttribute("playsinline","");var a=i.videoLang;a&&(s.setAttribute("lang",a),r("createVideoElement: language set to ".concat(a)));var o=i.videoElementStyles;if(o)for(var l=0;l<o.length;l++)s.classList.add(o[l]);return s.style.width="100%",s.style.height="100%",s.style.position="absolute",s.muted=i.muteVideo,s.addEventListener("contextmenu",(function(e){e.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(e){try{navigator.mediaSession.setActionHandler(e,(function(){}))}catch(e){}})),t.appendChild(s),r("createVideoElement done"),s},t.createVideoPlayButton=function(e,t,i,n){n("createVideoPlayButton started");var r=t.ownerDocument.createElement("style");r.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 ",t.ownerDocument.head.appendChild(r);var s=t.ownerDocument.createElement("div");s.id=e,s.className="hydra-play-button";var a=document.createElement("div");return a.className="triangle",s.appendChild(a),i||(s.style.display="none"),t.appendChild(s),n("createVideoPlayButton done"),s},t.getHttpFetchErrorReason=function(e){return void 0===e?s.HttpFetchErrorReason.Unknown:0===e?s.HttpFetchErrorReason.ClientNetworkOrUnreachableServer:401===e?s.HttpFetchErrorReason.ClientAuthIssue:404===e?s.HttpFetchErrorReason.ServerResourceNotFound:e>=400&&e<=499?s.HttpFetchErrorReason.ClientNetwork:e>=500&&e<=599?s.HttpFetchErrorReason.ServerNetwork:s.HttpFetchErrorReason.Unknown},t.NO_OP_BUFFERED={length:0,start:function(){return 0},end:function(){return 0}},t.TimeRanges={toString:function(e){for(var t="",i=e.length,n=0;n<i;n++)t+="[".concat(e.start(n).toFixed(3),"-").concat(e.end(n).toFixed(3),"]");return t},range:function(e){return e&&0!==e.length?[e.start(e.length-1),e.end(e.length-1)]:[0,0]},prevRange:function(e){if(e&&2===e.length)return[e.start(e.length-2),e.end(e.length-2)]}},t.addEvent=function(e,t){var i={};return(null==t?void 0:t.detail)&&(i={detail:t.detail}),new CustomEvent(e,i)},t.sanitizeForFormatSpecifiers=m,t.tryCallVideoElementPlay=function(e){var t=e.play();return void 0!==t?t:new Promise((function(e){return e()}))},t.isPlaybackStoppingState=function(e){return e===s.HydraPlayerPlaybackState.Pause||e===s.HydraPlayerPlaybackState.Ended||e===s.HydraPlayerPlaybackState.Seeking||e===s.HydraPlayerPlaybackState.Waiting||e===s.HydraPlayerPlaybackState.Stalled||e===s.HydraPlayerPlaybackState.Destroyed}},564:function(e,t){var i,n,r,s,a,o,l,c,d,u;Object.defineProperty(t,"__esModule",{value:!0}),t.UmsModality=t.HttpFetchErrorReason=t.IframeMessages=t.HydraPlayerType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=t.HydraStreamingEventType=void 0,(u=i||(t.HydraStreamingEventType=i={})).TLE="TLE",u.Overflow="Overflow",u.TownHallBasic="TownHall_Basic",u.TownHallPremium="TownHall_Premium",u.TownHall="TownHall",function(e){e.AMS="AMS",e.HLS="MiddleLaneHttpLiveStreaming",e.Ums="MiddleLaneUltraLowLatency"}(n||(t.HydraStreamDeliveryPipeline=n={})),function(e){e.MultiplePlayerLoad="MultiplePlayerLoad",e.PlayerInitializationFailed="PlayerInitializationFailed",e.InvalidStream="InvalidStream",e.SetSourceFailed="SetSourceFailed"}(r||(t.HydraPlayerSetupErrorType=r={})),function(e){e.LoadStart="loadstart",e.LoadedData="loadeddata",e.LoadedMetadata="loadedmetadata",e.Start="start",e.CanPlayThrough="canplaythrough",e.Play="play",e.Playing="playing",e.Pause="pause",e.Waiting="waiting",e.Seeking="seeking",e.Seeked="seeked",e.Ended="ended",e.Error="error",e.Destroyed="destroyed",e.Initialized="initialized",e.Stalled="stalled",e.VolumeChange="volumechange",e.PlaybackBitrateChanged="playbackbitratechanged",e.DownloadBitrateChanged="downloadbitratechanged",e.TimeUpdate="timeupdate",e.DurationChange="durationchange",e.HlsKeyLoading="hlsKeyLoading",e.HlsKeyLoaded="hlsKeyLoaded",e.HlsKeyLoadedFailed="hlsKeyLoadedFailed",e.HlsManifestLoading="hlsManifestLoading",e.HlsManifestLoaded="hlsManifestLoaded",e.HlsManifestLoadedFailed="hlsManifestLoadedFailed",e.HlsFirstFragmentLoading="hlsFragLoading",e.HlsFirstFragmentBuffered="hlsFragBuffered",e.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",e.HlsFragmentChanged="hlsFragmentChanged",e.Online="online",e.Offline="offline",e.NetworkChange="networkChange"}(s||(t.HydraPlayerPlaybackState=s={})),function(e){e.UnsupportedPlatform="UnsupportedPlatform",e.NetworkError="NetworkError",e.PlaybackRetried="PlaybackRetried",e.PlaybackError="PlaybackError",e.Unknown="Unknown",e.MediaTimeout="MediaTimeout",e.NoMediaFlow="NoMediaFlow"}(a||(t.HydraPlayerPlaybackErrorType=a={})),function(e){e[e.Hls=1]="Hls",e[e.Ums=2]="Ums"}(o||(t.HydraPlayerType=o={})),function(e){e.RequestIceCandidates="RequestIceCandidates"}(l||(t.IframeMessages=l={})),function(e){e.Unknown="Unknown",e.ClientNetwork="ClientNetwork",e.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",e.ServerNetwork="ServerNetwork",e.ClientAuthIssue="ClientAuthIssue",e.ServerResourceNotFound="ServerResourceNotFound"}(c||(t.HttpFetchErrorReason=c={})),function(e){e.audio="Audio",e.video="Video",e.text="Text"}(d||(t.UmsModality=d={}))},521:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayer=t.getSdkVersion=void 0;var s=i(346),a=i(378),o=i(715),l=i(357),c=i(534),d=i(42),u=i(103),h=i(282),g=i(10);t.getSdkVersion=function(){return"4.2521.1"};var p=function(){function e(e,t){this.playerSettings=e,this.eventHandler=t,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 o.HydraPlayerInternalEventHandler}return e.prototype.dispose=function(){var e;null===(e=this.telemetryReportHandler)||void 0===e||e.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.callPlayerApi("disposeHydraPlayer")},e.prototype.release=function(){var e;null===(e=this.spinner)||void 0===e||e.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)},e.prototype.setup=function(e){return n(this,void 0,void 0,(function(){var t,i,n,a,o,l,u,h;return r(this,(function(r){switch(r.label){case 0:t=Date.now(),this.container=e,i=null,r.label=1;case 1:return r.trys.push([1,14,,15]),this.spinner=new d.Spinner(this.container),this.playerInternalEventHandler.setSpinner(this.spinner),[4,this.initializeIFrame()];case 2:if(!(i=r.sent()).isSuccess)return[3,12];n={initSucceeded:!0,initStartTime:t,initDuration:Date.now()-t,runtimeDownloadResults:i.runtimeDownloadResults||[]},r.label=3;case 3:return r.trys.push([3,5,,11]),[4,this.callPlayerApi("createHydraPlayer",this.playerSettings,n)];case 4:return r.sent(),[3,11];case 5:return a=r.sent(),this.eventHandler.log("warn","Failed to create HydraPlayer: ".concat(a)),this.playerSettings.playerType!==s.HydraPlayerType.Hls?[3,7]:[4,this.callPlayerApi("createHlsHydraPlayer",this.playerSettings,n)];case 6:return r.sent(),[3,10];case 7:return this.playerSettings.playerType!==s.HydraPlayerType.Ums?[3,9]:[4,this.callPlayerApi("createUmsHydraPlayer",this.playerSettings,n)];case 8:return r.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(n),[2,!0];case 12:throw new Error(i.errorMsg);case 13:return[3,15];case 14:o=r.sent(),l=(0,c.stringifyObject)(o),this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(l)),u={initSucceeded:!1,initStartTime:t,initDuration:Date.now()-t,runtimeDownloadResults:(null==i?void 0:i.runtimeDownloadResults)||[],errorMsg:l};try{null===(h=this.spinner)||void 0===h||h.hide()}catch(e){this.eventHandler.log("error","Failed to hide spinner: ".concat((0,c.stringifyObject)(e)))}return this.onSetupCompleted(u),[2,!1];case 15:return[2]}}))}))},e.prototype.onSetupCompleted=function(e){this.telemetryReportHandler=new l.TelemetryReportHandler(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),e,this.spinner),this.playerInternalEventHandler.setTelemetryReportHandler(this.telemetryReportHandler)},e.prototype.getFullTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getFullTelemetryReport())||{}},e.prototype.getSnapshotTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getSnapshotTelemetryReport())||{}},e.prototype.callPlayerApi=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return n(this,void 0,void 0,(function(){var i,n,s,o,l;return r(this,(function(r){switch(r.label){case 0:return this.iframe?[3,2]:[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))];case 1:case 3:return[2,r.sent()];case 2:if(i=(0,g.default)(),n={msgType:a.MessageType.Command,id:i,name:e,args:t},!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 s=u.defer(),o={name:e,id:i},this.commandResultsMap.set(o,s),null===(l=this.iframe.contentWindow)||void 0===l||l.postMessage(n,"*"),[4,s.promise]}}))}))},Object.defineProperty(e.prototype,"contextWindow",{get:function(){var e;return null===(e=this.container)||void 0===e?void 0:e.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e.prototype.isIFrameCommunicationActive=function(){var e;return!!(null===(e=this.iframe)||void 0===e?void 0:e.contentWindow)&&!!this.contextWindow},e.prototype.getRuntimeUrls=function(e){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var t=(0,c.getMajorFromVersion)(e);return t&&this.playerSettings.playerRuntimeJsUrls[t]||[]}return this.playerSettings.playerRuntimeJsUrls},e.prototype.initializeIFrame=function(){return n(this,void 0,void 0,(function(){var e;return r(this,(function(t){switch(t.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,c.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,c.stringifyObject)(this.playerSettings.playerRuntimeJsUrls))}];case 1:return(e=t.sent()).initResult.isSuccess&&e.iframe&&(this.iframe=e.iframe,this.iframeCommunicationHandler=new h.IframeCommunicationHandler(this.iframe,this.playerSettings,this.eventHandler.log),this.contextWindow.addEventListener("message",this.onMessage.bind(this))),[2,e.initResult]}}))}))},e.prototype.onMessage=function(e){switch(e.data.msgType){case a.MessageType.PlayerEvent:this.processPlayerEvent(e.data);break;case a.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(e.data);break;case a.MessageType.CommandSuccessResult:this.processCommandSuccessResult(e.data);break;case a.MessageType.CommandFailureResult:this.processCommandFailureResult(e.data)}},e.prototype.processCommandSuccessResult=function(e){var t=this;this.eventHandler.log("debug","HydraPlayer command succeeded for ".concat(e.name," - result: ").concat((0,c.stringifyObject)(e.result))),this.getMapCommandResults(e).forEach((function(i){i[1].resolve(e.result),t.commandResultsMap.delete(i[0])}))},e.prototype.processCommandFailureResult=function(e){var t=this;this.eventHandler.log("debug","HydraPlayer command failed for ".concat(e.name," - error: ").concat(e.error.message)),this.getMapCommandResults(e).forEach((function(i){i[1].reject(e.error),t.commandResultsMap.delete(i[0])}))},e.prototype.getMapCommandResults=function(e){var t=Array.from(this.commandResultsMap.entries()),i=[];return e.id?i=t.filter((function(t){return t[0].id===e.id})):e.name&&(i=t.filter((function(t){return t[0].name===e.name}))),i},e.prototype.processPlayerEvent=function(e){var t;null===(t=this.eventHandler[e.name])||void 0===t||t.apply(this.eventHandler,e.args)},e.prototype.processInternalPlayerEvent=function(e){this.playerInternalEventHandler&&this.playerInternalEventHandler[e.name].apply(this,e.args)},e}();t.HydraPlayer=p},282:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.IframeCommunicationHandler=void 0;var n=i(346),r=i(735),s=function(){function e(e,t,i){var n=this;this.iframe=e,this.playerSettings=t,this.logger=i,this.setupMessageListener(),this.candidatesCollector=new r.WebRtcIceCandidateCollector(this.playerSettings),this.candidatesCollector.startCandidatesCollection().catch((function(e){n.logger("warn","Failed to start collecting ICE candidates ".concat(e))}))}return e.prototype.setupMessageListener=function(){var e;null===(e=this.iframe.ownerDocument.defaultView)||void 0===e||e.addEventListener("message",this.processMessage.bind(this))},e.prototype.postMessageToIframe=function(e){var t;null===(t=this.iframe.contentWindow)||void 0===t||t.postMessage(e,"*")},e.prototype.dispose=function(){var e;null===(e=this.iframe.ownerDocument.defaultView)||void 0===e||e.removeEventListener("message",this.processMessage.bind(this)),this.candidatesCollector&&this.candidatesCollector.destroy()},e.prototype.processMessage=function(e){var t=this;e.data===n.IframeMessages.RequestIceCandidates&&void 0===e.data.candidates&&this.candidatesCollector.getCandidates().then((function(e){var i=JSON.stringify(e.map((function(e){return JSON.stringify(e)})));t.postMessageToIframe({topic:n.IframeMessages.RequestIceCandidates,candidates:i})})).catch((function(){t.postMessageToIframe({topic:n.IframeMessages.RequestIceCandidates,candidates:[]})}))},e}();t.IframeCommunicationHandler=s},260:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),r(i(521),t),r(i(564),t)},715:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerInternalEventHandler=void 0;var i=function(){function e(){this.spinner=null,this.telemetryReportHandler=null}return e.prototype.setSpinner=function(e){this.spinner=e},e.prototype.setTelemetryReportHandler=function(e){this.telemetryReportHandler=e},e.prototype.firstPlayerLoadAttemptDone=function(){var e;null===(e=this.spinner)||void 0===e||e.hide()},e.prototype.fullTelemetryReportUpdated=function(e){var t;null===(t=this.telemetryReportHandler)||void 0===t||t.setFullTelemetryReport(e)},e.prototype.snapshotTelemetryReportUpdated=function(e){var t;null===(t=this.telemetryReportHandler)||void 0===t||t.setSnapshotTelemetryReport(e)},e}();t.HydraPlayerInternalEventHandler=i},357:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.TelemetryReportHandler=void 0;var r=i(346),s=i(176),a=i(963),o=i(171),l=i(534),c=function(){function e(e,t,i,n){var s=this;this.logFn=t,this.spinner=n,this.initialLiveStreamStatistic=new o.LiveStreamStatistic(e,(function(e,t){s.logFn(e,t)}),{videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],statsInterval:[]},{hydraPlayerSdkVersion:e.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:r.HydraPlayerType.Hls}),this.initialLiveStreamStatistic.setHydraInitResult(i),this.fullTelemetryReport=this.initialLiveStreamStatistic.getReport(),this.snapshotTelemetryReport=this.initialLiveStreamStatistic.getSnapshotReport()}return e.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e.prototype.setFullTelemetryReport=function(e){var t,i,r,s,a,o,l;this.fullTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(i=null===(t=this.spinner)||void 0===t?void 0:t.firstShowTimestamp)&&void 0!==i?i:-1,init_spinnerHideTimestamp:null!==(s=null===(r=this.spinner)||void 0===r?void 0:r.firstHideTimestamp)&&void 0!==s?s:-1,init_spinnerDuration:null!==(o=null===(a=this.spinner)||void 0===a?void 0:a.firstSpinnerDuration)&&void 0!==o?o:-1,init_spinnerVisible:(null===(l=this.spinner)||void 0===l?void 0:l.isVisible())||!1})},e.prototype.setSnapshotTelemetryReport=function(e){var t,i,r,s,a,o,l;this.snapshotTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(i=null===(t=this.spinner)||void 0===t?void 0:t.firstShowTimestamp)&&void 0!==i?i:-1,init_spinnerHideTimestamp:null!==(s=null===(r=this.spinner)||void 0===r?void 0:r.firstHideTimestamp)&&void 0!==s?s:-1,init_spinnerDuration:null!==(o=null===(a=this.spinner)||void 0===a?void 0:a.firstSpinnerDuration)&&void 0!==o?o:-1,init_spinnerVisible:(null===(l=this.spinner)||void 0===l?void 0:l.isVisible())||!1})},e.prototype.addDisposeTelemetry=function(){var e=Date.now();this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,e,"full"),this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,e,"snapshot"),this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,e,"full"),this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,e,"snapshot")},e.prototype.updateInitEventsWithDisposeEvent=function(e,t,i){try{var n=e.init_allEvents,r=JSON.parse(n);r[r.length-1].name!==a.PlayerScenarioType.Destroyed&&r.push({name:a.PlayerScenarioType.Destroyed,startTime:t,duration:0,details:s.HydraPlayerDestroyedReason.PlayerStopped}),e.init_allEvents=(0,l.stringifyObject)(r)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in ".concat(i," telemetry report."))}},e.prototype.updateStateChangeEventsWithDisposeEvent=function(e,t,i){try{var n=e.playback_stateChangeEvents,s=JSON.parse(n);s[s.length-1].name!==r.HydraPlayerPlaybackState.Destroyed&&s.push({eventType:a.TelemetryEventType.StateChanged,timestamp:t,currentPlayPosition:-1,payload:r.HydraPlayerPlaybackState.Destroyed}),e.playback_stateChangeEvents=(0,l.stringifyObject)(s)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in ".concat(i," telemetry report."))}},e}();t.TelemetryReportHandler=c},735:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},s=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcIceCandidateCollector=void 0;var a=i(103),o=i(534),l=i(508),c=function(){function e(e){this.playerSettings=e,this.latestCandidates=[],this.newCandidates=[],this.peerConnection=null,this.timeoutId=void 0,this.candidatesCollectionDefer=null,this.delayAfterComplete=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterCompleteMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterCompleteMs),this.delayAfterError=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterErrorMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterErrorMs),this.maxRetries=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxRetriesMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxRetriesMs),this.retryDelay=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorRetryDelayMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorRetryDelayMs),this.maxCollectionTime=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxCollectionTimeMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxCollectionTimeMs),this.disabledCollection=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDisableCollection",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDisableCollection)}return e.prototype.handleIceCandidate=function(e){e.candidate&&this.newCandidates.push(e.candidate)},e.prototype.handleIceGatheringStateChange=function(){var e,t;"complete"===(null===(e=this.peerConnection)||void 0===e?void 0:e.iceGatheringState)&&(this.latestCandidates=s([],this.newCandidates,!0),this.newCandidates=[],null===(t=this.candidatesCollectionDefer)||void 0===t||t.resolve(),this.candidatesCollectionDefer=null,this.destroyConnection(),this.clearCollectionTimeout(),this.startCandidatesCollection(this.delayAfterComplete))},e.prototype.setUpPeerConnection=function(){return n(this,void 0,void 0,(function(){var e,t,i,n;return r(this,(function(r){switch(r.label){case 0:return r.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===(i=this.peerConnection)||void 0===i?void 0:i.createOffer()];case 1:return e=r.sent(),[4,null===(n=this.peerConnection)||void 0===n?void 0:n.setLocalDescription(e)];case 2:return r.sent(),[3,4];case 3:throw t=r.sent(),this.destroyConnection(),new Error("Failure starting collection: ".concat((0,o.stringifyError)(t)));case 4:return[2]}}))}))},e.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)},e.prototype.clearCollectionTimeout=function(){void 0!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)},e.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)},e.prototype.startCandidatesCollection=function(){return n(this,arguments,void 0,(function(e){var t,i=this;return void 0===e&&(e=0),r(this,(function(s){switch(s.label){case 0:return this.candidatesCollectionDefer||this.disabledCollection?[2]:e>0?[4,new Promise((function(t){return setTimeout(t,e)}))]:[3,2];case 1:s.sent(),s.label=2;case 2:return this.candidatesCollectionDefer=(0,a.defer)(),this.candidatesCollectionDefer.promise.catch((function(){})),t=this.setUpPeerConnection.bind(this),[4,(0,o.retry)(t,this.maxRetries,this.retryDelay).then((function(){i.timeoutId=setTimeout((function(){var e;null===(e=i.candidatesCollectionDefer)||void 0===e||e.reject(new Error("Collection timed out")),i.candidatesCollectionDefer=null,i.destroyConnection(),i.startCandidatesCollection(i.delayAfterError)}),i.maxCollectionTime)})).catch((function(e){return n(i,void 0,void 0,(function(){var t,i;return r(this,(function(n){switch(n.label){case 0:return t="Failed to start collection ".concat((0,o.stringifyError)(e)),null===(i=this.candidatesCollectionDefer)||void 0===i||i.reject(new Error(t)),this.candidatesCollectionDefer=null,[4,Promise.reject(new Error(t))];case 1:return n.sent(),this.startCandidatesCollection(this.delayAfterError),[2]}}))}))}))];case 3:return s.sent(),[2]}}))}))},e.prototype.getCandidates=function(){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return 0===this.latestCandidates.length&&this.candidatesCollectionDefer?[4,this.candidatesCollectionDefer.promise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2,this.latestCandidates]}}))}))},e}();t.WebRtcIceCandidateCollector=c}},t={},function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}(260);var e,t},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e.hydra_player_sdk=n():i.hydra_player_sdk=n()}}),z=u({"../node_modules/pako/lib/utils/common.js"(e){var t="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var r in n)i(n,r)&&(e[r]=n[r])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),r);else for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){var t,i,n,r,s,a;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(a=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)s=e[t],a.set(s,r),r+=s.length;return a}},r={arraySet:function(e,t,i,n,r){for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,r))},e.setTyped(t)}}),W=u({"../node_modules/pako/lib/zlib/trees.js"(e){var t=z();function i(e){for(var t=e.length;--t>=0;)e[t]=0}var n=[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],r=[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],s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],a=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],o=new Array(576);i(o);var l=new Array(60);i(l);var c=new Array(512);i(c);var d=new Array(256);i(d);var u=new Array(29);i(u);var h,g,p,m=new Array(30);function f(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function S(e){return e<256?c[e]:c[256+(e>>>7)]}function y(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function C(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,y(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function T(e,t,i){C(e,i[2*t],i[2*t+1])}function E(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function b(e,t,i){var n,r,s=new Array(16),a=0;for(n=1;n<=15;n++)s[n]=a=a+i[n-1]<<1;for(r=0;r<=t;r++){var o=e[2*r+1];0!==o&&(e[2*r]=E(s[o]++,o))}}function _(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function I(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function w(e,i,n,r){I(e),r&&(y(e,n),y(e,~n)),t.arraySet(e.pending_buf,e.window,i,n,e.pending),e.pending+=n}function A(e,t,i,n){var r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]}function P(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&A(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!A(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function R(e,t,i){var s,a,o,l,c=0;if(0!==e.last_lit)do{s=e.pending_buf[e.d_buf+2*c]<<8|e.pending_buf[e.d_buf+2*c+1],a=e.pending_buf[e.l_buf+c],c++,0===s?T(e,a,t):(T(e,(o=d[a])+256+1,t),0!==(l=n[o])&&C(e,a-=u[o],l),T(e,o=S(--s),i),0!==(l=r[o])&&C(e,s-=m[o],l))}while(c<e.last_lit);T(e,256,t)}function M(e,t){var i,n,r,s=t.dyn_tree,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<l;i++)0!==s[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):s[2*i+1]=0;for(;e.heap_len<2;)s[2*(r=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[r]=0,e.opt_len--,o&&(e.static_len-=a[2*r+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)P(e,s,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],P(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,s[2*r]=s[2*i]+s[2*n],e.depth[r]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,s[2*i+1]=s[2*n+1]=r,e.heap[1]=r++,P(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,r,s,a,o,l=t.dyn_tree,c=t.max_code,d=t.stat_desc.static_tree,u=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,g=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=15;s++)e.bl_count[s]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(s=l[2*l[2*(n=e.heap[i])+1]+1]+1)>p&&(s=p,m++),l[2*n+1]=s,n>c||(e.bl_count[s]++,a=0,n>=g&&(a=h[n-g]),o=l[2*n],e.opt_len+=o*(s+a),u&&(e.static_len+=o*(d[2*n+1]+a)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(n=e.bl_count[s];0!==n;)(r=e.heap[--i])>c||(l[2*r+1]!==s&&(e.opt_len+=(s-l[2*r+1])*l[2*r],l[2*r+1]=s),n--)}}(e,t),b(s,c,e.bl_count)}function D(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=a,a=t[2*(n+1)+1],++o<l&&r===a||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4))}function k(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),n=0;n<=i;n++)if(r=a,a=t[2*(n+1)+1],!(++o<l&&r===a)){if(o<c)do{T(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==s&&(T(e,r,e.bl_tree),o--),T(e,16,e.bl_tree),C(e,o-3,2)):o<=10?(T(e,17,e.bl_tree),C(e,o-3,3)):(T(e,18,e.bl_tree),C(e,o-11,7));o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4)}}i(m);var O=!1;function N(e,t,i,n){C(e,0+(n?1:0),3),w(e,t,i,!0)}e._tr_init=function(e){O||(function(){var e,t,i,a,v,S=new Array(16);for(i=0,a=0;a<28;a++)for(u[a]=i,e=0;e<1<<n[a];e++)d[i++]=a;for(d[i-1]=a,v=0,a=0;a<16;a++)for(m[a]=v,e=0;e<1<<r[a];e++)c[v++]=a;for(v>>=7;a<30;a++)for(m[a]=v<<7,e=0;e<1<<r[a]-7;e++)c[256+v++]=a;for(t=0;t<=15;t++)S[t]=0;for(e=0;e<=143;)o[2*e+1]=8,e++,S[8]++;for(;e<=255;)o[2*e+1]=9,e++,S[9]++;for(;e<=279;)o[2*e+1]=7,e++,S[7]++;for(;e<=287;)o[2*e+1]=8,e++,S[8]++;for(b(o,287,S),e=0;e<30;e++)l[2*e+1]=5,l[2*e]=E(e,5);h=new f(o,n,257,286,15),g=new f(l,r,0,30,15),p=new f(new Array(0),s,0,19,7)}(),O=!0),e.l_desc=new v(e.dyn_ltree,h),e.d_desc=new v(e.dyn_dtree,g),e.bl_desc=new v(e.bl_tree,p),e.bi_buf=0,e.bi_valid=0,_(e)},e._tr_stored_block=N,e._tr_flush_block=function(e,t,i,n){var r,s,c=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),M(e,e.l_desc),M(e,e.d_desc),c=function(e){var t;for(D(e,e.dyn_ltree,e.l_desc.max_code),D(e,e.dyn_dtree,e.d_desc.max_code),M(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*a[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?N(e,t,i,n):4===e.strategy||s===r?(C(e,2+(n?1:0),3),R(e,o,l)):(C(e,4+(n?1:0),3),function(e,t,i,n){var r;for(C(e,t-257,5),C(e,i-1,5),C(e,n-4,4),r=0;r<n;r++)C(e,e.bl_tree[2*a[r]+1],3);k(e,e.dyn_ltree,t-1),k(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,c+1),R(e,e.dyn_ltree,e.dyn_dtree)),_(e),n&&I(e)},e._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(d[i]+256+1)]++,e.dyn_dtree[2*S(t)]++),e.last_lit===e.lit_bufsize-1},e._tr_align=function(e){C(e,2,3),T(e,256,o),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}}}),K=u({"../node_modules/pako/lib/zlib/adler32.js"(e,t){t.exports=function(e,t,i,n){for(var r=65535&e,s=e>>>16&65535,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{s=s+(r=r+t[n++]|0)|0}while(--a);r%=65521,s%=65521}return r|s<<16}}}),J=u({"../node_modules/pako/lib/zlib/crc32.js"(e,t){var i=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,n,r){var s=i,a=r+n;e^=-1;for(var o=r;o<a;o++)e=e>>>8^s[255&(e^t[o])];return~e}}}),Y=u({"../node_modules/pako/lib/zlib/messages.js"(e,t){t.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"}}}),X=u({"../node_modules/pako/lib/zlib/deflate.js"(e){var t,i=z(),n=W(),r=K(),s=J(),a=Y(),o=-2,l=258,c=262,d=103,u=113,h=666;function g(e,t){return e.msg=a[t],t}function p(e){return(e<<1)-(e>4?9:0)}function m(e){for(var t=e.length;--t>=0;)e[t]=0}function f(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(i.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))}function v(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,f(e.strm)}function S(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function C(e,t,n,a){var o=e.avail_in;return o>a&&(o=a),0===o?0:(e.avail_in-=o,i.arraySet(t,e.input,e.next_in,o,n),1===e.state.wrap?e.adler=r(e.adler,t,o,n):2===e.state.wrap&&(e.adler=s(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)}function T(e,t){var i,n,r=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,d=e.strstart>e.w_size-c?e.strstart-(e.w_size-c):0,u=e.window,h=e.w_mask,g=e.prev,p=e.strstart+l,m=u[s+a-1],f=u[s+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(u[(i=t)+a]===f&&u[i+a-1]===m&&u[i]===u[s]&&u[++i]===u[s+1]){s+=2,i++;do{}while(u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&s<p);if(n=l-(p-s),s=p-l,n>a){if(e.match_start=t,a=n,n>=o)break;m=u[s+a-1],f=u[s+a]}}}while((t=g[t&h])>d&&0!=--r);return a<=e.lookahead?a:e.lookahead}function E(e){var t,n,r,s,a,o=e.w_size;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-c)){i.arraySet(e.window,e.window,o,o,0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=n=e.hash_size;do{r=e.head[--t],e.head[t]=r>=o?r-o:0}while(--n);t=n=o;do{r=e.prev[--t],e.prev[t]=r>=o?r-o:0}while(--n);s+=o}if(0===e.strm.avail_in)break;if(n=C(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=n,e.lookahead+e.insert>=3)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+3-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<c&&0!==e.strm.avail_in)}function b(e,t){for(var i,r;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-c&&(e.match_length=T(e,i)),e.match_length>=3)if(r=n._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function _(e,t){for(var i,r,s;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-c&&(e.match_length=T(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(v(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=n._tr_tally(e,0,e.window[e.strstart-1]))&&v(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function I(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}function w(e){e.window_size=2*e.w_size,m(e.head),e.max_lazy_match=t[e.level].max_lazy,e.good_match=t[e.level].good_length,e.nice_match=t[e.level].nice_length,e.max_chain_length=t[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0}function A(){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=8,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 i.Buf16(1146),this.dyn_dtree=new i.Buf16(122),this.bl_tree=new i.Buf16(78),m(this.dyn_ltree),m(this.dyn_dtree),m(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(16),this.heap=new i.Buf16(573),m(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(573),m(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 P(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:u,e.adler=2===t.wrap?0:1,t.last_flush=0,n._tr_init(t),0):g(e,o)}function R(e){var t=P(e);return 0===t&&w(e.state),t}function M(e,t,n,r,s,a){if(!e)return o;var l=1;if(-1===t&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),s<1||s>9||8!==n||r<8||r>15||t<0||t>9||a<0||a>4)return g(e,o);8===r&&(r=9);var c=new A;return e.state=c,c.strm=e,c.wrap=l,c.gzhead=null,c.w_bits=r,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=s+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+3-1)/3),c.window=new i.Buf8(2*c.w_size),c.head=new i.Buf16(c.hash_size),c.prev=new i.Buf16(c.w_size),c.lit_bufsize=1<<s+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new i.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=t,c.strategy=a,c.method=n,R(e)}t=[new I(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(E(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,v(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-c&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(v(e,!1),e.strm.avail_out),1)})),new I(4,4,8,4,b),new I(4,5,16,8,b),new I(4,6,32,32,b),new I(4,4,16,16,_),new I(8,16,32,32,_),new I(8,16,128,128,_),new I(8,32,128,256,_),new I(32,128,258,1024,_),new I(32,258,258,4096,_)],e.deflateInit=function(e,t){return M(e,t,8,15,8,0)},e.deflateInit2=M,e.deflateReset=R,e.deflateResetKeep=P,e.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?o:(e.state.gzhead=t,0):o},e.deflate=function(e,i){var r,a,c,C;if(!e||!e.state||i>5||i<0)return e?g(e,o):o;if(a=e.state,!e.output||!e.input&&0!==e.avail_in||a.status===h&&4!==i)return g(e,0===e.avail_out?-5:o);if(a.strm=e,r=a.last_flush,a.last_flush=i,42===a.status)if(2===a.wrap)e.adler=0,S(a,31),S(a,139),S(a,8),a.gzhead?(S(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),S(a,255&a.gzhead.time),S(a,a.gzhead.time>>8&255),S(a,a.gzhead.time>>16&255),S(a,a.gzhead.time>>24&255),S(a,9===a.level?2:a.strategy>=2||a.level<2?4:0),S(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(S(a,255&a.gzhead.extra.length),S(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(e.adler=s(e.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69):(S(a,0),S(a,0),S(a,0),S(a,0),S(a,0),S(a,9===a.level?2:a.strategy>=2||a.level<2?4:0),S(a,3),a.status=u);else{var T=8+(a.w_bits-8<<4)<<8;T|=(a.strategy>=2||a.level<2?0:a.level<6?1:6===a.level?2:3)<<6,0!==a.strstart&&(T|=32),T+=31-T%31,a.status=u,y(a,T),0!==a.strstart&&(y(a,e.adler>>>16),y(a,65535&e.adler)),e.adler=1}if(69===a.status)if(a.gzhead.extra){for(c=a.pending;a.gzindex<(65535&a.gzhead.extra.length)&&(a.pending!==a.pending_buf_size||(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending!==a.pending_buf_size));)S(a,255&a.gzhead.extra[a.gzindex]),a.gzindex++;a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=73)}else a.status=73;if(73===a.status)if(a.gzhead.name){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending===a.pending_buf_size)){C=1;break}C=a.gzindex<a.gzhead.name.length?255&a.gzhead.name.charCodeAt(a.gzindex++):0,S(a,C)}while(0!==C);a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),0===C&&(a.gzindex=0,a.status=91)}else a.status=91;if(91===a.status)if(a.gzhead.comment){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending===a.pending_buf_size)){C=1;break}C=a.gzindex<a.gzhead.comment.length?255&a.gzhead.comment.charCodeAt(a.gzindex++):0,S(a,C)}while(0!==C);a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),0===C&&(a.status=d)}else a.status=d;if(a.status===d&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&f(e),a.pending+2<=a.pending_buf_size&&(S(a,255&e.adler),S(a,e.adler>>8&255),e.adler=0,a.status=u)):a.status=u),0!==a.pending){if(f(e),0===e.avail_out)return a.last_flush=-1,0}else if(0===e.avail_in&&p(i)<=p(r)&&4!==i)return g(e,-5);if(a.status===h&&0!==e.avail_in)return g(e,-5);if(0!==e.avail_in||0!==a.lookahead||0!==i&&a.status!==h){var b=2===a.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(E(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(a,i):3===a.strategy?function(e,t){for(var i,r,s,a,o=e.window;;){if(e.lookahead<=l){if(E(e),e.lookahead<=l&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=o[s=e.strstart-1])===o[++s]&&r===o[++s]&&r===o[++s]){a=e.strstart+l;do{}while(r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&s<a);e.match_length=l-(a-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=n._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(a,i):t[a.level].func(a,i);if(3!==b&&4!==b||(a.status=h),1===b||3===b)return 0===e.avail_out&&(a.last_flush=-1),0;if(2===b&&(1===i?n._tr_align(a):5!==i&&(n._tr_stored_block(a,0,0,!1),3===i&&(m(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),f(e),0===e.avail_out))return a.last_flush=-1,0}return 4!==i?0:a.wrap<=0?1:(2===a.wrap?(S(a,255&e.adler),S(a,e.adler>>8&255),S(a,e.adler>>16&255),S(a,e.adler>>24&255),S(a,255&e.total_in),S(a,e.total_in>>8&255),S(a,e.total_in>>16&255),S(a,e.total_in>>24&255)):(y(a,e.adler>>>16),y(a,65535&e.adler)),f(e),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?0:1)},e.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==d&&t!==u&&t!==h?g(e,o):(e.state=null,t===u?g(e,-3):0):o},e.deflateSetDictionary=function(e,t){var n,s,a,l,c,d,u,h,g=t.length;if(!e||!e.state)return o;if(2===(l=(n=e.state).wrap)||1===l&&42!==n.status||n.lookahead)return o;for(1===l&&(e.adler=r(e.adler,t,g,0)),n.wrap=0,g>=n.w_size&&(0===l&&(m(n.head),n.strstart=0,n.block_start=0,n.insert=0),h=new i.Buf8(n.w_size),i.arraySet(h,t,g-n.w_size,n.w_size,0),t=h,g=n.w_size),c=e.avail_in,d=e.next_in,u=e.input,e.avail_in=g,e.next_in=0,e.input=t,E(n);n.lookahead>=3;){s=n.strstart,a=n.lookahead-2;do{n.ins_h=(n.ins_h<<n.hash_shift^n.window[s+3-1])&n.hash_mask,n.prev[s&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=s,s++}while(--a);n.strstart=s,n.lookahead=2,E(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=d,e.input=u,e.avail_in=c,n.wrap=l,0},e.deflateInfo="pako deflate (from Nodeca project)"}}),ee=u({"../node_modules/pako/lib/utils/strings.js"(e){var t=z(),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}var r,s=new t.Buf8(256);for(r=0;r<256;r++)s[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;function a(e,r){if(r<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,t.shrinkBuf(e,r));for(var s="",a=0;a<r;a++)s+=String.fromCharCode(e[a]);return s}s[254]=s[254]=1,e.string2buf=function(e){var i,n,r,s,a,o=e.length,l=0;for(s=0;s<o;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),l+=n<128?1:n<2048?2:n<65536?3:4;for(i=new t.Buf8(l),a=0,s=0;a<l;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),n<128?i[a++]=n:n<2048?(i[a++]=192|n>>>6,i[a++]=128|63&n):n<65536?(i[a++]=224|n>>>12,i[a++]=128|n>>>6&63,i[a++]=128|63&n):(i[a++]=240|n>>>18,i[a++]=128|n>>>12&63,i[a++]=128|n>>>6&63,i[a++]=128|63&n);return i},e.buf2binstring=function(e){return a(e,e.length)},e.binstring2buf=function(e){for(var i=new t.Buf8(e.length),n=0,r=i.length;n<r;n++)i[n]=e.charCodeAt(n);return i},e.buf2string=function(e,t){var i,n,r,o,l=t||e.length,c=new Array(2*l);for(n=0,i=0;i<l;)if((r=e[i++])<128)c[n++]=r;else if((o=s[r])>4)c[n++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i<l;)r=r<<6|63&e[i++],o--;o>1?c[n++]=65533:r<65536?c[n++]=r:(r-=65536,c[n++]=55296|r>>10&1023,c[n++]=56320|1023&r)}return a(c,n)},e.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+s[e[i]]>t?i:t}}}),te=u({"../node_modules/pako/lib/zlib/zstream.js"(e,t){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}}),ie=u({"../node_modules/pako/lib/deflate.js"(e){var t=X(),i=z(),n=ee(),r=Y(),s=te(),a=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=i.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var l=this.options;l.raw&&l.windowBits>0?l.windowBits=-l.windowBits:l.gzip&&l.windowBits>0&&l.windowBits<16&&(l.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,l.level,l.method,l.windowBits,l.memLevel,l.strategy);if(0!==c)throw new Error(r[c]);if(l.header&&t.deflateSetHeader(this.strm,l.header),l.dictionary){var d;if(d="string"==typeof l.dictionary?n.string2buf(l.dictionary):"[object ArrayBuffer]"===a.call(l.dictionary)?new Uint8Array(l.dictionary):l.dictionary,0!==(c=t.deflateSetDictionary(this.strm,d)))throw new Error(r[c]);this._dict_set=!0}}function l(e,t){var i=new o(t);if(i.push(e,!0),i.err)throw i.msg||r[i.err];return i.result}o.prototype.push=function(e,r){var s,o,l=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=r===~~r?r:!0===r?4:0,"string"==typeof e?l.input=n.string2buf(e):"[object ArrayBuffer]"===a.call(e)?l.input=new Uint8Array(e):l.input=e,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new i.Buf8(c),l.next_out=0,l.avail_out=c),1!==(s=t.deflate(l,o))&&0!==s)return this.onEnd(s),this.ended=!0,!1;0!==l.avail_out&&(0!==l.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(n.buf2binstring(i.shrinkBuf(l.output,l.next_out))):this.onData(i.shrinkBuf(l.output,l.next_out)))}while((l.avail_in>0||0===l.avail_out)&&1!==s);return 4===o?(s=t.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,0===s):2!==o||(this.onEnd(0),l.avail_out=0,!0)},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Deflate=o,e.deflate=l,e.deflateRaw=function(e,t){return(t=t||{}).raw=!0,l(e,t)},e.gzip=function(e,t){return(t=t||{}).gzip=!0,l(e,t)}}}),ne=u({"../node_modules/pako/lib/zlib/inffast.js"(e,t){t.exports=function(e,t){var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w;i=e.state,n=e.next_in,I=e.input,r=n+(e.avail_in-5),s=e.next_out,w=e.output,a=s-(t-e.avail_out),o=s+(e.avail_out-257),l=i.dmax,c=i.wsize,d=i.whave,u=i.wnext,h=i.window,g=i.hold,p=i.bits,m=i.lencode,f=i.distcode,v=(1<<i.lenbits)-1,S=(1<<i.distbits)-1;e:do{p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=m[g&v];t:for(;;){if(g>>>=C=y>>>24,p-=C,0==(C=y>>>16&255))w[s++]=65535&y;else{if(!(16&C)){if(64&C){if(32&C){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}y=m[(65535&y)+(g&(1<<C)-1)];continue t}for(T=65535&y,(C&=15)&&(p<C&&(g+=I[n++]<<p,p+=8),T+=g&(1<<C)-1,g>>>=C,p-=C),p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=f[g&S];;){if(g>>>=C=y>>>24,p-=C,16&(C=y>>>16&255)){if(E=65535&y,p<(C&=15)&&(g+=I[n++]<<p,(p+=8)<C&&(g+=I[n++]<<p,p+=8)),(E+=g&(1<<C)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(g>>>=C,p-=C,E>(C=s-a)){if((C=E-C)>d&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(b=0,_=h,0===u){if(b+=c-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}else if(u<C){if(b+=c+u-C,(C-=u)<T){T-=C;do{w[s++]=h[b++]}while(--C);if(b=0,u<T){T-=C=u;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}}else if(b+=u-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}for(;T>2;)w[s++]=_[b++],w[s++]=_[b++],w[s++]=_[b++],T-=3;T&&(w[s++]=_[b++],T>1&&(w[s++]=_[b++]))}else{b=s-E;do{w[s++]=w[b++],w[s++]=w[b++],w[s++]=w[b++],T-=3}while(T>2);T&&(w[s++]=w[b++],T>1&&(w[s++]=w[b++]))}break}if(64&C){e.msg="invalid distance code",i.mode=30;break e}y=f[(65535&y)+(g&(1<<C)-1)]}}break}}while(n<r&&s<o);n-=T=p>>3,g&=(1<<(p-=T<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=s<o?o-s+257:257-(s-o),i.hold=g,i.bits=p}}}),re=u({"../node_modules/pako/lib/zlib/inftrees.js"(e,t){var i=z(),n=[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],r=[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],s=[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],a=[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];t.exports=function(e,t,o,l,c,d,u,h){var g,p,m,f,v,S,y,C,T,E=h.bits,b=0,_=0,I=0,w=0,A=0,P=0,R=0,M=0,D=0,k=0,O=null,N=0,L=new i.Buf16(16),x=new i.Buf16(16),F=null,U=0;for(b=0;b<=15;b++)L[b]=0;for(_=0;_<l;_++)L[t[o+_]]++;for(A=E,w=15;w>=1&&0===L[w];w--);if(A>w&&(A=w),0===w)return c[d++]=20971520,c[d++]=20971520,h.bits=1,0;for(I=1;I<w&&0===L[I];I++);for(A<I&&(A=I),M=1,b=1;b<=15;b++)if(M<<=1,(M-=L[b])<0)return-1;if(M>0&&(0===e||1!==w))return-1;for(x[1]=0,b=1;b<15;b++)x[b+1]=x[b]+L[b];for(_=0;_<l;_++)0!==t[o+_]&&(u[x[t[o+_]]++]=_);if(0===e?(O=F=u,S=19):1===e?(O=n,N-=257,F=r,U-=257,S=256):(O=s,F=a,S=-1),k=0,_=0,b=I,v=d,P=A,R=0,m=-1,f=(D=1<<A)-1,1===e&&D>852||2===e&&D>592)return 1;for(;;){y=b-R,u[_]<S?(C=0,T=u[_]):u[_]>S?(C=F[U+u[_]],T=O[N+u[_]]):(C=96,T=0),g=1<<b-R,I=p=1<<P;do{c[v+(k>>R)+(p-=g)]=y<<24|C<<16|T}while(0!==p);for(g=1<<b-1;k&g;)g>>=1;if(0!==g?(k&=g-1,k+=g):k=0,_++,0==--L[b]){if(b===w)break;b=t[o+u[_]]}if(b>A&&(k&f)!==m){for(0===R&&(R=A),v+=I,M=1<<(P=b-R);P+R<w&&!((M-=L[P+R])<=0);)P++,M<<=1;if(D+=1<<P,1===e&&D>852||2===e&&D>592)return 1;c[m=k&f]=A<<24|P<<16|v-d}}return 0!==k&&(c[v+k]=b-R<<24|64<<16),h.bits=A,0}}}),se=u({"../node_modules/pako/lib/zlib/inflate.js"(e){var t=z(),i=K(),n=J(),r=ne(),s=re(),a=-2,o=12,l=30;function c(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function d(){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 t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function u(e){var i;return e&&e.state?(i=e.state,e.total_in=e.total_out=i.total=0,e.msg="",i.wrap&&(e.adler=1&i.wrap),i.mode=1,i.last=0,i.havedict=0,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new t.Buf32(852),i.distcode=i.distdyn=new t.Buf32(592),i.sane=1,i.back=-1,0):a}function h(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,u(e)):a}function g(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?a:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,h(e))):a}function p(e,t){var i,n;return e?(n=new d,e.state=n,n.window=null,0!==(i=g(e,t))&&(e.state=null),i):a}var m,f,v=!0;function S(e){if(v){var i;for(m=new t.Buf32(512),f=new t.Buf32(32),i=0;i<144;)e.lens[i++]=8;for(;i<256;)e.lens[i++]=9;for(;i<280;)e.lens[i++]=7;for(;i<288;)e.lens[i++]=8;for(s(1,e.lens,0,288,m,0,e.work,{bits:9}),i=0;i<32;)e.lens[i++]=5;s(2,e.lens,0,32,f,0,e.work,{bits:5}),v=!1}e.lencode=m,e.lenbits=9,e.distcode=f,e.distbits=5}function y(e,i,n,r){var s,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new t.Buf8(a.wsize)),r>=a.wsize?(t.arraySet(a.window,i,n-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((s=a.wsize-a.wnext)>r&&(s=r),t.arraySet(a.window,i,n-r,s,a.wnext),(r-=s)?(t.arraySet(a.window,i,n-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=s,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=s))),0}e.inflateReset=h,e.inflateReset2=g,e.inflateResetKeep=u,e.inflateInit=function(e){return p(e,15)},e.inflateInit2=p,e.inflate=function(e,d){var u,h,g,p,m,f,v,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x,F=0,U=new t.Buf8(4),B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return a;(u=e.state).mode===o&&(u.mode=13),m=e.next_out,g=e.output,v=e.avail_out,p=e.next_in,h=e.input,f=e.avail_in,C=u.hold,T=u.bits,E=f,b=v,N=0;e:for(;;)switch(u.mode){case 1:if(0===u.wrap){u.mode=13;break}for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(2&u.wrap&&35615===C){u.check=0,U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0),C=0,T=0,u.mode=2;break}if(u.flags=0,u.head&&(u.head.done=!1),!(1&u.wrap)||(((255&C)<<8)+(C>>8))%31){e.msg="incorrect header check",u.mode=l;break}if(8!=(15&C)){e.msg="unknown compression method",u.mode=l;break}if(T-=4,O=8+(15&(C>>>=4)),0===u.wbits)u.wbits=O;else if(O>u.wbits){e.msg="invalid window size",u.mode=l;break}u.dmax=1<<O,e.adler=u.check=1,u.mode=512&C?10:o,C=0,T=0;break;case 2:for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(u.flags=C,8!=(255&u.flags)){e.msg="unknown compression method",u.mode=l;break}if(57344&u.flags){e.msg="unknown header flags set",u.mode=l;break}u.head&&(u.head.text=C>>8&1),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0,u.mode=3;case 3:for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.head&&(u.head.time=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,U[2]=C>>>16&255,U[3]=C>>>24&255,u.check=n(u.check,U,4,0)),C=0,T=0,u.mode=4;case 4:for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.head&&(u.head.xflags=255&C,u.head.os=C>>8),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0,u.mode=5;case 5:if(1024&u.flags){for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.length=C,u.head&&(u.head.extra_len=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0}else u.head&&(u.head.extra=null);u.mode=6;case 6:if(1024&u.flags&&((_=u.length)>f&&(_=f),_&&(u.head&&(O=u.head.extra_len-u.length,u.head.extra||(u.head.extra=new Array(u.head.extra_len)),t.arraySet(u.head.extra,h,p,_,O)),512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,u.length-=_),u.length))break e;u.length=0,u.mode=7;case 7:if(2048&u.flags){if(0===f)break e;_=0;do{O=h[p+_++],u.head&&O&&u.length<65536&&(u.head.name+=String.fromCharCode(O))}while(O&&_<f);if(512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,O)break e}else u.head&&(u.head.name=null);u.length=0,u.mode=8;case 8:if(4096&u.flags){if(0===f)break e;_=0;do{O=h[p+_++],u.head&&O&&u.length<65536&&(u.head.comment+=String.fromCharCode(O))}while(O&&_<f);if(512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,O)break e}else u.head&&(u.head.comment=null);u.mode=9;case 9:if(512&u.flags){for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C!==(65535&u.check)){e.msg="header crc mismatch",u.mode=l;break}C=0,T=0}u.head&&(u.head.hcrc=u.flags>>9&1,u.head.done=!0),e.adler=u.check=0,u.mode=o;break;case 10:for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}e.adler=u.check=c(C),C=0,T=0,u.mode=11;case 11:if(0===u.havedict)return e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,2;e.adler=u.check=1,u.mode=o;case o:if(5===d||6===d)break e;case 13:if(u.last){C>>>=7&T,T-=7&T,u.mode=27;break}for(;T<3;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}switch(u.last=1&C,T-=1,3&(C>>>=1)){case 0:u.mode=14;break;case 1:if(S(u),u.mode=20,6===d){C>>>=2,T-=2;break e}break;case 2:u.mode=17;break;case 3:e.msg="invalid block type",u.mode=l}C>>>=2,T-=2;break;case 14:for(C>>>=7&T,T-=7&T;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if((65535&C)!=(C>>>16^65535)){e.msg="invalid stored block lengths",u.mode=l;break}if(u.length=65535&C,C=0,T=0,u.mode=15,6===d)break e;case 15:u.mode=16;case 16:if(_=u.length){if(_>f&&(_=f),_>v&&(_=v),0===_)break e;t.arraySet(g,h,p,_,m),f-=_,p+=_,v-=_,m+=_,u.length-=_;break}u.mode=o;break;case 17:for(;T<14;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(u.nlen=257+(31&C),C>>>=5,T-=5,u.ndist=1+(31&C),C>>>=5,T-=5,u.ncode=4+(15&C),C>>>=4,T-=4,u.nlen>286||u.ndist>30){e.msg="too many length or distance symbols",u.mode=l;break}u.have=0,u.mode=18;case 18:for(;u.have<u.ncode;){for(;T<3;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.lens[B[u.have++]]=7&C,C>>>=3,T-=3}for(;u.have<19;)u.lens[B[u.have++]]=0;if(u.lencode=u.lendyn,u.lenbits=7,L={bits:u.lenbits},N=s(0,u.lens,0,19,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid code lengths set",u.mode=l;break}u.have=0,u.mode=19;case 19:for(;u.have<u.nlen+u.ndist;){for(;P=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(R<16)C>>>=A,T-=A,u.lens[u.have++]=R;else{if(16===R){for(x=A+2;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C>>>=A,T-=A,0===u.have){e.msg="invalid bit length repeat",u.mode=l;break}O=u.lens[u.have-1],_=3+(3&C),C>>>=2,T-=2}else if(17===R){for(x=A+3;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}T-=A,O=0,_=3+(7&(C>>>=A)),C>>>=3,T-=3}else{for(x=A+7;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}T-=A,O=0,_=11+(127&(C>>>=A)),C>>>=7,T-=7}if(u.have+_>u.nlen+u.ndist){e.msg="invalid bit length repeat",u.mode=l;break}for(;_--;)u.lens[u.have++]=O}}if(u.mode===l)break;if(0===u.lens[256]){e.msg="invalid code -- missing end-of-block",u.mode=l;break}if(u.lenbits=9,L={bits:u.lenbits},N=s(1,u.lens,0,u.nlen,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid literal/lengths set",u.mode=l;break}if(u.distbits=6,u.distcode=u.distdyn,L={bits:u.distbits},N=s(2,u.lens,u.nlen,u.ndist,u.distcode,0,u.work,L),u.distbits=L.bits,N){e.msg="invalid distances set",u.mode=l;break}if(u.mode=20,6===d)break e;case 20:u.mode=21;case 21:if(f>=6&&v>=258){e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,r(e,b),m=e.next_out,g=e.output,v=e.avail_out,p=e.next_in,h=e.input,f=e.avail_in,C=u.hold,T=u.bits,u.mode===o&&(u.back=-1);break}for(u.back=0;P=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(P&&!(240&P)){for(M=A,D=P,k=R;P=(F=u.lencode[k+((C&(1<<M+D)-1)>>M)])>>>16&255,R=65535&F,!(M+(A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}C>>>=M,T-=M,u.back+=M}if(C>>>=A,T-=A,u.back+=A,u.length=R,0===P){u.mode=26;break}if(32&P){u.back=-1,u.mode=o;break}if(64&P){e.msg="invalid literal/length code",u.mode=l;break}u.extra=15&P,u.mode=22;case 22:if(u.extra){for(x=u.extra;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.length+=C&(1<<u.extra)-1,C>>>=u.extra,T-=u.extra,u.back+=u.extra}u.was=u.length,u.mode=23;case 23:for(;P=(F=u.distcode[C&(1<<u.distbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(!(240&P)){for(M=A,D=P,k=R;P=(F=u.distcode[k+((C&(1<<M+D)-1)>>M)])>>>16&255,R=65535&F,!(M+(A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}C>>>=M,T-=M,u.back+=M}if(C>>>=A,T-=A,u.back+=A,64&P){e.msg="invalid distance code",u.mode=l;break}u.offset=R,u.extra=15&P,u.mode=24;case 24:if(u.extra){for(x=u.extra;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.offset+=C&(1<<u.extra)-1,C>>>=u.extra,T-=u.extra,u.back+=u.extra}if(u.offset>u.dmax){e.msg="invalid distance too far back",u.mode=l;break}u.mode=25;case 25:if(0===v)break e;if(_=b-v,u.offset>_){if((_=u.offset-_)>u.whave&&u.sane){e.msg="invalid distance too far back",u.mode=l;break}_>u.wnext?(_-=u.wnext,I=u.wsize-_):I=u.wnext-_,_>u.length&&(_=u.length),w=u.window}else w=g,I=m-u.offset,_=u.length;_>v&&(_=v),v-=_,u.length-=_;do{g[m++]=w[I++]}while(--_);0===u.length&&(u.mode=21);break;case 26:if(0===v)break e;g[m++]=u.length,v--,u.mode=21;break;case 27:if(u.wrap){for(;T<32;){if(0===f)break e;f--,C|=h[p++]<<T,T+=8}if(b-=v,e.total_out+=b,u.total+=b,b&&(e.adler=u.check=u.flags?n(u.check,g,b,m-b):i(u.check,g,b,m-b)),b=v,(u.flags?C:c(C))!==u.check){e.msg="incorrect data check",u.mode=l;break}C=0,T=0}u.mode=28;case 28:if(u.wrap&&u.flags){for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C!==(4294967295&u.total)){e.msg="incorrect length check",u.mode=l;break}C=0,T=0}u.mode=29;case 29:N=1;break e;case l:N=-3;break e;case 31:return-4;default:return a}return e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,(u.wsize||b!==e.avail_out&&u.mode<l&&(u.mode<27||4!==d))&&y(e,e.output,e.next_out,b-e.avail_out),E-=e.avail_in,b-=e.avail_out,e.total_in+=E,e.total_out+=b,u.total+=b,u.wrap&&b&&(e.adler=u.check=u.flags?n(u.check,g,b,e.next_out-b):i(u.check,g,b,e.next_out-b)),e.data_type=u.bits+(u.last?64:0)+(u.mode===o?128:0)+(20===u.mode||15===u.mode?256:0),(0===E&&0===b||4===d)&&0===N&&(N=-5),N},e.inflateEnd=function(e){if(!e||!e.state)return a;var t=e.state;return t.window&&(t.window=null),e.state=null,0},e.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,0):a},e.inflateSetDictionary=function(e,t){var n,r=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?a:11===n.mode&&i(1,t,r,0)!==n.check?-3:y(e,t,r,r)?(n.mode=31,-4):(n.havedict=1,0):a},e.inflateInfo="pako inflate (from Nodeca project)"}}),ae=u({"../node_modules/pako/lib/zlib/constants.js"(e,t){t.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}}}),oe=u({"../node_modules/pako/lib/zlib/gzheader.js"(e,t){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}}}),le=u({"../node_modules/pako/lib/inflate.js"(e){var t=se(),i=z(),n=ee(),r=ae(),s=Y(),a=te(),o=oe(),l=Object.prototype.toString;function c(e){if(!(this instanceof c))return new c(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var d=this.options;d.raw&&d.windowBits>=0&&d.windowBits<16&&(d.windowBits=-d.windowBits,0===d.windowBits&&(d.windowBits=-15)),!(d.windowBits>=0&&d.windowBits<16)||e&&e.windowBits||(d.windowBits+=32),d.windowBits>15&&d.windowBits<48&&(15&d.windowBits||(d.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var u=t.inflateInit2(this.strm,d.windowBits);if(u!==r.Z_OK)throw new Error(s[u]);if(this.header=new o,t.inflateGetHeader(this.strm,this.header),d.dictionary&&("string"==typeof d.dictionary?d.dictionary=n.string2buf(d.dictionary):"[object ArrayBuffer]"===l.call(d.dictionary)&&(d.dictionary=new Uint8Array(d.dictionary)),d.raw&&(u=t.inflateSetDictionary(this.strm,d.dictionary))!==r.Z_OK))throw new Error(s[u])}function d(e,t){var i=new c(t);if(i.push(e,!0),i.err)throw i.msg||s[i.err];return i.result}c.prototype.push=function(e,s){var a,o,c,d,u,h=this.strm,g=this.options.chunkSize,p=this.options.dictionary,m=!1;if(this.ended)return!1;o=s===~~s?s:!0===s?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=n.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(g),h.next_out=0,h.avail_out=g),(a=t.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&p&&(a=t.inflateSetDictionary(this.strm,p)),a===r.Z_BUF_ERROR&&!0===m&&(a=r.Z_OK,m=!1),a!==r.Z_STREAM_END&&a!==r.Z_OK)return this.onEnd(a),this.ended=!0,!1;h.next_out&&(0!==h.avail_out&&a!==r.Z_STREAM_END&&(0!==h.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=n.utf8border(h.output,h.next_out),d=h.next_out-c,u=n.buf2string(h.output,c),h.next_out=d,h.avail_out=g-d,d&&i.arraySet(h.output,h.output,c,d,0),this.onData(u)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(m=!0)}while((h.avail_in>0||0===h.avail_out)&&a!==r.Z_STREAM_END);return a===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(a=t.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),h.avail_out=0,!0)},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Inflate=c,e.inflate=d,e.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},e.ungzip=d}}),ce=u({"../node_modules/pako/index.js"(e,t){var i={};(0,z().assign)(i,ie(),le(),ae()),t.exports=i}}),de=u({"../signaling-agent/node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.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(e){return null!=e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.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(e){return null!=e.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(e){return null!=e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.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(e){return"x-signaling-fb:"+("*"===e.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(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ue=u({"../signaling-agent/node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))})(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=de(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),he=u({"../signaling-agent/node_modules/sdp-transform/lib/writer.js"(e,t){var i=de(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?n.push(i[t.name][a]):n.push(i[t.names[s]])}else n.push(i[t.name]);return r.apply(null,n)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||a,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))})),e.media.forEach((function(e){l.push(s("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),ge=u({"../signaling-agent/node_modules/sdp-transform/lib/index.js"(e){var t=ue(),i=he();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),pe=u({"../skype-calling-utilities/dist/skype-calling-utilities.bundle.js"(e,t){var i,n;i=e,n=(e,t)=>{var i={},n={exports:i},r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,l={};((e,t)=>{for(var i in t)r(e,i,{get:t[i],enumerable:!0})})(l,{SlimCoreElectronControlCapturer:()=>p}),n.exports=(e=>((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of a(t))o.call(e,i)||undefined===i||r(e,i,{get:()=>t[i],enumerable:!(n=s(t,i))||n.enumerable});return e})(r({},"__esModule",{value:!0}),e))(l);var c=Z;var d,u=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new h(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",function(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}(e))}}))}},h=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,c.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},g=class extends u{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}async onAsync(e,t){return this.on(e,t)}async onceAsync(e,t,i){return this.once(e,t,i)}async changedAsync(e,t){return this.changed(e,t)}async disposeAsync(e){this.dispose(e)}};(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,s=(e.buttonDown?1:0)<<5,a=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|s|a),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,s=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|s),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(d||(d={}));var p=class extends g{constructor(e,t,i=!0,n=1){super(),this._logger=e,this._element=t,this._captureRegionPreserveAspectRatio=i,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()}),250)},this._handleMouseLeave=e=>{!this._isOnScreenContent(e)&&this._isMouseOnRenderer&&(this._raiseCaptureEvent(2),this._logger.info("Mouse leaving render region")),this._isMouseOnRenderer=!1},this._handleMouseEnter=e=>{this._isOnScreenContent(e)&&(this._isMouseOnRenderer=!0,this._raiseCaptureEvent(1),this._logger.info("Mouse entering render region"))},this._handleLosingFocus=()=>{this._syncKeyStates(!0)},this._handleClick=e=>{this._isOnScreenContent(e)&&(this._raiseCaptureEvent(0),this._logger.info("Mouse clicked"))},this._handleMouseMove=e=>{if(!this._isOnScreenContent(e)&&this._isMouseOnRenderer)return this._raiseCaptureEvent(2),this._isMouseOnRenderer=!1,void this._logger.info("Mouse leaving render region");if(this._isOnScreenContent(e)&&!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(e)||!this._shouldMoveMouse())return}else if(!this._isOnScreenContent(e)||this._mouseMoveCount%2==0)return;const t={type:0};this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseDown=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:m(e.button),buttonDown:!0};this._isMouseDown=!0,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseUp=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:m(e.button),buttonDown:!1};this._isMouseDown=!1,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleKeyDown=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!1}),e.stopPropagation(),e.preventDefault()},this._handleKeyUp=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!0}),e.stopPropagation(),e.preventDefault()},this._handleWheel=e=>{this._raiseMouseEvent({type:1,wheelRotation:e.deltaY>0?-120:120})},this._handleContextMenu=e=>{e.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(t.clientHeight*n),height:t.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(e){this._mouseMoveThrottlingEnabled=e}dispose(e){this._logger.info(`dispose causeId: ${e}`),window.clearTimeout(this._pollTimerID),this._element.ownerDocument?.defaultView?.removeEventListener("resize",this._handleResizeEvents,!1),super.dispose(e)}updateVideoSize(e,t){this._videoSize.width=e,this._videoSize.height=t,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(e){3===this._captureMode&&3!==e&&this._syncKeyStates(!0),this._captureMode=e,0!==e?("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===e?(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()}),3e3)}_raiseMouseEvent(e){this.event("mouseControlEvent").raise(e)}_raiseKeyboardEvent(e){this.event("keyboardControlEvent").raise(e)}_raiseCaptureEvent(e){this.event("ctrlCaptureEvent").raise(e)}_normalizeMousePosition(e,t){t.xPos=(e.offsetX-this._captureRegion.left)/this._captureRegion.width*65535,t.yPos=(e.offsetY-this._captureRegion.top)/this._captureRegion.height*65535}_isOnScreenContent(e){const t=this._captureRegion.left,i=this._captureRegion.left+this._captureRegion.width,n=this._captureRegion.top,r=this._captureRegion.top+this._captureRegion.height;return t<=e.offsetX&&e.offsetX<i&&n<=e.offsetY&&e.offsetY<r}_shouldMoveMouse(){if(this._mouseMoveStartTime){const e=(new Date).getTime(),t=e-this._mouseMoveStartTime;if(this._isMouseDown&&t>=30||!this._isMouseDown&&t>=50)return this._mouseMoveStartTime=e,!0}else this._mouseMoveStartTime=(new Date).getTime();return!1}_syncKeyStates(e){this._raiseKeyboardEvent({codeType:1,code:17,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:16,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:18,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:91,repeat:!1,keyUp:e}),this._logger.info("Synced Key states.")}static formatMouseEvent(e){return d.encodeMouseEvent(e)}static formatKeyboardEvent(e){return d.encodeKeyboardEvent(e)}};function m(e){switch(e){case 0:return 0;case 2:return 1;case 1:return 2;default:return}}return"object"==typeof n.exports&&(n.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||undefined===i||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(n=Object.getOwnPropertyDescriptor(t,i))||n.enumerable});return e})(n.exports,i)),n.exports},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e["skype-calling-utilities"]=n():i["skype-calling-utilities"]=n(i["@skype/rt-js-bindings"],i.lodash)}}),me=u({"../node_modules/synctasks/dist/SyncTasks.js"(e){function t(e){return null!=e&&"function"==typeof e.then}function i(e){return null!=e&&"function"==typeof e.cancel}function n(t,i){if(!e.config.catchExceptions)return t();try{return t()}catch(e){return i(e)}}Object.defineProperty(e,"__esModule",{value:!0}),e.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(e){throw e}},e.fromThenable=function(e){var t=u();return e.then((function(e){t.resolve(e)}),(function(e){t.reject(e)})),t.promise().thenAsync((function(e){return e}))};var r,s,a,o=[],l="undefined"!=typeof setImmediate;function c(e){o.push(e),1===o.length&&(l?setImmediate(d):setTimeout(d,0))}function d(){var e=o;o=[];for(var t=0;t<e.length;t++)e[t]()}function u(){return new r.SyncTask}function h(e){return(new r.SyncTask).resolve(e).promise()}function g(e){var n=u(),s=!1;return n.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))})),e.forEach((function(e){t(e)?e.then((function(e){s||(s=!0,n.resolve(e))}),(function(e){s||(s=!0,n.reject(e))})):s||(s=!0,n.resolve(e))})),n.promise()}e.asyncCallback=c,s=r||(r={}),a=function(){function r(){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 r.prototype._addCallbackSet=function(e,t){var i=this,n=new r;return n.onCancel((function(t){e.wasCanceled=!0,e.cancelContext=t,i._cancelInternal(t)})),e.task=n,this._storedCallbackSets.push(e),t?this._mustHandleError=!1:n._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),n.promise()},r.prototype.onCancel=function(e){return this._completedSuccess||this._completedFail||(this._wasCanceled?e(this._cancelContext):this._cancelCallbacks.push(e)),this},r.prototype.then=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t},!0)},r.prototype.thenAsync=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t,asyncCallback:!0},!0)},r.prototype.catch=function(e){return this._addCallbackSet({failFunc:e},!0)},r.prototype.always=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!0)},r.prototype.setTracingEnabled=function(e){return this._traceEnabled=e,this},r.prototype.finally=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!1),this},r.prototype.done=function(e){return this._addCallbackSet({successFunc:e},!1),this},r.prototype.fail=function(e){return this._addCallbackSet({failFunc:e},!1),this},r.prototype.resolve=function(e){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=e,this._cancelCallbacks=[],this._resolveSuccesses(),this},r.prototype.reject=function(e){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=e,this._cancelCallbacks=[],this._resolveFailures(),r._enforceErrorHandled(this),this},r.prototype._checkState=function(t){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var i="Failed to "+(t?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(i)}(e.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},r._enforceErrorHandled=function(t){t._mustHandleError&&(r._rejectedTasks.push(t),r._enforceErrorHandledTimer||(r._enforceErrorHandledTimer=setTimeout((function(){r._enforceErrorHandledTimer=void 0;var t=r._rejectedTasks;r._rejectedTasks=[],t.forEach((function(t,i){t._mustHandleError&&e.config.unhandledErrorHandler(t._storedErrResolution)}))}),0)))},r.prototype.cancel=function(e){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(e)},r.prototype._cancelInternal=function(e){var t=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=e;var i=this._cancelCallbacks;this._cancelCallbacks=[],i.length>0&&i.forEach((function(e){t._completedSuccess||t._completedFail||e(t._cancelContext)}))}},r.cancelOtherInternal=function(e,t){var i=e;i._storedCallbackSets&&i._cancelInternal?i._cancelInternal(t):e.cancel(t)},r.prototype.promise=function(){return this},r.prototype._resolveSuccesses=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveSuccessCallback(t)})):e._resolveSuccessCallback(t)}))}this._resolving=!1},r.prototype._resolveSuccessCallback=function(e){var s=this;e.successFunc?n((function(){var n=e.successFunc(s._storedResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){s._handleException(t,"SyncTask caught exception in success block: "+t.toString()),e.task.reject(t)})):e.task.resolve(this._storedResolution)},r.prototype._resolveFailures=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveFailureCallback(t)})):e._resolveFailureCallback(t)}))}this._resolving=!1},r.prototype._resolveFailureCallback=function(e){var s=this;e.failFunc?n((function(){var n=e.failFunc(s._storedErrResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){s._handleException(t,"SyncTask caught exception in failure block: "+t.toString()),e.task.reject(t)})):e.task.reject(this._storedErrResolution)},r.prototype._handleException=function(t,i){e.config.exceptionsToConsole&&console.error(i),e.config.exceptionHandler&&e.config.exceptionHandler(t)},r.prototype.toEs6Promise=function(){var e=this;return new Promise((function(t,i){return e.then(t,i)}))},r._rejectedTasks=[],r}(),s.SyncTask=a,e.all=function(e){if(0===e.length)return h([]);var n,s=u(),a=e.length,o=Array(e.length);s.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))}));var l=function(){0==--a&&(void 0!==n?s.reject(n):s.resolve(o))};return e.forEach((function(e,i){t(e)?e.then((function(e){o[i]=e,l()}),(function(e){void 0===n&&(n=void 0===e||e),l()})):(o[i]=e,l())})),s.promise()},e.Defer=u,e.Resolved=h,e.Rejected=function(e){return(new r.SyncTask).reject(e).promise()},e.race=g,e.raceTimer=function(e,t){var i=u(),n=setTimeout((function(){i.resolve({timedOut:!0})}),t);return g([e.then((function(e){return clearTimeout(n),{timedOut:!1,result:e}})),i.promise()])}}}),fe=u({"../node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.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(e){return null!=e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.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(e){return null!=e.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(e){return null!=e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.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(e){return"x-signaling-fb:"+("*"===e.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(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ve=u({"../node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))})(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=fe(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),Se=u({"../node_modules/sdp-transform/lib/writer.js"(e,t){var i=fe(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?n.push(i[t.name][a]):n.push(i[t.names[s]])}else n.push(i[t.name]);return r.apply(null,n)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||a,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))})),e.media.forEach((function(e){l.push(s("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),ye=u({"../node_modules/sdp-transform/lib/index.js"(e){var t=ve(),i=Se();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),Ce={};h(Ce,{HttpRequestDispatcherImplementation:()=>st,generateCauseId:()=>be,getOvb:()=>mt,getVersion:()=>pt,pluginlessStackFactory:()=>lG,whiteList:()=>cG}),r.exports=(e=>g(a({},"__esModule",{value:!0}),e))(Ce);var Te=p(j()),Ee=8;function be(){let e="";for(let t=0;t<Ee;t++)e+="abcdef0123456789".charAt(Math.floor(16*Math.random()));return e}function _e(e){return new RegExp("^[a-f0-9]{8}$").test(e)&&e.length===Ee}var Ie=Q,we=Z,Ae=class e{constructor(e,t,i=""){this.ulLogComponent=e,this.ulSafeComponent=t,this._getPrefix=(0,we.isFunction)(i)?i:()=>i,this.logComponent=Ie.LogFactory.instance().component(this.ulLogComponent),Ie.LogFactory.instance().declareComponentSafe(this.ulLogComponent,t)}createChild(t){const i=(0,we.isFunction)(t)?t:()=>t;return new e(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${i()}`:i()))}log(...e){this._apply((e=>this.logComponent.debug2(null,e)),e)}debug(...e){this._apply((e=>this.logComponent.debug4(null,e)),e)}info(...e){this._apply((e=>this.logComponent.debug1(null,e)),e)}warn(...e){this._apply((e=>this.logComponent.warn(null,e)),e)}error(...e){this._apply((e=>this.logComponent.error(null,e)),e)}_apply(e,t=[]){this._addPrefix(t),e(t.map((e=>e instanceof DOMException?e.toString():e)).map((e=>(0,we.isObject)(e)?JSON.stringify(e):e)).join(", "))}_addPrefix(e){if(e&&e[0]){const t=`${this._getPrefix()} ${e[0]}`;e[0]=t}}},Pe=Q,Re=class{constructor(e,t){this.value=e,this.piiKind=t}},Me=["id"," orgid","username","phonenumber"];function De(e){return"string"==typeof e?Pe.pii.Mri(e):Pe.pii.Omit(e)}function ke(e,t=["id"],i={threadId:8}){if(!e||"object"!=typeof e)return e;try{let n=function(e){if(!e||"object"!=typeof e)return e;const t=new Set,i=JSON.stringify(e,((e,i)=>{if("object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}));return JSON.parse(i)}(e);return n=Fe(n,t,i),n}catch(e){return{error:"failed to scrub object fields"}}}function Oe(e){try{const t={};return Object.keys(e).forEach((i=>{const n=De(i);t[n]=e[i]})),t}catch(e){return{error:"failed to scrub mri keys"}}}function Ne(e){return JSON.stringify(Oe(e))}function Le(e){return e&&Pe.pii.Mri(e)}function xe(e){const t=function(e){return e&&"99:"===e.substr(0,3)?Pe.pii.Omit(e):e}(e);return t&&t.substr(0,8)}function Fe(e,t,i){if(!e||"object"!=typeof e)return e;const n={...e};for(const[r,s]of Object.entries(e))Array.isArray(s)?n[r]=s.map((e=>Fe(e,t,i))):"object"==typeof s?n[r]=Fe(s,t,i):"displayname"===r.toLowerCase()?n[r]="<redacted>":s&&(t.includes(r)||Me.includes(r.toLowerCase())?n[r]=De(s):i[r]&&"string"==typeof s&&(n[r]=s.toString().substring(0,i[r])));return n}function Ue(e){const t=String.raw`[\\]*['|\"]?\s*[\:|=]\s*[\\]*['|\"]?`,i=String.raw`[a-zA-Z\d#.~?!@$%^&*-_()+]*?`;return new RegExp(String.raw`((?:${e})${t})(${i})(\\{0,2}['\"])`,"g")}function Be(e){return(t,i,n,r)=>"false"===n?.toLowerCase()||"true"===n?.toLowerCase()?t:String.raw`${i}${e(n)}${r}`}var Ve=p(Z),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 $e(e){try{return JSON.parse(JSON.stringify(e,He,4))}catch(e){return{error:"failed to parse object"}}}function je(e,t=!1){if(null==e)return"void";if(e instanceof Error)return e.toString();if(e instanceof String||e instanceof Number||e instanceof Boolean)return e.toString();try{return e.stack&&(e.stack=(e=>{try{return e.split("\n")[0]}catch(e){return"invalid stack"}})(e.stack)),(t?JSON.stringify(e):JSON.stringify(e,He,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(t){return`failed to get error information:${e&&"function"==typeof e.toString&&e.toString()} ${e?.response&&JSON.stringify(e.response)}`}}function Ge(e){try{return JSON.stringify(e,null,2)}catch(t){return`failed to stringify obj ${e}`}}function qe(e,t){try{return e.substring(0,t)}catch(t){return e}}function ze(e){return e||!1===e||""===e||0===e}function We(e,t){try{const i=ke(e);return Object.keys(e).forEach((n=>{t.includes(n)?i[n]=De(e[n]):"conversationId"===n&&(i[n]=xe(e[n]))})),Ge(Ve.omit(i,["body.gp"]))}catch(e){return{error:"failed to get safe payload"}}}function Ke(e){try{let t=ke(e,["id","groupCallInitiator","organizerId"]);return Ze(t,"response.roster.participants"),Ze(t,"response.additionalActionResponses.0.output.roster.participants"),Ze(t,"response.muteUnmuteResponse"),t=Ve.omit(t,["meetingChatProperties"]),t=Ye(t),t}catch(e){return"failed to return safe response"}}function Je(e){try{return Ye(ke(e))}catch(e){return"failed to return safe request"}}function Ye(e){if(e?.config?.data){let t=e.config.data;t=JSON.parse(t),t=ke(t),e.config.data=Ge(t)}return Ge(e)}function Qe(e){try{return Ge(ke(e,["originalId"]))}catch(e){return"failed to return safe endpoint details"}}function Ze(e,t){e&&Ve.get(e,t)&&Ve.set(e,t,Oe(Ve.get(e,t)))}function Xe(e){if(!e)return!1;try{return atob(e),!0}catch(e){return!1}}function et(e){return!!e&&"function"==typeof e.then}function tt(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}function it(e){try{if(e.status)return`status: ${e.status}, URL: ${e.responseURL}, statusText: ${e.responseText}`}catch(e){}return tt(e)}function nt(e,t,i=0){return e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t),e}function rt(e,t,i,n=0){nt(e,0===i?0:i-1,n),0!==i&&e.push(t)}var st=class{constructor(e){e&&"function"==typeof e.createChild?this.logger=e.createChild("RequestDispatcher"):this.logger=new Ae("JS.TsCalling.RequestDispatcher",!1)}getRequestOptions(e,t,i,n,r){return{headers:t||{},timeout:n,payload:i||null,responseType:r}}getAsync(e,t){return this.sendRequest(e,t,"GET")}postAsync(e,t){return this.sendRequest(e,t,"POST")}putAsync(e,t){return this.sendRequest(e,t,"PUT")}removeAsync(e,t){return this.sendRequest(e,t,"DELETE")}async sendRequest(e,t={headers:{}},i){return t.useFetch?this.sendFetchRequest(e,t,i):this.sendAxiosRequest(e,t,i)}async sendAxiosRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||be()}][AxiosRequest]`);n.info(`sending, ${i}-${e}`);const r=Date.now();let s;ot(t);try{const a=Te.default.request({url:e,method:i,headers:t.headers,timeout:"number"==typeof t.timeout?t.timeout:45e3,data:t.payload||"",responseType:t.responseType||t.dataType||"json",withCredentials:at(t.withCredentials,!1),cancelToken:new Te.default.CancelToken((e=>{s=e}))});et(t.timeout)&&t.timeout.then((()=>{n.info("Aborting pending request"),s()}),(()=>{n.info("Timeout promise rejected, ignoring")}));const o=await a;return n.info(`success, status=${o.status}`),{response:o.data,request:{status:o.status,statusText:o.statusText,headers:o.headers,responseURL:o.request.responseURL,readyState:o.request.readyState,response:o.request.response,responseText:""===o.request.responseType||"text"===o.request.responseType?o.request.responseText:"",withCredentials:o.request.withCredentials},duration:Date.now()-r}}catch(e){if(n.info("failed"),Te.default.isCancel(e))throw n.info(`response=${Ke(e.message)}`),{aborted:!0};throw e.response?n.info(`response=${Ke(e.response)}`):e.request?n.info(`no response, request=${Je(e.request)}`):n.info(`request not made, error=${je(e)}`),e||new Error("Request failed")}}async sendFetchRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||be()}][FetchRequest]`);n.info(`sending, ${i}-${e}`);const r=Date.now(),s=new AbortController;let a,o=null,l=null;const c=()=>{n.info("Aborting pending request"),s.abort()};ot(t);try{if(t.fetchUseKeepAlive&&t.payload?.toString().length>65e3&&n.warn("Using fetch with keep alive with more than 64kib data"),n.info(`${JSON.stringify(t.headers)}`),o=fetch(e,{method:i,headers:t.headers,body:t.payload,credentials:t.withCredentials?"include":"same-origin",signal:s.signal,keepalive:t.fetchUseKeepAlive}),et(t.timeout))t.timeout.then((()=>{c()}),(()=>{n.info("Timeout promise rejected, ignoring")}));else if(t.timeout){const e=setTimeout((()=>c()),t.timeout);o=o.finally((()=>clearTimeout(e)))}l=await o;try{a=await l.json()}catch(e){n.info(`unable to parse response as json with error ${e}`)}const d={response:a,request:{status:l.status,statusText:l.statusText,headers:Object.fromEntries(l.headers.entries()),responseURL:l.url,response:a,withCredentials:t.withCredentials},duration:Date.now()-r};if(!l.ok)throw n.info(`failed response, status=${l.status}`),d;return n.info(`success, status=${l.status}`),d}catch(e){if(n.info(`failed error=${je(e)}`),"AbortError"===e.name)throw{aborted:!0};throw e||new Error("Request failed")}}};function at(e,t){return void 0!==e?e:t}function ot(e){e.headers=e.headers||{},e.headers["content-type"]||(e.headers["content-type"]=e.contentType||"application/json")}var lt=Z,ct=class e{constructor(e){this._callingLogger=e,this._maybeLog=(e,...t)=>{try{this._callingLogger[e](...t)}catch(e){this._callingLogger.info("[failed to log]",je(e))}}}getPrefix(e,t){let i="";return t&&(i+=`[${t}]`),e&&(i+=`[${e}]`),i}createChild(t,i){return new e(this._callingLogger.createChild(t,i))}createFnLogger(t,i,...n){return new e(this._callingLogger.createChild(this.getPrefix(t,i)+n.join(""),!1))}logSuccess(e){this._maybeLog("info",`success=${e}}`)}logFailure(e){const t=je(e);this._maybeLog("info",`failed=${t}}`)}log(...e){this._maybeLog("log",...e)}debug(...e){this._maybeLog("debug",...e)}info(...e){this._maybeLog("info",...e)}warn(...e){this._maybeLog("warn",...e)}error(...e){this._maybeLog("error",...e)}},dt=Z,ut=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new ht(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",tt(e))}}))}},ht=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,dt.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},gt=class extends ut{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}async onAsync(e,t){return this.on(e,t)}async onceAsync(e,t,i){return this.once(e,t,i)}async changedAsync(e,t){return this.changed(e,t)}async disposeAsync(e){this.dispose(e)}};function pt(){return"2025.07.01.15"}function mt(){return"8962f6ae8324f6a345d7997ae8f276ff81198956"}var ft=Z,vt=p(G()),St="Android",yt="iOS",Ct="Mac OS",Tt="Opera",Et="Edge",bt="Yandex",_t="Safari",It="Mobile Safari",wt="WebKit",At="Blink",Pt="EdgeHTML",Rt="Gecko",Mt="WebKit",Dt="Unknown",kt="0.0",Ot=class e{constructor(){const e=navigator.userAgent,t=new vt.UAParser(e).getResult();this.browserInfo={name:t.browser.name||"Unknown",engine:t.engine.name||"Unknown",version:t.browser.version||kt,formFactor:Nt(t)||"Unknown",osName:t.os.name||Dt,osVersion:t.os.version||Dt},this.modifyParserResult(t)}static get instance(){return e._instance||(e._instance=new e),e._instance}static isFormFactor(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().formFactor)}static isEngine(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().engine)}static isBrowser(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().name)}static isVersionGreaterOrEqual(e){const t=this.getBrowserInfo().version,i=e.split(".").map((e=>parseInt(e,10))),n=t.split(".").map((e=>parseInt(e,10)));return n[0]>i[0]||n[0]===i[0]&&n[1]>=i[1]}static getBrowserInfo(){return this.instance.browserInfo}static isRemote(){return window.navigator.mediaDevices?.isRemote}static toString(){const e=this.getBrowserInfo();return`${e.name}/${e.version} ${e.engine} ${e.formFactor}`}modifyParserResult(t){switch(t.engine.name){case Pt:this.browserInfo.engine="Edge";break;case At:this.browserInfo.engine="Chromium";break;case Mt:t.browser.name?.includes("Safari")||(this.browserInfo.engine="Chromium");break;case Rt:this.browserInfo.engine="Firefox"}t.engine.name===At&&t.browser.name===Et&&(this.browserInfo.name="EdgeAnaheim"),t.engine.name===At&&t.os.name===St&&(this.browserInfo.version=t.engine.version||kt),t.browser.name!==Tt&&t.browser.name!==bt||(this.browserInfo.version=t.engine.version||kt,t.browser.name===bt&&(this.browserInfo.name="YandexBrowser")),(t.os.name===yt||t.browser.name?.includes(_t))&&(this.browserInfo.engine="Safari"),t.os.name!==Ct&&t.os.name!==yt||t.browser.name!==wt||(this.browserInfo.engine="Safari",this.browserInfo.name="AppleWebView"),t.os.name===yt&&(this.browserInfo.version=t.os.version||kt),t.browser.name===It&&(this.browserInfo.name="Safari"),t.ua.includes("maglev")&&(this.browserInfo.name="Maglev",this.browserInfo.version=t.engine.version||kt),e.isRemote()&&(this.browserInfo.engine="ChromiumAVD"),t.ua.includes("Cisco")&&(this.browserInfo.name="CiscoOS"),t.ua.includes("ZoomRoom")&&(this.browserInfo.name="ZoomRoom"),t.ua.includes("TeamsSamsungTVBrowser")&&(this.browserInfo.name="SamsungTV")}};function Nt(e){if("136"===function(){const e="os-sku",t=window.external;return t?.getHostEnvironmentValue?JSON.parse(t.getHostEnvironmentValue(e))[e]:"-1"}())return"Hololens";if(/hostAudio-Processing/i.test(e.ua))return"RoomAudioProcessing";const t=e.device.type;return"mobile"===t||"tablet"===t?"Mobile":void 0===e.browser.name?"Unknown":"Desktop"}var Lt={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},xt={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"]},Ft={src:[],css:[],styles:[],playerType:2,hydraPlayerWebSdkUrls:["https://res.cdn.office.net/s01-ml-player/4.24352.3/hydra_player_ums_bundle.js"]},Ut=class{constructor(e,t,i,n){this.configIds=i,this.logger=n,this.defaultSettings=(Ot.isEngine("Safari")?new Vt:new Bt).getSettings(),this.logger.info(`client settings: ${JSON.stringify(t)}`),this.defaultSettings.debug=t?.debug||!1,this.defaultSettings.playerType=t?.playerConfig?.playerType||this.defaultSettings.playerType,t?.playerConfig&&(0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration=t.playerConfig:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration=t.playerConfig:2===this.defaultSettings.playerType&&(this.defaultSettings.umsSettings.liveStreamPlayerConfiguration=t.playerConfig)),(0,ft.mergeWith)(this.defaultSettings,e,Ht),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}},Bt=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:Lt,sourceResetTimeoutInMs:1e3,streamingUrlSwitchMaxCount:2,resetStreamingUrlSwitchCount:!1,useBrowserWindowSizeForBitRate:!0,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,collectUserInitiatedSeekEventsTelemetry:!0,maxUserInitiatedSeekEventCount:100,noMediaTimeoutMs:-1},hlsSettings:{liveStreamPlayerConfiguration:xt,timeoutForSwitchingUrl:9e3,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,playlistInitialSequenceNumber:1,skipNonce:!1,maxStreamConnectionResultsLogCount:100,logHlsJsEvents:!1,logHlsJsEventsEveryMs:5e3,maxPlayerExperimentalEvents:100},umsSettings:{liveStreamPlayerConfiguration:Ft,timeoutForSwitchingUrl:9e3,maxStreamConnectionResultsLogCount:100,minTargetEdgeLatency:.2,latencyCompensationThreshold:.5,maxPlayerExperimentalEvents:100}}}getSettings(){return this.defaultSettings}},Vt=class extends Bt{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 Ht(e,t){if((0,ft.isArray)(e))return t.slice()}function $t(e){return!!e&&!!e.url&&!!e.decryptionToken}function jt(e,t,i){if(!e&&!i)throw new Error("Assert failed"+(void 0!==t?`: ${t}`:""))}var Gt=class{constructor(e,t,i){this.name=e,this.stopCrash=t,this.start(i)}complete(){jt(this.startTime,"not started",this.stopCrash),jt(void 0===this.duration,"already completed",this.stopCrash),this.duration=Date.now()-this.startTime}updateDetails(e,t){if(this.details&&"object"==typeof this.details)for(let i=0;i<e.length;i++)this.details[e[i]]=t[i]}fail(e){this.failReason=e,this.complete()}set detail(e){this.details=e}getTelemetryEvent(){jt(this.startTime,"not started",this.stopCrash);try{jt(void 0!==this.duration,"not completed",this.stopCrash)}catch(e){if("SetSource"!==this.name&&"Load"!==this.name)throw e}const e={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(e.failReason=this.failReason),this.details&&(e.details=this.details),e}start(e){jt(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),this.details=e}},qt=class{constructor(e,t,i){this.config=e,this.logger=t,this.playerDiagnosticsLog=i,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.userInitiatedSeekEvents=[],this.experimentalEvents=[],this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxUserInitiatedSeekEventCount=e.ampSettings?.maxUserInitiatedSeekEventCount||100,this.stopCrash=e.stopCrash||!1,this.config.debug&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}getPlayerDiagnosticSnapshot(){return this.currentPlayerDiagnosticSnapshot}registerStatsUpdated(e){this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((t=>{const i=t,n=this.playerDiagnosticsLog[t];if(Array.isArray(n)){n.push(e[i]);const t="memoryLog"===i&&n.length>this.maxPlayerMemoryTraceLogCount,r="memoryLog"!==i&&n.length>this.maxPlayerDiagnosticsCount;(t||r)&&n.splice(0,1)}else this.playerDiagnosticsLog[t]=e[i]}))}registerEventLoadAttempt(e,t){this.registerScenario(e,t)}registerEventLoadFailed(e,t){this.completeScenario(e,t)}registerEventLoadSucceeded(e,t){this.completeScenario(e,void 0,t)}registerPlayerLoadAttempt(){this.registerScenario("Load")}registerPlayerLoadSucceeded(e){this.completeScenario("Load",void 0,e)}registerPlayerLoadFailed(e){this.completeScenario("Load",e)}registerPlayerSetupAttempt(){this.registerScenario("Setup")}registerPlayerSetupSucceeded(){this.completeScenario("Setup")}registerPlayerSetupFailed(e){this.completeScenario("Setup",e)}registerStreamConnectionAttempt(e){this.registerScenario("StreamConnection")}registerStreamConnectionSucceeded(){this.completeScenario("StreamConnection")}registerStreamConnectionFailed(e){this.completeScenario("StreamConnection",e)}registerSetSourceAttempt(e,t){let i=e;t&&(i={src:e,reason:t}),this.registerScenario("SetSource",i)}registerSetSourceSucceeded(e){this.getScenario("SetSource").updateDetails(["src"],[e]),this.completeScenario("SetSource")}registerSetSourcedFailed(e,t){this.getScenario("SetSource").updateDetails(["src"],[t]),this.completeScenario("SetSource",e)}registerSdnPluginLoad(e,t,i){this.registerScenario("SdnPluginLoad",e);const n=t?void 0:i;this.completeScenario("SdnPluginLoad",n)}registerPlayerDestroyed(e){this.registerScenario("Destroyed",e),this.completeScenario("Destroyed")}registerPlaybackStateChanged(e,t){let i;"Ready"!==e||this.firstReadyStateTimestamp?"Playing"!==e||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),t&&"Buffering"===e&&(t?i=t.message:this.logger.debug(`Unexpected buffering payload: ${JSON.stringify(t)}`)),this.registerPlaybackEvent("StateChanged",e,i)}registerPlaybackError(e,t){this.registerPlaybackEvent("Error",{errorType:e,details:t})}registerDownloadBitratechanged(e){this.registerPlaybackEvent("BitrateChangedDownload",e)}registerStreamOptionsConfigured(e,t){this.registerPlaybackEvent("StreamOptionsConfigured",this.generateCleanedStreamOption(e),t)}registerPlaybackBitratechanged(e){this.registerPlaybackEvent("BitrateChangedPlayback",e)}registerPotentialMediaFreeze(e){this.registerPlaybackEvent("PotentialMediaFreeze",e)}registerCaptionToggle(e,t,i){const n={isEnabled:e,culture:t,playerTime:i};this.registerPlaybackEvent("CaptionsToggled",n)}registerFullScreenChange(e){this.registerPlaybackEvent("FullscreenChanged",e)}registerMute(e){this.registerPlaybackEvent("Mute",e)}registerVolumeChange(e){this.registerPlaybackEvent("Volume",e)}getExperimentalEvents(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}}getUserInitiatedSeekEvents(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents)}}getSnapshotReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;let n={};return this.currentPlayerDiagnosticSnapshot&&(n=this.filterAndPrepareTelemetry()),{isFullReport:!1,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2025.07.01.15",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...n}}getReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;return{callendReason:e.callendReason,isFullReport:!0,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2025.07.01.15",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...this.getPlayerDiagnosticLog()}}registerExperimentalEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.logTelemetryEvent(n)}registerUserInitiatedSeek(e){const t=(this.currentPlayerDiagnosticSnapshot?.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1)<e.newCurrentPlayPosition,i={...e,seekForward:t},n=this.createTelemetryEvent("UserInitiatedSeek",i);this.userInitiatedSeekEvents.push(n),this.userInitiatedSeekEvents.length>this.maxUserInitiatedSeekEventCount&&this.userInitiatedSeekEvents.splice(0,1)}createTelemetryEvent(e,t,i){const n={eventType:e,timestamp:Date.now(),currentPlayPosition:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1};return void 0!==t&&(n.payload=this.prepareForTelemetry(t)),n.message=i,n}registerPlaybackEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);"Error"===e&&"PlaybackRetried"!==t?.errorType&&(n.fatal=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)}getPlayerDiagnosticLog(){if(!this.currentPlayerDiagnosticSnapshot)return{};const e={...this.currentPlayerDiagnosticSnapshot,...this.playerDiagnosticsLog},t={};return Object.keys(e).forEach((i=>{t[`player_${i}`]=this.prepareForTelemetry(e[i])})),t}getCallSetupSucceeded(e){const t=e.find((e=>"Load"===e.name));return!!t&&!t.failReason}getCallDropped(e){return!!e.filter((e=>"Error"===e.eventType)).find((e=>e.fatal))}getInitializationReport(e,t){const i=e.find((e=>"Load"===e.name));return{init_timeLoadToStreamConnectionEstablished:(i&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-i.startTime:-1)||-1,init_timeLoadToReady:(i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(i&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)}}getPlaybackReport(e){const t=e.filter((e=>"StateChanged"===e.eventType)),i=t.find((e=>"Ready"===e.payload)),n=t.find((e=>"Play"===e.payload)),r=t.find((e=>"Start"===e.payload)),s=t.find((e=>"Playing"===e.payload)),a=i&&n?n.timestamp-i.timestamp:-1,o=n&&r?r.timestamp-n.timestamp:-1,l=r&&s?s.timestamp-r.timestamp:-1,c=t.filter((e=>"Seeked"===e.payload)),d=t.filter((e=>"Seeking"===e.payload)),u=t.filter((e=>"Paused"===e.payload)),h=t.filter((e=>"Resume"===e.payload)),g=t.filter((e=>"Buffering"===e.payload)),p=["BitrateChangedDownload","BitrateChangedPlayback","Error","Mute","StateChanged","Volume","StreamOptionsConfigured"],m=e.filter((e=>"Error"===e.eventType)),f=e.filter((e=>"Volume"===e.eventType||"Mute"===e.eventType)),v=e.filter((e=>"StreamOptionsConfigured"===e.eventType)),S=e.filter((e=>!p.includes(e.eventType)));return{playback_timeReadyToPlay:a,playback_timePlayToStart:o,playback_timeStartToPlaying:l,playback_bufferingEvents:this.prepareForTelemetry(g),playback_errorEvents:this.prepareForTelemetry(m),playback_pauseEvents:this.prepareForTelemetry(u),playback_resumeEvents:this.prepareForTelemetry(h),playback_otherEvents:this.prepareForTelemetry(S),playback_seekedEvents:this.prepareForTelemetry(c),playback_seekingEvents:this.prepareForTelemetry(d),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(f),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(v)}}generateCleanedStreamOption(e){return{...e,stream:{...e?.stream,decryptionToken:e?.stream?.decryptionToken?"valid":"empty",sdnContext:e?.stream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"},altStream:e?.altStream?{...e?.altStream,decryptionToken:e?.altStream?.decryptionToken?"valid":"empty",sdnContext:e?.altStream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"}:void 0}}getBitrateReport(e){const t=e.filter((e=>"BitrateChangedDownload"===e.eventType)),i=t.sort((e=>Number(e.payload))),n=t.length?{bitrate_downloadChanges:this.prepareForTelemetry(t),bitrate_downloadChangeCount:t.length||-1,bitrate_downloadMin:i[0].payload||-1,bitrate_downloadMax:i[i.length-1].payload||-1}:{},r=e.filter((e=>"BitrateChangedPlayback"===e.eventType)),s=r.sort((e=>Number(e.payload)));return{...n,...r.length?{bitrate_playbackChanges:this.prepareForTelemetry(r),bitrate_playbackChangeCount:r.length||-1,bitrate_playbackMin:s[0].payload||-1,bitrate_playbackMax:s[s.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 e="Unknown";if(window.navigator?.connection?.type){const t=window.navigator?.connection?.type;switch(t){case"cellular":e="WWAN";break;case"ethernet":e="Wired";break;case"wifi":e="Wireless";break;default:e="Unknown"}}this.clientNetworkType=e}return this.clientNetworkType}getSdnReport(e){const t=e.filter((e=>"SdnPluginLoad"===e.name)),i=t.length?t[t.length-1]:void 0;return{sdn_loaded:!(!i||void 0!==i.failReason),sdn_details:i&&i.details||"",sdn_error:i&&i.failReason||"",sdn_events:this.prepareForTelemetry(t)}}getSetSourceReport(e){const t=e.filter((e=>"SetSource"===e.name));return{set_source_events:this.prepareForTelemetry(t)}}registerScenario(e,t){const i=this.currentScenarioMap.get(e),n=new Gt(e,this.stopCrash,t);jt(!i,`previous scenario:${tt(i)} is not completed, new scenario:${tt(n)}`,this.stopCrash),this.currentScenarioMap.set(e,n),this.playerEvents.push(n)}getScenario(e){return this.currentScenarioMap.get(e)}completeScenario(e,t,i){const n=this.currentScenarioMap.get(e);jt(n,"no scenario to complete",this.stopCrash),t?n.fail(t):("StreamConnection"!==e||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),i&&(n.detail=i),n.complete()),this.currentScenarioMap.delete(e)}logTelemetryEvent(e){this.config.debug&&(this.logger.debug(`PlayerTelemetryEvent: ${JSON.stringify(e)}`),this.logger.debug(`PlayerDiagnosticData: ${JSON.stringify(this.currentPlayerDiagnosticSnapshot)}`))}filterAndPrepareTelemetry(){const e=new Set;e.add("serviceLatencyCdg"),e.add("endToEndLatencyCdg"),e.add("videoEdgeLatencyCdg");const t={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((i=>{e.has(i)||(t[`player_${i}`]=this.prepareForTelemetry(this.currentPlayerDiagnosticSnapshot[i]))})),t}prepareForTelemetry(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?e??-1:JSON.stringify(e)}},zt=Z;function Wt(e){return new Promise((t=>{t(e())}))}var Kt=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((e,t)=>{this.resolveInt=e,this.rejectInt=t}))}get resolve(){return e=>{this.isPendingInt=!1,this.resolveInt(e),this.clearTimeout()}}get reject(){return e=>{this.isPendingInt=!1,this.rejectInt(e),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(e,t=`deferred timed out after ${e}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(t)}),e))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function Jt(e,t=`deferred timed out after ${e}ms`){const i=new Kt;return i.setTimeout(e,t),i}function Yt(e){return new Promise((t=>setTimeout(t,e)))}var Qt=class{static build(e,t){return new Zt(e,t)}},Zt=class{constructor(e,t){this.ontimeout=e,this.name=t}start(e){if(void 0!==this.timeoutId)throw new Error(`Timer ${this.name} already started`);return this.timeoutId=window.setTimeout((()=>this.ontimeout()),e),this}stop(){if(void 0===this.timeoutId)throw new Error(`Timer ${this.name} is not defined`);clearTimeout(this.timeoutId),this.timeoutId=void 0}};function Xt(){const e=ai(),t=oi();let i;return(i||(i={})).CaptionFunctionalityNotSupported="CaptionFunctionalityNotSupported",class{constructor(e,t){this.container=e,this.eventsHandler=t,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(e,t,i){this.liveStreamOptions=e,this.playerId=i,t&&(this.configProvider=t,this.statsInterval=t.config.playerTelemetryTickMs||this.statsInterval,this.maxMemoryTraceLogCount=t.config.maxPlayerMemoryTraceLogCount||this.maxMemoryTraceLogCount)}getIceCandidates(){let e=[];try{const t=this.liveStreamOptions.stream.sdnContext||this.liveStreamOptions.altStream?.sdnContext||"",i=JSON.parse(t),n=JSON.parse(i.sdnConfig);if(!n.RTCIceCandidates)throw new Error("RTCIceCandidates not present in SDN Context");e=n.RTCIceCandidates}catch(e){this.log(`getIceCandidates failed: ${JSON.stringify(e.message)}`,"error")}return this.log(`getIceCandidates: ${JSON.stringify(e)}`,"debug"),e}loadPlayerScript(){let e=Promise.resolve("");const t=this.configProvider.playerConfig.nonce,i=this.configProvider.playerConfig.css;for(let n=0;n<i.length;n++)e=e.then((()=>this.retry((()=>this.loadCss(this.container.ownerDocument,i[n],t)))));return e=e.then((()=>this.loadAmpScript())),e}loadAmpScript(){this.log("loadPlayerScript started");let e=Promise.resolve("");const t=this.configProvider.playerConfig?.nonce,i=this.configProvider.playerConfig?.src||[],n=Math.max(2,this.configProvider.config.maxRetryCountForLoadingResources);if(0===i.length)return Promise.reject("AMP Player Src is empty");for(let r=0;r<i.length;++r)e=e.then((()=>this.loadScriptPromise(i,r,t,n)));return e}loadScriptPromise(e,t,i,n,r=""){return this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i} `.concat(r))).catch((s=>this.retry((()=>this.setScriptByBlob(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i}`.concat(` ${s} `,` ${r} `))).catch((a=>this.retry((()=>this.setScriptByInnerHtml(this.container.ownerDocument,e[t],i)),1).then((i=>`${e[t]}: ${i}`.concat(` ${s} `,`${a} `,` ${r} `))).catch((s=>{let o=r;return t<e.length&&(o=o.concat(`Failed to load script, nonce: ${i}, src: ${e[t]} index: ${t} `),o=o.concat(`${n} attempts LoadFailure `,`${n} attempts BlobFetchFailure: `,a,", 1 attempt InnerHtmlFailure: ",`${s} `)),Promise.reject(o)}))))))}retry(e,t=this.configProvider.config.maxRetryCountForLoadingResources,i=1,n=200){return e(t).then((e=>`${e}, succeeded on load number: ${i} `)).catch((r=>(this.log(`Error loading resource: ${r} -- ${t} retriesLeft`),0==--t?Promise.reject(`${r}`):new Promise((s=>setTimeout((()=>s(this.retry(e,t,i+1).then((e=>"string"==typeof e?`${e}, succeeded on load number: ${i}`:e)).catch((e=>Promise.reject(`${r}`.concat(", ",e)))))),n))))))}setScriptByLoad(e,t,i){const n=e.createElement("script"),r=this.getElementLoadPromise(n,t);return n.src=t,i&&(n.nonce=i),e.head.appendChild(n),r.then((()=>Promise.resolve("Success: setScriptByLoad")))}setScriptByBlob(e,t,i){return this.safeResponse(t).then((t=>t.blob().then((n=>{if(n){const t=URL.createObjectURL(n);return this.setScriptByLoad(e,t,i).then((()=>Promise.resolve("Success: setScriptByBlob")))}return Promise.reject(`${t.status}, blob is null`)}))))}setScriptByInnerHtml(e,t,i){return this.safeResponse(t).then((t=>t.text().then((n=>{if(n){const t=document.createElement("script");return t.innerHTML=n,i&&!this.configProvider.config.hlsSettings.skipNonce&&(t.nonce=i),e.head.appendChild(t),Promise.resolve("Success: setScriptByInnerHtml")}return Promise.reject(`status code:${t.status}, text is null`)}))))}safeResponse(e){return fetch(e).then((e=>e.ok?e:Promise.reject(`${e.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 i=this.getAmpOptions();if(this.playerInstance=this.contextWindow.amp(this.video.id,i),!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 ri(this.log.bind(this)),this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider,this.absoluteTimeOffsetEstimator),this.absoluteTimeOffsetEstimator.setEstimationResultCallback(this.onAbsoluteTimeOffsetEstimation.bind(this))):this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider);const n={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 t(this.playerInstance,this,n,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(e){if(this.diagnosticProvider.appendAbsoluteTimeOffsetEstimation(e),!e.isSuccess){const e=this.addEvent("CaptionFunctionalityNotSupported",{detail:{data:{fatal:!0,details:"absolute time offset estimation failed - captions will fail"}}});this.video.dispatchEvent(e)}}addEvent(e,t){let i={};return t?.detail&&(i={detail:t.detail}),new CustomEvent(e,i)}setSource(e){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 t={src:e.url,type:this.videoSourceType,protectionInfo:e.decryptionToken?[{type:"AES",authenticationToken:e.decryptionToken}]:null};this.configureSdnSource(t,e),this.diagnosticProvider.setValue("streamUrl",e.url),this.diagnosticProvider.setValue("streamId",this.getStreamIdFromStreamUrl(e.url)),this.diagnosticProvider.setValue("streamDeliveryPipeline",e.streamDeliveryPipeline||""),this.playerInstance.src([t],this.getTextTracks()),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.setManifestFileURL(e.url+"(format=m3u8-aapl-v4)"),this.log("setSource done")}getStreamIdFromStreamUrl(e){try{const t=new URL(e).pathname;if(t){const e=t.split("/");if(e?.length>1)return e[1]}return this.log(`unable to parse stream ID from stream URL: ${e}`,"warn"),""}catch{return this.log(`cannot parse stream ID from invalid stream URL: ${e}`,"warn"),""}}setPlayTime(e){e&&(this.log(`setPlayerTime: ${e}`),this.playerInstance.currentTime(e))}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(e){this.log(`showCaptions: ${e}`),this.captionsControl.showCaptions(e)}addCues(e){e=e.filter((e=>e.text&&0!==e.text.trim().length)),this.captionsControl.addCues(e)}clearCues(){this.captionsControl.clearCues()}captionsToggled(e,t,i){this.log(`captionsToggled: ${e} for culture ${t} at ${i}`),this.eventsHandler.message("captionsToggled").send(e,t,i)}createVideoElement(){this.log("createVideoElement started"),this.video=this.container.ownerDocument.createElement("video"),this.video.id="amp-player",this.video.setAttribute("playsinline","");const e=this.configProvider.playerConfig.lang;e&&(this.video.setAttribute("lang",e),this.log(`createVideoElement: language set to ${e}`));const t=this.configProvider.playerConfig.styles;for(let e=0;e<t.length;e++)this.video.classList.add(t[e]);this.container.appendChild(this.video),this.log("createVideoElement done")}getAmpOptions(){const e=[];this.configProvider.config.debug?e.push({target:"memory",maxMemoryTraceCount:this.maxMemoryTraceLogCount}):e.push({target:"console"});const t={TraceTargets:e,maxLogLevel:this.configProvider.config.debug?3:2},i={techOrder:["azureHtml5JS","html5"],nativeControlsForTouch:!1,autoplay:!0,preload:"auto",controls:!this.isControlsDisabled(),logo:{enabled:!1},height:"100%",width:"100%",traceConfig:t,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(i),i}isStreamValid(e){return e&&!!e.url&&!!e.decryptionToken}initializePluginOptions(e){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;const t=this.isStreamValid(this.liveStreamOptions.stream)?this.liveStreamOptions.stream:this.liveStreamOptions.altStream;this.log(`initializePluginOptions, receivedSDNContext: ${JSON.stringify(t?.sdnContext)}`,"info");try{const i=this.liveStreamOptions.correlationId||this.playerId;switch(this.liveStreamOptions.sdn.name){case"hive":if(e.plugins={hive:{debugLevel:this.configProvider.config.debug?"debug":"notice",telemetryId:i}},t&&t.sdnContext)try{const i=JSON.parse(t.sdnContext);if(i.sdnConfig){const t=JSON.parse(i.sdnConfig);t.candidateTopicName="RequestIceCandidates",delete t.RTCIceCandidates,Object.assign(e.plugins.hive,t)}}catch(e){this.log(`initializePluginOptions, failed to parse Hive sdnConfig Json from sdnContext Json, error: ${e}`,"warn")}break;case"kollective":if(t&&t.sdnContext){let n=null,r=null,s=null;try{n=this.parseJson(t.sdnContext,"kollective sdn context")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext Json, error: ${e}`,"error")}if(n){try{r=this.parseJson(n.playbackinfo,"kollective sdn playback info")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext playbackinfo Json, error: ${e}`,"error")}try{s=this.parseJson(n.sdnConfig,"kollective sdn config")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext sdnConfig Json, error: ${e}`,"error")}}e.plugins={kollectiveSDN:{playbackInfo:r,sdnConfig:s,reportSessionId:i}}}break;case"ramp":t&&t.sdnContext&&(e.plugins={RampMOPlugin:this.parseJson(t.sdnContext,"ramp sdn context")},this.configProvider.config.debug&&(e.plugins.RampMOPlugin.verbose=!0));break;case"peer5":t.sdnContext&&(e.plugins={peer5:this.parseJson(t.sdnContext,"peer5 sdn context")})}}catch(e){this.log(`initializePluginOptions failed, error: ${e.message}`,"error")}this.log(`initializePluginOptions, configured plugin options: ${JSON.stringify(e.plugins)}`,"info")}getTextTracks(){const e=[];if(this.isControlsDisabled())e.push({id:"amp-player_default",kind:"captions",label:"default-text-track",src:"",srclang:"en"});else if(this.liveStreamOptions.supportedSubtitleLanguages){const t=this.liveStreamOptions.supportedSubtitleLanguages;for(let i=0;i<t.length;i++)e.push({id:`amp-player_${t[i].culture}`,kind:this.configProvider.config.textTrackKind,label:t[i].name||t[i].culture,src:"",srclang:t[i].culture.substr(0,2)})}return e}configureSdnSource(e,t){if(this.sdnPluginLoaded&&this.liveStreamOptions.sdn){switch(this.liveStreamOptions.sdn.name){case"hive":if(!t.sdnContext){e.sdnList=[];break}try{const i=JSON.parse(t.sdnContext);i.playbackinfo&&(e.sdnList=[{sdnName:"hive",sdnUrl:i.playbackinfo}])}catch(i){e.sdnList=[{sdnName:"hive",sdnUrl:t.sdnContext}]}break;case"kollective":if(!t.sdnContext){e.sdnList=[];break}try{const i=this.parseJson(t.sdnContext,"kollective sdn list context"),n=this.parseJson(i.playbackinfo,"kollective sdn list playback info"),r=this.parseJson(i.sdnConfig,"kollective sdn list sdn config");e.sdnList=[{sdnName:"kollectiveSDN",playbackInfo:n,sdnConfig:r}]}catch(t){return e.sdnList=[],void this.log(`configureSdnSource failed, error: ${t}`,"error")}break;case"ramp":case"peer5":e.sdnList=[];break;default:return}this.log(`configureSdnSource, configured source context: ${JSON.stringify(e)}`,"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(i).forEach((e=>{this.registerVideoEvent(e,(t=>{this.handleUserExperienceErrorEvent(e,t.detail.data.details,t.detail.data.fatal)}))})),this.configProvider.config.ampSettings.collectUserInitiatedSeekEventsTelemetry&&(this.playerEvents.push("currentTimeChanging"),this.playerInstance.addEventListener("currentTimeChanging",((e,t)=>this.onAmpCurrentTimeChangingEvent(e,t))))}onAmpCurrentTimeChangingEvent(e,t){if("currentTimeChanging"!==e.type||!t.time)return;const i={newCurrentPlayPosition:t.time};this.eventsHandler.message("stateChanged").send("UserInitiatedSeek",i)}registerPlayerEvent(e,t){this.playerEvents.push(e),this.playerInstance.addEventListener(e,t)}registerVideoEvent(e,t){this.videoElementEvents.push({name:e,callback:t}),this.video.addEventListener(e,t)}removePlayerEventListeners(){this.playerEvents.forEach((e=>{this.playerInstance.removeEventListener(e)}))}removeVideoEventListeners(){this.videoElementEvents.forEach((e=>{this.video.removeEventListener(e.name,e.callback)}))}onAmpEvent(e){let t,i;switch(e){case this.contextWindow.amp.eventName.error:i=this.playerInstance.error(),t={currentTime:this.playerInstance.currentTime(),errorCode:i?i.code:0,message:i?i.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:t={isFullscreen:this.playerInstance.isFullscreen()};break;case this.contextWindow.amp.eventName.playbackbitratechanged:t={bitrate:this.playerInstance.currentPlaybackBitrate()};break;case this.contextWindow.amp.eventName.downloadbitratechanged:t={bitrate:this.playerInstance.currentDownloadBitrate()};break;case this.contextWindow.amp.eventName.seeked:t={captionsTimestamp:this.isControlsDisabled()?this.playerInstance.currentMediaTime():this.playerInstance.currentTime()};break;case this.contextWindow.amp.eventName.volumechange:t={value:this.playerInstance.volume()}}this.updatePlaybackDiagnostics(),this.updatePlayerState(e),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(e,t)}updatePlayerState(e){this.updatePlayingState(e),this.updateBufferingState(e),this.updateCurrentVideoTrackBitrate(e),e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error||this.handlePlaybackStopped()}handleUserExperienceErrorEvent(e,t,i){const n={currentTime:this.video?this.video.currentTime:0,message:t,type:e,errorCode:0,fatal:i};this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(this.contextWindow.amp.eventName.error,n)}updatePlayingState(e){this.isPlaying?e!==this.contextWindow.amp.eventName.pause&&e!==this.contextWindow.amp.eventName.seeking&&e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error&&e!==this.contextWindow.amp.eventName.waiting||(this.isPlaying=!1):e===this.contextWindow.amp.eventName.playing&&(this.isPlaying=!0)}updateBufferingState(e){this.isBuffering?(e===this.contextWindow.amp.eventName.pause&&"html5"===this.playerInstance.currentTechName()?.toLowerCase()||e===this.contextWindow.amp.eventName.seeking||e===this.contextWindow.amp.eventName.ended||e===this.contextWindow.amp.eventName.error||e===this.contextWindow.amp.eventName.playing)&&(this.isBuffering=!1):e===this.contextWindow.amp.eventName.waiting&&(this.isBuffering=!0)}updateCurrentVideoTrackBitrate(e){e===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 e=new Date;if(this.currentVideoPlaybackBitrate){const t=this.diagnosticProvider.getValue("videoTrackHistory"),i=this.diagnosticProvider.getValue("videoTrackTotalDurations");if(t.length>0&&this.currentVideoPlaybackBitrate===t[t.length-1].trackPlaybackBitrate){if(this.videoTrackHistoryUpdatedTimestamp){this.latestVideoTrackDuration+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,t[t.length-1].durationInSeconds=Number(this.latestVideoTrackDuration.toFixed(0));const n=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate)),r=i.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));n&&r&&(n.totalDurationInSeconds+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,r.totalDurationInSeconds=Number(n.totalDurationInSeconds.toFixed(0)))}}else{const n=this.playerInstance.videoBufferData();let r=null;n&&n.perceivedBandwidth&&(r=n.perceivedBandwidth),t.push({trackPlaybackBitrate:this.currentVideoPlaybackBitrate,trackSwitchTimestamp:e.getTime(),trackSwitchMeasuredBandwidth:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredBandwidth():null,trackSwitchMeasuredByteSize:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredVideoDownloadSize():null,trackSwitchPerceivedBandwidth:r,durationInSeconds:0}),this.latestVideoTrackDuration=0,t.length>this.configProvider.config.maxVideoTrackHistoryLogCount&&t.splice(0,1);const s=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));if(!s){const e={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0},t={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0};this.videoTrackTotalDurations.push(e),i.push(t)}}}this.videoTrackHistoryUpdatedTimestamp=e}updateTotalPlayingTimeStatistic(){const e=new Date;this.isPlaying&&this.totalPlayingTimeUpdatedTimestamp&&(this.totalPlayingTime+=e.getTime()-this.totalPlayingTimeUpdatedTimestamp.getTime()),this.totalPlayingTimeUpdatedTimestamp=e,this.diagnosticProvider.setValue("totalPlayingTimeInSeconds",Number((this.totalPlayingTime/1e3).toFixed(0)))}updateBufferingRateStatistic(){const e=new Date;this.isBuffering&&this.bufferingRateStatUpdatedTimestamp&&(this.totalBufferingTime+=e.getTime()-this.bufferingRateStatUpdatedTimestamp.getTime()),this.bufferingRateStatUpdatedTimestamp=e;const t=this.totalPlayingTime>0||this.totalBufferingTime>0?this.totalBufferingTime/(this.totalPlayingTime+this.totalBufferingTime):0;this.diagnosticProvider.setValue("bufferingRate",Number(t.toFixed(3)))}getPlayerDiagnostics(){const e=this.diagnosticProvider.getPlayerDiagnosticSnapshot();return e.statsInterval=this.statsInterval,this.configProvider.config.debug&&(e.memoryLog=this.playerInstance.getMemoryLog(!0)),e}log(e,t="info"){const i=`[AmpPlayer${1===this.configProvider.config.loadType?"IFrame":""}]: ${e}`;this.configProvider.config.debug&&console.log(i),this.eventsHandler.message("log").send(t,i)}getElementLoadPromise(e,t){return new Promise(((i,n)=>{e.onload=()=>{i("Element Load success")},e.onerror=()=>{n(`Failed to load script: ${t}`)}}))}loadCss(e,t,i){const n=e.createElement("link"),r=this.getElementLoadPromise(n,t);return n.href=t,n.rel="stylesheet",i&&(n.nonce=i),e.head.appendChild(n),r}parseJson(e,t){try{return JSON.parse(e)}catch(e){throw this.log(`Error parsing JSON for ${t}, error: ${JSON.stringify(e)}`),e}}}}function ei(){const e=Xt();return class{constructor(t,i){this.pipe=t,this.amp=new e(i,this)}processMessage(e){"Command"===e.msgType&&Promise.resolve().then((()=>this.amp[e.cmd].apply(this.amp,e.args))).then((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,result:JSON.stringify(t)})})).catch((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,error:t})}))}message(e){return{send:this.fromMessage(((...t)=>{this.sendMessageImpl(e,t)}))}}ampDisposed(){this.pipe.dispose(),this.pipe=null,this.amp=null}fromMessage(e){return e}sendMessageImpl(e,t){this.pipe.sendMsg({msgType:"PlayerNotification",name:e,args:t})}}}Xt();var ti=ei();function ii(){function e(e){let t="unknown";try{t="string"==typeof e?e:"toString"in e&&0!==e.toString().indexOf("[object")?e.toString():JSON.stringify(e)}catch(t){console.error("Failed to stringify error",e)}return t}return class{constructor(){this.processMsg=this.processMsg.bind(this),window.addEventListener("message",this.processMsg)}sendMsg(t){try{let i=t;(function(e){return"CommandResult"===e.msgType})(t)&&t.error instanceof Event&&(console.debug("Stringifying error Event before trying to postMessage:",t),i={msgType:t.msgType,cmd:t.cmd,error:`Event: ${e(t.error)}`}),this.postMessage(i)}catch(i){console.error("Unexpected exception caught from postMessage.\n","message:",t,"\n","exception:",i);const n={msgType:"PlayerNotification",name:"log",args:["error",`Unexpected error with postMessage: ${e(i)}`]};throw this.postMessage(n),i}}registerObserver(e){this.observer=e}dispose(){window.removeEventListener("message",this.processMsg),this.observer=null}processMsg(e){this.observer.processMessage(e.data)}postMessage(e){window.parent.postMessage(e,"*")}}}function ni(){const e=si();return class{constructor(t){this.playlistFileDownloadPromise=Promise.resolve(),this.playlistFileDownloadRetryWaitTime=250,this.playlistFileDownloadMaxRetryCount=20,this.playlistFileDownloadCancellationFlag=!1,this.logFn=(e,i)=>t(`[HlsAbsoluteTimeOffsetEstimator]: ${e}`,i),this.hlsFileParser=new e(t)}get absoluteTimeOffset(){return this.estimatedAbsoluteTimeOffset}setEstimationResultCallback(e){this.onAbsoluteTimeOffsetEstimation=e}restartStreamAbsoluteTimeOffsetRetrieval(){this.stopStreamAbsoluteTimeOffsetRetrieval().then((()=>this.startStreamAbsoluteTimeOffsetRetrieval()))}setManifestFileURL(e){this.cachedManifestUrl=e}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((e=>{this.logFn(`Failed to download playlist files to estimate absolute stream time offset: ${e.message}`,"error")}))}stopStreamAbsoluteTimeOffsetRetrieval(){return this.playlistFileDownloadCancellationFlag=!0,this.playlistFileDownloadPromise.then((()=>{this.playlistFileDownloadCancellationFlag=!1,this.currentManifestUrl=this.cachedManifestUrl,this.cachedManifestUrl=null}))}retryPlaylistFileDownload(e,t=0){let i=Promise.resolve();return i=e().then((()=>(this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!0,absoluteTimeOffsetEstimation:this.absoluteTimeOffset}),Promise.resolve()))).catch((i=>(t++,this.logFn(`Error loading playlist file: ${i} -- attempt ${t}`),this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!1,error:i.message}),t===this.playlistFileDownloadMaxRetryCount?Promise.reject(new Error(`${i} after ${t} attempts`)):this.playlistFileDownloadCancellationFlag?Promise.reject(new Error("cancelling playlist file download")):new Promise((i=>setTimeout((()=>i(this.retryPlaylistFileDownload(e,t))),this.playlistFileDownloadRetryWaitTime)))))),i}estimateStreamTimeFromPlaylist(e){return this.hlsFileParser.getStreamRenditionsUrlsFromManifest(e).then((t=>{if(0===t.audioRenditions.length&&0===t.videoRenditions.length)throw new Error(`Unable to retrieve renditions URLs from manifest: ${e}`);return Promise.all([t.videoRenditions.length>0?this.hlsFileParser.getTextFileContent(t.videoRenditions[0]):Promise.resolve(null),t.audioRenditions.length>0?this.hlsFileParser.getTextFileContent(t.audioRenditions[0]):Promise.resolve(null)])})).then((e=>{let t;for(let i=0;i<e.length;i++){const n=e[i];if(n){this.logFn("Using segment duration and sequence number to calculate absolute time offset","debug");const e=this.hlsFileParser.getHlsFieldByName("SequenceNumber",n);if(0==e.length)throw new Error("Unable to retrieve sequence number from playlist file");const i=this.hlsFileParser.getHlsFieldByName("SegmentDuration",n,10);if(0==i.length)throw new Error("Unable to retrieve segment durations from playlist file");const r=i.map(Number);r.sort(((e,t)=>e-t));const s=r[Math.floor(r.length/2)],a=Number(e[0])*Number(s);t=t?Math.max(t,a):a}}this.estimatedAbsoluteTimeOffset=t}))}}}var ri=ni();function si(){return class{constructor(e){this.fieldNameRegexMap={BaseUrl:/(.*)\/.*/,AudioManifestFile:/#EXT-X-MEDIA:TYPE=AUDIO.*URI=\"(.*)\"/,SequenceNumber:/#EXT-X-MEDIA-SEQUENCE:(\d+)/,SegmentDuration:/#EXTINF:(\d+(\.\d+)?)/},this.logFn=(t,i)=>e(`[HlsFileParser]: ${t}`,i)}getHlsFieldByName(e,t,i=1){const n=[];for(let r=1;r<=i;r++){const i=this.fieldNameRegexMap[e].exec(t);if(!(i&&i.length>0))break;n.push(i[1]),t=t.substring(i.index+i[0].length)}return n}getStreamRenditionsUrlsFromManifest(e){return e?this.getTextFileContent(e).then((t=>{const i={audioRenditions:[],videoRenditions:[]},n=t.split("\n"),r=this.getHlsFieldByName("BaseUrl",e);for(let e=0;e<n.length;e++)if(n[e].includes("#EXT-X-STREAM-INF")){const t=n[e+1];t.includes("http")?i.videoRenditions.push(t):r.length>0&&i.videoRenditions.push(`${r[0]}/${t}`)}else if(n[e].includes("EXT-X-MEDIA:TYPE")){const t=this.getHlsFieldByName("AudioManifestFile",n[e]);if(t.length>0){const e=t[0];e.includes("http")?i.audioRenditions.push(e):r.length>0&&i.audioRenditions.push(`${r[0]}/${e}`)}}return i})).catch((e=>(this.logFn(`Failed to extract stream renditions from manifest, error: ${e.message}`,"error"),{audioRenditions:[],videoRenditions:[]}))):(this.logFn("No manifest URL provided to parse"),Promise.resolve({audioRenditions:[],videoRenditions:[]}))}getTextFileContent(e){return fetch(e).then((t=>{if(!t.ok)throw new Error(`http-error ${t.status} when downloading: ${e}`);return t.text()})).catch((e=>(this.logFn(`Error downloading resource: ${e}`,"error"),Promise.reject(e))))}}}function ai(){return class{constructor(e,t,i,n,r){this.playerInstance=e,this.contextWindow=t,this.streamingStartedTimestamp=i,this.configProvider=n,this.absoluteTimeOffsetEstimator=r,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(e,t){this.currentDiagnosticSnapshot[e]=t}getValue(e){return this.currentDiagnosticSnapshot[e]}appendAbsoluteTimeOffsetEstimation(e){this.absoluteTimeOffsetEstimationResults.push(e),this.absoluteTimeOffsetEstimationResults.length>this.configProvider.config.ampSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount&&this.absoluteTimeOffsetEstimationResults.splice(0,1)}getPlayerDiagnosticSnapshot(){if(!this.playerInstance)return null;const e=window.screen,t=this.playerInstance.error(),i=e=>{const t=e.slice().sort();return t[Math.floor(t.length/2)]};this.currentDiagnosticSnapshot.errorCode=t&&t.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 n=this.getPlayerCachedLength(),r=this.getPlayerEdgeLatency();this.currentDiagnosticSnapshot.audioBufferLength=this.playerAudioBuffer?this.playerAudioBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.audioCachedLength=n,this.currentDiagnosticSnapshot.audioEdgeLatency=r,this.currentDiagnosticSnapshot.videoBufferLength=this.playerVideoBuffer?this.playerVideoBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.videoCachedLength=n,this.currentDiagnosticSnapshot.videoEdgeLatency=r,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=e?e.height:0,this.currentDiagnosticSnapshot.windowWidth=e?e.width:0,this.currentDiagnosticSnapshot.isFullscreen=this.playerInstance.isFullscreen(),this.currentDiagnosticSnapshot.avgAudioDownloadLatency=i(this.audioDownloadLatencies),this.currentDiagnosticSnapshot.avgVideoDownloadLatency=i(this.videoDownloadLatencies),this.currentDiagnosticSnapshot.avgAudioDownloadBytes=i(this.audioDownloadBytes),this.currentDiagnosticSnapshot.avgVideoDownloadBytes=i(this.videoDownloadBytes),this.currentDiagnosticSnapshot.maxVideoDownloadBytes=Math.max.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.minVideoDownloadBytes=Math.min.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.avgAudioDownloadBandwidth=i(this.audioDownloadBandwidths),this.currentDiagnosticSnapshot.avgVideoDownloadBandwidth=i(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 s=this.getDiagnosticWritableField();return Object.keys(s).forEach((e=>{this.currentDiagnosticSnapshot[e]=s[e]})),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 e="options_";return this.playerInstance[e]&&this.playerInstance[e].sdn&&this.playerInstance[e].sdn.name}getStreamType(e){let t="";return this.playerInstance&&(t=this.playerInstance.isLive()?"LIVE":"DVR"),""===t||"LIVE"===e&&t!==e?e||"":t}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 e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;return Number(e.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 e=this.playerAudioBuffer.downloadCompleted.mediaDownload.bitrate;e!==this.lastAudioDownloadBitrate&&(this.lastAudioDownloadBitrate=e)}addToList(e,t,i){e.push(t),e.length>i&&e.shift()}onVideoDownloadError(){this.videoDownloadFailureCount++,this.addDownloadFailureInfo(this.playerVideoBuffer.downloadFailed,this.videoDownloadFailures)}onAudioDownloadError(){this.audioDownloadFailureCount++,this.addDownloadFailureInfo(this.playerAudioBuffer.downloadFailed,this.audioDownloadFailures)}addDownloadFailureInfo(e,t){const i={bitrate:e.mediaDownload.bitrate,errorCode:e.code,mediaTime:e.mediaDownload.mediaTime,message:e.message,timestamp:Date.now()};this.addToList(t,i,this.downloadFailuresLimit)}getAudioStreamData(){const e=this.playerInstance.currentAudioStreamList();if(e)try{const t=e.streams[e.enabledIndices[0]];return{bitrate:t.bitrate,codec:t.codec,enabled:t.enabled,name:t.name,language:t.language}}catch(e){return}}getVideoStreamData(){const e=this.playerInstance.currentVideoStreamList();if(e)try{const t=e.streams[e.selectedIndex],i=this.playerInstance.currentPlaybackBitrate(),n=e=>({bitrate:e.bitrate,height:e.height,id:e.id,selectable:e.selectable,width:e.width}),r=t.tracks?t.tracks.map(n).find((e=>e.bitrate===i)):null;return{codec:t.codec,name:t.name,currentTrack:r}}catch(e){return}}getLivePosition(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t}getAverageDownloadBitrate(){if(this.streamingStartedTimestamp&&this.totalDownloadedBytes){const e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;if(e>0)return 8*this.totalDownloadedBytes/e}return 0}getRetryFrequency(){const e=this.currentDiagnosticSnapshot.retryCount;if(this.streamingStartedTimestamp&&e){const t=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/6e4;if(t>0)return e/t}return 0}getAverageMeasuredBandwidth(){if(0===this.videoDownloadBandwidths.length)return null;let e=0;for(let t=0;t<this.videoDownloadBandwidths.length;t++)e+=this.videoDownloadBandwidths[t];return e/this.videoDownloadBandwidths.length}getAverageMeasuredVideoDownloadSize(){if(0===this.videoDownloadBytes.length)return null;let e=0;for(let t=0;t<this.videoDownloadBytes.length;t++)e+=this.videoDownloadBytes[t];return e/this.videoDownloadBytes.length}getPlayerCachedLength(){const e=this.playerInstance.buffered();let t=0;for(let i=0;i<e.length;i++)t+=e.end(i)-e.start(i);return t}getPlayerEdgeLatency(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t-this.playerInstance.currentTime()}}}function oi(){return class{constructor(e,t,i,n){this.player=e,this.toggleListener=t,this.config=i,this.diagnosticProvider=n,this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.isHtml5Tech="html5"===this.player.currentTechName()?.toLowerCase()}dispose(){this.unsubscribeFromTrackEvents(),this.player=null,this.toggleListener=null}initialize(){const e=this.getPlayerTextTracksAsArray();if(!this.config.controlsEnabled&&e.length>0)e[0].mode="showing";else for(let t=0;t<e.length;t++)e[t].mode="disabled";this.subscribeOnTrackEvents()}addCues(e){const t=this.player.getCurrentTextTrack();if(!t)return;const i=this.getCurrentAbsoluteTime()||1,n=this.getCurrentTime(),r=this.config.controlsEnabled?i-n:Math.max(i-n,0),s=this.isHtml5Tech?window.VTTCue:window.vttjs&&window.vttjs.VTTCue||window.VTTCue;for(let i=0;i<e.length;i++){const{start:n,end:a,text:o}=e[i],l=2,c=new s(Number((n-r).toFixed(l)),Number((a-r).toFixed(l)),o);c.size=100,!this.containsCue(t,c)&&t.addCue(c)}}clearCues(){const e=this.player.getCurrentTextTrack();if(e)try{if(e.activeCues&&e.removeCue)for(;e.activeCues.length>0;)e.removeCue(e.activeCues[0]);const t="setCues_";if(e.cues[t]){e.cues_&&(e.cues_.length=0),e.cues[t]([]);const i=Object.getOwnPropertyNames(e.cues);for(let t=0;t<i.length;t++)"length"!==i[t]&&"length_"!==i[t]&&"cues_"!==i[t]&&delete e.cues[i[t]]}}catch(e){this.config.logFn(`[clearCues]: ${e}`,"warn")}}showCaptions(e){this.config.logFn(`[CaptionsControl]: showCaptions(${e})`),e?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 e=this.player.textTracks(),t="addEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}unsubscribeFromTrackEvents(){const e=this.player.textTracks(),t="removeEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}onTextTrackChanged(){const e=this.player.getCurrentTextTrack();if(!e||!this.currentTextTrack||this.currentTextTrack.label!==e.label||this.currentTextTrack.mode!==e.mode){if(e||this.currentTextTrack){const t=!!e&&"showing"===e.mode,i=this.getCulture(e||this.currentTextTrack),n=this.getCurrentTime();this.toggleListener.captionsToggled(t,i,n),this.config.logFn(`[CaptionsControl]: track changed: culture '${i}', timestamp '${n}'`)}this.currentTextTrack=e}}onAddTrack(e){const t=e?.track;"captions"===t?.kind&&!t.label&&!t.id&&(this.player?.textTracks_?.removeTrack_(t),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(e){if(!e)return"";if(e.id){const t=e.id.split("_")[1];if(t)return t}return""}getPlayerTextTracksAsArray(){const e=this.player.textTracks();return e&&e.tracks_||[]}containsCue(e,t){return Array.from(e?.cues||[]).some((e=>this.areCueEquals(e,t)))}areCueEquals(e,t){function i(e){return{start:e.start?e.start:e.startTime,end:e.end?e.end:e.endTime,text:e.text}}const n=i(e),r=i(t);return n.start===r.start&&n.end===r.end&&n.text===r.text}}}function li(){const e=ii(),t=ei(),i=new e,n=new t(i,document.body);i.registerObserver(n)}function ci(){let e=`(${li.toString()})();`;return e+=Xt.toString()+";",e+=ii.toString()+";",e+=ei.toString()+";",e+=oi.toString()+";",e+=ai.toString()+";",e+=ni.toString()+";",e+=si.toString()+";",e+="//# sourceURL=TsCallingAmpPlayer.js",e}var di=class{sendMsg(e){this.peer.onMsg(e)}registerObserver(e){this.observer=e}onMsg(e){this.observer&&this.observer.processMessage(e)}connect(e){this.peer=e}dispose(){this.peer=null,this.observer=null}},ui=class{constructor(e){this.container=e}get contextWindow(){return this.container.ownerDocument.defaultView}sendMsg(e){this.iframe?.contentWindow?.postMessage(e,"*")}registerObserver(e){this.observer=e}dispose(){this.contextWindow&&this.contextWindow.removeEventListener("message",this.processMsg),this.iframe&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe),this.iframe=null}initializeAmpIframe(e){const t=this.initializeIframe();return this.setAmpIframeContent(e),this.finalizeIframe(t)}initializeIframe(){const e=new Kt;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=()=>{e.resolve()},this.iframe.onerror=()=>{e.reject("iframe load failed")},e}finalizeIframe(e){return this.container.appendChild(this.iframe),this.processMsg=this.processMsg.bind(this),this.contextWindow.addEventListener("message",this.processMsg),e.promise}processMsg(e){"null"===e.origin&&e.source===this.iframe.contentWindow&&this.observer&&("RequestIceCandidates"===e.data?this.observer.processMessage({msgType:"Command",cmd:"getIceCandidates",args:[]}):this.observer.processMessage(e.data))}setAmpIframeContent(e){const t=ci(),i=`\n <html class style='height: 100%; width: 100%; overflow: hidden'>\n <head></head>\n <body class style='height: 100%; width: 100%; margin: 0px'>\n ${e?`<script nonce='${e}'> ${t}<\/script>`:`<script> ${t}<\/script>`}\n </body>\n </html>\n `;this.iframe.srcdoc=i}},hi=class extends gt{constructor(e){super(e),this.logger=e,this.resultsMap=new Map,this.on("log",((e,t)=>{this.logger[e](t)}))}async initialize(e,t,i,n){const r={config:i.config,playerConfig:i.playerConfig},s=i.playerConfig?.nonce||"";this.pipe=await async function(e,t,i){if(0===t){const t=new di,i=new di;return t.connect(i),i.connect(t),i.registerObserver(new ti(i,e)),t}if(1===t){const t=new ui(e);return await t.initializeAmpIframe(i),t}throw new Error(`Unsupported communication type ${t}`)}(e,i.config.loadType,s),this.pipe.registerObserver(this),await this.message("configure").send(t,r,n)}message(e){return{send:this.fromMessage(((...t)=>this.sendMessageImpl(e,...t)))}}dispose(){super.dispose(),this.pipe.sendMsg(this.buildMsg("dispose")),this.pipe.dispose()}processMessage(e){let t;switch(e.msgType){case"CommandResult":t=this.getDeferred(e.cmd.toString()),t&&(e.error?(t.reject(e.error),this.logger.warn(`remote command failed: ${String(e.cmd)}, ${e.error}`)):e.result?t.resolve(e.result):t.resolve(),this.processCommandResult(e),this.resultsMap.delete(e.cmd.toString()));break;case"PlayerNotification":{const t=this.event(e.name);t.raise.apply(t,e.args);break}case"Command":this.processCommand(e).catch((t=>this.logger.warn(`error while processing command: ${JSON.stringify(e)}: ${t}`)));break;default:this.logger.warn(`unexpected message received: ${JSON.stringify(e)}`)}}async processCommand(e){"getIceCandidates"===e.cmd.toString()?await this.message("getIceCandidates").send():this.logger.warn(`unsupported command received: ${JSON.stringify(e)}`)}processCommandResult(e){"getIceCandidates"===e.cmd.toString()?this.pipe.sendMsg({topic:"RequestIceCandidates",candidates:e.result}):this.logger.debug(`ignoring command result for: ${JSON.stringify(e)}`)}fromMessage(e){return e}sendMessageImpl(e,...t){return this.pipe.sendMsg(this.buildMsg(e,t)),this.waitForCompletion(e.toString())}buildMsg(e,t){return{msgType:"Command",cmd:e,args:t}}getDeferred(e){return this.resultsMap.get(e)}waitForCompletion(e){const t=this.getDeferred(e);t&&t.reject(new Error(`function ${e} is invoked again, before previous call is completed`));const i=new Kt;return this.resultsMap.set(e,i),i.promise}},gi=class extends gt{constructor(e,t){super(),this.player=e,this.logger=t,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(e){this.player.seek(e)}seekToLiveEdge(){this.player.seekToLiveEdge()}play(){this.player.play()}pause(){this.player.pause()}setVolume(e){this.player.setVolume(e)}selectVideoTrack(e){this.player.selectVideoTrack(e)}dispose(){this.stopPlayer(),super.dispose()}captions(){return this.player.getCaptionsControl()}getStats(){throw new Error("Method not implemented.")}setScalingMode(e,t){throw new Error("Method not implemented.")}captureFrame(e,t){throw new Error("Method not implemented.")}stopPlayer(){const e=this.player;this.player=null,e&&(this.logger.info("stopPlayer"),this.unsubscribeFromPlayerEvents(),e.stop())}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("fullscreenToggled",(e=>this.onFullScreenToggled(e)))),this.playerSubs.push(this.player.on("captionsToggled",((e,t,i)=>this.onCaptionsToggled(e,t,i)))),this.playerSubs.push(this.player.on("playbackTimeUpdated",(e=>this.onPlaybackTimeUpdated(e)))),this.playerSubs.push(this.player.on("videoTracksChanged",(e=>this.onVideoTracksChanged(e))))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onFullScreenToggled(e){this.event("fullScreenToggled").raise(e)}onCaptionsToggled(e,t,i){this.logger.info(`Turned captions ${e?"ON":"OFF"} for culture [${t}] at player time [${i}]`),this.event("captionsToggled").raise(e,t,i)}onPlaybackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}onVideoTracksChanged(e){this.event("videoTracksUpdated").raise(e)}},pi=class{constructor(e,t){this.player=e,this.availableCultures=t,this.selectedCulture="",this.disposable=this.player.on("captionsToggled",((e,t,i)=>{this.selectedCulture=e?t:""}))}async addCues(e){await this.player.message("addCues").send(e)}async clearCues(){await this.player.message("clearCues").send()}async showCaptions(e){await this.player.message("showCaptions").send(e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.disposable.dispose(),this.player=null}};function mi(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function fi(e){return new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)&&36===e.length}var vi=[2097152,2097552,2097556,2097557,2097564,2097652,2097654,2097655,2097656,2097752,3145728,4194305,4194306,4194307,4194308,4194309,5242880,5242881,5242882,5242884,5242885,5242886],Si=2097753,yi=class extends gt{constructor(e,t,i){super(),this.logger=e,this.liveStreamStatistic=t,this.configProvider=i,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=mi(),this.logger.info(`AmpLiveStreamPlayer created: ID: ${this.id}`)}get playerId(){return this.id}async configure(e){if(!$t(e.stream)&&!$t(e.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=e;const t=$t(e.stream)?e.stream:e.altStream;if(this.playerInstance&&!this.isPlaybackUnsupported){try{await this.playerInstance.message("configure").send(e)}catch(e){const t=tt(e);this.logger.error(`configure failed: ${t}`)}await this.handleStreamInfoUpdate(t)}else this.selectedStreamDetails=t}async loadPlayer(e){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||!$t(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 hi(this.logger.createChild("AmpPlayerWrapper")),this.playerInstance.on("stateChanged",((e,t)=>this.ampStateChanged(e,t))),this.playerInstance.on("captionsToggled",((e,t,i)=>this.captionsToggled(e,t,i))),this.playerInstance.on("statsUpdated",(e=>this.liveStreamStatistic.registerStatsUpdated(e)));const t=this.configProvider.config.ampSettings.noMediaTimeoutMs;let i;-1!==t&&-1===this.noMediaTimeoutId&&(this.noMediaTimeoutId=self.setTimeout((()=>this.callDropDueToMediaTimeout()),t)),await this.playerInstance.initialize(e,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{i=await this.srcLoadPromise}catch(e){const t=tt(e);return this.logger.error(`playerLoadFailed: player scripts load failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("LoadScript",`Load Script failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`script load failed: ${i}`),this.srcLoadPromise=null,{setupSucceeded:!1,playerSetupError:{errorType:"PlayerScriptLoadFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("LoadScript"),await this.tryLoadSdnPlugin(),this.liveStreamStatistic.registerEventLoadAttempt("CreateAmp");try{await this.playerInstance.message("createAmp").send()}catch(e){const t=tt(e);return this.logger.error(`playerLoadFailed: createAmp failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("CreateAmp",`createAmp failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`create amp failed ${t}, script load: ${i}`),{setupSucceeded:!1,playerSetupError:{errorType:"PlayerInitializationFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("CreateAmp");try{return await this.setPlayerSource(this.selectedStreamDetails),this.loadSucceeded=!0,this.logger.info(`loadPlayer succeeded: ${this.loadSucceeded}`),this.liveStreamStatistic.registerPlayerLoadSucceeded(i),this.playerState="Initialized",{setupSucceeded:this.loadSucceeded}}catch(e){const t=tt(e);return this.loadSucceeded=!1,this.logger.error(`loadPlayer succeeded: ${this.loadSucceeded}: setSource failed: ${t}`),this.liveStreamStatistic.registerPlayerLoadFailed(`setPlayerSource failed; script load: ${i}`),{setupSucceeded:this.loadSucceeded,playerSetupError:{errorType:"SetSourceFailed",errorMessage:t}}}}getRenderer(){return!this.renderer&&this.playerInstance&&(this.renderer=new gi(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}seek(e){throw new Error(`Method not implemented - cannot perform video seek operation with args: [timestamp: ${e}]`)}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(e){throw new Error(`Method not implemented - cannot set video volume with args: [volume: ${e}]`)}selectVideoTrack(e){throw new Error(`Method not implemented - cannot select video track with args: [track: ${e}]`)}stop(){this.destroy("PlayerStopped")}getPlaybackState(){return this.playerState}getCaptionsTimestamp(){return this.captionsTimestamp}getCaptionsControl(){if(!this.captionsControl&&this.playerInstance){const e=this.liveStreamOptions.supportedSubtitleLanguages?this.liveStreamOptions.supportedSubtitleLanguages.map((e=>e.culture)):[];this.captionsControl=new pi(this.playerInstance,e)}return this.captionsControl}getStreamSize(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e?{width:e.mediaWidth,height:e.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.height>0}ampStateChanged(e,t){switch(e){case"error":return this.handlePlaybackError(t);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(t);case"loadedmetadata":return this.onMetadataLoaded();case"waiting":return this.onWaiting();case"playbackbitratechanged":return this.onPlaybackBitrateChanged(t);case"downloadbitratechanged":return this.onDownloadBitrateChanged(t);case"fullscreenchange":return this.onFullscreenChange(t);case"potentialMediaFreeze":return this.onPotentialMediaFreeze();case"mute":return this.onMute();case"unmute":return this.onUnmute();case"volumechange":return this.onVolumeChange(t);case"loadstart":return this.onLoadStart();case"loadeddata":return this.onLoadedData();case"UserInitiatedSeek":return this.onUserInitiatedSeek(t);default:this.logger.warn(`Unknown amp event ${e}`)}}onUserInitiatedSeek(e){this.liveStreamStatistic.registerUserInitiatedSeek(e)}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i),this.liveStreamStatistic.registerCaptionToggle(e,t,i)}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 e;this.liveStreamStatistic.registerEventLoadAttempt("SdnPluginLoad");try{this.sdnPluginLoadPromise=this.playerInstance.message("tryLoadSdnPlugin").send(),await this.sdnPluginLoadPromise,this.liveStreamStatistic.registerEventLoadSucceeded("SdnPluginLoad",this.liveStreamOptions.sdn.name)}catch(t){e=tt(t),this.sdnPluginLoadPromise=void 0,this.logger.error(`loadSdnPlugin failed: ${e}`),this.liveStreamStatistic.registerEventLoadFailed("SdnPluginLoad",e),this.event("sdnPluginLoadFailed").raise(e)}}raiseSdnPluginSkippedEvent(e){this.logger.warn(`skipping SDN plugin load: ${e}`),this.event("sdnPluginLoadSkipped").raise(e)}async setPlayerSource(e){if(!e)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: [${e.url}]`),this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;try{this.logger.info("setPlayerSource: src changed"),this.selectedStreamDetails=e,this.liveStreamStatistic.registerSetSourceAttempt(e.url),await this.playerInstance.message("setSource").send(e),this.liveStreamStatistic.registerSetSourceSucceeded()}catch(e){const t=tt(e);throw this.logger.error(`setPlayerSource: failed with error [${t}]`),this.liveStreamStatistic.registerSetSourcedFailed(t),e}}async handleStreamInfoUpdate(e){this.loadSucceeded&&e.url!==this.selectedStreamDetails.url?await this.setPlayerSource(e):this.loadSucceeded&&this.playerInstance&&this.getCurrentTime()>0&&this.setPlaybackState("Start")}async switchStreamingUrl(e,t){if(this.streamingUrlSwitchCount>=this.configProvider.config.ampSettings.streamingUrlSwitchMaxCount||!(0,zt.includes)(this.configProvider.config.ampSettings.errorCodesEligibleForStreamingUrlSwitch,e)&&!t)return!1;const i=this.selectedStreamDetails.url===this.liveStreamOptions.stream?.url,n=i?this.liveStreamOptions.altStream:this.liveStreamOptions.stream;return $t(n)?(this.isSwitchStreamingUrlOngoing=!0,this.streamingUrlSwitchCount++,this.setPlayerSource(n).then((()=>!0)).catch((()=>!1))):(this.logger.error(`Stream to switch (${i?"alternative":"primary"}) is not valid`),!1)}destroy(e){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(e),this.playerInstance.dispose(),this.playerInstance=null,this.setPlaybackState("Destroyed"))}getCurrentTime(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e&&e.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(e){this.captionsTimestamp=e.captionsTimestamp,this.setPlaybackState("Seeked")}onMetadataLoaded(){this.setPlaybackState("LoadedMetadata")}onWaiting(){this.setPlaybackState("Buffering")}onLoadedData(){this.setPlaybackState("LoadedData")}onLoadStart(){this.setPlaybackState("LoadStart")}setPlaybackState(e){this.playerState=e,this.logger.debug(`playback state changed: ${e}`),this.liveStreamStatistic.registerPlaybackStateChanged(e),this.event("playbackStateChanged").raise()}onPlaybackBitrateChanged(e){this.liveStreamStatistic.registerPlaybackBitratechanged(e.bitrate)}onDownloadBitrateChanged(e){this.liveStreamStatistic.registerDownloadBitratechanged(e.bitrate)}onFullscreenChange(e){this.logger.debug(`fullscreenchange, isFullscreen=${e.isFullscreen}`),this.event("fullscreenToggled").raise(e.isFullscreen),this.liveStreamStatistic.registerFullScreenChange(e.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(e){this.liveStreamStatistic.registerVolumeChange(e.value)}stringifyPlayerError(e){return JSON.stringify(e,(function(e,t){return"errorCode"===e?t.toString(16):t}))}async handlePlaybackError(e){const t=4194307;this.playerState="Error",this.lastPlaybackError=e;const i=this.stringifyPlayerError(e);if(this.logger.info(`Playback error ${i}`),!e.errorCode&&null==e.fatal)return void this.logger.error("onError: error details are not available");if((e.errorCode&t)===t)return this.isPlaybackUnsupported=!0,this.raisePlaybackError("UnsupportedPlatform",i),void this.destroy("PlaybackError");this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;const n=e.errorCode,r=268435455&n;this.logger.error(`onError: errorCode: 0x${n.toString(16)}, errorCodeExcludingTech: 0x${r.toString(16)}, message: ${e.message}`),this.retryCount<this.configProvider.config.maxRetryCount&&(!1===e.fatal||-1!==(0,zt.indexOf)(vi,r))?setTimeout((async()=>{this.logger.info(`Retry loading stream because of error code: 0x${n.toString(16)}`),this.retryCount++,this.raisePlaybackError("PlaybackRetried",i),this.setPlayerSource(this.selectedStreamDetails)}),this.configProvider.config.ampSettings.sourceResetTimeoutInMs):await this.switchStreamingUrl(r,e.fatal)?this.configProvider.config.ampSettings.resetStreamingUrlSwitchCount&&(this.streamingUrlSwitchCount=0):(r===Si||e.message?.includes(Si.toString(16))?this.raisePlaybackError("NetworkError",i):this.raisePlaybackError("PlaybackError",i),this.destroy("PlaybackError"))}raisePlaybackError(e,t){this.liveStreamStatistic.registerPlaybackError(e,t),this.event("playbackError").raise(e,t)}callDropDueToMediaTimeout(){const e={currentTime:-1,errorCode:0,message:JSON.stringify({state:this.playerState,error:this.stringifyPlayerError(this.lastPlaybackError)}),fatal:!0},t=this.stringifyPlayerError(e);this.raisePlaybackError("MediaTimeout",t),this.destroy("MediaTimeout")}},Ci=p(q()),Ti=class extends gt{constructor(e,t,i){super(),this.logger=e,this.telemetryLogger=i,this.playerLoaded=!1,this.playbackState="Destroyed",this.playerSubs=[],this.isFinalTelemetrySent=!1,this.captionsTimestamp=0,this.configProvider=t;const n=this.createHydraPlayerSettings();this.eventHandler=this.createEventHandler(),this.addPlayerEventSubscribers(),this.hydraPlayer=new Ci.HydraPlayer(n,this.eventHandler)}async configure(e){if(this.streamOptions=e,this.threadId=e.threadId,this.playerLoaded){const e=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}}async loadPlayer(e){if(!await this.hydraPlayer.setup(e))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const e=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}else this.logger.warn("No stream options configured before Hydra player loaded");const t=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return t.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(t)}convertStreamDeliveryPipeline(e){switch(e){case"AMS":return Ci.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return Ci.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return Ci.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${e} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(e){switch(e){case"TLE":return Ci.HydraStreamingEventType.TLE;case"Overflow":return Ci.HydraStreamingEventType.Overflow;case"TownHall_Basic":return Ci.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return Ci.HydraStreamingEventType.TownHallPremium;case"TownHall":return Ci.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${e} to HydraStreamingEventType`)}}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(e=>{this.onPlaybackStateChanged(e)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(e=>{this.onPlaybackSeeked(e)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("playbackTimeUpdated",(e=>{this.onPlaybackTimeUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("videoTracksUpdated",(e=>{this.onVideoTracksUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(e=>{this.onStatsUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("log",((e,t)=>{this.onLog(e,t)}))),this.playerSubs.push(this.eventHandler.on("capabilitiesUpdated",(e=>{this.onCapabilitiesUpdated(e)})))}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}startTelemetryGathering(){let e,t;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?(e=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs):(e=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs),e&&(this.diagSub=window.setInterval((async()=>{this.sendSnapshotTelemetry()}),t))}getHydraPlayerSetupResult(e){return{setupSucceeded:e.setupSucceeded,playerSetupError:e.playerSetupError?{errorType:this.convertHydraPlayerSetupError(e.playerSetupError.errorType),errorMessage:e.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(e){switch(e){case Ci.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case Ci.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case Ci.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case Ci.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new gi(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(e){this.playerStats=e}getStats(){return this.playerStats}onLog(e,t){this.logger[e](t)}onPlaybackStateChanged(e){try{this.playbackState=this.convertHydraPlaybackState(e),this.event("playbackStateChanged").raise()}catch(e){this.logger.warn(`Not handling playback state changed event: ${tt(e)}`)}}convertHydraPlaybackState(e){switch(e){case Ci.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case Ci.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case Ci.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case Ci.HydraPlayerPlaybackState.Start:return"Start";case Ci.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case Ci.HydraPlayerPlaybackState.Play:return"Play";case Ci.HydraPlayerPlaybackState.Playing:return"Playing";case Ci.HydraPlayerPlaybackState.Pause:return"Paused";case Ci.HydraPlayerPlaybackState.Waiting:return"Buffering";case Ci.HydraPlayerPlaybackState.Seeking:return"Seeking";case Ci.HydraPlayerPlaybackState.Seeked:return"Seeked";case Ci.HydraPlayerPlaybackState.Ended:return"Ended";case Ci.HydraPlayerPlaybackState.Error:return"Error";case Ci.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case Ci.HydraPlayerPlaybackState.Initialized:return"Initialized";case Ci.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${e} to PlaybackState`)}}onPlaybackError(e,t){try{const i=this.convertHydraPlaybackErrorType(e);this.event("playbackError").raise(i,t)}catch(e){this.logger.warn(`Not handling playback error event: ${tt(e)}`)}}convertHydraPlaybackErrorType(e){switch(e){case Ci.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case Ci.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case Ci.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case Ci.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case Ci.HydraPlayerPlaybackErrorType.MediaTimeout:return"MediaTimeout";case Ci.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${e} to PlaybackErrorType`)}}seek(e){this.hydraPlayer.callPlayerApi("seekHydraPlayer",e)}seekToLiveEdge(){this.hydraPlayer.callPlayerApi("seekHydraPlayerToLiveEdge")}play(){this.hydraPlayer.callPlayerApi("playHydraPlayer")}pause(){this.hydraPlayer.callPlayerApi("pauseHydraPlayer")}setVolume(e){this.hydraPlayer.callPlayerApi("setHydraPlayerVolume",e)}selectVideoTrack(e){this.hydraPlayer.callPlayerApi("selectHydraPlayerVideoTrack",e)}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.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(e){if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const t={...this.getTelemetryReport(),isFinal:e,threadId:this.threadId,tsCallingVersion:"2025.07.01.15",correlationId:this.streamOptions.correlationId};this.logger.debug("generated live stream report: ",t),this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}else this.logger.info("telemetry not sent")}sendSnapshotTelemetry(){if(this.telemetryLogger){const e={...this.getSnapshotTelemetryReport(),isFinal:!1,threadId:this.threadId,tsCallingVersion:"2025.07.01.15",correlationId:this.streamOptions.correlationId};this.logger.debug("sending snapshot telemetry: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set")}clearPlayerEventSubscribers(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackSeeked(e){this.captionsTimestamp=e}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}onVideoTracksUpdated(e){this.event("videoTracksChanged").raise(e)}onCapabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},Ei=class extends gt{constructor(){super()}playbackStateChanged(e){this.event("playbackStateChanged").raise(e)}playbackSeeked(e){this.event("playbackSeeked").raise(e)}log(e,t){this.event("log").raise(e,t)}playbackError(e,t){this.event("playbackError").raise(e,t)}urlSwitched(e){this.event("urlSwitched").raise(e)}sdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}sdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}statsUpdated(e){this.event("statsUpdated").raise(e)}playbackStarted(){this.event("playbackStarted").raise()}playbackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}videoTracksUpdated(e){this.event("videoTracksUpdated").raise(e)}capabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},bi=p(q());function _i(e){if(e.playbackCoordinates)return e.playbackCoordinates;if(!e.url&&!e.hlsUrls)return[];const t=[];return(e.hlsUrls?e.hlsUrls:[e.url]).forEach((i=>{t.push({url:i,sdnContext:e.sdnContext})})),t}function Ii(e){return e.url?[{url:e.url,sdnContext:e.sdnContext}]:[]}var wi=["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"],Ai=class extends Ti{createEventHandler(){return new Ri}createHydraPlayerSettings(){return{playerType:bi.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??wi,disableSandbox:this.configProvider.config.hlsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??""}}createHydraStreamOptions(){let e=bi.HydraStreamingEventType.TLE;e=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?bi.HydraStreamingEventType.Overflow:bi.HydraStreamingEventType.TLE;const t={stream:{playbackCoordinates:_i(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:_i(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:e,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&&(t.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(t.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(t.meetingMetadata=this.streamOptions.meetingMetadata),t}onCaptionsToggled(e,t,i){this.captionsControl&&this.captionsControl.toggleCaptions(e,t),this.event("captionsToggled").raise(e,t,i)}getCaptionsControl(){if(!this.captionsControl&&this.hydraPlayer){const e=this.streamOptions?.supportedSubtitleLanguages?this.streamOptions.supportedSubtitleLanguages.map((e=>e.culture)):["en","es"];this.captionsControl=new Pi(this.hydraPlayer,e)}return this.captionsControl}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("captionsToggled",((e,t,i)=>{this.onCaptionsToggled(e,t,i)})))}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Pi=class{constructor(e,t){this.hydraPlayer=e,this.availableCultures=t,this.selectedCulture=""}async addCues(e){const t=this.convertCues(e);await this.hydraPlayer.callPlayerApi("addHydraPlayerCues",t)}convertCues(e){const t=[];return e.forEach((e=>{t.push({start:e.start,end:e.end,text:e.text})})),t}async clearCues(){await this.hydraPlayer.callPlayerApi("clearHydraPlayerCues")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.hydraPlayer=null}toggleCaptions(e,t){this.selectedCulture=e?t:""}},Ri=class extends Ei{constructor(){super()}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i)}},Mi=p(q()),Di=class extends Ti{get tracks(){return this.trackInfo}createEventHandler(){return new Oi}createHydraPlayerSettings(){return{playerType:Mi.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 e=Mi.HydraStreamingEventType.TLE;e=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?Mi.HydraStreamingEventType.Overflow:Mi.HydraStreamingEventType.TLE;const t={stream:{playbackCoordinates:Ii(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:Ii(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:e,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&&(t.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(t.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(t.meetingMetadata=this.streamOptions.meetingMetadata),t}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("trackListUpdated",(e=>{this.onTrackListUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("trackSelected",(e=>{this.onTrackSelected(e)})))}onTrackListUpdated(e){this.trackInfo=e;const t=tt(e);this.logger.info(`[onTrackListUpdated]: Track list updated to: ${t}`)}onTrackSelected(e){const t=tt(e);this.logger.info(`[onTrackSelected]: Track selected: ${t}`)}getCaptionsControl(){return!this.captionsControl&&this.hydraPlayer&&(this.captionsControl=new ki(this.hydraPlayer,this.logger.createChild("CaptionsControl"))),this.captionsControl}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},ki=class{constructor(e,t){this.hydraPlayer=e,this.logger=t}async addCues(e){this.logger.warn("[addCues]: not implemented for UMS player")}async clearCues(){this.logger.warn("[clearCues]: not implemented for UMS player")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",e)}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(e){await this.hydraPlayer.callPlayerApi("selectHydraPlayerTextTrack",e)}},Oi=class extends Ei{constructor(){super()}trackListUpdated(e){this.event("trackListUpdated").raise(e)}trackSelected(e){this.event("trackSelected").raise(e)}},Ni=class extends gt{constructor(e,t,i){super(),this.configProvider=e,this.logger=t,this.getTelemetryLogger=i,this.isAvailable=!0,this._isStreaming=!1,this.playerSubs=[],this.isFinalTelemetrySent=!1,this.telemetryLogger=this.getTelemetryLogger(),1===this.configProvider.playerConfig.playerType?this.player=new Ai(this.logger.createChild("HlsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):2===this.configProvider.playerConfig.playerType?this.player=new Di(this.logger.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):(this.initializeAmpTelemetry(),this.player=new yi(this.logger.createChild("AmpLiveStreamPlayer"),this.liveStreamStatistic,this.configProvider)),this.subscribeForPlayerEvents()}get isStreaming(){return this._isStreaming}isActive(){return this.isAvailable&&this.isStreaming}async start(e,t){await this.setOptions(t),this.isFinalTelemetrySent=!1;const i=await this.player.loadPlayer(e);if(!i.setupSucceeded){this.player.stop(),this.logger.error("playerLoadFailed");const e=JSON.stringify(i.playerSetupError);throw this.sendFinalTelemetry(e),new Error(e)}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(){this.liveStreamStatistic=new qt(this.configProvider.config,this.logger.createChild("LiveStreamStatistic"),{perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],currentMediaTime:[],statsInterval:[]})}async stop(){}async setOptions(e){return void 0!==e.overflow&&(e.streamingEventType||(e.streamingEventType=e.overflow?"Overflow":"TLE"),delete e.overflow),this.options=e,this.player.configure(e)}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(e){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0,e))}sendTelemetry(e,t){if(this.liveStreamStatistic)if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const i={configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:e,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton,callendReason:t},n=this.liveStreamStatistic?.getReport(i);this.logger.debug("generated live stream report",n),this.telemetryLogger.sendEvent({eventName:"live_events",props:n})}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 e=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: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}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",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.player.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.player.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.player.on("capabilitiesUpdated",(e=>this.onCapabilitiesUpdated(e))))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackStateChanged(){const e=this.player.getPlaybackState();switch(e){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: ${e}`)}this.event("playbackStateChanged").raise(this.player.getPlaybackState())}onPlaybackError(e,t){this.event("error").raise(e,t)}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}onCapabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},Li=class{constructor(e,t,i){this.ecsConfig=e,this.logger=t,this.getTelemetryLogger=i}configure(e){this.configuration=e}async initialize(){const e="MDN_MIDDLELANE_TEAMS",t="liveStream",i=this.ecsConfig.getString(e,t);let n={};try{n=JSON.parse(i)}catch(i){this.logger.warn(`failed to parse ECS configuration for ${e}/${t}`)}const r=this.ecsConfig.getString("ConfigIDs",e);this._configProvider=new Ut(n,this.configuration,r,this.logger.createChild("LiveStreamConfigProvider"))}createLiveStream(){return new Ni(this._configProvider,this.logger.createChild("LiveStream"),this.getTelemetryLogger)}dispose(){}},xi=class extends gt{constructor(){super(...arguments),this.isAudioOutputSelectionSupported=!1}createAudioPlayer(){return null}createAudioRenderer(){return null}getRawDeviceMediaStream(e){return null}askDevicePermission(){return Promise.resolve({audio:!1,video:!1})}getPermissionState(e){return"granted"}enumerateDevicesAsync(){return Promise.resolve([])}getPreferredCamera(){return null}selectDevices(){}getSelectedDevices(){return{}}startPreview(){return null}createPreview(){return Promise.resolve(new Fi)}createPreviewRenderer(){return Promise.resolve(new Fi)}createScreenSharingPreviewRenderer(){return Promise.resolve(new Fi)}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(e){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(e,t){return Promise.resolve()}downloadAiModel(e,t){return Promise.resolve("")}setAudioProcessingFlags(e){}getSpeakerVolume(){return Promise.resolve(0)}getSpeakerSystemVolume(){return Promise.resolve(0)}setSpeakerVolume(e){return Promise.resolve()}setSpeakerSystemVolume(e){return Promise.resolve()}unmuteMicrophone(){return Promise.resolve()}unmuteSpeaker(){return Promise.resolve()}getNrgLevelsForDeviceTuner(e){return Promise.resolve(0)}getNrgLevelPollerForDeviceTuner(e){return Promise.resolve(new Bi)}setAudioEffectsAsync(){return Promise.resolve()}getAudioFeatureCapability(e){return Promise.resolve(0)}getMicrophoneVolume(){return Promise.resolve(0)}setMicrophoneVolume(e){return Promise.resolve()}setDeviceTelemetryData(e,t,i,n=0){return Promise.resolve()}getSpeakerDeviceDomIdAsync(e,t){return Promise.reject()}mapBrowserDevices(e,t){return Promise.reject()}getSourceFormats(e){return Promise.resolve([])}enableShellSharing(){return Promise.resolve()}disableShellSharing(){return Promise.resolve()}enableParticipantCameras(){return Promise.resolve()}registerDerivedSource(e,t){return Promise.resolve()}unregisterDerivedSource(e){return Promise.resolve()}startAudioLoopbackDevice(e){return Promise.resolve()}async dispose(e){return Promise.resolve()}},Fi=class extends gt{constructor(){super(...arguments),this.isRendering=!1,this.streamSize={width:0,height:0},this.rendererType=-1,this.frameType=-1}captureFrame(){return Promise.resolve(new Ui)}getStats(){return Promise.resolve({framesDropped:0,framesTotal:0})}setScalingMode(){return Promise.resolve()}cameraAutoControl(e){return Promise.resolve(!1)}getCameraManualControlStates(e){return Promise.resolve([])}setCameraManualControlStates(e){return Promise.resolve([])}enumerateCameraManualControls(){return Promise.resolve([])}isCameraAdvancedControlCapable(){return Promise.resolve(!1)}dispose(){}},Ui=class extends gt{getSize(){return{width:0,height:0}}isMirrored(){return!1}},Bi=class{getInputLevel(){return 0}getInputLevelNormalized(e,t){return 0}dispose(){}},Vi=gt,Hi="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",$i="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",ji="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00",Gi={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:Hi,MSSDP_ENCODED_URI:Hi.replace(/\//g,"\\"),ATTRIBUTE:"transport-cc"},ABS_SEND_TIME:{EXT_URI:$i,MSSDP_ENCODED_URI:$i.replace(/\//g,"\\")},VLA:{EXT_URI:ji,EXT_URI_NON_ADV:ji+"-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}]},NATIVE_RATIO_PRECISION:6};function qi(e,t){for(const i in e)e.hasOwnProperty(i)&&t(e[i],i)}function zi(e,t){for(const i in e)e.hasOwnProperty(i)&&("object"==typeof e[i]?zi(e[i],t):t(e[i],i,e))}function Wi(e){return null!=e&&!Number.isNaN(e)}function Ki(e,t){return Wi(t)?Wi(e)?Math.min(e,t):t:e}function Ji(e,t){return Wi(t)?Wi(e)?Math.max(e,t):t:e}function Yi(e){let t=0;return e.forEach((e=>t+=e)),t/=e.length,t}function Qi(e,t){let i=!1;for(let n=e.length;n-- >0;)t(e[n],n,e)&&(e.splice(n,1),i=!0);return i}function Zi(e){const t=[];for(const i in e)e.hasOwnProperty(i)&&t.push(e[i]);return t}function Xi(e){return!Object.keys(e).length}function en(e){return Object.keys(e)}function tn(e){const t={};return qi(e,((e,i)=>{t[i]=e})),t}function nn(e){let t;if(!e||"object"!=typeof e)return e;if(e instanceof Date)return t=new Date,t.setTime(e.getTime()),t;if(e instanceof Array){t=[];for(let i=0,n=e.length;i<n;i++)t[i]=nn(e[i]);return t}if(e instanceof Object)return t={},qi(e,(function(e,i){t[i]=nn(e)})),t;throw new Error("Unable to copy: "+tt(e))}function rn(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function sn(){const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+e()+"4"+e().substring(1)+"b"+e().substring(1)+e()+e()+e()}function an(e,t){let i;const n=typeof e;if(e===t)return!0;if(n!==typeof t||"object"!==n&&"function"!==n)return!1;if(null===e||null===t)return e===t;if(e instanceof Date&&t instanceof Date)return+e==+t;if(e instanceof Map&&t instanceof Map)return function(e,t){let i;if(e.size!==t.size)return!1;let n=!0;return e.forEach(((e,r)=>{i=t.get(r),(i!==e||void 0===i&&!t.has(r))&&(n=!1)})),n}(e,t);for(i in e)if(!(i in t)||!an(e[i],t[i]))return!1;for(i in t)if(!(i in e)||!an(e[i],t[i]))return!1;return!0}function on(e,t){if(-1===t.indexOf(e))throw{detail:`${e} mediaContent.contentType is not supported`,type:Gi.MEDIA_ERROR.incompatibleOffer}}function ln(e,t){e.forEach((e=>{if(""!==e&&-1!==t.findIndex((t=>t===e)))throw{detail:`Required feature '${e}' is not acceptable.`,type:Gi.MEDIA_ERROR.incompatibleOffer}}))}function cn(e,t,i,n=0){for(let r=1;r<e.length;r++)if(e[r-1]+n<t&&t<=e[r]+n)return i?e[r]:e[r-1];return e[0]}function dn(e,t,i){return t<=e&&e<=i}function un(e,...t){for(const i of t)if(i.hasOwnProperty(e))return i[e]}function hn(e,t){return e.filter((e=>!t.some((t=>t===e))))}function gn(e,t){if(e===t)return e;let i=0,n=0,r="";for(let s=0;s<e.length&&!(r.length>e.length-s);s++){let a=s;n-i>r.length&&(r=e.substring(i,n),s=n-1),i=s,n=s;for(let o=0;o<t.length;o++)a<e.length&&t[o]===e[a++]?n=a:(a=s,n-i>r.length&&(r=e.substring(i,n),s=n-1),i=s,n=s)}return r}function pn(e,t){const i=new Array(e.length+1);for(let n=0;n<e.length+1;n++){i[n]=new Array(t.length+1);for(let e=0;e<t.length+1;e++)i[n][e]=0}for(let t=1;t<e.length+1;t++)i[t][0]=t;for(let e=1;e<t.length+1;e++)i[0][e]=e;for(let n=1;n<e.length+1;n++)for(let r=1;r<t.length+1;r++){let s=1;e[n-1]===t[r-1]&&(s=0),i[n][r]=Math.min(i[n-1][r]+1,i[n][r-1]+1,i[n-1][r-1]+s)}return i[e.length][t.length]}function mn(e,t=3){return e&&parseFloat(e.toFixed(t))}function fn(e,t){if(!e)return"";if(e.length<3)return e;const i=[],n=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);n&&i.push(n[1]);try{if(t?.length){const n=new RegExp(`(${t.join("|")})`,"gi");let r=n.exec(e);for(;r;)i.push(r[1]),r=n.exec(e)}else i.push("no_keywords")}catch(e){i.push(`Error: ${tt(e)}`)}return 0===i.length?"unknown":i.join(" ")}function vn(e,t,i=0){return e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t),e}function Sn(e,t,i,n=0){vn(e,0===i?0:i-1,n),0!==i&&e.push(t)}function yn(e,t){const i={};for(const e in t)i[e]={get:t[e],configurable:!1,enumerable:!0};Object.defineProperties(e,i)}function Cn(e){return e?.length>0?e[e.length-1]:void 0}var Tn=globalThis?.performance?.now&&globalThis?.performance?.timeOrigin,En=Tn?()=>globalThis.performance.now():()=>Date.now(),bn=Tn?globalThis.performance.timeOrigin:0,_n=En,In=bn;function wn(e,t,i){if(e?.length>0){const n=[];for(const r of e){const e=nn(r);e[t]=e[t]&&e[t]-i,n.push(e)}return n}return e}function An(e,t,i){if(!e)return;const n={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]};for(const[r,s]of Object.entries(e))for(const e of s)Sn(n[r],e-t,i);return n}function Pn(e,t,i=!1){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e&&(!1===i||0!==e)));return n?.length?n.join(","):void 0}function Rn(e,t,i){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e)).splice(-i);return n?.length?n:void 0}function Mn(e,t){const i=[];for(const n of e.keys())t.has(n)||i.push(n);for(const t of i)e.delete(t)}function Dn(e){return"object"==typeof e?tt(e):e}function kn(e){const t=Object.keys(e).map(Number).sort(((e,t)=>e-t)),i=t.reduce(((t,i)=>t+(e[i]??0)),0);return{getPercentile:n=>{const r=i*n;let s=0;for(const i of t)if(s+=e[i],s>=r)return i}}}function On(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}function Nn(e){const t=e.toLowerCase(),i=t.indexOf('token_types="');if(-1===i)return[];const n=t.indexOf('"',i+13);if(-1===n)return[];const r=t.substring(i+13,n).trim();return""===r?[]:r.split(" ")}function Ln(e){return 16*Math.ceil(e/16)}function xn(e,t,i,n){return JSON.stringify(wn(vn(e,t),i,n))}var Fn=Z;function Un(e){return e.map((e=>new Bn(e.w,e.h,e.fps,e.minBr,e.maxBr)))}var Bn=class{constructor(e,t,i=0,n=0,r=0){this.width=e,this.height=t,this.fps=i,this.minBitrate=n,this.maxBitrate=r,this.fs=Math.ceil(e/Gi.MACROBLOCK_SIZE)*Math.ceil(t/Gi.MACROBLOCK_SIZE)}toString(){return this.height?`${this.height}p`:`${this.fs}fs`}},Vn=class e{constructor(e){e||(this.resolutions=Un(Gi.RES_TABLE.SEND)),this.resolutions=Un(e)}static initialize(t){e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride),t.on("configUpdated",(()=>{e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride)}))}get initialResolution(){return this.resolutions[this.resolutions.length-1]}getResolutionByFs(e){return this.getResolutionRecord(void 0,e)}getMaxFsForHeight(e){return this.getResolutionRecord(e).fs}getResolutionForBitrate(e){let t=this.resolutions.filter((t=>t.maxBitrate&&t.maxBitrate>=e)).shift(),i=this.resolutions.filter((t=>t.minBitrate&&t.minBitrate<=e)).pop();return t=t??i,i=i??t,{lowRes:t,highRes:i}}getBitrateForResolution(e,t){const i=this.getResolutionRecord(Math.min(e,t));return{minBitrate:i.minBitrate,maxBitrate:i.maxBitrate}}getResolutionRecord(t,i){if(this===e.Send){for(let e=this.resolutions.length-1;e>=0;e--){if(t&&this.resolutions[e].height<=t)return this.resolutions[e];if(i&&this.resolutions[e].fs<=i)return this.resolutions[e]}return this.resolutions[0]}for(const e of this.resolutions){if(t&&e.height>=t)return e;if(i&&e.fs>=i)return e}return this.resolutions[this.resolutions.length-1]}getNextLowerResolution(t,i){const n=Math.min(t,i),r=this.getResolutionRecord(n),s=this.resolutions.indexOf(r);return n===Math.min(r.width,r.height)||this===e.Recv?this.resolutions[s-1]:this.resolutions[s]}getNextHigherResolution(t,i){const n=Math.min(t,i),r=this.getResolutionRecord(n),s=this.resolutions.indexOf(r);return n===Math.min(r.width,r.height)?this.resolutions[s+1]:this===e.Recv?this.resolutions[s]:this.resolutions[s+1]}getResolutions(){return[...this.resolutions]}};Vn.Recv=new Vn(Gi.RES_TABLE.RECV),Vn.Send=new Vn(Gi.RES_TABLE.SEND);var Hn=Vn,$n=e=>Hn.Send.getResolutionByFs(e).height,jn=e=>Hn.Send.getMaxFsForHeight(e),Gn={numVideoChannelsGvc:({current:e,constraints:t})=>Wn(e,t),specCompliantSimulcast:({current:e,constraints:t})=>Jn(e,t),multiviewResolutionLimits:({current:e,constraints:t,logger:i})=>Kn(e,t,i),enableVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),allowRemoteVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),enableNonAdvVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),outgoingVideoLimit:({current:e,settings:t,constraints:i})=>Zn(e,t,i),webrtcCameraOpenFs:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Xn(e,t,i,n),webrtcVideoCapabilityMaxFS:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Xn(e,t,i,n)},qn=(e,t,i)=>({...zn(e,t,i),...zn(e,t,i,"1on1"),...zn(e,t,i,"Multiparty")}),zn=(e,t,i,n)=>{const r={};for(const s of Object.keys(Gn)){const a=`${s}${n??""}`;n&&!Wi(t[a])||(r[a]=Gn[s]({current:t[a],settings:t,constraints:i,settingsSuffix:n,logger:e}))}return r},Wn=(e,t)=>Ki(e,t.maxIncomingStreams),Kn=(e,t,i)=>{const n=t.maxParticipantResolutions;if(!n)return e;const r={more:e.more};if(Number.isInteger(n))Object.keys(e).forEach((t=>{r[t]=Ki(n,e[t])}));else{const t=Object.keys(n);if(!t.length)return i.warn(`ignoring invalid value provided for maxParticipantResolutions: ${n}}`),e;t.forEach((t=>{r[t]=Ki(n[t],e[t]||e.more)}))}return r},Jn=(e,t)=>void 0!==t.maxSimulcastLayers||e.allowOverride?{...e,video:Yn(e.video,t),sharing:Yn(e.sharing,t)}:e,Yn=(e,t)=>{const i=e?.layerScaleFactors?.filter((e=>e<=t.maxSimulcastLayers));return i?.length>1?{...e,layerScaleFactors:i}:{...e,enableLocally:!1,allowEnableRemotely:!1}},Qn=e=>Ki((0,Fn.isNumber)(e?.outgoingVideoLimit)?e?.outgoingVideoLimit:e?.outgoingVideoLimit?.maxResolution,e?.maxOutgoingResolution),Zn=(e,t,i)=>{const{outgoingVideoLimit:n}=i,r=(0,Fn.isNumber)(n),s=Qn(i);if(t.sendVideoCapabilityManager?.isEnabled){const s=e=>e?$n(e):e,a=(e,t,i,n)=>t?Ji(Ki(t,n),i):e,o=r?void 0:n?.maxFramerate,l=r?void 0:n?.maxBitrate,c=Qn(i);return{...e,maxResolution:a(e?.maxResolution,c,s(t.sendVideoCapabilityManager?.minFS),s(t.sendVideoCapabilityManager?.maxFS)),maxFramerate:a(e?.maxFramerate,o,t.sendVideoCapabilityManager?.minFPS,t.sendVideoCapabilityManager?.maxFPS),maxBitrate:a(e?.maxBitrate,l)}}let a=Ki(e?.maxResolution,s);if(s>0&&t.maxCameraFsViaCallConstraints>0){const e=$n(t.maxCameraFsViaCallConstraints);a=Ji(Ki(a,e),Ki(s,e))}const o=Ki(e?.maxBitrate,r?void 0:n?.maxBitrate),l=Ki(e?.maxFramerate,r?void 0:n?.maxFramerate);return{...e,maxResolution:a,maxBitrate:o,maxFramerate:l}},Xn=(e,t,i,n)=>{if(Qn(i)>0&&t.maxCameraFsViaCallConstraints>0){const r=`outgoingVideoLimit${n??""}`,{maxResolution:s}=Zn(t[r],t,i);return Ji(e,s?jn(s):e)}return e},er=(e,t,i,n)=>!((t.specCompliantSimulcast.constraintsDisableVla||t[`specCompliantSimulcast${n}`]?.constraintsDisableVla)&&i.maxSimulcastLayers<2)&&e,tr=class extends Vi{constructor(e){super(e),this.logger=e,this._constraints={},this._callConstraintsTelemetry=[]}get constraints(){return this._constraints}get callConstraintsTelemetry(){return this._callConstraintsTelemetry}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};this._callConstraintsTelemetry.push(i)}setConstraints(e){this.logger.debug("Setting new platform call constraints",JSON.stringify(e)),this._constraints=e,this.addCallConstraintsTelemetryEvent(e,"requested"),this.raiseChanged()}getSettings(e){return qn(this.logger,e,this._constraints)}},ir=Z,nr='"rtcmedia"';function rr(e){return{expires:e.expires,username:e.username,password:e.password,realm:e.realm}}var sr=class{constructor(e){this.version=e,this.reports={},this.version||(this.version=1)}watch(e){const t={time:Date.now(),duration:-1,version:this.version};return this.reports[e]&&(e=`${e}_last`),this.reports[e]=t,{end:e=>{e&&(t.error=e),t.duration=Date.now()-t.time}}}getReports(){return this.reports}};function ar(e){return{Service:e.Service,Relay:e.Relay,Token:e.Token}}var or="configFetch",lr="skypeTokenFetch",cr="trapTokenFetch",dr=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new sr,this.context=e,this.logger=e.logger.createChild("RM"),this.request=e.request,this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e)}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getAuthTokenStats(){}getStats(){return{config:ar(this.config),stats:this.timers.getReports()}}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",it(t)):this.logger.error("failed to retrieve relays",it(t)),null)));return t}refreshRelaysFromConfig(){this.request.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}updateRelaysAsync(){const e=this.config.Service.tokenUrl;let t;const i=this.context.trapTokenCredentialsProvider?async()=>(t=this.timers.watch(cr),this.context.trapTokenCredentialsProvider()):async()=>{const i=this.timers.watch(lr);let n="";try{n=await this.context.tokenProvider(),this.logger.info("fetching skypeToken")}catch(e){throw i.end(it(e)),e}return i.end(),t=this.timers.watch(cr),(await this.request.get(e,{headers:{"X-Skypetoken":n,"api-version":2}})).response};return this.logger.info("Fetch TRAP token "+(this.context.trapTokenCredentialsProvider?"with provider":"directly")),i().then((e=>{t.end();let i=0;const n=this.config.Token.earlyRefreshMinutes,r=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),i=Math.max(e.expires-60*n,e.expires*r/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*i);const s=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:nr,a=rr(this.getTrapToken(s)),o={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"},l={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"},c={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"},d={Skype:[{...o,...a}],Lync:[{...l,...a}],Turn:[{...c,...a}]};return this.logger.info("relays from trap",[o,l,c]),d})).catch((e=>{throw t&&t.end(it(e)),e}))}storeTrapTokens(e){if(!e?.tokens)return void this.logger.error("failed to get tokens from trap response");const t={};e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}})),this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch(or);try{const t=await this.context.configProvider();e.end(),this.logger.info("retrieved configuration:",t),(0,ir.isEmpty)(t)||(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",tt(t)),e.end(it(t))}}},ur=Z,hr=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new sr(2),this.context=e,this.authTokenFetcher=this.context.authTokenFetcher,this.logger=e.logger.createChild("RM2")}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e),this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setClientSupportsGenericTokenApi(e){this.authTokenFetcher.supportsGenericTokenApi=e}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getStats(){return{config:ar(this.config),stats:this.timers.getReports()}}getAuthTokenStats(){return this.context.authTokenFetcher.getStats()}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",it(t)):this.logger.error("failed to retrieve relays",it(t)),null)));return t}refreshRelaysFromConfig(){this.context.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}async updateRelaysAsync(){const e=this.context.configProvider?.config.useNewTokenApi?"aadTokenFetch":lr,t=this.timers.watch(e),i=be();this.logger.info(`${i}[RM2] Fetch TRAP token`);try{const e=await this.context.authTokenFetcher.fetchTrapToken(i,this.config);t.end();let n=0;const r=this.config.Token.earlyRefreshMinutes,s=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),n=Math.max(e.expires-60*r,e.expires*s/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*n);const a=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:nr,o=rr(this.getTrapToken(a)),l={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"},c={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"},d={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"},u={Skype:[{...l,...o}],Lync:[{...c,...o}],Turn:[{...d,...o}]};return this.logger.info("relays from trap",[l,c,d]),u}catch(e){throw this.logger.info(`Fetch TRAP token failed with error ${e}`),t&&t.end(it(e)),e}}storeTrapTokens(e){const t={};if(e?.tokens)e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}}));else{if(!e.realm)return void this.logger.error("failed to get tokens from trap response");t[e.realm]=e}this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch(or);try{const t=await this.context.relayConfigProvider();e.end(),this.logger.info("retrieved configuration:",t),(0,ur.isEmpty)(t)||(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",it(t)),e.end(it(t))}}},gr=class{constructor(e,t,i,n,r){this.signalingAgentProvider=t,this.request=i,this.tokenProviders=n,this.configProvider=r,this.errors=[],this.clientSupportsGenericTokenAPI=!1,this.logger=e.createChild("AuthTokenFetcher")}set supportsGenericTokenApi(e){this.clientSupportsGenericTokenAPI=e}buildHeaders(e,t){const i={"api-version":2};switch(this.configProvider?.config.useTokenMigrationHeader&&(i["X-MS-Migration"]="True"),e){case 4:case 8:return i.Authorization=`Bearer ${t}`,i;case 1:return i["X-Skypetoken"]=t,i;default:throw new Error(`TokenType ${e} is not supported`)}}serviceSupportedTokenTypes(e){let t=null;if(void 0===e)t=this.clientSupportedTokenTypes();else{const i=e?.toLowerCase();t=this.constructTokenType(i)}return null===t&&this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader&&(t|=1),t}extractWwwauthenticateHeaders(e){let t={};if(e){const i=On(e,"www-authenticate");i&&(t={authenticationHeaders:[i]})}return t}convertStringToTokenType(e){switch(e){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(e,t){if(!this.clientSupportsGenericTokenAPI)return 1;let i=null;const n=t?.authenticationHeaders;if(!n&&e)this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader?(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),i=1):(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),i=this.clientSupportedTokenTypes());else if(n||e){if(n&&e)for(const e of n){const t=Nn(e);if(this.configProvider?.config.supportMissingTokenTypesInResponse&&0===t.length)this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),i=this.clientSupportedTokenTypes();else for(const e of t){const t=this.convertStringToTokenType(e.toLowerCase());this.configProvider?.config.clientSupportsCaeToken&&8===t&&(i|=8),this.configProvider?.config.clientSupportsAadToken&&4===t&&(i|=4),this.configProvider?.config.clientSupportsSkypeToken&&1===t&&(i|=1)}}}else this.logger.info("[authTokenFetcher][getTokenTypeFromHeaders] retrying to fetch token woth client supported tokens"),i=this.clientSupportedTokenTypes();return i}constructTokenType(e){let t=null;return e.includes("aad")&&this.configProvider?.config.clientSupportsAadToken&&(t|=4),e.includes("cae")&&this.configProvider?.config.clientSupportsCaeToken&&(t|=8),e.includes("skype")&&this.configProvider?.config.clientSupportsSkypeToken&&(t|=1),t}getTokenMetadataForTrapService(e,t,i){const n={verb:"POST",path:e},r=JSON.stringify(n);let s=null;const a=this.extractWwwauthenticateHeaders(i),o=!!a?.authenticationHeaders;return s=i?this.getTokenTypeFromHeaders(o,a):this.serviceSupportedTokenTypes(t),this.logger.info(`[authTokenFetcher][getTokenMetadata] return token type=${s}, factoJson=${r}`),{tokenType:s,factorsJson:r,requestMetadataJson:a,isUnauthorized:o}}clientSupportedTokenTypes(){let e=null;return this.configProvider?.config.clientSupportsAadToken&&(e|=4),this.configProvider?.config.clientSupportsCaeToken&&(e|=8),this.configProvider?.config.clientSupportsSkypeToken&&(e|=1),e}async handleAuthTokenFailure(e,t,i,n){this.logger.info("[authTokenFetcher][handleAuthTokenFailure] failed to fetch token, retrying");try{const r=this.getTokenMetadataForTrapService(t,void 0,i);return this.logger.info(`[authTokenFetcher][handleAuthTokenFailure] token request options=${r}`),r.invalidToken=n,await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(e,!1,r)}catch(e){const t={status:e?.response?.status||e?.status,error:e,fatal:!0};this.errors.push(tt(t)),this.logger.error(`[authTokenFetcher] failed to fetch token trough new api with error: ${tt(t)}, quiting`)}}getRequestToken(e){const t=On(e,"X-Skypetoken");if(t)return t;const i=On(e,"Authorization");if(i){const e=i.split(" ");if(2===e.length)return e[1]}}async fetchTrapCredentials(e,t,i){const n=this.buildHeaders(t,e),r=await this.request.get(i,{headers:n});return r?.response}async fetchTrapTokenWithNewTokenApi(e,t,i){let n;this.logger.info(`${i}[authTokenFetcher] fetching token through fetchTrapTokenWithNewTokenApi`);const r=this.getTokenMetadataForTrapService(e,t);try{return n=await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(i,!1,r),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}catch(t){const r={status:t?.response?.status||t?.status,error:t,fatal:!1};this.errors.push(tt(r)),this.logger.error(`${i}[authTokenFetcher] fetchTrapTokenWithNewTokenApi failed with ${tt(r)}, retrying...`);const s=t?.response?.headers;if(s){const t=this.getRequestToken(s);return n=await this.handleAuthTokenFailure(i,e,s,t),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}throw t}}async fetchTrapTokenThroughProvider(){return this.logger.info("[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokenThroughProvider"),this.tokenProviders.trapTokenCredentialsProvider()}async fetchTrapTokensWithLegacyTokenFetcher(e,t){this.logger.info(`${t}[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokensWithLegacyTokenFetcher`);try{this.tokenTypeFetched=1;const t=await this.tokenProviders.skypeTokenProvider();return(await this.request.get(e,{headers:{"X-Skypetoken":t,"api-version":2}})).response}catch(e){throw this.errors.push(tt(e)),this.logger.error(`${t}[authTokenFetcher] fetchTrapTokensWithLegacyTokenFetcher failed with ${tt(e)}`),e}}getStats(){return{tokenType:this.tokenTypeFetched,errors:nt(this.errors,this.configProvider?.config.diagnostics.telemetryLimits.numAuthTokenErrors??100)}}async fetchTrapToken(e,t){let i;this.logger.info(`${e}[AuthTokenFetcher] Start fetching token`);const n=t.Service.tokenUrl,r=t.Service.supportedTokenTypes;return i=this.configProvider?.config.useNewTokenApi?this.fetchTrapTokenWithNewTokenApi(n,r,e):this.tokenProviders.trapTokenCredentialsProvider?this.fetchTrapTokenThroughProvider():this.fetchTrapTokensWithLegacyTokenFetcher(n,e),i}},pr=class{constructor(e,t,i,n){this.config=e,this.signalingAgentProvider=t,this.ecsProvider=i,this.logger=n}getOrCreateRelayManager(){return this.config.relayManager?this.config.relayManager:this.relayManager||this.createRelayManager()}setConfigProvider(e){this.configProvider=e}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(e,t,i,n,r,s){const a=e||new st(this.logger),o=this.ecsProvider.getEcsConfig("SkypeCalling","enableFetchApi"),l={get:(e,t)=>a.getAsync(e,{...a.getRequestOptions("GET",t?.headers,null,t?.timeout),useFetch:o}),isOnline:n.isOnline};if(this.configProvider?.config.useNewTokenApi){const e=new gr(this.logger,this.signalingAgentProvider,l,{skypeTokenProvider:t,trapTokenCredentialsProvider:r},s);return new hr({logger:this.logger,relayConfigProvider:()=>i.getRelayConfig(),isOnline:n.isOnline,authTokenFetcher:e,configProvider:s})}return function(e){return new dr(e)}({logger:this.logger,tokenProvider:t,trapTokenCredentialsProvider:r,configProvider:()=>i.getRelayConfig(),request:{get:(e,t)=>a.getAsync(e,{...a.getRequestOptions("GET",t?.headers,null,t?.timeout),useFetch:o}),isOnline:n.isOnline}})}},mr="*13",fr={totalParticipants:0,preheatedParticipants:0,lobbyParticipants:0,totalPresenters:0,requestingAttentionPresenters:0,totalAttendees:0,requestingAttentionAttendees:0,overflowAttendees:0},vr=Q,Sr=class{constructor(e,t,i,n,r){this.eventName=e,this.eventStartTime=t,this.type=i,this.causeId=n,this.status="Pending",this.eventStartTimestamp=(new Date).getTime(),this.data=[],this.causeId=n?.substring(0,8),"Event"===this.type&&delete this.status,r&&this.data.push(r)}set variant(e){this.eventVariant=e}recordSuccess(e,t){this.recordResult("Success",e,t)}recordFailure(e,t){this.recordResult("Failure",e,t)}recordTimeout(e,t){this.recordResult("Timeout",e,t)}addData(e){this.data.push(e)}isPending(){return"Pending"===this.status}getEvent(){const e={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((e=>this.prepareData(e,!0))).filter((e=>!!e))};return"Event"===this.type&&delete e.status,e.data.length||delete e.data,e.causeId||delete e.causeId,e.resultCauseId||delete e.resultCauseId,e.result||delete e.result,e.variant||delete e.variant,{[this.eventName]:e}}recordResult(e,t,i){this.status=e,this.result=this.prepareData(t),this.causeId!==i&&(this.resultCauseId=i),this.duration=(new Date).getTime()-this.eventStartTimestamp}prepareData(e,t=!1){if(null==e)return"";if("string"==typeof e)return De(e);if("number"==typeof e||"boolean"==typeof e)return String(e);if("function"==typeof e)return"";if(e instanceof Error)return e.toString();try{return Object.keys(e).length?t?e:$e(e):""}catch(e){return"invalid"}}},yr=class{constructor(e,t,i,n){this.logger=e,this.startTime=t,this.maxEventsExceeded=i,this.perfModule=n,this.recordedEvents=[],this.ipcStats=[],this.ongoingOperations={}}recordEvent(e,t,i=be()){this.logger.debug("Event:",e,vr.pii.Omit(t));const n=new Sr(e,this.getEventStartTime(),"Event",i,t);return this.pushToRecordedEvents(n),n}recordOperationSuccess(e,t=null,i,n,r){this.logger.info("Event success:",n,e,vr.pii.Omit(i),vr.pii.Omit(t)),this.recordOperationResult(e,t,"Success",i,n,r)}recordOperationFailure(e,t,i,n,r){this.logger.info("Event failure:",e,vr.pii.Omit(i),t),this.recordOperationResult(e,t,"Failure",i,n,r)}recordOperationTimeout(e,t,i,n,r){this.logger.info("Event timeout:",e,vr.pii.Omit(i),t),this.recordOperationResult(e,t,"Timeout",i,n,r)}maybeRecordOperationSuccess(e,t=null,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationSuccess(e,t,i,n,r)}maybeRecordOperationFailure(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationFailure(e,t,i,n,r)}maybeRecordOperationTimeout(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationTimeout(e,t,i,n,r)}recordOperationResult(e,t,i,n,r,s){this.hasOngoingEvent(e,n)||this.recordOperation(e,r,n);let a=this.ongoingOperations[e];switch(n&&(a=a[n]),s&&a.addData(s),i){case"Success":a.recordSuccess(t,r);break;case"Failure":a.recordFailure(t,r);break;case"Timeout":a.recordTimeout(t,r);break;default:this.logger.error("Unknown operation record state in record operation result.")}n?delete this.ongoingOperations[e][n]:delete this.ongoingOperations[e]}recordOperation(e,t,i,n){this.logger.debug("Event create:",t,e,vr.pii.Omit(i),n);const r=new Sr(e,this.getEventStartTime(),"Operation",t,n);return this.ongoingOperations[e]||(this.ongoingOperations[e]={}),i?this.ongoingOperations[e][i]=r:this.ongoingOperations[e]=r,this.pushToRecordedEvents(r),r}setOperationVariant(e,t,i){let n;n=i?this.ongoingOperations[e][i]:this.ongoingOperations[e],n?n.variant=t:this.logger.error(`Could not find operation ${e} to set variant ${t}`)}updateOperationData(e,t,i,n){try{if(!this.ongoingOperations[e])return void this.recordEvent(e,t,i);n?this.ongoingOperations[e][n]&&this.ongoingOperations[e][n].addData(t):this.ongoingOperations[e].addData(t)}catch(t){return void this.logger.info(`Unable to update operation: ${e} data`)}}pushToRecordedEvents(e){if(this.maxEventsExceeded&&this.maxEventsExceeded()&&this.recordedEvents.shift(),this.recordedEvents.push(e),this.perfModule&&this.ipcStats.length<=30){const e=this.perfModule.getIpcStats();e&&this.ipcStats.push({ingestionTime:this.getEventStartTime(),stats:e})}}hasOngoingEvent(e,t){return this.ongoingOperations[e]?!(t&&!this.ongoingOperations[e][t]&&(this.logger.warn(`Unable to find event for name\\id ${e}\\${vr.pii.Omit(t)}`),1)):(this.logger.warn(`Unable to find event for name ${e}`),!1)}getEventStartTime(){return(new Date).getTime()-this.startTime}getEventTimestampBag(e,t){const i=t?[t.getEvent()]:this.recordedEvents.filter((t=>!e||!t.isPending())).map((e=>e.getEvent())),n=JSON.stringify({eventStart:this.startTime,events:i});return this.logger.info(`Call eventTimestampBag ${vr.pii.Omit(n)}`),n}getIPCStats(){return 0!==this.ipcStats.length?JSON.stringify(this.ipcStats):""}removeRecordedEvent(e){const t=this.recordedEvents.indexOf(e);t>-1&&this.recordedEvents.splice(t,1)}},Cr=class extends yr{constructor(e,t){super(e,t,(()=>this.recordedEvents.length>150)),this.getHostName=()=>{try{return"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>"}catch(e){return"unknown"}},this.tsCallingVersion="2025.07.01.15",this.logger=e.createChild("CallRegistryTelemetry")}setClientType(e){this.clientType=e}setEndpointId(e){this.endpointId=e}setSkypeId(e){this.skypeId=De(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}getEvent(e,t){const i=e=>void 0===e?"":e;return{EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),userHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),TsCallingVersion:i(this.tsCallingVersion),HostName:this.getHostName(),EventTimestampBag:this.getEventTimestampBag(e,t),DiagnosticInfo:this.callEndDiagnosticInfo,ClientType:i(this.clientType)}}removeNonPendingOperations(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending()))}},Tr=class extends yr{constructor(e,t,i){super(e,t,(()=>this.inCallMode&&this.recordedEvents.length>150),i),this.inCallMode=!1,this.tsCallingVersion="2025.07.01.15",this.logger=e.createChild("CallTelemetry")}setClientType(e){this.clientType=e}setCallId(e){this.currentCallId&&(this.previousCallId=this.currentCallId),this.currentCallId=e}setConsultativeCallId(e){this.consultativeCallId=e}setEndpointId(e){this.endpointId=e}setParticipantId(e){this.participantId=e}setDisplayName(e){this.displayName=e}setPreheatFlags(e){this.preheatFlags=e}setCallOrigin(e){this.origin=e}setGroupId(e){this.groupId=e}setThreadId(e){this.threadId=e}setBackroomThreadId(e){this.backroomThreadId=e}setStreamThreadId(e){this.streamThreadId=e}setLobbyThreadId(e){this.lobbyThreadId=e}setComplianceRecordingContentLength(e){this.complianceRecordingContentLength=e}setConversationStartTime(e){this.conversationStartTime=e}setCompositionServiceState(e){this.compositionServiceState=e}setMessageId(e){this.messageId=e}setSkypeId(e){this.skypeId=De(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}setFailureType(e){this.failureType=e}setIsCast(e){this.isCast=e?"True":"False"}setIsHuddleGroupCall(e){this.isHuddleGroupCall=e?"True":"False"}setIsEmergency(e){this.isEmergency=e?"True":"False"}setRole(e){this.isAnonymous="admin"===e?"False":"True"}setCallType(e){this.callType=e}setConversationType(e){this.conversationType=e}setDirection(e){this.direction=e}setSelfParticipantRole(e){this.selfParticipantRole=e}setTerminationState(e){this.terminationState=e}setTerminationReason(e){this.terminationReason=e}setCallEndDiagnosticInfo(e){this.callEndDiagnosticInfo=e}setStackConfig(e){this.stackConfig=e}setJoinedFrom(e){this.joinedFrom=e}setMeetingCode(e){this.meetingCode=e}setMeetingUrl(e){this.meetingUrl=e}setHasMeetingRegistrationId(e){this.hasMeetingRegistrationId=e?"True":"False"}setHasParticipantPin(e){this.hasParticipantPin=e?"True":"False"}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.currentCallId),PreviousCorrelationId:i(this.previousCallId),ConsultativeCallId:i(this.consultativeCallId),EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ParticipantId:i(this.participantId),DisplayName:new Re(this.displayName??"",1),PreheatFlags:i(this.preheatFlags),CallType:i(this.callType),ConversationType:i(this.conversationType),Direction:i(this.direction),Origin:i(this.origin),SelfParticipantRole:i(this.selfParticipantRole),IsAnonymous:i(this.isAnonymous),GroupId:De(i(this.groupId)),ThreadId:xe(i(this.threadId)),MessageId:i(this.messageId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),UserHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),FailureType:i(this.failureType),IsCast:i(this.isCast),IsHuddleGroupCall:i(this.isHuddleGroupCall),IsEmergency:i(this.isEmergency),TsCallingVersion:i(this.tsCallingVersion),TerminationState:i(this.terminationState),TerminationReason:i(this.terminationReason),StackConfig:i(this.stackConfig),EventTimestampBag:this.getEventTimestampBag(e,t),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:i(this.complianceRecordingContentLength),ConversationStartTime:i(this.conversationStartTime),BackroomThreadId:xe(i(this.backroomThreadId)),StreamThreadId:xe(i(this.streamThreadId)),LobbyThreadId:xe(i(this.lobbyThreadId)),ClientType:i(this.clientType),CompositionServiceState:i(this.compositionServiceState)}}getShortEvent(){const e=e=>void 0===e?"":e;return{CorrelationId:e(this.currentCallId),EndpointId:e(this.endpointId),ParticipantId:e(this.participantId),DisplayName:new Re(this.displayName??"",1),CallType:e(this.callType),ConversationType:e(this.conversationType),Direction:e(this.direction),Origin:e(this.origin),SelfParticipantRole:e(this.selfParticipantRole),IsAnonymous:e(this.isAnonymous),ThreadId:xe(e(this.threadId)),ApplicationType:e(this.applicationType),Ring:e(this.ring),TenantId:e(this.tenantId),UserHexCID:e(this.userHexCID),AcsResourceId:e(this.acsResourceId),Region:e(this.region),TsCallingVersion:e(this.tsCallingVersion),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,ClientType:e(this.clientType)}}switchToInCallTelemetry(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending())),this.inCallMode=!0}getHostName(){try{return location.host}catch(e){return"unknown"}}},Er=e=>Array.isArray(e)?e.map((e=>({endpointId:e.endpointId,participantId:e.participantId}))):null;function br(e,t,i){if(!e)return i.info(`sanitizeMeetingCode[${t}] empty / undefined meeting code parameter`),e;let n=e.replace(/\s/g,"");return n=n.replace(/-/g,""),i.info(`sanitizeMeetingCode[${t}] meetingCode: ${e}, sanitizedMeetingCode: ${n}`),n}function _r(e,t,i){if(!e)return i.info(`getMeetingCodeFromMeetingUrl[${t}] empty / undefined meeting Url parameter`),e;const n=new URL(e);let r="";if(n&&n.pathname&&n.pathname.split("/").length>=2){const e=n.pathname.split("/");"meet"===e[e.length-2]&&(r=e[e.length-1])}return i.info(`getMeetingCodeFromMeetingUrl[${t}] meetingUrl: ${e}, meetingUrlObject: ${Ge(n)}, meetingCode: ${r}`),r}function Ir(e,t,i,n){const r=br(e&&e.meetingCode||"",i,n),s=br(t&&t.meetingCode||"",i,n),a=(e,t)=>!!e&&!!t&&e===t;if(a(r,s))return!0;let o=_r(e&&e.meetingUrl||"",i,n);o=br(o,i,n);let l=_r(t&&t.meetingUrl||"",i,n);if(l=br(l,i,n),a(o,l))return!0;if(a(o,s)||a(l,r))return!0;if(e&&e.meetingUrl&&t&&t.meetingUrl){const i=new URL(e.meetingUrl),n=new URL(t.meetingUrl);if(i.hostname===n.hostname&&i.pathname===n.pathname)return!0}return!1}function wr(){}var Ar=0,Pr=410,Rr=499,Mr=497,Dr=3e3,kr=3548,Or=3757,Nr=4990,Lr=5028,xr=4521,Fr=3545,Ur=4294967294,Br="_operationIdValue_",Vr="_causeIdValue_",Hr="_callStartOptionsValue_",$r="_clientReasonValue_",jr="_guidIdValue_";function Gr(e,t){return Qr(0,e,t)}function qr(e,t){return Qr(1,e,t)}var zr=(e,t,i)=>{if(e[t][Br])throw new Error("can not specify more than one operation id");e[t][Br]=i},Wr=(e,t,i)=>{if(e[t][Vr])throw new Error("can not specify more than one cause id");e[t][Vr]=i},Kr=(e,t,i)=>{if(e[t][Hr])throw new Error("can not specify options more than once");e[t][Hr]=i},Jr=(e,t,i)=>{if(e[t][$r])throw new Error("can not specify reason more than once");e[t][$r]=i},Yr=(e,t,i)=>{if(e[t][jr])throw new Error("can not specify more than one guid");e[t][jr]=i},Qr=(e,t,i)=>(n,r,s)=>{const a=s.value,o=n[r]?.[Br],l=n[r]?.[Vr],c=n[r]?.[jr],d=n[r]?.[Hr],u=n[r]?.[$r],h=i?.type||"Async";return s.value=function(...n){const r=this;let s=be();void 0!==l&&(n[l]&&(_e(n[l])||fi(n[l]))?s=n[l]:n[l]=s);let g,p=void 0!==o?n[o]:void 0;if(void 0!==p)if(Array.isArray(p))try{const e=p.map((e=>e.toString())).sort().concat().toString();p=function(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}(e).toString()}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`[${p}]${t} failed in array parsing in operationDecorator`};return Promise.reject(e)}else if(p&&"object"==typeof p)try{let e=JSON.stringify(p);i&&i.operationIdKey&&p.hasOwnProperty(i.operationIdKey)&&(e=p[i.operationIdKey]),p=e}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`[${p}]${t} failed in object parsing in operationDecorator`};return Promise.reject(e)}void 0!==u&&n[u]&&(g=n[u]);const m=Zr(r,e);if(m.logOperation(s,t),i&&i.singular&&m.hasPendingOperation(t))return m.logOperation(s,t,"Not allowed, pending operation exists"),Promise.reject(60);if(i&&i.idempotencyLevel&&m.getRecord(t)>0)switch(m.logOperation(s,t,`Called multiple times, handling operation according to specified policy: idempotency=${i.idempotencyLevel}`),i.idempotencyLevel){case"NoOp":return Promise.resolve();case"Error":return Promise.reject(60)}try{void 0!==d&&n[d]&&r.processCallStartOptions(n[d],s)}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`${t} failed in processCallStartOptions`};return Promise.reject(e)}if(void 0!==c&&n[c]&&_e(n[c])&&!fi(n[c])){let e=mi();e=e.replace(e.substring(0,8),n[c]),n[c]=e}const f=!(!i||!i.convertError),v=()=>"Chained"===h?m.executeChained(a.bind(this,...n),t,p,s,f,g,i):"Sync"===h?m.executeSync(a.bind(this,...n),t,p,s,f,g):m.execute(a.bind(this,...n),t,p,s,f,g,i);if("StartCall"!==t&&"JoinCall"!==t||m.hasPendingOperation("_CallStartOrJoinInitiated")||m.createPendingOperation("_CallStartOrJoinInitiated").catch(wr),i&&i.triggerAttach&&(m.hasPendingOperation("_ElectronSlimcoreReady")||m.createPendingOperation("_ElectronSlimcoreReady").catch(wr)),i&&"Sync"!==i.type){const e=i&&i.waitFor;if(Array.isArray(e))return Promise.all(e.map((e=>e&&m.hasPendingOperation(e)&&m.waitForOperation(e,void 0,s)))).then(v,v);if(e&&m.hasPendingOperation(e))return m.waitForOperation(e,void 0,s).then(v,v)}return v()},s},Zr=(e,t)=>{if(0===t)return e._callOperationHandler;if(1===t)return e._participantOperationHandler;throw new Error("Unsupported operation handler type!")},Xr=class{constructor(e){this._disposed=!1,this._logger=e.createChild("[ASYNC]"),this._endOperationDeferred=new Kt,this._endOperationDeferred.promise.catch((e=>{this._logger.info("Rejected all operations")})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._deferredOperationsWithCauseId={},this._logger=e}registerPromise(e,t){let i=!1;const n=()=>{i=!0};t.then(n,n);const r=this._endOperationDeferred.promise.catch((t=>{if(!i)throw new Error(`Operation ${e} did not complete, reason:${t}`)}));return Promise.race([r,t])}updateOperationId(e,t){this._logger.info(`updateOperationId ${e} ${t}`),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{i&&this._deferredOperationsWithOperationId[i]&&(this._logger.info(`_deferredOperationsWithOperationId ${i}`),Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{n&&this._deferredOperationsWithOperationId[i][n]&&(this._logger.info(`_deferredOperationsWithOperationId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))})),Object.keys(this._deferredOperationsWithCauseId).forEach((i=>{i&&this._deferredOperationsWithCauseId[i]&&(this._logger.info(`_deferredOperationsWithCauseId ${i}`),Object.keys(this._deferredOperationsWithCauseId[i]).forEach((n=>{n&&this._deferredOperationsWithCauseId[i][n]&&(this._logger.info(`_deferredOperationsWithCauseId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))}))}createPendingOperation(e,t,i=be(),n={}){const r=new Kt;r.promise.catch(wr);const s=this.getOperationInfoForLogging(i,e,t);let a;if(this._logger.info(`${s}[creating...]`),this._disposed)return this._logger.info(`${s}[create failed, call is disposed]`),Promise.reject(60);if(t){if(this._deferredOperationsWithOperationId[e]||(this._deferredOperationsWithOperationId[e]={}),this._deferredOperationsWithOperationId[e][t])return this._logger.warn(`${s} Deferred operation with given name and operation id is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}/${De(t)}`));this._deferredOperationsWithOperationId[e][t]={deferred:r,causeId:i},this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][t]={deferred:r,options:n,operationName:e},a=this._endOperationDeferred.promise.catch((i=>{if(this.hasPendingOperationWithOperationId(e,t))throw new Error(`Operation ${e} ${t} did not complete, reason:${i}`)}))}else{if(this._deferredOperations[e])return this._logger.warn(`${s} Deferred operation with given name is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}`));this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][""]={deferred:r,options:n,operationName:e},this._deferredOperations[e]={deferred:r,causeId:i},a=this._endOperationDeferred.promise.catch((t=>{if(this.hasPendingOperation(e))throw new Error(`Operation ${e} did not complete, reason:${t}`)}))}return Promise.race([a,r.promise])}hasPendingOperation(e){return!!this._deferredOperations[e]}hasAtleastOneOfPendingOperation(e){for(const t of e)if(this.hasPendingOperation(t))return!0;return!1}hasPendingOperationWithOperationId(e,t){return!(!t||!this._deferredOperationsWithOperationId[e]||!this._deferredOperationsWithOperationId[e][t])}hasPendingOperationWithCauseId(e,t){const i=t||"";return this._deferredOperationsWithCauseId[e]&&!!this._deferredOperationsWithCauseId[e][i]}getPendingOperationWithCauseId(e,t){return this.hasPendingOperationWithCauseId(e,t)?this._deferredOperationsWithCauseId[e][t].deferred.promise:Promise.reject(`[${e}][${t}]: getPendingOperationWithCauseId for given causeId, operationId`)}resolveOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return t.deferred.resolve(i),this._logger.info(`[${e}][${n}] resolved, result=${je(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] resolveOperationWithCauseId failed, operation not found`)}rejectOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return r.catch(wr),t.deferred.reject(i),this._logger.info(`[${e}][${n}] rejected, result=${je(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] rejectOperationWithCauseId failed, operation not found`)}maybeResolveOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.resolveOperationWithCauseId(e,t,i).catch((t=>{this._logger.info(`${e}maybeResolveOperationWithCauseId failed, reason=${je(t)}`)})):this._logger.info(`${e}maybeResolveOperationWithCauseId ignored, operation does not exist`)}maybeRejectOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.rejectOperationWithCauseId(e,t,i).catch(wr):this._logger.info(`${e}maybeRejectOperationWithCauseId ignored, operation does not exist`)}getPendingOperation(e,t,i=be()){return!t&&this._deferredOperations[e]?this._deferredOperations[e].deferred.promise:t&&this._deferredOperationsWithOperationId[e]&&this._deferredOperationsWithOperationId[e][t]?this._deferredOperationsWithOperationId[e][t].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}: Deferred operation with given name and operation does not exist`)}waitForOperation(e,t,i=be()){return t&&this.hasPendingOperationWithOperationId(e,t)?this._deferredOperationsWithOperationId[e][t].deferred.promise:this.hasPendingOperation(e)?this._deferredOperations[e].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}failed=wait failed, operation not found`)}resolveOperation(e,t,i,n=be(),r=!1){if(!e)return Promise.reject("Unable to resolve deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],s=n.deferred.promise;return n.deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${je(t)||"void"}`),r||delete this._deferredOperationsWithOperationId[e][i],s}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],s=this._deferredOperations[e].deferred.promise;return this._deferredOperations[e].deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${je(t)||"void"}`),r||delete this._deferredOperations[e],s}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=resolve failed, operation not found`)}rejectOperation(e,t,i,n=be()){if(!e)return Promise.reject("Unable to reject deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],r=n.deferred.promise;return r.catch(wr),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${je(t)||"void"}`),delete this._deferredOperationsWithOperationId[e][i],r}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],r=n.deferred.promise;return r.catch(wr),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${je(t)||"void"}`),delete this._deferredOperations[e],r}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=reject failed, operation not found`)}maybeResolveOperation(e,t,i,n=be()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.resolveOperation(e,t,i,n).catch((e=>{this._logger.info(`${r}maybeResolveOperation failed, reason=${je(e)}`)})):this._logger.info(`${r}maybeResolveOperation ignored, operation does not exist`)}maybeResolveOperations(e,t,i,n=be()){for(const r of e)this.maybeResolveOperation(r,t,i,n)}maybeRejectOperation(e,t,i,n=be()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.rejectOperation(e,t,i,n).catch(wr):this._logger.info(`${r}maybeRejectOperation ignored, operation does not exist`)}maybeRejectOperations(e,t,i,n=be()){for(const r of e)this.maybeRejectOperation(r,t,i,n)}rejectPendingOperations(e,t=be()){this._disposed=!0,this._logger.info(`[${t}]rejectPendingOperations=${JSON.stringify(e)}`),Object.keys(this._deferredOperations).forEach((i=>{this.maybeRejectOperation(i,e,void 0,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][""]})),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{this.maybeRejectOperation(i,e,n,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][n]}))})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._endOperationDeferred.reject(e)}maybeRejectPendingOperationsWithPredicate(e,t=be(),i){this._logger.info(`[${t}]rejectPendingOperationsWithPredicate`),Object.keys(this._deferredOperationsWithCauseId).forEach((t=>{Object.keys(this._deferredOperationsWithCauseId[t]).forEach((n=>{const r=this._deferredOperationsWithCauseId[t][n];r&&i(r.operationName,r.options)&&(this.maybeRejectOperation(r.operationName,e,n),this.maybeRejectOperationWithCauseId(t,n,e))}))}))}getOperationInfoForLogging(e,t,i=""){const n=i?`[${De(i)}]`:"";return`[${e.substring(0,8)}][${t}]${n}`}},es=Z,ts=class{constructor(e){this._logger=e,this._promise=Promise.resolve(void 0),this._actionQueue=[]}chainPromise(e,t,i=be(),n=!1){const r=Date.now(),s=(("function"==typeof t?t():t)||"").toString();this._actionQueue.push(s),this._logger.info(`[${i}][${s}]enqueueing, queue=[${this._actionQueue}], reset=${n}`);const a=()=>{this._actionQueue=this._actionQueue.filter((e=>e!==s))};return n&&this.reset(i),this._promise=this._promise.catch(es.noop).then((()=>{const t=Date.now()-r;return this._logger.info(`[${i}][${s}]begin, delayMs=${t}`),e()})),this._promise.then((()=>{a();const e=Date.now()-r;this._logger.info(`[${i}][${s}]success, durationMs=${e}`)}),(e=>{a();const t=Date.now()-r;this._logger.warn(`[${i}][${s}]failed=${Ge(e)}, durationMs=${t}`)})),this._promise}reset(e){this._logger.info(`[${e}] resetting`),this._promise=Promise.resolve(void 0)}};function is(e){return!!e?.code}function ns(e,t){let i;return i=is(e)?e:{code:499,subCode:void 0!==t?t:0,phrase:"string"==typeof e?e:je(e)},i}var rs=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 e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}get startTime(){return this._startTime}};function ss(){return new rs}var as=class extends Xr{constructor(e,t,i,n,r){super(e),this.callTelemetry=t,this._ecsConfig=i,this._publishCallback=n,this._preconditionFunction=r,this._record={},this.logSuccess=(e,t,i)=>{this._logger.info(`${e} execution succeeded, result=${t?je(t):"void"}, time=${i.duration()}`)},this.logFailure=(e,t,i)=>{this._logger.info(`${e} execution failed, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.logTimeout=(e,t,i)=>{this._logger.info(`${e} execution timed out, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.stringifyForLogging=e=>{let t;if(e instanceof Error)t=e.toString()||"Unknown Error";else try{t=JSON.stringify(e)}catch(e){t="Unable to stringify data"}return t},this.convertToTransactionEndIfErrorOrString=(e,t,i)=>{if(this._logger.info(`ecsEnableErrorConversion in operationHandler is: ${this._ecsConfig&&this._ecsConfig.enableErrorConversion}`),t&&this._ecsConfig&&this._ecsConfig.enableErrorConversion&&("string"==typeof e||e instanceof Error)){const t=ns(e);return this._logger.info(`${i} Error converted from ${e} to ${je(t)}`),t}return e},this._logger=e.createChild("[Operation]"),this._chainedPromise=new ts(this._logger.createChild("[Chained]"))}resetOperationChain(e){this._chainedPromise.reset(e)}executeSync(e,t,i,n=be(),r,s){const a=this.getOperationInfoForLogging(n,t,i),o=ss();this._logger.info(`${a}API calledSync`);const l=this.callTelemetry.recordOperation(t,n,i,s);let c;try{this._setRecord(t),c=e(),l.recordSuccess(c,n),this.logSuccess(a,c,o)}catch(e){const t=this.convertToTransactionEndIfErrorOrString(e,r,a);l.recordFailure(t,n),this.logFailure(a,t,o)}return c}async executeChained(e,t,i,n=be(),r,s,a){return this.checkPendingOperationAndExecute(e,!0,t,i,n,r,s,a)}async execute(e,t,i,n=be(),r,s,a){return this.checkPendingOperationAndExecute(e,!1,t,i,n,r,s,a)}logOperation(e,t,...i){const n=i.length&&i.map((e=>this.stringifyForLogging(De(e))));this._logger.info(`[${e.substring(0,8)}][${t}]API called, ${n?`with args=${n}`:""}`)}rejectPendingOperations(e,t=be(),i){if(i){for(const e of Object.keys(this._deferredOperations))this.callTelemetry.maybeRecordOperationFailure(e,i,void 0,t);for(const e of Object.keys(this._deferredOperationsWithOperationId))for(const n of Object.keys(this._deferredOperationsWithOperationId[e]))this.callTelemetry.maybeRecordOperationFailure(e,i,n,t)}super.rejectPendingOperations(e,t)}maybeRejectOperations(e,t,i,n=be(),r){if(r)for(const t of e)this.callTelemetry.maybeRecordOperationFailure(t,r,void 0,n);super.maybeRejectOperations(e,t,i,n)}checkPendingOperationAndExecute(e,t,i,n,r=be(),s,a,o){const l=this.getOperationInfoForLogging(r,i,n);let c=null,d=null;return this.hasPendingOperationWithOperationId(i,n)||this.hasPendingOperation(i)?(this._logger.info(`${l}already pending, returning existing operation`),c=this.waitForOperation(i,n,r)):d=this.createPendingOperation(i,n,r,o),t?(this._logger.info(`${l}chained`),this._chainedPromise.chainPromise((()=>c||this.executeInternal(d,r,e,i,n,s,a,o)),i,r)):c||this.executeInternal(d,r,e,i,n,s,a,o)}_setRecord(e){this._record.hasOwnProperty(e)||(this._record[e]=0),this._record[e]+=1}getRecord(e){return this._record[e]}_recordTelemetryTimeoutAndPublish(e,t,i,n,r,s,a){const o=e||60;return window.setTimeout((()=>{if(!this._publishCallback)return void this._logger.warn(`${r} is marked to publish telemetry but no publish callback is defined.`);if(!this.hasPendingOperationWithOperationId(n,a)&&!this.hasPendingOperation(n))return;const e=new Error(`${r} execution did not complete before telemetry timeout of ${o}s.`);this.logTimeout(r,e,s),this.callTelemetry.maybeRecordOperationTimeout(n,e,a,i),this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)}),1e3*o)}_instantTelemetryPublish(e,t){this._publishCallback?(this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)):this._logger.warn(`${e} is marked to publish telemetry but no publish callback is defined.`)}parseInstantTelemetryParameters(e){let t,i=!1;return e&&(i=e.enableInstantTelemetry,t=e.telemetryTimeout),[i,t]}async executeInternal(e,t,i,n,r,s,a,o){const l=this.getOperationInfoForLogging(t,n,r);this._logger.info(`${l} executing operation...`);const c=ss(),d=this.callTelemetry.recordOperation(n,t,r,a),[u,h]=this.parseInstantTelemetryParameters(o);try{let e;this._setRecord(n),u&&(e=this._recordTelemetryTimeoutAndPublish(h,d,t,n,l,c,r)),o?.preconditionTags?.length&&this._preconditionFunction&&this._preconditionFunction(n,o.preconditionTags);const s=await i();e&&clearTimeout(e),this.callTelemetry.maybeRecordOperationSuccess(n,s,r),this.logSuccess(l,s,c),this.maybeResolveOperation(n,s,r,t)}catch(e){const i=this.convertToTransactionEndIfErrorOrString(e,s,l);this.callTelemetry.maybeRecordOperationFailure(n,function(e){return function(e){return!!e?.terminatedReasonCode}(e)?{code:e.terminatedReasonCode,subCode:e.terminatedReasonSubCode,phrase:e.errorMessage}:e}(i),r),this.logFailure(l,i,c),this.maybeRejectOperation(n,i,r,t)}return u&&this._instantTelemetryPublish(l,d),e}getEcsConfig(){return this._ecsConfig}},os=487,ls=603,cs=480,ds=403,us=412,hs=0,gs=302,ps=400,ms=404,fs=406,vs=408,Ss=409,ys=410,Cs=413,Ts=450,Es=451,bs=452,_s=470,Is=481,ws=488,As=490,Ps=491,Rs=495,Ms=496,Ds=497,ks=498,Os=500,Ns=580,Ls=3109,xs={[hs]:1,[os]:12,[ls]:10,[cs]:2,[vs]:6,[Ts]:30,[gs]:75,[ms]:24,[Is]:46,[fs]:5,[ps]:5,[ys]:4,[Cs]:59,[Ns]:4,[As]:3,[Ms]:31,[ks]:25,[Es]:27,[bs]:28,[Rs]:29,[Os]:7,[Ss]:7,[Ps]:7,[_s]:7,[ws]:26,[Ds]:32,[ds]:8,[us]:65},Fs={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},Us={500:39,403:41,404:42,480:40},Bs={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},Vs={SHARED_LINE_CALL_RECORD:121,SHARED_LINE_V2_CALL_RECORD:123,MEETING_STARTED_NOTIFICATION:128},Hs={LOG_UPLOAD_EVENT:120},$s="CallEndReasonLocalUserInitiated",js="CallEndReasonRedirected",Gs=(e=>(e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.CallStart="CallStart",e.WaitForAnswer="WaitForAnswer",e.WaitForConnect="WaitForConnect",e.Accept="Accept",e))(Gs||{}),qs=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.UpdateMediaModalities="UpdateMediaModalities",e.CreateOffer="CreateOffer",e.CreateAnswer="CreateAnswer",e.ProcessAnswer="ProcessAnswer",e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.MuteUnmute="MuteUnmute",e.MuteUnmuteSpeakers="MuteUnmuteSpeakers",e.StartVideoSafe="StartVideoSafe",e.CompleteNegotiation="CompleteNegotiation",e.MuteInput="MuteInput",e.MuteOutput="MuteOutput",e.UnmuteInput="UnmuteInput",e.UnmuteOutput="UnmuteOutput",e.evaluateEndpointStatesForAccept="evaluateEndpointStatesForAccept",e.handleEndpointStatesForAccept="handleEndpointStatesForAccept",e))(qs||{}),zs=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.ProcessOffer="ProcessOffer",e.ProcessOfferedModalities="ProcessOfferedModalities",e.TrySendingProvisionalAnswer="TrySendingProvisionalAnswer",e))(zs||{}),Ws=Z,Ks=p(Z),Js=p(Z),Ys=p(ce()),Qs="Success",Zs="ExpectedError",Xs="UnexpectedClientError",ea={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:[Xs]},CALL_END_TOKEN_TIMEOUT_ERROR:{code:499,subCode:3119,phrase:"CallEndReasonTokenFetchTimeout",resultCategories:[Xs]},CALL_END_UNSUPPORTED_TOKEN_ERROR:{code:499,subCode:3126,phrase:"CallEndReasonUnsupportedTokenError",resultCategories:[Xs]},CALL_END_TOKEN_ERROR:{code:499,subCode:3127,phrase:"CallEndReasonTokenFetchError",resultCategories:[Xs]},CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED:{code:499,subCode:3128,phrase:"CallEndReasonTokenTimeoutInterActvityRequired",resultCategories:[Xs]},CALL_END_LOCAL_HTTP_STACK_ERROR:{code:496,subCode:4520,phrase:"LocalHTTPStackError",resultCategories:[Xs]},CALL_END_UNKNOWN_ERROR:{code:497,subCode:3121,phrase:"CallEndReasonUnknownError",resultCategories:[Xs]},CALL_END_NETWORK_ERROR:{code:490,subCode:4502,phrase:"CallEndReasonNetworkError",resultCategories:[Xs]},CALL_END_DNS_HOST_NAME_RESOLVE_ERROR:{code:490,subCode:4522,phrase:"CallEndReasonDnsHostNameResolveError",resultCategories:[Xs]},CALL_END_LOCAL_DECLINE:{code:486,subCode:4508,phrase:"LocalDecline",resultCategories:[Qs]},RESOURCE_NOT_FOUND_ERROR:{code:404,subCode:404,phrase:"ResourceNotFound",resultCategories:[Zs]},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:[Qs]},VALIDATION:{VALIDATION_FAILED:6e3,NULL_OR_EMPTY:6001}},ta={REQUEST_TIMEOUT:{status:ea.HTTP_STATUS_CODES.TIMEOUT,statusText:"Request timed out",readyState:0,response:ea.HTTP_STACK_ERROR.REQUEST_TIMEOUT},ATTEMPT_TIMEOUT:{status:ea.HTTP_STATUS_CODES.TIMEOUT,statusText:"Attempt timed out",readyState:0,response:ea.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT},REQUEST_ABORTED:{status:ea.HTTP_STATUS_CODES.ABORTED,statusText:"Request Aborted",readyState:0,response:ea.HTTP_STACK_ERROR.REQUEST_ABORTED},ATTEMPT_ABORTED:{status:ea.HTTP_STATUS_CODES.ABORTED,statusText:"Attempt Aborted",readyState:0,response:ea.HTTP_STACK_ERROR.ATTEMPT_ABORTED}},ia={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/"},na={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/"},ra={...ia,...na},sa="callNotification",aa="mediaAnswer",oa="mediaAcknowledgement",la="callAcceptance",ca="callEnd",da="callProgress",ua="callAcceptanceAcknowledgement",ha="mediaNegotiation",ga="mediaNegotiationFailure",pa="balanceUpdate",ma="retargetCompleted",fa="callTransfer",va="transferCompletion",Sa="transferAcceptance",ya="holdCompletion",Ca="resumeCompletion",Ta="updateMeetingLiveStateResponse",Ea="updateMeetingGroupsResponse",ba="setMeetingLayoutResponse",_a="updateMeetingStatesResponse",Ia="monitorCompletion",wa=ea,Aa=p(Z),Pa=class e{constructor(e){this.headers={},e&&Object.keys(e).forEach((t=>{this.headers[this.getLowerCaseName(t)]=e[t]}))}isEmpty(){return Aa.isEmpty(this.headers)}set(e,t){this.headers[this.getLowerCaseName(e)]=t}get(t,i){return i?e.getHeaderValue(this.headers,t)||i:e.getHeaderValue(this.headers,t)}delete(e){delete this.headers[e],delete this.headers[e.toLowerCase()]}hasOwnPropertyCaseInsensitive(e){return Object.keys(this.headers).filter((function(t){return t.toUpperCase()===e.toUpperCase()})).length>0}getAll(){return this.headers}getLowerCaseName(t){return e.useLowerCaseHeaders?t.toLowerCase():t}static getHeaderValue(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}};function Ra(e,t,i=Na()){return Fa(t,"trailingPath cannot be null"),Ua(e,"signalingSession cannot be null"),Ua(e.baseMessagingChannelUrl,"messaging channel url is not set"),`${e.baseMessagingChannelUrl}${wa.URL_BASE.CALLAGENT}/${e.sessionId}/${i}${t}`}function Ma(e){let t=1;return e.callingServiceSupportsAADTokens&&(t|=4),e.callingServiceSupportsCAETokens&&(t|=8),t}function Da(e){const t=e.toLowerCase(),i=t.indexOf('token_types="');if(-1===i)return[];const n=t.indexOf('"',i+13);if(-1===n)return[];const r=t.substring(i+13,n).trim();return""===r?[]:r.split(" ")}function ka(e){return!!e.match(/^8:/)}function Oa(e){return e.replace(/^\d+:/,"")}function Na(){return La().substr(0,8)}function La(){const e="0123456789abcdef";let t="",i=0,n=0;for(;n<36;){const r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[n];switch(i=n%8==0?4294967295*Math.random()|0:i>>4,r){case"x":t+=e[15&i];break;case"y":t+=e[3&i|8];break;case"4":case"-":t+=r}n++}return t}function xa(e,t){e||Va("Assert failed"+(void 0!==t?`:${t}`:""))}function Fa(e,t){(!e||e instanceof String&&""===e||e instanceof Array&&0===e.length)&&Va("AssertNotNullOrEmpty failed. "+(void 0!==t?`: ${t}`:""))}function Ua(e,t){e||Va("AssertNotNull failed. "+(void 0!==t?`: ${t}`:""))}function Ba(e){Fa(e,"callEndReason cannot be null or empty"),(void 0===e.code||void 0===e.subCode||void 0===e.phrase||e.code<0||e.subCode<0||" "===e.phrase)&&Va(`callEndReason must specify code, subCode and phrase. Invalid reason : ${je(e)}`)}function Va(e){throw{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.MISC_ERROR,phrase:e,resultCategories:[Zs]}}function Ha(e){Ua(e,"MediaTypes passed cannot be null");const t=[],i=wa.MEDIA_TYPES;for(const n of Object.keys(i))Ga(e,i[n])&&t.push(i[n]);return t}function $a(e,t){const i={};for(const n of Object.values(t)){const t=n.split("/");i[t[t.length-2]]=Ra(e,n)}return i}function ja(e,t){return e.length>=t.length&&e.indexOf(t,e.length-t.length)>-1}function Ga(e,t){const i=t.toString().toLowerCase();return e.map((e=>e.toString().toLowerCase())).indexOf(i)>-1}function qa(e,t,i){return!e.hasOwnProperty(t)&&(e[t]=i,!0)}function za(e,t){return!!e.hasOwnProperty(t)&&(delete e[t],!0)}function Wa(e){let t=null;try{return t=JSON.parse(e),"object"==typeof t?t:null}catch(e){return null}}function Ka(e,t){if(!e)return{telemetryEndSubCode:wa.CALL_END_CODE.UNKNOWN_ERROR,error:wa.CALL_END_UNKNOWN_ERROR};let i;if("object"==typeof e.response)i=e.response;else try{i=JSON.parse(e.response)}catch(e){}if(e.skypeTokenError)return{telemetryEndSubCode:wa.CALL_END_CODE.SKYPE_TOKEN_ERROR,error:wa.CALL_END_SKYPE_TOKEN_ERROR};if(e.tokenTimeoutError&&!e.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:wa.CALL_END_TOKEN_TIMEOUT_ERROR};if(e.tokenError){const t=e.tokenErrorSubCode?{code:wa.CALL_END_TOKEN_ERROR.code,subCode:e.tokenErrorSubCode,phrase:wa.CALL_END_TOKEN_ERROR.phrase,resultCategories:wa.CALL_END_TOKEN_ERROR.resultCategories}:wa.CALL_END_TOKEN_ERROR;return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:t}}if(e.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED};if(i&&(i.operationFailure||i.broadcastOperationFailure)){const e=i.operationFailure||i.broadcastOperationFailure;return{telemetryEndSubCode:e.code,error:e}}return i&&"net::err_name_not_resolved"===i._error?.toLowerCase()?{telemetryEndSubCode:wa.CALL_END_CODE.NETWORK_ERROR,error:wa.CALL_END_DNS_HOST_NAME_RESOLVE_ERROR}:i?.code?{telemetryEndSubCode:i.code,error:i}:isNaN(e.status)||e.status!==wa.CALL_END_CODE.NOT_FOUND?!isNaN(e.status)&&e.status?{telemetryEndSubCode:e.status,error:{code:e.status,subCode:isNaN(e.response)?0:e.response,phrase:e.statusText,resultCategories:[Xs]}}:!isNaN(e.response)&&e.response?{telemetryEndSubCode:0,error:{code:0,subCode:e.response,phrase:e.statusText,resultCategories:[Xs]}}:{telemetryEndSubCode:wa.CALL_END_CODE.NETWORK_ERROR,error:wa.CALL_END_NETWORK_ERROR}:{telemetryEndSubCode:wa.CALL_END_CODE.NOT_FOUND,error:wa.RESOURCE_NOT_FOUND_ERROR}}function Ja(e,t){if(e&&!e.isEmpty()&&t){const i=e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID),n=e.get(wa.HEADERS.MESSAGE_ID);if(n&&Ga(t,n)||i&&Ga(t,i))return!0;t.length>9&&t.shift(),t.push(i||n)}return!1}function Ya(e){const t="unknown";return e.headers?e.headers.get(wa.HEADERS.ORIGINAL_MESSAGE_ID,t):t}function Qa(e){try{return e.headers.get(wa.HEADERS.ORIGINAL_MESSAGE_ID).replace("-","").substr(0,8)}catch(e){return Na()}}function Za(e){return e&&e.hasOwnPropertyCaseInsensitive(wa.HEADERS.CONTENT_ENCODING)}function Xa(e){return e&&wa.KNOWN_PAYLOAD_ENCODINGS.hasOwnProperty(e.get(wa.HEADERS.CONTENT_ENCODING).toUpperCase())}function eo(e){const t=atob(e);return Ys.inflate(t,{to:"string"})}function to(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)}}}function io(e){let t=!1;try{if(t=e&&2===e.state(),navigator.onLine&&t)return 3;if(!navigator.onLine&&t)return 2;if(navigator.onLine&&!t)return 1}catch{}return 0}function no(e){return[wa.HTTP_STATUS_CODES.UNKNOWN,wa.HTTP_STATUS_CODES.UNAUTHORIZED,wa.HTTP_STATUS_CODES.NETWORK_ERROR,wa.HTTP_STATUS_CODES.OFFLINE,wa.HTTP_STATUS_CODES.TIMEOUT,wa.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,wa.HTTP_STATUS_CODES.BAD_GATEWAY,wa.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE,wa.HTTP_STATUS_CODES.GATEWAY_TIMEOUT].indexOf(e)>=0}function ro(e,t){switch(e){case wa.HEADERS.CAE_KEYWORD.toLowerCase():return 8;case wa.HEADERS.AAD_KEYWORD.toLowerCase():return 4;case wa.HEADERS.SKYPE_KEYWORD.toLowerCase():return 1;default:return t?.info("unexpected: unrecognized token type ${tokenType}"),null}}function so(e){switch(e){case 0:return"GET";case 1:return"POST";case 2:return"PUT";case 3:return"DELETE"}}function ao(e,t,i,n,r=!1,s,a){a?.createChild("[utils.ts]");const o={verb:so(i),path:n.url},l=JSON.stringify(o),c=function(e){let t={};if(e){const i=Pa.getHeaderValue(e,wa.HEADERS.AUTHENTICATE);i&&(t={authenticationHeaders:[i]})}return t}(s),d=function(e,t,i,n,r){if(!t)return 1;const{callingServiceSupportsAADTokens:s,callingServiceSupportsCAETokens:a,supportMissingTokenTypesInResponse:o,useSkypeTokenWhenNoAuthenticateHeader:l}=e,c=r?.authenticationHeaders;n?.info(`[getAuthHeadersTokenTypes] UnauthorizedResponse=${i} and authHeaders=${c}`);let d=null;if(!c&&i)l?(n?.info("[getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),d=1):(n?.info("[getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),d=Ma(e));else if(c||i){if(c&&i)for(const t of c){const i=Da(t);if(o&&0===i.length)n?.info("[getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),d=Ma(e);else for(const e of i){const t=ro(e.toLowerCase(),n);a&&8===t&&(d|=8),s&&4===t&&(d|=4),1===t&&(d|=1)}}}else n?.info("[getAuthHeadersTokenTypes] first time requesting token, request client supported token types"),d=Ma(e);return d}(e,t,r,a,c);return a?.info(`[getTokenMetadata] return token type=${d}, factoJson=${l}, headers=${c?.authenticationHeaders}`),{tokenType:d,factorsJson:l,requestMetadataJson:c,isUnauthorized:r}}function oo(){return Math.floor(Date.now()/1e3)}function lo(e){return 1e3*e}function co(e){switch(e){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 uo(e){switch(e){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 ho(e){switch(e){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 go(e){let t={};return e.additionalData&&e.customHeaderContext?t="object"==typeof e.additionalData?{...e.additionalData,customContext:e.customHeaderContext}:{additionalData:e.additionalData,customContext:e.customHeaderContext}:!e.additionalData&&e.customHeaderContext?t={customContext:e.customHeaderContext}:e.additionalData&&!e.customHeaderContext&&(t=e.additionalData),t}function po(e){if(!e)return;let t="unknown";return"substrate"===e&&(t="substrate"),t}var mo=class e{static isInLobby(e,t){for(const i of e)if(i.endpointId===t&&i.isLobby)return!0;return!1}static isParticipantServerMuted(e){for(const t of e)if(t.mediaStreams&&!t.mappedTo)for(const e of t.mediaStreams)if("audio"===e.type&&!0===e.serverMuted)return!0;return!1}static fromWireParticipant(t){return Ua(t,"invalid wireParticipant"),Fa(t.id,"participant must have valid Id"),new e({id:t.id,displayName:t.displayName,languageId:t.languageId,acceptedBy:t.acceptedBy})}static getPluginlessStateTypeFromWire(e){return uo(e)}static findOrCreateTypeState(e,t){let i=t.typeStates.findIndex((t=>t.type===e));if(-1===i){const n={participantStates:[],type:e};t.typeStates.push(n),i=t.typeStates.length-1}return i}static processPublishedStates(e,t){const i={typeStates:[]},n=e;return Ks.forEach(n,(e=>{const n=this.findOrCreateTypeState(this.getPluginlessStateTypeFromWire(e.stateType),i),r={id:t,publishedState:{content:e.content,stateId:e.stateId,typeRank:e.typeRank}};i.typeStates[n].participantStates.push(r)})),i}static fromRosterEndpoints(e){let t=[],i=!1,n=!1,r=!1,s=!1;return t=Object.keys(e).map((t=>{let a,o,l,c=[],d=!1,u=0;if(e[t].call&&(i=!0,c=e[t].call.mediaStreams||null,u=e[t].call.serverMuteVersion||0,o=e[t].call.appliedInteractivityLevel||"unknown",l=e[t].call.negotiationTag),e[t].lobby&&(d=!0,n=!0,c=e[t].lobby.mediaStreams||null),e[t].broadcast?.sessionInformation&&(a=e[t].broadcast.sessionInformation.role||null),e[t].mappedParticipant&&(r=!0,c=e[t].mappedParticipant.mediaStreams||null),!e[t].capabilities&&e[t].endpointCapabilities){const i=e[t].endpointCapabilities;e[t].capabilities={implicitCallback:16&i?"enabled":"disabled",cloudAudioVideoConference:1&i?"enabled":"disabled",cloudScreenSharing:2&i?"enabled":"disabled",hostlessConference:4&i?"enabled":"disabled",autoJoinOnConflict:32&i?"enabled":"disabled",serverMuteUnmute:64&i?"enabled":"disabled",supportsCompressedServicePayload:128&i?"enabled":"disabled",cloudMerge:8&i?"enabled":"disabled"}}return s=s||!!e[t].streamLobby||!!e[t].stream,{endpointId:t,participantId:e[t].participantId||null,clientVersion:e[t].clientVersion||null,endpointMetadata:e[t].endpointMetadata||null,originalId:e[t].originalId||null,contentSharing:e[t].contentSharing||null,capabilities:e[t].capabilities||null,endpointType:e[t].endpointType||"default",deviceType:e[t].deviceType||void 0,clientEndpointCapabilities:e[t].clientEndpointCapabilities||void 0,mediaStreams:c,serverMuteVersion:u,broadcastMeetingRole:a,isLobby:d,endpointState:e[t].endpointState||null,publishedStates:e[t].publishedStates||null,callLinks:e[t].callLinks||null,appliedInteractivityLevel:o||"unknown",mappedTo:e[t].mappedTo||null,meetingGroupDetails:e[t].meetingGroupDetails,streamInformation:e[t].streamInformation,propertyBag:e[t].propertyBag,streamLobby:e[t].streamLobby,stream:e[t].stream,endpointMeetingRoles:e[t].endpointMeetingRoles,negotiationTag:l}})),{endpointDetails:t,participantHasCallModality:i,participantIsInLobby:n,participantHasMappedEndpoint:r,participantHasStreamEndpoint:s}}static fromRoster(t,i=!1){Ua(t,`invalid rosterParticipant ${JSON.stringify(t)}`),Fa(t.details.id,"participant must have valid Id");const n=t.endpoints||{},r=this.fromRosterEndpoints(n),s=r.endpointDetails,a=r.participantHasCallModality,o=r.participantHasMappedEndpoint,l=r.participantHasStreamEndpoint;let c=r.participantIsInLobby;return a||c||o||i||l?(a&&(c=!1),new e({id:t.details.id,displayName:t.details.displayName,otpIdentity:t.details.otpIdentity,version:t.version||0,propertyBag:t.details.propertyBag||null,languageId:t.details.languageId,role:t.role||"",tenantId:t.details.tenantId||"",endpointDetails:s||[],acceptedBy:t.acceptedBy||"",isLobby:c,meetingRole:t.meetingRole,advancedMeetingRole:t.advancedMeetingRole,meetingRoles:t.meetingRoles,participantType:t.details.participantType,publishedStates:t.publishedStates||null,isIdentityMasked:t.details.isIdentityMasked,nonMaskedId:t.details.nonMaskedId||"",nonMaskedObjectId:t.details.nonMaskedObjectId||"",nonMaskedDisplayName:t.details.nonMaskedDisplayName||"",maskedIdSeqNumber:t.details.maskedIdSeqNumber||0,maskedId:t.details.maskedId||"",joinAsStreamingUser:t.joinAsStreamingUser,enableCaptcha:t.enableCaptcha})):null}static fromRosterSearchResults(e){Ua(e,`invalid rosterParticipant ${JSON.stringify(e)}`),Fa(e.details.id,"participant must have valid Id");const t=e.endpoints,{endpointDetails:i,participantHasCallModality:n,participantIsInLobby:r,participantHasMappedEndpoint:s,participantHasStreamEndpoint:a}=this.fromRosterEndpoints(t);let o=0;return n||a?o=3:r?o=10:s&&(o=3),{id:e.details.id,state:o,tenantId:e.details.tenantId||"",displayName:e.details.displayName,role:e.role||"",meetingRole:e.meetingRole,advancedMeetingRole:e.advancedMeetingRole,meetingRoles:e.meetingRoles,participantType:e.details.participantType,isServerMuted:this.isParticipantServerMuted(i),publishedStates:this.processPublishedStates(e.publishedStates,e.details.id),endpoints:i||[],isIdentityMasked:e.details.isIdentityMasked,nonMaskedId:e.details.nonMaskedId||"",nonMaskedDisplayName:e.details.nonMaskedDisplayName||"",nonMaskedObjectId:e.details.nonMaskedObjectId||"",maskedIdSeqNumber:e.details.maskedIdSeqNumber||0,maskedId:e.details.maskedId||"",joinAsStreamingUser:e.joinAsStreamingUser}}constructor(e){this.id=e.id,this.displayName=e.displayName||"",this.otpIdentity=e.otpIdentity,this.version=e.version,this.propertyBag=e.propertyBag,this.languageId=e.languageId||null,this.endpointDetails=e.endpointDetails||[],this.acceptedBy=e.acceptedBy,this.role=e.role,this.tenantId=e.tenantId,this.isLobby=e.isLobby,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.meetingRoles=e.meetingRoles,this.participantType=e.participantType,this.publishedStates=e.publishedStates,this.isIdentityMasked=e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,this.enableCaptcha=e.enableCaptcha}},fo="HandleMediaAcknowledgement",vo="HandleMediaAnswer",So="AddParticipant",yo="AddParticipantTimeout",Co="AddParticipantWithReplacesTimeout",To="AdmitFailure",Eo="RemoveParticipantTimeout",bo="HandleAddParticipantSuccess",_o="HandleRosterUpdateFail",Io="HandleCallAcceptanceFailed",wo="HandleCallEnd",Ao="TrouterUrlChanged",Po="TrouterUrlUpdateFailed",Ro="HandleContentSharingUpdate",Mo="HandleAddModalitySuccess",Do="HandleAddModalityFailure",ko="TransferCompletionFailed",Oo="TransferRequestReceived",No="DuplicateMessageIgnored",Lo="FailedToHandleMessage",xo="MessageMissingBody",Fo="HandlePstnBalanceUpdate",Uo="IgnoreOldRoster",Bo="TransferRequestSent",Vo="TransferRequestFailed",Ho="TransferCompleted",$o="WaitingForUpdateMeetingLiveStateCompletion",jo="WaitingForUpdateMeetingGroupsCompletion",Go="WaitingForSetMeetingLayoutCompletion",qo="UpdateParticipantsPropertiesResponseFailed",zo="WaitingForJoinMeetingGroupCompletion",Wo="WaitingForLeaveMeetingGroupCompletion",Ko="SendMessageCompletion",Jo="WaitingForUpdateMeetingStatesCompletion",Yo="UpdateMeetingStatesResponseFailure",Qo="WaitingForUpdateMonitorSessionCompletion",Zo={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}},Xo="Local",el="SkypeConcore",tl="skypecosi_concore_web_csa_conversation_callmodality",il="skypecosi_concore_web_csa_conversation_contentsharing",nl="skypecosi_concore_web_csa_conversation_httprequest",rl="skypecosi_concore_web_csa_conversation_token",sl="Direction",al="ContentSharingDirection",ol="ConnectedDurationInMsecs",ll="PreheatedCallSetupDurationInSeconds",cl="CallCancelationDurationInSeconds",dl="IsPreheated",ul="TimeToRingInMsecs",hl="CallTerminatingEnd",gl="NetworkRequestsPending",pl="NetworkRequestsCompleted",ml="LocalOperationsPerformed",fl="TrouterWaitOperations",vl="CallStartTime",Sl="CallEndTime",yl="IsGroupCall",Cl="IsHostLessCall",Tl="IsCastCall",El="IsHuddleGroupCall",bl="IsMeetupCall",_l="IsOnBehalfOfCall",Il="SdpInCallNotification",wl="Code",Al="SubCode",Pl="Phrase",Rl="ResultCategories",Ml="CauseId",Dl="ConflictingCallId",kl="ConversationServiceUrl",Ol="ContentSharingServiceUrl",Nl="MeetingInfo",Ll="JoinedFrom",xl="ResultValue",Fl="ResultDetail",Ul="ResultCauseId",Bl="LocalOfferAnswerGenerationTimestamps",Vl="SelfParticipantRole",Hl="Scenario",$l="Caller_Type",jl="Callee_Type",Gl="Call_Type",ql="Test_Context_Id",zl="Outgoing_Modalities",Wl="Incoming_Modalities",Kl="CallOfferredModalities",Jl="CallAnsweredModalities",Yl="VBSS_Operations",Ql="ChangingCorrelationId_NewId",Zl="ChangingCorrelationId_OldId",Xl="MessagingChannel",ec="EventTimestampBag",tc="RosterUpdatesBag",ic="NetworkRequestBag",nc="ClientInformation",rc="EcsEtag",sc="ApplicationType",ac="Ring",oc="TenantId",lc="UserHexCID",cc="AcsResourceId",dc="Region",uc="Partition",hc="CallEventCallEndClientSubCode",gc="CallEventCallEndClientPhrase",pc="MeetingCode",mc="MeetingJoinUrl",fc="BroadcastMeetingRole",vc="MeetingRole",Sc="AdvancedMeetingRole",yc="MeetingRoles",Cc="ParticipantType",Tc="DisplayName",Ec="ClientSupportsAudioOnlyWatermark",bc="ClientSupportsWatermark",_c="TargetApplicationType",Ic="IsReinviteless",wc="ClientType",Ac="ClientSupportsPreventScreenCapture",Pc="Trouter",Rc="Broker",Mc="JsCsaConfig",Dc="BrokerOutgoingEnabled",kc="BrokerIncomingEnabled",Oc="BrokerRequestBatchingEnabled",Nc="BrokerExclusivelyEnabled",Lc="SupportsCompressedPayload",xc="SyncTrouterResponse",Fc="serverMuteUnmute",Uc="handleMediaOfferFromPushNotification",Bc="handleNewOfferRequest",Vc="sendProgressFromCC",Hc="internalHttpDispatcher",$c="enableTokenCache",jc="enableTokenPrefetch",Gc="supportMediaRetargetWhileIncomingRenegotiation",qc="enableCallEstablishmentTimeoutsForStartJoinCall",zc="enableTokenCacheForGenericTokenAPI",Wc="enableLongOutgoing1To1SetupTimeoutForWeb",Kc="CorrelationId",Jc="SharedCorrelationId",Yc="SignalingSessionId",Qc="GroupId",Zc="ThreadId",Xc="TeamsMessageId",ed="TeamsMeetingInfo",td="EndpointId",id="ParticipantId",nd="ContentSharingSessionId",rd="ContentSharingCorrelationId",sd="Local",ad="Remote",od="Success",ld="Failure",cd="Incoming",dd="Outgoing",ud="caller",hd="callee",gd="join",pd="joinForRosterOnly",md="preheat",fd="Start",vd="Stop",Sd="Rejected",yd="RemoteStart",Cd="Timeout",Td="CallEnd",Ed="Started",bd="Ended",_d="Failed",Id="TokenTelemetry";function wd(e){e.cloudScreenSharingFlag="disabled"===e.cloudScreenSharingFlag?e.cloudScreenSharingFlag:"enabled",e.isWebRtcEnabled="undefined"==typeof RTCIceGatherer,e.shouldServiceSendNGCUpgradeMessages=Ad(e.shouldServiceSendNGCUpgradeMessages,!0),e.isGVCOutgoingEnabled=Ad(e.isGVCOutgoingEnabled,!0),e.supportsCompressedServicePayload=Ad(e.supportsCompressedServicePayload,!0),e.supportsSynchronousTrouterResponse=Ad(e.supportsSynchronousTrouterResponse,!0),e.supportsHostlessGroupCalls=Ad(e.supportsHostlessGroupCalls,!0),e.doHostlessCalling=Ad(e.doHostlessCalling,!1),e.brokerExclusively=Ad(e.brokerExclusively,!1),e.brokerEnabledOutgoing=Ad(e.brokerEnabledOutgoing,!0),e.brokerEnabledIncoming=Ad(e.brokerEnabledIncoming,!0),e.brokerRequestBatching=Ad(e.brokerRequestBatching,!0),e.handleMediaOfferFromPushNotification=Ad(e.handleMediaOfferFromPushNotification,!0),e.handleNewOfferRequest=Ad(e.handleNewOfferRequest,!1),e.autoJoinOnConflict=Ad(e.autoJoinOnConflict,!0),e.endConflictedCall=Ad(e.endConflictedCall,!1),e.autoResolveConflictedCall=Ad(e.autoResolveConflictedCall,!1),e.shouldServiceSendCallEventMessages=Ad(e.shouldServiceSendCallEventMessages,!1),e.forceTrouterReconnectOnNetworkOnline=Ad(e.forceTrouterReconnectOnNetworkOnline,!0),e.attemptHttpRequestWithCachedSkypetoken=Ad(e.attemptHttpRequestWithCachedSkypetoken,!0),e.useInternalHttpDispatcher=Ad(e.useInternalHttpDispatcher,!1),e.enableTokenCache=Ad(e.enableTokenCache,!1),e.enableTokenPrefetch=Ad(e.enableTokenPrefetch,!1),e.hedgeDelayMs=Ad(e.hedgeDelayMs,4e3),e.hedgeMaxParallelAttempts=Ad(e.hedgeMaxParallelAttempts,3),e.useInternalHttpDispatcher&&(e.httpRequestDispatcher=new st(e.logger)),e.enableQuickSendAcceptanceAck=Ad(e.enableQuickSendAcceptanceAck,!1),e.supportMediaRetargetWhileIncomingRenegotiation=Ad(e.supportMediaRetargetWhileIncomingRenegotiation,!1),e.callingServiceSupportsAADTokens=Ad(e.callingServiceSupportsAADTokens,!1),e.callingServiceSupportsCAETokens=Ad(e.callingServiceSupportsCAETokens,!1),e.aadTokenExpirationTimeInSeconds=Ad(e.aadTokenExpirationTimeInSeconds,3600),e.caeTokenExpirationTimeInSeconds=Ad(e.caeTokenExpirationTimeInSeconds,86400),e.disableTokenMigrationHeader=Ad(e.disableTokenMigrationHeader,!1),e.enablePublishTokenTelemetry=Ad(e.enablePublishTokenTelemetry,!1),e.forceClearExpiredTokens=Ad(e.forceClearExpiredTokens,!1),e.enableRefreshToken=Ad(e.enableRefreshToken,!0),e.refreshTimeBeforeTokenTimeoutInSeconds=Ad(e.refreshTimeBeforeTokenTimeoutInSeconds,30),e.enableCallEstablishmentTimeoutsForStartJoinCall=Ad(e.enableCallEstablishmentTimeoutsForStartJoinCall,!1),e.csaTimeoutConfiguration=function(e,t){return(t||e)&&{...t,...e}}(e.csaTimeoutConfiguration,{conversationKeepAliveTimeoutSec:2700,promotionUnmuteTimeoutSec:1e4}),e.reportPreviousErrorsForTimeout=Ad(e.reportPreviousErrorsForTimeout,!1),e.callingTokenLogicalUrl=Ad(e.callingTokenLogicalUrl,"https://calling.teams.microsoft.com"),e.enableAsyncDisablePreheat=Ad(e.enableAsyncDisablePreheat,!1),e.forceLowercaseHttpHeaders=Ad(e.forceLowercaseHttpHeaders,!1),e.enableResolveScreenSharingWhenNegotiationComplete=Ad(e.enableResolveScreenSharingWhenNegotiationComplete,!1),e.maxReinvitelessMediaForVideoForWeb=Ad(e.maxReinvitelessMediaForVideoForWeb,0),e.maxReinvitelessMediaForVBSSForWeb=Ad(e.maxReinvitelessMediaForVBSSForWeb,0),e.enableRefreshTokenRetry=Ad(e.enableRefreshTokenRetry,!0),e.enableRefreshTokenRetryInSeconds=Ad(e.enableRefreshTokenRetryInSeconds,60),e.enableConversationTypeUpdateOnCallEnd=Ad(e.enableConversationTypeUpdateOnCallEnd,!1),e.supportMissingTokenTypesInResponse=Ad(e.supportMissingTokenTypesInResponse,!0),e.useSkypeTokenWhenNoAuthenticateHeader=Ad(e.useSkypeTokenWhenNoAuthenticateHeader,!1),e.enableAutoPromotion=Ad(e.enableAutoPromotion,!1),e.enableBatchedSendMessageStatus=Ad(e.enableBatchedSendMessageStatus,!1),e.enableBatchedReceiveMessage=Ad(e.enableBatchedReceiveMessage,!1),e.enableAddParticipantEnhancements=Ad(e.enableAddParticipantEnhancements,!1),e.enableTokenCacheForGenericTokenAPI=Ad(e.enableTokenCacheForGenericTokenAPI,!1),e.disableRealTimeModeFromRoster=Ad(e.disableRealTimeModeFromRoster,!0),e.enableLongOutgoing1To1SetupTimeoutForWeb=Ad(e.enableLongOutgoing1To1SetupTimeoutForWeb,!1),e.checkAttendeeRoleInCreateContentSharing=Ad(e.checkAttendeeRoleInCreateContentSharing,!0),e.enableSpecificErrorCodesForCallEnd=Ad(e.enableSpecificErrorCodesForCallEnd,!1),e.enableSplitConversationEndUrl=Ad(e.enableSplitConversationEndUrl,!1),e.enableFetchRequestWithKeepAlive=Ad(e.enableFetchRequestWithKeepAlive,!1),e.enableFetchApi=Ad(e.enableFetchApi,!1),e.enableFetchApiForBeacon=Ad(e.enableFetchApiForBeacon,!1)}function Ad(e,t){return null==e?t:e}var Pd=class{constructor(){this.skypeTokenContext={},this.aadTokenContext={},this.caeTokenContext={}}getTokenContext(e){return 4===e?this.aadTokenContext:8===e?this.caeTokenContext:1===e?this.skypeTokenContext:void 0}getTokenExpiry(e,t){return 4===e?this.aadTokenContext?.expiryTime:8===e?this.caeTokenContext?.expiryTime:1===e?this.skypeTokenContext?.expiryTime:(t?.info("[getTokenExpiry] unrecognized token type, return Number.MAX_VALUE"),Number.MAX_VALUE)}getToken(e,t,i,n){return 8&e&&this.caeTokenContext?.token&&this.caeTokenContext.token!==n?{token:this.caeTokenContext.token,tokenType:8}:4&e&&this.aadTokenContext?.token&&this.aadTokenContext.token!==n?{token:this.aadTokenContext.token,tokenType:4}:1&e&&this.skypeTokenContext?.token&&this.skypeTokenContext.token!==n?{token:this.skypeTokenContext.token,tokenType:1}:(i?.info(`[getToken] no cached token found of token type: ${e}`),null)}setToken(e,t,i,n){switch(e){case 4:this.aadTokenContext.factorsJson=i,this.aadTokenContext.tokenType=e,this.aadTokenContext.token=t,this.aadTokenContext.expiryTime=n;break;case 1:this.skypeTokenContext.factorsJson=i,this.skypeTokenContext.tokenType=e,this.skypeTokenContext.token=t,this.skypeTokenContext.expiryTime=n;break;case 8:this.caeTokenContext.factorsJson=i,this.caeTokenContext.tokenType=e,this.caeTokenContext.token=t,this.caeTokenContext.expiryTime=n;break;default:throw new Error(`Invalid tokenType ${e}`)}}clearExpiredTokens(e){const t=Math.round(Date.now()/1e3);this.caeTokenContext?.expiryTime<=t&&(this.resetToken(8),e?.info("[cacheTokenManager] reset expired cae token")),this.aadTokenContext?.expiryTime<=t&&(this.resetToken(4),e?.info("[cacheTokenManager] reset expired aad token")),this.skypeTokenContext?.expiryTime<=t&&(this.resetToken(1),e?.info("[cacheTokenManager] reset expired skype token"))}resetToken(e){8===e?this.caeTokenContext={}:4===e?this.aadTokenContext={}:1===e&&(this.skypeTokenContext={})}},Rd=class{constructor(e){this.timers={},this.startTimer=(e,t,i,n)=>{this.logger.info(`startTimer called for : ${e} with timeoutInSeconds : ${i}s`);const r=window.setTimeout(t,1e3*i),s=n?`${e}${n}`:e;this.timers[s]=r},this.stopTimer=(e,t)=>{this.logger.info(`stopTimer called for : ${e}`);const i=t?`${e}${t}`:e;this.timers.hasOwnProperty(i)&&(clearTimeout(this.timers[i]),delete this.timers[i])},this.dispose=()=>{this.logger.info("timeoutManager :: dispose"),Object.keys(this.timers).forEach((e=>{this.stopTimer(e)}))},this.logger=e}},Md=class{constructor(e,t,i,n){this.tokenProvider=t,this.tokenCachingEnabled=!1,this.enableTokenCacheForGenericTokenAPI=!1,this.cachedToken="",this.lastTokenType=1,this.lastToken="",this.clientSupportsGenericTokenAPI=!1,this.stopTimerFlag=!1,this.tokensPromiseMap={},this.logger=e.createChild("TokenManager"),i&&this.updateTokenSettings(i),this.cacheTimers=new Rd(e),this.cacheTokenManager=new Pd,this.telemetryManager=n,this.nextRefreshTimePointInSeconds=Number.MAX_VALUE}deletePromisesByTriggeredByRefresh(e,t){if(this.tokensPromiseMap[e]){const i=this.tokensPromiseMap[e];for(let n=i.length-1;n>=0;n--)i[n]?.tokenRequestOptions.triggeredByRefresh===t&&this.tokensPromiseMap[e].splice(n,1)}}startTokenRefreshTimer(e){const t="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=${e}`);const i=oo(),n=function(e){return e/1e3}(e),r=i+n;this.nextRefreshTimePointInSeconds===Number.MAX_VALUE||this.nextRefreshTimePointInSeconds<i||r<this.nextRefreshTimePointInSeconds?(this.logger.info("[startTokenRefreshTimer] cancelling current refresh timer to create new one with shorter time"),this.cacheTimers.stopTimer(t),this.nextRefreshTimePointInSeconds=r,this.logger.info(`[startTokenRefreshTimer] start new timer with timeout=${n} at time=${i}`),this.cacheTimers.startTimer(t,(()=>{this.nextRefreshTimePointInSeconds=Number.MAX_VALUE,this.refreshToken()}),n)):this.logger.info("[startTokenRefreshTimer] no need to set a new refresh timer")}async refreshTokenWithContext(e){const t={triggeredByRefresh:!0},i=La(),n={causeId:i},r=Date.now();let s,a,o,l=2;this.logger.info(`[${i}][refreshTokenWithContext] refreshing token tokenType=${e.tokenType} factorsJson=${e.factorsJson}`);let c=null;try{const t=this.onTokenRequired({factorsJson:e.factorsJson,tokenType:e.tokenType,requestMetadataJson:n,invalidToken:void 0,isUnauthorized:void 0,triggeredByRefresh:!0}),r=await this.timeoutPromiseRace(t,this.enableRefreshTokenRetryInSeconds,"ActiveRefresh Token Timeout");s=Date.now(),o=r?.causeId,c=r?.tokenType,this.lastTokenType=c,this.lastToken=r.token,l=1,this.logger.info(`[${i}][refreshTokenWithContext] refresh token success for factorsJson ${e.factorsJson} and tokenType ${e.tokenType}`)}catch(t){a=t,o=a?.causeId,t?.timeOut?(this.logger.info(`[${i}][refreshTokenWithContext] refresh token timeout, UI did not respond with token in time ${je(t)}`),l=5):(this.logger.info(`[${i}][refreshTokenWithContext] failed to refresh token, UI did not respond with token ${je(t)}`),l=2),s=Date.now(),this.deletePromisesByTriggeredByRefresh(e.factorsJson,!0)}finally{t&&(t.requestCauseId=i,t.responseCauseId=o,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=e.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=s,t.tokenRequestStatus=l,t.requestTokenType=e.tokenType,t.foundInCache=!1,t.responseTokenType=c,t.errorCode=a?.errorCode,t.errorSubCode=a?.errorSubCode,this.sendTokenTelemetry(t))}}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 e=this.cacheTokenManager.getTokenContext(4),t=this.cacheTokenManager.getTokenContext(8),i=this.cacheTokenManager.getTokenContext(1);if(!e&&!t&&!i)return void this.logger.info("[refreshToken] no cached tokens available to refresh");const n=oo()+this.refreshTimeBeforeTokenTimeoutInSeconds;let r=Number.MAX_VALUE,s=!1;if(e)if(e.expiryTime>n){const t=e?.expiryTime-n;t<r&&(r=t)}else e.expiryTime<=n&&(this.refreshTokenWithContext(e),s=!0);if(t)if(t.expiryTime>n){const e=t?.expiryTime-n;e<r&&(r=e)}else t.expiryTime<=n&&(this.refreshTokenWithContext(t),s=!0);if(i)if(i.expiryTime>n){const e=i?.expiryTime-n;e<r&&(r=e)}else i.expiryTime<=n&&(this.refreshTokenWithContext(i),s=!0);s&&this.enableRefreshTokenRetry&&this.enableRefreshTokenRetryInSeconds>0&&this.enableRefreshTokenRetryInSeconds<r&&(r=this.enableRefreshTokenRetryInSeconds),r>=0&&r!==Number.MAX_VALUE&&this.startTokenRefreshTimer(lo(r))}async getTokenWithTokenType(e,t=!1,i,n){this.logger.info(`[${e}][getTokenWithTokenType] call with factorJson=${i?.factorsJson} and request tokenType ${i?.tokenType}`);const{factorsJson:r,requestMetadataJson:s,invalidToken:a,isUnauthorized:o}=i||{},l=Date.now(),c=i?.tokenType;let d,u,h,g=2,p=null;this.clearExpiredTokens(),this.startTokenRefreshTimer(1);try{if(t)this.invalidateCachedTokenWithTokenType(c,a,r);else if(this.enableTokenCacheForGenericTokenAPI){const t=this.cacheTokenManager.getToken(c,r,this.logger,a);if(t?.token)return this.logger.info(`[${e}][getTokenWithTokenType] returning cached token for factorsJson ${r} and request tokenType ${c}, response tokenType ${t.tokenType}`),g=3,d=Date.now(),p=t.tokenType,this.lastToken=t.token,this.lastTokenType=p,t}this.logger.info(`[${e}][getTokenWithTokenType] fetching new token for factorsJson ${r} and tokenType ${c}`);const i=s||{};i.causeId=e;const n=this.onTokenRequired({factorsJson:r,tokenType:c,requestMetadataJson:i,invalidToken:a,isUnauthorized:o,triggeredByRefresh:!1}),l=await this.timeoutPromiseRace(n,wa.TIMEOUT_VALUES_IN_SECONDS.TOKEN_REQUIRED_TIMEOUT,"Token not received from UI in time");return d=Date.now(),h=l?.causeId,p=l?.tokenType,this.lastToken=l?.token,this.lastTokenType=p,g=1,this.logger.info(`[${e}][getTokenWithTokenType] fetching new token success for factorsJson ${r} and tokenType ${c}`),l}catch(t){throw this.logger.info(`[${e}][getTokenWithTokenType] failed to fetch token ${je(t)}`),u=t,h=u?.causeId,u.timeOut&&(g=4),this.deletePromisesByTriggeredByRefresh(r,!1),t}finally{const t=!n?.tokenTelemetryData,r=t?{}:n?.tokenTelemetryData;r&&(r.requestCauseId=e,r.responseCauseId=h,r.supportTokenApi=this.clientSupportsGenericTokenAPI,r.requestTokenFactors=i?.factorsJson,r.tokenRequestTime=l,r.tokenResponseTime=d,r.tokenRequestStatus=g,r.requestTokenType=i?.tokenType,r.foundInCache=3===g,r.responseTokenType=p,r.timeToResponse=d?d-l:d,r.errorCode=u?.errorCode,r.errorSubCode=u?.errorSubCode),(!n||t&&!n.signalingSession)&&(this.logger?.info("[getTokenWithTokenType] TokenContext is not provided, sending token telemetry to Token table"),this.sendTokenTelemetry(r))}}async onTokenRequired(e){const{factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:s,triggeredByRefresh:a}=e;if(this.logger.info(`[onTokenRequired] factorsJson=${t} tokenType=${i}`),!i)return this.logger.info(`[onTokenRequired] factorsJson=${t} with no token type`),Promise.reject({errorCode:wa.HTTP_STATUS_CODES.UNAUTHORIZED,errorSubCode:0,causeId:n?.causeId});if(this.tokensPromiseMap[t]&&!a)for(const e of this.tokensPromiseMap[t])if(e.tokenRequestOptions.tokenType===i)return this.logger.info(`[onTokenRequired] factorsJson=${t} and tokenType ${i} has pending request`),e.defered.promise;this.tokensPromiseMap[t]||(this.tokensPromiseMap[t]=[]);const o=new Kt;return this.tokensPromiseMap[t].push({tokenRequestOptions:e,defered:o}),this.tokenCallback({factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:s}),o.promise}setTokenCaching(e,t){this.tokenCachingEnabled!==e&&(this.logger.info(`[authTokenManager]setTokenCaching=${e}`),this.tokenCachingEnabled=e)}setTokenCachingForGenericTokenAPI(e,t){this.enableTokenCacheForGenericTokenAPI!==e&&(this.logger.info(`[authTokenManager]setTokenCachingForGenericTokenAPI=${e}`),this.enableTokenCacheForGenericTokenAPI=e)}calculateTokenExpiry(e,t,i){const{factorsJson:n,tokenType:r}=t;let s=i-oo(),a=s,o=i;if(s&&s>0&&s>this.refreshTimeBeforeTokenTimeoutInSeconds){switch(r){case 4:s>this.aadTokenExpirationTimeInSeconds&&(s=this.aadTokenExpirationTimeInSeconds);break;case 8:s>this.caeTokenExpirationTimeInSeconds&&(s=this.caeTokenExpirationTimeInSeconds);break;default:s>3600&&(s=3600)}a=s-this.refreshTimeBeforeTokenTimeoutInSeconds,o=a+oo()}return this.logger.info(`[${e}][calculateTokenExpiry] calculate expiry to ${o} tokenType=${r} factorsJson=${n}`),o}addToCache(e,t,i,n){this.clearExpiredTokens(),this.cacheTokenManager.setToken(e,t,i,n)}clearExpiredTokens(){this.forceClearExpiredTokens&&this.cacheTokenManager.clearExpiredTokens(this.logger)}async getToken(e,t=!1,i,n){if(this.clientSupportsGenericTokenAPI){this.logger.info(`[${e}][getToken] callingTokenAPI is enabled so using new API to fetch it`);const{token:r}=await this.getTokenWithTokenType(e,t,i,n);return r}const r=Date.now();let s,a,o=2;try{if(t&&this.invalidateCachedToken(e),this.cachedToken&&this.tokenCachingEnabled)return this.logger.info(`[${e}][getToken] returning cached token`),o=3,this.lastTokenType=1,Promise.resolve(this.cachedToken);this.logger.info(`[${e}][getToken] fetching new token`);const i=await this.tokenProvider();return s=Date.now(),i?(this.tokenCachingEnabled&&(this.cachedToken=i),o=1,this.lastToken=i,this.lastTokenType=1,this.logger.info(`[${e}][getToken] fetching new token success`),i):(this.logger.info(`[${e}][getToken] received empty token`),Promise.reject("Received empty token"))}catch(t){throw this.logger.info(`[${e}][getToken] failed to fetch token=${je(t)}`),a=t,this.cachedToken="",t}finally{const t=n?.tokenTelemetryData;t&&(t.requestCauseId=e,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=i?.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=s,t.tokenRequestStatus=o,t.requestTokenType=i?.tokenType,t.foundInCache=3===o,t.responseTokenType=this.lastTokenType,t.timeToResponse=s?s-r:s,t.errorCode=a?.errorCode,t.errorSubCode=a?.errorSubCode)}}invalidateCachedToken(e){this.cachedToken&&(this.logger.info(`[${e}][invalidateCachedToken]`),this.cachedToken="")}invalidateCachedTokenWithTokenType(e,t,i){8===e&&this.cacheTokenManager.getToken(8,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(8)),4===e&&this.cacheTokenManager.getToken(4,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(4)),1===e&&this.cacheTokenManager.getToken(1,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(1))}getLastToken(e){return this.logger.info(`[${e}][getLastToken]`),this.lastToken}async timeoutPromiseRace(e,t,i){let n;const r=new Promise(((e,r)=>{n=window.setTimeout((()=>{r({phrase:i,timeOut:!0})}),lo(t))}));return Promise.race([e.then((e=>(clearTimeout(n),e))),r])}getLastTokenType(e){return this.logger.info(`[${e}][getLastTokenType] lastTokenType=${this.lastTokenType}`),this.lastTokenType}updateTokenSettings(e){const{clientSupportsGenericTokenAPI:t,aadTokenExpirationTimeInSeconds:i,caeTokenExpirationTimeInSeconds:n,refreshTimeBeforeTokenTimeoutInSeconds:r,enablePublishTokenTelemetry:s,enableRefreshToken:a,forceClearExpiredTokens:o,enableRefreshTokenRetry:l,enableRefreshTokenRetryInSeconds:c}=e;this.logger.info(`updateTokenSettings ${JSON.stringify(e)}`),this.clientSupportsGenericTokenAPI=t??this.clientSupportsGenericTokenAPI,this.aadTokenExpirationTimeInSeconds=i??this.aadTokenExpirationTimeInSeconds,this.caeTokenExpirationTimeInSeconds=n??this.caeTokenExpirationTimeInSeconds,this.refreshTimeBeforeTokenTimeoutInSeconds=r??this.refreshTimeBeforeTokenTimeoutInSeconds,this.enablePublishTokenTelemetry=s??this.enablePublishTokenTelemetry,this.forceClearExpiredTokens=o??this.forceClearExpiredTokens,this.enableRefreshToken=a??this.enableRefreshToken,this.enableRefreshTokenRetry=l??this.enableRefreshTokenRetry,this.enableRefreshTokenRetryInSeconds=c??this.enableRefreshTokenRetryInSeconds}updateToken(e,t,i,n,r){if(this.logger.info(`[${n}][updateToken] UI replies with a token with factorsJson=${e} updateMetadata=${JSON.stringify(t)} tokenExpirySecSinceEpoch?=${r}`),t.error){this.logger.info(`[${n}][updateToken] UI replies with error ${t.error} for factorsJson ${e}`);for(const i of this.tokensPromiseMap[e])i.tokenRequestOptions.requestMetadataJson.causeId===n&&i.defered.reject({phrase:t.error?.phrase,errorCode:t.error?.code,errorSubCode:t.error?.subCode,causeId:n});return}if(!i){this.logger.info(`[${n}][updateToken] received empty token`);for(const t of this.tokensPromiseMap[e])t.tokenRequestOptions.requestMetadataJson.causeId===n&&t.defered.reject({phrase:"Received empty token",causeId:n});return}if(r>oo()&&this.enableTokenCacheForGenericTokenAPI){this.logger.info(`[${n}][updateToken] caching Token with tokenType=${t.tokenType}`);const s={factorsJson:e,tokenType:t.tokenType,invalidToken:i};this.addToCache(t.tokenType,i,e,this.calculateTokenExpiry(n,s,r))}if(!this.tokensPromiseMap[e]){this.logger.warn(`[updateToken]: UI tries to update token with invalid factorsJson=${e}`);const i={responseCauseId:n,supportTokenApi:this.clientSupportsGenericTokenAPI,requestTokenFactors:e,tokenResponseTime:Date.now(),tokenRequestStatus:6,responseTokenType:t.tokenType};return void this.sendTokenTelemetry(i)}if(this.tokensPromiseMap[e]){const r=this.tokensPromiseMap[e];for(let s=r.length-1;s>=0;s--)(r[s]?.tokenRequestOptions.tokenType&t.tokenType)>0&&(r[s].defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),this.tokensPromiseMap[e].splice(s,1))}if(this.logger.info(`[${n}][updateToken] resolved and upateToken with factorsJson=${e} tokenType=${t.tokenType}`),0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e],4!==t.tokenType&&8!==t.tokenType&&1!==t.tokenType)return;if(Object.keys(this.tokensPromiseMap).length>0)for(const r of Object.values(this.tokensPromiseMap))for(let s=r.length-1;s>=0;s--){const a=r[s];a.tokenRequestOptions.factorsJson!==e&&(a.tokenRequestOptions.tokenType&t.tokenType)>0&&!a.tokenRequestOptions.isUnauthorized&&(a.defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),r.splice(s,1))}for(const e of Object.keys(this.tokensPromiseMap))0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e];const s=r-oo();this.startTokenRefreshTimer(s>=0?lo(s):0)}setTokenRequiredCallBack(e){this.tokenCallback=e}setDisableTimerFlag(e){this.logger.info(`[setDisableTimerFlag] set disableTimerFlag to ${e}`),this.stopTimerFlag=e}sendTokenTelemetry(e){if(!this.enablePublishTokenTelemetry)return;const t={};t[Id]=JSON.stringify(e),this.telemetryManager?(this.logger.info("[sendTokenTelemetry] sending token telemetry:",t),this.telemetryManager.sendEvent(rl,t)):this.logger.warn("[sendTokenTelemetry] telemetryManager is undefined, cannot send token telemetry")}dispose(){this.cacheTimers&&this.cacheTimers.dispose()}},Dd=class{constructor(e){this.piiScrubber=this.getPiiScrubber(e)}scrubParticipantsList(e){const t=[];return Array.isArray(e)&&e.forEach((e=>t.push(this.scrubMriOrOmit(e)))),t}scrubMriOrOmit(e){return"string"==typeof e?this.piiScrubber.mri(e):this.piiScrubber.omit(e)}getPiiScrubber(e){return e&&"function"==typeof e.omit&&"function"==typeof e.mri?e:{omit:()=>"<pii:omit/>",mri:()=>"<pii:mri/>"}}},kd=p(Z);function Od(e){switch(e){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 Nd(e){switch(e){case"audio":return 0;case"video":return 1;case"applicationsharing-video":case"xapplicationsharing-video":return 2;case"data":return 3;default:return}}function Ld(e,t){return e.endpoints?.endpointDetails.find((e=>e.participantId===t))}function xd(e,t){return e.participants.find((e=>function(e,t){return e.endpoints?.endpointDetails?.some((e=>e.participantId===t))??!1}(e,t)))}function Fd(e){return!!e?.meetingGroupDetails?.groups&&Object.keys(e.meetingGroupDetails.groups).some((e=>"stagingGroup"===e))}function Ud(e,t){let i=-1;try{if(e.endpoints)e:for(const n of e.endpoints.endpointDetails)if(void 0!==n?.mediaStreams){for(const e of n.mediaStreams)if(Nd(e.type)===t){i=e.sourceId;break e}}else i=Ur}catch(e){return-1}return i}function Bd(e,t,i){try{if(!e.endpoints)return;for(const n of e.endpoints.endpointDetails)if(n?.mediaStreams)for(const e of n.mediaStreams)if(i===e.sourceId&&Nd(e.type)===t)return n.participantId??null;return}catch(e){return}}function Vd(e){return"sendonly"===e.direction&&"applicationsharing-video"===e.label}function Hd(e){if(e.endpoints?.endpointDetails)return 1===e.endpoints.endpointDetails.length?e.endpoints.endpointDetails[0].participantId:e.endpoints.endpointDetails.find((e=>e?.mediaStreams?.some(Vd)))?.participantId}function $d(e){let t={};if(e.stateId)t.result=e.stateId;else if(e.results){const{results:i}=e;1===i.length&&i[0].stateId&&(t.result=i[0].stateId);const n={};e.results.forEach((e=>{const{result:i}=e,r=function(e){return e.participantId||e.participant&&e.participant.id}(e);(void 0===t.code||i.code>t.code)&&(t.code=i.code,t.subCode=i.subCode),n[r]=e})),t.result=JSON.stringify(n)}else e.result&&(t={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode,resultCategories:e.result.resultCategories},e.additionalDetail&&(t.result=e.additionalDetail));return t}var jd=class{constructor(e,t){this.broadcastContext=null,this.broadcastControllerUrl="",this.broadcastCallbackUrl="",this.broadcastState=null,this.setContext=(e=null)=>{this.logger.info("BroadcastSession :: set broadcast context",e),this.broadcastContext=e},this.getContext=()=>(this.logger.info("BroadcastSession :: get broadcast context",this.broadcastContext||null),this.broadcastContext||null),this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[Broadcast]"))}handleBroadcastStateChanged(e){const t=e.body;this.broadcastState=t;const i=Qa(e);this.signalingSession.telemetryHelper.recordIncomingEvent("BroadcastStateChanged",e),this.logger.info(`[${i}] broadcast state changed=${this.broadcastState}`),this.updateBroadcastMetadata(i)}updateBroadcastCallbackUrl(e){const t=Ra(this.signalingSession,ra.CONV_BROADCAST_UPDATE);this.broadcastCallbackUrl!==t&&(this.broadcastCallbackUrl=t,this.logger.info(`[${e}] broadcast callback url changed=${this.broadcastCallbackUrl}`),this.updateBroadcastMetadata(e))}handleBroadcastDetailsChanged(e,t){this.signalingSession.telemetryHelper.recordEvent("UpdateBroadcastDetails",{causeId:t}),e.activeModalities&&e.activeModalities.broadcast&&e.activeModalities.broadcast.controller!==this.broadcastControllerUrl&&(this.broadcastControllerUrl=e.activeModalities.broadcast.controller,this.broadcastAdditionalData=e.activeModalities.broadcast,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.signalingSessionCallback.onBroadcastMeetingConnected(wa.SUCCESS_TRANSACTION_END,t),this.updateBroadcastMetadata(t)),!this.broadcastControllerUrl||e.activeModalities&&e.activeModalities.broadcast||(this.broadcastControllerUrl="",this.broadcastContext=null,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.updateBroadcastMetadata(t),this.signalingSessionCallback.onBroadcastMeetingEnded(wa.SUCCESS_TRANSACTION_END,t))}handleAddBroadcastModalitySuccess(e,t){this.logger.info(`[${t}][handleAddBroadcastModalitySuccess]`)}handleAddBroadcastModalityFailure(e,t){this.logger.info(`[${t}][handleAddBroadcastModalityFailure]`);const i={...e.modalityFailure.broadcast};this.signalingSessionCallback.onBroadcastMeetingEnded(i,t)}updateBroadcastMetadata(e){const t={broadcastControllerUrl:this.broadcastControllerUrl,broadcastStateCallbackUrl:this.broadcastCallbackUrl,broadcastState:this.broadcastState,broadcastAdditionalData:this.broadcastAdditionalData};this.logger.info(`[${e}] update broadcast metadata=${t}`),this.signalingSessionCallback.onBroadcastMeetingUpdated&&this.signalingSessionCallback.onBroadcastMeetingUpdated(t,e)}},Gd=class{constructor(e){this._signalingSession=e,this.baseUrl="http://broker.invalid/",this.currentSubscriptionUrl=null,this._currentSubscriptionTimeoutInSec=30,this._subscribers=[],this._disposed=!1,this._reportedResultCount=0,this._subscriptionRetryBackoffInSec=5,this._notifySubscribers=e=>{this._logger.info("_notifySubscribers"),Promise.resolve().then((()=>{e.split(",").forEach((e=>{const t=function(e){const t=e.split(/\r?\n\r?\n/),i=t[0].split(/\r?\n/),n=t[1].split(/\r?\n/),r=i.shift().split(" "),s=r[0],a=r[1]||"",o=new Pa;for(const e of i)try{const[t,i]=e.split(":").map((e=>Js.trim(e)));o.set(t,i)}catch(t){throw new Error(`Malformed header: ${e+t}`)}return{url:a,headers:o,method:s,body:n.join("")}}(eo(e));let i=t.body;Za(t.headers)&&Xa(t.headers)&&(i=eo(i));const n={url:t.url,body:JSON.parse(i),headers:t.headers};this._logger.info("message length=",i.length,"n. of subscribers",this._subscribers.length),this._subscribers.forEach((e=>e(n)))}))})).catch((e=>{this._logger.error("_notifySubscribers, failed to decode message",e),this._signalingSession.telemetryHelper.recordEvent("BrokerDecodePayloadFailure")}))},this._subscribeToBroker=(e,t)=>{if(this._disposed)return void this._logger.warn("_subscribeToBroker, disposed, ignore subscription");const i=Na();this._logger.info("_subscribeToBroker, url: ",e,",timeout in sec",t),this.currentSubscriptionUrl=e,this._currentSubscriptionTimeoutInSec=t,this._clearAllPendingTimeouts(),this._setSubscriptionTimeout(t),this._signalingSession.http.sendGetRequest({url:this.currentSubscriptionUrl,requestName:Zo.BROKER_SUBSCRIBE.name,customHeaders:this._getBrokerRequestHeaders(i),payload:null,skipHttpTelemetry:!this._reportSubscriptionInTelemetry(),causeId:Na(),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(Zo.BROKER_SUBSCRIBE.name,Na())},this._setSubscriptionTimeout=e=>{this._cancelRequestTimer=Qt.build((()=>{this._disposed||(this._signalingSession.http.hasPendingRequest(Zo.BROKER_SUBSCRIBE.name)?(this._logger.warn("timeout subscription"),this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionTimeout"),this._signalingSession.http.cancelRequestIfPending(Zo.BROKER_SUBSCRIBE.name,Na())):this._logger.error("Unable to resolve timeout deferred, it is not defined!"))}),"TIMEOUT").start(1e3*e)},this._handleSubscriptionSuccess=e=>{if(this._disposed)this._logger.warn("_handleSubscriptionSuccess, disposed, ignore subscription success");else if(this._reportSubscriptionInTelemetry(e)&&this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionSuccessful"),e?.response){const t=e.response;this._logger.info("_handleSubscriptionSuccess, response",t),t.message&&this._notifySubscribers(t.message);const i=t.nextSubscribeUrl||this.currentSubscriptionUrl,n=t.expirationTimeInSec||this._currentSubscriptionTimeoutInSec;this._subscribeToBroker(i,n)}else this._logger.info("_handleSubscriptionSuccess, empty response")},this._handleSubscriptionFailure=e=>{if(this._disposed)return void this._logger.warn("_handleSubscriptionFailure, disposed, ignore subscription");if(e.status>=400&&e.status<500&&401!==e.status&&this.isNotNetworkErrors(e.status))return void this._logger.warn(`_handleSubscriptionFailure, received status ${e.status}, stop subscribing`);const t=je(e);this._logger.error("_handleSubscriptionFailure failed, re-subscribing",t),this._reportSubscriptionInTelemetry()&&this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionFailed"),this._retryRequestTimer=Qt.build((()=>{this._subscribeToBroker(this.currentSubscriptionUrl,this._currentSubscriptionTimeoutInSec)}),"RETRY").start(1e3*this._subscriptionRetryBackoffInSec)},this._reportSubscriptionInTelemetry=e=>(this._reportedResultCount++,this._reportedResultCount<=1),this._getBrokerRequestHeaders=e=>{const t=new Pa;return t.set(wa.HEADERS.CONTENT_TYPE,wa.CONTENT_TYPE.JSON),this._signalingSession.signalingAgentConfig.brokerRequestBatching&&t.set(wa.HEADERS.BROKER_USE_BATCHING_HEADER_NAME,"1"),t},this._logger=this._signalingSession.logger.createChild("Broker"),this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration?.brokerRetryBackOffInSec&&(this._subscriptionRetryBackoffInSec=this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration.brokerRetryBackOffInSec)}subscribeToBroker(e){this._logger.info("subscribeToBroker called."),this._abortPendingRequest(),this._clearAllPendingTimeouts(),this._subscribeToBroker(e,this._currentSubscriptionTimeoutInSec)}onBrokerMessage(e){this._logger.info("onBrokerMessage callback added"),this._subscribers.push(e)}dispose(){this._disposed=!0,this._logger.info("dispose"),this._subscribers=[],this._clearAllPendingTimeouts(),this._abortPendingRequest()}isNotNetworkErrors(e){return 490!==e&&496!==e&&498!==e&&499!==e}},qd=class{constructor(e){this.requests={},this.logger=e}clear(e,t){const i=t||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{try{const n=parseInt(t,10);Object.keys(this.requests[n]).forEach((t=>{this.rejectOperation(n,t,e,i)}))}catch(e){this.logger.warn(`CallOperations: clear error = ${e}`)}}))}hasOperation(e,t){return this.requests.hasOwnProperty(e.valueOf())&&this.requests[e.valueOf()].hasOwnProperty(t)}getAllOperations(){return this.requests}getOperation(e,t){return this.hasOperation(e,t)?this.requests[e.valueOf()][t]:null}setOperation(e,t,i){return!this.hasOperation(e,t)&&(this.hasOwnProperty(e.valueOf())||(this.requests[e.valueOf()]={}),this.requests[e.valueOf()][t]=i,!0)}rejectOperation(e,t,i,n){if(this.hasOperation(e,t)){const i=e.valueOf(),r=this.requests[i][t].promise;delete this.requests[i][t],r.reject(n)}}resolveOperation(e,t,i,n){if(this.hasOperation(e,t)){const n=e.valueOf(),r=this.requests[n][t].promise;delete this.requests[n][t],r.resolve(i)}}},zd=class{constructor(e){this.logger=e,this.localRequests=new qd(e)}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}hasPendingOperation(e,t,i){return this.logger.info(`[${i}][hasPendingOperation] ${e} ${De(t)}}`),this.localRequests.hasOperation(e,t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${t} reason: ${i} endCode: ${n}`),this.localRequests.rejectOperation(e,t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${De(t)}`),this.localRequests.resolveOperation(e,t,i,n)}setPendingOperation(e,t,i,n){return this.logger.info(`[${n}][setPendingOperation] ${e} value: ${i}`),this.localRequests.setOperation(e,t,i)}rejectAllPendingOperations(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localRequests.clear(e,t)}};function Wd(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"content cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[]},contentSharing:{identifier:t.contentIdentifier,subject:t.subject,sessionState:t.sessionState,sequenceNumber:t.sequenceNumber,links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}function Kd(e){return Ua(e,"signalingSession cannot be null"),{payload:{contentSharing:{links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Jd(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{contentSharingTransactionEnd:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Yd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Qd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}}}}function Zd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Xd(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"sessionState cannot be null"),Ua(i,"sequenceNumber cannot be null"),{payload:{sessionUpdateSequenceNumber:i,sessionState:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}var eu=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 e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}};function tu(){return new eu}var iu=class{constructor(e,t,i,n){this.signalingSession=e,this.correlationId=t,this.sessionId=null,this.fsmState=wa.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=wa.CONTENT_SHARING_FSM_STATE,this.logger=e.logger.createChild((()=>`[${this.fsmState}][cs=${this.sessionId}][cc=${this.correlationId}]`)),i&&(this.sessionId=i),n&&(this.links=n)}start(e,t,i,n){if(this.logger.info(`[${n}][start]`),Fa(e,"Correct addModality url is not provided"),!this.checkState("start",this.FSM_STATES.IDLE,this.addSessionPromise))return Promise.reject(null);this.addSessionPromise=i,this.confirmInRosterPromise=to(),this.fsmState=this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.addTelemetryOperation(Zo.ADD_CONTENT_SHARING_MODALITY.name,{causeId:n});const r=new Pa;return r.set(wa.HEADERS.CONTENT_SHARING_CORRELATION_ID,this.correlationId),this.signalingSession.http.sendPostRequest({url:e,payload:Wd(this.signalingSession,t),requestName:Zo.ADD_CONTENT_SHARING_MODALITY.name,customHeaders:r,onceTrouterReady:()=>{this.startContentSharingTimer(n)},causeId:n}).then((()=>{this.disposed||(this.presenterMri=this.signalingSession.participantManager.localParticipant.id,this.isPresenter=!0)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${n}][start] error: ${je(t)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise(je(e),t.error)),Promise.reject(null)}))}delete(e,t){this.logger.info(`[${t}][delete]`);let i=!1;if(this.fsmState===this.FSM_STATES.IDLE)return this.logger.info(`[${t}][delete] skipped because state is already ${this.fsmState}`),e.resolve(),Promise.resolve();if(this.fsmState===this.FSM_STATES.CONTENT_SHARING_START_INITIATED)i=!0,this.rejectPendingPromise("Session delete called before start was finished");else if(!this.checkState("delete",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return Promise.reject(null);i||Fa(this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],"Correct controller url is not set"),this.removeSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_DELETE_INITIATED;const n=tu(),r=this.addTelemetryOperation(Zo.DELETE_CONTENT_SHARING.name,{causeId:t});return(i?Promise.resolve(void 0):this.signalingSession.http.sendDeleteRequest({url:this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],requestName:Zo.DELETE_CONTENT_SHARING.name,payload:Jd(this.signalingSession,{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED}),causeId:t})).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};i&&(e.skipReason="Session delete called before start was finished"),this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}})).catch((e=>{const i=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][delete] error: ${je(i)}`),!this.disposed){const e={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}return Promise.reject(null)}))}join(e,t){if(this.logger.info(`[${t}][join]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],"Correct joinContentSharing url is not provided"),!this.checkState("join",this.FSM_STATES.IDLE,e))return;this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.addSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_JOIN_INITIATED;const i=tu(),n=this.addTelemetryOperation(Zo.JOIN_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],payload:Kd(this.signalingSession),requestName:Zo.JOIN_CONTENT_SHARING.name,causeId:t}).then((e=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),this.processStartOrJoinSuccess(e.response),this.resolvePendingPromise(e.response)}})).catch((e=>{const r=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][join] error: ${je(r)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const s=r.error;this.rejectPendingPromise(je(e),s)}}))}takeControl(e,t){if(this.logger.info(`[${t}][takeControl]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL],"correct contentSharingTakeControl url is not provided"),!this.checkState("takeControl",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=tu(),n=this.addTelemetryOperation(Zo.TAKE_CONTROL_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL],payload:Yd(this.signalingSession),requestName:Zo.TAKE_CONTROL_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((t=>{if(!this.disposed){const r={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,r);const s={contentIdentifier:t.response.identifier,presenter:t.response.presenter.id,subject:t.response.subject||null,sessionState:t.response.sessionState||null};e.resolve(s)}})).catch((r=>{const s=Ka(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][takeControl] error: ${je(s)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const a=new Error(je(r));a.endCode=s.error,e.reject(a)}}))}updateSessionState(e,t,i){if(this.logger.info(`[${i}][updateSessionState]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],"Correct sendUpdateSessionState url is not provided"),!this.checkState("updateSessionState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,t))return;const n=tu(),r=this.addTelemetryOperation(Zo.UPDATE_SESSION_STATE_CONTENT_SHARING.name,{causeId:i});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],payload:Xd(this.signalingSession,e,this.nextClientSequenceNumberToUse++),requestName:Zo.UPDATE_SESSION_STATE_CONTENT_SHARING.name,causeId:i}).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};this.updateTelemetryOperation(r,e),t.resolve()}})).catch((e=>{const s=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${i}][updateSessionState] error: ${je(s)}`),!this.disposed){const i={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,i);const a=new Error(je(e));a.endCode=s.error,t.reject(a)}}))}updateParticipantState(e,t){if(this.logger.info(`[${t}][updateParticipantState]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],"correct confirmContentSharingView url is not provided"),!this.checkState("updateParticipantState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=tu(),n=this.addTelemetryOperation(Zo.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],payload:Zd(this.signalingSession),requestName:Zo.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((()=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),e.resolve()}})).catch((r=>{const s=Ka(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][updateParticipantState] error: ${je(s)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const a=new Error(je(r));a.endCode=s.error,e.reject(a)}}))}updateNotificationLinks(e){if(this.logger.info(`[${e}][updateNotificationLinks]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],"correct notificationLinks url is not provided"),!this.checkState("updateState",this.FSM_STATES.CONTENT_SHARING_CONNECTED))return;const t=tu(),i=this.addTelemetryOperation(Zo.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,{causeId:e});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],payload:Qd(this.signalingSession),requestName:Zo.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,withoutTrouter:!0,causeId:e}).then((()=>{if(!this.disposed){const e={success:!0,duration:t.duration()};this.updateTelemetryOperation(i,e)}})).catch((n=>{const r=Ka(n,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${e}][updateNotificationLinks] error: ${je(r)}`),!this.disposed){const e={success:!1,duration:t.duration()};this.updateTelemetryOperation(i,e)}}))}confirmInRoster(){this.confirmInRosterPromise&&this.confirmInRosterPromise.isPending&&(this.logger.info("Confirmed in roster"),this.confirmInRosterPromise.resolve())}handleAddModalitySuccess(e,t){return this.logger.info(`[${t}][handleAddModalitySuccess]`),this.checkState("handleAddModalitySuccess",this.FSM_STATES.CONTENT_SHARING_START_INITIATED)?e.modalitySuccess&&e.modalitySuccess.contentSharing?(this.addTelemetryOperation(Mo,{causeId:t}),this.processStartOrJoinSuccess(e.modalitySuccess.contentSharing),this.confirmInRosterPromise.promise.then((()=>{delete this.confirmInRosterPromise,this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.resolvePendingPromise(e.modalitySuccess.contentSharing)})),!0):(this.addTelemetryOperation(Mo,{causeId:t,skipReason:"no content sharing blob"}),this.logger.info(`[${t}][handleAddModalitySuccess] ignored because modalitySuccess was missing or did not contain content sharing blob`),!1):(this.logger.info(`[${t}][handleAddModalitySuccess] ignored because session is not waiting to start`),!1)}handleAddModalityFailure(e,t){if(this.logger.info(`[${t}][handleAddModalityFailure]`),!this.checkState("handleAddModalityFailure",[this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.FSM_STATES.CONTENT_SHARING_CONNECTED]))return!1;if(!e.modalityFailure||!e.modalityFailure.contentSharing)return this.addTelemetryOperation(Do,{causeId:t,skipReason:"no content sharing blob"}),!1;const i=e.modalityFailure.contentSharing;this.addTelemetryOperation(Do,{reason:i,causeId:t});const n={...i};return this.sendTelemetryData(n),this.rejectPendingPromise(n.phrase,n),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),!0}handleStartFromRoster(e,t){this.logger.info(`[${t}][handleStartFromRoster]`),this.addTelemetryOperation("ContentSharingStartFromRoster",{causeId:t})}handleStopFromRoster(e,t){this.logger.info(`[${t}][handleStopFromRoster]`),this.addTelemetryOperation("ContentSharingEndFromRoster",{causeId:t}),this.sendTelemetryData(e)}handleStop(e,t){if(this.logger.info(`[${t}][handleStop]`),this.isSelfInitiatedAction(e))return this.logger.info(`[${t}][handleStop]handleStop skipped because session was ended by self`),!1;const i={...e.contentSharingTransactionEnd};return this.addTelemetryOperation("HandleContentSharingEnd",{causeId:t}),this.sendTelemetryData(i),!0}handleUpdate(e,t){return this.logger.info(`[${t}][handleUpdate]`),e.sequenceNumber<=this.lastUpdateSequenceNumber?(this.logger.info(`handleUpdate skipped because of old sequence number: last received ${this.lastUpdateSequenceNumber}, update contained ${e.sequenceNumber}`),this.addTelemetryOperation(Ro,{causeId:t,skipReason:"old sequence number"}),!1):(this.lastUpdateSequenceNumber=e.sequenceNumber,this.isPresenter=e.presenter.id===this.signalingSession.participantManager.localParticipant.id,this.addTelemetryOperation(Ro,{causeId:t}),!0)}dispose(e,t){this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.rejectPendingPromise("call ended",e||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED}),this.addTelemetryOperation(wo,{causeId:t}),this.sendTelemetryData(e)}rejectPendingPromise(e,t){this.logger.info("rejectPendingPromise");const i=new Error(e);t&&(i.endCode=t),this.removeSessionPromise&&(this.removeSessionPromise.reject(i),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.reject(i),this.addSessionPromise=null)}resolvePendingPromise(e){this.logger.info("resolvePendingPromise");let t=null;e&&(t={sessionId:e.sessionId,correlationId:e.contentSharingCorrelationId,contentIdentifier:e.identifier,presenter:e.presenter.id,subject:e.subject||null,sessionState:e.sessionState||null}),this.removeSessionPromise&&(this.removeSessionPromise.resolve(t),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.resolve(t),this.addSessionPromise=null)}processStartOrJoinSuccess(e){this.logger.info("processStartOrJoinSuccess"),this.sessionId=e.sessionId,this.fsmState=this.FSM_STATES.CONTENT_SHARING_CONNECTED,this.lastUpdateSequenceNumber=-1,this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER]=e.links.contentSharingController,this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL]=e.links.takeControl,this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE]=e.links.updateSessionState,this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE]=e.links.sync,this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[wa.LINKS.CONTENT_SHARING_LEAVE]=e.links.leave}checkState(e,t,i){let n;if(n="string"==typeof t?this.fsmState===t:t.indexOf(this.fsmState)>-1,n)return!0;{const n=`${e} requires state ${t}, but state is ${this.fsmState}`;return this.logger.error(n),i&&i.reject(n),!1}}isSelfInitiatedAction(e){return e.presenter.participantId===this.signalingSession.participantManager.localParticipant.participantId}startContentSharingTimer(e){this.logger.info("startContentSharingTimer"),this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY,(()=>{this.addTelemetryOperation("AddModalityTimeout",{causeId:e}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise("timed out waiting for ContentSharing to start",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT})}),wa.TIMEOUT_VALUES_IN_SECONDS.ADD_MODALITY_TIMEOUT)}addTelemetryOperation(e,t){return this.signalingSession.telemetryHelper.addContentSharingOperation(this.correlationId,e,t)}updateTelemetryOperation(e,t){this.signalingSession.telemetryHelper.updateContentSharingOperation(this.correlationId,e,t)}sendTelemetryData(e){this.signalingSession.telemetryHelper.sendContentSharingTelemetryData(this.correlationId,this.signalingSession.sessionId,this.isPresenter,e,this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],this.sessionId)}},nu=class{constructor(e,t){this.contentSharingToStartCallWith=null,this.contentSharingSessions={},this.DEFAULT_STOP_REASON={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.REMOTE_USER_INITIATED},this.DEFAULT_STOP_ID="8:unknown",this.deleteContentSharingAsync=(e,t)=>{this.logger.info(`[${t}][deleteContentSharingAsync]`);const i=to();let n=this.contentSharingSessions[e];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===e&&(n=this.pendingSessionToStart),n){const r=()=>{this.contentSharingSessions[e]&&delete this.contentSharingSessions[e]};n.delete(i,t).then(r,r)}else this.rejectBecauseOfMissingSession(e,i);return i.promise},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[ContentSharingManager]")),this.lastProcessedSequenceNumber=-1,this.lastProcessedSequenceNumberForParticipant={}}startContentSharingAsync(e,t,i,n,r,s,a){if(this.logger.info(`startContentSharingAsync called for: ${e}`),this.pendingSessionToStart){const e="There is already a ContentSharing session start pending";return this.logger.error(e),Promise.reject(new Error(e))}const o={contentIdentifier:e,subject:i||null,sessionState:t||null,sequenceNumber:1},l=to(),c=new iu(this.signalingSession,a||La());return this.pendingSessionToStart=c,r?(this.logger.info("Call connected, send content sharing request out immediately"),c.start(n,o,l,s)):(this.logger.info("Content sharing is to be started when startOutgoingCall is called"),c.addSessionPromise=l,c.fsmState=wa.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED,this.contentSharingToStartCallWith=o),l.promise.then((()=>{this.contentSharingSessions.hasOwnProperty(c.correlationId)||(this.contentSharingSessions[c.correlationId]=c),this.pendingSessionToStart=null})).catch((()=>{this.pendingSessionToStart=null})),l.promise}joinContentSharingAsync(e,t){this.logger.info(`[${t}][joinContentSharingAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.join(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingSessionStateAsync(e,t,i){this.logger.info(`[${i}][updateContentSharingSessionStateAsync][sessionState=${JSON.stringify(t)}]`);const n=to(),r=this.contentSharingSessions[e];return r?r.updateSessionState(t,n,i):this.rejectBecauseOfMissingSession(e,n),n.promise}takeContentSharingControlAsync(e,t){this.logger.info(`[${t}][takeContentSharingControlAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.takeControl(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingParticipantStateAsync(e,t){this.logger.info(`[${t}][updateContentSharingParticipantStateAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.updateParticipantState(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingNotificationLinksAsync(e){this.logger.info(`[${e}][updateContentSharingNotificationLinksAsync]`);for(const t of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(t)){const i=this.contentSharingSessions[t];i&&i.updateNotificationLinks(e)}}getContentSharingInfoToStartSharing(){if(this.contentSharingToStartCallWith){const e=this.pendingSessionToStart,t=wa.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED;e&&e.fsmState===t||(this.contentSharingToStartCallWith=null,this.pendingSessionToStart=null)}return this.contentSharingToStartCallWith}dispose(e,t){this.logger.info(`[${t}][dispose]`);for(const i of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(i)){const n=this.contentSharingSessions[i];n&&n.dispose(e,t)}}handleContentSharingUpdate(e){const t=e.body,i=Qa(e),n=this.contentSharingSessions[t.contentSharingCorrelationId];n?n.handleUpdate(t,i)&&this.signalingSessionCallback.onContentSharingUpdated({sessionId:t.sessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:t.presenter.id,subject:t.subject||null,sessionState:t.sessionState||null},i):this.logger.info(`[${i}][handleContentSharingUpdate][failed][reason=no session with correlation ID ${t.correlationId}]`)}handleAddModalitySuccess(e,t){this.logger.info(`[${t}][handleAddModalitySuccess]`);const i=this.pendingSessionToStart;i?i.handleAddModalitySuccess(e,t):this.logger.info(`[${t}][handleAddModalitySuccess]Ignoring handleAddModalitySuccess because not waiting for one`)}handleAddModalityFailure(e,t){this.logger.info(`[${t}][handleAddModalityFailure]`);const i=this.pendingSessionToStart;i?i.handleAddModalityFailure(e,t):this.logger.info(`[${t}][handleAddModalityFailure]Ignoring handleAddModalityFailure because not waiting for one`)}handleIncomingContentSharingFromRoster(e,t,i){if(this.logger.info(`[${i}] handleIncomingContentSharingFromRoster: isFullRoster ${t} content ${je(e)}`),("MultiPartyEndpoint"===e.type||t)&&this.lastProcessedSequenceNumber>e.sequenceNumber)return void this.logger.info(`[${i}] handleIncomingContentSharingFromRoster invalid roster current sequenceNumber ${e.sequenceNumber} lastProcessedSequenceNumber ${this.lastProcessedSequenceNumber}`);const{sessionsWithPresenters:n,sessionsWithoutPresenters:r}=this.parseContentSharingSessionsFromRoster(e);this.startSessionsFromRoster(n,i),this.stopSessionsFromRoster(r,i),this.lastProcessedSequenceNumber=e.sequenceNumber}handleContentSharingEnd(e){const t=e.body,i=Qa(e);this.logger.info("handleContentSharingEnd : ",je(t));const n=this.contentSharingSessions[t.contentSharingCorrelationId];if(!n)return void this.logger.info("Ignoring contentSharingEnd since there is no corresponding sharing ongoing");if(!n.handleStop(t,i))return;const r={...t.contentSharingTransactionEnd};this.raiseContentSharingStopped(t.contentSharingCorrelationId,i,t.presenter.id,r)}parseContentSharingSessionsFromRoster(e){const t={},i={},n=new Set;for(const i of Object.keys(e.participants)){const r=e.participants[i];if("Delta"===e.type&&this.lastProcessedSequenceNumberForParticipant.hasOwnProperty(i)&&r.version<=this.lastProcessedSequenceNumberForParticipant[i])continue;if(r.version=r.version||-1,this.lastProcessedSequenceNumberForParticipant[i]=r.version,n.add(r.details.id),!r.endpoints)continue;const s=this.signalingSession.participantManager.localParticipant.participantId;for(const e of Object.keys(r.endpoints)){const i=r.endpoints[e],n=i?.contentSharing?.sessionInformation;"presenter"===n?.role&&(t[n.contentSharingCorrelationId]={presenterId:r.details.id,sessionInfo:n,selfEndpointIsPresenter:i.participantId===s})}}for(const e of Object.keys(this.contentSharingSessions))!t[e]&&n.has(this.contentSharingSessions[e].presenterMri)&&(i[e]=this.contentSharingSessions[e]);return{sessionsWithPresenters:t,sessionsWithoutPresenters:i}}stopSessionsFromRoster(e,t){this.logger.info(`[${t}][stopSessionsFromRoster]`);for(const i of Object.keys(e))this.logger.info(`[${t}][stopSessionsFromRoster] stopping session with correlationId ${i}`),this.stopSession(e[i],t)}stopSession(e,t){this.logger.info(`[${t}][stopSession] Stopping session ${e.sessionId}`),e.handleStopFromRoster(this.DEFAULT_STOP_REASON,t),this.raiseContentSharingStopped(e.correlationId,t)}startSessionsFromRoster(e,t){this.logger.info(`[${t}][startSessionsFromRoster]`);for(const i of Object.keys(e)){this.logger.info(`[${t}][startSessionsFromRoster]`);const n=this.contentSharingSessions[i],r=e[i];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===i?this.pendingSessionToStart.confirmInRoster():n&&n.confirmInRoster(),n)n&&(this.contentSharingSessions[i].presenterMri=r.presenterId,this.logger.info(`[${t}][startSessionsFromRoster]Session ${i} is already present locally`));else{if(r.selfEndpointIsPresenter){this.logger.info(`[${t}][startSessionsFromRoster]This endpoint is presenting, dont fire callback`);continue}this.logger.info(`[${t}][startSessionsFromRoster]New sharing session found. Raising ContentSharingStarted`),this.raiseContentSharingStarted(r.presenterId,r.sessionInfo,t).handleStartFromRoster(r.presenterId,t)}}}raiseContentSharingStopped(e,t,i,n){this.logger.info(`[${t}][raiseContentSharingStopped]`),this.signalingSessionCallback.onContentSharingStopped({sessionId:this.contentSharingSessions[e].sessionId,correlationId:e,endedBy:i||this.DEFAULT_STOP_ID,reason:n||this.DEFAULT_STOP_REASON},t),delete this.contentSharingSessions[e]}raiseContentSharingStarted(e,t,i){this.logger.info(`[${i}][raiseContentSharingStarted]`);const n=new iu(this.signalingSession,t.contentSharingCorrelationId,t.contentSharingSessionId,{[wa.LINKS.CONTENT_SHARING_CONTROLLER]:t.contentSharingController});n.presenterMri=e,this.contentSharingSessions[n.correlationId]=n;const r={sessionId:t.contentSharingSessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:e,subject:t.subject||null,sessionState:t.sessionState||null};return this.signalingSessionCallback.onContentSharingStarted(r,i),n}rejectBecauseOfMissingSession(e,t){const i=`There is no ContentSharing session with the correlation ID ${e}`;this.logger.error(i),t&&t.reject(new Error(i))}},ru={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}},su={CallSetup:{requestHedgingCapability:["disabled"],hedgeDelayMs:4e3},Other:{requestHedgingCapability:["disabled"]},BrokerSubscribe:{requestHedgingCapability:["disabled"]}},au="HttpRequestDispatcherFactory";function ou(e,t,i){t?.signalingSession?t.signalingSession.telemetryHelper?.addTokenTelemetry(e,t?.tokenTelemetryData):i?.info("[reportTokenTelemetryData] signaling session is not available, cannot send token telemetry")}function lu(e,t){const{signalingSession:i,operation:n,causeId:r,data:s,customHeaders:a={},forceFetchToken:o,tokenRequestOptions:l,useFetch:c,fetchUseKeepAlive:d}=e;if(i.disposed)return Promise.reject("Session already disposed");const u=e=>{const t="string"==typeof e?new Error(e):e;throw i.signalingAgent.clientSupportsGenericTokenAPI?e.timeOut?t.tokenTimeoutError=!0:(t.tokenError=!0,t.tokenErrorSubCode=e.errorSubCode):t.skypeTokenError=!0,t};let h=!1;const g={signalingSession:i,tokenTelemetryData:{}};return i.signalingAgent.authTokenManager.getToken(r,o,l,g).catch((n=>(ou(e.requestId,g,t),!o&&function(e){const t=io(e.signalingAgentConfig.trouterServiceProvider);return 3===t||1===t}(i)&&i.signalingAgentConfig.attemptHttpRequestWithCachedSkypetoken&&i.signalingAgent.authTokenManager.getLastToken(r)?(h=!0,t?.info(`[${r}][requestBuilder] failed to fetch token, using lastToken`),Promise.resolve(i.signalingAgent.authTokenManager.getLastToken(r))):(t?.info(`[${r}][requestBuilder] getToken failed with error ${n}`),u(n))))).then((o=>{if(i.disposed)throw new Error("token returned too late. Object is already disposed");ou(e.requestId,g,t);const l=new Pa;if(l.set(wa.HEADERS.CORRELATION_ID,i.correlationId),l.set(wa.HEADERS.MESSAGE_ID,function(e){return e&&/^[a-z0-9]{8}$/.test(e)?e+La().substr(8):La()}(r)),l.set(wa.HEADERS.CLIENT_USER_AGENT,i.signalingAgentConfig.clientInformation),i.signalingAgent.clientSupportsGenericTokenAPI){const e=i.signalingAgent.authTokenManager.getLastTokenType(r);switch(i.signalingAgentConfig.disableTokenMigrationHeader||l.set(wa.HEADERS.TOKEN_MIGRATION,"True"),e){case 8:case 4:l.set(wa.HEADERS.AUTHORIZATION,`${wa.HEADERS.BEARER_KEYWORD} ${o}`),l.delete(wa.HEADERS.SKYPE_TOKEN);break;case 1:l.set(wa.HEADERS.SKYPE_TOKEN,o),l.delete(wa.HEADERS.AUTHORIZATION);break;default:throw new Error(`Error in RequestBuilder. TokenType ${e} is not supported`)}}else l.set(wa.HEADERS.SKYPE_TOKEN,o);const u=i.participantManager.localParticipant;u&&(u.ring&&l.set(wa.HEADERS.RING,u.ring),u.region&&l.set(wa.HEADERS.REGION,u.region),u.partition&&l.set(wa.HEADERS.PARTITION,u.partition));const p=s?.payload?JSON.stringify(s.payload):null,m={headers:{...l?.getAll(),...a},payload:p,usedCachedSkypetoken:h,reporting:{serviceName:n?`${au}-${n}`:au},useFetch:c,fetchUseKeepAlive:d};return i.telemetryHelper.addNetworkOperationStarted(n),m})).catch(u)}var cu=class{constructor(e,t,i,n,r,s,a,o,l){this.causeId=e,this.logger=t,this.dispatcher=i,this.requestType=n,this.url=r,this.request=s,this.onRequestFailed=a,this.authRequiredCallback=o,this.settings=l,this.requestsSent=0,this.otherAttemptSuccessful=!1,this.pendingAttempts=[],this.hedgeDelayMs=3e3,this.hedgeMaxParallelAttempts=3,this.stopStandardRetryTimer=()=>{this.standardRetryTimer&&(this.standardRetryTimer.stop(),this.standardRetryTimer=null)},this.stopHedgeTimer=()=>{this.hedgeTimer&&(this.hedgeTimer.stop(),this.hedgeTimer=null)},this.stopAttemptTimeoutTimer=e=>{try{e.timeoutTimer&&(e.timeoutTimer.stop(),this.logger.info("attempt timer stopped"))}catch(e){this.logger.info(`stopAttemptTimeoutTimer error ${e}`)}},this.stopRequestTimer=()=>{try{this.requestTimer&&(this.requestTimer.stop(),this.logger.info("Request timer stopped"))}catch(e){this.logger.info(`stopRequestTimer error ${e}`)}this.requestTimer=null},this.canScheduleNextAttempt=()=>{if(this.stackError===wa.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 e=this.pendingAttempts.length<this.hedgeMaxParallelAttempts;return e||this.logger.info(`canScheduleNextAttempt enableRequestHedging attempts sent: ${this.pendingAttempts.length} max attempts: ${this.hedgeMaxParallelAttempts}`),e}{const e=this.requestsSent<this.settings.retryIntervalsMs.length;return e||this.logger.info(`canScheduleNextAttempt attempts sent: ${this.requestsSent} max attempts: ${this.settings.retryIntervalsMs.length}`),e}},this.scheduleNextRequest=e=>{this.settings.enableRequestHedging?(this.logger.info("scheduleNextRequest with hedging"),this.hedgeTimer=Qt.build((()=>{this.attempt(),this.canScheduleNextAttempt()&&this.scheduleNextRequest(!1)}),"HEDGE").start(this.getNextDelay(e))):(this.logger.info("scheduleNextRequest with retry"),this.standardRetryTimer=Qt.build((()=>{this.attempt()}),"RETRY").start(this.getNextDelay(e)))},this.standardizeFailedRequest=(e,t)=>{let i;const n=this.logger.createChild("[standardizeFailedRequest]");try{if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT)n.info("request timed out"),i=ta.REQUEST_TIMEOUT;else if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_ABORTED)n.info("request aborted"),i=ta.REQUEST_ABORTED;else if(t&&t.status===wa.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT)n.info("request attempt timed out"),i=ta.ATTEMPT_TIMEOUT;else if(t&&[wa.HTTP_STACK_ERROR.ATTEMPT_ABORTED,wa.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL].indexOf(t.status)>-1)n.info("request attempt aborted"),i=ta.ATTEMPT_ABORTED;else if(e){if(n.info(`request ${Je(e)}`),e.request?.response){const t=e;i={response:{..."string"==typeof t?.request?.response?t?.response?.data:t?.request?.response,headers:t.response?.headers},status:t.request.status,statusText:t.request.statusText,readyState:t.request.readyState}}else e.status||e.statusCode||e.response?i={response:e.response,status:[void 0,null,""].indexOf(e.status)>-1?e.statusCode:e.status,statusText:e.statusText,readyState:e.readyState}:(n.info("Local http stack error"),i={response:wa.CALL_END_SUB_CODE.LOCAL_HTTP_STACK_ERROR,status:wa.CALL_END_CODE.LOCAL_HTTP_STACK_ERROR,statusText:"LocalHTTPStackError",readyState:e.readyState||0});this.isBrowserOffline()&&0===i.status&&4===i.readyState&&(n.info("offline"),i={response:wa.HTTP_STACK_ERROR.CANNOT_CONNECT,status:wa.HTTP_STATUS_CODES.OFFLINE,statusText:"offline",readyState:i.readyState}),e.response?.message&&(e.response.message.operationFailure||e.response.message.broadcastOperationFailure)?i={response:e.response.message}:!e.response&&e.body?.operationFailure&&(i={response:e.body})}else n.info("no response"),i={response:wa.HTTP_STACK_ERROR.NONE,status:wa.HTTP_STATUS_CODES.OTHER,statusText:"Empty Response",readyState:0}}catch(e){n.info(`Failed to handle error ${e}`),i={response:"",status:wa.HTTP_STATUS_CODES.OTHER,statusText:"FailedToHandleError",readyState:0}}return i},this.hasPendingAttempts=()=>this.pendingAttempts.some((e=>e.pending)),this.getRequestFromStatus=e=>e?.request?.status||0,this.isBrowserOffline=()=>navigator&&!1===navigator.onLine,this.logger=t.createChild(`[${this.causeId}][Dispatcher]`),this.logger.info(`created request, url=${r}`),!isNaN(this.settings.hedgeDelayMs)&&this.settings.hedgeDelayMs>=500&&this.settings.hedgeDelayMs<=1e4&&(this.hedgeDelayMs=this.settings.hedgeDelayMs),!isNaN(this.settings.hedgeMaxParallelAttempts)&&this.settings.hedgeMaxParallelAttempts>=0&&this.settings.hedgeMaxParallelAttempts<=4&&(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(){return this.stackError=wa.HTTP_STACK_ERROR.NONE,this.logger.info("send api called"),this.requestTimer=Qt.build((()=>{this.stackError=wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT,this.cancelAllAttempts(wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT)}),"REQUEST_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perRequestTimeoutWithHedgingMs:this.settings.perRequestTimeoutMs),new Promise(((e,t)=>{this.resolve=e,this.reject=t,this.scheduleNextRequest(!0)}))}cancelRequest(){this.logger.info("cancelRequest"),this.stackError=wa.HTTP_STACK_ERROR.REQUEST_ABORTED,this.cancelAllAttempts(wa.HTTP_STACK_ERROR.ATTEMPT_ABORTED)}cancelOtherAttempts(e){this.pendingAttempts.splice(e-1,1),this.cancelAllAttempts(wa.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL)}cancelAllAttempts(e){this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.pendingAttempts.forEach((t=>{t.status=e,t.cancelDeferred.resolve(),this.stopAttemptTimeoutTimer(t)})),this.stopRequestTimer()}getRequestMethod(e){switch(e){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(e){const t=e&&this.isNotRetryable(e);if(this.logger.info("queueAttempt"),t||!this.canScheduleNextAttempt())return this.logger.info(`unable to retry isNotRetryable ${t} ${JSON.stringify(e)}`),this.stopHedgeTimer(),this.stopRequestTimer(),void(this.hasPendingAttempts()||(this.settings.reportPreviousErrorsForTimeout&&e===ta.ATTEMPT_TIMEOUT&&this.previousAttempt?this.reject(this.previousAttempt):this.reject(e)));if(this.isAuthFailedStatus(e)){this.logger.info("auth failed"),this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.stopRequestTimer();try{const t=e?.response?.headers,i=function(e){const t=Pa.getHeaderValue(e,wa.HEADERS.SKYPE_TOKEN);if(t)return t;const i=Pa.getHeaderValue(e,wa.HEADERS.AUTHORIZATION);if(i){const e=i.split(" ");if(2===e.length)return e[1]}}(this.request?.headers),n=e.response?.status===wa.HTTP_STATUS_CODES.UNAUTHORIZED&&e.response?.operationFailure?.subCode===wa.CALL_END_SUB_CODE.CONVERSATION_TERMINATION_INTERACTION_REQUIRED,r=await this.authRequiredCallback(t,i,{IPCAFailure:n});this.request=r}catch(t){return t.authCallBackFailure=!0,e.error=t,void this.reject(e)}}this.previousAttempt=e,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===wa.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful)return;const e=(new Date).getTime();this.requestsSent++;const t=this.requestsSent,i=to();this.request.timeout=i.promise;const n={cancelDeferred:i,status:wa.HTTP_STACK_ERROR.NONE,timeoutTimer:null,pending:!0},r=Qt.build((()=>{n.status=wa.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT,n.cancelDeferred.resolve()}),"ATTEMPT_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perAttemptTimeoutWithHedgingMs:this.settings.perAttemptTimeoutMs);n.timeoutTimer=r,this.pendingAttempts.push(n),this.getRequestMethod(this.requestType)(this.url,this.request).then((i=>{if(this.logger.info(`attempt successful, request response=${Ke(i)} status=${this.getRequestFromStatus(i)}`),this.otherAttemptSuccessful)throw"Other attempt succesful";if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_ABORTED)throw"Session disposed";if(!i)throw"Invalid response";n.pending=!1,this.otherAttemptSuccessful=!0,this.stopRequestTimer(),this.stopHedgeTimer(),this.stopAttemptTimeoutTimer(n),this.cancelOtherAttempts(t),this.resolve({success:!0,request:i.request,response:i.response,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()})})).catch((t=>{n.pending=!1,this.stopAttemptTimeoutTimer(n);const i=this.standardizeFailedRequest(t,n);this.logger.info(`attempt failed, request: ${Je(t)} status=${i.status}`),this.onRequestFailed({abandoned:this.otherAttemptSuccessful,success:!1,request:i,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()}),this.queueAttempt(i)}))}getNextDelay(e){let t;if(e)t=0;else if(this.settings.enableRequestHedging)t=this.hedgeDelayMs;else{if(!(this.requestsSent<=this.settings.retryIntervalsMs.length))throw"Unable to get next delay";t=this.settings.retryIntervalsMs[this.requestsSent-1]}return this.logger.info(`next delay= ${t} ms`),t}isRequestWithStatus(e,t){return!!e&&t.indexOf(e.status)>-1}isNotRetryable(e){return!no(e?.status)}isAuthFailedStatus(e){return this.isRequestWithStatus(e,[wa.HTTP_STATUS_CODES.UNAUTHORIZED])}},du={1:"POST",0:"GET",2:"PUT",3:"DELETE"},uu=class{constructor(e,t){this.signalingSession=e,this.callStartTime=t,this.pendingRequests={},this.sendGetRequest=e=>this.sendRequest(0,e),this.sendPostRequest=e=>this.sendRequest(1,e),this.sendPutRequest=e=>this.sendRequest(2,e),this.sendDeleteRequest=e=>this.sendRequest(3,e),this.cancelRequestIfPending=(e,t,i,n)=>{this.logger.info(`[${t}][cancelRequestIfPending]`),this.pendingRequests[e]?i?this.hasPendingRequest(e,i)&&this.cancelRequest(e,i,t,n):Object.keys(this.pendingRequests[e]).forEach((i=>this.cancelRequest(e,i,t,n))):this.logger.info(`[${t}][cancelRequestIfPending]no pending request with name=${e}`)},this.cancelAllRequests=e=>{this.logger.info(`[${e}][cancelAllRequests]`);const t=[];return Object.keys(this.pendingRequests).forEach((i=>{Object.keys(this.pendingRequests[i]).forEach((n=>{t.push(this.cancelRequest(i,n,e))}))})),Promise.all(t).catch((()=>{}))},this.hasPendingRequest=(e,t)=>!!this.pendingRequests[e]&&Boolean(t?this.pendingRequests[e][t]:this.pendingRequests[e]),this.cancelRequest=(e,t,i,n)=>{try{return this.pendingRequests[e][t].dispatcher&&this.pendingRequests[e][t].dispatcher.cancelRequest(),this.pendingRequests[e][t].aborted=!0,this.pendingRequests[e][t].errorDetails=n,this.logger.info(`[${i}][cancelRequest]Request=${e} aborted ${n?`with errorDetails ${JSON.stringify(n)}`:""}`),this.pendingRequests[e][t].requestPromise.catch((()=>{}))}catch(n){return this.logger.warn(`[${i}][cancelRequest]Unable to cancel request=${e}, requestId=${t}`),Promise.resolve()}},this.buildRequestTelemetry=(e,t,i,n)=>({name:`${du[e]}-${t.requestName}`,url:t.url,eventStart:i-this.callStartTime,trouterReady:-1,requestReady:-1,status:-1,attempts:[],rtt:-1,uid:t.requestId,causeId:t.causeId,requestDispatcherConfig:n,enableRequestHedging:this.shouldEnableRequestHedging(n)}),this.addPendingRequest=e=>(this.pendingRequests[e.requestName]||(this.pendingRequests[e.requestName]={}),this.pendingRequests[e.requestName][e.requestId]={dispatcher:null,requestPromise:null,aborted:!1},this.pendingRequests[e.requestName][e.requestId]),this.sendRequest=(e,t)=>{if(!t.url){this.logger.error(t.requestName,"Link does not exist");const e={code:wa.CALL_END_CODE.HTTP_OTHER_ERROR,subCode:wa.CALL_END_SUB_CODE.MISSING_REQUEST_URI,phrase:`Link does not exist for requestName: ${t.requestName}.`};return Promise.reject(e)}t.requestId||(t.requestId=La()),t.causeId||(t.causeId=Na());let i=!1,n=!1;const r=this.logger.createChild(`[${t.causeId}][${t.requestName}]`);r.info("[scheduled]");const s=this.getInternalHttpDispatcherConfig(t.requestName,t.operationType);let a;t.skipHttpTelemetry||(t.skipHttpTelemetry=!1);const o=tu(),l=(new Date).getTime(),c=[],d=this.buildRequestTelemetry(e,t,l,s),u=()=>{this.signalingSession.disposed?this.logger.info("Unable to record telemetry, session disposed"):this.signalingSession.telemetryHelper.updateNetworkRequest(d)},h=()=>{this.signalingSession.telemetryHelper.deleteNetworkRequest(d)};u();const g=(e,i,s)=>{if(!e?.request)return void this.logger.warn(t.requestName,"missing request details, unable to record for telemetry!");r.info(`[finished][status=${e.request.status}][statusText=${e.request.statusText}][retryCount=${e.attempt}]`);const a=e.request.status,o=e.request.response?.operationFailure?.subCode,c={status:a,statusSubCode:o||s,start:e.attemptStartTimestamp-l,end:e.attemptResponseTimestamp-l,online:io(this.signalingSession.signalingAgentConfig.trouterServiceProvider)};e.abandoned&&(c.abandoned=!0),e.request.statusText&&(c.statusText=e.request.statusText),!i&&n||(d.status=a,d.statusSubCode=s||o),(i||!n&&a>=200&&a<400)&&(n=!0),d.attempts.push(c),u()};if(this.hasPendingRequest(t.requestName,t.requestId))return this.logger.warn(t.requestName,t.requestId,"is already pending request!!"),this.pendingRequests[t.requestName][t.requestId].requestPromise;a=this.addPendingRequest(t);const p=(e,i,n,s)=>{if(e&&t.skipHttpTelemetry)return this.logger.info("Skipping telemetry"),void h();r.info(`[steps=${c}]`),this.pendingRequests[t.requestName][t.requestId].aborted&&(d.aborted=!0),this.hasPendingRequest(t.requestName,t.requestId)?(delete this.pendingRequests[i][n],Object.keys(this.pendingRequests[i]).length||delete this.pendingRequests[i]):this.logger.warn("Unable to clean up!"),this.signalingSession.disposed||(s&&(d.error=s),d.rtt=o.duration(),this.signalingSession.telemetryHelper.addNetworkOperationCompleted(t.requestName,e,o.duration()),u(),this.signalingSession.telemetryHelper.sendHttpTelemetryData(d.uid))},m=e=>(...i)=>{if(this.signalingSession.disposed){const e=`[${t.causeId}][${t.requestName}][failed][reason=Session disposed]`;throw r.info("[failed][reason=Session disposed]"),new Error(e)}if(this.hasPendingRequest(t.requestName,t.requestId)&&this.pendingRequests[t.requestName][t.requestId].aborted){let e;const i=`[${t.causeId}][${t.requestName}][failed][reason=request already aborted]`,n=this.pendingRequests[t.requestName][t.requestId].errorDetails;throw n?(e=n,e.phrase=i):e=i,r.info(`${i}`),new Error(JSON.stringify(e))}return e(...i)},f=m((()=>(c.push("[waitForTrouter]"),t.withoutTrouter?Promise.resolve():this.signalingSession.ensureMessageChannelReady(t.requestName)))),v=m((()=>(c.push("[trouterReady]"),d.trouterReady=o.duration(),t.onceTrouterReady&&t.onceTrouterReady(),u(),Promise.resolve()))),S=m((()=>{const i=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,n=this.signalingSession.signalingAgentConfig.enableFetchApi||t.useFetch,r=ao(this.signalingSession.signalingAgentConfig,i,e,t,!1,void 0,this.logger);return c.push("[buildRequest]"),lu({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,tokenRequestOptions:r,requestId:t.requestId,useFetch:n,fetchUseKeepAlive:t.fetchUseKeepAlive},this.logger)})),y=e=>{const t={request:{status:wa.HTTP_STATUS_CODES.OTHER,statusText:"Local error"},attempt:1,success:!1,attemptResponseTimestamp:(new Date).getTime(),attemptStartTimestamp:(new Date).getTime()};let n;e&&(e.skypeTokenError?(t.request={status:wa.CALL_END_SKYPE_TOKEN_ERROR.code,statusText:wa.CALL_END_SKYPE_TOKEN_ERROR.phrase},n=wa.CALL_END_SKYPE_TOKEN_ERROR.subCode):e.tokenError?(t.request={status:wa.CALL_END_TOKEN_ERROR.code,statusText:wa.CALL_END_TOKEN_ERROR.phrase},n=e.errorSubCode&&e.errorSubCode>0?e.errorSubCode:wa.CALL_END_TOKEN_ERROR.subCode):e.tokenTimeoutError&&(i?(t.request={status:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.code,statusText:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.phrase},n=wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.subCode,e.tokenInteractivityRequiredTimeout=!0):(t.request={status:wa.CALL_END_TOKEN_TIMEOUT_ERROR.code,statusText:wa.CALL_END_TOKEN_TIMEOUT_ERROR.phrase},n=wa.CALL_END_TOKEN_TIMEOUT_ERROR.subCode))),g(t,!1,n)},C=m((e=>(c.push("[failedToBuildRequestOptions]"),y(e),Promise.reject(e)))),T=m((e=>(c.push("[requestBuilt]"),d.requestReady=o.duration(),e.usedCachedSkypetoken&&(d.usedCachedSkypetoken=e.usedCachedSkypetoken),u(),Promise.resolve(e)))),E=(n,r,s)=>{c.push("[authRequired]"),s?.IPCAFailure&&(i=!0);const a=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,o=ao(this.signalingSession.signalingAgentConfig,a,e,t,!0,n,this.logger);return o.invalidToken=r,lu({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,forceFetchToken:!0,tokenRequestOptions:o,requestId:t.requestId},this.logger)},b=m((i=>{c.push("[sendRequest]");const n={...s,enableRequestHedging:this.shouldEnableRequestHedging(s),hedgeDelayMs:s.hedgeDelayMs,hedgeMaxParallelAttempts:this.signalingSession.signalingAgentConfig.hedgeMaxParallelAttempts,retryIntervalsMs:t.disableRetry||!s.retryIntervalsMs?[]:s.retryIntervalsMs,reportPreviousErrorsForTimeout:this.signalingSession.signalingAgentConfig.reportPreviousErrorsForTimeout},r=function(e){return new cu(e.causeId,e.logger,e.dispatcher,e.requestType,e.url,e.request,e.attemptFailureCallback,e.authRequiredCallback,e.settings)}({logger:this.logger,causeId:t.causeId,dispatcher:this.signalingSession.signalingAgentConfig.httpRequestDispatcher,url:t.url,request:i,requestType:e,authRequiredCallback:E,attemptFailureCallback:e=>{g(e,!1)},settings:n});return a.dispatcher=r,u(),r.sendRequest()})),_=m((async e=>(g(e,!0),r.info("[success]"),p(!0,t.requestName,t.requestId),e))),I=Promise.resolve().then(f).then(v).then(S).catch(C).then(T).then(b).then(_).catch((e=>{const i=je(e);r.info(`onFailure err:${i}`);let n=e;return e.error?.authCallBackFailure&&(n=e.error,r.info(`authCallBackerror:${je(n)}`),y(n)),p(!1,t.requestName,t.requestId,i),!e||e.readyState||e.status?r.info(`[failed][reason=${i}]`):r.info(`[failed][offline][reason=${i}]`),Promise.reject(n)}));return a.requestPromise=I,I},this.logger=this.signalingSession.logger.createChild("[HTTP]")}getInternalHttpDispatcherConfig(e,t="Other"){let i={...ru.Default,...su[t],...ru[e]};return this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap[t]}),this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap.Default,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap[e]}),this.logger.info(`getInternalHttpDispatcherConfig request type: ${e} config: ${Ge(i)}`),i}shouldEnableRequestHedging(e){return!!(this.signalingSession.getMeetingInfo()&&e.requestHedgingCapability.indexOf("enabledForMeetings")>-1)||!this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForP2PCalls")>-1||!!(this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForGroupCalls")>-1)||e.requestHedgingCapability.indexOf("enabled")>-1}};function hu(e,t,i){Ua(e,"signalingSession cannot be null");let n=[];i&&(n=Ha(i),e.telemetryHelper.addOutgoingModalities(n));const r=Na();return{payload:{mediaNegotiation:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAnswer:Ra(e,ra.MEDIA_ANSWER,r),rejection:Ra(e,ra.MEDIA_REJECTION,r)},mediaContent:t}}}}function gu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{mediaNegotiationFailure:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},code:t.code,subCode:t.subCode,phrase:t.phrase},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}function pu(e,t,i){Ua(e,"signalingSession cannot be null");let n=[];return i&&(n=Ha(i),e.telemetryHelper.addOutgoingModalities(n)),{payload:{mediaAnswer:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAcknowledgement:Ra(e,ra.MEDIA_ACKNOWLEDGEMENT)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}var mu=class{constructor(e,t,i){this.telemetryHelper=i,this.vbssInitiated=!1,this.disposed=!1,this.fsmState=wa.MEDIA_RENEGOTIATION_FSM_STATE.IDLE,this.fsmStateCauseId="",this.links={},this.renegotiationOffersSeenSoFar=[],this.isOutgoingRenegotiationInProgress=()=>this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION||this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.isIncomingRenegotiationInProgress=()=>this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION||this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.acceptRenegotiationAsync=(e,t,i)=>{this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.signalingSession.telemetryHelper.recordEvent("AcceptRenegotiation",{mediaTypes:t,causeId:i}),Fa(this.links[wa.LINKS.MEDIA_ANSWER],"MediaAnswer link not set");const n=to();switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,i);break;default:return this.logger.info(`[${i}][acceptRenegotiationAsync]there is no incoming media renegotiation offer to accept`),n.reject(new Error("there is no incoming media renegotiation offer to accept")),n.promise}return this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.MEDIA_ANSWER],payload:pu(this.signalingSession,e,t),requestName:Zo.SEND_MEDIA_ANSWER.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT,this.handleMediaAnswerAcknowledgmentTimeout.bind(this,i),wa.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT)},causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][acceptRenegotiationAsync] error: ${je(t)}`),this.disposed||this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),n.reject(new Error(`acceptRenegotiationAsync failed because : ${je(e)}`))})),n.promise},this.startRenegotiationAsync=(e,t,i,n)=>{this.logger.info(`[${n}][startRenegotiationAsync][mediaTypes=${i}]`),this.signalingSession.telemetryHelper.recordEvent("StartRenegotiation",{causeId:n,mediaTypes:i}),Fa(t,"MediaRenegotiation link not set");const r=to();switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed with no current outstanding renegotiations, previous negotiation causeId=${this.fsmStateCauseId}`),this.signalingSessionCallback.onMediaRenegotiationRejection(this.getGlareError(),n),Promise.resolve(null);default:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed on an established call`),r.reject(new Error("media renegotiation can only be performed on an established call")),r.promise}const s=i&&Ga(i,wa.MEDIA_TYPES.SCREEN_SHARER);return s?(this.vbssInitiated=!0,this.signalingSession.telemetryHelper.addVbssOperations(fd)):!s&&this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(vd)),this.signalingSession.http.sendPostRequest({url:t,payload:hu(this.signalingSession,e,i),requestName:Zo.START_RENEGOTIATION.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER,this.handleMediaAnswerTimeout.bind(this),wa.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_TIMEOUT)},causeId:n}).then((e=>{r.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${n}][startRenegotiationAsync] error: ${je(t)}`),!this.disposed){switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n)}this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER)}r.reject(new Error(`startRenegotiationAsync failed because : ${je(e)}`))})),r.promise},this.handleMediaAcknowledgment=(e,t)=>{this.signalingSession.telemetryHelper.recordEvent(fo,{causeId:t}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSession.saveMediaControllerLinksIfAny(e),this.signalingSession.saveUpdatedCallLinksIfAny(e),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!0,t)},this.onCallConnected=e=>{this.logger.info("onCallConnected"),this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,e)},this.handleMediaNegotiationFailure=e=>{const t=Qa(e);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleMediaNegotiationFailure",e),this.handleMediaNegotiationFailureInternal(e.body.mediaNegotiationFailure,e.origin,t)},this.handleMediaAnswer=(e,t)=>{switch(this.logger.info(`[${t}][handleMediaAnswer]`),this.signalingSession.telemetryHelper.recordEvent(vo,{causeId:t}),this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,t);break;default:return}this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER);let i=[];e.mediaAnswer.callModalities&&e.mediaAnswer.callModalities.length>0&&(i=Ha(e.mediaAnswer.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i));const n={provisional:!1,renegotiation:!0,mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaAnswer.mediaContent),mediaContent:e.mediaAnswer.mediaContent};this.signalingSession.http.sendPostRequest({url:e.mediaAnswer.links.mediaAcknowledgement,payload:null,requestName:Zo.SEND_MEDIA_ACKNOWLEDGEMENT.name,causeId:t}).catch((e=>{const i=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${t}][handleMediaAnswer] error: ${je(i)}`),this.signalingSession.disposed||this.signalingSession.telemetryHelper.recordEvent("HandleMediaAnswerFailed",{causeId:t})})),this.signalingSessionCallback.onAnswer(n,t)},this.handleMediaNegotiationOffer=e=>{const t=e.body,i=e.headers,n=Qa(e);this.logger.info(`[${n}][handleMediaNegotiationOffer]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleMediaOffer",e);const r=Ja(i,this.renegotiationOffersSeenSoFar);switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,n),this.raiseMediaRenegotiationOffer(t,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n),this.raiseMediaRenegotiationOffer(t,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:if(this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.supportMediaRetargetWhileIncomingRenegotiation){this.raiseMediaRenegotiationOffer(t,n);break}this.rejectAndLog(n,r,t);break;default:this.rejectAndLog(n,r,t)}},this.rejectRenegotiationAsync=(e,t)=>{this.logger.info(`[${t}][rejectRenegotiationAsync]`),this.signalingSession.telemetryHelper.recordEvent("RejectRenegotiation",{rejectionData:e,causeId:t}),Fa(this.links[wa.LINKS.MEDIA_REJECTION],"MediaRejection link not set");const i=e||{code:wa.CALL_END_CODE.NOT_ACCEPTABLE_HERE,subCode:wa.CALL_END_SUB_CODE.MEDIA_ANSWER_PROCESSING_ERROR,phrase:wa.CALL_END_PHRASE.MEDIA_ANSWER_ERROR};switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:return this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t),this.rejectMediaRenegotiation(this.links[wa.LINKS.MEDIA_REJECTION],i,t);case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,t),this.rejectMediaRenegotiation(this.links[wa.LINKS.MEDIA_REJECTION],i,t);default:return this.logger.error(`[${t}][rejectRenegotiationAsync][failed] There is no incoming media renegotiation offer to reject`),Promise.resolve(null)}},this.handleRetargetCompleted=e=>{const t=e.body.retargetCompleted,i=Qa(e);this.logger.info(`[${i}][handleRetargetCompleted][details=${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRetargetCompleted",e,$e(t)),0===t.code?this.signalingSessionCallback.onReTargetCompletedSuccess(i):this.signalingSessionCallback.onReTargetCompletedFailure(t,i)},this.dispose=()=>{this.logger.info("mediaRenegotiationManager :: dispose"),this.disposed=!0},this.getGlareError=()=>({code:wa.CALL_END_CODE.GLARE_ERROR,subCode:wa.CALL_END_SUB_CODE.MEDIA_GLARE_ERROR,phrase:wa.CALL_END_PHRASE.RENEGOTIATION_IN_PROGRESS,previousNegotiationCauseId:this.fsmStateCauseId}),this.handleMediaNegotiationFailureInternal=(e,t,i)=>{switch(this.logger.info(`[${i}][handleMediaNegotiationFailureInternal][failureData=${$e(e)}]`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,i);break;default:return}this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(Sd)),this.signalingSession.telemetryHelper.addIncomingModalities(["Rejected"]),this.signalingSessionCallback.onMediaRenegotiationRejection({code:e.code,subCode:e.subCode,phrase:e.phrase},i)},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>`[RenegotiationManager][${this.fsmState}][stateCauseId=${this.fsmStateCauseId}]`))}rejectAndLog(e,t,i){this.logger.error(`[${e}][handleMediaNegotiationOffer] Cannot handle the incoming mediaRenegotiation offer in present callstate. Either call not connected or renegotiation in progress. isDuplicateOffer=${t}`),t||this.rejectMediaRenegotiation(i.mediaNegotiation.links.rejection,this.getGlareError(),e)}setFsmState(e,t){this.fsmState=e,this.fsmStateCauseId=t,this.logger.info(`[setFsmState]state=${e}`),this.telemetryHelper.recordEvent("MediaFsmStateChanged",{state:e,causeId:t})}raiseMediaRenegotiationOffer(e,t){this.logger.info(`[${t}][raiseMediaRenegotiationOffer]`),this.links[wa.LINKS.MEDIA_ANSWER]=e.mediaNegotiation.links.mediaAnswer,this.links[wa.LINKS.MEDIA_REJECTION]=e.mediaNegotiation.links.rejection;let i=[];e.mediaNegotiation.callModalities&&e.mediaNegotiation.callModalities.length>0&&(i=Ha(e.mediaNegotiation.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i),Ga(i,wa.MEDIA_TYPES.SCREEN_SHARER)&&this.signalingSession.telemetryHelper.addVbssOperations(yd));const n={mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaNegotiation.mediaContent),mediaContent:e.mediaNegotiation.mediaContent,renegotiation:!0};this.signalingSessionCallback.onOffer(n,t)}rejectMediaRenegotiation(e,t,i){this.logger.info(`[${i}][rejectMediaRenegotiation][rejectionData=${$e(t)}]`);const n=to();return this.signalingSession.http.sendPostRequest({url:e,payload:gu(this.signalingSession,t),requestName:Zo.SEND_MEDIA_REJECTION.name,causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][rejectMediaRenegotiation] error: ${je(t)}`),n.reject(new Error(`rejectMediaRenegotiation failed because : ${je(e)}`))})),n.promise}handleMediaAnswerTimeout(e){this.logger.info(`[${e}][handleMediaAnswerTimeout]`),this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(Cd)),this.signalingSession.telemetryHelper.addIncomingModalities(["Timeout"]),this.signalingSession.telemetryHelper.recordEvent("HandleMediaAnswerTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.handleMediaNegotiationFailureInternal({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.MEDIA_FINAL_ANSWER_TIMEOUT,phrase:wa.CALL_END_PHRASE.MEDIA_FINAL_ANSWER_TIMEOUT},Xo,e)}handleMediaAnswerAcknowledgmentTimeout(e){this.logger.info(`[${e}][handleMediaAnswerAcknowledgmentTimeout]`),this.signalingSession.telemetryHelper.recordEvent("HandleMediaAcknowledgementTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSessionCallback.onMediaAcknowledgementFailure(!0,{reason:"timed out waiting for Media Answer Acknowledgement"},e)}},fu=class{constructor(){this.requests={}}clear(e,t){const i=t||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{this.rejectOperation(t,e,i)}))}hasOperation(e){return this.requests.hasOwnProperty(e)}getAllOperations(){return this.requests}getOperation(e){return this.hasOperation(e)?this.requests[e]:null}setOperation(e,t){return!this.hasOperation(e)&&(this.requests[e]=t,!0)}rejectOperation(e,t,i){const n=new Error(t);if(i&&(n.endCode=i),this.hasOperation(e)){const t=this.requests[e].promise;delete this.requests[e],t.reject(n)}}resolveOperation(e,t){if(this.hasOperation(e)){const i=this.requests[e].promise;delete this.requests[e],i.resolve(t)}}},vu=class{constructor(e){this.logger=e,this.localAddParticipantRequests=new fu,this.localAdmitParticipantRequests=new fu,this.localCallMeBackRequests=new fu,this.localRemoveParticipantEndpointRequests=new fu,this.localRemoveParticipantRequests=new fu,this.localUpdateParticipantInterpretationStateRequest=new fu,this.participantIdMriMap=new Map}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}getAllPendingOperations(e,t){this.logger.info(`[${t}][getAllPendingOperations] ${e}`);const i=this.getOperationTable(e);return i?i.getAllOperations():null}getPendingOperation(e,t,i){this.logger.info(`[${i}][getPendingOperation] ${e} ${t}`);const n=this.getOperationTable(e);return n?n.getOperation(t):null}getRnlMri(e,t){this.logger.info(`[${t}][getRnlMri] ${e}`);for(const t of e)if(this.participantIdMriMap.has(t))return this.participantIdMriMap.get(t);return""}hasPendingOperation(e,t,i){this.logger.info(`[${i}][hasPendingOperation] ${e} ${De(t)}`);const n=this.getOperationTable(e);return!!n&&n.hasOperation(t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${De(t)} reason: ${i}`);const s=this.getOperationTable(e);s&&s.rejectOperation(t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${De(t)}`);const r=this.getOperationTable(e);r&&r.resolveOperation(t,i)}setPendingOperation(e,t,i,n){this.logger.info(`[${n}][setPendingOperation] ${e} ${De(t)} value: ${i}`);const r=this.getOperationTable(e);if(!r)return!1;if(0===e){const e=i&&i.participant&&i.participant.participantId;e&&this.participantIdMriMap.set(e,t)}return r.setOperation(t,i)}setParticipantIdToMriMapping(e,t,i,n){n?(this.logger.info(`[${i}][setParticipantIdMriMap] ${Le(e)}: ${De(t)} clear mapping.`),this.participantIdMriMap.delete(e)):e&&t&&(this.logger.info(`[${i}][setParticipantIdMriMap] ${Le(e)}: ${De(t)}`),this.participantIdMriMap.set(e,t))}getOperationTable(e){switch(e){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(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localAddParticipantRequests.clear(e,t),this.localAdmitParticipantRequests.clear(e,t),this.localCallMeBackRequests.clear(e,t),this.localRemoveParticipantRequests.clear(e,t),this.localRemoveParticipantEndpointRequests.clear(e,t),this.localUpdateParticipantInterpretationStateRequest.clear(e,t)}};function Su(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=i.groupId?{id:i.groupId}:null,s=i.threadId?{threadId:i.threadId,messageId:i.messageId||null}:null;let a=[],o={};t&&t.length>0?(a=t.map((t=>({id:t.nonMaskedId?t.nonMaskedId:t.id,assertedId:t.assertedId,displayName:t.displayName,participantId:t.participantId,replacementDetails:3===i.replacementType?e.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,t.id,t.replacementParticipantId):void 0}))),o={addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)}):o={addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)};const l={payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:a},participantInvitationData:go(i),replacementDetails:3===i.replacementType?void 0:n,groupContext:r,groupChat:s,links:o}};return i&&i.alternateId&&(l.payload.participants.from.alternateId=i.alternateId),i?.callingLineIdentity&&(l.payload.participants.from.callingLineIdentity=i.callingLineIdentity),i?.clientScenario&&(l.payload.debugContent={clientScenario:i.clientScenario}),l}function yu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{admitFailure:Ra(e,ra.CONV_ADMIT_PARTICIPANT_FAILURE),admitSuccess:Ra(e,ra.CONV_ADMIT_PARTICIPANT_SUCCESS)},debugContent:{causeId:i}}}}function Cu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,toEndpoints:[{id:t.id,endpointId:t.endpointId}]},links:{removeParticipantSuccess:Ra(e,ra.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Ra(e,ra.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function Tu(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{removeParticipantSuccess:Ra(e,ra.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Ra(e,ra.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function Eu(e,t,i,n=""){Ua(i&&"specified"===i,"Only non-null non-empty scope of 'specified' is supported."),Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const r=[];return t.forEach((e=>{const t={id:e,meetingRole:n};r.push(t)})),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,to:r}}}var bu=p(Z),_u=class{constructor(e,t){this.participantManager=e,this.logger=t,this.handleRosterUpdate=(e,t,i,n)=>{if("Delta"===e.type||"MultiPartyEndpoint"===e.type){if(void 0===e.sequenceNumber&&(e.sequenceNumber=this.lastRosterUpdateSeqNumber),this.logger.info(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}]`),this.rostersInLifetime.add(e.sequenceNumber),"Delta"===e.type)this.logger.info(`[${n}][handleRosterUpdate], RosterType: Delta, isFullRoster: ${i}`),this.handleDeltaRoster(e,i,t,n);else{if(this.logger.info(`[${n}][handleRosterUpdate], RosterType: MultiPartyEndpoint`),this.isRosterStale(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(Uo,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const i of Object.keys(e.participants)){const r=mo.fromRoster(e.participants[i]);this.handleRosterParticipant(r,t,n)}this.checkForRemovedParticipants(t,e.participants,n),this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n)}if(e.sequenceNumber>this.lastRosterUpdateSeqNumber){this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n),this.lastRosterUpdateSeqNumber=e.sequenceNumber,this.firstRosterUpdateSeqNumber<0&&(this.firstRosterUpdateSeqNumber=this.lastRosterUpdateSeqNumber);const t=Object.keys(e.participants||0).length;this.participantCountInFirstRoster<0&&(this.participantCountInFirstRoster=t),this.maxConcurrentParticipantsDuringLeg=Math.max(this.maxConcurrentParticipantsDuringLeg,t)}this.recordTelemetry(e,i,n),this.participantManager.signalingSessionCallback.onRosterHandlingComplete()}else this.logger.warn(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}] invalid roster type ${e.type}`)},this.isRosterStaleFromFull=(e,t)=>(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastFullRosterSeqNumber}`),e.sequenceNumber<this.lastFullRosterSeqNumber),this.isRosterStale=(e,t)=>(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastRosterUpdateSeqNumber}`),e.sequenceNumber<this.lastRosterUpdateSeqNumber),this.updateLocalParticipantFromSubscribe=(e,t)=>{this.logger.info(`[${t}][updateLocalParticipantFromSubscribe]`),this.updateLocalParticipant(e,t)},this.handleParticipantAcceptedBy=(e,t,i)=>{const n=t.hasOwnProperty(e.id),r=e.id===e.acceptedBy.id;this.logger.info(`[${i}][RosterManager::handleParticipantAcceptedBy] oldParticipantInRoster: ${n}`),this.participantManager.participantOperationHandler.setParticipantIdToMriMapping(e.participantId,e.id,i,!0),n&&!r&&this.handleRemovedDeltaRosterParticipant(new mo({id:e.id}),this.lastRosterUpdateSeqNumber,t,i)},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(e,t,i){const n={participantCountInLastRoster:Object.keys(e.participants||0).length,participantCountInFirstRoster:this.participantCountInFirstRoster,sequenceNumberOfLastRoster:this.lastRosterUpdateSeqNumber,sequenceNumberOfLastFullRoster:this.lastFullRosterSeqNumber,sequenceNumberOfFirstRoster:this.firstRosterUpdateSeqNumber,rosterType:e.type,isFullRoster:t,maxConcurrentParticipantsDuringLeg:this.maxConcurrentParticipantsDuringLeg,totalParticipantsDuringLifetimeOfLeg:this.tombstoneSequence.size+this.latestRosterVersionForActiveParticipants.size,countOfMissingNotifications:this.getMissingNotificiations()};this.logger.info(`[recordTelemetry] data ${JSON.stringify(n,null,4)}`),this.participantManager.signalingSession.telemetryHelper.recordRosterEvent(n,"HandleRosterUpdate",i)}getMissingNotificiations(){const e=this.lastRosterUpdateSeqNumber-this.firstRosterUpdateSeqNumber+1-this.rostersInLifetime.size;return e>0?e:0}isParticipantRosterStale(e,t){if(this.logger.info(`[isParticipantRosterStale], rosterParticipantVersion ${t}`),t){if(this.tombstoneSequence.has(e))return t<=this.tombstoneSequence.get(e);if(this.latestRosterVersionForActiveParticipants.has(e))return t<=this.latestRosterVersionForActiveParticipants.get(e)}return!1}handleDeltaRoster(e,t,i,n){if(this.logger.info(`[${n}][handleDeltaRoster] isFullRoster ${t}`),this.isRosterStaleFromFull(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(Uo,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,lastFullRosterSeqNumber:this.lastFullRosterSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled full roster ${this.lastFullRosterSeqNumber}`);if(t){for(const t of Object.keys(i))if(!e.participants.hasOwnProperty(t)&&!this.isParticipantRosterStale(t,e.sequenceNumber)){const r=new mo({id:t});this.logger.info(`[${n}][handleRosterUpdate] participant missing from delta, full roster`),this.handleRemovedDeltaRosterParticipant(r,e.sequenceNumber,i,n)}this.lastFullRosterSeqNumber=e.sequenceNumber}else if(!e?.participants)return void this.logger.warn(`[${n}][handleRosterUpdate] participants blob empty in delta roster`);for(const t of Object.keys(e.participants)){const r=e.participants[t];if(!this.isParticipantRosterStale(t,r.version)){let e=mo.fromRoster(r);r.state&&"active"===r.state?(this.logger.info(`[${n}][handleDeltaRoster] participant active`),this.handleRosterParticipant(e,i,n),this.tombstoneSequence.has(t)&&this.tombstoneSequence.delete(t),this.latestRosterVersionForActiveParticipants.set(t,r.version)):r.state&&"inactive"===r.state?(e=e||new mo({id:r.details.id}),this.logger.info(`[${n}][handleDeltaRoster] participant inactive`),this.handleRemovedDeltaRosterParticipant(e,r.version,i,n)):this.logger.info(`[${n}][handleDeltaRoster] unexpected participant state ${r.state}`)}}this.handleRemoveParticipantRequests(this.getActiveParticipants(e.participants),n)}getRnlMri(e,t){const i=this.participantManager.participantOperationHandler;if(e){const n=this.getRnlParticipantIdsFromRoster(e,t);return i.getRnlMri(n,t)}return""}handleRemovedDeltaRosterParticipant(e,t,i,n){const r=e.id,s=this.getRnlMri(e,n);let a="";i.hasOwnProperty(r)?a=r:i.hasOwnProperty(s)&&(a=s),a&&this.handleRemovedParticipant(i,a,n),this.tombstoneSequence.set(r,t),this.latestRosterVersionForActiveParticipants.has(r)&&this.latestRosterVersionForActiveParticipants.delete(r)}handleRemovedParticipant(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession;!1!==e[t]&&(za(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][handleRemovedParticipant] ${De(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t))}getActiveParticipants(e){const t={};for(const i of Object.keys(e))"inactive"!==e[i].state&&(t[i]=e[i]);return t}handleRosterParticipant(e,t,i){if(!e)return void this.logger.info(`[handleRosterParticipant][${i}] rosterParticipant processing skipped because null.`);if(e.id===this.participantManager.localParticipant.id){this.updateLocalParticipant(e,i);const t=this.getLocalEndpoint(),n=!(!t?.stream&&!t?.streamLobby),r=0===this.participantManager.signalingSession.callMode;return this.logger.info(`[handleRosterParticipant][${i}] isStreaming:${n} isInitialMode:${r}`),void(n&&r?this.participantManager.signalingSession.configureStreamingMode(i):n||this.participantManager.signalingSession.setRealTimeState(1,i))}const n=this.participantManager.participantOperationHandler,r=this.participantManager.signalingSession,s=this.participantManager.signalingSessionCallback,a=e.id,o=this.getRnlMri(e,i),l=this.getRnlParticipantIdsFromRoster(e,i);r.remoteCaller&&-1!==l.indexOf(r.remoteCaller.participantId)&&(e.displayName=r.remoteCaller.displayName),qa(this.participantManager.connectedRemoteParticipantIds,e.id,!0);const c=t.hasOwnProperty(e.id),d=t.hasOwnProperty(o);(c||d)&&(t[e.id]=!1),n.hasPendingOperation(0,e.id,i)&&this.isParticipantInCall(e)?(this.logger.info(`participant ${De(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e.id),n.resolvePendingOperation(0,e.id,e,i)):o&&n.hasPendingOperation(0,o,i)&&this.isParticipantInCall(e)?(this.logger.info(`RNL participant ${De(o)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,o),n.resolvePendingOperation(0,o,e,i)):n.hasPendingOperation(1,e.id,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant: ${De(e.id)} appears in roster. Resolving AdmitParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),n.resolvePendingOperation(1,e.id,e,i));for(const t of e.endpointDetails)n.hasPendingOperation(0,t.participantId,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant ${De(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t.participantId),n.resolvePendingOperation(0,t.participantId,e,i));c?(this.logger.info(`participantIds=[${l}] updated ${De(e.id)}`),s.onParticipantUpdated(e,i),r.setParticipantCallLinks(e)):d?(this.logger.info(`RNL participant participantIds=[${l}] removed old ${De(o)} and added new ${De(a)}`),s.onParticipantRemoved({id:o},i,!0),r.clearParticipantCallLinks(o),s.onParticipantJoined(e,i),r.setParticipantCallLinks(e)):n.hasPendingOperation(3,e.id,i)?this.logger.info(`participantIds=[${l}] ignored ${De(e.id)}`):(this.logger.info(`participantIds=[${l}] joined ${De(e.id)}`),s.onParticipantJoined(e,i),r.setParticipantCallLinks(e))}getLocalEndpoint(){return bu.find(this.participantManager.localParticipant.endpointDetails,(e=>this.participantManager.localParticipant.endpointId===e.endpointId))}getRnlParticipantIdsFromRoster(e,t){const i=[];for(const t of e.endpointDetails)i.push(t.participantId);return this.logger.info(`[${t}][getRnlParticipantIdsFromRoster] ${JSON.stringify(i)}`),i}isParticipantInCall(e){return e.endpointDetails?.[0]&&!e.endpointDetails[0].isLobby}updateLocalParticipant(e,t){const i=this.participantManager.localParticipant,n=this.participantManager.signalingSession,r=this.participantManager.signalingSessionCallback;n.setParticipantCallLinks(e),this.logger.info(`[${t}][updateLocalParticipant]`);let s=!1;if(e?.endpointDetails){const a=bu.find(e.endpointDetails,(e=>i.endpointId===e.endpointId)),o=bu.find(i.endpointDetails,(e=>i.endpointId===e.endpointId));s=Fd(a),a?.isLobby&&!o?.isLobby?n.telemetryHelper.recordEvent("InLobby",{causeId:t}):!a||a.isLobby||o&&!o.isLobby||(s?n.telemetryHelper.recordEvent("Staging",{causeId:t}):n.telemetryHelper.recordEvent("Connected",{causeId:t})),a?.broadcastMeetingRole&&i&&i.broadcastMeetingRole!==a.broadcastMeetingRole&&(i.broadcastMeetingRole=a.broadcastMeetingRole,n.telemetryHelper.setBroadcastMeetingRole(a.broadcastMeetingRole)),r.onMeetingGroupDetailsUpdated(a?.meetingGroupDetails,t)}if(e?.meetingRole&&n.telemetryHelper.setMeetingRole(e.meetingRole),e?.advancedMeetingRole&&n.telemetryHelper.setAdvancedMeetingRole(e.advancedMeetingRole),e?.meetingRoles&&n.telemetryHelper.setMeetingRoles(e.meetingRoles),e?.participantType&&n.telemetryHelper.setParticipantType(e.participantType),e&&(i.endpointDetails=e.endpointDetails||[],i.acceptedBy=e.acceptedBy,i.role=e.role,i.meetingRole=e.meetingRole,i.advancedMeetingRole=e.advancedMeetingRole,i.meetingRoles=e.meetingRoles,i.participantType=e.participantType,i.tenantId=e.tenantId,i.isLobby=e.isLobby,i.publishedStates=e.publishedStates,i.isStaging=s,i.version=e.version,i.propertyBag=e.propertyBag,i.isIdentityMasked=e.isIdentityMasked,i.maskedIdSeqNumber=e.maskedIdSeqNumber,i.maskedId=e.maskedId,void 0!==e?.joinAsStreamingUser&&(i.joinAsStreamingUser=e.joinAsStreamingUser),void 0!==e?.enableCaptcha&&(i.enableCaptcha=e.enableCaptcha),void 0!==e?.otpIdentity&&(i.otpIdentity=e.otpIdentity),this.participantManager.localParticipant.fromRoster=!0,r.onSelfParticipantUpdated(i,t)),this.isParticipantInCall(e)){const i=this.participantManager.participantOperationHandler,r=this.getRnlMri(e,t);r&&i.hasPendingOperation(0,r,t)&&(this.logger.info(`RNL participant ${De(r)} appears in roster. Resolving AddParticipant request`),n.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,r),i.resolvePendingOperation(0,r,e,t))}}checkForRemovedParticipants(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession,s=this.participantManager.participantOperationHandler;this.logger.info(`[${i}][checkForRemovedParticipants]`);for(const t of Object.keys(e))e.hasOwnProperty(t)&&!1!==e[t]&&!s.hasPendingOperation(0,t,i)&&(za(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][checkForRemovedParticipants] ${De(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t));this.handleRemoveParticipantRequests(t,i)}handleRemoveParticipantRequests(e,t){const i=this.participantManager.signalingSession,n=this.participantManager.participantOperationHandler;this.logger.info(`handleRemoveParticipantRequests [${t}] dynamicRosterParticipants`);const r=[];Object.keys(e).forEach((t=>{const i=mo.fromRoster(e[t]);i&&i.endpointDetails&&i.endpointDetails.forEach((e=>{e.originalId&&r.push(e.originalId)}))}));const s=n.getAllPendingOperations(3,t);for(const a of Object.keys(s))-1!==r.indexOf(a)||e.hasOwnProperty(a)||(this.logger.info(`[${t}][handleRemoveParticipantRequests] ${De(a)} no longer appears in roster. Resolving RemoveParticipant request`),za(this.participantManager.connectedRemoteParticipantIds,a),i.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,a),n.resolvePendingOperation(3,a,{id:a},t))}},Iu=class{constructor(e,t,i,n){this.connectedRemoteParticipantIds={},this.disposed=!1,this.unmuteApprovalLinks={},this._asyncMuteUnmuteDefers=new Map,this.muteAsyncEnabled=!1,this.unmuteAsyncEnabled=!1,this.setLocalParticipantId=(e,t)=>{e&&(this.logger.info(`[${t}][setLocalParticipantId][participantId=${e}]`),this.localParticipant.participantId=e,this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId))},this.setEnableMuteAsync=e=>{this.muteAsyncEnabled=e},this.setEnableUnmuteAsync=e=>{this.unmuteAsyncEnabled=e},this.admitParticipantAsync=(e,t,i)=>{const n=`[${i}][admitParticipantAsync]`;this.logger.info(`${n}${this.piiUtils.scrubMriOrOmit(e.id)}`);const r=to();return this.participantOperationHandler.hasPendingOperation(1,e.id,i)?(this.logger.info(`${n}there is an existing pending request to admit the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),r.reject(new Error("there is an existing pending request to admit the participant"))):(this.participantOperationHandler.setPendingOperation(1,e.id,{participant:e,promise:r,causeId:i},i),this.sendNetworkRequestForAdmittingParticipant(e,t,i)),r.promise},this.addParticipantsAsync=(e,t,i,n,r)=>{const s=`[${r}][addParticipantsAsync]`,a=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${s} remoteParticipantsIds: ${a}`);const o=[],l=[];return e.forEach((e=>{const t=to(),i=3===n.replacementType?e.participantId:e.id;this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`${s}the given participant is already connected to the call ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(0,i,r)?(this.logger.info(`${s}there is an existing pending request to add the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to add the participant"))):(e.participantId||(e.participantId=La(),this.logger.info(`participantId created ${e.participantId}`)),this.participantOperationHandler.setPendingOperation(0,i,{participant:e,promise:t,causeId:r},r),o.push(e)),l.push(t.promise)})),i&&this.sendNetworkRequestForAddingParticipant(o,t,n,r),l},this.nudgeParticipantsAsync=(e,t,i,n,r,s,a,o)=>(this.logger.info(`[${n}][nudgeParticipantAsync] ${this.piiUtils.scrubParticipantsList(e)}`),i?this.sendNetworkRequestForNudgingParticipants(e,t,n,r,s,a,o):Promise.reject(`[${n}][nudgeParticipantAsync] Call not started`)),this.updateMeetingRolesAsync=(e,t,i,n=Na())=>{const r=to();if(!e||e.length<1){const e=`[${n}][updateMeetingRolesAsync] participantsInfo cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else if(t)if(i){let s;"attendee"===t?s=Zo.UPDATE_MEETING_ROLE_ATTENDEE.name:"presenter"===t?s=Zo.UPDATE_MEETING_ROLE_PRESENTER.name:"organizer"===t?s=Zo.UPDATE_MEETING_ROLE_ORGANIZER.name:r.reject(new Error(`[${n}] Invalid meetingRole value(${t})`)),this.logger.info(`[${n}][updateMeetingRolesAsync][meetingRole=${t}]`),this.signalingSession.ensureMessageChannelReady(s).then((()=>{this.sendNetworkRequestForUpdatingMeetingRoles(e,t,i,s,n,r)})).catch((e=>{const t=je(e);this.logger.info(`[${n}][updateMeetingRolesAsync][failed][reason=${t}]`);const i={...Ka(e,this.signalingSession.signalingAgentConfig).error};r.reject(i)}))}else{const e=`[${n}][updateMeetingRolesAsync] updateMeetingRoleUrl cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else{const e=`[${n}][updateMeetingRolesAsync] meetingRole cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}return r.promise},this.updateParticipantInterpretationStateAsync=(e,t,i)=>{const n=`[${i}][updateParticipantInterpretationStateAsync]`,r=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${n} remoteParticipantsIds: ${r}`);const s=[],a=[];return e.forEach((e=>{const t=to();this.participantOperationHandler.hasPendingOperation(5,e.id,i)?(this.logger.info(`${n}there is an existing pending request to update the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to update the participant"))):(this.participantOperationHandler.setPendingOperation(5,e.id,{option:e,promise:t,causeId:i},i),s.push(e)),a.push(t.promise)})),this.sendNetworkRequestToUpdateParticipantInterpretationState(s,t,e,i),a},this.callMeBackAsync=(e,t,i)=>{this.logger.info(`[${i}][callMeBackAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`);const n=to();return this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`the given participant is already connected to the call : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(2,e.id,i)?(this.logger.info(`there is an existing pending request to call back the participant : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to call back the participant"))):(this.participantOperationHandler.setPendingOperation(2,e.id,{participant:e,promise:n},i),this.sendNetworkRequestForCallMeBack(e,t,i)),n.promise},this.isRosterStale=(e,t)=>this.rosterManager.isRosterStale(e,t),this.removeParticipantAsync=(e,t,i)=>{this.logger.info(`[${i}][removeParticipantAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`),Fa(t,"correct removeParticipantUrl is not provided");const n=to();if(this.participantOperationHandler.hasPendingOperation(3,e.id,i))this.logger.info(`there is an existing pending request to remove the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to remove the participant"));else{this.participantOperationHandler.setPendingOperation(3,e.id,{participant:e,promise:n},i);const r=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession.telemetryHelper.recordEvent(Eo),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,"timed out waiting for participant to not show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},i)}),wa.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:Tu(this.signalingSession,e),requestName:Zo.REMOVE_PARTICIPANT_NONE.name,onceTrouterReady:r,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][removeParticipantAsync][failed][reason=${je(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,t,n.error,i))}))}return n.promise},this.removeParticipantEndpointAsync=(e,t,i,n)=>{this.logger.info(`[${n}][removeParticipantEndpointAsync] ${qe(e.endpointId,8)} [endPointScope] ${i}`),Fa(t,"correct removeParticipantUrl is not provided");const r=to();let s="";switch(i){case"all":s=Zo.REMOVE_PARTICIPANT_OTHERS.name;break;case"specified":s=Zo.REMOVE_PARTICIPANT_SPECIFIED.name;break;default:return Promise.reject(`invalid scope ${i} removeParticipantEndpointAsync`)}return this.participantOperationHandler.setPendingOperation(4,e.endpointId,{participant:e,promise:r,scope:i},n),this.signalingSession.http.sendPostRequest({url:t,payload:Cu(this.signalingSession,e,i),requestName:s,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(Eo),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,"timed out waiting for participant endpoint sync response from service",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},n))}),wa.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.endpointId)},causeId:n}).then((e=>{if(e.response?.code)if(-1!==[wa.HTTP_STATUS_CODES.OK,wa.HTTP_STATUS_CODES.CREATED].indexOf(e.response.code))this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [passed][reason=${je(e.response)}]`),r.resolve(e.response);else{const t=new Error("invalid service response for removeParticipantEndpoint");t.endCode={code:e.response.code,subCode:e.response.subcode,phrase:e.response.reason},this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${je(e.response)}]`),r.reject(t)}r.resolve()})).catch((t=>{const r=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${je(r)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,je(t),r.error,n))})),r.promise},this.getParticipantsToInitiateCallWith=()=>{this.logger.info("getParticipantsToInitiateCallWith");const e=[],t=this.participantOperationHandler.getAllPendingOperations(0,Na());for(const i of Object.keys(t))t.hasOwnProperty(i)&&t[i]&&e.push(t[i].participant);return e},this.initializeForIncomingCall=e=>{this.logger.info("initializeForIncomingCall"),this.participantOperationHandler.dispose("incoming calls cannot add/remove participants until call is connected",null,Na())},this.handleAddParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddParticipantSuccess(${t.participantInfos?"new format":"old format"})]${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(bo,e),this.internalHandleCallMeBackSuccess(t,i)||this.signalingSession.telemetryHelper.recordEvent(bo),this.signalingSession.signalingAgentConfig.enableAddParticipantEnhancements&&this.internalHandleAcceptedByParticipants(t,i)},this.handleAddParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddParticipantFailure(${t.participantInfos?"new format":"old format"})][${je(t)}]`),t.modalityFailure?(this.logger.info(`[${i}][handleAddParticipantFailure][modalityFailure=${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAddParticipantModalityFailure",e)):this.internalHandleAddParticipantFailure(e,i)},this.handleAdmitParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAdmitParticipantSuccess][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAdmitParticipantSuccess",e),t.participants&&this.internalHandleAdmitParticipantSuccess(e,i)},this.handleAdmitParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAdmitParticipantFailure][${je(t)}]`),t.participants&&this.internalHandleAdmitParticipantFailure(e,i)},this.handleRemoveParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleRemoveParticipantFailure][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRemoveParticipantFailure",e);for(const e of Object.keys(t.participants))t.participants.hasOwnProperty(e)&&this.internalHandleRemoveParticipantFailure(e,t.participants[e],i)},this.handleRemoveParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleRemoveParticipantSuccess][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRemoveParticipantSuccess",e)},this.handleUnmuteConfirmRequest=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleUnmuteConfirmRequest][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleUnmuteConfirm",e),this.unmuteApprovalLinks[t.from.id]={approve:t.links.approveUnmute,reject:t.links.rejectUnmute},this.signalingSessionCallback.onUnmuteRequested(t.from.id,i)},this.approveUnmuteRequestAsync=(e,t)=>{this.logger.info(`[${t}][approveUnmuteRequestAsync]`);const i=to();return this.unmuteApprovalLinks.hasOwnProperty(e)?(this.signalingSession.ensureMessageChannelReady(Zo.APPROVE_UNMUTE.name).then((()=>{this.muteUnmute(Zo.APPROVE_UNMUTE.name,function(e){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]}}}(this.signalingSession),i,this.unmuteApprovalLinks[e].approve,t)})).catch((e=>{const n=je(e);this.logger.info(`[${t}][approveUnmuteRequestAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise):(i.reject(new Error("no unmute links found for given participant")),i.promise)},this.rejectUnmuteRequestAsync=(e,t,i)=>{this.logger.info(`[${t}][rejectUnmuteRequestAsync]`);const n=to();if(!this.unmuteApprovalLinks.hasOwnProperty(e))return n.reject(new Error("no unmute links found for given participant")),n.promise;const r=i||{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UNMUTE_REQUEST_REJECTED,phrase:wa.CALL_END_PHRASE.UNMUTE_REQUEST_REJECTED};return this.signalingSession.ensureMessageChannelReady(Zo.REJECT_UNMUTE.name).then((()=>{this.muteUnmute(Zo.REJECT_UNMUTE.name,function(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{transactionEnd:t}}}(this.signalingSession,r),n,this.unmuteApprovalLinks[e].reject,t)})).catch((e=>{const i=je(e);this.logger.info(`[${t}][rejectUnmuteRequestAsync][failed][reason=${i}]`),n.reject(new Error(e))})),n.promise},this.handleRosterUpdate=(e,t,i)=>{const n=this.getCurrentParticipantsInCallModality(!1);this.rosterManager.handleRosterUpdate(e,n,t,i)},this.updateLocalParticipantFromSubscribe=(e,t)=>{this.localParticipant.fromRoster||this.rosterManager.updateLocalParticipantFromSubscribe(e,t)},this.muteAsync=(e,t,i,n)=>{this.logger.info(`[${n}][muteAsync][muteScope=${t}]`);let r="specified";const s=[];let a=Zo.MUTE_SPECIFIED;switch(t){case wa.MUTE_SCOPE.MYSELF:a=Zo.MUTE_MYSELF,s.push({id:this.localParticipant.id});break;case wa.MUTE_SCOPE.EVERYONE_ELSE:a=Zo.MUTE_ALL_SYNC,r="all",i.forEach((e=>{s.push({id:e})}));break;case wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS:Fa(i,`[${n}]array of participantIds must be specified for SPECIFIED_PARTICIPANTS mute scope`),a=Zo.MUTE_SPECIFIED_SYNC,i.forEach((e=>{s.push({id:e})}));break;default:xa(!1,`[${n}]muteScope is a required param. please pass in a valid value.`)}const o=to();if(t===wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS){const e=this.areParticipantsConnectedToCall(i);if(!e.result)return o.reject(new Error(`[${n}]specified participant is not connected to call yet. Id = ${e.participant}`)),o.promise}const l=this.muteAsyncEnabled&&(t===wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS||t===wa.MUTE_SCOPE.EVERYONE_ELSE);return this.signalingSession.ensureMessageChannelReady(a.name).then((()=>{this.muteUnmute(a.name,function(e,t,i,n=!1,r=null){Ua(e,"signalingSession cannot be null"),Ua(t,"muteScope be null"),Ua(i,"participantList cannot be null");const s={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t,muteParticipants:i,mediaTypes:["audio"]};return n&&(s.links={clientCallback:Ra(e,ra.MUTE_UNMUTE_ASYNC,r)},s.operationId=r),{payload:s}}(this.signalingSession,r,s,l,n),o,e,n,!1,l)})).catch((e=>{const t=je(e),i=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][muteAsync][failed][reason=${t}]`),o.reject(i)})),o.promise},this.unmuteAsync=(e,t)=>{this.logger.info(`[${t}][unmuteAsync]`);const i=to();return this.signalingSession.ensureMessageChannelReady(Zo.UNMUTE_SYNC.name).then((()=>{this.muteUnmute(Zo.UNMUTE_SYNC.name,function(e,t=!1,i=null){Ua(e,"signalingSession cannot be null");const n={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]};return t&&(n.links={clientCallback:Ra(e,ra.MUTE_UNMUTE_ASYNC,i)},n.operationId=i),{payload:n}}(this.signalingSession,this.unmuteAsyncEnabled,t),i,e,t,!0,this.unmuteAsyncEnabled)})).catch((e=>{const n=je(e);this.logger.info(`[${t}][unmuteAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise},this.dispose=(e,t)=>{this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.participantOperationHandler.dispose("call ended",e,t),this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId),this._asyncMuteUnmuteDefers.forEach(((t,i)=>{t.reject(e)})),this._asyncMuteUnmuteDefers.clear()},this.handleMuteUnmuteAsyncResponse=e=>{const t=Qa(e),i=this.logger.createFnLogger("handleMuteUnmuteAsyncResponse",t);if(!e.body)return void i.error("ignored. Empty message body.");const n={info:e.body.muteUnmuteResponseAsync,operationId:e.body.operationId};if(i.info(`Received async response for mute/unmute operation, operation id = ${n.operationId}.`),this.disposed)return void i.info("ignored. Call disposed.");if(!n.operationId)return void i.error("operationId is undefined.");const r=this._asyncMuteUnmuteDefers.get(n.operationId);r?(r.resolve(n),this._asyncMuteUnmuteDefers.delete(n.operationId)):i.warn(`cannot find deferred promise for operation id [${n.operationId}].`)},this.internalHandleAcceptedByParticipants=(e,t)=>{if(e?.participantInfos){const i=e.participantInfos,n=this.getCurrentParticipantsInCallModality(!1);this.logger.info(`[${t}][internalHandleAcceptedByParticipants] handling participants with acceptedBy blob.`);for(const e of i)if(e?.acceptedBy){const i=e.id;this.participantOperationHandler.hasPendingOperation(0,i,t)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,i),this.logger.info(`[${t}][internalHandleAcceptedByParticipants] ${this.piiUtils.scrubMriOrOmit(i)} added using a different MRI. Resolving operation.`),this.participantOperationHandler.resolvePendingOperation(0,i,void 0,t)),this.rosterManager.handleParticipantAcceptedBy(e,n,t)}}},this.internalHandleCallMeBackSuccess=(e,t)=>{let i=!1;if(e?.participantInfos){const n=e.participantInfos;for(const e of n){const n=e.id;this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0)}}else if(e?.participants)for(const n of e.participants)this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0);return i},this.signalingSession=e,this.signalingSessionCallback=t,this.localParticipant=i,this.localParticipant.endpointId||(this.localParticipant.endpointId=this.signalingSession.getEndpointId());const r=qe(this.localParticipant.endpointId,8);this.logger=n.createChild((()=>`[PM][${r}]`)),this.piiUtils=e.piiUtils,this.participantOperationHandler=new vu(e.logger.createChild((()=>`[ParticipantOperationHandler][${r}]`))),this.rosterManager=new _u(this,e.logger.createChild((()=>`[RosterManager][${r}]`))),this.localParticipant.participantId||(this.localParticipant.participantId=La()),"string"==typeof e.signalingAgentConfig.languageCode?this.localParticipant.languageId=e.signalingAgentConfig.languageCode:"function"==typeof e.signalingAgentConfig.languageCode&&(this.localParticipant.languageId=e.signalingAgentConfig.languageCode()),e.telemetryHelper.setParticipantId(this.localParticipant.participantId),e.telemetryHelper.setEndPointId(this.localParticipant.endpointId)}handleUpdateParticipantInterpretationStateCompletion(e){const t=e.body,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateParticipantInterpretationStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] starts`);const r=e.body;if(r.participantInfos)for(const t of r.participantInfos)if(this.logger.info(t),this.participantOperationHandler.hasPendingOperation(5,t.participant.id,i))if(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,t.participant.id),t.transactionEnd.code===wa.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}]Update participant interpretation state succeeded for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)}`),this.signalingSession.telemetryHelper.recordIncomingEvent("UpdateParticipantInterpretationStateResponseCompleted",e),this.participantOperationHandler.resolvePendingOperation(5,t.participant.id,void 0,i);else{const n=t.transactionEnd.reason;this.logger.info(`[${i}]Update participant interpretation state failed for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)} reason : ${je(n)}`);const r=this.getCallEndGivenParticipantFailure(n);this.signalingSession.telemetryHelper.recordIncomingEvent("UpdateParticipantInterpretationStateResponseFailed",e,r),this.participantOperationHandler.rejectPendingOperation(5,t.participant.id,r.phrase,r,i)}}setEnableCaptcha(e,t){this.logger.info(`[${t}][setEnableCaptcha] value:${e}`),this.localParticipant.enableCaptcha=e,this.signalingSessionCallback.onSelfParticipantUpdated(this.localParticipant,t)}areParticipantsConnectedToCall(e){this.logger.info(`areParticipantsConnectedToCall : ${je(e)}`);const t=this.getCurrentParticipantsInCallModality(!0);for(const i of e)if(!t.hasOwnProperty(i))return this.logger.info(`areParticipantsConnectedToCall : returning false for :${this.piiUtils.scrubMriOrOmit(i)}`),{result:!1,participant:i};return this.logger.info("areParticipantsConnectedToCall : returning true"),{result:!0}}muteUnmute(e,t,i,n,r,s,a=!1){const o=this.logger.createFnLogger("muteUnmute",r);xa(2!==this.signalingSession.callMode,"mute/unmute operations are not allowed in streaming mode"),o.info(`operation=${e}, isAsync=${a}`),n?(s&&this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UNMUTE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent("UnmuteTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNMUTE);const e=new Error("timed out waiting for response to request");e.endCode={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UNMUTE_REQUEST_TIMEOUT,phrase:wa.CALL_END_PHRASE.UNMUTE_REQUEST_TIMEOUT},i.reject(e)}}),wa.TIMEOUT_VALUES_IN_SECONDS.UNMUTE_TIMEOUT),a&&this._asyncMuteUnmuteDefers.set(r,i),this.signalingSession.http.sendPostRequest({url:n,payload:t,requestName:e,withoutTrouter:!0,causeId:r}).then((t=>{if(!this.disposed)if(a)o.info(`Inline response received for async operation, operation id: ${r}.`);else{if(t.response?.muteUnmuteResponse){const n={info:t.response.muteUnmuteResponse,operationId:t.response.operationId};switch(e){case Zo.UNMUTE_SYNC.name:case Zo.MUTE_ALL_SYNC.name:case Zo.MUTE_SPECIFIED_SYNC.name:i.resolve(n)}}i.resolve()}})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);o.info(`operation failed, reason=${je(t)}`),this.disposed||(s&&this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNMUTE),i.reject(t.error))}))):i.reject(new Error(`[${r}][muteUnmute] cannot be performed now, the link is not yet available`))}sendNetworkRequestForUpdatingMeetingRoles(e,t,i,n,r,s){if(!i){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because correct updateMeetingRoleUrl is not provided`;new Error(e).endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),s.reject()}if(!e){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because participants list is empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),s.reject(t)}this.signalingSession.http.sendPostRequest({url:i,payload:Eu(this.signalingSession,e,"specified",t),requestName:n,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent("UpdateMeetingRole",{causeId:r}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE);const e=new Error(`[${r}] Timed out waiting for response to request`);e.endCode={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_ROLE_TIMEOUT},s.reject(e)}}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_ROLE_TIMEOUT)},causeId:r}).then((e=>{s.resolve(e.response)})).catch((e=>{const t=je(e);this.logger.info(`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed: ${t}`);const i=new Error(`[${r}][CS response] Forbidden request`),n=Ka(e,this.signalingSession.signalingAgentConfig);i.code=n.error.code,i.subCode=n.error.subCode,i.phrase=n.error.phrase,this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE),s.reject(i))}))}sendNetworkRequestForNudgingParticipants(e,t,i,n,r,s,a){if(t){const o=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("NudgeParticipantTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""))}),wa.TIMEOUT_VALUES_IN_SECONDS.NUDGE_PARTICIPANT_TIMEOUT,e?e.join():"")},l=s||r?function(e,t,i,n,r,s){Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const a=e.groupId?{id:e.groupId}:null,o=n?{threadId:n,messageId:r||null}:null,l=[];return t.forEach((e=>{const t={id:e};l.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:wa.INVITATION_TYPE.NUDGE,to:l},participantInvitationData:s,groupContext:a,groupChat:o,links:{nudgeParticipantSuccess:Ra(e,ra.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Ra(e,ra.CONV_NUDGE_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,0,s,a,n):function(e,t,i){Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const n=[];return t.forEach((e=>{const t={id:e};n.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:wa.INVITATION_TYPE.NUDGE,to:n},participantInvitationData:i,links:{nudgeParticipantSuccess:Ra(e,ra.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Ra(e,ra.CONV_NUDGE_PARTICIPANT_FAILURE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,n);return this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:Zo.NUDGE_PARTICIPANT.name,onceTrouterReady:o,causeId:i}).then((()=>{})).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant][failed][reason=${je(n)}]`),this.disposed||this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""),Promise.reject(n.error)}))}return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant] failed because correct nudgeParticipantUrl is not provided`),Promise.reject("Missing nudgeParticipant url")}sendNetworkRequestForAddingParticipant(e,t,i,n=Na()){if(t){let r=Zo.ADD_PARTICIPANT.name,s=yo,a={};switch(i.replacementType){case 2:r=Zo.ADD_PARTICIPANT_WITH_PICKUP_CODE.name,s="AddParticipantWithPickupCodeTimeout",a.unparkContent={pickupCode:i.pickupCode};break;case 1:r=Zo.ADD_PARTICIPANT_WITH_REPLACES.name,s=Co,a=this.signalingSession.getCallReplacementDetailsForCall(i.callIdToReplace,n);break;case 3:r=Zo.ADD_PARTICIPANT_WITH_REPLACES.name,s=Co,a=this.signalingSession.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,e[0].id,e[0].replacementParticipantId,n);break;default:r=Zo.ADD_PARTICIPANT.name,s=yo,a=null}const o=()=>{e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(s,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t),this.participantOperationHandler.rejectPendingOperation(0,t,"timed out waiting for participant to show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},n))}),wa.TIMEOUT_VALUES_IN_SECONDS.ADD_PARTICIPANT_TIMEOUT,t)}))},l=i.threadId||i.groupId?Su(this.signalingSession,e,i,a):function(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=t.map((e=>(Ua(e,"remoteParticipant cannot be null"),{id:e.id,assertedId:e.assertedId,displayName:e.displayName,participantId:e.participantId})));return{payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,alternateId:i?i.alternateId:null,callingLineIdentity:i?i.callingLineIdentity:null},to:r},participantInvitationData:go(i),replacementDetails:n,links:{addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)},debugContent:{clientScenario:i.clientScenario}}}}(this.signalingSession,e,i,a);this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:r,onceTrouterReady:o,causeId:n}).catch((t=>{const r=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestForAddingParticipant] failed:${je(t)}`),this.disposed||e.forEach((e=>{const s=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,s),this.participantOperationHandler.rejectPendingOperation(0,s,t,r.error,n)}))}))}else this.logger.info(`[${n}][sendNetworkRequestForAddingParticipants] failed because correct addParticipantUrl is not provided`),e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.participantOperationHandler.rejectPendingOperation(0,t,"correct addParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},n)}))}sendNetworkRequestToUpdateParticipantInterpretationState(e,t,i,n=Na()){if(t){const r=Zo.UPDATE_PARTICIPANT_INTERPRETATION_STATE.name,s="UpdateParticipantInterpretationStateTimeout",a=()=>{const t={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT};e.forEach((e=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] timed out`),this.signalingSession.telemetryHelper.recordEvent(s,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,"timed out waiting to update particiant interpretation state",t,n))}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT,e.id)}))},o=function(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"options cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id},to:t,links:{updateParticipantInterpretationStateStatus:Ra(e,ra.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS)},operationId:i}}}(this.signalingSession,i,n);this.signalingSession.http.sendPostRequest({url:t,payload:o,requestName:r,onceTrouterReady:a,causeId:n}).catch((t=>{const i=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed:${je(t)}`),this.disposed||e.forEach((e=>{this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,t,i.error,n)}))}))}else{this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed because correct updateParticipantUrl is not provided`);const t={code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING};e.forEach((e=>{this.participantOperationHandler.rejectPendingOperation(5,e.id,"correct updateParticipantUrl is not provided",t,n)}))}}sendNetworkRequestForCallMeBack(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("CallMeBackTimeout",{causeId:i}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,"timed out waiting for call me back success response",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),wa.TIMEOUT_VALUES_IN_SECONDS.CALL_ME_BACK_TIMEOUT,e.id)},r={groupId:this.signalingSession.groupId,threadId:this.signalingSession.threadId,messageId:this.signalingSession.teamsMessageId};this.signalingSession.http.sendPostRequest({url:t,payload:Su(this.signalingSession,[e],r),requestName:Zo.CALL_ME_BACK.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed: ${je(n)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed because correct addParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(2,e.id,"correct addParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},i)}sendNetworkRequestForAdmittingParticipant(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("AdmitParticipantTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,"timed out waiting for participant to show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),wa.TIMEOUT_VALUES_IN_SECONDS.ADMIT_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:yu(this.signalingSession,e,i),requestName:Zo.ADMIT_PARTICIPANT.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant][failed][reason=${je(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant] failed because correct admitParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(1,e.id,"correct admitParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADMIT_PARTICIPANT_URL_MISSING},i)}getCurrentParticipantsInCallModality(e){const t={},i=[wa.PARTICIPANT_AUDIO_STATE.CONNECTED];return e||i.push(wa.PARTICIPANT_AUDIO_STATE.CONNECTING,wa.PARTICIPANT_AUDIO_STATE.RINGING),this.signalingSessionCallback.getRemoteParticipantCollection()?.forEach((e=>{i.some((t=>t===e.audioState))&&(t[e.mri]=!0)})),t}internalHandleRemoveParticipantFailure(e,t,i){if(this.participantOperationHandler.hasPendingOperation(3,e,i)){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e),this.logger.info(`[${i}][internalHandleRemoveParticipantFailure] failed for ${this.piiUtils.scrubMriOrOmit(e)} reason ${je(t)}`);const n=this.getCallEndGivenParticipantFailure(t);this.participantOperationHandler.rejectPendingOperation(3,e,n.phrase,n,i)}}internalHandleCallMeBackSuccessHelper(e,t){if(this.participantOperationHandler.hasPendingOperation(2,e,t)){const i={id:e};return this.logger.info(`participant : ${this.piiUtils.scrubMriOrOmit(e)} was successfully added. Resolving CallMeBack request`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.participantOperationHandler.resolvePendingOperation(2,i.id,i,t),!0}return!1}internalHandleAddParticipantFailure(e,t=Na()){const i=e.body;if(i.participantInfos)i.participantInfos.forEach((i=>{const n=[i.participant.participantId],r=this.participantOperationHandler.getRnlMri(n,t)||i.participant.id;this.rejectAddParticipantFailure(r,i.transactionEnd,e,t)}));else if(i.participants)for(const n of Object.keys(i.participants))this.rejectAddParticipantFailure(n,i.participants[n],e,t)}rejectAddParticipantFailure(e,t,i,n){const r=this.getCallEndGivenParticipantFailure(t);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAddParticipantFailure",i,r),this.participantOperationHandler.hasPendingOperation(0,e,n)?(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e),this.logger.info(`participantAdd failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${je(t)}`),this.participantOperationHandler.rejectPendingOperation(0,e,r.phrase,r,n)):this.participantOperationHandler.hasPendingOperation(2,e,n)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.logger.info(`callMeBack failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${je(t)}`),this.participantOperationHandler.rejectPendingOperation(2,e,r.phrase,r,n))}internalHandleAdmitParticipantSuccess(e,t){const i=e.body;for(const e of i.participants)this.participantOperationHandler.hasPendingOperation(1,e,t)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e),this.logger.info(`Admit participant success for : ${this.piiUtils.scrubMriOrOmit(e)}`),this.participantOperationHandler.resolvePendingOperation(1,e,void 0,t))}internalHandleAdmitParticipantFailure(e,t){const i=e.body;for(const n of Object.keys(i.participants))if(this.participantOperationHandler.hasPendingOperation(1,n,t)){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,n);const r=i.participants[n];this.logger.info(`Admit participant failed for : ${this.piiUtils.scrubMriOrOmit(n)} reason : ${je(r)}`);const s=this.getCallEndGivenParticipantFailure(r);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAdmitParticipantFailure",e,s),this.participantOperationHandler.rejectPendingOperation(1,n,s.phrase,s,t)}}getCallEndGivenParticipantFailure(e){let t={code:e.code,subCode:e.subCode,phrase:e.phrase,resultCategories:e.resultCategories};return e.code===wa.CALL_END_CODE.CALL_MODALITY_FAILURE&&e.callControllerTransactionEnd?t={...e.callControllerTransactionEnd}:e.code===wa.CALL_END_CODE.ATC_CONTROLLER_FAILURE&&e.atcControllerTransactionEnd?t={...e.atcControllerTransactionEnd}:e.code===wa.CALL_END_CODE.CVA_CONTROLLER_FAILURE&&e.cvaControllerTransactionEnd&&(t={...e.cvaControllerTransactionEnd}),t}};function wu(e,t){return`${e}-${t}`}function Au(e,t){return`${e}-${t}`}function Pu(e,t,i){return`${e}_${t}_${i}`}var Ru=class{constructor(e){this.signalingSession=e,this.scopeAllOperations=new Map,this.mriOperations=new Map,this.legOperations=new Map,this.logger=e.logger.createChild((()=>"[ProxiedMessageNotificationManager]"))}sendProxiedMessageAsync(e,t,i){this.logger.createChild("sendProxiedMessageAsync",e).info(`Url: ${i}`);const n=[],r=[];for(const i of t)if(0!==i.scope){if(1===i.scope)for(const t in i.to)if("participant"===i.to[t].level){const s=wu(t,i.operationId),a=to();this.mriOperations.set(s,a),n.push(a.promise),r.push(s),this.startTimeout(e,"participant",s)}else if("endpoint"===i.to[t].level)for(const s in i.to[t].participantLegIdMap){const t=Au(s,i.operationId),a=to();this.legOperations.set(t,a),n.push(a.promise),r.push(t),this.startTimeout(e,"endpoint",t)}}else{const t=to();this.scopeAllOperations.set(i.operationId,t),n.push(t.promise),r.push(i.operationId),this.startTimeout(e,"all",i.operationId)}return this.sendProxiedMessageNetworkRequest(e,t,i,r),n}sendProxiedMessageNetworkRequest(e,t,i,n){const r=function(e,t){Ua(e,"signalingSession cannot be null"),Fa(t,"sendMessageOptions cannot be null or empty");const i=[];for(const n of t){const t=0===n.scope?"all":"specified",r=[];n.to&&Object.keys(n.to).forEach((e=>{n.to[e].participantLegIdMap?Object.keys(n.to[e].participantLegIdMap).forEach((t=>{r.push({id:e,level:n.to[e].level,endpointId:n.to[e].participantLegIdMap[t].endpointId,participantId:t})})):r.push({id:e,level:n.to[e].level})})),i.push({links:{sendMessageStatus:Ra(e,ra.SEND_MESSAGE_STATUS)},operationId:n.operationId,payload:n.payload,scope:t,to:r,type:n.type})}return{payload:{from:{displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,id:e.participantManager.localParticipant.id,languageId:e.participantManager.localParticipant.languageId??"",participantId:e.participantManager.localParticipant.participantId},messageContent:i}}}(this.signalingSession,t),s=this.logger.createChild("sendProxiedMessageNetworkRequest",e);s.info(`Url: ${i}`),this.signalingSession.http.sendPostRequest({url:i,requestName:Zo.SEND_PROXIED_MESSAGE.name,payload:r,causeId:e}).catch((t=>{const i=Ka(t,this.signalingSession.signalingAgentConfig);if(s.info(`failed:${je(t)}`),this.signalingSession.disposed)s.info("signaling session is already disposed.");else for(const t of n){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,t);let n=null;this.scopeAllOperations.has(t)?(n=this.scopeAllOperations.get(t),this.scopeAllOperations.delete(t)):this.mriOperations.has(t)?(n=this.mriOperations.get(t),this.mriOperations.delete(t)):this.legOperations.get(t)?(n=this.legOperations.get(t),this.legOperations.delete(t)):s.warn(`could not find resolveString:${t} to reject it.`),null!==n&&n.reject({transactionEnd:i.error,causeId:e,resolveString:t})}}))}startTimeout(e,t,i){const n=this.logger.createChild("startTimeout",e);n.info(`Creating timeout for level ${t} message with resolveString ${i}`),this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,(()=>{this.signalingSession.telemetryHelper.recordEvent("SendMessageTimeout",{causeId:e,resolveString:i}),n.info(`timed out waiting for level [${t}] message with resolveString [${i}]`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,i);const r="all"===t?this.scopeAllOperations:"participant"===t?this.mriOperations:"endpoint"===t?this.legOperations:null;null!==r?r.has(i)?(r.get(i).reject({transactionEnd:{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CONVERSATION_NOTIFICATION_TIMEOUT,phrase:wa.CALL_END_PHRASE.CONVERSATION_NOTIFICATION_TIMEOUT},causeId:e,resolveString:i}),r.delete(i)):n.warn(`Could not find resolveString [${i}] on map for ${t}. Will not reject promise.`):n.warn(`Could not find a operations map for ${t}. Will not reject promise.`)}),wa.TIMEOUT_VALUES_IN_SECONDS.SEND_MESSAGE_COMPLETION_TIMEOUT,i)}handleProxiedMessageNotificationItem(e,t,i){if(t.info(`Message contains ${e.participantInfos?.length} participantInfos.`),0===this.scopeAllOperations.size&&0===this.mriOperations.size&&0===this.legOperations.size)return void t.info("Received statusMessage but there is no pending operation.");const n=e.operationId;if(this.scopeAllOperations.has(n)){t.info(`Scope all resolveString:${n}`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,n);const e={transactionEnd:{code:0,subCode:0,phrase:""},causeId:i,resolveString:n};return this.scopeAllOperations.get(n).resolve(e),this.scopeAllOperations.delete(n),void this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"all"})}for(const r of e.participantInfos){const e=0===r.transactionEnd?.code,s=wu(r.participant.id,n),a=Au(r.participant.participantId,n);if(s&&this.mriOperations.has(s)){t.info(`Scope mri resolveString:${s}`);const a={transactionEnd:r.transactionEnd,causeId:i,resolveString:s};e?this.mriOperations.get(s).resolve(a):this.mriOperations.get(s).reject(a),this.mriOperations.delete(s),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,s),this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"mri"})}else if(a&&this.legOperations.has(a)){t.info(`Scope legId resolveString:${a}`);const s={transactionEnd:r.transactionEnd,causeId:i,resolveString:a};e?this.legOperations.get(a).resolve(s):this.legOperations.get(a).reject(s),this.legOperations.delete(a),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,a),this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"leg"})}else t.warn(`Could not map this participantInfo to any pending operation operationId:${n}`)}}handleProxiedMessageNotification(e){const t=Qa(e),i=this.logger.createChild("handleProxiedMessageNotification",t);let n;n=Array.isArray(e.body?.statuses)?e.body.statuses:[e.body],i.info(`Received ${n.length} proxied message notification(s).`);for(const e of n)this.handleProxiedMessageNotificationItem(e,i,t)}};function Mu(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{admitAllStatus:Ra(e,ra.CONV_ADMIT_ALL_STATUS)},operationId:t,debugContent:{causeId:t}}}}function Du(e,t,i=!0){Ua(e,"signalingSession cannot be null"),Ua(t,"joinUrl cannot be null");const n={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},r=e.getEndpointCapabilities(),s={payload:{attach:{requireMediaContent:i,links:{end:Ra(e,ra.END)},locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent(),...e?.signalingAgent?.accountConfig?.applicationType?{applicationType:e.signalingAgent.accountConfig.applicationType}:{}},capabilities:null,endpointCapabilities:r,additionalActions:[{input:{capabilities:null,endpointCapabilities:r,conversationRequest:{applicationType:e.participantManager.localParticipant.applicationType,roster:n,links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},endpointMetadata:e.endpointMetadata,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}},name:"join",url:t,waitForResponse:!0}]}};return e.signalingAgentConfig.ecsEtag&&(s.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),s.payload.additionalActions.length>0&&e.deviceType&&"default"!==e.deviceType&&(s.payload.additionalActions[0].input.conversationRequest.deviceType=e.deviceType),s}function ku(e){return Ua(e,"signalingSession cannot be null"),{payload:{callAcceptanceAcknowledgement:{links:{mediaRenegotiation:Ra(e,ra.MEDIA_RENEGOTIATION),transfer:Ra(e,ra.TRANSFER),replacement:Ra(e,ra.REPLACE),balanceUpdate:Ra(e,ra.BALANCE_UPDATE),retargetCompletion:Ra(e,ra.RETARGET_COMPLETION),controlVideoStreaming:Ra(e,ra.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Ra(e,ra.UPDATE_MEDIA_DESCRIPTIONS)}}}}}function Ou(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=Ha(i);e.telemetryHelper.addOutgoingModalities(r);const s=e.getEndpointCapabilities();return{payload:{callAcceptance:{acceptedBy:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},acceptedCallModalities:r,capabilities:null,endpointCapabilities:s,clientEndpointCapabilities:0!==n?n:null,links:{mediaRenegotiation:Ra(e,ra.MEDIA_RENEGOTIATION),transfer:Ra(e,ra.TRANSFER),replacement:Ra(e,ra.REPLACE),balanceUpdate:Ra(e,ra.BALANCE_UPDATE),retargetCompletion:Ra(e,ra.RETARGET_COMPLETION),controlVideoStreaming:Ra(e,ra.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Ra(e,ra.UPDATE_MEDIA_DESCRIPTIONS)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,callKeepAliveInterval:null,...e?.signalingAgent?.accountConfig?.applicationType?{applicationType:e.signalingAgent.accountConfig.applicationType}:{}}}}}function Nu(e){return Ua(e,"signalingSession cannot be null"),{payload:{callProgress:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},status:"ringing",phrase:"ringing"}}}}function Lu(e,t,i){Ua(e,"signalingSession cannot be null"),Ba(t);const n={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===wa.CALL_END_CODE.CANCEL&&(n.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),n}function xu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED},callTransactionEnd:t}}}function Fu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t}}}function Uu(e,t,i,n,r){Ua(e,"signalingSession cannot be null");const s={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},a=e.getEndpointCapabilities(),o=e.groupId?{id:e.groupId}:null,l=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,c={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,scenario:n.scenario,applicationType:n.applicationType,roster:s,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?n.subscribe?ra.CONV_END_SUBSCRIBE:ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},groupContext:o,groupChat:l,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin}},capabilities:null,endpointCapabilities:a,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("joinConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),c.payload.publishedStates=t}if(n?.applyServerMute&&(c.payload.participants.from.applyServerMute=n.applyServerMute.value,n.applyServerMute.mediaTypes&&(c.payload.participants.from.mediaTypes=n.applyServerMute.mediaTypes)),e.deviceType&&"default"!==e.deviceType&&(c.payload.conversationRequest.deviceType=e.deviceType),!n.subscribe){const r=Ha(i);e.telemetryHelper.addOutgoingModalities(r),c.payload.callInvitation={callModalities:r,replaces:null,transferor:null,links:{progress:Ra(e,ra.PROGRESS),mediaAnswer:Ra(e,ra.MEDIA_ANSWER),acceptance:Ra(e,ra.ACCEPT),redirection:Ra(e,ra.REDIRECTION),end:Ra(e,ra.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent(),sharedLineCallInvitationContent:n.sharedLineCallInvitationContent,invitationData:n.invitationData,callQueueContext:n.callQueueContext}}if(e.signalingAgentConfig.ecsEtag&&(c.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),r&&(c.payload.debugContent||(c.payload.debugContent={}),c.payload.debugContent.causeId=r),n.clientEndpointDebugContent){c.payload.debugContent||(c.payload.debugContent={});try{c.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){xa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{c.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){xa(!1,`Failed to parse ${n.captchaContentJson}`)}return n.callQueueContext&&(c.payload.conversationRequest.callQueueContext=n.callQueueContext),n.participationPreferences&&(c.payload.participationPreferences=n.participationPreferences),n.participantPropertyBag&&(c.payload.participantPropertyBag=n.participantPropertyBag),c}function Bu(e,t,i,n){Ua(e,"signalingSession cannot be null"),Ba(t);const r={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:n&&"all"!==n?void 0:n},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===wa.CALL_END_CODE.CANCEL&&(r.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),r}function Vu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(i,"newOfferLink cannot be null"),{payload:{mediaOfferRequirements:{compatibleContentTypes:t,links:{offerReady:Ra(e,ra.NEW_MEDIA_OFFER)}}}}}function Hu(e,t){return Ua(t,"signalingSession cannot be null"),{payload:{callTransfer:{target:{id:t.participantManager.localParticipant.id},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},parkType:e,links:{transferAcceptance:Ra(t,ra.TRANSFER_ACCEPTANCE),transferCompletion:Ra(t,ra.TRANSFER_COMPLETION)}}}}}function $u(e,t,i){Ua(e,"ParkRequestPayload: signalingSession cannot be null");const n={payload:{hold:{holdType:t,links:{holdCompletion:Ra(e,ra.PARK_COMPLETION)}}}};return i&&(n.payload.debugContent=i),n}function ju(e,t,i,n,r,s){const a={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},publishedState:{content:n,level:i,stateType:t,sequenceNumber:e.getPublishStateSequenceNumber()},scope:r}};if(s&&s.length>0){const e=s.map((e=>({id:e})));a.payload.to=e}return a}function Gu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{callEnd:t}}}function qu(e,t,i,n){const r={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},sequenceNumber:e.getPublishStateSequenceNumber(),scope:t};return"specified"===t?r.stateIds=i:r.stateType=n,{payload:r}}function zu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},searchOptions:t}}}function Wu(e,t,i,n,r){return Ua(t,"signalingSession cannot be null"),Fa(e,"transferTarget cannot be null OR empty"),{payload:{callTransfer:{target:{id:e,endpointType:"TransferTypeVoicemail"===n?"voicemail":void 0},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},links:{transferAcceptance:Ra(t,ra.TRANSFER_ACCEPTANCE),transferCompletion:Ra(t,ra.TRANSFER_COMPLETION)},replacementDetails:i,disableForwardingAndUnanswered:r&&r.disableForwardingAndUnanswered,transferContext:r&&r.clientTransferContext}}}}function Ku(e){return{payload:{transferCompletion:e}}}function Ju(e,t){Ua(e,"ResumePayload: signalingSession cannot be null");const i={payload:{resume:{links:{resumeCompletion:Ra(e,ra.UNPARK_COMPLETION)}}}};return t&&(i.payload.debugContent=t),i}function Yu(e,t){return Ua(t,"clientMetadataJson cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},endpointMetadata:t}}}function Qu(e,t,i,n,r){Ua(t,"clientStateJson cannot be null");const s={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},endpointState:t}};if(r)try{s.payload.captchaContent=JSON.parse(r)}catch(t){e.logger.warn("updateEndpointState getPayload() failed to parse captchaContentJson")}if(i?.publishedStates.length>0){let t=[];t=i.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("updateEndpointState getPayload() failed to parse stateType.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),s.payload.publishedStates=t}return n&&(s.payload.links={updateEndpointStateStatus:Ra(e,ra.DISABLE_PREHEAT_ASYNC_STATUS)}),s}function Zu(e,t){const i={};return void 0!==t.allowRaiseHands&&(i.allowRaiseHands=t.allowRaiseHands),void 0!==t.attendeeRestrictions&&(i.attendeeRestrictions=t.attendeeRestrictions),void 0!==t.lockMeeting&&(i.lockMeeting=t.lockMeeting),void 0!==t.breakoutRoomsEnabled&&(i.breakoutRoomsEnabled=t.breakoutRoomsEnabled),void 0!==t.allowPresentersToManageBreakoutRooms&&(i.allowPresentersToManageBreakoutRooms=t.allowPresentersToManageBreakoutRooms),void 0!==t.disableMdpClientAudioRecording&&(i.disableMdpClientAudioRecording=t.disableMdpClientAudioRecording),void 0!==t.refreshSettings&&(i.refreshSettings=t.refreshSettings),void 0!==t.aiInterpretationEnabled&&(i.aiInterpretationEnabled=t.aiInterpretationEnabled),void 0!==t.groupCopilotDetails&&(i.groupCopilotDetails=t.groupCopilotDetails),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingSettings:i,sequenceNumber:e.getPublishStateSequenceNumber()}}}function Xu(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{mediaAnswer:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaContent:t,pstnContent:e.pstnContent}}}}function eh(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{UpdateMediaDescriptions:{mediaDescriptions:t}}}}var th=p(Z),ih=p(ge()),nh=["CorrelationId","SignalingSessionId","Region","ParticipantId","ClientInformation","ResultCode","ResultDetail","ResultValue","Direction","ClientType","MeetingRoles"],rh=class{constructor(e,t){this.signalingSession=e,this.logger=t,this.logConversationCallModalityEvent=e=>{const t=this.createCallModalityEvent(e);this.logger.info("sending modality telemetry:",this.getStringifiedEventData(t)),t.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(tl,t)},this.logConversationContentSharingEvent=e=>{e[Kc]=this.signalingSession.correlationId,e[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,this.logger.info("sending content sharing telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(il,e)},this.logHttpTelemetryEvent=e=>{e[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,e[Mc]=this.getSignalingAgentConfig(),this.logger.info("sending http telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(nl,e)},this.getHostDomainInfo=()=>"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>",this.getSignalingAgentConfig=()=>{const e=[],t=this.signalingSession.signalingAgentConfig;return t.supportsCompressedServicePayload&&e.push(Lc),t.brokerEnabledOutgoing&&e.push(Dc),t.brokerEnabledIncoming&&e.push(kc),t.brokerRequestBatching&&e.push(Oc),t.brokerExclusively&&e.push(Nc),t.supportsSynchronousTrouterResponse&&e.push(xc),t.handleMediaOfferFromPushNotification&&e.push(Uc),t.handleNewOfferRequest&&e.push(Bc),t.sendProgressFromCC&&e.push(Vc),t.useInternalHttpDispatcher&&e.push(Hc),t.enableTokenCache&&e.push($c),t.enableTokenPrefetch&&e.push(jc),t.supportMediaRetargetWhileIncomingRenegotiation&&e.push(Gc),t.enableCallEstablishmentTimeoutsForStartJoinCall&&e.push(qc),t.enableTokenCacheForGenericTokenAPI&&e.push(zc),t.enableLongOutgoing1To1SetupTimeoutForWeb&&e.push(Wc),e.push(Fc),e.join(",")},this.getStringifiedEventData=e=>{try{return JSON.stringify(e,nh,4)}catch(e){return"invalid data"}},this.telemetryLogger=this.signalingSession.signalingAgentConfig.oneDsTelemetryLogger??this.signalingSession.signalingAgentConfig.telemetryManager}createCallModalityEvent(e){const t={};t.Type=el;const i=(i,n=!1)=>{t[i]=n?JSON.stringify(e[i]):e[i]},n=(t,n=!1)=>{e.hasOwnProperty(t)&&i(t,n)};if(t.ResultDetail=e[Fl],t.ResultValue=e[xl],t.ResultCode=e[wl],t.ResultCauseId=e[Ul],t[Mc]=this.getSignalingAgentConfig(),t[Kc]=this.signalingSession.correlationId,t[Yc]=this.signalingSession.sessionId,i(td),i(id),t[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,i(kl),i(vl,!0),i(Sl,!0),i(Xl,!0),t[yl]=this.signalingSession.multiParty?"true":"false",t[Cl]=this.signalingSession.isHostLessCall?"true":"false",t[Tl]=this.signalingSession.isCastCall?"true":"false",t[El]=this.signalingSession.isHuddleGroupCall?"true":"false",t[_l]=this.signalingSession.onBehalfOf?"true":"false",i(nc),i(Il),i(hl),i(wl,!0),i(Al,!0),n(Jc),n(sl),n(Vl),n(ol,!0),n(ul,!0),n(pl),n(gl),n(ml),n(ec),n(tc),n(ic),n(fl),n(Bl),n(zl),n(Wl),n(Kl),n(Jl),n(Yl),n($l),n(jl),n(Hl),n(ll),n(cl),n(dl),n(cc),n(Rl),n(sc),n(ac),n(dc),n(uc),n(Ll),n(mc),n(pc),n(lc),n(fc),n(vc),n(Sc),n(yc,!0),n(Cc),n(Tc),n(Ec),n(_c),n(Ic),n(wc),n(Dl),this.signalingSession.callType&&(t[Gl]=this.signalingSession.callType),this.signalingSession.signalingAgentConfig.testCall&&(t[ql]="Test"),this.signalingSession.groupId&&(t[Qc]=De(this.signalingSession.groupId)),this.signalingSession.threadId&&(t[Zc]=xe(this.signalingSession.threadId)),this.signalingSession.teamsMessageId&&(t[Xc]=this.signalingSession.teamsMessageId),this.signalingSession.getMeetingInfo()){const e={...this.signalingSession.getMeetingInfo()};e.hasOwnProperty("organizerId")&&(e.organizerId=De(e.organizerId)),t[ed]=JSON.stringify(e)}return this.signalingSession.multiParty&&0===this.signalingSession.numberOfOriginalInvitees&&e.hasOwnProperty(Vl)&&e[Vl]===ud&&(t[bl]="true"),t}},sh=class{constructor(e,t,i){this.signalingSession=e,this.callStartTime=i,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(Rc)},this.addTrouterChannel=()=>{this.setMessagingChannel(Pc)},this.addTrouterWaitOperation=e=>{this.trouterWaitOperations.push(this.recordOperation(e))},this.recordIncomingEvent=(e,t,i)=>{const n=Qa(t),r={origin:t.origin,causeId:n,data:i};i||delete r.data,this.recordEvent(e,r)},this.recordIncomingEventCount=e=>{this.localOperationsPerformed.push(this.recordOperation(e));const t=this.recordedEvents.findIndex((t=>t[e]));if(-1!==t)this.recordedEvents[t][e]+=1;else{const t={};t[e]=1,this.recordedEvents.push(t)}},this.recordEvent=(e,t)=>{this.logger.debug("Event:",e,t),this.localOperationsPerformed.push(this.recordOperation(e));const i={};i[e]=this.timeSinceCallStart(),t&&(i.data=t),this.recordedEvents.push(i)},this.recordRosterEvent=(e,t,i)=>{this.localOperationsPerformed.push(this.recordOperation(t));const n={data:e,causeId:i},r={eventName:this.timeSinceCallStart(),data:n};this.rosterUpdates.push(r)},this.addOutgoingModalities=e=>{e&&this.outgoingModalities.push(e)},this.addIncomingModalities=e=>{e&&this.incomingModalities.push(e)},this.setOfferedModalities=(e,t)=>{this.offeredModalities=this.sdpTelemetryFormat(e,t)},this.setAnsweredModalities=(e,t)=>{this.answeredModalities=this.sdpTelemetryFormat(e,t)},this.setIsSdpInCallNotification=e=>{this.isSdpInCallNotification=e},this.addVbssOperations=e=>{e&&(this.vbssStarted=e===fd,this.vbssOperations.push(this.recordOperation(e)))},this.addNetworkOperationStarted=e=>{qa(this.networkRequestsStarted,e,this.recordOperation(e))},this.addNetworkOperationCompleted=(e,t,i)=>{const n=t?od:ld,r=i?`${e}:${n}:${i}`:`${e}:${n}`;this.networkRequestsCompleted.push(this.recordOperation(r)),za(this.networkRequestsStarted,e)},this.updateNetworkRequest=e=>{this.networkRequests[e.uid]?th.assign(this.networkRequests[e.uid],e):this.networkRequests[e.uid]=e},this.deleteNetworkRequest=e=>{delete this.networkRequests[e.uid]},this.addContentSharingOperation=(e,t,i)=>{this.contentSharingOperationsPerformed[e]||(this.contentSharingOperationsPerformed[e]=[]);const n={[t]:this.timeSinceCallStart()};this.contentSharingOperationsPerformed[e].push(n);const r=this.contentSharingOperationsPerformed[e].length-1;return i&&this.updateContentSharingOperation(e,r,i),r},this.updateContentSharingOperation=(e,t,i)=>{if(!this.contentSharingOperationsPerformed[e])return;const n=this.contentSharingOperationsPerformed[e][t],r=[];for(const e of Object.keys(i))r.push(`${e}: ${i[e]}`);n.data=r.join(", ")},this.setDirection=e=>{this.telemetryData[sl]=e},this.setEndPointId=e=>{this.telemetryData[td]=e,this.contentSharingBaseTelemetryData[td]=e,this.httpRequestTelemetryData[td]=e},this.setParticipantId=e=>{this.telemetryData[id]=e,this.contentSharingBaseTelemetryData[id]=e,this.httpRequestTelemetryData[id]=e},this.addTokenTelemetry=(e,t)=>{e?this.networkRequests?.[e]?(this.networkRequests[e].tokenTelemetries||(this.networkRequests[e].tokenTelemetries=[]),this.networkRequests[e].tokenTelemetries.push(t)):this.logger.info(`[addTokenTelemtry] httprequest: ${e} is not found in networkRequests`):this.logger.error("[addTokenTelemetry] httprequest uid is undefined")},this.setConversationServiceUrl=e=>{this.telemetryData[kl]=e},this.setMeetingInfo=e=>{e||(this.telemetryData[Nl]=e)},this.setJoinedFrom=e=>{this.telemetryData[Ll]=e},this.setMeetingCode=e=>{this.telemetryData[pc]=e},this.setMeetingUrl=e=>{this.telemetryData[mc]=e},this.setBroadcastMeetingRole=e=>{this.telemetryData[fc]=e},this.setMeetingRole=e=>{this.telemetryData[vc]=e},this.setAdvancedMeetingRole=e=>{this.telemetryData[Sc]=e},this.setParticipantType=e=>{this.telemetryData[Cc]=e},this.setSelfParticipantRole=e=>{this.telemetryData[Vl]=e},this.setDisplayName=e=>{const t=new Re(e,1);this.telemetryData[Tc]=t},this.setAudioOnlyWatermark=e=>{this.telemetryData[Ec]=e},this.setWatermarkSupport=e=>{this.telemetryData[bc]=e},this.setClientSupportsPreventScreenCapture=e=>{this.telemetryData[Ac]=e},this.setScenario=e=>{this.telemetryData[Hl]=e},this.setTargetApplicationType=e=>{e&&(this.telemetryData[_c]=e)},this.setCallerType=e=>{e&&(this.telemetryData[$l]=e.split(":",1)[0])},this.setCalleeType=e=>{e&&(this.telemetryData[jl]=e.split(":",1)[0])},this.setTerminatingData=e=>{this.telemetryData[hl]=e.terminatingEnd,this.telemetryData[wl]=e.endCode||wa.CALL_END_CODE.SUCCESS,this.telemetryData[Al]=e.endSubCode||wa.CALL_END_SUB_CODE.SUCCESS,this.telemetryData[Pl]=e.phrase||wa.CALL_END_PHRASE.UNKNOWN,this.telemetryData[xl]=e.resultValue||od,this.telemetryData[Fl]=e.resultDetail||"Call gracefully hungup",this.telemetryData[Ul]=e.causeId||"unknown",this.telemetryData[Rl]=e.resultCategories||[],this.telemetryData[hc]=e.clientReasonSubCode,this.telemetryData[gc]=e.clientReasonPhrase},this.startCallInitializationWatch=e=>{this.timeToRingStopWatch=tu(),e&&(this.timeToRingStopWatch.msElapsed+=e)},this.startCallConnectedWatch=()=>{this.connectedStopWatch=tu()},this.setIsPreheated=()=>{this.isPreheated=1},this.startPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch=tu()},this.stopPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch.pause()},this.startCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=tu()},this.stopCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch&&this.callCancelationDurationWatch.pause()},this.getCallCancelationDuration=()=>this.callCancelationDurationWatch?this.callCancelationDurationWatch.durationInSeconds():0,this.resetCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=null},this.setOfferAnswerGenerationTimestamps=e=>{this.localOfferAnswerGenerationTimestamps.push(this.recordOperation(e))},this.setTimeToRingDuration=()=>{this.timeToRingStopWatch&&(this.telemetryData[ul]=this.timeToRingStopWatch.duration(),this.timeToRingStopWatch=null)},this.dispose=()=>{this.sendCallModalityTelemetryData()},this.setMessagingChannel=e=>{this.telemetryData[Xl]||(this.telemetryData[Xl]=[]),this.telemetryData[Xl].some((t=>-1!==t.indexOf(e)))||this.telemetryData[Xl].push(this.recordOperation(e))},this.sendHttpTelemetryData=e=>{const t={...this.httpRequestTelemetryData};t[Kc]=this.signalingSession.correlationId,t[Yc]=this.signalingSession.sessionId,t[nc]=this.signalingSession.signalingAgentConfig.clientInformation;const i=JSON.stringify({eventStart:this.callStartTime,events:this.networkRequests[e]});za(this.networkRequests,e),t[ic]=i,this.telemetryLogger.logHttpTelemetryEvent(t)},this.sdpTelemetryFormat=(e,t)=>{if(!e)return"";const i=e=>{switch(e){case"main-audio":return"Audio";case"main-video":return"Video";case"applicationsharing-video":return"AppSharing";default:return}},n=e=>{switch(e){case"inactive":return"Inactive";case"sendonly":return t?"ReceiveFromPeer":"SendToPeer";case"recvonly":return t?"SendToPeer":"ReceiveFromPeer";default:return"Bidirectional"}},r={"main-audio":0,"main-video":0,"applicationsharing-video":0},s=[],a=ih.parse(e);for(const e of a.media){const t=i(e.label);if(!t)continue;const a=r[e.label]++,o=n(e.direction);s.push(`${t}[${a}] = ${o}`)}return s.join(", ")},this.setReinviteless=e=>{this.isReinviteless=e?1:0},this.logger=e.logger,this.telemetryLogger=function(e,t){return new rh(e,t)}(e,this.logger),this.telemetryData[vl]=this.callStartTime,this.telemetryData[kl]=e.signalingAgentConfig.conversationServiceUrl,this.fillCommonData(t,this.telemetryData),this.fillCommonData(t,this.httpRequestTelemetryData),this.fillCommonData(t,this.contentSharingBaseTelemetryData)}fillCommonData(e,t){t[sc]=e.applicationType,t[ac]=e.ring,t[oc]=e.tenantId,t[lc]=e.userHexCID,t[cc]=e.acsResourceId,t[dc]=e.region,t[uc]=e.partition,t[wc]=e.clientType}addChangingCorrelationId(e,t){this.telemetryData[Zl]=e,this.telemetryData[Ql]=t}addSharedCorrelationId(e){this.telemetryData[Jc]=e}setMeetingRoles(e){this.telemetryData[yc]=e}setConflictingCallId(e){this.telemetryData[Dl]=e}sendContentSharingTelemetryData(e,t,i,n,r,s){const a={...this.contentSharingBaseTelemetryData},o=this.contentSharingOperationsPerformed[e];o&&(a[ec]=JSON.stringify(o)),a[rd]=e,a[Yc]=t,a[nd]=s||"",a[Ol]=r,a[al]=i?dd:cd,a[wl]=n.code,a[Al]=n.subCode,a[Pl]=n.phrase,a[Rl]=this.getResultCategoryString(n.resultCategories),a[Ml]=n.causeId,a[nc]=this.signalingSession.signalingAgentConfig.clientInformation,delete this.contentSharingOperationsPerformed[e],this.telemetryLogger.logConversationContentSharingEvent(a)}recordOperation(e){return`${e}:${this.timeSinceCallStart()}`}timeSinceCallStart(){return(new Date).getTime()-this.callStartTime}sendCallModalityTelemetryData(){this.vbssStarted&&this.addVbssOperations(Td);const e=e=>"number"==typeof e?e/1e3:0;if(this.telemetryData[nc]=this.signalingSession.signalingAgentConfig.clientInformation,this.telemetryData[Sl]=(new Date).getTime(),this.connectedStopWatch&&(this.telemetryData[ol]=this.connectedStopWatch.duration()),this.telemetryData[dl]=this.isPreheated,this.preheatedCallSetupDurationWatch&&(this.telemetryData[ll]=e(this.preheatedCallSetupDurationWatch.duration())),this.callCancelationDurationWatch&&(this.telemetryData[cl]=e(this.callCancelationDurationWatch.duration())),this.networkRequestsCompleted.length&&(this.telemetryData[pl]=JSON.stringify(this.networkRequestsCompleted)),this.localOperationsPerformed.length&&(this.telemetryData[ml]=JSON.stringify(this.localOperationsPerformed)),this.trouterWaitOperations.length&&(this.telemetryData[fl]=JSON.stringify(this.trouterWaitOperations)),this.localOfferAnswerGenerationTimestamps.length&&(this.telemetryData[Bl]=JSON.stringify(this.localOfferAnswerGenerationTimestamps)),this.incomingModalities.length&&(this.telemetryData[Wl]=JSON.stringify(this.incomingModalities)),this.outgoingModalities.length&&(this.telemetryData[zl]=JSON.stringify(this.outgoingModalities)),this.offeredModalities.length&&(this.telemetryData[Kl]=this.offeredModalities),this.answeredModalities.length&&(this.telemetryData[Jl]=this.answeredModalities),this.telemetryData[Rl]=this.getResultCategoryString(this.telemetryData[Rl]),this.telemetryData[Il]=this.isSdpInCallNotification.toString(),this.vbssOperations.length&&(this.telemetryData[Yl]=JSON.stringify(this.vbssOperations)),this.recordedEvents.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.recordedEvents});this.telemetryData[ec]=e}if(this.rosterUpdates.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.rosterUpdates});this.telemetryData[tc]=e}const t=[];for(const e of Object.keys(this.networkRequestsStarted))t.push(this.networkRequestsStarted[e]);t.length>0&&(this.telemetryData[gl]=JSON.stringify(t)),this.telemetryData[Ic]=this.isReinviteless,this.telemetryLogger.logConversationCallModalityEvent(this.telemetryData)}getResultCategoryString(e){return e&&Array.isArray(e)?e.join(","):""}},ah=class{constructor(e,t){this.disposed=!1,this.lastSeenSeqNumbers={},this.isDominantSpeakerInfoLinkEnabled=!0,this.clientUrlsGenerated=!1,this.getClientUrls=()=>{this.clientUrlsGenerated=!0;let e=null;return this.isWebRtcCall&&(e={controlVideoStreaming:Ra(this.signalingSession,ra.CONTROL_VIDEO_STREAMING),csrcInfo:Ra(this.signalingSession,ra.CSRC_INFO)},this.isDominantSpeakerInfoLinkEnabled&&(e.dominantSpeakerInfo=Ra(this.signalingSession,ra.DOMINANT_SPEAKER_INFO))),e},this.handleDominantSpeakerInfo=e=>{const t=e.body;this.logger.debug("handleDominantSpeakerInfo : ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEventCount("HandleDominantSpeakerChangedCount"),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO,t.dominantSpeakerInformation)},this.handleControlVideoStreaming=e=>{const t=e.body;this.logger.debug("handleControlVideoStreaming: ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleControlVideoStreaming",e),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING,t.controlVideoStreaming,!1)},this.handleCsrcInfo=e=>{const t=e.body;this.logger.debug("handleCsrcInfo : ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleCsrcInfo",e),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO,t.csrcInfo)},this.sendWebRtcMediaNotificationAsync=({operation:e,requestUrl:t,requestBody:i,stackRetry:n=!0},r)=>{this.logger.info("sendWebRtcMediaNotificationAsync"),xa(this.isWebRtcCall,"this is not a webrtc call"),Fa(t,"correct media notification requestUrl is not provided"),Fa(i,"media notification requestBody cannot be null or empty");const s=to(),a={url:t,payload:{payload:i},requestName:e,withoutTrouter:!0,causeId:r};return n||(a.disableRetry=!0),this.signalingSession.http.sendPostRequest(a).then((()=>{this.disposed||s.resolve()})).catch((e=>{const t=je(e);if(this.logger.error(`sendWebRtcMediaNotificationAsync failed because : ${t}`),!this.disposed){const t=new Error(e);t.endCode=wa.CALL_END_NETWORK_ERROR,s.reject(t)}})),s.promise},this.dispose=()=>{this.logger.info("WebRtcSignalingManager :: dispose"),this.disposed=!0},this.signalingSession=e,this.signalingSessionCallback=t,this.isWebRtcCall=e.signalingAgentConfig.isWebRtcEnabled,this.logger=e.logger,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING]=-1,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO]=-1,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO]=-1}areClientURLsGenerated(){return this.clientUrlsGenerated}getIsDominantSpeakerInfoLinkEnabled(){return this.isDominantSpeakerInfoLinkEnabled}setIsDominantSpeakerInfoLinkEnabled(e){this.isDominantSpeakerInfoLinkEnabled=e}handleWebRtcNotification(e,t,i=!0){xa(this.isWebRtcCall,"ignoring message in non-webrtc call");const n=this.lastSeenSeqNumbers[e];i&&t.sequenceNumber<=n?this.logger.info(`ignoring ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`):(t.sequenceNumber<=n&&this.logger.info(`let listener to handle older ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`),this.lastSeenSeqNumbers[e]=Math.max(t.sequenceNumber,this.lastSeenSeqNumbers[e]),this.signalingSessionCallback.onWebRtcMediaNotification(e,t))}},oh=class{constructor(e,t,i,n,r,s){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=La(),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.meetingLayoutDetails=null,this.compositionServiceDetails=null,this.realTimeState=0,this.disposing=!1,this.links={},this.provisionalMediaAnswersSeenSoFar=[],this.incomingTrouterMessagesSeenSoFar=[],this.incomingBrokerMessagesSeenSoFar=[],this.currentCallStatus=null,this.fsmState=wa.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=to(),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=(e,t=Na(),i,n)=>{this.logger.info(`[${t}][requestedEndpointState=${je(e,!0)}][captchaContentJson=${n}]`);const r=this.links[wa.LINKS.UPDATE_ENDPOINT_STATE],s=this.getEndpointState();this.logger.info(`[${t}][currentEndpointState=${je(s,!0)}] startOrJoinConvResponseReceived=${this.startOrJoinConvResponseReceived}`);const a={...s,...e,endpointStateSequenceNumber:++this.endpointStateSequenceNumber};this.telemetryHelper.recordEvent("UpdateEndpointState",{newEndpointState:a,causeId:t});const o=0===a?.endpointProperties?.preheatProperties&&this.isPreheatOnly;if(o&&(this.telemetryHelper.recordEvent("DisablingPreheat",{causeId:t}),this.telemetryHelper.startPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallCancelationDurationWatch()),2===this.callMode&&o)return this.logger.info(`[${t}][updateEndpointState skipped as mode is streaming]`),this.handleEndpointStateUpdated(t,!0),Promise.resolve();if(!this.startOrJoinConvResponseReceived)return this.logger.info(`[${t}][updateEndpointState will be queued as we don't have a link yet]`),this.requestedEndpointStateWhileConnecting=e,this.requestedPublishedStatesWhileConnecting=i,o?this.disablePreheatDefer.promise:Promise.resolve();if(!this.shouldUpdateEndpointState(s,a)&&!this.http.hasPendingRequest(Zo.UPDATE_ENDPOINT_STATE.name))return this.logger.info(`[${t}][updateEndpointState will ignore current update as there is nothing new to send]`),Promise.resolve();if(!r)return this.logger.info(`[${t}][updateEndpointState operation cannot be performed now, the link is not yet available]`),Promise.reject("No link");this.latestEndpointState=a;const l=this.signalingAgentConfig.enableAsyncDisablePreheat&&o;l&&this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT,(()=>{const e={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.DISABLE_PREHEAT_TIMEOUT,phrase:wa.CALL_END_PHRASE.DISABLE_PREHEAT_TIMEOUT};this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject({response:e})}),wa.TIMEOUT_VALUES_IN_SECONDS.DISABLE_PREHEAT_TIMEOUT);const c=this.http.sendPostRequest({url:r,requestName:Zo.UPDATE_ENDPOINT_STATE.name,payload:Qu(this,a,i,l,n),causeId:t}).then((()=>(l&&(this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: true`),this.telemetryHelper.recordEvent("DisablePreheatResponseReceived",{causeId:t})),Promise.resolve()))).catch((e=>{if(!l)throw e;this.disablePreheatDefer.reject(e)}));return(l?this.disablePreheatDefer.promise:c).then((()=>{this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: ${l}`),this.telemetryHelper.recordEvent(l?"AsyncDisablePreheatSucceeded":"DiablePreheatSucceeded",{causeId:t}),this.disposed||this.handleEndpointStateUpdated(t,o)})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointState] error: ${je(i)}`),o&&(this.handleDisablePreheatError(i.error,l?"AsyncDiablePreheatFailed":"DiablePreheatFailed",t),this.stopCallPreheatTimer(),this.terminateEstablishedCall({code:i.error.code,subCode:i.error.subCode,phrase:i.error.phrase},{forEveryone:!1,causeId:t})),Promise.reject(i.error)}))},this.setParticipantCallLinks=e=>{e&&e.endpointDetails&&(this.participantReplacementDetails[e.id]={},e.endpointDetails.forEach((t=>{t&&t.callLinks&&(this.participantReplacementDetails[e.id][t.participantId]=t.callLinks)})))},this.clearParticipantCallLinks=e=>{this.participantReplacementDetails?.hasOwnProperty(e)&&delete this.participantReplacementDetails[e]},this.getReplacementDetailsByParticipantLeg=(e,t,i=Na())=>(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: participantMri ${this.piiUtils.scrubMriOrOmit(e)} participantLegId ${t}`),this.participantReplacementDetails?.hasOwnProperty(e)&&this.participantReplacementDetails[e].hasOwnProperty(t)?{replaces:this.participantReplacementDetails[e][t].replacement,replacementTargetParticipantId:t}:(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: unable to find replacement details for participantLegId ${t}`),{})),this.getReplacementDetailsByParticipantLegOfCall=(e,t,i,n=Na())=>{this.logger.info(`[${n}]getReplacementDetailsByParticipantLegOfCall: callId ${e} participantMri ${this.piiUtils.scrubMriOrOmit(t)} participantLegId ${i}`);const r=this.signalingAgent.getSignalingSession(e);return r?r.getReplacementDetailsByParticipantLeg(t,i,n):{}},this.getMriByParticipantLegOfCall=(e,t,i)=>{this.logger.info(`[${i}]getMriByParticipantLegOfCall: callId: ${e} participantLegId ${t}`);const n=this.signalingAgent.getSignalingSession(e);return n?n.getMriByParticipantLeg(t,i):""},this.getMriByParticipantLeg=(e,t)=>{this.logger.info(`getMriByParticipantLeg[${t}] participantLegId ${e}`);for(const t of Object.keys(this.participantReplacementDetails))if(t&&this.participantReplacementDetails.hasOwnProperty(t)&&this.participantReplacementDetails[t]?.hasOwnProperty(e))return t;return""},this.handleEndpointStateUpdated=(e,t)=>{this.requestedEndpointStateWhileConnecting=null,this.requestedPublishedStatesWhileConnecting=null,t&&this.handlePreheatDisabled(e)},this.handlePreheatDisabled=e=>{this.isPreheatOnly=!1,this.telemetryHelper.setSelfParticipantRole(this.originalRoleBeforePreheat),this.telemetryHelper.recordEvent("PreheatDisabled",{causeId:e}),this.telemetryHelper.resetCallCancelationDurationWatch(),this.telemetryHelper.stopPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallConnectedWatch(),this.stopCallPreheatTimer(),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.resolve()},this.shouldUpdateEndpointState=(e,t)=>{if(!t)return!1;const i=t.state&&t.state.isMuted?1:0,n=t.endpointProperties&&1===t.endpointProperties.preheatProperties?1:0,r=e&&e.state&&e.state.isMuted?1:0,s=e&&e.endpointProperties&&1===e.endpointProperties.preheatProperties?1:0,a=e?.endpointProperties?.additionalEndpointProperties,o=t?.endpointProperties?.additionalEndpointProperties;return!!(i^r||n^s||o!==a)},this.setInitialTelemetry=(e,t)=>{let i,n;switch(e){case"Subscribe":this.telemetryHelper.recordEvent("JoinConversationWithoutCallModality",{causeId:t.causeId,correlationId:t.correlationId}),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(pd),this.telemetryHelper.setConversationServiceUrl(t.conversationServiceUrl||this.signalingAgentConfig.conversationServiceUrl),this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);break;case"Acknowledge":this.telemetryHelper.recordEvent("HandleIncomingCall",{causeId:t.causeId}),this.telemetryHelper.setDirection(cd),this.telemetryHelper.setSelfParticipantRole(hd),this.telemetryHelper.setCalleeType(this.participantManager.localParticipant.id);break;case"JoinCall":i=this.gatherTelemetryForStartOrJoin(t.joinCallOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent("JoinCall",i),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(gd);break;case"StartCall":case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":n=this.gatherTelemetryForStartOrJoin(t.callStartOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent("StartCall",n),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(ud),this.telemetryHelper.startCallInitializationWatch(t.offerGenerationTime),this.telemetryHelper.setMeetingInfo(this.getMeetingInfo())}},this.getParticipantIdForOfferAnswer=e=>{Ua(e,"mediaContent should be a non null value"),this.logger.info("getParticipantIdForOfferAnswer");let t=null;return!this.remoteUser||this.groupId||this.threadId||e.newOffer||e.escalationOccurring||(t=this.remoteUser.id),t},this.getMeetingInfo=()=>this.meetingInfo,this.getEmergencyContent=()=>(this.telemetryHelper.recordEvent("GetEmergencyContent"),this.emergencyContent),this.getEndpointId=()=>this.signalingAgent.endpointId,this.getConversationUrl=()=>this.links[wa.LINKS.CONVERSATION_CONTROLLER],this.setJoinedFrom=e=>{!this.disposed&&e&&(this.telemetryHelper.recordEvent("SetJoinedFrom"),this.telemetryHelper.setJoinedFrom(e))},this.setMeetingCode=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingCode(e)},this.setMeetingUrl=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingUrl(e)},this.setSubject=e=>{this.disposed||(this.telemetryHelper.recordEvent("SetSubject"),Ua(e,"subject should be a non null value"),this.convSubject=e)},this.setDeviceType=e=>{this.disposed||(this.telemetryHelper.recordEvent("SetDeviceType"),e&&(this.deviceType=e,this.logger.info("setDeviceType",this.deviceType)))},this.setOfferAnswerGenerationTimestamps=e=>{this.disposed||this.telemetryHelper.setOfferAnswerGenerationTimestamps(e)},this.setTimeToRingDuration=()=>{this.disposed||this.telemetryHelper.setTimeToRingDuration()},this.setGroupId=e=>{this.telemetryHelper.recordEvent("SetGroupId"),this.groupId!==e&&e&&(xa(!this.groupId,"conversation groupId has already been set. It cannot be overwritten"),this.groupId=e)},this.setThreadId=e=>{this.telemetryHelper.recordEvent("SetThreadId"),Ua(e,"threadId should be a non null value"),this.threadId!==e&&(xa(!this.threadId,"conversation threadId has already been set. It cannot be overwritten"),this.threadId=e)},this.setDisplayName=e=>{!this.disposed&&e&&this.telemetryHelper.setDisplayName(e)},this.setCallOptions=e=>{if(Ua(e,"callOptions should be a non null value"),this.logger.info("setCallOptions",je(e)),this.telemetryHelper.recordEvent("SetCallOptions"),e){this.teamsMessageId=e.teamsMessageId,this.meetingInfo=e.meetingInfo||null,this.emergencyContent=e.emergencyContent||null,this.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration||!1,e.broadcastContext&&(this.broadcastSession=new jd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e.broadcastContext));try{this.endpointMetadata=JSON.parse(e.endpointMetadata)}catch(e){this.logger.warn("Unable to parse endpoint metadata")}}},this.setTransferContext=e=>{Ua(e,"transferContext should not be null"),this.logger.info("Transfer: setTransferContext",ke(e)),this.telemetryHelper.recordEvent("SetTransferContext"),this.transferContext=e},this.muteAsync=(e,t,i=Na())=>(xa(2!==this.callMode||e!==wa.MUTE_SCOPE.MYSELF,"mute self operation is not allowed in streaming mode"),this.logger.info(`[${i}][muteAsync][scope=${e}]`),this.telemetryHelper.recordEvent("Mute",{causeId:i}),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,`[${i}]mute operation for all or specified only allowed in a connected call`),this.participantManager.muteAsync(this.links[wa.LINKS.MUTE],e,t,i)),this.unmuteAsync=(e=Na())=>(xa(2!==this.callMode,"unmute operation is not allowed in streaming mode"),this.logger.info(`[${e}][unmuteAsync]`),this.telemetryHelper.recordEvent("Unmute",{causeId:e}),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"unmute operation only allowed in a connected call"),this.participantManager.unmuteAsync(this.links[wa.LINKS.UNMUTE],e)),this.recordTelemetryForStartAudio=(e,t)=>(this.telemetryHelper.recordEvent("StartAudio",{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.recordTelemetryForStopAudio=(e,t)=>(this.telemetryHelper.recordEvent("StopAudio",{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.rejectUnmuteRequestAsync=(e,t=Na(),i)=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"rejectUnmute operation only allowed in a connected call"),Fa(e,"requestor must be specified"),this.logger.info(`[${t}][rejectUnmuteRequestAsync][rejectionReason=${i}]`),this.telemetryHelper.recordEvent("RejectUnmute",{causeId:t,rejectionReason:i}),this.participantManager.rejectUnmuteRequestAsync(e,t,i)),this.approveUnmuteRequestAsync=(e,t=Na())=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"approveUnmute operation only allowed in a connected call"),Fa(e,"requestor must be specified"),this.logger.info(`[${t}][approveUnmuteRequestAsync]`),this.telemetryHelper.recordEvent("ApproveUnmute",{causeId:t}),this.participantManager.approveUnmuteRequestAsync(e,t)),this.sendWebRtcMediaNotificationAsync=(e,t,i=Na())=>(xa(2!==this.callMode,"sendWebRtcMediaNotification operation is not allowed in streaming mode"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"webRtc media notification can only be sent in a connected call"),this.telemetryHelper.recordEvent("SendWebRtcMediaNotification",{causeId:i}),0===e?this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:Zo.SEND_APPLY_CHANNEL_PARAMETERS.name,requestUrl:this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS],requestBody:t,stackRetry:!1},i):this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:Zo.SEND_CONTROL_VIDEO_STREAMING.name,requestUrl:this.links[wa.LINKS.CONTROL_VIDEO_STREAMING],requestBody:t},i)),this.addParticipantsAsync=(e,t,i=Na())=>{Fa(e,"remoteParticipants should be a non null value"),xa(this.isCallOngoing()||this.isCallNotConnected(),"remoteParticipants can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${i}][addParticipantsAsync][addParticipantOptions=${je(t)}]\n [remoteParticipantId=${e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)))}]`);let n=So;switch(t.replacementType){case 2:n="AddParticipantWithPickupCode";break;case 1:case 3:n="AddParticipantWithReplaces";break;default:n=So}this.telemetryHelper.recordEvent(n,{causeId:i}),t.groupId=this.groupId||t.groupId,t.threadId=this.threadId||t.threadId;const r=t.threadId||t.groupId?this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[wa.LINKS.ADD_PARTICIPANT],s=this.participantManager.addParticipantsAsync(e,r,this.isCallConnectedOrConnectedForRoster(),t,i);return this.currentCallStatus||this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i),s},this.addGroupModalityAsync=(e,t)=>{xa(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addGroupModalityAsync][addGroupModalityOptions=${je(e)}]`);this.telemetryHelper.recordEvent("AddParticipantsAndModality",{causeId:t});const i=Su(this,null,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY],payload:i,requestName:Zo.ADD_PARTICIPANTS_AND_MODALITY.name,causeId:t}).then((()=>{kd.noop()})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);throw this.logger.info(`[${t}][sendNetworkRequestForAddingParticipant] failed:${je(i)}`),i.error}))},this.addModalityAsync=(e,t)=>{xa(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addModalityAsync][modalityContext=${je(e)}]`),this.telemetryHelper.recordEvent("AddModality",{causeId:t});const i=function(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"broadcastContext cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},groupContext:t.groupContext?{id:t.groupContext.groupId}:null,groupChat:t.groupChat?{threadId:t.groupChat.threadId,messageId:t.groupChat.messageId}:null,links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}(this,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_MODALITY],payload:i,requestName:Zo.ADD_MODALITY.name,causeId:t}).then((e=>(this.logger.info(`[${t}][addModalityAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForAddModalityCompletion",{causeId:t}),wa.SUCCESS_TRANSACTION_END))).catch((e=>{const i=Ka(e);return this.logger.info(`[${t}][sendNetworkRequestForAddModalityAsync] failed:${je(i)}`),Promise.reject(i.error)}))},this.addBroadcastModalityAsync=(e,t)=>{if(xa(this.isCallOngoing(),"BroadcastModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addBroadcastModalityAsync][addBroadcastContext=${je(this.addBroadcastModalityAsync)}]`),this.telemetryHelper.recordEvent("AddBroadcastModality",{causeId:t}),this.broadcastSession){const e="There is already a broadcast session";return this.logger.info(e),Promise.resolve(wa.SUCCESS_TRANSACTION_END)}this.broadcastSession=new jd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e);const i=function(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"broadcastContext cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},broadcast:t,links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}(this,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_MODALITY],payload:i,requestName:Zo.ADD_BROADCAST_MODALITY.name,causeId:t}).then((e=>(this.logger.info(`[${t}][addBroadcastModalityAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForAddBroadcastModalityCompletion",{causeId:t}),wa.SUCCESS_TRANSACTION_END))).catch((e=>{const i=Ka(e);return this.logger.info(`[${t}][sendNetworkRequestForAddBroadcastModalityAsync] failed:${je(i)}`),this.endBroadcastMeeting(t),Promise.reject(i.error)}))},this.nudgeParticipantsAsync=e=>{if(Ua(e.participantsIds,"ParticipantsIds should be a non null value"),xa(this.isCallOngoing(),"Participants can only be nudged before starting an outgoing call or to an ongoing call"),this.logger.info(`[${e.causeId}][nudgeParticipantsAsync][participantsIds=${this.piiUtils.scrubParticipantsList(e.participantsIds)}][invitationData=${e.invitationData}]`),void 0===e.participantsIds||e.participantsIds.length<1)return Promise.reject("List of participants to nudge is empty");this.telemetryHelper.recordEvent(So,{withNudge:wa.INVITATION_TYPE.NUDGE,causeId:e.causeId});const t=this.groupId||e.newGroupId,i=this.threadId||e.newThreadId,n=this.teamsMessageId||e.newMessageId,r=i||t?this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[wa.LINKS.ADD_PARTICIPANT];return this.participantManager.nudgeParticipantsAsync(e.participantsIds,r,this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,e.causeId,e.invitationData,t,i,n)},this.callMeBackAsync=(e,t=Na())=>(Ua(e,"remoteParticipant should be a non null value"),this.logger.info(`[${t}][callMeBackAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent("CallMeBack",{causeId:t}),this.hasGroupModality()||xa(!1,"threadId/groupId must be set before using call me back"),this.participantManager.callMeBackAsync(e,this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY],t)),this.removeParticipantAsync=(e,t=Na(),i="none")=>{switch(Ua(e,"remoteParticipant should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"participants can only be removed from an ongoing call"),this.logger.info(`[${t}][removeParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}] [removeEndpointScope] ${i}`),i){case"all":this.telemetryHelper.recordEvent("RemoveParticipantOthers",{causeId:t});break;case"specified":this.telemetryHelper.recordEvent("RemoveParticipantSpecified",{causeId:t});break;default:this.telemetryHelper.recordEvent("RemoveParticipant",{causeId:t})}return"none"!==i&&e.endpointId?this.participantManager.removeParticipantEndpointAsync(e,this.links[wa.LINKS.REMOVE_PARTICIPANT],i,t):this.participantManager.removeParticipantAsync(e,this.links[wa.LINKS.REMOVE_PARTICIPANT],t)},this.admitParticipantAsync=(e,t=Na())=>(Ua(e,"remoteParticipant should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"remoteParticipants can only be admitted to an ongoing call"),this.hasGroupModality()||xa(!1,"threadId/groupId must be set before admitting more participants to connected call"),this.logger.info(`[${t}][admitParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent("AdmitParticipant",{causeId:t}),this.participantManager.admitParticipantAsync(e,this.links[wa.LINKS.ADMIT],t)),this.admitAsync=e=>{if(this.logger.info(`[${e}][admitAsync]`),this.telemetryHelper.recordEvent("Admit",{causeId:e}),!this.links[wa.LINKS.ADMIT_ALL]){const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.ADMIT_ALL_LINK_MISSING,phrase:wa.CALL_END_PHRASE.ADMIT_ALL_URL_MISSING};return this.telemetryHelper.recordEvent(To,{causeId:e,transactionEnd:t}),this.logger.warn(`admitAsync error ${je(t)}`),Promise.reject(t)}const t=to();return this.callOperationHandler.setPendingOperation(0,e,{promise:t,causeId:e},e),this.sendNetworkRequestForAdmit(e),t.promise},this.updateMeetingRolesAsync=(e,t,i=Na())=>(Ua(e,"participants array should be a non null value"),Ua(t,"meetingRole should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"remote participant roles can only be updated in an ongoing call"),this.logger.info(`[${i}][updateMeetingRolesAsync][participants=${this.piiUtils.scrubMriOrOmit(e)}]`),this.participantManager.updateMeetingRolesAsync(e,t,this.links[wa.LINKS.UPDATE_PARTICIPANT_ROLE],i)),this.startContentSharingAsync=(e,t,i,n,r=Na())=>(Ua(e,"contentIdentifier should be a non null value"),xa(this.isCallOngoing(),"contentSharing can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${r}][startContentSharingAsync]`),this.telemetryHelper.recordEvent("AddContentSharingModality",{causeId:r}),this.contentSharingManager.startContentSharingAsync(e,t,i,this.links[wa.LINKS.ADD_MODALITY],this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,r,n)),this.deleteContentSharingAsync=(e,t=Na())=>(this.logger.info(`[${t}][deleteContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent("DeleteContentSharing",{causeId:t,correlationId:e}),this.contentSharingManager.deleteContentSharingAsync(e,t)),this.joinContentSharingAsync=(e,t=Na())=>(this.logger.info(`[${t}][joinContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent("JoinContentSharing",{causeId:t,correlationId:e}),this.contentSharingManager.joinContentSharingAsync(e,t)),this.updateContentSharingSessionStateAsync=(e,t,i=Na())=>(Ua(t,"sessionState should be a non null value"),this.telemetryHelper.recordEvent("UpdateSessionStateContentSharing",{causeId:i,correlationId:e}),this.logger.info(`[${i}][updateContentSharingSessionStateAsync][correlationId=${e}][sessionState=${t}]`),this.contentSharingManager.updateContentSharingSessionStateAsync(e,t,i)),this.takeContentSharingControlAsync=(e,t=Na())=>(this.telemetryHelper.recordEvent("TakeControlContentSharing",{causeId:t,correlationId:e}),this.logger.info(`[${t}][takeContentSharingControlAsync][correlationId=${e}]`),this.contentSharingManager.takeContentSharingControlAsync(e,t)),this.updateContentSharingParticipantStateAsync=(e,t=Na())=>(this.telemetryHelper.recordEvent("UpdateParticipantStateContentSharing",{causeId:t}),this.logger.info(`[${t}][updateContentSharingParticipantStateAsync][correlationId=${e}]`),this.contentSharingManager.updateContentSharingParticipantStateAsync(e,t)),this.configureEndpointStateForStartOrJoin=e=>{const t={endpointStateSequenceNumber:this.endpointStateSequenceNumber};let i=!1;if(e&&(e.muted&&(i=!0,Object.assign(t,{state:{isMuted:e.muted}})),e.isPreheatOnly||e.additionalEndpointProperties)){const n={};i=!0,e.isPreheatOnly&&(n.preheatProperties=1),e.additionalEndpointProperties&&(n.additionalEndpointProperties=e.additionalEndpointProperties),Object.assign(t,{endpointProperties:n})}if(i)return t},this.gatherTelemetryForStartOrJoin=(e,t,i)=>{const n={causeId:t};return e&&(e.invitationType===wa.INVITATION_TYPE.NUDGE&&(n.withNudge=e.invitationType===wa.INVITATION_TYPE.NUDGE),e.parkContext&&(n.unpark=!0,n.context=e.parkContext),e.isPreheatOnly&&(n.isPreheatOnly=!0),e.targetApplicationType&&(n.targetApplicationType=e.targetApplicationType,this.telemetryHelper.setTargetApplicationType(e.targetApplicationType))),n},this.startOutgoingCall=(e,t,i,n,r=Na())=>{if(Ua(e,"mediaContent should be a non null value"),Ua(e.blob,"outgoingSdp should be a non null value"),xa(this.isCallNotConnected(),"a call is already in progress"),this.logger.info(`[${r}][startOutgoingCall][start] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${r}][startOutgoingCall][failed][reason=Session disposed]`);this.lastUsedJoinCallOptions={muted:i?i.muted:null,scenario:i?i.scenario:null,isPreheatOnly:i?i.isPreheatOnly:null,clientEndpointCapabilities:i?i.clientEndpointCapabilities:null,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null},this.originalRoleBeforePreheat=ud,i&&i.scenario&&this.telemetryHelper.setScenario(i.scenario),this.logger.info(`[${r}][startOutgoingCall]options=${je(this.gatherTelemetryForStartOrJoin(i,r,n))}`),this.isBrokerEnabledForOutgoingCall()&&this.setupBrokerChannel(),this.callUsesMixer=!(!i||!i.callUsesMixer),this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING,this.meetingData=i?.meetingData,this.meetingPreferences=i?.meetingPreferences;const s={newCall:!0,suppressDialout:i&&i.suppressDialout||!1,conversationServiceUrl:this.signalingAgentConfig.conversationServiceUrl,onBehalfOf:i?i.onBehalfOf:null,onBehalfOfUserDisplayName:i?i.onBehalfOfUserDisplayName:null,callQueueContext:i?i.callQueueContext:null,callToVoicemail:!!i&&i.callToVoicemail,voicemailResourcePath:i?i.voicemailResourcePath:null,voicemailItemId:i?i.voicemailItemId:null,endpointState:this.configureEndpointStateForStartOrJoin(i),invitationType:i&&i.invitationType?i.invitationType:null,participantsToNudge:i&&Array.isArray(i.participantsToNudge)?i.participantsToNudge:null,routingFlags:i?i.routingFlags:null,parkContext:i?i.parkContext:null,pickupCode:i?i.pickupCode:null,scenario:i?i.scenario:null,isPreheatOnly:!!i&&i.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:i?i.clientEndpointCapabilities:0,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null,invitationData:i?i.invitationData:null,conversationType:i?this.getConversationType(i.isEmergency,i.castCall,i.isHuddleGroupCall):null,meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,alternateId:i?i.alternateId:null,meetingRegistrationId:i?i.meetingRegistrationId:null,participantPin:i?i.participantPin:null,publishedStates:i?i.publishedStates:null,targetApplicationType:i?i.targetApplicationType:null,captchaContentJson:i?i.captchaContentJson:null,customHeaderContext:i?i.customHeaderContext:null,participationPreferences:i?i.participationPreferences:null,participantPropertyBag:i?i.participantPropertyBag:null};this.isCastCall=i&&i.castCall,this.isHuddleGroupCall=i&&i.isHuddleGroupCall,this.onBehalfOf=s.onBehalfOf,this.onBehalfOfUserDisplayName=s.onBehalfOfUserDisplayName,this.callQueueContext=s.callQueueContext,this.startOrJoinCall(s,Zo.START_CALL.name,r,e,t)},this.joinGivenConversation=(e,t,i,n,r,s={},a=Na())=>{if(Ua(t,"correlationId should be a non null value"),Fa(e||this.getConversationUrl(),"conversationUrl should be a non null value"),Ua(i,"mediaContent should be a non null value"),Ua(i.blob,"outgoingSdp should be a non null value"),this.isPromotingToRealtime=2===this.callMode,xa(this.isCallNotConnected()||this.isPromotingToRealtime,"a call is already in progress"),this.logger.info(`[${a}][joinGivenConversation][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${a}][joinGivenConversation][failed][reason=Session disposed]`);const o=this.gatherTelemetryForStartOrJoin(s,a,r);this.lastUsedJoinCallOptions=s,this.originalRoleBeforePreheat=gd,this.telemetryHelper.startCallInitializationWatch(r),s&&s.scenario&&this.telemetryHelper.setScenario(s.scenario),this.logger.info(`[${a}][joinGivenConversation]options=${je(o)}`),this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING,this.updateCorrelationId(t,a),this.meetingData=s?.meetingData,this.meetingPreferences=s?.meetingPreferences;const l={newCall:!1,suppressDialout:!0,conversationServiceUrl:e,endpointState:this.configureEndpointStateForStartOrJoin(s),scenario:s?s.scenario:null,isPreheatOnly:!!s&&s.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:s?s.clientEndpointCapabilities:0,clientEndpointDebugContent:s?s.clientEndpointDebugContent:null,conversationType:s?this.getConversationType(s.isEmergency,!1):null,meetingPreferences:this.meetingPreferences,meetingData:this.meetingData,meetingRegistrationId:s?.meetingRegistrationId,participantPin:s?.participantPin,sharedLineCallInvitationContent:s?.sharedLineCallInvitationContent,applyServerMute:s?.applyServerMute,publishedStates:s?.publishedStates,invitationData:s?.invitationData,captchaContentJson:s?.captchaContentJson,callQueueContext:s?.callQueueContext,participationPreferences:s?.participationPreferences,participantPropertyBag:s?.participantPropertyBag};this.isCastCall=!1,this.startOrJoinCall(l,Zo.JOIN_CONVERSATION.name,a,i,n)},this.subscribeToCall=(e,t,i=0,n,r=Na())=>{Ua(t,"correlationId should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.IDLE,"a call is already in progress");let s=e;return s||(s=this.signalingAgentConfig.conversationServiceUrl,this.logger.info(`conversationServiceUrl passed is empty. so it is set to ${s}`)),Fa(s,"conversationUrl should be a non null value"),this.logger.info(`[${r}][subscribeToCall][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed?(this.logger.warn(`[${r}][subscribeToCall][failed][reason=Session disposed]`),Promise.reject(wa.CALL_END_CODE.CALL_DOES_NOT_EXIST)):(this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.lastUsedJoinCallOptions=n||{},this.lastUsedJoinCallOptions.clientEndpointCapabilities=i||this.lastUsedJoinCallOptions?.clientEndpointCapabilities,this.meetingData=n?.meetingData,this.meetingPreferences=n?.meetingPreferences,this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY,this.updateCorrelationId(t,r),this.http.sendPostRequest({url:s,requestName:Zo.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,operationType:"CallSetup",payload:Uu(this,null,null,{subscribe:!0,clientEndpointCapabilities:i,...n,applicationType:this.participantManager.localParticipant.applicationType,endpointState:this.configureEndpointStateForStartOrJoin({additionalEndpointProperties:n?.additionalEndpointProperties})},r),causeId:r}).then((e=>{this.disposed||(this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.processConversationServiceResponseHeaders(e,r),this.processConversationServiceResponse(e.response,r,1),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY,r))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return Promise.resolve();const t=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${r}][subscribeToCall] error: ${je(e)} xhrError: ${je(t)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:t.telemetryEndSubCode,endSubCode:t.error.subCode,resultCategories:t.error.resultCategories,resultDetail:t.error.phrase||"SubscribeFailure",causeId:r}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,r,t.error),Promise.reject(t.error))})))},this.getCallReplacementDetailsForCall=(e,t=Na())=>{this.logger.info(`[${t}] getCallReplacementDetailsForCall callId ${e}`);const i=this.signalingAgent.getSignalingSession(e);return i?i.getCallReplacementDetails(t):{replaces:""}},this.getCallReplacementDetails=(e=Na())=>(this.logger.info(`[${e}] getCallReplacementDetails`),{replaces:this.links[wa.LINKS.REPLACE]}),this.transferCallAsync=(e,t,i,n,r=Na())=>{this.logger.info(`[${r}] transferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(e)} transferType ${t} callTransferOptions: ${Ge(n)}`),this.transferHelper(e,t,i,n,r)},this.redirectCall=(e,t=Na(),i)=>{const{id:n,endpointType:r,type:s}=e.redirectOptions;if(this.logger.info(`[${t}] redirectCall: targetId: ${this.piiUtils.scrubMriOrOmit(n)} targetEndpointType ${r}`),!this.isRedirectAllowed){const e={code:wa.CALL_END_CODE.REJECT,phrase:wa.CALL_END_PHRASE.CALL_REDIRECT_IS_NOT_ALLOWED};return Promise.reject(e)}this.telemetryHelper.recordEvent("CallRedirect",{causeId:t});const a=function(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=e.participantManager.localParticipant;return{payload:{invitationRedirection:{target:{type:t,endpointType:n,id:i},sender:{id:r.id,endpointId:r.endpointId,participantId:r.participantId,languageId:r.languageId}}}}}(this,s,n,r);return this.http.sendPostRequest({url:this.links[wa.LINKS.REDIRECT],requestName:Zo.SEND_CALL_REDIRECT_REQUEST.name,payload:a,causeId:t}).then((n=>(this.logger.info(`[${t}][redirectCall] succeeds. Leaving the call...`),this.telemetryHelper.recordEvent("CallRedirectRequestSent",{causeId:t,targetEndpointType:r}),this.terminateEstablishedCall(i,e)))).catch((e=>{const n=Ka(e);this.logger.info(`[${t}][redirectCall] error: ${je(n)}`);const s=n.error;return this.telemetryHelper.recordEvent("CallRedirectRequestFailed",{causeId:t,transactionEnd:s,endpointType:r}),this.disposed||(this.telemetryHelper.setTerminatingData({terminatingEnd:sd,endCode:i.code,endSubCode:i.subCode,clientReasonSubCode:i.clientReasonSubCode,clientReasonPhrase:i.clientReasonPhrase,resultDetail:i.phrase||"RedirectCall",resultCategories:i.resultCategories,causeId:t}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,i),this.dispose(i,t)),Promise.reject(s)}))},this.transferHelper=(e,t,i,n,r=Na())=>{xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet");let s=!1;this.logger.info(`[${r}][transferHelper][replacementDetails=${je(i)}] disableForwardingAndUnanswered=${n&&n.disableForwardingAndUnanswered}`),this.telemetryHelper.recordEvent("TransferCall",{causeId:r}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(r,s)}),wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER],requestName:Zo.SEND_TRANSFER_REQUEST.name,payload:Wu(e,this,i,t,n),causeId:r}).then((()=>{this.telemetryHelper.recordEvent("WaitingForTransferAcceptance",{causeId:r}),s=!0})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${r}][transferCallAsync] error: ${je(t)}`),this.disposed||(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.NETWORK_ERROR,reason:je(e)}},r),this.telemetryHelper.recordEvent(Vo,{causeId:r,...t.error}))})),this.telemetryHelper.recordEvent(Bo,{causeId:r,transferType:t})},this.consultTransferCallAsync=(e,t,i,n,r)=>{let s,a;if(this.logger.info(`[${n}] consultTransferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(t)} transferTargetParticipantLegId: ${i}`),i?(a=this.getMriByParticipantLegOfCall(e,i,n),s=this.getReplacementDetailsByParticipantLegOfCall(e,t,i,n)):(a=t,s=this.getCallReplacementDetailsForCall(e,n)),!a||!s){const r=s?"target mri corresponding not found":`unable to retrieve replacementDetails for transferTargetCallId: ${e}, transferTargetMri: ${t}, transferTargetParticipantLegId: ${i}`;return this.logger.info(`[${n}] consultTransferCallAsync: error: ${r}`),void this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.BAD_REQUEST,reason:r}},n)}this.transferHelper(a,"TransferTypeStandard",s,r,n)},this.isParkByTransfer=(e,t)=>{const i=["serverHold","sharedLinePark","teamPark"].indexOf(e)>-1;return this.logger.info(`[${t}][isParkByTransfer][context=${e}] result = ${i}`),i},this.parkCallAsync=(e,t=Na())=>{if(e&&"none"===e)throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};return xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet"),this.logger.info(`[${t}][parkCallAsync][context=${e}]`),this.telemetryHelper.recordEvent("ParkCall",{causeId:t,parkType:co(e)}),this.isParkByTransfer(e,t)?this.parkByTransfer(e,t):this.park(e,t)},this.unparkAsync=(e,t=Na())=>{if(e&&"none"===e)throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};if(!this.links[wa.LINKS.UNPARK])throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark link not available"};this.logger.info(`[${t}][unparkAsync][context=${e}]`),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION,(()=>{this.handleUnparkError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UNPARK_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UNPARK_COMPLETION_TIMEOUT},"WaitingForUnparkCompletionTimeout",t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.UNPARK_COMPLETION_TIMEOUT);const i={causeId:t};return this.http.sendPostRequest({url:this.links[wa.LINKS.UNPARK],requestName:Zo.SEND_UNPARK_REQUEST.name,payload:Ju(this,i),causeId:t}).then((e=>(this.logger.info(`[${t}][unparkAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForUnparkCompletion",{causeId:t}),Promise.resolve()))).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][unparkAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUnparkError(n.error,"UnparkRequestFailed",t,e),Promise.reject(n.error))}))},this.handleUpdateParticipantsPropertiesCompletion=e=>{const t=e.body,i=Qa(e),n=this.logger.createChild(`[${i}][handleUpdateParticipantsPropertiesCompletion]`,this.correlationId),r={};if(this.disposed)n.info("ignored. Call disposed.");else{if(t.operationId||n.warn("operationId is undefined."),n.info("starts"),t.participantInfos)for(const e of t.participantInfos){if(!e.participant.id){n.warn("participant id is undefined."),this.telemetryHelper.recordEvent(qo,"participant id is undefined in response, property");continue}if(!e.participant.key){n.warn("property name (key) is undefined."),this.telemetryHelper.recordEvent(qo,"property name (key) is undefined in response");continue}const s=Pu(e.participant.id,t.operationId,e.participant.key),a={code:e.transactionEnd.code,subCode:e.transactionEnd.subCode,phrase:e.transactionEnd.phrase,resultCategories:e.transactionEnd.resultCategories};n.info(`Update participants properties completed for: ${this.piiUtils.scrubMriOrOmit(e.participant.id)} with transactionEnd ${je(a)}`),this.telemetryHelper.recordEvent("UpdateParticipantsPropertiesResponseCompleted",{causeId:i,resolveId:this.piiUtils.scrubMriOrOmit(s),property:e.participant.key,result:je(a)}),r[s]=a,this.updateParticipantsPromises[t.operationId].delete(s)}this.checkAndCleanupPromisesForOperationId(t.operationId),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(r,t.operationId,i)}},this.getCallStatus=()=>this.currentCallStatus,this.processIncomingCallRequest=(e,t,i=Na())=>{Ua(e,"request should be a non null value"),Fa(e.body,"request should have a valid body"),Fa(e.body.gp||e.body.cp,"request body should have payload"),xa(this.isCallNotConnected(),"a call is already in progress");const n=this.logger.createChild(`[${i}][processIncomingCallRequest]`);if(this.callUsesMixer=e.fromMixer,n.info("[start]"),this.disposed)return void n.warn("processIncomingCallRequest canceled");this.telemetryHelper.startCallInitializationWatch(),this.isIncomingCall=!0,this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=wa.SIGNALING_FSM_STATE.INCOMING,this.participantManager.initializeForIncomingCall();let r={};try{t&&(r=JSON.parse(t))}catch(e){n.warn("Unable to parse endpoint metadata")}this.endpointMetadata=r;try{let t;if(e?.body?.gp&&!Xe(e.body.gp))n.info("unencoded payload, skipping decoding."),t=e.body.gp;else{const i=e.body.gp?atob(e.body.gp):eo(e.body.cp);t=JSON.parse(i)}if(!t.callNotification)throw n.info("[failed][reason=CallNotification missing]"),new Error("CallNotification is missing");n.info(`incoming call payload: ${Ge(ke(t))}`),this.processIncomingCallPayload(t,i),this.incomingCallPayload=t}catch(e){this.endIncomingCallBecauseOfInvalidPayload(i)}},this.sendAttachToCall=(e=Na())=>(this.logger.info(`[${e}][sendAttachToCall]`),this.incomingCallPayload?(this.onCallStatusChanged(wa.CALL_STATUS.IDLE,e),this.sendAttachToCallInternal(e)):(this.endIncomingCallBecauseOfInvalidPayload(e),Promise.reject(wa.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD))),this.supportsNewOfferRequest=()=>this.signalingAgentConfig.handleNewOfferRequest,this.requestNewOffer=(e,t=Na())=>(this.telemetryHelper.recordEvent("RequestNewOffer",{compatibleContentTypes:e,causeId:t}),this.signalingAgentConfig.handleNewOfferRequest?(Fa(this.links[wa.LINKS.NEW_OFFER],"newOffer link should be a non null value"),this.http.sendPostRequest({url:this.links[wa.LINKS.NEW_OFFER],requestName:Zo.REQUEST_NEW_OFFER.name,payload:Vu(this,e,this.links[wa.LINKS.NEW_OFFER]),causeId:t}).then((e=>this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):Promise.resolve(e))).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[requestNewOffer][${t}] error ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||"RequestNewOfferFailure",causeId:t}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,i.error),this.dispose(i.error,t),Promise.reject(i.error))}))):Promise.reject("Disabled")),this.endAsync=(e,t={})=>{t.causeId=t.causeId||Na();const i=t.causeId;if(this.logger.info(`[${i}][endAsync][rejectionData=${e&&je(e)}][endCallForAll=${t.forEveryone}]`),this.disposed)return this.logger.warn(`[${i}][endAsync] canceled but session already disposed`),Promise.resolve(null);if(this.disposing=!0,this.telemetryHelper.recordEvent("EndCall",e?{code:e.code,subCode:e.subCode,causeId:i,callEndClientSubCode:e.clientReasonSubCode,callEndClientPhrase:e.clientReasonPhrase}:{causeId:i}),t.preventAllCallbacks){const e=Object.keys(this.signalingSessionCallback);for(const t of e)this.signalingSessionCallback[t]=kd.noop}const n=this.mediaRenegotiationManager?.isIncomingRenegotiationInProgress()||this.mediaRenegotiationManager?.isOutgoingRenegotiationInProgress();if(this.telemetryHelper.stopCallCancelationDurationWatch(),this.fsmState===wa.SIGNALING_FSM_STATE.INCOMING)return e.code===wa.CALL_END_CODE.CALL_REDIRECTED?this.redirectCall(t,i,e):this.rejectIncomingCall(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY)return this.cancelOutgoingCall(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK)return this.rejectIncomingCall(e,i);if((this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||n)&&t.forEveryone)return this.deleteConversation(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||n)return this.terminateEstablishedCall(e,t);{this.logger.info(`[${i}][endAsync] there is no call to cancel or end or reject in current state`);const t={code:isNaN(e?.code)?wa.CALL_END_CODE.NOT_FOUND:e.code,subCode:isNaN(e?.subCode)?wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED:e.subCode,phrase:e?.phrase||wa.CALL_END_PHRASE.CALL_DOES_NOT_EXIST,resultCategories:e?.resultCategories||[Zs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};return this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultDetail:t.phrase||"CallDoesNotExist",endCode:t.code,endSubCode:t.subCode,resultCategories:t.resultCategories,causeId:i,clientReasonSubCode:t.clientReasonSubCode,clientReasonPhrase:t.clientReasonPhrase}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,t),this.dispose(t,i),Promise.resolve(null)}},this.handleIncomingMsgAsync=(e,t=wa.INCOMING_MESSAGE_ORIGIN.TROUTER)=>{Ua(e,"incoming message should be a non null value");const i=Ya(e),n=to(),r=e.body,s=e.url,a={...e,origin:t},o=Qa(a);if(this.logger.info(`[${o}][handleIncomingMsgAsync][url=${s}][messageId=${i}]`),!r)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(xo,{origin:t,messageId:i,causeId:o}),n.reject(new Error("received message with no body")),n.promise;if(this.disposed)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=call is disposed]`),n.reject(this.getCallNotFoundTransactionEnd()),n.promise;if(this.isDuplicatedIncomingMessage(a))return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=duplicate]`),this.telemetryHelper.recordEvent(No,{origin:t,messageId:i,causeId:o}),n.resolve(new Error("Message was already handled")),n.promise;this.checkCorrelationIdChange(e,o);const l={[sa]:e=>{this.handleCallNotification(e)},[aa]:e=>{this.handleMediaAnswer(e)},[oa]:e=>{this.handleMediaAcknowledgement(e)},[la]:e=>{this.handleCallAcceptance(e)},[ca]:e=>{this.handleCallEnd(e,!1)},[da]:e=>{this.handleCallProgress(e)},[ua]:e=>{this.handleCallAcceptanceAck(e)},[ha]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationOffer(e)},[ga]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationFailure(e)},[pa]:e=>{this.handlePSTNBalanceUpdate(e)},[ma]:e=>{this.mediaRenegotiationManager?.handleRetargetCompleted(e)},[fa]:e=>{this.handleTransferRequested(e)},[va]:e=>{this.handleTransferCompletion(e)},[Sa]:e=>{this.handleTransferAcceptance(e)},[ya]:e=>{this.handleParkCompletion(e)},[Ca]:e=>{this.handleUnparkCompletion(e)},[Ta]:e=>{this.handleUpdateMeetingLiveStateCompletion(e)},[Ea]:e=>{this.handleUpdateMeetingGroupsCompletion(e)},[ba]:e=>{this.handleSetMeetingLayoutCompletion(e)},[_a]:e=>{this.handleUpdateMeetingStatesCompletion(e)},[Ia]:e=>{this.handleUpdateMonitorSessionCompletion(e)}},c={[ra.CONTROL_VIDEO_STREAMING]:e=>{this.webRtcSignalingManager.handleControlVideoStreaming(e)},[ra.DOMINANT_SPEAKER_INFO]:e=>{this.webRtcSignalingManager.handleDominantSpeakerInfo(e)},[ra.CSRC_INFO]:e=>{this.webRtcSignalingManager.handleCsrcInfo(e)},[ra.CONV_ROSTER_UPDATE]:e=>{this.handleRosterUpdate(e,!1)},[ra.NEW_MEDIA_OFFER]:e=>{this.handleNewMediaOffer(e)},[ra.CONV_ADD_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAddParticipantSuccess(e)},[ra.CONV_ADD_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAddParticipantFailure(e)},[ra.CONV_ADMIT_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAdmitParticipantSuccess(e)},[ra.CONV_ADMIT_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAdmitParticipantFailure(e)},[ra.CONV_ADMIT_ALL_STATUS]:e=>{this.handleAdmitAllStatus(e)},[ra.CONV_REMOVE_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleRemoveParticipantSuccess(e)},[ra.CONV_REMOVE_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleRemoveParticipantFailure(e)},[ra.CONV_CONFIRM_UNMUTE]:e=>{this.participantManager.handleUnmuteConfirmRequest(e)},[ra.CONV_UPDATE]:e=>{this.handleConversationUpdate(e)},[ra.CONV_LOCAL_PARTICIPANT_UPDATE]:e=>{this.handleLocalParticipantUpdate(e)},[ra.CONV_ADD_MODALITY_SUCCESS]:e=>{this.handleAddModalitySuccess(e)},[ra.CONV_ADD_MODALITY_FAILURE]:e=>{this.handleAddModalityFailure(e)},[ra.CONV_BROADCAST_UPDATE]:e=>{this.broadcastSession.handleBroadcastStateChanged(e)},[ra.CONV_CONTENT_SHARING_UPDATE]:e=>{this.contentSharingManager?.handleContentSharingUpdate(e)},[ra.CONV_CONTENT_SHARING_END]:e=>{this.contentSharingManager?.handleContentSharingEnd(e)},[ra.CONV_END]:e=>{this.handleCallEnd(e,!1)},[ra.CONV_END_JOIN]:e=>{this.handleCallEnd(e,!1)},[ra.CONV_END_SUBSCRIBE]:e=>{this.handleCallEnd(e,!0)},[ra.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS]:e=>{this.participantManager.handleUpdateParticipantInterpretationStateCompletion(e)},[ra.UPDATE_PARTICIPANT_PROPERTIES_STATUS]:e=>{this.handleUpdateParticipantsPropertiesCompletion(e)},[ra.JOIN_MEETING_GROUP_STATUS]:e=>{this.handleJoinMeetingGroupCompletion(e)},[ra.LEAVE_MEETING_GROUP_STATUS]:e=>{this.handleLeaveMeetingGroupCompletion(e)},[ra.RECEIVE_MESSAGE]:e=>{this.handleReceiveMessage(e)},[ra.SEND_MESSAGE_STATUS]:e=>{this.proxiedMessageNotificationManager.handleProxiedMessageNotification(e)},[ra.DISABLE_PREHEAT_ASYNC_STATUS]:e=>{this.handleDisablePreheatCompletion(e)},[ra.MUTE_UNMUTE_ASYNC]:e=>{this.participantManager.handleMuteUnmuteAsyncResponse(e)},[ra.SET_MEETING_LAYOUT_STATUS]:e=>{this.handleSetMeetingLayoutCompletion(e)}};try{const e=Object.keys(l).filter((e=>r.hasOwnProperty(e)))[0],t=this.signalingAgentConfig.enableSplitConversationEndUrl&&(ja(a.url,ra.CONV_END_JOIN)||ja(a.url,ra.CONV_END_SUBSCRIBE))?Object.keys(c).filter((e=>a.url&&ja(a.url,e)))[1]:Object.keys(c).filter((e=>a.url&&ja(a.url,e)))[0];e?l[e](a):t?c[t](a):(this.telemetryHelper.recordEvent("UnkownMessageType",{messageId:i}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received unknown message]`)),n.resolve(!0)}catch(e){this.telemetryHelper.recordEvent(Lo,{messageId:i,error:je(e)}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=${e.message}]`),n.reject(new Error(e.message))}return n.promise},this.canHandleIncomingMsgSync=e=>{if(this.signalingAgentConfig.supportsSynchronousTrouterResponse){const t=e.body;return Boolean(t.callAcceptance)}return!1},this.handleIncomingMsgSync=e=>{const t=Ya(e),i=e.body,n=e.url,r=wa.INCOMING_MESSAGE_ORIGIN.TROUTER,s={...e,origin:r},a=Qa(s);this.logger.info(`[${a}][handleIncomingMsgSync][url=${n}][messageId=${t}]`);const o=s.headers;let l=wa.HTTP_STATUS_CODES.OK,c="";const d=new Pa;if(Ja(o,this.incomingTrouterMessagesSeenSoFar)){this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=duplicate]`);const e=function(e,t){return e&&t[e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(wa.HEADERS.MESSAGE_ID)||null]||null}(o,this.incomingMessageSyncResponseCache);if(e)return this.logger.info(`[${a}][handleIncomingMsgSync][cachedResponse]`),e;this.telemetryHelper.recordEvent(No,{origin:r,messageId:t,causeId:a}),this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=cachedResponseNotFound]`),l=wa.HTTP_STATUS_CODES.BAD_REQUEST}else if(i){if(i.callAcceptance)try{c=Ge(this.handleCallAcceptanceSync(s))}catch(e){this.telemetryHelper.recordEvent(Lo,{messageId:t,origin:r,causeId:a,error:je(e)}),this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=${e?.message}]`),l=wa.HTTP_STATUS_CODES.BAD_REQUEST}}else this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(xo,{origin:r,messageId:t,causeId:a}),l=wa.HTTP_STATUS_CODES.BAD_REQUEST;o&&(o.get(wa.HEADERS.CORRELATION_ID)&&d.set(wa.HEADERS.CORRELATION_ID,o.get(wa.HEADERS.CORRELATION_ID)),o.get(wa.HEADERS.MESSAGE_ID)&&d.set(wa.HEADERS.MESSAGE_ID,o.get(wa.HEADERS.MESSAGE_ID)));const u={resultCode:l,responseBody:c,responseHeaders:d.getAll()};return function(e,t,i){if(e&&t){const n=e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(wa.HEADERS.MESSAGE_ID)||null;n&&(t[n]=i)}}(o,this.incomingMessageSyncResponseCache,u),this.logger.info(`[${a}][handleIncomingMsgSync][success][resultCode=${l}]`),u},this.acceptRenegotiationAsync=(e,t,i=Na())=>(Ua(e.blob,"finalSdp should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.mediaRenegotiationManager.acceptRenegotiationAsync(e,t,i)),this.setProvisionalAnswerAsync=(e,t=Na())=>{Ua(e.blob,"sdp should be a non null value"),this.telemetryHelper.recordEvent("SetProvisionalAnswer",{causeId:t});const i=to();return this.fsmState!==wa.SIGNALING_FSM_STATE.INCOMING?(this.logger.info(`[setProvisionalAnswerAsync][${t}] there is no incoming call to set provisional answer on.`),i.reject(new Error("there is no incoming call to set provisional answer on.")),i.promise):(this.http.sendPostRequest({url:this.links[wa.LINKS.MEDIA_ANSWER],requestName:Zo.SEND_MEDIA_ANSWER.name,payload:Xu(this,e),causeId:t}).then((e=>{this.disposed||this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,t),i.resolve(null),this.disposed||(this.telemetryHelper.recordEvent(fo,{causeId:t}),this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,t),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!1,t))})).catch((e=>{const n=Ka(e,this.signalingAgentConfig);this.logger.info(`[setProvisionalAnswerAsync][${t}] error: ${je(n)}`),this.disposed?i.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent("SetProvisionalAnswerFailed",{causeId:t}),i.reject(n.error))})),i.promise)},this.startRenegotiationAsync=(e,t,i=Na())=>(Ua(e,"mediaContent should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][startRenegotiationAsync]`),this.mediaRenegotiationManager.startRenegotiationAsync(e,this.links[wa.LINKS.MEDIA_RENEGOTIATION],t,i)),this.updateMediaDescriptionsAsync=(e=Na(),t)=>{Ua(t,"mediaDescriptions should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"updateMediaDescriptions operations are only allowed when the call is connected");const i=this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS];return Ua(i,"updateMediaDescriptionsUrl should be a non null value"),this.telemetryHelper.recordEvent("UpdateMediaDescriptions",{causeId:e}),this.http.sendPostRequest({url:i,requestName:Zo.UPDATE_MEDIA_DESCRIPTIONS.name,payload:eh(this,t),causeId:e}).catch((t=>{const i=Ka(t,this.signalingAgentConfig);return this.logger.info(`[updateMediaDescriptionsAsync][${e}] error: ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent("UpdateMediaDescriptionsFailed",{causeId:e}),Promise.reject(i.error))}))},this.acceptAsync=(e,t,i,n=Na())=>{Ua(e,"mediaContent should be a non null value"),Ua(e.blob,"outgoingSdp should be a non null value"),this.logger.info(`[${n}][acceptAsync][mediaTypes=${t}]`),this.telemetryHelper.recordEvent("AcceptCall",{causeId:n}),this.telemetryHelper.setAnsweredModalities(e.blob);const r=to();return this.fsmState!==wa.SIGNALING_FSM_STATE.INCOMING?(this.logger.warn("acceptAsync, there is no incoming call to accept"),r.reject(new Error("there is no incoming call to accept")),r.promise):(this.fsmState=wa.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK,this.http.sendPostRequest({url:this.links[wa.LINKS.ACCEPT],requestName:Zo.SEND_ACCEPTANCE.name,payload:Ou(this,e,t,i),causeId:n}).then((e=>{this.disposed||(this.currentCallStatus===wa.CALL_STATUS.IDLE&&(this.telemetryHelper.setTimeToRingDuration(),this.telemetryHelper.recordEvent("AcceptedBeforeRinging",{causeId:n}),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,n)),e.response.callAcceptanceAcknowledgement&&(this.logger.info("acceptAsync, handling inlined callAcceptanceAcknowledgement"),this.internalHandleCallAcceptanceAck(e.response,n))),r.resolve(null)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[acceptAsync][${n}] error: ${je(t)}`),this.disposed?r.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.INCOMING,this.telemetryHelper.recordEvent("AcceptCallFailed",{causeId:n,xhrError:t}),r.reject(t.error))})),r.promise)},this.rejectRenegotiationAsync=(e,t=Na())=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${t}][rejectRenegotiationAsync][rejectionData=${e}]`),this.mediaRenegotiationManager.rejectRenegotiationAsync(e,t)),this.saveMediaControllerLinksIfAny=e=>{e.links&&(this.links[wa.LINKS.CONTROL_VIDEO_STREAMING]=e.links.controlVideoStreaming||this.links[wa.LINKS.CONTROL_VIDEO_STREAMING],this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS]=e.links.applyChannelParameters||this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS])},this.getInitialMediaOfferFromIncomingCallPayload=(e=Na())=>{if(!this.signalingAgentConfig.handleMediaOfferFromPushNotification)return null;const t=this.incomingCallPayload?.callNotification?.mediaContent?this.incomingCallPayload.callNotification.mediaContent:null;return this.telemetryHelper.setIsSdpInCallNotification(!!t),t},this.updateCorrelationId=(e,t=Na())=>{if(this.logger.info(`[${t}][updateCorrelationId][old=${this.correlationId}][new=${e}]`),this.correlationId!==e&&!this.disposed){const i=this.correlationId;this.correlationId=e,this.telemetryHelper&&this.telemetryHelper.recordEvent&&this.telemetryHelper.recordEvent("CorrelationIdUpdated",{newId:this.correlationId,oldId:i,causeId:t}),this.signalingSessionCallback&&this.signalingSessionCallback.onCorrelationIdUpdated&&this.signalingSessionCallback.onCorrelationIdUpdated(this.correlationId,t)}},this.endIncomingCallBecauseOfInvalidPayload=e=>{this.logger.info(`[${e}][endIncomingCallBecauseOfInvalidPayload]`),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const t={code:wa.CALL_END_CODE.BAD_REQUEST,subCode:wa.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD,phrase:wa.CALL_END_PHRASE.BAD_NOTIFICATION_PAYLOAD,resultCategories:["UnexpectedServerError"]};this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:t.code,endSubCode:t.subCode,resultDetail:t.phrase||"EndIncomingCall",resultCategories:t.resultCategories,causeId:e}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,t),this.dispose(t,e)},this.isDuplicatedIncomingMessage=e=>e.origin===wa.INCOMING_MESSAGE_ORIGIN.BROKER&&Ja(e.headers,this.incomingBrokerMessagesSeenSoFar)||e.origin===wa.INCOMING_MESSAGE_ORIGIN.TROUTER&&Ja(e.headers,this.incomingTrouterMessagesSeenSoFar),this.getEndpointState=()=>{let e;return e=this.startOrJoinConvResponseReceived?{...this.latestEndpointState}:{...this.requestedEndpointStateWhileConnecting},e},this.setMultiParty=(e,t)=>{const i=!!e;this.multiParty!==i&&(this.telemetryHelper.recordEvent("SetMultiparty",{isMultiparty:i,causeId:t}),this.multiParty=i)},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 e=e=>{e&&"string"==typeof e&&e.trim()&&(this.baseMessagingChannelUrl=this.previousTrouterUrl=this.currentTrouterUrl=e.trim(),this.telemetryHelper.addTrouterChannel())};this.brokerExclusiveEnabled()||(this.signalingAgentConfig.trouterServiceProvider?(2===this.signalingAgentConfig.trouterServiceProvider.state()&&this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync().then(e),this.signalingAgentConfig.trouterServiceProvider.onStateChanged(this.onTrouterStateChanged)):(e(this.signalingAgentConfig.trouterUrlGetter.trouterUrl()),this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed(this.onTrouterUrlChanged)))},this.isTrouterDisconnected=()=>{try{return 3===this.signalingAgentConfig.trouterServiceProvider.state()}catch(e){return!1}},this.forceTrouterConnectionCheck=()=>{try{return void this.signalingAgentConfig.trouterServiceProvider.checkConnection(!1)}catch(e){return}},this.navigatorOnlineCallback=()=>{this.disposed||(this.reportConnectivityStatus(),this.isTrouterDisconnected()&&this.signalingAgentConfig.forceTrouterReconnectOnNetworkOnline&&this.forceTrouterConnectionCheck())},this.navigatorOfflineCallback=()=>{this.reportConnectivityStatus()},this.reportConnectivityStatus=()=>{if(!this.disposed){const e=io(this.signalingAgentConfig.trouterServiceProvider);this.logger.info(`[Connectivity] status=${e}`),this.telemetryHelper.recordEvent("ConnectivityChanged",{status:e})}},this.onTrouterStateChanged=(e,t)=>{const i=Na();this.logger.info(`[${i}][onTrouterStateChanged][state=${e}]`),this.disposed?this.logger.info("onTrouterStateChanged ignored"):(this.reportConnectivityStatus(),2===e&&(this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter("TrouterStateChanged",i)))},this.setupConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.addEventListener&&(window.addEventListener("online",this.navigatorOnlineCallback),window.addEventListener("offline",this.navigatorOfflineCallback))}catch(e){return}},this.tearDownConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.removeEventListener&&(window.removeEventListener("online",this.navigatorOnlineCallback),window.removeEventListener("offline",this.navigatorOfflineCallback))}catch(e){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 Gd(this),this.brokerService.onBrokerMessage((e=>{this.logger.info("setupBrokerChannel, message from broker",function(e){try{const t=ke(e,["id","groupCallInitiator"]);return Ze(t,"body.participants"),Ge(t)}catch(e){return"failed to return safe response"}}(e)),this.handleIncomingMsgAsync(e,wa.INCOMING_MESSAGE_ORIGIN.BROKER).catch((e=>{this.telemetryHelper.recordEvent("FailedToHandleBrokerMessage"),this.logger.info("setupBrokerChannel, Failed to handle message from broker",e)}))})),this.baseMessagingChannelUrl||(this.telemetryHelper.addBrokerChannel(),this.baseMessagingChannelUrl=this.brokerService.baseUrl))},this.onTrouterUrlChanged=()=>{const e=Na();this.logger.info(`[${e}][onTrouterUrlChanged]`),this.disposed?this.logger.info("onTrouterUrlChanged ignored"):this.getTrouterUrlAsync().then((t=>{this.telemetryHelper.recordEvent(Ao,{url:t}),this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(Ao,e)})).catch((e=>{this.logger.info(`Failed to update links to trouter: ${e}`)}))},this.updateLinksToTrouter=(e,t)=>{this.logger.info(`[${t}][updateLinksToTrouter][tag=${e}]`),this.ensureLatestTrouterUrl(e).then((()=>{this.previousTrouterUrl!==this.currentTrouterUrl?(this.previousTrouterUrl=this.currentTrouterUrl,this.updateConversationLinks(),this.updateKeepAliveUrl(),this.contentSharingManager?.updateContentSharingNotificationLinksAsync(t),this.broadcastSession&&this.broadcastSession.updateBroadcastCallbackUrl(t)):this.logger.info(`[${t}][updateLinksToTrouter]skip updating links, url did not change`)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Po,{causeId:t}),this.logger.info(`[${t}][updateLinksToTrouter][failed][reason=${je(e)}]`)}))},this.updateLinks=(e,t)=>{this.ensureLatestTrouterUrl(Ao).then((()=>{e(t)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Po,{causeId:t}),this.logger.warn("Failed to update links")}))},this.startCallPreheatTimer=e=>{this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT,(()=>{this.handleCallEstablishmentTimeout(e,wa.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,"Preheat timed out!"),this.terminateEstablishedCall({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,phrase:"Preheat timed out!"},{forEveryone:!1,causeId:e})}),wa.TIMEOUT_VALUES_IN_SECONDS.MAX_PREAHEATED_TIMEOUT)},this.stopCallPreheatTimer=()=>{this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT)},this.updateKeepAliveUrl=()=>{this.logger.info("updateKeepAliveUrl"),this.links.hasOwnProperty(wa.LINKS.KEEPALIVE)?(this.linkUpdateRequested.keepAliveLinks=!1,this.logger.info("updateKeepAliveUrl, sending request"),this.sendToKeepAliveUrl(function(e){return Ua(e,"signalingSession cannot be null"),{payload:{callParticipantUpdate:{links:$a(e,ia),clientContentForMediaController:e.webRtcSignalingManager.getClientUrls()}}}}(this))):this.linkUpdateRequested.keepAliveLinks=!0},this.updateConversationLinks=(e=Na())=>{this.logger.info(`[${e}][updateConversationLinks]`),this.telemetryHelper.recordEvent("UpdateConversationLinks",{causeId:e}),this.links.hasOwnProperty(wa.LINKS.NOTIFICATION_LINKS)?(this.linkUpdateRequested.conversationLinks=!1,this.logger.info("updateConversationLinks, sending request"),this.sendToUpdateConversationLinks(!0)):this.linkUpdateRequested.conversationLinks=!0},this.sendAttachToCallInternal=(e=Na())=>{this.telemetryHelper.recordEvent("SendAttach",{causeId:e}),this.logger.info(`[${e}][sendAttachToCallInternal]`);const t=new Pa;return this.signalingAgentConfig.sendProgressFromCC&&t.set(wa.HEADERS.CACHE_SKYPE_TOKEN,"1"),this.http.sendPostRequest({url:this.incomingCallPayload.callNotification.links.attach,customHeaders:t,requestName:Zo.SEND_CALL_ATTACH.name,payload:Du(this,this.incomingCallPayload.conversationInvitation.conversationController,!this.getInitialMediaOfferFromIncomingCallPayload()),causeId:e}).then((t=>{if(!this.disposed){this.processAttachResponse(this.incomingCallPayload,t,e);const i=t.response.additionalActionResponses;i&&i.length>0&&this.processConversationServiceResponse(i[0].output,e,0),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,e),this.telemetryHelper.setTimeToRingDuration(),this.handleBrokerSubscription(t.response.callInvitation,e)}})).catch((t=>{const i=Ka(t,this.signalingAgentConfig);if(this.logger.info(`[${e}][sendAttachToCallInternal] error: ${je(t)} xhrError: ${je(i)}`),!this.disposed)throw this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||"SendAttachtoCallFailure",causeId:e}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,i.error),this.dispose(i.error,e),{code:i.telemetryEndSubCode,subCode:i.error.subCode,resultCategories:i.error.resultCategories}}))},this._processCallAcceptance=(e,t)=>{if(this.logger.info(`[${t}][_processCallAcceptance]`),this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING){this.processCallAcceptance(e.body,t),this.telemetryHelper.setTimeToRingDuration();try{this.multiParty||this.callUsesMixer||this.participantManager.handleRosterUpdate(this.getFakeRoster(e.body),!0,t)}catch(i){const n={code:wa.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:wa.CALL_END_SUB_CODE.CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE,phrase:i?.toString()};throw this.logger.info(`[${t}][_processCallAcceptance] ${Ge(n)}`),this.telemetryHelper.recordRosterEvent(e,_o,t),n}}},this.restartKeepAliveInterval=(e,t=!1,i)=>{this.disposed||(window.clearInterval(this.keepAliveTimer),t&&(this.telemetryHelper.recordEvent("SendKeepAliveFailed",i),i?.code===wa.RESOURCE_NOT_FOUND_ERROR.code)?this.logger.info(`[${e}][restartKeepAliveInterval] keepAlive stopped since last request returned NOT_FOUND.`):this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval))},this.isCallOngoing=()=>this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.IDLE,this.isCallNotConnected=()=>{const e=this.signalingAgentConfig.enableSplitConversationEndUrl&&this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING;return this.fsmState===wa.SIGNALING_FSM_STATE.IDLE||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||e},this.isCallConnectedOrConnectedForRoster=()=>this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,s&&(this.callStartTime=s),this.signalingSessionCallback=t,this.signalingAgentConfig=i,this.signalingAgent=r,this.urlIdentifier=n,this.piiUtils=new Dd(i.piiScrubber),this.isHostLessCall=i.doHostlessCalling||!1,this.logger=i.logger.createChild((()=>`CSA[${this.correlationId}][${this.fsmState}]`),this.correlationId,!0),this.updateCorrelationId(n),this.logger.info(`[endpointId=${qe(this.signalingAgent.endpointId,8)}]`),this.logger.info(`[participantId=${e.participantId}]`),this.callOperationHandler=new zd(this.logger.createChild((()=>`[CallOperationHandler][${e.participantId}]`))),this.http=new uu(this,this.callStartTime),this.telemetryHelper=new sh(this,e,this.callStartTime),this.mediaRenegotiationManager=new mu(this,t,this.telemetryHelper),this.participantManager=new Iu(this,t,e,new ct(this.logger)),this.proxiedMessageNotificationManager=new Ru(this),this.timeoutManager=new Rd(this.logger),this.contentSharingManager=new nu(this,t),this.webRtcSignalingManager=new ah(this,t),this.pstnContent={emergencyCallCountry:i.emergencyCallCountry||"",platformName:i.clientInformation,publicApiCall:!1},this.setupTrouterChannel(),this.setupConnectionCheck()}onPromotionCompleted(e,t,i){this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} error=${je(t)}]`),this.isPromotingToRealtime=!1,this.signalingSessionCallback.onPromotionCompleted(e,t,i)}setRealTimeState(e,t){let i=e;(2===e&&1===this.realTimeState||1===e&&2===this.realTimeState)&&(i=3),i!==this.realTimeState&&(this.logger.info(`[${t}][setRealTimeState] changed: input=${e} old=${this.realTimeState}, new=${i}`),this.realTimeState=i,3===i?this.setCallMode(1,t):0!==this.callMode||2!==i&&(this.signalingAgentConfig.disableRealTimeModeFromRoster||1!==i)||this.setCallMode(1,t))}setCallMode(e,t){this.callMode!==e&&(this.logger.info(`[${t}][setCallMode] oldMode=${this.callMode}, newMode=${e}`),this.callMode=e,this.signalingSessionCallback.onCallModeChanged(this.callMode,t))}configureStreamingMode(e){2!==this.callMode?(this.logger.info(`[${e}][configureStreamingMode]`),this.setCallMode(2,e),this.cleanUpDueToStreaming(e),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,e)):this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT)}updateDominantSpeakerHistoryMessageSubscription(e){this.webRtcSignalingManager.getIsDominantSpeakerInfoLinkEnabled()!==e&&(this.logger.info(`Signaling dominant speaker history subscription updated: ${e}`),this.webRtcSignalingManager.setIsDominantSpeakerInfoLinkEnabled(e),this.webRtcSignalingManager.areClientURLsGenerated()&&this.updateKeepAliveUrl())}cleanUpDueToStreaming(e){this.setRealTimeState(0,e),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.isPromotingToRealtime=!1,this.provisionalMediaAnswersSeenSoFar=[],this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=new mu(this,this.signalingSessionCallback,this.telemetryHelper),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const t={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.DOWNGRADE_TO_STREAMING_CLIENT,phrase:wa.CALL_END_PHRASE.DOWNGRADE_TO_STREAMING_CLIENT},i=Zo;for(const n of Object.keys(i))0!==i[n].controller&&4!==i[n].controller&&3!==i[n].controller||this.http.cancelRequestIfPending(i[n].name,e,void 0,t)}updateEndpointMetadata(e,t=Na()){let i={};try{i=JSON.parse(e)}catch(e){return Promise.reject("Invalid metadata")}return this.http.sendPutRequest({url:this.links[wa.LINKS.UPDATE_ENDPOINT_METADATA],requestName:Zo.UPDATE_ENDPOINT_METADATA.name,payload:Yu(this,i),causeId:t}).then((()=>{this.telemetryHelper.recordEvent("UpdateEndpointMetadataSuccess",{causeId:t})})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointMetadata] error: ${je(i)}`),this.telemetryHelper.recordEvent("UpdateEndpointMetadataFailure",{...i.error}),Promise.reject(i.error)}))}isOneToOnePSTNCall(){return this.signalingSessionCallback.isOneToOnePstnCall()}getLocationContent(){return this.isOneToOnePSTNCall()?Wa(this.locationInfoContent):null}getNetworkContent(){return this.isOneToOnePSTNCall()?Wa(this.networkInfoContent):null}getAreaContent(){return this.isOneToOnePSTNCall()?Wa(this.areaContent):null}setLocationInfo(e,t,i){this.locationInfoContent=e,this.networkInfoContent=t,this.areaContent=i}setStreamInformationReceived(){this.disposed||this.streamInformationReceived||(this.streamInformationReceived=!0,this.telemetryHelper.recordEvent("StreamInformationReceived"))}getEndpointCapabilities(){let e=0;return this.signalingAgentConfig.brokerEnabledIncoming&&(e|=16),this.signalingAgentConfig.isGVCJoiningEnabled&&(e|=1),"disabled"!==this.signalingAgentConfig.cloudScreenSharingFlag&&(e|=2),this.signalingAgentConfig.supportsHostlessGroupCalls&&(e|=4),this.signalingAgentConfig.autoJoinOnConflict&&(e|=32),this.signalingAgentConfig.supportsCompressedServicePayload&&(e|=128),this.signalingAgentConfig.enableAutoPromotion&&(e|=65536),this.signalingAgentConfig.enableBatchedSendMessageStatus&&(e|=16384),this.signalingAgentConfig.enableBatchedReceiveMessage&&(e|=8192),e|=64,e|=1024,this.signalingAgent?.accountConfig?.clientSupportsAudioOnlyWatermark&&(e|=4096,this.telemetryHelper.setAudioOnlyWatermark(!0)),this.signalingAgent?.accountConfig?.clientSupportsWatermark&&(e|=2048,this.telemetryHelper.setWatermarkSupport(!0)),this.signalingAgent?.accountConfig?.clientSupportsPreventScreenCapture&&(e|=131072,this.telemetryHelper.setClientSupportsPreventScreenCapture(!0)),(this.getMaxReinvitelessMediaForVBSSForWeb()||this.getMaxReinvitelessMediaForVideoForWeb())&&(this.telemetryHelper.setReinviteless(this.callUsesMixer),e|=512),e}handleAdmitAllStatus(e){const t=e.body?.transactionResponse,i=Qa(e);this.logger.info(`[${i}][handleAdmitAllStatus][${je(t)}]`);const n=t?.operationId;if(n&&this.callOperationHandler.hasPendingOperation(0,n,i)){this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,n);const e=t?.result?.code,r=t?.result?.subCode,s=t?.result?.resultCategories,a=t?.additionalDetail;if(0===e||e>=200&&e<300){const t={code:e,subCode:r,resultCategories:s,result:Ge(a)};this.telemetryHelper.recordEvent("AdmitSuccess",{causeId:n,transactionEnd:t}),this.callOperationHandler.resolvePendingOperation(0,n,t,i)}else{const a={code:e||wa.CALL_END_CODE.BAD_REQUEST,subCode:r||0,resultCategories:s,result:t,phrase:wa.CALL_END_PHRASE.BAD_SERVICE_RESPONSE};this.telemetryHelper.recordEvent(To,{causeId:n,transactionEnd:a}),this.callOperationHandler.rejectPendingOperation(0,n,"AdmitAllStatus response contains failure",a,i)}}else this.logger.warn(`[${i}][handleAdmitAllStatus] invalid admitAllStatus response or no pending operation. operationId=${n}`)}sendNetworkRequestForAdmit(e){this.http.sendPostRequest({url:this.links[wa.LINKS.ADMIT_ALL],requestName:Zo.ADMIT.name,payload:Mu(this,e),causeId:e,onceTrouterReady:()=>{this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADMIT,(()=>{this.telemetryHelper.recordEvent("AdmitTimeout",{causeId:e}),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,"timed out waiting for admit operation",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.ADMIT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ADMIT_TIMEOUT},e)}),wa.TIMEOUT_VALUES_IN_SECONDS.ADMIT_TIMEOUT,e)}}).catch((t=>{const i=Ka(t,this.signalingAgentConfig);this.telemetryHelper.recordEvent(To,{causeId:e,...i.error}),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,t,i.error,e)}))}getConversationType(e,t,i){return e?"emergencyGroupCall":t?"cast":i?"huddleGroupCall":null}getMaxReinvitelessMediaForVideoForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVideoForWeb}getMaxReinvitelessMediaForVBSSForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVBSSForWeb}convertParkType(e){return"teamPark"===e?"TransferTypeTeamPark":"sharedLinePark"===e?"TransferTypeSharedLinePark":"serverHold"===e?"TransferTypeServerHold":(this.logger.info(`convertParkType, parkType: ${e} is unknown`),"none")}parkByTransfer(e,t){this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(t)}),wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT);const i=this.getNetworkRequestName(e);return this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER],requestName:i,payload:Hu(e,this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][parkByTransfer] error: ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.NETWORK_ERROR,reason:je(e)}},t),this.telemetryHelper.recordEvent(Vo,{causeId:t,...i.error}),Promise.reject(i.error))})),this.telemetryHelper.recordEvent(Bo,{causeId:t,transferType:this.convertParkType(e)}),Promise.resolve()}park(e,t){this.logger.info(`[${t}][park] context ${e}`),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.PARK_COMPLETION,(()=>{this.handleParkError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.PARK_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARK_COMPLETION_TIMEOUT},"WaitingForParkCompletionTimeout",t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.PARK_COMPLETION_TIMEOUT);const i=this.getHoldTypeInRequest(e),n={causeId:t};return this.http.sendPostRequest({url:this.links[wa.LINKS.PARK],requestName:Zo.PARK_REQUEST.name,payload:$u(this,i,n),causeId:t}).then((e=>{this.logger.info(`[${t}][park] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForParkCompletion",{causeId:t}),Ua(e.response.holdResponse.links,"server response does not include park links"),this.links[wa.LINKS.UNPARK]=e.response.holdResponse.links.resume})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][park] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleParkError(n.error,"ParkRequestFailed",t,e),Promise.reject(n.error))})),Promise.resolve()}getHoldTypeInRequest(e){switch(e){case"serverHoldV2":return"musicOnHold";case"sharedLineParkV2":return"sharedLineAppearance";case"callPark":return"callPark";default:return null}}handleParkError(e,t,i,n){this.disposed?this.logger.info("handleParkError ignored"):(this.logger.info(`[${i}] handleParkError reject reason: ${je(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.PARK_COMPLETION),this.signalingSessionCallback.onParkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onParkCompleted(e,i)),this.links[wa.LINKS.UNPARK]=void 0)}handleParkCompletion(e){const t=e.body,i=Qa(e),n=t.holdCompletion;this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleParkCompletion",wa.TIMEOUT_OPERATIONS.PARK_COMPLETION,"ParkCompleted","ParkFailed",this.signalingSessionCallback.onParkCompleted,this.handleParkError.bind(this))}handleUnparkError(e,t,i,n){this.disposed?this.logger.info("handleUnparkError ignored"):(this.logger.info(`[${i}] handleUnparkError reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.signalingSessionCallback.onUnparkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(e,i)),this.links[wa.LINKS.UNPARK]=void 0)}handleUnparkCompletion(e){const t=e.body,i=Qa(e);if(this.disposed)return void this.logger.info(`[${i}]handleUnparkCompletion ignored`);this.logger.info(`[${i}][handleUnparkCompletion] body ${je(t)}`);const n=t.resumeCompletion;n.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.telemetryHelper.recordEvent("UnparkCompleted",{...n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(n,i),this.links[wa.LINKS.UNPARK]=void 0):this.handleUnparkError(n,"UnparkFailed",i)}getNetworkRequestName(e){return{none:null,teamPark:Zo.SEND_PARK_REQUEST.name,sharedLinePark:Zo.SEND_SHARED_LINE_PARK_REQUEST.name,serverHold:Zo.SEND_SERVER_HOLD_REQUEST.name}[e]}updateMeetingsGroupsAsync(e,t){this.logger.info(`[${e}][updateMeetingsGroupsAsync] scope=${t.scope}`),this.telemetryHelper.recordEvent("UpdateMeetingGroups",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION,(()=>{this.handleUpdateMeetingGroupsError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT},jo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT);const i=function(e,t,i){Ua(e,"signalingSession cannot be null");const{scope:n,toGroup:r,fromGroup:s,participants:a}=t;"specified"===n&&Ua(a,"participantsIds cannot be null");const o={from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},scope:n,fromGroup:s,toGroup:r,links:{updateMeetingGroupsStatus:Ra(e,ra.UPDATE_MEETING_GROUPS_STATUS)},operationId:i};return a&&(o.to=a.map((e=>({id:e.mri,endpointId:e.endpointId,participantId:e.participantId})))),{payload:o}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_GROUPS],requestName:Zo.UPDATE_MEETING_GROUPS.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingsGroupsAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(jo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingsGroupsAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingGroupsError(n.error,"UpdateMeetingGroupsRequestFailed",e,e,t),Promise.reject(n.error))}))}updateMonitorSessionAsync(e,t){this.logger.info(`[${t}][updateMonitorSessionAsync]`),this.telemetryHelper.recordEvent("UpdateMonitorSession",{causeId:t,options:e}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,(()=>{this.handleUpdateMonitorSessionError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT},Qo,t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT);const i=function(e,t,i,n){return Ua(e,"signalingSession cannot be null"),{payload:{monitorContent:{sequenceId:e.getMonitorSequenceId(),monitorActionType:t,monitorData:i??{},links:{monitorCompletion:Ra(e,ra.MONITOR_COMPLETION)}},debugContent:{causeId:n}}}}(this,e.monitorActionType,e.monitorData,t);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MONITOR_SESSION],requestName:Zo.UPDATE_MONITOR_SESSION.name,payload:i,causeId:t}).then((e=>{this.logger.info(`[${t}][updateMonitorSessionAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent(Qo,{causeId:t})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][updateMonitorSessionAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMonitorSessionError(n.error,"UpdateMonitorSessionRequestFailed",t,e),Promise.reject(n.error))}))}updateParticipantInterpretationStateAsync(e,t){return Fa(t,"options should be a non null value"),this.logger.info(`[${e}][updateParticipantInterpretationStateAsync]`),this.telemetryHelper.recordEvent("UpdateParticipantInterpretationState",{causeId:e,options:t}),this.participantManager.updateParticipantInterpretationStateAsync(t,this.links[wa.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE],e)}async sendProxiedMessageAsync(e,t){return t&&0!==t.length?this.links[wa.LINKS.SEND_MESSAGE]?this.proxiedMessageNotificationManager.sendProxiedMessageAsync(e,t,this.links[wa.LINKS.SEND_MESSAGE]):Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"missing url for CONSTANTS.LINKS.SEND_MESSAGE"}):Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"options should be a non empty array"})}async updateParticipantsPropertiesAsync(e,t,i,n){this.telemetryHelper.recordEvent("UpdateParticipantsProperties",{causeId:n,updateParticipantsPropertiesContext:e});const r=this.links[wa.LINKS.UPDATE_PARTICIPANTS_PROPERTIES],s=[],a=e.scope;if("self"===a){const t={id:this.participantManager.localParticipant.id,propertyBag:e.propertyBag};s.push(t)}else{if("specified"!==a)return Promise.reject("This scope is not Supported");{const t=e.participants;for(const e of t){const t={id:e.id,propertyBag:e.propertyBag};s.push(t)}}}return this.sendNetworkRequestForUpdateParticipantsProperties(s,t,r,i,n)}sendNetworkRequestForUpdateParticipantsProperties(e,t,i,n,r){const s=this.logger.createChild(`[${r}][sendNetworkRequestForUpdateParticipantsProperties]`,this.correlationId);if(i){const a=()=>{const e={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT};this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,(()=>{this.handleUpdateParticipantsPropertiesOnTimeout(t,e,"UpdateParticipantsPropertiesTimeout",n,r)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT,n)},o=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId},to:t,links:{updateParticipantPropertiesStatus:Ra(e,ra.UPDATE_PARTICIPANT_PROPERTIES_STATUS)},operationId:i}}}(this,e,n);return this.updateParticipantsPromises[n]=t,this.http.sendPostRequest({url:i,payload:o,requestName:Zo.UPDATE_PARTICIPANTS_PROPERTIES.name,onceTrouterReady:a,causeId:r}).then((e=>{s.info(`response: ${je(e)}`)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);s.info(`failed: ${je(t)}`);const i={...t.error};return this.disposed||(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,n),delete this.updateParticipantsPromises[n]),this.telemetryHelper.recordEvent(qo,{causeId:r,transactionEnd:i}),Promise.reject(i)}))}{const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING,phrase:"updateParticipantsProperties link is missing"};return s.warn(e),this.telemetryHelper.recordEvent(qo,{causeId:r,error:e}),Promise.reject(e)}}checkAndCleanupPromisesForOperationId(e){this.updateParticipantsPromises[e]&&(0===this.updateParticipantsPromises[e].size?(delete this.updateParticipantsPromises[e],this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,e)):this.logger.info(`remaining promises for the operation ${e} (count: ${this.updateParticipantsPromises[e].size}):\n ${this.piiUtils.scrubMriOrOmit(Ge(this.updateParticipantsPromises[e]))}`))}handleUpdateParticipantsPropertiesOnTimeout(e,t,i,n,r){if(this.disposed)return void this.logger.info("handleUpdateParticipantsPropertiesOnTimeout ignored");this.logger.createChild(`[${r}][handleUpdateParticipantsPropertiesOnTimeout]`,this.correlationId).info(`reason: ${t}`),this.telemetryHelper.recordEvent(i,{...t,causeId:r});const s={};e.forEach((e=>{s[e]=t,this.updateParticipantsPromises[n].delete(e)})),this.checkAndCleanupPromisesForOperationId(n),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(s,n,r)}joinMeetingGroupAsync(e,t){this.logger.info(`[${e}][joinMeetingGroupAsync]`),this.telemetryHelper.recordEvent("JoinMeetingGroup",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION,(()=>{this.handleJoinMeetingGroupError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.JOIN_MEETING_GROUP_TIMEOUT,phrase:wa.CALL_END_PHRASE.JOIN_MEETING_GROUP_TIMEOUT},zo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.JOIN_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},..."meetingGroupId"in t&&{meetingGroup:t.meetingGroupId},..."meetingGroupLabel"in t&&{meetingGroupLabel:t.meetingGroupLabel},...t.groupPreferences&&{groupPreferences:t.groupPreferences},links:{joinMeetingGroupStatus:Ra(e,ra.JOIN_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.JOIN_MEETING_GROUP],requestName:Zo.JOIN_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][joinMeetingGroupAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(zo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][joinMeetingGroupAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleJoinMeetingGroupError(n.error,"JoinMeetingGroupRequestFailed",e,e,t),Promise.reject(n.error))}))}leaveMeetingGroupAsync(e,t){this.logger.info(`[${e}][leaveMeetingGroupAsync]`),this.telemetryHelper.recordEvent("LeaveMeetingGroup",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION,(()=>{this.handleLeaveMeetingGroupError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.LEAVE_MEETING_GROUP_TIMEOUT,phrase:wa.CALL_END_PHRASE.LEAVE_MEETING_GROUP_TIMEOUT},Wo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){Ua(e,"signalingSession cannot be null");const{meetingGroupId:n}=t;return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingGroup:n,links:{leaveMeetingGroupStatus:Ra(e,ra.LEAVE_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE_MEETING_GROUP],requestName:Zo.LEAVE_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][leaveMeetingGroupAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(Wo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][leaveMeetingGroupAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleLeaveMeetingGroupError(n.error,"LeaveMeetingGroupRequestFailed",e,e,t),Promise.reject(n.error))}))}handleUpdateMeetingGroupsError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingGroupsError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingGroupsError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(e,i,n))}handleUpdateMeetingGroupsCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingGroupsResponse.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateMeetingGroupsCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] starts`);const{updateMeetingGroupsResponse:r}=t,s=$d(r);s.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group succeeded`),this.telemetryHelper.recordEvent("UpdateMeetingGroupsResponseSuccess",{...s,causeId:i})):(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group failed code=${s.code} subCode=${s.subCode}`),this.telemetryHelper.recordEvent("UpdateMeetingGroupsResponseFailure",{...s,causeId:i})),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] completes`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(s,i,n)}handleJoinMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleJoinedMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleJoinedMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,joinMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onJoinMeetingGroupCompleted(e,i,n))}handleJoinMeetingGroupCompletion(e){const t=e.body.joinMeetingGroupResponse,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleJoinMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] starts`);const r=$d(t);r.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group succeeded`),this.telemetryHelper.recordEvent("JoinMeetingGroupRequestCompleted",{...r,causeId:i})):(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent("JoinMeetingGroupRequestFailed",{...r,causeId:i})),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onJoinMeetingGroupCompleted(r,i,n)}handleLeaveMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleLeaveMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleLeaveMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,leaveMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(e,i,n))}handleLeaveMeetingGroupCompletion(e){const t=e.body.leaveMeetingGroupResponse,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleLeaveMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] starts`);const r=$d(t);r.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group succeeded`),this.telemetryHelper.recordEvent("LeaveMeetingGroupRequestCompleted",{...r,causeId:i})):(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent("LeaveMeetingGroupRequestFailed",{...r,causeId:i})),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(r,i,n)}handleDisablePreheatError(e,t,i){this.disposed?this.logger.info(`[${i}][handleDisablePreheatError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleDisablePreheatError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject(e))}handleDisablePreheatCompletion(e){const t=e.body,i=Qa(e),n=t.transactionEnd;if(this.disposed)this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Call disposed.`);else if(this.disablePreheatDefer.isPending()){if(this.logger.info(`[${i}][handleDisablePreheatCompletion] starts`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),n.code===wa.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state succeeded`),this.handleEndpointStateUpdated(i,!0);else if(this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state failed code=${n.code} subCode=${n.subCode}`),this.disablePreheatDefer.isPending()){const e={response:n};this.disablePreheatDefer.reject(e)}}else this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Disable preheat promise is resolved/rejected.`)}handleReceiveMessage(e){const t=Qa(e);if(this.disposed)return void this.logger.info(`[${t}][handleReceiveMessage] ignored. Call disposed.`);let i;i=Array.isArray(e.body?.messageContent)?e.body.messageContent:[e.body];let n="";const r=[];for(let e=0;e<i.length;e++){const t=i[e];n+=t?.operationId,e<i.length-1&&(n+=","),r.push({operationId:t.operationId,messageType:t.type,payload:t.payload,from:{[t.from.id]:{participantLegIdMap:{[t.from.participantId]:{...t.from.endpointId&&{endpointId:t.from.endpointId}}},level:"endpoint"}}})}this.logger.info(`[${t}][handleReceiveMessage] complete. OperationIds:${n}`),this.telemetryHelper.recordEvent("incomingProxiedMessages",{causeId:t,operationIds:n}),this.signalingSessionCallback.onIncomingProxiedMessages(r,t)}publishStateAsync(e,t,i,n,r,s){this.logger.info(`[${i}][publishStateAsync][publishType=${e} publishLevel=${t}]`),this.telemetryHelper.recordEvent("PublishState",{causeId:i,publishType:e,publishLevel:t});const a=this.links[wa.LINKS.PUBLISH_STATE];if(!a){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_LINK_MISSING,phrase:"publish state link is missing"};return this.logger.warn(e),Promise.reject(e)}let o={};try{o=JSON.parse(n)}catch(e){const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_CONTENT,phrase:"publish state content is invalid"};return this.logger.warn(t),Promise.reject(t)}return this.http.sendPostRequest({url:a,requestName:Zo.PUBLISH_STATE.name,payload:ju(this,e,t,o,r,s),causeId:i,requestId:i}).then((e=>{if(e?.response?.publishStateResponse)return this.parsePublishStateResult(e,i);{const t=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${i}][publishStateAsync] error: ${je(t)}`);const n=t.error;return this.telemetryHelper.recordEvent("PublishStateFailure",{causeId:i,transactionEnd:n}),Promise.reject(n)}))}getPublishStateSequenceNumber(){return++this.publishStateSequenceNumber}getMonitorSequenceId(){return++this.monitorSequenceId}parsePublishStateResult(e,t){let i={};if(e?.response?.publishStateResponse){if(e.response.publishStateResponse.stateId)return e.response.publishStateResponse.stateId;if(e.response.publishStateResponse.results){if(1===e.response.publishStateResponse.results.length){if(e.response.publishStateResponse.results[0].stateId)return e.response.publishStateResponse.results[0].stateId;this.logger.warn("invalid response format")}return e.response.publishStateResponse.results.forEach((e=>{i[e.participantId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})),JSON.stringify(i)}if(e.response.publishStateResponse.result)return i={code:e.response.publishStateResponse.result.code,phrase:e.response.publishStateResponse.result.phrase,subCode:e.response.publishStateResponse.result.subCode,result:e.response.publishStateResponse.additionalDetail},JSON.stringify(i)}const n=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(n),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:n}}}removeStateAsync(e,t,i,n){if(this.logger.info(`[${e}][removeStateAsync][scope=${t} publishType=${i} stateIds=${n}]`),this.telemetryHelper.recordEvent("RemoveState",{causeId:e,scope:t,publishType:i,stateIds:n}),!i&&!n){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.REMOVE_STATE_MISSING_ARGUMENTS,phrase:"remove state operation miss arguments"};return this.logger.warn(e),Promise.reject(e)}const r=this.links[wa.LINKS.REMOVE_STATE];if(!r){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.REMOVE_STATE_LINK_MISSING,phrase:"remove state link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:r,requestName:Zo.REMOVE_STATE.name,payload:qu(this,t,n,i),causeId:e,requestId:e}).then((t=>this.parseRemoveStateResult(t,e))).catch((t=>{const i=Ka(t,this.signalingAgentConfig);this.logger.info(`[${e}][removeStateAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("RemoveStateFailure",{causeId:e,transactionEnd:n}),Promise.reject(n)}))}parseRemoveStateResult(e,t){let i={};return e?.response?.removeStateResponse&&(e.response.removeStateResponse.results?e.response.removeStateResponse.results.forEach((e=>{i[e.stateId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})):e.response.removeStateResponse.result&&(i={code:e.response.removeStateResponse.result.code,phrase:e.response.removeStateResponse.result.phrase,subCode:e.response.removeStateResponse.result.subCode,result:e.response.removeStateResponse.additionalDetail})),JSON.stringify(i)}updateMeetingSettingsAsync(e,t){this.telemetryHelper.recordEvent("UpdateMeetingSettings",{causeId:t,meetingSettings:e});const i=this.links[wa.LINKS.UPDATE_MEETING_SETTINGS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_LINK_MISSING,phrase:"update meeting settings link is missing"};return this.logger.warn(e),Promise.reject(e)}if(!Object.keys(e).length){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS,phrase:"update meeting settings missing arguments"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPutRequest({url:i,requestName:Zo.UPDATE_MEETING_SETTINGS.name,payload:Zu(this,e),causeId:t,requestId:t}).then((()=>{kd.noop()})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][updateMeetingSettingsAsync] error: ${je(i)}`);const n=i.error;throw this.telemetryHelper.recordEvent("UpdateMeetingSettingsFailure",{causeId:t,transactionEnd:n}),n}))}searchParticipantsAsync(e,t){this.logger.info(`[${t}][searchParticipantsAsync][queryOptions=${e}]`),this.telemetryHelper.recordEvent("SearchParticipants",{causeId:t,queryOptions:e});const i=this.links[wa.LINKS.SEARCH_PARTICIPANTS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_LINK_MISSING,phrase:"search participants link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:Zo.SEARCH_PARTICIPANTS.name,payload:zu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response?.participants)return this.parseSearchParticipantsResult(e,t);{const t=`Invalid CS response which does not contain proper search results. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][searchParticipantsAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("SearchParticipantsFailure",{causeId:t,transactionEnd:n}),Promise.reject(n)}))}parseSearchParticipantsResult(e,t){const i=[];if(e?.response){const t=e.response.participants;if(t)for(const n of Object.keys(t))i.push(mo.fromRosterSearchResults(e.response.participants[n]))}return{participants:i}}getAllParticipantsAsync(e,t){this.logger.info(`[${t}][getAllParticipantsAsync][scope=${e}]`),this.telemetryHelper.recordEvent("GetAllParticipants",{causeId:t,scope:e});const i=this.links[wa.LINKS.GET_ALL_PARTICIPANTS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_LINK_MISSING,phrase:"get all participants link is missing"};return this.logger.warn(e),Promise.reject(e)}if("lobby"!==e){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SCOPE,phrase:"get all participants scope is invalid"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:Zo.GET_ALL_PARTICIPANTS.name,payload:Fu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response)return{participants:e.response.participants};{const e="Invalid CS response which does not contain results.";throw this.logger.warn(e),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:e}}}})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][getAllParticipantsAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("GetAllParticipantsFailure",{causeId:t,transactionEnd:n}),Promise.reject(n)}))}resetState(){this.currentCallStatus=null,this.fsmState=wa.SIGNALING_FSM_STATE.IDLE}saveUpdatedCallLinksIfAny(e){e.links&&(this.logger.info(`saveUpdatedCallLinksIfAny, updated call links found, update to new links ${je(e)}`),this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.links.mediaRenegotiation||this.links[wa.LINKS.MEDIA_RENEGOTIATION],this.links[wa.LINKS.TRANSFER]=e.links.transfer||this.links[wa.LINKS.TRANSFER],this.links[wa.LINKS.REPLACE]=e.links.replacement||this.links[wa.LINKS.REPLACE],this.links[wa.LINKS.HANGUP]=e.links.callLeg||this.links[wa.LINKS.HANGUP],this.links[wa.LINKS.KEEPALIVE]=e.links.callLeg||this.links[wa.LINKS.KEEPALIVE],this.links[wa.LINKS.PARK]=e.links.hold||this.links[wa.LINKS.PARK],this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.links.updateMediaDescriptions||this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS],this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.links.monitor||this.links[wa.LINKS.UPDATE_MONITOR_SESSION])}ensureMessageChannelReady(e){return this.disposed?(this.logger.info("ensureMessageChannelReady: error: call already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):this.brokerService?(this.telemetryHelper.addTrouterWaitOperation(`${Ed}:${e}`),this.telemetryHelper.addTrouterWaitOperation(`${bd}:${e}`),Promise.resolve()):this.ensureLatestTrouterUrl(e)}ensureLatestTrouterUrl(e){return this.telemetryHelper.addTrouterWaitOperation(`${Ed}:${e}`),this.getTrouterUrlAsync().then((t=>!t||"string"==typeof t&&!t.trim()?(this.telemetryHelper.recordEvent("TrouterUrlChangedToInvalid"),this.telemetryHelper.addTrouterWaitOperation(`${bd}:${e}`),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(`${bd}:${e}`),this.baseMessagingChannelUrl=this.currentTrouterUrl=t,Promise.resolve()))).catch((t=>(this.disposed||this.telemetryHelper.addTrouterWaitOperation(`${_d}:${e}`),this.logger.info(`ensureLatestTrouterUrl, failed because:${t}`),Promise.reject(t))))}signalTransferAcceptedAsync(e,t=Na()){return this.logger.info(`[signalTransferAcceptedAsync][${t}] transferType ${e}`),this.disposed?(this.logger.info(`[signalTransferAcceptedAsync][${t}] Call already ended, skip acceptance request`),Promise.reject({code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(this.telemetryHelper.recordEvent("SendAcceptTransfer",{causeId:t,transferType:e}),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER_ACCEPTANCE],requestName:Zo.TRANSFER_ACCEPTANCE.name,payload:{payload:{transferAcceptance:{}}},causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferAcceptedAsync][${t}] error: ${je(i)}`),this.telemetryHelper.recordEvent("SendAcceptTransferFail",{causeId:t}),Promise.reject(i.error)})))}signalTransferCompletedAsync(e,t=Na()){return this.logger.info(`[signalTransferCompletedAsync][${t}] rejectReason ${e}`),this.disposed?(this.logger.info(`[signalTransferCompletedAsync][${t}] Call already ended by transferor, skip completion request`),Promise.reject({code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(0!==e.code?this.telemetryHelper.recordEvent(ko,{code:e.code,subcode:e.subCode,causeId:t}):this.telemetryHelper.recordEvent(Ho,{causeId:t}),this.telemetryHelper.recordEvent("SendCompleteTransfer",{causeId:t}),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER_COMPLETION],requestName:Zo.TRANSFER_COMPLETION.name,payload:Ku(e),causeId:t}).catch((e=>{this.telemetryHelper.recordEvent("SendCompleteTransferFailed",{causeId:t});const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferCompletedAsync][${t}] error: ${je(i)}`),Promise.reject(i.error)})))}async rejectCallWithFetchAndKeepAlive(e){this.telemetryHelper.recordEvent("RejectWithFetchKeepAlive",{causeId:e});const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.BEACON,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:[Qs]};await this.http.sendDeleteRequest({url:this.links[wa.LINKS.REJECT],requestName:Zo.REJECT_CALL.name,payload:Gu(this,t),causeId:e??Na(),requestId:La(),useFetch:!0,fetchUseKeepAlive:!0})}async endCallWithFetchAndKeepAlive(e,t,i,n){this.telemetryHelper.recordEvent("EndWithFetchKeepAlive",{causeId:n}),await this.http.sendPostRequest({url:e,requestName:Zo.END_CALL.name,payload:t,causeId:n??Na(),requestId:La(),useFetch:!0,fetchUseKeepAlive:!0})}endWithBeacon(e){if(this.disposed)return!1;const t=()=>{this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,i),this.dispose(i,e)};if(this.signalingAgentConfig.enableFetchRequestWithKeepAlive&&window.Request?.prototype?.hasOwnProperty("keepalive")&&this.currentCallStatus===wa.CALL_STATUS.RINGING)return this.rejectCallWithFetchAndKeepAlive(e),t(),!0;const i={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.BEACON,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED},n=JSON.stringify(Bu(this,i).payload),r=-1===this.links[wa.LINKS.LEAVE].indexOf("?")?"?":"&",s=this.signalingAgent?.authTokenManager?.getLastTokenType(e),a=this.signalingAgent?.authTokenManager?.getLastToken(e);let o="";switch(s){case 4:case 8:this.logger.info(`[endWithBeacon] with tokenType:${s},token size:${a.length},query parameter:access_token`),o=`${this.links[wa.LINKS.LEAVE]}${r}access_token=${a}`;break;default:this.logger.info(`[endWithBeacon] with tokenType:${s},token size:${a.length},query parameter:skypeToken`),o=`${this.links[wa.LINKS.LEAVE]}${r}skypeToken=${a}`}return this.signalingAgentConfig.enableFetchApiForBeacon&&window.Request?.prototype?.hasOwnProperty("keepalive")?(this.endCallWithFetchAndKeepAlive(o,n,i,e),t(),!0):!!navigator?.sendBeacon&&(this.telemetryHelper.recordEvent("EndWithBeacon",{causeId:e}),navigator.sendBeacon(o,n))}setFsmState(e){this.fsmState=e}setIsHostless(e,t){const i=!!e;this.isHostLessCall!==i&&(this.logger.info(`[${t}][setIsHostless] isHostless=${i}`),this.isHostLessCall=i)}hasGroupModality(){return this.threadId||this.groupId}processConversationServiceResponseHeaders(e,t){this.logger.info(`[${t}][processConversationServiceResponseHeaders]`);try{const i=e.request.headers[wa.HEADERS.CORRELATION_ID]||e.request.headers[wa.HEADERS.CORRELATION_ID.toLowerCase()];this.updateCorrelationId(i,t)}catch(e){this.logger.info(`[${t}][processConversationServiceResponseHeaders] failed, reason=${je(e)}`)}}processConversationServiceResponse(e,t,i){const n=this.logger.createChild(`[${t}][processConversationServiceResponse]`);if(n.info(`responseType :${i}`),this.processConversationServiceUpdate(e,t),e.subscriptionDetails?.selfParticipant){const i=mo.fromRoster(e.subscriptionDetails.selfParticipant,!0);n.info("converted selfParticipant to Participant type"),this.participantManager.updateLocalParticipantFromSubscribe(i,t)}e.selfParticipant?.enableCaptcha&&this.participantManager.setEnableCaptcha(!0,t),this.handleBrokerSubscription(e,t),e.roster&&this.internalHandleRosterUpdate(e.roster,!0,t),0===i&&(this.startOrJoinConvResponseReceived=!0,this.handlePendingEndpointState(t))}processConversationServiceUpdate(e,t){const i=this.logger.createChild(`[${t}][processConversationServiceUpdate]`);i.info(),this.convJoined=!0;const n=e.sequenceNumber>=0?e.sequenceNumber:-1;n<this.updateSequenceNumber?i.info(`seqNum=${n} is less than latest seqNum=${this.updateSequenceNumber}`):(this.updateSequenceNumber=n,this.links[wa.LINKS.CONVERSATION_CONTROLLER]=e.conversationController,this.links[wa.LINKS.ADD_PARTICIPANT]=e.links.addParticipant,this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]=e.links.addParticipantAndModality,this.links[wa.LINKS.LEAVE]=e.links.leave,this.links[wa.LINKS.NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[wa.LINKS.REMOVE_PARTICIPANT]=e.links.removeParticipant,this.links[wa.LINKS.ADD_MODALITY]=e.links.addModality,this.links[wa.LINKS.REMOVE_MODALITY]=e.links.removeModality,this.links[wa.LINKS.MUTE]=e.links.mute||null,this.links[wa.LINKS.UNMUTE]=e.links.unmute||null,this.links[wa.LINKS.ADMIT]=e.links.admit||null,this.links[wa.LINKS.ADMIT_ALL]=e.links.admitAll||null,this.links[wa.LINKS.UPDATE_ENDPOINT_STATE]=e.links.updateEndpointState||null,this.links[wa.LINKS.UPDATE_ENDPOINT_METADATA]=e.links.updateEndpointMetadata||null,this.links[wa.LINKS.UPDATE_PARTICIPANT_ROLE]=e.links.updateParticipantRole||null,this.links[wa.LINKS.PUBLISH_STATE]=e.links.publishState||null,this.links[wa.LINKS.REMOVE_STATE]=e.links.removeState||null,this.links[wa.LINKS.UPDATE_MEETING_SETTINGS]=e.links.updateMeetingSettings||null,this.links[wa.LINKS.SEARCH_PARTICIPANTS]=e.links.searchParticipants||null,this.links[wa.LINKS.GET_ALL_PARTICIPANTS]=e.links.getAllParticipants||null,this.links[wa.LINKS.UPDATE_MEETING_LIVE_STATE]=e.links.updateMeetingLiveState||null,this.links[wa.LINKS.UPDATE_MEETING_GROUPS]=e.links.updateMeetingGroups||null,this.links[wa.LINKS.SET_MEETING_LAYOUT]=e.links.setMeetingLayout||null,this.links[wa.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE]=e.links.updateParticipantInterpretationState||null,this.links[wa.LINKS.UPDATE_PARTICIPANTS_PROPERTIES]=e.links.updateParticipantProperties||null,this.links[wa.LINKS.JOIN_MEETING_GROUP]=e.links.joinMeetingGroup||null,this.links[wa.LINKS.LEAVE_MEETING_GROUP]=e.links.leaveMeetingGroup||null,this.links[wa.LINKS.SEND_MESSAGE]=e.links.sendMessage||null,this.links[wa.LINKS.UPDATE_MEETING_STATES]=e.links.updateMeetingStates||null,this.convSubject=e.subject,e.state&&(this.setMultiParty(e.state.isMultiParty,t),this.setIsHostless(e.state.isHostless||!1,t),this.conversationType=e.state.conversationType,this.isCastCall="cast"===e.state.conversationType,this.isHuddleGroupCall="huddleGroupCall"===e.state.conversationType),e.activeModalities&&e.activeModalities.groupChat&&this.updateGroupChatIds(e.activeModalities.groupChat,t),e.activeModalities&&e.activeModalities.broadcast&&(this.broadcastSession||(this.broadcastSession=new jd(this,this.signalingSessionCallback)),this.broadcastSession.handleBroadcastDetailsChanged(e,t)),this.handleMeetingDetailsChanged(e,t),this.handleMeetingStatesChanged(e,t),this.linkUpdateRequested.conversationLinks?(i.info("Updating CS links as requested"),this.updateLinks(this.updateConversationLinks,t)):this.scheduleConversationKeepAlive(),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo),e.region&&(this.region=e.region),e.callLimits&&(this.callLimits=e.callLimits),e.complianceRecordingContent&&(this.complianceRecordingContent=e.complianceRecordingContent),e.conversationStartTime&&(this.conversationStartTime=e.conversationStartTime),e.layoutDetails&&(this.meetingLayoutDetails=e.layoutDetails),e.compositionServiceDetails&&(this.compositionServiceDetails=e.compositionServiceDetails),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,meetingLayoutDetails:this.meetingLayoutDetails,compositionServiceDetails:this.compositionServiceDetails},t))}processLocalParticipantUpdateResponse(e,t){this.logger.info(`[${t}][processLocalParticipantUpdateResponse]`),e.sequenceNumber&&e.sequenceNumber<this.localParticipantUpdateSequenceNumber||(this.breakoutDetails=e.breakoutDetails||{},this.signalingSessionCallback.onBreakoutDetailsUpdated(this.breakoutDetails,t),!0===e.nudgeToJoinAsRealtime&&(this.telemetryHelper.recordEvent("NudgeToJoinAsRealtime",{causeId:t}),this.signalingSessionCallback.onNudgeToJoinRealtime(t)))}handlePendingEndpointState(e){this.requestedEndpointStateWhileConnecting&&(this.logger.info(`[${e}][handlePendingEndpointState]sending pending endpoint state now that we are connected.`),this.updateEndpointState(this.requestedEndpointStateWhileConnecting,e,this.requestedPublishedStatesWhileConnecting).catch((e=>{this.isPreheatOnly&&this.disablePreheatDefer.isPending()&&(this.logger.info("handlePendingEndpointState failed"),this.disablePreheatDefer.reject(e))})))}handleMeetingDetailsChanged(e,t){this.logger.info(`[${t}][handleMeetingDetailsChanged]`),e.meetingDetails&&!kd.isEqual(e.meetingDetails,this.meetingDetails)&&this.signalingSessionCallback.onMeetingDetailsUpdated&&(this.meetingDetails=e.meetingDetails,this.meetingDetails.meetingCapability?.meetingLiveState&&(this.meetingLiveStateSequenceNumber=this.meetingDetails.meetingCapability.meetingLiveState.seqNum,this.logger.info(`[${t}][handleMeetingDetailsChanged] update meeting seqNum as ${this.meetingLiveStateSequenceNumber}`)),this.signalingSessionCallback.onMeetingDetailsUpdated(this.meetingDetails,t))}handleMeetingStatesChanged(e,t){this.logger.info(`[${t}][handleMeetingStatesChanged]`),this.signalingSessionCallback.onMeetingStatesUpdated&&this.signalingSessionCallback.onMeetingStatesUpdated(e.meetingStates,t)}handleBrokerSubscription(e,t){this.logger.info(`[${t}][handleBrokerSubscription]`),e.links.subscribe?(this.telemetryHelper.recordEvent("SubscribeUrlFound",t),this.brokerService&&!kd.isEqual(e.links.subscribe,this.brokerService.currentSubscriptionUrl)?this.brokerService.subscribeToBroker(e.links.subscribe):(this.logger.info(`[${t}][handleBrokerSubscription] broker subscribe ignored. Broker is disabled or subscribe url is same.`),this.telemetryHelper.recordEvent("BrokerDisabledSubscribeUrlPresent",t))):this.telemetryHelper.recordEvent("SubscribeUrlMissing",t)}cancelOutgoingCall(e,t){const i=to();this.logger.info(`[${t}][cancelOutgoingCall][rejectionData=${e&&je(e)}]`);const n={code:isNaN(e?.code)?wa.CALL_END_CODE.CANCEL:e.code,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories||[Qs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};if(this.signalingAgentConfig.enableSpecificErrorCodesForCallEnd&&(n.code=wa.CALL_END_CODE.CANCEL,n.subCode=wa.CALL_END_SUB_CODE.SUCCESS,n.phrase=wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,n.resultCategories=[Qs]),this.links.hasOwnProperty(wa.LINKS.LEAVE)){this.logger.info(`[${t}][cancelOutgoingCall] cancelling outgoing call`),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const e={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()},r={terminatingEnd:sd,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE],requestName:Zo.CANCEL_CALL.name,payload:Lu(this,n,e),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const s=Ka(e,this.signalingAgentConfig);this.logger.info(`[cancelOutgoingCall][${t}] error: ${je(e)} xhrError: ${je(s)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)}))}else this.logger.info(`[${t}][cancelOutgoingCall] Conversation Service Leave Url is not yet set. Cannot leave conversation. Disposing anyways.`),n.subCode=wa.CALL_END_SUB_CODE.CONV_URL_NOT_SET,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t),i.resolve(null);return i.promise}terminateEstablishedCall(e,t){const i=t.causeId||Na();this.logger.info(`[${i}][terminateEstablishedCall]`);const n=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const r=this.convJoined?Zo.LEAVE_CONVERSATION.name:Zo.END_CALL.name,s=tu(),a={code:e?.code||wa.CALL_END_CODE.SUCCESS,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};a.resultCategories=a.resultCategories||[Qs];const o={terminatingEnd:sd,endCode:a.code,endSubCode:a.subCode,resultDetail:a.phrase||"TerminateEstablishedCall",causeId:i,clientReasonSubCode:a.clientReasonSubCode,clientReasonPhrase:a.clientReasonPhrase,resultCategories:a.resultCategories};return this.leaveConversation(a,t).then((()=>{this.logger.info(`[${i}][terminateEstablishedCall]success`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!0,s.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,a),this.dispose(a,i)),n.resolve(null)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${i}][terminateEstablishedCall][failed] error: ${je(e)} xhrError: ${je(t)}]`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!1,s.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,a),this.dispose(a,i)),n.resolve(null)})),n.promise}deleteConversation(e,t){this.logger.info(`[${t}][deleteConversation]`);const i=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const n=Zo.DELETE_CONVERSATION.name,r=tu(),s={code:e?.code||wa.CALL_END_CODE.SUCCESS,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED,resultCategories:e?.resultCategories||[Qs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase},a={terminatingEnd:sd,endCode:s.code,endSubCode:s.subCode,resultDetail:s.phrase,causeId:t,clientReasonSubCode:s.clientReasonSubCode,clientReasonPhrase:s.clientReasonPhrase,resultCategories:s.resultCategories};return this.deleteConversationController(s,t).then((()=>{this.logger.info(`[${t}][deleteConversation]success`),this.disposed||(this.telemetryHelper.setTerminatingData(a),this.telemetryHelper.addNetworkOperationCompleted(n,!0,r.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,s),this.dispose(s,t)),i.resolve(null)})).catch((e=>{const o=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][deleteConversation][failed] error: ${je(e)} xhrError: ${je(o)}`),this.disposed||(this.telemetryHelper.setTerminatingData(a),this.telemetryHelper.addNetworkOperationCompleted(n,!1,r.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,s),this.dispose(s,t)),i.resolve(null)})),i.promise}leaveConversation(e,t){const i=t.causeId||Na();if(this.convJoined){this.logger.info(`[${i}][leaveConversation]`);const n={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()};return this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE],requestName:Zo.LEAVE_CONVERSATION.name,payload:Bu(this,e,n,t.scope),withoutTrouter:!0,causeId:i})}return this.logger.info(`[${i}][leaveConversation] ignore, not joined to conversation`),Promise.resolve(void 0)}deleteConversationController(e,t){return this.convJoined?(this.logger.info(`[${t}][deleteConversationController]`),this.http.sendDeleteRequest({url:this.links[wa.LINKS.CONVERSATION_CONTROLLER],requestName:Zo.DELETE_CONVERSATION.name,payload:xu(this,e),withoutTrouter:!0,causeId:t})):(this.logger.info(`[${t}][deleteConversationController]ignored, not joined to conversation`),Promise.resolve(void 0))}rejectIncomingCall(e,t){this.telemetryHelper.recordEvent("RejectIncomingCall",t),this.logger.info(`[${t}][rejectIncomingCall]`);const i=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const n={code:isNaN(e?.code)?wa.CALL_END_CODE.REJECT:e.code,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase,...this.signalingAgent?.accountConfig?.applicationType?{applicationType:this.signalingAgent.accountConfig.applicationType}:{}};n.resultCategories=n.resultCategories||[Qs];const r={terminatingEnd:sd,endCode:n.code,endSubCode:n.subCode,resultDetail:n.phrase||"RejectCall",causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};return this.http.sendDeleteRequest({url:this.links[wa.LINKS.REJECT],requestName:Zo.REJECT_CALL.name,payload:Gu(this,n),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const s=Ka(e,this.signalingAgentConfig);this.logger.info(`[rejectIncomingCall][${t}] error: ${je(e)} xhrError: ${je(s)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})),i.promise}onCallStatusChanged(e,t,i){const n=`[${t}][onCallStatusChanged]`;if(this.logger.info(`${n}${this.currentCallStatus}=>${e}]`),this.disposed)this.logger.info(`${n}Call is already disposed!!`);else if(i&&this.logger.info(`${n}[statusCode=${je(i)}]`),this.isPromotingToRealtime)e===wa.CALL_STATUS.CONNECTED&&this.onPromotionCompleted(!1,void 0,t);else if(this.isValidStateTransitions(e)){this.currentCallStatus=e;const n={callStatus:e,statusCode:i,causeId:t};this.isPreheatOnly&&(n.isPreheatOnly=!0),this.telemetryHelper.recordEvent("UpdateCallStatus",n),this.signalingSessionCallback.onCallStatusChanged(e,i,t),this.currentCallStatus===wa.CALL_STATUS.CONNECTED&&(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.telemetryHelper.resetCallCancelationDurationWatch(),this.isPreheatOnly&&this.startCallPreheatTimer(t))}}updateMeetingLiveStateAsync(e,t){this.logger.info(`[${e}][updateMeetingLiveStateAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent("UpdateMeetingLiveState",{causeId:e,meetingLiveStateOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,(()=>{this.handleUpdateMeetingLiveStateError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT},$o,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT);const i=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingLiveState:t,links:{updateMeetingLiveStateStatus:Ra(e,ra.UPDATE_MEETING_LIVE_STATE_STATUS)},operationId:i}}}(this,{...t,sequenceNumber:this.meetingLiveStateSequenceNumber},e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_LIVE_STATE],requestName:Zo.UPDATE_MEETING_LIVE_STATE.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingLiveStateAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent($o,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingLiveStateAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingLiveStateError(n.error,"UpdateMeetingLiveStateRequestFailed",e,e,t),Promise.reject(n.error))}))}updateMeetingStatesAsync(e,t){const i=this.logger.createChild(`[${e}][updateMeetingStatesAsync]`,this.correlationId);if(i.info(`meetingStatesOptions: ${JSON.stringify(t)}`),!t)return Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"meetingStatesOptions should be a non empty object"});this.telemetryHelper.recordEvent("UpdateMeetingStates",{causeId:e,meetingStatesOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,(()=>{for(const i in t.meetingStates)this.handleUpdateMeetingStatesError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT},Jo,e,t.operationId+"_"+i)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT);const n=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingStates:t,updateMeetingStatesStatus:Ra(e,ra.UPDATE_MEETING_STATES_STATUS),operationId:i}}}(this,{...t.meetingStates},e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_STATES],requestName:Zo.UPDATE_MEETING_STATES.name,payload:n,causeId:e}).then((t=>{i.info(`response: ${je(t)}`),this.telemetryHelper.recordEvent(Jo,{causeId:e})})).catch((n=>{const r=Ka(n,this.signalingAgentConfig);if(i.error(`error: ${je(r)}`),!this.disposed){for(const i in t.meetingStates)this.handleUpdateMeetingStatesError(r.error,Yo,e,t.operationId+"_"+i);return Promise.reject(r.error)}return Promise.reject(this.getCallNotFoundTransactionEnd())}))}handleUpdateMeetingLiveStateError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted&&this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted(e,i,n))}handleUpdateMeetingLiveStateCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingLiveStateResponse.result,r=t.updateMeetingLiveStateResponse.operationId;r||this.logger.warn(`[${i}][handleUpdateMeetingLiveStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingLiveStateCompletion] meetingLiveUpdate completes with operationId=${r}`),this.handleOperationCompletionCommon(n,i,r,je(t),"handleUpdateMeetingLiveStateCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,"UpdateMeetingLiveStateResponseSuccess","UpdateMeetingLiveStateResponseFailure",this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted,this.handleUpdateMeetingLiveStateError.bind(this))}handleUpdateMeetingStatesError(e,t,i,n){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingStatesError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingStatesError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.signalingSessionCallback.onUpdateMeetingStatesCompleted&&this.signalingSessionCallback.onUpdateMeetingStatesCompleted(e,i,n))}handleUpdateMeetingStatesCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingStatesResponse,r=t.operationId,s=this.logger.createChild(`[${i}][handleUpdateMeetingStatesCompletion]`,this.correlationId);r||s.warn("operationId is undefined.");for(const e of n)s.info(`UpdateMeetingStates completes with operationId=${r}.`),this.handleOperationCompletionCommon(e.transactionEnd,i,r+"_"+e.meetingStateName,je(t),"handleUpdateMeetingStatesCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,"UpdateMeetingStatesResponseSuccess",Yo,this.signalingSessionCallback.onUpdateMeetingStatesCompleted,this.handleUpdateMeetingStatesError.bind(this))}handleUpdateMonitorSessionCompletion(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleUpdateMeetingStatesCompletion]`,this.correlationId);const n=t.monitorCompletion;this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleUpdateMonitorSessionCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,"UpdateMonitorSessionResponseCompleted","UpdateMonitorSessionResponseFailed",this.signalingSessionCallback.onUpdateMonitorSessionCompleted,this.handleUpdateMonitorSessionError.bind(this))}handleUpdateMonitorSessionError(e,t,i,n){this.disposed?this.logger.info(`[${i}][handleUpdateMonitorSessionError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMonitorSessionError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,monitorOptions:n,causeId:i}),this.signalingSessionCallback.onUpdateMonitorSessionCompleted(e,i))}setMeetingLayoutAsync(e,t){this.logger.info(`[${e}][setMeetingLayoutAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent("SetMeetingLayout",{causeId:e,setMeetingLayoutOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,(()=>{this.handleSetMeetingLayoutError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT},Go,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT);const i=function(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},...t,links:{setMeetingLayoutStatus:Ra(e,ra.SET_MEETING_LAYOUT_STATUS)}}}}(this,{...t,sequenceNumber:this.meetingLayoutSequenceNumber});return this.http.sendPostRequest({url:this.links[wa.LINKS.SET_MEETING_LAYOUT],requestName:Zo.SET_MEETING_LAYOUT.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][setMeetingLayoutAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(Go,{causeId:e})})).catch((i=>{const n=Ka(i);return this.logger.info(`[${e}][setMeetingLayoutAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleSetMeetingLayoutError(n.error,"SetMeetingLayoutRequestFailed",e,e,t),Promise.reject(n.error))}))}handleSetMeetingLayoutError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleSetMeetingLayoutError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleSetMeetingLayoutError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onSetMeetingLayoutCompleted&&this.signalingSessionCallback.onSetMeetingLayoutCompleted(e,i,n))}handleSetMeetingLayoutCompletion(e){const t=e.body,i=Qa(e),n=t.transactionEnd,r=t.operationId;n.result=t.layoutDetails,r||this.logger.warn(`[${i}][handleSetMeetingLayoutCompletion] operationId is undefined.`),this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleSetMeetingLayoutCompletion",wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,"SetMeetingLayoutResponseSuccess","SetMeetingLayoutResponseFailure",this.signalingSessionCallback.onSetMeetingLayoutCompleted,this.handleSetMeetingLayoutError.bind(this))}handleOperationCompletionCommon(e,t,i,n,r,s,a,o,l,c){this.disposed?this.logger.info(`[${t}][${r}] ignored. Call disposed.`):(this.logger.info(`[${t}][${r}] body ${n}`),e.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(s),this.telemetryHelper.recordEvent(a,{...e,causeId:t}),l&&l(e,t,i)):c&&c(e,o,t,i))}isValidStateTransitions(e){if(this.currentCallStatus===wa.CALL_STATUS.LOCAL_TERMINATED&&e===wa.CALL_STATUS.CONNECTING)return!0;const t=e=>{switch(e){case wa.CALL_STATUS.IDLE:case wa.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY:return 0;case wa.CALL_STATUS.CONNECTING:return 1;case wa.CALL_STATUS.RINGING:return 2;case wa.CALL_STATUS.CONNECTED:return 3;case wa.CALL_STATUS.LOCAL_TERMINATED:case wa.CALL_STATUS.REMOTE_TERMINATED:return 4;default:return-1}};return t(e)>t(this.currentCallStatus)}handlePSTNBalanceUpdate(e){const t=e.body.balanceUpdate,i=Qa(e);this.logger.info(`[${i}][handlePSTNBalanceUpdate]`),this.telemetryHelper.recordIncomingEvent(Fo,e),t.updateBalance?this.signalingSessionCallback.onPSTNBalanceUpdate(t):this.logger.info(Fo,"this was a pstn keepAlive message - ignore")}handleCallAcceptanceAck(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleCallAcceptanceAck]`),this.telemetryHelper.recordIncomingEvent("HandleCallAcceptanceAck",e),this.internalHandleCallAcceptanceAck(t,i)}internalHandleCallAcceptanceAck(e,t){this.logger.info(`[${t}][internalHandleCallAcceptanceAck] ${je(e)}`),this.fsmState!==wa.SIGNALING_FSM_STATE.CONNECTED&&(this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptanceAcknowledgement.links.mediaRenegotiation,this.links[wa.LINKS.TRANSFER]=e.callAcceptanceAcknowledgement.links.transfer,this.links[wa.LINKS.REPLACE]=e.callAcceptanceAcknowledgement.links.replacement,this.links[wa.LINKS.HANGUP]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[wa.LINKS.KEEPALIVE]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[wa.LINKS.PARK]=e.callAcceptanceAcknowledgement.links.hold,this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptanceAcknowledgement.links.updateMediaDescriptions,this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.callAcceptanceAcknowledgement.links.monitor,this.saveMediaControllerLinksIfAny(e.callAcceptanceAcknowledgement),this.scheduleKeepAlives(e.callAcceptanceAcknowledgement.callKeepAliveInterval),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptanceAcknowledgement.callProperties?.isSharedLineAppearanceV2Activated),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.INCOMING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][internalHandleCallAcceptanceAck] updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t)))}isFatalException(e){let t=!0;try{JSON.parse(e.message).code===wa.CALL_END_CODE.CONFLICT&&(t=!1,this.logger.info("isFatalException: received non-fatal 409 error"))}catch(e){this.logger.error("isFatalException: failed to parse error")}return t}startOrJoinCall(e,t,i,n,r){if(this.logger.info(`[${i}]startOrJoinCall[${t}]`),this.disposed)return void this.logger.info(`[${i}][${t}] session already disposed, ignore`);this.telemetryHelper.recordEvent("StartOrJoinCall",{causeId:i,requestName:t}),this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i);const s=this.getConversationUrl()?this.getConversationUrl():e.conversationServiceUrl;this.telemetryHelper.setConversationServiceUrl(s),this.logger.info(`options.conversationServiceUrl ${e.conversationServiceUrl} conversationServiceUrl ${s}`),e.isPreheatOnly?(this.isPreheatOnly=!0,this.telemetryHelper.recordEvent("EnablingPreheat",{causeId:i}),this.telemetryHelper.setSelfParticipantRole(md),this.telemetryHelper.setIsPreheated()):this.telemetryHelper.startCallCancelationDurationWatch(),this.mediaTypesToUse=r,this.lastUsedOutgoingMediaContent=n,this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);const a=!this.multiParty&&this.signalingAgentConfig.enableLongOutgoing1To1SetupTimeoutForWeb,o=a?wa.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`[${i}][${t}]target endpointType = ${this.transferContext&&this.transferContext.target?this.transferContext.target.endpointType:"default"} timeout = ${o} LongerTimeout = ${a}`);const l=e.newCall?function(e,t,i,n){Ua(e,"signalingSession cannot be null");let r=[];r=n.invitationType===wa.INVITATION_TYPE.NUDGE&&Array.isArray(n.participantsToNudge)?n.participantsToNudge.map((e=>({id:e}))):e.participantManager.getParticipantsToInitiateCallWith(),e.signalingAgentConfig.doHostlessCalling||xa(r.length>0,"remoteParticipants need to be set before a call can be made");const s={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},a=e.groupId?{id:e.groupId}:null,o=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,l=e.contentSharingManager.getContentSharingInfoToStartSharing(),c=null===l?null:{identifier:l.contentIdentifier,subject:l.subject,sessionState:l.sessionState,sessionUpdateSequenceNumber:l.sequenceNumber,links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},d=e.broadcastSession?.getContext(),u=e.getEndpointCapabilities();1===r.length&&e.telemetryHelper.setCalleeType(r[0].id),e.numberOfOriginalInvitees=r.length;const h=[];r.forEach((t=>{const i={id:t.id};t.displayName&&(i.displayName=t.displayName),t.participantId&&(i.participantId=t.participantId),(n.callToVoicemail||e.transferContext&&e.transferContext.target&&"voicemail"===e.transferContext.target.endpointType)&&(i.endpointType="voicemail"),h.push(i)}));const g=e.transferContext?e.transferContext.transferor:null,p=e.transferContext?e.transferContext.transferContext:null,m={};n.callToVoicemail&&(n.voicemailResourcePath&&(m.localResourcePath=n.voicemailResourcePath),n.voicemailItemId&&(m.voicemailItemId=n.voicemailItemId));const f={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,applicationType:n.applicationType,targetApplicationType:n.targetApplicationType,roster:s,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?n.subscribe?ra.CONV_END_SUBSCRIBE:ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE),confirmUnmute:Ra(e,ra.CONV_CONFIRM_UNMUTE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},broadcast:d,contentSharing:c,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin},to:h},capabilities:null,endpointCapabilities:u,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,groupContext:a,groupChat:o,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("createConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),f.payload.publishedStates=t}e.deviceType&&"default"!==e.deviceType&&(f.payload.conversationRequest.deviceType=e.deviceType);const v=Ha(i);if(e.telemetryHelper.addOutgoingModalities(v),f.payload.callInvitation={callModalities:v,replaces:null,transferor:g||null,clientTransferContext:p,customContext:n.customHeaderContext||null,links:{progress:Ra(e,ra.PROGRESS),mediaAnswer:Ra(e,ra.MEDIA_ANSWER),acceptance:Ra(e,ra.ACCEPT),redirection:Ra(e,ra.REDIRECTION),end:Ra(e,ra.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),pstnContent:e.pstnContent,emergencyContent:e.getEmergencyContent(),mediaContent:t,voicemailSettings:m,routingFlags:n.routingFlags,invitationData:n.invitationData,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent()},n.pickupCode&&(f.payload.callInvitation.unparkContent={pickupCode:parseInt(n.pickupCode,10)}),n.onBehalfOf&&(f.payload.callInvitation.onBehalfOf={id:n.onBehalfOf},n.onBehalfOfUserDisplayName&&(f.payload.callInvitation.onBehalfOf.displayName=n.onBehalfOfUserDisplayName)),n.callQueueContext&&(f.payload.callInvitation.callQueueContext=n.callQueueContext),n.scenario&&(f.payload.conversationRequest.scenario=n.scenario),n.alternateId&&(f.payload.participants.from.alternateId=n.alternateId),n.callingLineIdentity&&(f.payload.participants.from.callingLineIdentity=n.callingLineIdentity),n.invitationType===wa.INVITATION_TYPE.NUDGE&&(f.payload.participants.invitationType=n.invitationType),e.signalingAgentConfig.ecsEtag&&(f.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),n.clientEndpointDebugContent){f.payload.debugContent||(f.payload.debugContent={});try{f.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){xa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{f.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){xa(!1,`Failed to parse ${n.captchaContentJson}`)}return n.participationPreferences&&(f.payload.participationPreferences=n.participationPreferences),n.participantPropertyBag&&(f.payload.participantPropertyBag=n.participantPropertyBag),f}(this,n,r,e):Uu(this,n,r,e,i);this.signalingAgentConfig.enableCallEstablishmentTimeoutsForStartJoinCall&&this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(i)}),o),this.signalingSessionCallback.onTransferredCallAcceptance(i),e.endpointState&&(this.latestEndpointState=e.endpointState),this.http.sendPostRequest({url:s,requestName:t,operationType:"CallSetup",payload:l,causeId:i}).then((e=>{this.disposed||(this.processConversationServiceResponseHeaders(e,i),this.processConversationServiceResponse(e.response,i,0),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,i))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return;const n=Ka(e,this.signalingAgentConfig);if(this.logger.info(`[startOrJoinCall][${i}][${t}] error: ${je(e)} xhrError: ${je(n)}`),!this.disposed){if(this.isPromotingToRealtime)return void this.onPromotionCompleted(!0,n.error,i);this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:n.telemetryEndSubCode,endSubCode:n.error.subCode,resultCategories:n.error.resultCategories,resultDetail:n.error.phrase||"StartOrJoinCallFailure",causeId:i}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,n.error),this.dispose(n.error,i)}}))}processIncomingCallPayload(e,t){this.remoteUser=mo.fromWireParticipant(e.callNotification.from),this.participantManager.setLocalParticipantId(e.callNotification.to.participantId,t),e?(e.conversationInvitation&&(this.links[wa.LINKS.CONVERSATION_CONTROLLER]=e.conversationInvitation.conversationController,this.setMultiParty(e.conversationInvitation.isMultiParty,t),this.setIsHostless(!!e.conversationInvitation.isHostless,t)),e.callNotification&&(this.links[wa.LINKS.ATTACH]=e.callNotification.links?.attach,this.links[wa.LINKS.REDIRECT]=e.callNotification.links?.redirection,this.onBehalfOf=e.callNotification.onBehalfOf?.id,this.onBehalfOfUserDisplayName=e.callNotification.onBehalfOf?.displayName,this.callQueueContext=e.callNotification.callQueueContext,this.callPhoneLineType=e.callNotification.callPhoneLineType,this.callType=e.callNotification.callType,this.incomingCallCallerId=e.callNotification.from?.id,this.callUsesMixer=!!e.callNotification.mediaContent?.fromMixer,this.isRedirectAllowed=!!e.callNotification.redirectionProperties?.isRedirectAllowed,this.callQueueSupervisorContent=e.callNotification.callQueueSupervisorContent,this.bannerContent=e.callNotification.bannerContent),e.debugContent&&this.updateCorrelationId(e.debugContent.callId,t),e.callNotification.transferor&&(this.transferor=e.callNotification.transferor.details?e.callNotification.transferor.details.id:null),e.groupChat&&this.updateGroupChatIds(e.groupChat,t),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo)):this.logger.info(`[${t}][processIncomingCallPayload] empty incoming payload content`)}processAttachResponse(e,t,i){this.telemetryHelper.recordEvent("ProcessInitialOffer",{causeId:i}),this.links[wa.LINKS.MEDIA_ANSWER]=t.response.callInvitation.links.mediaAnswer,this.links[wa.LINKS.ACCEPT]=t.response.callInvitation.links.acceptance,this.links[wa.LINKS.REJECT]=t.response.callInvitation.links.callLeg,this.links[wa.LINKS.REDIRECT]=t.response.callInvitation.links.redirection,this.links[wa.LINKS.NEW_OFFER]=t.response.callInvitation.links.newOffer,this.signalingAgentConfig.sendProgressFromCC||this.sendProgress(t),this.remoteCaller=t.response.participants.from;const n=this.getInitialMediaOfferFromIncomingCallPayload()||t.response.callInvitation.mediaContent;this.telemetryHelper.setCallerType(this.getParticipantIdForOfferAnswer(n));const r=Ha(t.response.callInvitation.callModalities);this.telemetryHelper.addIncomingModalities(r),this.telemetryHelper.setOfferedModalities(n.blob,!0),this.callUsesMixer=n.fromMixer,this.isRedirectAllowed=!(!t.response.callInvitation.redirectionProperties||!t.response.callInvitation.redirectionProperties.isRedirectAllowed),this.signalingSessionCallback.onOffer({subject:e.conversationInvitation.subject,remoteParticipantId:this.getParticipantIdForOfferAnswer(n),remoteEndpointId:t.response.participants.from.endpointId,transferor:t.response.callInvitation.transferor,clientTransferContext:e.callNotification.transferContext,customHeaderContext:t.response.callInvitation.customContext,mediaTypes:r,mediaContent:n,renegotiation:!1,invitationData:t.response.callInvitation.invitationData,riskLevel:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.riskLevel,stirAttestation:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.stirAttestation,isRedirectAllowed:this.isRedirectAllowed},i)}sendProgress(e,t=Na()){this.logger.info(`[${t}][sendProgress]`),this.telemetryHelper.recordEvent("SendProgress",{causeId:t}),this.http.sendPostRequest({url:e.response.callInvitation.links.progress,requestName:Zo.SEND_CALL_PROGRESS.name,payload:Nu(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][sendProgress] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent("SendProgressFailed",{causeId:t,...i.error})}))}handleCallNotification(e){const t=Qa(e);if(this.logger.info(`[${t}][handleCallNotification]`),this.telemetryHelper.recordIncomingEvent("HandleCallNotification",e),!ja(e.url,ra.REPLACE))throw new Error(`[${t}][handleCallNotification]IncomingCallNotification should not be received in handleIncomingMsg`);this.telemetryHelper.recordIncomingEvent("HandleIncomingCallReplacement",e),this.logger.info(`[${t}][handleCallNotification]replacementCallNotification`),this.signalingSessionCallback&&this.signalingSessionCallback.onIncomingCallReplacement(e.body,t)}handleMediaAnswer(e){this.telemetryHelper.recordIncomingEvent(vo,e);const t=e.body,i=Qa(e);if(this.logger.info(`[${i}][handleMediaAnswer]`),this.mediaRenegotiationManager.isOutgoingRenegotiationInProgress())this.mediaRenegotiationManager.handleMediaAnswer(t,i);else if(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED);else if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING){if(Ja(e.headers,this.provisionalMediaAnswersSeenSoFar))return void this.logger.info(`[${i}][handleMediaAnswer] ignoring provisional answer retried by service`);t.mediaAnswer.sender&&(this.remoteUser=t.mediaAnswer.sender),this.resetCallEstablishmentTimeout(i),t.mediaAnswer.noRingBack||(this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,i));const n=t.mediaAnswer.mediaContent;this.signalingSessionCallback.onAnswer({provisional:!0,renegotiation:!1,remoteEndpointId:t.mediaAnswer.sender?t.mediaAnswer.sender.endpointId:La(),remoteParticipantId:this.getParticipantIdForOfferAnswer(n),mediaContent:n},i)}}async _sendCallAcceptanceAcknowledgement(e,t){this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][_sendCallAcceptanceAcknowledgement] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent(Io,{causeId:t,...i.error})}))}handleCallAcceptance(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleCallAcceptance",e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptance]enableQuickSendAcceptanceAck:\n ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?(this._sendCallAcceptanceAcknowledgement(e,t),this._processCallAcceptance(e,t)):(this._processCallAcceptance(e,t),this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][handleCallAcceptance] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent(Io,{causeId:t,...i.error})})))}handleCallAcceptanceSync(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleCallAcceptanceSync",e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptanceSync] enableQuickSendAcceptanceAck:\n ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?kd.defer(this._processCallAcceptance,e,t):this._processCallAcceptance(e,t);const i=ku(this).payload;return this.telemetryHelper.addNetworkOperationCompleted(Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,!0),i}getFakeRoster(e){const t=this.participantManager.getParticipantsToInitiateCallWith();let i;i=1===t.length?t[0].id:e.callAcceptance.acceptedBy.id;const n={id:i,displayName:e.callAcceptance.acceptedBy.id===i?e.callAcceptance.acceptedBy.displayName:"",languageId:e.callAcceptance.acceptedBy.languageId},r=e.callAcceptance.acceptedBy.endpointId;return{type:"MultiPartyEndpoint",participants:{[i]:{acceptedBy:e.callAcceptance.acceptedBy.id,details:n,endpoints:{[r]:{call:{},contentSharing:{},capabilities:e.callAcceptance.capabilities,participantId:e.callAcceptance.acceptedBy.participantId}}}}}}processCallAcceptance(e,t){this.logger.info(`[${t}][processCallAcceptance] ${je(e)}`),this.telemetryHelper.recordEvent("ProcessCallAcceptance",{causeId:t}),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t);let i=!1;e.callAcceptance.controllerName===wa.MISC.LOBBY_CALL_CONTROLLER&&(this.logger.info(`[${t}][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}),i=!0,this.telemetryHelper.recordEvent("AcceptanceUserInLobby",{causeId:t})),this.participantManager.localParticipant.isStaging=Fd(e.callAcceptance),this.signalingSessionCallback.onMeetingGroupDetailsUpdated(e.callAcceptance.meetingGroupDetails,t),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptance.callProperties?.isSharedLineAppearanceV2Activated),this.logger.info(`[${t}][processCallAcceptance] for localParticipant, isStaging is set to ${this.participantManager.localParticipant.isStaging}`);let n=this.mediaTypesToUse,r=La();e.callAcceptance.acceptedBy&&(this.remoteUser=mo.fromWireParticipant(e.callAcceptance.acceptedBy),r=e.callAcceptance.acceptedBy.endpointId),e.callAcceptance.acceptedCallModalities&&e.callAcceptance.acceptedCallModalities.length>0&&(n=e.callAcceptance.acceptedCallModalities);const s=e.callAcceptance.mediaContent;this.callUsesMixer=s.fromMixer;const a=Ha(n);this.telemetryHelper.addIncomingModalities(a),this.telemetryHelper.setAnsweredModalities(s.blob,!0),this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptance.links.mediaRenegotiation,this.links[wa.LINKS.TRANSFER]=e.callAcceptance.links.transfer,this.links[wa.LINKS.REPLACE]=e.callAcceptance.links.replacement,this.links[wa.LINKS.HANGUP]=e.callAcceptance.links.callLeg,this.links[wa.LINKS.KEEPALIVE]=e.callAcceptance.links.callLeg,this.links[wa.LINKS.PARK]=e.callAcceptance.links.hold,this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptance.links.updateMediaDescriptions,this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.callAcceptance.links.monitor,this.saveMediaControllerLinksIfAny(e.callAcceptance),this.scheduleKeepAlives(e.callAcceptance.callKeepAliveInterval);const o=this.getParticipantIdForOfferAnswer(s);this.signalingSessionCallback.onAnswer({provisional:!1,renegotiation:!1,remoteEndpointId:r,remoteParticipantId:o,callAcceptedByNGCVoicemail:o===wa.KNOWN_BOTS.VOICEMAIL_BOT_ID,mediaTypes:a,mediaContent:s},t),this.setRealTimeState(2,t),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,t),i&&this.signalingSessionCallback.onSelfParticipantUpdated(this.participantManager.localParticipant,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][processCallAcceptance] Updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t))}updateGroupChatIds(e,t){const i=this.groupId,n=this.threadId,r=this.teamsMessageId,s=this.backroomThreadId,a=this.streamThreadId,o=this.lobbyThreadId;this.groupId=e.groupId,this.threadId=e.threadId,this.teamsMessageId=e.messageId,this.backroomThreadId=e.backroomThreadId,this.streamThreadId=e.streamThreadId,this.lobbyThreadId=e.lobbyThreadId,this.groupId===i&&this.threadId===n&&this.teamsMessageId===r&&this.backroomThreadId===s&&this.streamThreadId===a&&this.lobbyThreadId===o||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},t)}handleCallEnd(e,t){let i=e.body.callEnd||e.body;const n=Qa(e);if(this.logger.info(`[${n}][handleCallEnd][content=${je(i)}]`),this.telemetryHelper.recordEvent(wo,{origin:e.origin,code:i?i.code:"unknown",subCode:i?i.subCode:"unknown",resultCategories:i?i.resultCategories:[],causeId:n}),this.signalingAgentConfig.enableConversationTypeUpdateOnCallEnd&&(this.conversationType=i?.conversationType||this.conversationType,this.signalingSessionCallback.onConversationTypeUpdated(this.conversationType,n)),this.fsmState!==wa.SIGNALING_FSM_STATE.IDLE)if(i.code===wa.CALL_END_CODE.CONFLICT&&this.multiParty&&i.conversationUrl?.Location)this.handleConversationResolutionConflict(i,n);else{this.disposing=!0,i.callControllerTransactionEnd&&(this.logger.info("handleCallEnd: using CC end details specified in CS end"),i=i.callControllerTransactionEnd),i.broadcastOperationFailure&&(this.logger.info("handleCallEnd: using broadcastOperationFailure end details specified in CS end"),i=i.broadcastOperationFailure);const e=i.code===wa.CALL_END_CODE.SUCCESS||i.code===wa.CALL_END_CODE.CANCEL||i.code===wa.CALL_END_CODE.REJECT;this.telemetryHelper.setTerminatingData({terminatingEnd:ad,resultDetail:i.phrase,resultValue:e?od:ld,endCode:i.code,endSubCode:i.subCode,resultCategories:i?i.resultCategories:[],causeId:n});const r={code:i.code,subCode:i.subCode,phrase:i.phrase,resultCategories:i.resultCategories,pickupCode:""},s=this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY;i.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:i.acceptedElsewhereBy.id,displayName:i.acceptedElsewhereBy.displayName}),i.unparkContent&&(i.unparkContent.CallParkAdditionalContext&&(this.parkAdditionalContextJson=JSON.stringify(i.unparkContent.CallParkAdditionalContext),this.serverHoldLocation=i.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),i.unparkContent.pickupCode&&(r.pickupCode=i.unparkContent.pickupCode));const a=this.signalingAgentConfig.enableSplitConversationEndUrl;a&&s===t?(this.logger.info("fsmstate = SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY or OUTGOING_FOR_ROSTER_ONLY"),this.onCallStatusChanged(wa.CALL_STATUS.REMOTE_TERMINATED,n,r),this.dispose(r,n)):a||(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(wa.CALL_STATUS.REMOTE_TERMINATED,n,r),this.dispose(r,n))}else this.logger.info(`[${n}][handleCallEnd] not handling incoming callEnd since fsmstate = SIGNALING_FSM_STATE.IDLE`)}handleConversationResolutionConflict(e,t){this.logger.info(`[${t}][handleConversationResolutionConflict]`);const i={...e,phrase:e.phrase||"Conflict Resolution Error"};if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY)this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.http.cancelRequestIfPending(Zo.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,t,void 0,i),this.subscribeToCall(e.conversationUrl.Location,e.correlationId,this.lastUsedJoinCallOptions?this.lastUsedJoinCallOptions.clientEndpointCapabilities:0,{meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,additionalEndpointProperties:this.lastUsedJoinCallOptions?.additionalEndpointProperties},t);else{this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const n={meetingData:this.meetingData,meetingPreferences:this.meetingPreferences};if(this.lastUsedJoinCallOptions){const e=this.lastUsedJoinCallOptions.scenario;n.muted=this.lastUsedJoinCallOptions.muted,n.scenario=`409Redirect${e||""}`,n.isPreheatOnly=this.lastUsedJoinCallOptions.isPreheatOnly,n.clientEndpointCapabilities=this.lastUsedJoinCallOptions.clientEndpointCapabilities,n.clientEndpointDebugContent=this.lastUsedJoinCallOptions.clientEndpointDebugContent,n.additionalEndpointProperties=this.lastUsedJoinCallOptions.additionalEndpointProperties}else n.scenario="409RedirectJoin";this.setInitialTelemetry("JoinCall",{correlationId:e.correlationId,causeId:t,conversationServiceUrl:e.conversationUrl.Location,joinCallOptions:n,offerGenerationTime:void 0}),this.http.cancelRequestIfPending(Zo.JOIN_CONVERSATION.name,t,void 0,i),this.http.cancelRequestIfPending(Zo.START_CALL.name,t,void 0,i),this.joinGivenConversation(e.conversationUrl.Location,e.correlationId,this.lastUsedOutgoingMediaContent,this.mediaTypesToUse,void 0,n,t)}}handleCallProgress(e){this.telemetryHelper.recordIncomingEvent("HandleCallProgress",e);const t=Qa(e);this.logger.info(`[${t}][handleCallProgress]`);const i=e.body.callProgress;this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING&&(this.telemetryHelper.setTimeToRingDuration(),this.resetCallEstablishmentTimeout(t),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,t),"forwarded"===i.status&&this.signalingSessionCallback.onCallForwarded({destinationType:i.forwardingDestinationType||"user"},t))}resetCallEstablishmentTimeout(e){const t=this.isOneToOnePSTNCall()?wa.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`resetCallEstablishmentTimeout: ${t}s`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(e)}),t)}handleMediaAcknowledgement(e){this.telemetryHelper.recordIncomingEvent("HandleMediaAck",e);const t=e.body,i=Qa(e);this.currentCallStatus!==wa.CALL_STATUS.CONNECTED?this.telemetryHelper.recordEvent("HandleMediaProvisionalAck",{causeId:i}):this.mediaRenegotiationManager.handleMediaAcknowledgment(t,i)}handleConversationUpdate(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleConversationUpdate]content=${je(t)}`),this.telemetryHelper.recordIncomingEvent("HandleConversationUpdate",e),this.processConversationServiceResponse(t,i,2)}endBroadcastMeeting(e){this.logger.info(`[${e}][endBroadcastMeeting]`),this.broadcastSession=null}handleLocalParticipantUpdate(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleLocalParticipantUpdate]content=${je(t)}`),this.telemetryHelper.recordIncomingEvent("HandleLocalParticipantUpdate",e),this.processLocalParticipantUpdateResponse(t,i)}handleAddModalityFailure(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddModalityFailure]`),this.telemetryHelper.recordIncomingEvent(Do,e),t.modalityFailure.contentSharing?this.contentSharingManager?.handleAddModalityFailure(t,i):t.modalityFailure.groupChat?this.signalingSessionCallback.onChatModalitySetupFailed({code:t.modalityFailure.groupChat.code,subCode:t.modalityFailure.groupChat.subCode,phrase:t.modalityFailure.groupChat.phrase,resultCategories:t.modalityFailure.groupChat.resultCategories},i):t.modalityFailure.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalityFailure(t,i)}handleAddModalitySuccess(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddModalitySuccess]`),this.telemetryHelper.recordIncomingEvent(Mo,e),t.modalitySuccess.contentSharing?this.contentSharingManager?.handleAddModalitySuccess(t,i):t.modalitySuccess.groupChat?this.logger.info(`[${i}][handleAddModalitySuccess] group modality ${je(t.modalitySuccess.groupChat)}`):t.modalitySuccess.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalitySuccess(t,i)}handleTransferRequested(e){const t=e.body.callTransfer,i=Qa(e);this.logger.info(`[${i}][handleTransferRequested]`),t.parkType?(this.telemetryHelper.recordIncomingEvent("HandleParkRequested",e,{type:t.parkType}),this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId)):"voicemail"===t.target.endpointType?(this.logger.info(`[${i}][handleTransferRequested] target endpointType = ${t.target.endpointType}`),this.telemetryHelper.recordIncomingEvent(Oo,e)):this.telemetryHelper.recordIncomingEvent(Oo,e),this.links[wa.LINKS.TRANSFER_ACCEPTANCE]=t.links.transferAcceptance,this.links[wa.LINKS.TRANSFER_COMPLETION]=t.links.transferCompletion,this.signalingSessionCallback.onTransferRequested?this.signalingSessionCallback.onTransferRequested(t,i):this.logger.info(`[${i}][handleTransferRequested] failed, no callback defined`)}handleTransferAcceptance(e){const t=Qa(e);this.logger.info(`[${t}][handleTransferAcceptance]`),this.telemetryHelper.recordIncomingEvent("WaitingForTransferCompletion",e),this.signalingSessionCallback.onTransferAccepted?this.signalingSessionCallback.onTransferAccepted(t):this.logger.info(`[${t}][handleTransferAcceptance]failed, no callback defined`)}handleTransferCompletion(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleTransferCompletion]`),t.sharedCorrelationId&&this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId),void 0!==t.unparkContent?.pickupCode&&(t.unparkContent.pickupCode=t.unparkContent.pickupCode.toString(),this.telemetryHelper.recordIncomingEvent("PickupCodeSet",e)),this.signalingSessionCallback.onTransferCompleted?(e.body.transferCompletion&&(0===e.body.transferCompletion.code?this.telemetryHelper.recordIncomingEvent(Ho,e):(this.logger.info(`[${i}][handleTransferCompletion]-1-code: ${t.transferCompletion.code}, message: ${je(e)}`),this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories}))),this.signalingSessionCallback.onTransferCompleted(t,i)):(e.body.transferCompletion&&(e.body.transferCompletion.code===wa.CALL_END_CODE.NETWORK_ERROR?this.telemetryHelper.recordIncomingEvent("WaitingForTransferCompletionFail",e):this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories})),this.logger.info(`[${i}][handleTransferCompletion]failed, no callback defined`))}handleRosterUpdate(e,t){const i=e.body,n=Qa(e);this.disposing||this.disposed?this.logger.info(`[${n}][handleRosterUpdate]failed=ignore call ending or ended`):this.internalHandleRosterUpdate(i,t,n)}handleNewMediaOffer(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleNewOffer",e);const i=e.body.mediaOfferReady.mediaContent;this.callUsesMixer=i.fromMixer,this.signalingSessionCallback.onNewOffer({mediaContent:i,renegotiation:!1},t)}internalHandleRosterUpdate(e,t,i){if(e&&"Delta"!==e.type&&"MultiPartyEndpoint"!==e.type)this.logger.warn(`[${i}][internalHandleRosterUpdate] roster.type=${e.type} is invalid`);else{this.logger.info(`[${i}][internalHandleRosterUpdate]`);try{this.participantManager.handleRosterUpdate(e,t,i),this.contentSharingManager?.handleIncomingContentSharingFromRoster(e,t,i)}catch(t){const n={code:wa.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:wa.CALL_END_SUB_CODE.ROSTER_HANDLING_INVALID_SERVICE_RESPONSE,phrase:t?.toString()};throw this.logger.info(`[${i}][internalHandleRosterUpdate] ${Ge(n)}`),this.telemetryHelper.recordRosterEvent(e,_o,i),n}}}scheduleKeepAlives(e){const t=.9*e*1e3;this.logger.info(`scheduleKeepAlives: every ${t} milliseconds`),this.keepAliveInterval=t,this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval)}scheduleConversationKeepAlive(){if(!this.conversationKeepAliveTimer&&!this.disposed){if(!this.conversationKeepAliveInterval){const e=function(e){const t=Math.floor(11*Math.random())+10;return Math.floor(e*(1-t/100))}(1e3*this.signalingAgentConfig.csaTimeoutConfiguration.conversationKeepAliveTimeoutSec);this.logger.info(`sendConversationKeepAlive: every ${e} milliseconds`),this.conversationKeepAliveInterval=e}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(e,t=Na()){if(this.disposed)return Promise.resolve();const i=this.logger.createChild(`[${t}][sendToUpdateConversationLinks]`,this.correlationId),n=e?function(e){Ua(e,"signalingSession cannot be null");const t={type:"Delta",rosterUpdate:Ra(e,na.CONV_ROSTER_UPDATE)};return{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},roster:t,links:$a(e,na)}}}(this):{},r=e?Zo.UPDATE_CONVERSATION_LINKS.name:Zo.SEND_CONVERSATION_KEEP_ALIVE.name,s=this.links[wa.LINKS.NOTIFICATION_LINKS];return i.info(`shouldUpdateUrl: ${e}, url: ${s}, payload: ${je(n)}`),s?(this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.http.sendPostRequest({url:s,payload:n,withoutTrouter:!0,requestName:r,causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.recordEvent("UpdateConversationLinksSuccess",{causeId:t}),this.processConversationServiceResponse(e.response,t,2))})).catch((e=>{const i=Ka(e,this.signalingAgentConfig),n=no(i.error.code);this.logger.info(`[${t}][updateConversationLinks] error: ${je(i)}, retryable: ${n}`),this.disposed||(this.telemetryHelper.recordEvent("UpdateConversationLinksFailed",{causeId:t,...i.error}),n?this.scheduleConversationKeepAlive():this.links[wa.LINKS.NOTIFICATION_LINKS]=null)}))):Promise.resolve()}sendToKeepAliveUrl(e,t=Na()){const i=this.logger.createChild(`[${t}][sendToKeepAliveUrl]`,this.correlationId);return i.info(`payload: ${je(e)}`),window.clearInterval(this.keepAliveTimer),this.disposed?Promise.resolve():(this.telemetryHelper.recordEvent("SendKeepAlive"),this.http.sendPostRequest({url:this.links[wa.LINKS.KEEPALIVE],payload:e,requestName:Zo.SEND_KEEP_ALIVE.name,withoutTrouter:!0,causeId:t}).then((()=>{this.restartKeepAliveInterval(t)})).catch((e=>{const n=Ka(e,this.signalingAgentConfig);i.info(`error: ${je(n)}`),this.restartKeepAliveInterval(t,!0,n.error)})))}handleCallEstablishmentTimeout(e,t,i){const n={code:wa.CALL_END_CODE.TIMEOUT,subCode:t||wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:i||wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT,resultCategories:[Xs]};this.isPromotingToRealtime?this.onPromotionCompleted(!0,n,e):(this.telemetryHelper.recordEvent("HandleCallEstablishmentTimeout"),this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,resultDetail:n.phrase,endCode:n.code,endSubCode:n.subCode,causeId:e,resultCategories:n.resultCategories}),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,n),this.dispose(n,e))}handleCallTransferTimeout(e,t){if(this.disposed)return void this.logger.info("Transfer: handleCallTransferTimeout ignored");const i={code:wa.CALL_END_CODE.TIMEOUT,phrase:wa.CALL_END_PHRASE.TRANSFER_COMPLETION_TIMEOUT};this.signalingSessionCallback.onTransferCompleted&&(!1===t?this.telemetryHelper.recordEvent(ko,{code:wa.CALL_END_CODE.TIMEOUT,subcode:wa.CALL_END_SUB_CODE.TRANSFER_COMPLETE_TIMEOUT,causeId:e}):!0===t&&this.telemetryHelper.recordEvent("WaitingForTransferAcceptanceFail",{causeId:e}),this.signalingSessionCallback.onTransferCompleted({transferCompletion:i},e))}checkCorrelationIdChange(e,t){if(e&&e.headers){const i=e.headers.get(wa.HEADERS.CORRELATION_ID);if(i&&i.length){const n=[ra.CONV_CONTENT_SHARING_UPDATE,ra.CONV_CONTENT_SHARING_END].some((t=>e.url&&ja(e.url,t)));this.correlationId===i||n||(this.logger.info(`[${t}]checkCorrelationIdChange:${this.correlationId} => ${i}`),this.telemetryHelper.addChangingCorrelationId(this.correlationId,i),this.updateCorrelationId(i,t))}}}getCommandUrlPresence(){let e=0;return this.links[wa.LINKS.MUTE]&&(e|=1),this.links[wa.LINKS.UNMUTE]&&(e|=2),e}getCallNotFoundTransactionEnd(){return{code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,subCode:0,phrase:wa.CALL_END_PHRASE.CALL_DOES_NOT_EXIST}}dispose(e,t){this.disposed||(this.logger.info(`[${t}][dispose] end reason ${je(e)}`),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(t).then((()=>{this.signalingAgent.onCallCompleted(this.sessionId,t),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(e,t),this.callOperationHandler.dispose("call ended",e,t),this.participantManager=null,this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=null,this.contentSharingManager?.dispose(e,t),this.contentSharingManager=null,this.telemetryHelper.dispose(),this.telemetryHelper=null,this.webRtcSignalingManager.dispose(),this.webRtcSignalingManager=null})))}},lh=class{constructor(e){this.endpointId=La(),this.signalingSessions={},this.clientSupportsGenericTokenAPI=!1,this.getNewSignalingSession=(e,t,i,n)=>{const r=Na();Ua(e,"selfParticipant should be a non null value"),Ua(t,"signalingSessionCallback should be a non null value");const s=i||La();Fa(s,"signalingSession id generated cannot be null or empty"),this.checkConfigChange(r);const a=function(e,t,i,n,r,s){return new oh(e,t,i,n,r,s)}(e,t,this.signalingAgentConfig,s,this,n),o=a.sessionId;return this.signalingSessions[o]=a,this.logger.info(`[${r}]Created new signalingSession with correlation ID ${s} and session ID ${o}`),a},this.resolvePotentialCallConflict=e=>{const t=Na();if(this.logger.info(`[${t}][resolvePotentialCallConflict]`),e.multiParty)return;const i=Object.values(this.signalingSessions).find((t=>this.isSessionInConflictingState(t,e)));if(!i)return;let n;if(n=e.isIncomingCall?this.getConflictingSessionToEnd(e,i):this.getConflictingSessionToEnd(i,e),!n)return;const r=n===e?i:e;return this.logger.info("Call conflict done.",` conflictingSession.correlationId=${i.correlationId}`,` conflictingSession.urlIdentifier=${i.urlIdentifier}`,` sessionToEnd.correlationId=${n.correlationId}`,` sessionToEnd.urlIdentifier=${n.urlIdentifier}`),n.telemetryHelper.setConflictingCallId(r.correlationId),n.telemetryHelper.recordEvent("ConflictedCall"),this.signalingAgentConfig.endConflictedCall?(this.endConflictedSession(n,t),n):void 0},this.handleIncomingNotification=e=>{if(Ua(e,"request should be a non null value"),this.logger.info(`handleIncomingNotification to : ${e.url}`),!e.body&&!e.rawBody)return this.logger.error("request has no body"),this.buildNotificationResponse(wa.HTTP_STATUS_CODES.BAD_REQUEST);let t=wa.HTTP_STATUS_CODES.OK;const i=function(e){const t=e.match(new RegExp(`/${function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(wa.URL_BASE.CALLAGENT)}/+([^/]+)`,"i"));return t?t[1]:null}(e.url);if(i){const n=this.signalingSessions.hasOwnProperty(i);if(this.logger.info(`Is session found:${n}`),n){const t=this.signalingSessions[i];if(e.headers=new Pa(e.headers),Za(e.headers))try{if(!Xa(e.headers))throw new Error("Unsupported encoding");const t=eo(e.rawBody),i=JSON.parse(t);e.body=i}catch(e){return t.telemetryHelper.recordEvent("TrouterDecodePayloadFailure"),this.buildNotificationResponse(wa.HTTP_STATUS_CODES.BAD_REQUEST)}if(t.canHandleIncomingMsgSync(e))return t.handleIncomingMsgSync(e);window.setTimeout((()=>{if(this.signalingSessions.hasOwnProperty(i)){const t=this.signalingSessions[i];t.handleIncomingMsgAsync(e).catch((e=>{t&&t.telemetryHelper&&t.telemetryHelper.recordEvent("FailedToHandleTrouterMessage"),this.logger.error(`handling IncomingMsg failed with error: ${e}`)}))}}),0)}else this.logger.info(`Incoming message for session ID ${i}, but session was not found!`),t=wa.HTTP_STATUS_CODES.NOT_FOUND}else this.logger.error(`Could not retrieve session ID from Url path. Path = ${e.url}`),t=wa.HTTP_STATUS_CODES.BAD_REQUEST;const n=this.buildNotificationResponse(t);return this.logger.info(`Result code:${je(n)}`),n},this.onCallCompleted=(e,t)=>{this.signalingSessions.hasOwnProperty(e)?(delete this.signalingSessions[e],this.logger.info(`[${t}][onCallCompleted] Session ID ${e} found. Deleted from signalingSession table`)):this.logger.info(`[${t}][onCallCompleted] Session ID ${e} not found. Could not delete from signalingSession table`)},this.applyAuthTokenCacheConfig=e=>{this.signalingAgentConfig.enableTokenCache?(this.authTokenManager.setTokenCaching(!0,e),this.signalingAgentConfig.enableTokenPrefetch&&this.authTokenManager.getToken(e).then((()=>{this.logger.info(`[${e}] token prefetch success`)})).catch((t=>{this.logger.info(`[${e}] token prefetch failure, error=${je(t)}`)}))):this.authTokenManager.setTokenCaching(!1,e),this.signalingAgentConfig.enableTokenCacheForGenericTokenAPI?this.authTokenManager.setTokenCachingForGenericTokenAPI(!0,e):this.authTokenManager.setTokenCachingForGenericTokenAPI(!1,e)},this.endConflictedSession=(e,t)=>{this.logger.info("Call conflict, ending signalingSession with callId=",e.correlationId,"urlIdentifier=",e.urlIdentifier),e.endAsync({code:wa.CALL_END_CODE.CONFLICT,subCode:wa.CALL_END_SUB_CODE.CONFLICT_IN_NG,phrase:wa.CALL_END_PHRASE.CONFLICT},{forEveryone:!1,causeId:t})},this.getConflictingSessionToEnd=(e,t)=>{if(!ka(e.incomingCallCallerId)||!ka(t.participantManager.localParticipant.id))return;const i=Oa(e.incomingCallCallerId),n=t.participantManager.getParticipantsToInitiateCallWith();if(0===n.length)return;const r=Oa(n[0].id),s=Oa(t.participantManager.localParticipant.id);return r===i?s>i?e:t:void 0},this.isSessionInConflictingState=(e,t)=>{if(!e)return this.logger.info("Call conflict, ignore, session already disposed"),!1;const i=[wa.CALL_STATUS.IDLE,wa.CALL_STATUS.CONNECTING,wa.CALL_STATUS.RINGING];return!e.multiParty&&i.indexOf(e.getCallStatus())>-1&&t.isIncomingCall!==e.isIncomingCall},this.buildNotificationResponse=(e,t)=>this.signalingAgentConfig.supportsSynchronousTrouterResponse?{resultCode:e,responseBody:t}:e,wd(e),this.signalingAgentConfig=e,this.logger=e.logger.createChild("SignalingAgent"),Ua(e,"signalingAgentConfig should be a non null value"),this.logger.info(e.isWebRtcEnabled?"webRTC enabled":"ORTC enabled");const t={aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds};this.authTokenManager=((e,t,i,n)=>new Md(e,t,i,n))(this.logger,e.skypeToken,t,e.telemetryManager),this.applyAuthTokenCacheConfig(Na()),Pa.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateSignalingAgentConfig(e){const t=Na(),i=JSON.stringify(e,((e,t)=>e?String(t):t));this.logger.info(`[${t}] updateSignalingAgentConfig, SignalingAgentConfig: ${i}`),this.logger.info(`[${t}] ecsEtag=${e.ecsEtag}`),wd(e),this.updatedSignalingAgentConfig=e,this.authTokenManager?.updateTokenSettings({aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds}),Pa.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateUrls(e,t,i){this.logger.info(`updateUrls: conversationServiceUrl: ${e}, uploadLogRequestUrl: ${t}, enforceUrls: ${i}`),this.updatedSignalingAgentConfig=this.updatedSignalingAgentConfig||this.signalingAgentConfig,i||!this.updatedSignalingAgentConfig.isConversationServiceUrlFromEcs?this.updatedSignalingAgentConfig.conversationServiceUrl=e||this.updatedSignalingAgentConfig.conversationServiceUrl:this.updatedSignalingAgentConfig.conversationServiceUrl=this.updatedSignalingAgentConfig.conversationServiceUrl||e,i||!this.updatedSignalingAgentConfig.isUploadLogRequestUrlFromEcs?this.updatedSignalingAgentConfig.uploadLogRequestUrl=t||this.updatedSignalingAgentConfig.uploadLogRequestUrl:this.updatedSignalingAgentConfig.uploadLogRequestUrl=this.updatedSignalingAgentConfig.uploadLogRequestUrl||t}update(e){this.logger.info(`update accountConfiguration ${JSON.stringify(e)}`),e&&e.clientSupportsGenericTokenAPI!==this.clientSupportsGenericTokenAPI&&(this.clientSupportsGenericTokenAPI=e.clientSupportsGenericTokenAPI,this.authTokenManager.updateTokenSettings({clientSupportsGenericTokenAPI:this.clientSupportsGenericTokenAPI})),this.accountConfig=e}sendPushAsync(e,t,i,n,r=Na()){const s=new Dd(this.signalingAgentConfig.piiScrubber),a=`sendPush[local participant mri = ${s.scrubMriOrOmit(e)}][recipientList = ${s.scrubMriOrOmit(t)}][headers = ${i})][causeId = ${r}]`;if(!e?.id)return this.logger.info(`${a} Empty localParticipantId`),Promise.reject("invalid localParticipantId");if(!t||0===t.length||t.every((e=>e&&""===e.id)))return this.logger.info(`${a} Empty recipientList`),Promise.reject("invalid recipientList");if(!i)return this.logger.info(`${a} Empty headers`),Promise.reject("invalid headers");if(!n||null===Wa(n))return this.logger.info(`${a} Invalid body.`),Promise.reject("invalid body");const o={...Wa(n),To:Array.from(t,(e=>e.id)),From:e.id},l=new Pa(i);l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CORRELATION_ID)||l.set(wa.HEADERS.CORRELATION_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.MESSAGE_ID)||l.set(wa.HEADERS.MESSAGE_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.PARTICIPANT_ID)||l.set(wa.HEADERS.PARTICIPANT_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CONTENT_TYPE)||l.set(wa.HEADERS.CONTENT_TYPE,"application/json"),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CLIENT_USER_AGENT)&&l.set(wa.HEADERS.CLIENT_USER_AGENT,l.get(wa.HEADERS.CLIENT_USER_AGENT)+"/TsCallingVersion=2025.07.01.15/Ovb=8962f6ae8324f6a345d7997ae8f276ff81198956");const c=this.signalingAgentConfig.httpRequestDispatcher.getRequestOptions("POST",l?.getAll(),JSON.stringify(o),3e4);return c.useFetch=this.signalingAgentConfig.enableFetchApi,new Promise(((e,t)=>{this.signalingAgentConfig.httpRequestDispatcher.postAsync(this.signalingAgentConfig.uploadLogRequestUrl||wa.URL_DEFAULTS.UPLOAD_LOG_URL,c).then((()=>{e()})).catch((e=>{t(e)}))}))}getSignalingSession(e){for(const t of Object.keys(this.signalingSessions)){const i=this.signalingSessions[t];if(i.correlationId===e)return i}return null}updateToken(e,t,i,n,r){this.authTokenManager.updateToken(e,t,i,n,r)}setTokenRequiredCallBack(e){this.authTokenManager.setTokenRequiredCallBack(e)}resetAuthTokenManager(){this.setTokenRequiredCallBack(null),this.authTokenManager.setDisableTimerFlag(!0),this.authTokenManager.dispose()}checkConfigChange(e){this.updatedSignalingAgentConfig&&this.updatedSignalingAgentConfig!==this.signalingAgentConfig&&(this.signalingAgentConfig=this.updatedSignalingAgentConfig,this.updatedSignalingAgentConfig=null,this.applyAuthTokenCacheConfig(e))}},ch=/;aliases=.*$/i,dh="8:";function uh(e){return e?e.replace(ch,""):e}function hh(e,t){let i=e;return t&&(i+=";aliases=2:"+t),i}var gh=(e,t)=>t&&void 0!==t.phase&&!!e[t.phase],ph=(e,t)=>t&&void 0!==t.phase&&t.phase===e;function mh(e){const t={},i=e=>{t[e]={status:"Pending"}},n=(e,i)=>{t[e].t=i,delete t[e].status},r=(e,i,n)=>{t[e].status="Failed",t[e].t=i,t[e].reason=je(n)};return{execute:async(s,a)=>{const o=e.createChild(`[phase=${s}]`);i(s),o.info("started");const l=(new Date).getTime();try{const e=await a(),t=+new Date-l;return o.logSuccess(`done, time=${t}`),n(s,t),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${je(e)}`),r(s,i,e),{phase:s,error:e,phases:t}}},executeSync:(s,a)=>{const o=e.createChild(`[phase=${s}]`);o.info("started"),i(s);const l=(new Date).getTime();try{const e=a(),t=+new Date-l;return n(s,t),o.logSuccess(`done, time=${t}`),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${je(e)}`),r(s,i,e),{phase:s,error:e,phases:t}}},getTelemetryData:()=>t}}function fh(e,t){return-1!==t.indexOf(e)}var vh,Sh,yh,Ch={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:[]};(e=>{let t;var i;let n;var r;let s;var a;let o;var l;(i=t=e.VideoEffectType||(e.VideoEffectType={})).Off="off",i.BackgroundBlur="blur",i.BackgroundReplacement="replacement",i.PresenterMode="presenterMode",i.None="none",(r=n=e.PowerPreference||(e.PowerPreference={})).Default="default",r.HighPerformance="high-performance",r.LowPower="low-power",(a=s=e.ProcessorType||(e.ProcessorType={})).Wasm="Wasm",a.Webgl2="Webgl2",(l=o=e.EffectQualityChangeReason||(e.EffectQualityChangeReason={}))[l.ExternalParam=0]="ExternalParam",l[l.Performance=1]="Performance",l[l.RendererSize=2]="RendererSize"})(vh||(vh={})),(e=>{let t;var i;let n;var r;let s;var a;let o;var l;let c;var d;(i=t=e.CallType||(e.CallType={}))[i.P2P=0]="P2P",i[i.Conference=1]="Conference",i[i.PSTN=2]="PSTN",i[i.BroadcastingConf=3]="BroadcastingConf",(r=n=e.AudioUsageMode||(e.AudioUsageMode={}))[r.Default=0]="Default",r[r.LongRangeSpeaker=1]="LongRangeSpeaker",r[r.Auditorium=2]="Auditorium",(a=s=e.AecPerfProfile||(e.AecPerfProfile={}))[a.Normal=0]="Normal",a[a.Soc=1]="Soc",a[a.Mobile=2]="Mobile",a[a.NoisyTimestamps=3]="NoisyTimestamps",(l=o=e.VqeMode||(e.VqeMode={}))[l.Off=0]="Off",l[l.SkypeNS=1]="SkypeNS",l[l.SkypeAEC=2]="SkypeAEC",l[l.SkypeVQE=3]="SkypeVQE",l[l.DeepNS=4]="DeepNS",l[l.DeepVQE=5]="DeepVQE",(d=c=e.AudioEffectType||(e.AudioEffectType={})).Off="Off",d.NoiseSuppressionDeep="Deep NS",d.NoiseSuppressionClassic="Classic NS",d.EchoCancellationClassic="Classic AEC",d.VoiceQualityEnhancementClassic="Classic VQE",d.VoiceQualityEnhancementDeep="Deep VQE"})(Sh||(Sh={})),(e=>{let t;var i;let n;var r;(i=t=e.FrameType||(e.FrameType={}))[i.None=0]="None",i[i.Software=1]="Software",i[i.Hardware=2]="Hardware",(r=n=e.LogLevel||(e.LogLevel={}))[r.Default=0]="Default",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warning=3]="Warning",r[r.Error=4]="Error"})(yh||(yh={}));var Th=Z,Eh=(e=>(e[e.CallStateChanged=0]="CallStateChanged",e[e.TrouterStateChanged=1]="TrouterStateChanged",e[e.MultiPartyModeSet=2]="MultiPartyModeSet",e[e.MediaRetargetSucceeded=3]="MediaRetargetSucceeded",e[e.MediaRetargetFailed=4]="MediaRetargetFailed",e))(Eh||{}),bh=(e=>(e[e.StartModality=0]="StartModality",e[e.StopModality=1]="StopModality",e[e.StreamStateChanged=2]="StreamStateChanged",e[e.NegotiationStateChanged=3]="NegotiationStateChanged",e))(bh||{}),_h=(e=>(e[e.SelectSource=0]="SelectSource",e[e.AttachSource=1]="AttachSource",e[e.DetachSource=2]="DetachSource",e))(_h||{}),Ih=(e=>(e[e.Available=0]="Available",e[e.Subscribe=1]="Subscribe",e[e.Subscribed=2]="Subscribed",e[e.Unsubscribe=3]="Unsubscribe",e[e.Unsubscribed=4]="Unsubscribed",e[e.RenderingStarted=5]="RenderingStarted",e[e.RenderingStopped=6]="RenderingStopped",e))(Ih||{}),wh=class{};wh.agentEnvironmentId="agent_environment_id",wh.correlationId="CorrelationId",wh.participantId="participant_id",wh.displayName="display_name",wh.tenantId="TenantId",wh.userHexCID="UserHexCID",wh.acsResourceId="AcsResourceId",wh.endpointId="endpoint_id",wh.mediaLegId="media_leg_id",wh.webMediaConfigIds="web_media_config_ids",wh.tsCallingVersion="ts_calling_version",wh.rpcSessionId="rpc_session_id";var Ah=class{};Ah.diagnostics="MediaDiagnostic",Ah.qoeStats="QoE",Ah.webrtcSession="webrtc_session",Ah.webrtcSessionInitial="webrtc_session_initial",Ah.realtimeTelemetry="realtimetelemetry",Ah.webrtcMediaSession="webrtc_call_session",Ah.mediaSession="pluginless_modality_session",Ah.callSession="pluginless_call_session";var Ph=class{constructor(e){this.eventName=e,this.ended=!1,this.events=[]}setLocalUserId(e){this.localUserId=e}start(){this.ended||(this.startTime=Date.now())}end(e=0){this.ended||(this.ended=!0,this.resultCode=e)}asStatsRecord(e={}){if((0,Th.isEmpty)(this.events))return null;const t=(0,Th.uniqBy)(this.events,(e=>JSON.stringify(e))).map((e=>{const t={[e.type]:e.timestamp-this.startTime};return(0,Th.isEmpty)(e.data)||(t.data=e.data),t}));return{name:this.eventName,record:(0,Th.assign)({LocalUser:this.localUserId,ResultCode:String(this.resultCode),EventTimestampBag:JSON.stringify({eventStart:this.startTime,events:t})},e)}}add(e){!this.ended&&e.type&&((0,Th.isUndefined)(this.startTime)&&(this.startTime=Date.now()),(0,Th.isUndefined)(e.timestamp)&&(e.timestamp=Date.now()),this.events.push(e))}},Rh=class e extends Ph{constructor(){super(Ah.callSession)}callStateChanged(t){super.add({type:Eh[0],data:e.callStateToString[t]||t})}event(e){super.add({type:Eh[e]})}};Rh.callStateToString={0:"None",1:"Notified",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",6:"Disconnecting",7:"Disconnected",8:"Observing",10:"Lobby"};var Mh=Rh,Dh=class e extends Ph{constructor(t,i){super(Ah.mediaSession),this.mediaType=t,this.mediaDirection=i,this.streamDirection=e.mediaDirectionToStream[this.mediaDirection]}addEvent(e,t){super.add({type:e,data:t})}lifecycle(e){this.addEvent(bh[e])}streamStateChanged(t,i=this.streamDirection){const n=bh[2];this.addEvent(n,{state:e.streamStateToString[t],direction:e.streamDirectionToString[i]})}negotiationStateChanged(t,i,n=this.streamDirection){const r=bh[3];this.addEvent(r,{state:e.negotiationStateToString[t],reason:i})}asStatsRecord(t={}){return super.asStatsRecord((0,Th.assign)({MediaType:e.mediaTypeToString[this.mediaType],Role:e.mediaDirectionToRole[this.mediaDirection]},t))}};Dh.negotiationStateToString={started:"NegotiationStarted",rejected:"NegotiationRejected",completed:"NegotiationCompleted"},Dh.streamStateToString={created:"StreamCreated",started:"StreamStarted",active:"StreamActive",inactive:"StreamInactive",stopped:"StreamStopped",removed:"StreamRemoved",failed:"StreamFailed",cancelled:"StreamCancelled"},Dh.streamDirectionToString={send:"Send",receive:"Receive"},Dh.mediaTypeToString={0:"Audio",1:"Video",2:"ScreenShare",3:"Data"},Dh.mediaDirectionToRole={1:"Receiver",2:"Sender",4:"Bidirectional"},Dh.mediaDirectionToStream={1:"receive",2:"send"};var kh=Dh,Oh=class extends kh{constructor(){super(0,4)}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}},Nh=class extends kh{constructor(e){super(e,2),this.mediaType=e}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}event(e){super.addEvent(_h[e])}},Lh=class extends kh{constructor(e,t){super(e,1),this.mediaType=e,this.remoteParticipantId=t,this.rendererCounter=0}newRendererId(){return this.rendererCounter+=1,String(this.rendererCounter)}event(e,t,i){super.addEvent(Ih[e],(0,Th.isUndefined)(i)?{rendererId:t}:{rendererId:t,sourceId:i})}asStatsRecord(){return super.asStatsRecord({TargetUser:this.remoteParticipantId})}},xh=class{constructor(){this.allStats=[],this.ended=!1}setLocalUserId(e){this.localUserId=e}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(e,t){let i=this.renderingStats[t];return i||(i=this.renderingStats[t]=this.receive(e,t)),i}startCall(){return this.callStats?this.callStats:(this.callStats=new Mh,this.callStats.start(),this.addStats(this.callStats))}endCall(e=0){this.ended=!0,this.call.end(e),this.allStats.forEach((e=>e.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(e){let t;switch(e){case 0:t=this.audioStats=new Oh;break;case 1:t=this.videoStats=new Nh(e);break;case 2:t=this.sharingStats=new Nh(e)}return this.addStats(t)}receive(e,t){const i=new Lh(e,t);return i.start(),this.addStats(i)}buildStatsRecords(){return this.allStats.map((e=>e.asStatsRecord())).filter((e=>!!e))}addStats(e){return this.ended||(this.allStats.push(e),e.setLocalUserId(this.localUserId)),e}},Fh=class e{constructor(){this.startTime=Date.now(),this.localStats=new xh,this.tsCallingVersion="2025.07.01.15"}setRpcSessionId(e){this.rpcSessionId=e}setCallId(e){this.callId=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setParticipantId(e){this.participantId=e}setDisplayName(e){this.displayName=e}setEndpointId(e){this.endpointId=e}setMediaLegId(e){this.mediaLegId=e}setMediaStats(e){this.mediaStats=e}setAcsResourceId(e){this.acsResourceId=e}appendDataChannelInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.DataHandlers=e)}appendSharingControlInfo(e){this.mediaStats?.data&&(this.mediaStats.data.SharingControlEnabled=e?"true":"false")}appendMediaControlPlaneInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.MediaControlPlane=e)}appendTerminationInfo(e,t){this.mediaStats?.data&&(this.mediaStats.data.TerminatedReason=`${e}`,this.mediaStats.data.TerminatedState=`${t}`)}appendPictureInPictureInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.PictureInPicture=e)}appendCallDeviceManagerInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.CallDeviceManager=e)}async buildVDItelemetryReport(e){const{transport:t,rpc:i,rpcRemote:n,transportRemote:r}=await e.getStats(this.startTime);return{CallId:this.callId,ParticipantId:this.participantId,Transport:JSON.stringify(t),Rpc:JSON.stringify(i),Rpc_Remote:JSON.stringify(n),Transport_Remote:JSON.stringify(r)}}buildFromMediaStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,Ah.webrtcSession)]:[]}buildShortCallEvent(e){const t={};return t[wh.correlationId]=this.callId||"",t[wh.participantId]=this.participantId||"",t[wh.displayName]=new Re(this.displayName||"",1),t[wh.tenantId]=this.tenantId||"",t[wh.tsCallingVersion]=this.tsCallingVersion||"",t[wh.rpcSessionId]=this.rpcSessionId||"",t.metrics_TerminationReason_code=new Re(e.data.metrics.TerminationReason_code,0),t.metrics_TerminationReason_subCode=new Re(e.data.metrics.TerminationReason_subCode,0),t.metrics_eventType=new Re(e.eventType,0),[{eventName:Ah.webrtcMediaSession,props:this.buildProps(e.data,null,t)}]}buildMediaTelemetry(){if(!this.mediaStats)return;const e=this.buildEvent(this.mediaStats.data,null).props,t={};return Object.keys(e).forEach((i=>{void 0===e[i].piiKind?t[i]=e[i]:t[i]=e[i].value})),t}buildMidCallTelemetry(e){if(!this.mediaStats)return[];const t=this.buildEvent(this.mediaStats.data,Ah.webrtcSession),i=t.props,n=e.reduce(((e,t)=>(i[t]&&(e[t]=i[t]),e)),{});return[{eventName:t.eventName,props:n}]}buildFromCallSetupStats(e){return"WebRtcMediaStats"===this.mediaStats?.type?(this.mediaStats.data.trouterUrl=e,[this.buildEvent(this.mediaStats.data,Ah.webrtcSessionInitial)]):[]}buildFromLocalStats(){return this.localStats.buildStatsRecords().map((e=>this.buildEvent(e.record,e.name)))}buildEvent(t,i){const n={};return n[wh.agentEnvironmentId]=e.agentEnvironmentId,n[wh.correlationId]=this.callId||"",n[wh.tenantId]=this.tenantId||"",n[wh.userHexCID]=this.userHexCID||"",n[wh.participantId]=this.participantId||"",n[wh.displayName]=new Re(this.displayName||"",1),n[wh.endpointId]=this.endpointId||"",n[wh.mediaLegId]=this.mediaLegId||"",n[wh.webMediaConfigIds]=this.webMediaConfigIds||"",n[wh.tsCallingVersion]=this.tsCallingVersion||"",n[wh.acsResourceId]=this.acsResourceId||"",n[wh.rpcSessionId]=this.rpcSessionId||"",{eventName:i,props:this.buildProps(t,null,n)}}normalizeKey(e){return e.replace(/[^a-zA-Z0-9._]/g,"_")}buildProps(e,t,i){return Object.keys(e).forEach((n=>{const r=this.normalizeKey(n),s=t?`${t}_${r}`:r,a=e[n];if((0,Th.isString)(a))i[s]=this.getPiiAwareValue(n,a);else if((0,Th.isArray)(a)){if(a.length>0){const e=a,t=e.map((e=>e.value)).toString();i[s]=new Re(t,e[0].type)}}else if((0,Th.isObject)(a))if(a.__VALUE__){const e=a;(0,Th.isBoolean)(e.value)&&(e.value=e.value?"true":"false"),i[s]=new Re(e.value,e.type)}else this.buildProps(a,s,i)})),i}getPiiAwareValue(t,i){return e.piiProps.hasOwnProperty(t)?new Re(i,e.piiProps[t]):i}build(){return(0,Th.flatten)([this.buildFromMediaStats(),this.buildFromLocalStats()])}};Fh.agentEnvironmentId=mi(),Fh.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,[wh.displayName]:1};var Uh=Fh,Bh=Z;function Vh(e){return e?$h(e.code,e.subCode):0}function Hh(e,t){const i={clientVersion:e.clientVersion,participantId:e.participantId,endpointId:e.endpointId,endpointType:e.endpointType,endpointMetadata:e.endpointMetadata,originalId:e.originalId,capabilities:e.capabilities,clientEndpointCapabilities:e.clientEndpointCapabilities,mappedTo:e.mappedTo,meetingGroupDetails:e.meetingGroupDetails,endpointMeetingRoles:e.endpointMeetingRoles};return e.mediaStreams&&(i.mediaStreams=e.mediaStreams),e.appliedInteractivityLevel&&(i.appliedInteractivityLevel=e.appliedInteractivityLevel),e.deviceType&&(i.deviceType=e.deviceType),e.streamInformation&&32&t&&(i.streamInformation=e.streamInformation),e.propertyBag&&(i.propertyBag=e.propertyBag),e.negotiationTag&&(i.negotiationTag=e.negotiationTag),i}function $h(e,t=null){if(0===e)switch(t){case 5e3:case 5300:return 44;case 5854:return 55;case 5855:return 56;default:return 1}if(null!==t&&t>=2e5&&t<=299999){const e=t-2e5;return Fs[e]?Fs[e]:0}return null!==t&&t>=4e5&&t<=499999?Us[e]?Us[e]:43:403===e?10005===t?64:5448===t?62:5723===t?66:5354===t?67:5810===t?68:10193===t?70:5724===t?71:8:412===e&&5204===t?63:503===e?800100===t?69:48:500===e?7:413===e?5807===t?73:59:xs[e]?xs[e]:e}function jh(e){if(1===e)return 0;const t=Object.keys(xs).filter((t=>xs[t]===e));if(t.length>=1)for(const i of t){const t=parseInt(i);if(t&&xs[t]===e)return t}return Ds}function Gh(e,t){if(void 0!==t&&3!==t&&1!==t)return{mediaType:e,isDisabled:0===t,label:Od(e)}}function qh(e){if(e.sendMediaModalities)return e;const t={mediaStates:[]};let i=Gh(0,e.audioDirection?e.audioDirection:4);return i&&t.mediaStates.push(i),i=Gh(1,e.withVideo?4:e.videoDirection),i&&t.mediaStates.push(i),i=Gh(2,e.screenshareDirection?e.screenshareDirection:1),i&&t.mediaStates.push(i),e.sendMediaModalities=t,e}function zh(e){const t=function(e){if("mri"===e)return"mri";throw"Unknown RedirectionTargetIdType"}(e.type),i=function(e){switch(e){case"voicemail":return"voicemail";case"default":return"default";default:throw"Unknown RedirectionEndpointType"}}(e.endpointType);return{type:t,id:e.id,endpointType:i}}var Wh=class{constructor(e){this.mediaStateConfiguration=e}isDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!!t&&!!t.isDisabled}return!1}isInactiveOrDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!t||!!t.isDisabled}return!1}isSending(e){return!!this.mediaStateConfiguration?.mediaStates&&!!this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e&&!t.isDisabled))}disableModality(e){this.setModality(e,!0)}enableModality(e){this.setModality(e,!1)}removeModality(e){this.mediaStateConfiguration?.mediaStates&&(0,Bh.remove)(this.mediaStateConfiguration.mediaStates,(t=>t.mediaType===e))}setCallAcceptOptions(e){const t=this.isDisabled(1),i=this.isDisabled(2),n=this.isSending(3);if(e.sendMediaModalities)this.mediaStateConfiguration=e.sendMediaModalities;else{void 0===e.answerMediaType&&(e.answerMediaType=e.withVideo?1:0);const t={mediaStates:[]};switch(e.answerMediaType){case 0:t.mediaStates.push(Gh(0,4));break;case 1:t.mediaStates.push(Gh(0,4)),t.mediaStates.push(Gh(1,4));break;case 2:t.mediaStates.push(Gh(1,0))}this.mediaStateConfiguration=t}t&&this.setModality(1,!0),i&&this.setModality(2,!0),n&&this.setModality(3,!1),e.sendMediaModalities=this.mediaStateConfiguration}setModality(e,t){if(this.mediaStateConfiguration?.mediaStates){const i=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));i?i.isDisabled=t:this.mediaStateConfiguration.mediaStates.push({mediaType:e,isDisabled:t,label:Od(e)})}}};function Kh(e){return e||!1===e||""===e||0===e}function Jh(e){switch(e){case 0:return"Audio";case 1:return"Video";case 2:return"ScreenShare"}throw new Error("MediaType required")}function Yh(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2}throw new Error("MediaType required")}var Qh={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"},Zh={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"},Xh=class{constructor(e,t){this.mediaSession=e,this.signalingSession=t,this.operationNames=Qh,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(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_STARTED),this.mediaSession.processOfferAsync(e,t).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_ENDED),e)))}createAnswerAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_STARTED),this.mediaSession.createAnswerAsync(e,t).then((t=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_ENDED),e||(this.operationNames=Zh),t)))}createOfferAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_STARTED),this.mediaSession.createOfferAsync(e,t).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_ENDED),e)))}processAnswerAsync(e,t,i,n=!1){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_STARTED),this.mediaSession.processAnswerAsync(e,t,i,n).then((()=>{this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_ENDED),this.operationNames=Zh}))}completeNegotiationAsync(e){return this.mediaSession.completeNegotiationAsync(e).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps("NegotiationCompleted"),e)))}sendDtmf(e){return this.mediaSession.sendDtmf?this.mediaSession.sendDtmf(e):Promise.reject("Not Implemented")}reconnectAsync(e,t=!1,i){return this.mediaSession.reconnectAsync(e,t,i)}completeEscalationAsync(e){return this.mediaSession.completeEscalationAsync(e)}rejectEscalationAsync(e,t){return this.mediaSession.rejectEscalationAsync(e,t)}getAcceptedTypes(){return this.mediaSession.getAcceptedTypes()}getLocalMediaTrackId(e){return this.mediaSession.getLocalMediaTrackId?this.mediaSession.getLocalMediaTrackId(e):null}getAudioSenderStats(){return this.mediaSession.getAudioSenderStats()}processNotification(e,t){this.mediaSession.processNotification(e,t)}};function eg(e,t,i){if(void 0===t?.serverMuteVersion||void 0===i?.serverMuteVersion||i.serverMuteVersion>=t.serverMuteVersion)return;const n=i&&i.mediaStreams,r=n&&n.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),s=t&&t.mediaStreams,a=s&&s.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));r&&r.length&&(i.serverMuteVersion=t.serverMuteVersion,r[0].serverMuted=a[0].serverMuted,e.info(`handleServerMutedVersion: patching server muted state in audio streams updated:${JSON.stringify(r[0])} as we encountered stale muteServerVersion. Updated to ${t.serverMuteVersion}`))}function tg(e,t,i,n){if("success"!==i.reason||void 0===t||i.serverMuteVersion<=t.serverMuteVersion)return e.info(`handleMuteUnmuteParticipantInfo: ignoring updating since we encountered invalid state: ${i.reason} serverMuteVersion: ${i.serverMuteVersion}`),!1;const r=t&&t.mediaStreams,s=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));return!!s&&(s[0].serverMuted=n,t.serverMuteVersion=i.serverMuteVersion,e.info(`handleMuteUnmuteParticipantInfo: updating since we encountered valid state serverMuteVersion: ${i.serverMuteVersion} to: ${n} streams: ${s[0].sourceId}`),!0)}var ig=Q;function ng(e,t,i,n){i?.forEach((i=>{e[i]&&(t[i]=n(e[i]))}))}function rg(e){return`id=${ig.pii.Mri(e.id)}, participantId=${e.participantId}`}var sg=Z,ag=i.setImmediate?e=>{i.setImmediate(e)}:e=>{(0,sg.defer)(e)},og=class e{constructor(){this.deferredOperations=new Map,this.deferredOperationsNames=[],this.isRunning=!1}setLogger(e){this._logger=e.createChild("[DeferHandler]")}setDeferToQueueMicrotask(t){t&&i.queueMicrotask?e.defer=e=>i.queueMicrotask(e):e.defer=ag}createDeferRunner(e){const t={};return i=>this.runDeferred(t,i,e)}runDeferredWithoutDedup(e,t){this.runDeferred({},e,t)}runDeferred(t,i,n){this.deferredOperations.has(t)||(this.deferredOperations.set(t,i),n&&this.deferredOperationsNames.push(" "+n),this.isRunning||(this.isRunning=!0,this._startDeferalTime=Date.now(),this.causeId=be(),this._logger?.info(`[${this.causeId}]Deferring operations`),e.defer((()=>{this._timeToRun=Date.now()-this._startDeferalTime,this.deferredOperations.forEach((t=>{e.runWithTryCatch(t)})),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(e){try{e&&e()}catch(e){}}};og.defer=ag;var lg=og,cg=class{};cg.instance=new lg;var dg=Z,ug="sendonly",hg="recvonly",gg="sendrecv",pg="audio",mg="video",fg="applicationsharing-video",vg="audio-teleconferencing",Sg="xapplicationsharing-video",yg=class extends gt{constructor(e,t,i){super(t),this.mediaSession=e,this.isAvailable=!1,this.mediaSessionInitPromise=new Kt,this.currentIsStreaming=!1,e&&this.mediaSessionInitPromise.resolve(),this.id=i,this.logger=t.createChild(`Stream[${this.id}]`)}set isStreaming(e){this.currentIsStreaming=e,this.logger.info(`isStreaming has changed to ${this.currentIsStreaming}`),this.raiseChanged()}get isStreaming(){return this.currentIsStreaming}update({sourceId:e=null,direction:t=hg,participantId:i=null,endpointId:n=null}={},r,s){this.logger.info(`[${r}][update before] sourceId=${e}, direction=${t}, isAvailable=${this.isAvailable}, participantId=${i}, endpointId=${qe(n,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.id=e;const a=t===gg||t===ug;this.isAvailable!==a&&(this.negotiationTag=s?.get(n)),this.isAvailable=a,this.mediaSession?.getSessionConfig().config.streamAvailabilityConsiderModalities&&this.getIsModalityDisabled()&&(this.logger.info(`Disabling current modality, disabled: ${JSON.stringify(this.mediaSession?.getDisabledModalities?.()||"")}`),this.isAvailable=!1),this.participantId=i,this.endpointId=n,this.logger.info(`[${r}][update after] sourceId=${e}, direction=${t}, isAvailable=${this.isAvailable}, participantId=${i}, endpointId=${qe(n,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.raiseChanged()}setMediaSession(e,t){const i=e?.getAllowedModalities?.()||{};this.logger.info(`[${t}][setMediaSession] ${JSON.stringify(i)}`),this.mediaSession=e,e?this.mediaSessionInitPromise.resolve():this.mediaSessionInitPromise.reject(new Error("MediaSession is null"))}isActive(){return this.isAvailable&&this.isStreaming}getIsModalityDisabled(){return!1}},Cg=class extends yg{},Tg=Z,Eg=class extends yg{constructor(e,t,i,n,r,s){super(void 0,e,t),this.configProvider=i,this.streamOptions=n,this.telemetryLogger=r,this.callInfo=s,this.type=2,this.finalTelemetrySent=!1,this.player=new Di(e.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 e=this.player.getSnapshotTelemetryReport(),t={isAvailable:this.isAvailable,isStreaming:this.isStreaming,...e};return(0,Tg.isEqual)(this.lastStreamStats,t)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=t),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,rank:this.rank,...this.lastStreamStats}}stop(){return Promise.resolve(void 0)}async start(e){if(this.logger.info("[start]: Starting UMS stream"),!this.renderer){if(await this.player.configure(this.streamOptions),!(await this.player.loadPlayer(e)).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 e=this.player.getSnapshotTelemetryReport();this.logger.debug(`[sendSnapshotTelemetry] sending snapshot telemetry report: ${JSON.stringify(e)}`);const t={...this.callInfo,...e};this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}sendTelemetry(e){if(this.finalTelemetrySent)return;e&&(this.finalTelemetrySent=!0);const t=this.player.getTelemetryReport();this.logger.debug(`[sendTelemetry] sending telemetry report: ${JSON.stringify(t)}`);const i={...this.callInfo,...t};this.telemetryLogger.sendEvent({eventName:"live_events",props:i})}},bg=class extends gt{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(e){this.renderer.setScalingMode(function(e){switch(e){case 1:return"crop";case 0:return"stretch";default:return"fit"}}(e))}async cameraAutoControl(e){throw new Error("Not implemented")}async getCameraManualControlStates(e){throw new Error("Not implemented")}async setCameraManualControlStates(e){throw new Error("Not implemented")}async enumerateCameraManualControls(){throw new Error("Not implemented")}async isCameraAdvancedControlCapable(){throw new Error("Not implemented")}onVideoSizeChanged(e,t){this.streamSize={width:e,height:t},this.event("videoSizeChanged").raise(e,t),this.raiseChanged()}},_g=class extends bg{constructor(){super(),this.disposed=!1}initialize(e,t,i){this.disposed||this.renderer||(this.renderer=t.createPreviewRenderer(e,i),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t))))}onVideoSizeChanged(e,t){this.isRendering=e>0&&t>0,super.onVideoSizeChanged(e,t)}setVideoMirroring(e){this.renderer.setVideoMirroring(e)}startVideoAsync(){return this.renderer.startVideoAsync()}dispose(){this.disposed=!0,this.renderer&&(this.renderer.dispose(),this.renderer=null)}},Ig=class extends bg{constructor(e,t,i,n,r){super(),this.logger=e,this.target=t,this.rendererStats=n,this.configProvider=r,this.subscriptionActive=!1,this.firstFrameRendered=!1,this.rendererId=n.newRendererId(),this.renderer=i.createRemoteRenderer(t),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t))),this.renderer.on("onVideoStateChanged",(e=>this.onVideoStateChanged(e))),this.renderer.on("onIsRenderingChanged",(e=>this.onIsRenderingChanged(e)))}toString(){return`rvr:${this.rendererId}`}onVideoStateChanged(e){this.rendererStats.streamStateChanged(e.stream)}onVideoSizeChanged(e,t){this.configProvider.config.videoIsRenderingCheck&&this.setIsRendering(e>0&&t>0),super.onVideoSizeChanged(e,t)}setIsRendering(e){this.isRendering!==e&&(this.isRendering=e,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(e){this.setIsRendering(e),this.raiseChanged()}subscribeVideoAsync(e){this.currentVideoStream=e,this.rendererStats.event(1,this.rendererId,e.id);const t=this.renderer.subscribeVideoAsync(e.id,1===e.type);return this.subscriptionActive=!0,t.then((()=>{this.rendererStats.event(2,this.rendererId,e.id),this.watchStream(e)})),t}watchStream(e){this.changeSub&&this.changeSub.dispose(),this.changeSub=e.changed((()=>{e.isAvailable?this.subscriptionActive||this.subscribeVideoAsync(e):(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)}},wg=class extends gt{constructor(e,t,i){super(i),this.getRawStream=e,this.disposeStream=t,this.logger=i,this.isClientDisposed=!1,this.clientId=sn()}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")}},Ag=class{constructor(e,t){this.stream=e,this.rawBaseClient=new wg((async()=>this.stream),(()=>this.dispose()),t)}client(){return this.rawBaseClient}updateAndNotifyClient(e){this.rawBaseClient&&(this.stream=e,this.rawBaseClient.notifyStreamChange())}dispose(){this.rawBaseClient=null,this.stream=null}},Pg=class{constructor(e,t,i){this.videoStream=e,this.subscriptionManager=t,this.logger=i,this.subscriptionActive=!1,this.modality=0===e.type?Gi.MODALITY.video:Gi.MODALITY.sharing,this.createSubscription(),this.rawBaseClient=new wg((async()=>this.subscriptionClient?.subscribedStream),(()=>this.unsubscribeVideo()),i),this.videoStream.changed((()=>{this.rawBaseClient?.isDisposed||(this.logger.info(`isAvailable: ${e.isAvailable}, subscriptionActive: ${this.subscriptionActive}`),e.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()))}},Rg=class{constructor(e){this.logger=e,this.handlerMap=new Map}dispose(){this.logger.info("dispose"),this.handlerMap.forEach((e=>e.client().dispose())),this.handlerMap.clear()}handlerAdded(e){const t=e.client();t.on("clientDisposed",(()=>this.deleteRawStreamManagerById(t.clientId))),this.handlerMap.set(t.clientId,e)}deleteRawStreamManagerById(e){this.handlerMap.delete(e)}},Mg=class extends Rg{constructor(e){super(e)}streamChanged(e){this.handlerMap.forEach((t=>t.updateAndNotifyClient(e)))}createIRawStreamClient(e,t){const i=new Ag(e,this.logger);super.handlerAdded(i);const n=i.client();return this.logger.info(`[${t}] - clientId:${n.clientId}, client created`),n}updateHandlers(e){e.forEach(((e,t)=>{this.handlerMap.has(t)||this.handlerMap.set(t,e)}))}},Dg=class extends Rg{constructor(e){super(e)}createIRawStreamClient(e,t,i){const n=new Pg(e,t,this.logger);super.handlerAdded(n);const r=n.client();return this.logger.info(`[${i}] - clientId:${r.clientId}, client created`),r}},kg=Z,Og=class extends yg{constructor(e,t,i,n){super(e,i,n),this.rendererStats=t,this.rawIncomingVideoStreamManager=new Dg(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 e={isAvailable:this.isAvailable,isStreaming:this.isStreaming};return(0,kg.isEqual)(this.lastStreamStats,e)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=e),{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(e=be()){return this.logger.info(`[${e}] - getRawStream called for incoming video stream`),this.rawIncomingVideoStreamManager.createIRawStreamClient(this,this.mediaSession.getSubscriptionManager(),e)}start(e,t){return this.logger.info(`video start: target=${e}, options=${JSON.stringify(t)}`),this.mediaSessionInitPromise.promise.then((()=>new Ig(this.logger.createChild("RemoteVideoRenderer"),e,this.mediaSession,this.rendererStats,this.mediaSession?.getSessionConfig()))).then((e=>(t&&e.setScalingMode(t.scalingMode),this.logger.info(`subscribeVideoAsync: videoRenderer=${e}, id=${this.id}`),e.subscribeVideoAsync(this).catch((t=>{throw e.dispose(),t})).then((()=>(this.isStreaming=!0,e))))))}update(e,t,i){this.logger.info(`[${t}][update] stream=${JSON.stringify(e)}`);const n=this.isAvailable;super.update(e,t,i),this.isAvailable&&this.isAvailable!==n&&this.rendererStats.event(0)}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().video}},Ng=class extends Og{constructor(e,t,i,n){super(e,t,i,n),this.type=1}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().sharing}},Lg=class e extends gt{constructor(e,t,i,n){super(),this.participantId=e,this.mediaSession=t,this.localStats=i,this.audioSourceIds=[],this.streams={},this.lastUmsStreamId=1;const r=i.receive(1,e),s=i.receive(2,e);this.audio=new Cg(t,n,1);const a=new Og(t,r,n,2),o=new Ng(t,s,n,3),l=this.mediaSession?.getSessionConfig()?.config.participantStreamInitialSubscriptions;l&&(a.changed((()=>this.event("streamChanged").raise())),o.changed((()=>this.event("streamChanged").raise()))),this.streams[0]=[a],this.streams[1]=[o],this.streams[2]=[],this.logger=n.createChild("PluginlessCallStreamManager")}setMediaSession(e,t){this.logger.info(`[${t}][setMediaSession]`),this.mediaSession=e,[[this.audio],this.streams[0],this.streams[1]].forEach((i=>i.forEach((i=>i.setMediaSession(e,t)))))}updateStreams(t,i,n,r){this.logger.info(`[${i}][updateStreams]`);const s=i=>t.filter((e=>i.includes(e.type))).sort(e.compareStreams);let a=s([pg]);0===a.length&&(a=s([vg])),a.length>0&&(this.audioSourceIds=a.map((e=>e.sourceId)));const o=a[0];o&&this.audio.update(o,i),this.updateMediaStreams(s([mg]),0,i,n),r?this.updateMediaStreams(s([fg,Sg]),1,i,n):this.updateMediaStreams(s([fg]),1,i,n)}hasAudioSource(e){return this.audioSourceIds.some((t=>t===e))||this.audio.id===e}useUmsStream(t,i,n,r,s,a){this.logger.info(`[${a}][useUmsStream] Updating ums streams`);const o=this.getUmsInformation(t,r),l=this.streams[2],c=l.filter((t=>!o.some((i=>e.compareUmsStreams(t,i)))));c.forEach((e=>(0,dg.remove)(l,e))),c.length&&this.logger.info(`[${a}][useUmsStream] Removing ${c.length} ums streams`),o.forEach((t=>{let r=l.find((i=>e.compareUmsStreams(i,t)));r||(r=new Eg(this.logger.createChild("UmsStream"),this.lastUmsStreamId++,i,t,s,n),this.logger.info(`[${a}][useUmsStream] Adding ums stream with metadata: ${JSON.stringify(t)}`),l.push(r))}))}getUmsStreamMetadata(e,t){let i=null,n=null;if(i=e.find((function(e){return"MiddleLaneUltraLowLatency"===e.deliveryPipelineType&&t===e.isPrimary})),i){const e=i.urls;if(e&&e.length>0){i.identifier||this.logger.warn(`[getUmsStreamMetadata]: no ums stream identifier found, isPrimary: ${t}`);const r=i.decryptionKey?.id,s=i.decryptionKey?.value;r&&s||this.logger.warn(`[getUmsStreamMetadata]: no valid ums stream decryption key found, isPrimary: ${t}`);const a=i.deliveryPipelineType||void 0;n={url:e[0],streamDeliveryPipeline:a,decryptionKey:r&&s?{id:r,value:s}:null}}else this.logger.info(`[getUmsStreamMetadata]: no ums URLs found, isPrimary: ${t}`)}else this.logger.info(`[getUmsStreamMetadata]: no ums stream information found, isPrimary: ${t}`);return n}getUmsInformation(e,t){const i=[];let n=null,r=null;for(const t in e){const i=e[t].streams;if(i){if(n)this.logger.info(`[getUmsInformation]: primary ums stream already found, skipping finding primary stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!0);e?n=e:this.logger.info(`[getUmsInformation]: no primary ums stream found for participant: ${t}`)}if(r)this.logger.info(`[getUmsInformation]: alternate ums stream already found, skipping finding alternate stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!1);e?r=e:this.logger.info(`[getUmsInformation]: no alternate ums stream found for participant: ${t}`)}}else this.logger.warn(`[getUmsInformation]: no stream information found for participant: ${t}`)}return(n||r)&&i.push({stream:n,altStream:r,threadId:t}),i}static compareStreams(e,t){const i="sendonly"===e.direction||"sendrecv"===e.direction,n="sendonly"===t.direction||"sendrecv"===t.direction;return i&&!n?-1:n&&!i?1:t.sourceId-e.sourceId}static compareUmsStreams(t,i){const n=t.getStreamOptions();return e.compareUmsStreamMetadata(n.stream,i.stream)&&e.compareUmsStreamMetadata(n.altStream,i.altStream)}static compareUmsStreamMetadata(e,t){return!e&&!t||!(!e&&t||e&&!t)&&e.decryptionKey.id===t.decryptionKey.id&&e.decryptionKey.value===t.decryptionKey.value&&e.url===t.url}updateMediaStreams(e,t,i,n){const r=this.streams[t],s=r.filter((t=>!e.some((e=>e.sourceId===t.id))));s.forEach((e=>(0,dg.remove)(r,e))),s.length&&this.logger.info(`[${i}][updateMediaStreams] Removing ${s.length} streams of type ${t}`),e.forEach(((s,a)=>{let o=r.find((e=>e.id===s.sourceId));o||(0===t?o=new Og(this.mediaSession,this.localStats.receive(1,this.participantId),this.logger,s.sourceId):1===t&&(o=new Ng(this.mediaSession,this.localStats.receive(2,this.participantId),this.logger,s.sourceId)),this.logger.info(`[${i}][updateMediaStreams] Adding stream ${s.sourceId} of type ${t}`),r.push(o),o.changed((()=>this.event("streamChanged").raise()))),o.update(s,i,n),o.rank=e.length-a}))}},xg={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]},Fg={0:"Disconnected",1:"Connecting",2:"Ringing",3:"Connected",5:"Connected",4:"Disconnected",7:"Connecting"},Ug=class extends gt{constructor(e,t,i,n,r,s=be(),a=[]){super(i),this.mri=e,this.callTelemetry=r,this.cachedMediaStreams=a,this.state=0,this.voiceLevel=0,this.isServerMuted=!1,this.endpointType="default",this.balanceUpdates={},this._raiseChangeDeferRunner=cg.instance.createDeferRunner("CallParticipant.RaiseChange"),this.filteredParticipantEndpointDetails={},this.recordTelemetryForStateChange=(e,t,i,n)=>{if(n){const n="_SetParticipantStateInvalid",r={state:t,reason:i,endpoints:[]};this.endpoints?.endpointDetails?.length&&(r.endpoints=Er(this.endpoints.endpointDetails)),this.callTelemetry.recordEvent(n,r,e)}},this.checkIfIncomingServerMutedIsUpdated=e=>{e.endpointDetails.forEach((e=>{const t=this.filteredParticipantEndpointDetails[e.participantId];void 0!==t&&eg(this.logger,t,e)}))},this.handleServerMutedInfoUpdate=e=>{let t=!1;for(const i of e){const e=this.filteredParticipantEndpointDetails[i.participantId];tg(this.logger,e,i,!0)&&(t=!0)}t&&this.updateIsServerMuted()},this.id=this.mri,this.logger=i.createChild((()=>`ICallParticipant[${De(this.id)}][${this.state}]`)),this.logger.info(`[${s}]created`),this.streamManager=new Lg(this.id,t,n,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:De(this.id),state:this.state,isServerMuted:this.isServerMuted})}async getDiagnosticDataAsync(){return this.getDiagnosticData()}isSameParticipantsMri(e){return this.id===e}setMediaSession(e,t=be()){this.streamManager.setMediaSession(e,t)}applyCachedMediaStreams(e=be()){const t=this.logger.createFnLogger("applyCachedMediaStreams",e);this.cachedMediaStreams?.length?(t.info("applying cachedMediaStreams"),this.updateStreams(this.cachedMediaStreams,e,!1)):t.info("cachedMediaStreams is empty")}updateStreams(e,t=be(),i=!1,n,r=!1){this.logger.createFnLogger("updateStreams",t).info(`isStreamingMode=${i} mediaStreams=${Ge(e)}`),e?.length&&(this.cachedMediaStreams=e),i||(this.streamManager.updateStreams(e,t,n,r),this.raiseChangedDeferred())}hasAudioSource(e){return this.streamManager.hasAudioSource(e)}raiseChangedDeferred(){this._raiseChangeDeferRunner((()=>this.raiseChanged()))}updateIsServerMuted(){if(!Object.values(this.filteredParticipantEndpointDetails).length)return void this._updateIsServerMuted(!1);let e=!1;Object.values(this.filteredParticipantEndpointDetails).forEach((t=>{const i=e=>t.mediaStreams?.filter((t=>t.type===e)).sort(Lg.compareStreams);let n=i(pg)?.[0];n||(n=i(vg)?.[0]);const r=!!n?.serverMuted,s=t.endpointState?.state;!1!==r||0!=!!s?.isMuted||(e=!0)}));const t=!e;this._updateIsServerMuted(t)}_updateIsServerMuted(e){e!==this.isServerMuted&&(this.isServerMuted=e,this.logger.info(`_updateIsServerMuted updating to: ${this.isServerMuted}`),this.raiseChanged())}updateVoiceLevel(e){this.voiceLevel!==e&&(this.voiceLevel=e,this.raiseChanged())}setState(e,t,i){if(this.state===e)return;const n=this.logger.createFnLogger("setState",i);if(3===this.state&&6===e)return void n.info("Ignore Connected->EarlyMedia transition, it is a race between media and signaling");const r=xg[this.state].indexOf(e)>=0;this.recordTelemetryForStateChange(i,e,t,!r),r?(n.info(`state=${this.state}->${e} reason=${this.stateReason}->${t}`),this.state=e,this.stateReason=t,this.raiseChangedDeferred()):n.logFailure(`Invalid state transition ${this.state}->${e} attempted`)}processParticipantDetails(e,t,i){const n=this.logger.createFnLogger("processParticipantDetails","");this.role=e.role,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.meetingRoles=e.meetingRoles,this.participantType=e.participantType,this.displayName=e.displayName,this.tenantId=e.tenantId,this.propertyBag=e.propertyBag,this.version=e.version,this.otpIdentity=e.otpIdentity,this.isIdentityMasked=!!e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,e.endpointDetails?.length&&(this.endpoints={endpointDetails:[]},this.participantCapabilities={canConference:!1,canShareScreen:!1,canMerge:!0},this.checkIfIncomingServerMutedIsUpdated(e),this.filteredParticipantEndpointDetails={},e.endpointDetails.forEach((e=>{const n=Hh(e,t);if(this.endpoints.endpointDetails.push(n),!n.mappedTo){if(this.filteredParticipantEndpointDetails[e.participantId]={endpointId:e.endpointId,serverMuteVersion:e.serverMuteVersion,endpointState:e.endpointState,mediaStreams:e.mediaStreams},e.capabilities&&(this.participantCapabilities.canConference||"enabled"!==e.capabilities.cloudAudioVideoConference||(this.participantCapabilities.canConference=!0),this.participantCapabilities.canShareScreen||"enabled"!==e.capabilities.cloudScreenSharing||(this.participantCapabilities.canShareScreen=!0),this.participantCapabilities.canMerge||"enabled"!==e.capabilities.cloudMerge||(this.participantCapabilities.canMerge=!0)),this.contentSharingRole=0,e.contentSharing&&e.contentSharing.sessionInformation){const t=e.contentSharing.sessionInformation;"attendee"===t.role?this.contentSharingRole=1:"presenter"===t.role&&(this.contentSharingRole=2)}n.streamInformation&&i&&i()}})),this.updateIsServerMuted(),n.info(`endpointDetails=${Qe(this.endpoints)}`),this.raiseChangedDeferred())}toCafeParticipant(){return{audioState:Fg[this.state],mri:this.mri}}getSourceIdForMediaType(e){const t=Ud(this,e);return-1===t&&this.logger.warn("getSourceIdForMediaType failed"),t}useUmsStream(e,t,i,n,r,s){this.streamManager.useUmsStream(e,t,i,n,r,s),this.raiseChangedDeferred()}hasSourceId(e,t){return void 0!==Bd(this,e,t)}},Bg=class extends gt{constructor(e,t,i,n,r,s="",a,o){super(),this.callTelemetry=e,this.signalingSession=i,this.contentSharingGuid=n,this.contentSharingIdentity=r,this.state=s,this.subject=a,this.handleOperationFailure=(e,t,i)=>{i.logFailure(e);const n=this.getTerminatedReasonFromError(e);return t.updateStatusTo&&(this.contentSharingStatus=t.updateStatusTo,this.rejectContentSharing(n)),Promise.reject(n)},this._logger=t.createChild((()=>`[ContentSharingSession][${this.contentSharingGuid}]`)),this.contentSharingStatus=0,this.contentSharingTerminationReason=null,this.contentSharingState=s,this._callOperationHandler=new as(this._logger,this.callTelemetry),o&&(this.sessionId=o)}get contentSharingStatus(){return this.status}set contentSharingStatus(e){if(this._logger.info(`[set contentSharingStatus][currentStatus=${this.status}][newStatus=${e}]`),this.callTelemetry.recordEvent("_SetContentSharingStatus",{newStatus:e,oldStatus:this.status}),this.status!==e&&7!==this.status&&8!==this.status){if(this._logger.info(`[set contentSharingStatus] Changing content sharing status to: ${e}`),this.status=e,7===this.status){const e={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[set contentSharingStatus] Content sharing is disconnected"};this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(e)}if(2===this.status||5===this.status){const e={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Content sharing cannot be ended when not presenting"};this._callOperationHandler.maybeRejectOperation("StopContentSharing",e)}3===this.status&&(this._callOperationHandler.maybeResolveOperation("StartContentSharing"),this._callOperationHandler.maybeResolveOperation("TakeContentSharingControl")),this.raiseChanged()}}get contentSharingState(){return this.state}set contentSharingState(e){this.state!==e&&(this.state=e,this.raiseChanged())}startContentSharing(e=be()){const t=this._logger.createFnLogger("StartContentSharing",e);if(0!==this.contentSharingStatus){const i=`[${e}][startContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.startContentSharingAsync(this.contentSharingIdentity,this.contentSharingState,this.subject,this.contentSharingGuid,e).then((e=>{this.sessionId=e.sessionId,this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StartContentSharing",updateStatusTo:8},t))),this._callOperationHandler.waitForOperation("StartContentSharing")}joinContentSharing(e=be()){const t=this._logger.createFnLogger("JoinContentSharing",e);if(2!==this.contentSharingStatus){const i=`[${e}][joinContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.joinContentSharingAsync(this.contentSharingGuid,e).then((e=>(this.contentSharingStatus=4,this.contentSharingState=e.sessionState,this.presenterId=e.presenter,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"JoinContentSharing",updateStatusTo:8},t)))}updateContentSharingSessionState(e,t,i=be()){const n=this._logger.createFnLogger("UpdateContentSharingSessionState",i);if(3!==this.contentSharingStatus){const e=`[${i}][updateContentSharingSessionState][failed][reason=InvalidState]`,t={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:e};return n.logFailure(`state=${this.contentSharingStatus}, reason=${e}`),Promise.reject(t)}return this.signalingSession.updateContentSharingSessionStateAsync(this.contentSharingGuid,t,i).then((()=>Promise.resolve())).catch((t=>this.handleOperationFailure(t,{causeId:i,operation:"UpdateContentSharingSessionState",operationId:e},n)))}takeContentSharingControl(e=be()){const t=this._logger.createFnLogger("TakeContentSharingControl",e);if(5!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.takeContentSharingControlAsync(this.contentSharingGuid,e).then((()=>{this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"TakeContentSharingControl"},t))),this._callOperationHandler.waitForOperation("TakeContentSharingControl")}updateContentSharingParticipantStateToViewer(e=be()){const t=this._logger.createFnLogger("UpdateParticipantState",e);if(4!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.updateContentSharingParticipantStateAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=this.presenterId===this.signalingSession.participantManager.localParticipant.id?3:5,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"UpdateParticipantState"},t)))}stopContentSharing(e=be()){const t=this._logger.createFnLogger("StopContentSharing",e);if(2===this.contentSharingStatus||4===this.contentSharingStatus||5===this.contentSharingStatus){const i=`[${e}][stopContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.deleteContentSharingAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=7,this._callOperationHandler.waitForOperation("StopContentSharing")))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StopContentSharing"},t)))}dispose(e=be()){this._callOperationHandler.rejectPendingOperations({terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Call ended"},e),this.contentSharingStatus=7,this.contentSharingState="",super.dispose()}rejectContentSharing(e={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(e)}getTerminatedReasonFromError(e){const t=e?.endCode?.code||0,i={terminatedReason:32,terminatedReasonCode:t,terminatedReasonSubCode:e?.endCode?.subCode||0,errorMessage:e};switch(t){case 404:i.terminatedReason=34,i.errorMessage="Active session not found on server";break;case 403:i.terminatedReason=8,i.errorMessage="Failed due to insufficient permissions"}return i}};m([Gr("StartContentSharing"),f(0,Wr)],Bg.prototype,"startContentSharing",1),m([Gr("JoinContentSharing"),f(0,Wr)],Bg.prototype,"joinContentSharing",1),m([Gr("UpdateContentSharingSessionState"),f(0,zr),f(2,Wr)],Bg.prototype,"updateContentSharingSessionState",1),m([Gr("TakeContentSharingControl"),f(0,Wr)],Bg.prototype,"takeContentSharingControl",1),m([Gr("UpdateParticipantState"),f(0,Wr)],Bg.prototype,"updateContentSharingParticipantStateToViewer",1),m([Gr("StopContentSharing",{waitFor:"StartContentSharing"}),f(0,Wr)],Bg.prototype,"stopContentSharing",1);var Vg,Hg=class{constructor(e){this.value=e,this.next=void 0}},$g=class{constructor(){this.length=0}enqueue(e){const t=new Hg(e);this.front?(this.rear.next=t,this.rear=t):(this.front=t,this.rear=t),this.length++}dequeue(){if(!this.front)return;const e=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,e.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}},jg=Z,Gg=class{constructor(e){this.comparator=e,this.heap=[]}enqueue(e){this.heap.push(e),this.bubbleUp()}dequeue(){const e=this.peek();if(void 0!==e){const e=this.heap.pop();this.size()>0&&(this.heap[0]=e,this.bubbleDown())}return e}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(){let e=this.size()-1,t=this.getParentIndex(e);for(;!this.isRoot(e)&&this.comparator(this.heap[e],this.heap[t]);)[this.heap[t],this.heap[e]]=[this.heap[e],this.heap[t]],e=t,t=this.getParentIndex(e)}bubbleDown(){if(this.size()<=1)return;let e=this.getRootIndex(),t=this.getLeftIndex(e),i=this.getRightIndex(e);for(;this.heap[t]&&this.comparator(this.heap[t],this.heap[e])||this.heap[i]&&this.comparator(this.heap[i],this.heap[e]);)!this.heap[i]||this.comparator(this.heap[t],this.heap[i])?([this.heap[e],this.heap[t]]=[this.heap[t],this.heap[e]],e=t):([this.heap[e],this.heap[i]]=[this.heap[i],this.heap[e]],e=i),t=this.getLeftIndex(e),i=this.getRightIndex(e)}getRootIndex(){return 0}isRoot(e){return 0===e}getLeftIndex(e){return 2*e+1}getRightIndex(e){return 2*e+2}getParentIndex(e){return Math.floor((e-1)/2)}},qg=class{constructor(e,t,i){this.maxPacketRate=t,this.rateLimiterCheckInterval=i,this.maxDataRate=0,this.packetsEndTimeForPacketRate=0,this.packetsEndTimeForBitrate=0,this.maxDataRate=e/8}canSend(e){if(0===this.maxDataRate&&0===this.maxPacketRate)return!0;const t=_n();if(this.maxPacketRate&&this.packetsEndTimeForPacketRate>t+this.rateLimiterCheckInterval)return!1;if(this.maxDataRate&&this.packetsEndTimeForBitrate>t+this.rateLimiterCheckInterval)return!1;const i=this.maxPacketRate?1e3/this.maxPacketRate:0,n=this.maxDataRate?e.length/this.maxDataRate*1e3:0;return this.packetsEndTimeForPacketRate=Math.max(this.packetsEndTimeForPacketRate,t)+i,this.packetsEndTimeForBitrate=Math.max(this.packetsEndTimeForBitrate,t)+n,!0}},zg=class{constructor(e){this.dataIds=new Map,this.maxBitrate=e.config.webrtcDataChannel.maxBitrate,this.maxPacketRate=e.config.webrtcDataChannel.maxPacketRate,this.maxQueueSize=e.config.webrtcDataChannel.maxQueueSize,e.config.webrtcDataChannel.dataIds.forEach((e=>{this.dataIds.set(e.dataId,e)}))}getMaxBitrate(e){return this.dataIds.get(e)?.maxBitrate??this.maxBitrate}getMaxPacketRate(e){return this.dataIds.get(e)?.maxPacketRate??this.maxPacketRate}getMaxQueueSize(e){return this.dataIds.get(e)?.maxQueueSize??this.maxQueueSize}getConfig(e){const t=this.dataIds.get(e)||{dataId:e};return t.maxBitrate=t.maxBitrate??this.maxBitrate,t.maxPacketRate=t.maxPacketRate??this.maxPacketRate,t.maxQueueSize=t.maxQueueSize??this.maxQueueSize,t.priorityWeight=t.priorityWeight??1,t}},Wg=class{constructor(e,t,i){this.dataIdConfig=t,this.rateLimiterCheckInterval=i,this.timeOffset=0,this.packets=new $g,this.startTime=e(),this.finishTime=this.startTime,this.rateLimiter=new qg(t.maxBitrate,t.maxPacketRate,this.rateLimiterCheckInterval),this.getCurrentTime=e,this.stats={bufferSize:t.maxQueueSize,remainingBytes:0,remainingPackets:0}}enqueue(e){if(0===e.length)return 0;const t=(0,jg.sumBy)(e,(e=>e.length)),i=this.dataIdConfig.maxQueueSize;if(i&&this.stats.remainingBytes+t>i)throw new Error(`dataId ${this.dataIdConfig.dataId} send queue is full`);const n=this.getCurrentTime();let r=0;return 0===this.packets.size()?(this.startTime=n,this.finishTime=n,this.timeOffset=0,r=n):r=this.finishTime,e.forEach((e=>{r+=e.length*this.dataIdConfig.priorityWeight,this.packets.enqueue({finishTime:r,packet:e}),this.stats.remainingBytes+=e.length,this.stats.remainingPackets++})),this.finishTime=r,t}dequeue(){const e=this.peek();if(void 0!==e){if(!this.rateLimiter.canSend(e.packet))return;this.packets.dequeue(),this.stats.remainingBytes-=e.packet.length,this.stats.remainingPackets--}return e}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 e=this.packets.peek();return{finishTime:e.finishTime+this.timeOffset,packet:e.packet}}getConfig(){return this.dataIdConfig}getStats(){return(0,jg.clone)(this.stats)}},Kg=class{constructor(e){this.senders=new Map,this.currentVirtualClock=0,this.dataIdConfigManager=new zg(e),this.virtualTimeQueue=new Gg(((e,t)=>e.minTime<t.minTime)),this.sendStats={bufferSize:0,remainingBytes:0,remainingPackets:0},this.rateLimiterCheckInterval=e.config.webrtcDataChannel.rateLimiterCheckInterval}getPacketsToSend(e){if(0===this.virtualTimeQueue.size())return[];const t=[],i=[];for(;e>=0&&this.virtualTimeQueue.size();){const n=this.virtualTimeQueue.peek();if(n.size>e)break;this.virtualTimeQueue.dequeue();const r=n.dataId,s=this.senders.get(r);if(void 0!==s.peek()){const n=s.dequeue();if(void 0!==n){t.push(n.packet),this.sendStats.remainingBytes-=n.packet.length,e-=n.packet.length,this.sendStats.remainingPackets--,this.currentVirtualClock=Math.max(this.currentVirtualClock,n.finishTime);const i=s.peek();i&&this.virtualTimeQueue.enqueue({dataId:r,minTime:i.finishTime,size:i.packet.length})}else i.push(r)}}return i.forEach((e=>{const t=this.senders.get(e);t.updateTimeOffset();const i=t.peek();i&&this.virtualTimeQueue.enqueue({dataId:e,minTime:i.finishTime,size:i.packet.length})})),t}appendPackets(e,t){let i=this.senders.get(e);void 0===i&&(i=new Wg((()=>this.currentVirtualClock),this.dataIdConfigManager.getConfig(e),this.rateLimiterCheckInterval),this.senders.set(e,i));const n=i.getStats(),r=i.enqueue(t);if(this.sendStats.remainingBytes+=r,this.sendStats.remainingPackets+=t.length,0===n.remainingPackets){const t=i.peek();void 0!==t&&this.virtualTimeQueue.enqueue({dataId:e,minTime:t.finishTime,size:t.packet.length})}}getStats(e){if(void 0===e)return(0,jg.clone)(this.sendStats);const t=this.senders.get(e);return void 0===t?{bufferSize:this.dataIdConfigManager.getMaxQueueSize(e),remainingBytes:0,remainingPackets:0}:t.getStats()}},Jg=class{constructor(e){this.data={protocolCounters:{},id:void 0,label:void 0,ordered:void 0,negotiated:void 0},this.data.id=e.id,this.data.label=e.label,this.data.ordered=e.ordered,this.data.negotiated=e.negotiated,this.data.protocol=e.protocol||void 0,this.data.maxPacketLifeTime=e.maxPacketLifeTime??void 0,this.data.maxRetransmits=e.maxRetransmits??void 0}recordProtocolEvent(e,t,i){this.data.protocolCounters[i]||(this.data.protocolCounters[i]={});const n=this.data.protocolCounters[i];switch(n[e]||(n[e]={successful:0,failed:0,fragmented:0,dismissed:0}),t){case 0:n[e].successful++;break;case 1:n[e].failed++;break;case 2:n[e].fragmented++;break;case 3:n[e].dismissed++}}recordError(e){this.data.error=e}getObjectRef(){return this.data}},Yg=class{constructor(e,t,i){this.dataId=e,this.diagnostics=t,this.logger=i,this.pendingFragments=[]}depacketize(e){const t=new DataView(e.buffer),i=63&t.getUint8(2);if(i!==this.dataId)throw new Error(`Invalid packet dataId: ${this.dataId} !== ${i}`);const n=((15&t.getUint8(0))<<8)+t.getUint8(1),r=128&t.getUint8(2),s=t.getUint16(3),a=t.getUint8(5),o=t.getUint32(6),l=t.getUint8(10);if(r){this.pendingFragments.length&&this.logger.warn(`Unfinished message: dataId: ${this.dataId} seqNum: ${s}`),this.remainingPackets=a,0!==a&&this.diagnostics.recordProtocolEvent("recv",2,i),this.pendingFragments=[],this.sourceId=o,this.recipients=[];for(let e=0;e<l;e++){const i=t.getUint32(11+4*e);this.recipients.push(i)}}else{if(0===this.pendingFragments.length)return this.logger.safe.error(`No start flag dataId: ${this.dataId} seqNum: ${s}`),this.diagnostics.recordProtocolEvent("recv",3,i),null;if(this.nextSeqNum!==s)return this.logger.safe.error(`Invalid sequence number: dataId: ${this.dataId} seqNum: ${s}`),this.diagnostics.recordProtocolEvent("recv",3,i),null;this.remainingPackets-=1}if(this.nextSeqNum=s+1&65535,this.pendingFragments.push(e.slice(n)),0===this.remainingPackets){const e=this.pendingFragments.reduce(((e,t)=>e+t.length),0),t=new Uint8Array(e);let i=0;for(const e of this.pendingFragments)t.set(e,i),i+=e.length;return this.pendingFragments=[],{dataId:this.dataId,sourceId:this.sourceId,data:t,recipients:this.recipients}}return null}},Qg=class{constructor(e){this.dataId=e,this.seqNum=0}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=new Uint8Array(e.data.length+t),n=new DataView(i.buffer);n.setUint8(0,16+(t>>8)),n.setUint8(1,255&t),n.setUint8(2,128|63&e.dataId),n.setUint16(3,this.seqNum),n.setUint8(5,0),n.setUint32(6,e.sourceId),n.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)n.setUint32(11+4*t,e.recipients[t]);return i.set(e.data,t),this.seqNum+=1,[i]}},Zg=class{constructor(e,t,i){this.dataId=e,this.fragmentationSize=t,this.diagnostics=i,this.seqNum=0}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=[],n=this.fragmentationSize-t;if(n<0)throw new Error(`message dataId: ${this.dataId} payload size: ${t} exceeds limit`);let r=e.data.length?Math.ceil(e.data.length/n):1;const s=r-1;s>0&&this.diagnostics.recordProtocolEvent("send",2,this.dataId);let a=e.data.length,o=!0,l=0;for(;r>0;){const c=Math.min(a,n),d=new Uint8Array(c+t),u=new DataView(d.buffer);u.setUint8(0,16+(t>>8)),u.setUint8(1,255&t),o?(o=!1,u.setUint8(2,128|63&e.dataId)):u.setUint8(2,63&e.dataId),u.setUint16(3,this.seqNum),u.setUint8(5,s),u.setUint32(6,e.sourceId),u.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)u.setUint32(11+4*t,e.recipients[t]);d.set(e.data.slice(l,l+c),t),l+=c,i.push(d),this.seqNum+=1,r-=1,a-=c}return i}},Xg=class extends Vi{constructor(e,t,i,n){super(),this.dataChannel=e,this.sessionDiagnostics=t,this.stateInternal="Created",this.packetizers=new Map,this.depacketizers=new Map,this.sendScheduleTimer=0,this.pendingPackets=new $g,this.sourceIdInternal=Ur,this.label=e.label,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(e),this.logger=i.createChild(`[WebRtcDataChannel ${this.label}]`),this.logger.safe.info(`Created with settings ${tt(this.getDataChannelSettings(e))}`),this.bufferedAmountLowThreshold=n.config.webrtcDataChannel.bufferedAmountLowThreshold,this.bufferedAmountHighThreshold=n.config.webrtcDataChannel.bufferedAmountHighThreshold,this.fragmentationSize=n.config.webrtcDataChannel.enableFragmentation?n.config.webrtcDataChannel.fragmentationSize:0,n.config.webrtcDataChannel.enableSendScheduler&&(this.sendScheduler=new Kg(n)),this.rateLimiterCheckInterval=n.config.webrtcDataChannel.rateLimiterCheckInterval,this.discardOnSendFailure=n.config.webrtcDataChannel.discardOnSendFailure,this.subscribeOnDataChannelEvents()}getDataIdStats(e){return this.sendScheduler?.getStats(e)}get state(){return this.stateInternal}set sourceId(e){this.sourceIdInternal=e}setDataChannel(e){this.dataChannel&&(this.logger.info(`Replacing internal data channel ${this.label}:${this.dataChannel.id} with ${e.label}:${e.id} with settings ${tt(this.getDataChannelSettings(e))}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close()),this.dataChannel=e,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(e),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(e,t=this.sourceIdInternal,i,n=[]){try{this.packetizers.has(e)||(this.fragmentationSize?this.packetizers.set(e,new Zg(e,this.fragmentationSize,this.diagnostics)):this.packetizers.set(e,new Qg(e)));const r=this.packetizers.get(e).packetize({dataId:e,sourceId:t,data:i,recipients:n});void 0!==this.sendScheduler?(this.sendScheduler.appendPackets(e,r),this.scheduleSend()):r.forEach((e=>{this.dataChannel.send(e)})),this.diagnostics.recordProtocolEvent("send",0,e)}catch(t){throw this.logger.unsafe.warn(`Failed to construct protocol message: ${tt(t)}`),this.diagnostics.recordProtocolEvent("send",1,e),t}}scheduleSend(){if("Connected"!==this.state)return;const e=e=>{try{this.dataChannel.send(e)}catch(e){return this.logger.unsafe.warn(`Failed to send message: ${tt(e)}`),!1}return!0};if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){const t=Date.now();let i=this.bufferedAmountHighThreshold-this.dataChannel.bufferedAmount;for(;this.pendingPackets.size();){const t=this.pendingPackets.peek();if(t.length>i)break;if(!e(t))break;this.pendingPackets.dequeue(),i-=t.length}if(0===this.pendingPackets.size()&&i>0){const t=this.sendScheduler.getPacketsToSend(i);for(const i of t)if(!1===e(i)&&!1===this.discardOnSendFailure){this.pendingPackets.enqueue(i);break}}if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){if(this.sendScheduleTimer)return;if(this.sendScheduler.getStats().remainingPackets>0){const e=Math.max(t+this.rateLimiterCheckInterval-Date.now(),20);this.sendScheduleTimer=window.setTimeout((()=>{this.sendScheduleTimer=0,this.scheduleSend()}),e)}}}}subscribeOnDataChannelEvents(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=e=>{const t=new Uint8Array(e.data),i=63&t[2];try{this.depacketizers.has(i)||this.depacketizers.set(i,new Yg(i,this.diagnostics,this.logger));const e=this.depacketizers.get(i).depacketize(t);e&&(this.diagnostics.recordProtocolEvent("recv",0,i),this.event("onmessage").raise(i,e.sourceId,e.data))}catch(e){this.logger.unsafe.warn(`Failed to parse incoming message: ${tt(e)}`),this.diagnostics.recordProtocolEvent("recv",1,i)}},this.dataChannel.onerror=e=>{const t=e?.target,i=tt(e?.error??e);this.logger.safe.warn(`onerror: label:${t.label} id:${t.id} ${i} `),this.diagnostics.recordError(i)},"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=e=>{const t=e.target;this.logger.safe.info(`onopen label:${t.label} id:${t.id}`),t.id%2==0&&this.setState("Connected")},this.dataChannel.onclose=e=>{const t=e.target;this.logger.safe.info(`onclose label:${t.label} id:${t.id}`),this.setState("Closed")},this.dataChannel.onclosing=e=>{const t=e.target;this.logger.safe.debug(`onclosing label:${t.label} id:${t.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(e){this.stateInternal=e,this.event("onStateChanged").raise(),"Connected"===e&&void 0!==this.sendScheduler&&this.scheduleSend()}getDataChannelSettings(e){return{ordered:e.ordered,maxRetransmits:e.maxRetransmits,maxPacketLifeTime:e.maxPacketLifeTime}}},ep=class extends Vi{constructor(e,t,i,n){const r=i.createChild("PluginlessDataChannel");super(r),this.pc=e,this.diagnostics=t,this.configProvider=n,this._state="Inactive",this.logger=r,this.subscribeOnDatachannel()}get state(){return this._state}getDataChannel(e){if(!this.dataChannel){this.logger.safe.info(`[${e}] creating new dataChannel`);try{const e=this.configProvider.config.dataChannelDebugInitSettings||{};this.dataChannel=new Xg(this.pc.createDataChannel("main-channel",e),this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()}catch(t){const i=tt(t);return this.logger.safe.error(`[${e}] createDataChannel failed: ${i}`),this.diagnostics.createChannelFailReason=i,this.setState("Failed"),null}}return this.dataChannel}updateDataModalityState(e){"Failed"!==this._state&&"Disabled"!==this._state&&(e===Gi.MEDIA_STATE.sendReceive?this.setState("Active"):e===Gi.MEDIA_STATE.inactive&&this.setState("Inactive"))}disable(){this.setState("Disabled")}dispose(){this.stopDataChannel(),this.pc=null,super.dispose()}subscribeOnDatachannel(){this.pc.ondatachannel=e=>{this.onDataChannel(e.channel)}}onDataChannel(e){this.logger.safe.info(`onDataChannel id=${e.id} label=${e.label}`),e.id%2==0?this.dataChannel?(this.logger.safe.info("Found existing data channel, replacing"),this.dataChannel.setDataChannel(e)):(this.dataChannel=new Xg(e,this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()):this.logger.safe.info(`onDataChannel ignoring id ${e.id}`)}subscribeForDataChannelEvents(){this.dataChannel.on("onStateChanged",(()=>{"Closed"===this.dataChannel.state&&(this.stopDataChannel(),this.setState("Inactive"))}))}setState(e){if(this._state!==e){this.diagnostics.dataChannelSessionState=e;const t=be();this._state=e,this.logger.safe.info(`[${t}] SessionDataChannelState changed, state=${this._state}`),"Inactive"===this._state||"Disabled"===this._state?this.stopDataChannel():"Active"===this._state&&this.getDataChannel(t),this.event("onStateChanged").raise(this._state)}}stopDataChannel(){this.dataChannel&&(this.logger.safe.info("stopDataChannel"),this.dataChannel.dispose(),this.dataChannel=null)}},tp=class extends gt{constructor(e){super(),this.mainChannel=null,this.sourceId=Ur,this._state="Inactive",this.dataHandlers=new Map,this.dataHandlerTelemetry=new Map,this.startTime=Date.now(),this.sendMessage=async(e,t,i)=>{if(!this.mainChannel||"Connected"!==this.mainChannel.state||"Active"!==this.state)throw new Error("No active data channel to send data from");this.mainChannel.sendMessage(e,this.sourceId,t,i)},this.logger=e.createChild("PluginlessDataChannel")}get state(){return this._state}registerSessionDataChannel(e,t){this.sessionDataChannel&&this.stop(t),this.sessionDataChannel=e,this.subscribeForSessionDataChannelEvents()}setDataChannelSourceId(e){this.logger.debug(`setDataChannelSourceId ${e}`),this.mainChannel&&(this.mainChannel.sourceId=e),this.sourceId=e}requestDataChannelHandler(e){return this.sessionDataChannel.getDataChannel(e)}async sendUserEvents(e,t){if(!this.mainChannel)throw this.logger.info("sendUserEvents() no data channel available"),new Error("Main DataChannel is not active");{const i=t?t.map((e=>parseInt(e,10))):[];this.mainChannel.sendMessage(0,this.sourceId,(new TextEncoder).encode(e),i)}}async addHandler(e,t){if(this.logger.info(`Adding handler with dataId ${e}`),this.dataHandlers.get(e))throw new Error(`Data Id ${e} is already registered`);const i={isStarted:!1,handler:t};this.dataHandlers.set(e,i),this.recordDataHandlerEvent(e,"added"),"Connected"===this.mainChannel?.state&&this.startHandler(e,i)}async removeHandler(e){if(this.logger.info(`Removing handler with dataId ${e}`),!this.dataHandlers.has(e))throw new Error(`Handler associated with Data Id ${e} is not attached`);const t=this.dataHandlers.get(e);t.isStarted&&this.stopHandler(e,t),this.dataHandlers.delete(e)}async updateNegotiationTag(e){}getTelemetry(){if(!this.dataHandlerTelemetry.size)return"";const e={};for(const[t,i]of this.dataHandlerTelemetry)e[t]=i;return JSON.stringify(e)}start(e){this.mainChannel?this.logger.info(`[${e}] already started`):(this.logger.info(`[${e}] starting`),this.mainChannel=this.sessionDataChannel.getDataChannel(e),this.subscribeForMainDataChannelEvents())}stop(e){this.mainChannel&&(this.logger.info(`[${e}] stopping`),this.mainChannel.dispose(),this.mainChannel=null)}dispose(){this.stop(void 0),this.sessionDataChannel=null,super.dispose()}setConfigProviderView(e){this.configProviderView=e}subscribeForMainDataChannelEvents(){this.mainChannel.on("onmessage",((e,t,i)=>{this.dataHandlers.has(e)&&(this.recordDataHandlerEvent(e,"recvd"),this.dataHandlers.get(e).handler.onDataReceived(e,i,t)),this.event("remoteUserEventsReceived").raise(e.toString(),(new TextDecoder).decode(i))})),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[e,t]of this.dataHandlers.entries())t.isStarted||this.startHandler(e,t)}stopHandlers(){for(const[e,t]of this.dataHandlers.entries())t.isStarted&&this.stopHandler(e,t)}startHandler(e,t){this.logger.info(`Starting dataHandler id: ${e}`),t.handler.onStarted(e,((t,i)=>(this.recordDataHandlerEvent(e,"sent"),this.sendMessage(e,t,i))),(()=>{const t=this.mainChannel?.getDataIdStats(e);if(void 0!==t){const e={bufferSize:t.bufferSize,remainingBytes:t.remainingBytes,remainingPackets:t.remainingPackets};return Promise.resolve(e)}return Promise.reject(new Error(`Stats of dataId ${e} is not available`))})),t.isStarted=!0,this.recordDataHandlerEvent(e,"started")}stopHandler(e,t){this.logger.info(`Stopping dataHandler id: ${e}`),t.handler.onStopped(e),t.isStarted=!1,this.recordDataHandlerEvent(e,"removed")}subscribeForSessionDataChannelEvents(){this.sessionDataChannel.on("onStateChanged",(e=>{const t=be();switch(e){case"Active":this.start(t),this.setState("Active");break;case"Inactive":this.stop(t),this.setState("Inactive");break;case"Failed":this.stop(t),this.setState("Failed");break;case"Disabled":this.stop(t),this.setState("Disabled");break;default:this.logger.warn(`[${t}] unhandled SessionDataChannelState ${e}`)}}))}recordDataHandlerEvent(e,t){this.dataHandlerTelemetry.has(e)||this.dataHandlerTelemetry.set(e,[{}]);const i=this.dataHandlerTelemetry.get(e);let n=i[i.length-1];if("added"===t&&void 0!==n.added){n={},i.push(n);const e=this.configProviderView?.config.maxStoredDataChannelValues??15;i.length>e&&i.shift()}switch(t){case"added":case"started":case"removed":n[t]=Date.now()-this.startTime;break;case"recvd":case"sent":n[t]=isNaN(n[t])?1:n[t]+1}}setState(e){this._state!==e&&(this._state=e,this.logger.info(`PluginlessDataChannelState changed, state=${this._state}`),this.event("onDataChannelStateUpdated").raise(this._state))}},ip=p(pe());(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,s=(e.buttonDown?1:0)<<5,a=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|s|a),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,s=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|s),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(Vg||(Vg={}));var np=Z,rp=Q,sp=1e4,ap="",op=class extends yr{constructor(e,t,i,n,r,s,a,o,l){super(e,n,(()=>this.recordedEvents.length>100)),this.auditLogger=t,this.config=i,this.negotiationTag=r,this.callId=s,this.participantId=a,this.endpointId=o,this.dataSourceId=l,this.messagesFromUnknownSender={},this.tsCallingVersion="2025.07.01.15"}setCallId(e){this.callId=e}setParticipantId(e){this.participantId=e}setDataSourceId(e){this.dataSourceId=e}callStateChanged(e){this.recordEvent("CallState",{state:e})}dataChannelAvailable(e){e?this.recordEvent("DataChannelAvailable"):this.recordEvent("DataChannelUnavailable")}shutdownSession(e){this.negotiationTag&&this.negotiationTag!==e?this.recordEvent("ShutdownByOtherSession",null,e):this.recordEvent("Shutdown")}recordProtocolMessage(e,t){e||(t in this.messagesFromUnknownSender||(this.messagesFromUnknownSender[t]=0),this.messagesFromUnknownSender[t]++)}sendAuditEvent(e,t,i,n,r){if(!this.auditLogger)return void this.logger.warn("AuditLogger is not set");const s=e=>e??"",a={TenantId:s(this.tenantId),CorrelationId:s(this.callId),ParticipantId:s(this.participantId),EndpointId:s(this.endpointId),TsCallingVersion:s(this.tsCallingVersion),sharingNegotiationTag:s(this.negotiationTag),timestamp:Date.now(),eventType:t,role:mp(this.role),initiator:mp(i),controlCauseId:e,viewerParticipantId:s(r.participantId),viewerEndpointId:s(r.endpointId),viewerDataSourceId:s(r.dataSourceId),sharerParticipantId:s(n.participantId),sharerEndpointId:s(n.endpointId),sharerDataSourceId:s(n.dataSourceId)};try{this.auditLogger.sendEvent({eventName:"mdsc_gtc_audit",props:a})}catch(e){this.logger.error("Failed to send audit event",e)}}},lp=class extends op{constructor(e,t,i,n,r,s,a,o,l,c){super(e,t,i,n,r,s,a,o,l),this.role=2;const d=Hd(c);if(d){this.sharerParticipantId=d;const e=(0,np.find)(c.endpoints.endpointDetails,(e=>e.participantId===d));e&&(this.sharerEndpointId=e.endpointId,this.sharerClientVersion=e.clientVersion)}}startHandshake(e){this.recordOperation("AvailableHandshake",e)}delayHandshakeSending(e,t,i){const n={delay:t,maxDelay:i};this.updateOperationData("AvailableHandshake",n,e)}handshakeSucceeded(e,t){const i={retries:t};this.recordOperationSuccess("AvailableHandshake",i,null,e)}handshakeFailed(e,t,i){const n={retries:t,reason:up(i)};this.recordOperationFailure("AvailableHandshake",n,null,e)}requestControl(e,t){this.recordOperation("ControlRequest",e,e),this.recordAuditEvent(e,2,"ControlRequest",t)}requestControlAccepted(e,t){this.recordOperationSuccess("ControlRequest",e,e),this.recordAuditEvent(e,1,"ControlRequestAccepted",t),this.recordAuditEvent(e,2,"ControlStarted",t)}requestControlRejected(e,t,i){const n={reason:pp(t)};2===t?this.recordOperationTimeout("ControlRequest",n,e,e):this.recordOperationFailure("ControlRequest",n,e,e),this.recordAuditEvent(e,1,"ControlRequestDeclined",i)}controlGiven(e,t){this.recordEvent("ControlGiven",{sharerSourceId:t},e),this.recordAuditEvent(e,1,"ControlGiven",t),this.recordAuditEvent(e,2,"ControlStarted",t)}controlTerminated(e,t,i,n){const r={sharerSourceId:i,reason:pp(t)};this.recordEvent("ControlTerminated",r,e);const s=n?1:2;this.recordAuditEvent(e,s,"ControlTerminated",i)}recordAuditEvent(e,t,i,n){if(this.config.disableAudit)return;const r={participantId:this.sharerParticipantId,endpointId:this.sharerEndpointId,dataSourceId:n},s={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(e,i,t,r,s)}getEvent(e,t){const i=e=>e??"";return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),SharerParticipantId:i(this.sharerParticipantId),SharerClientVersion:i(this.sharerClientVersion),EventTimestampBag:super.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},cp=class extends op{constructor(e,t,i,n,r,s,a,o,l){super(e,t,i,n,r,s,a,o,l),this.role=1}availableAckChanged(e){e?this.recordEvent("AvailableAckEnabled"):this.recordEvent("AvailableAckDisabled")}controlRequest(e,t,i){this.recordOperation("ControlRequest",e,e),this.recordAuditEvent(e,2,"ControlRequest",t,i)}controlRequestAccept(e,t,i){const n={status:"accepting",participantId:i};this.updateOperationData("ControlRequest",n,e,e),this.recordAuditEvent(e,1,"ControlRequestAccepted",t,i)}controlRequestAccepted(e,t,i){const n={participantId:i};this.recordOperationSuccess("ControlRequest",n,e,e),this.recordAuditEvent(e,2,"ControlStarted",t,i)}controlRequestRejected(e,t,i,n){const r={reason:pp(t),participantId:n};4===t?this.recordOperationTimeout("ControlRequest",r,e,e):this.recordOperationFailure("ControlRequest",r,e,e),this.recordAuditEvent(e,1,"ControlRequestDeclined",i,n)}giveControl(e,t,i){this.recordOperation("GiveControl",e,e),this.recordAuditEvent(e,1,"ControlGiven",t,i)}giveControlSucceeded(e,t,i){const n={participantId:i};this.recordOperationSuccess("GiveControl",n,e,e),this.recordAuditEvent(e,2,"ControlStarted",t,i)}giveControlFailed(e,t,i,n){const r={reason:pp(t)};this.recordOperationTimeout("GiveControl",r,e,e),this.recordAuditEvent(e,1,"ControlGiveFailed",i,n)}controlTerminated(e,t,i,n,r){const s={controllerSourceId:n,reason:pp(t)};this.recordEvent("ControlTerminated",s,e);const a=r?2:1;this.recordAuditEvent(e,a,"ControlTerminated",i,n)}recordAuditEvent(e,t,i,n,r){if(this.config.disableAudit)return;const s=function(e,t){return e.endpoints?.endpointDetails?.find((e=>e.mediaStreams?.find((e=>e.sourceId===t))))}(n,r)??n.endpoints?.endpointDetails?.[0],a={participantId:s?.participantId,endpointId:s?.endpointId,dataSourceId:r},o={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(e,i,t,o,a)}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),EventTimestampBag:this.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},dp=class extends gt{constructor(e,t,i,n){super(e),this._logger=e,this._call=t,this._telemetryLoggers=i,this._config=n,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",(e=>{this._callId=e,this._recordSessionTelemetry((t=>t.setCallId(e)))})),this._participantId=this._call.participantId,this._call.on("callLegIdChanged",(e=>{this._participantId=e,this._recordSessionTelemetry((t=>{t.setParticipantId(e),t.setDataSourceId(this.getLocalEndpointDataSourceId())}))})),this._endpointId=this._call.endpointId}get role(){return this._role}setAdapters(e,t,i){this._controlInjector=e,this._rendererAdapter=t,this._dataChannelAdapter=i,this._dataChannelAdapter.on("stateChange",(e=>{this._onDataChannelStatusChanged(e),this._recordSessionTelemetry((t=>t.dataChannelAvailable(e)))})),this._dataChannelAdapter.on("protocolMessage",((e,t,i,n)=>this.processProtocolMessage(e,t,i,n))),this._dataChannelAdapter.on("controlMessage",((e,t)=>this.processControlMessage(e,t)))}testSetControlInjector(e){}enableScreenSharingControl(e,t,i,n){if(this._logger.info(`enableScreenSharingControl() enabled=${e} disabledReason=${t}`),this._availableAckEnabled!==e||this._allowControlForUser!==n){if(this._allowControlForUser=n,e)this._raiseScreenSharingControlCapableEvent(!0,ap);else{if(0===t){const e={reason:2,detail:i};this.event("sharingControlError").raise(e)}this._raiseScreenSharingControlCapableEvent(!1,ap)}this._availableAckEnabled!==e&&this._recordSharerSessionTelemetry((t=>t.availableAckChanged(e)),!1),this._availableAckEnabled=e}}_canEnableGiveControl(){return this._controlInjector.canBeEnabled()}setRaiseRenderedAtViewer(e){this._raiseRenderedAtViewer=e}setScreenSharingControlFeatureFlag(e,t){this._logger.info(`setScreenSharingControlFeatureFlag() enabled=${e} clientConfiguration=${JSON.stringify(t)}`),this._enabled=e,this._availableAckEnabled=e,this._clientConfiguration={...t},this._enabled&&this._handleCallState(this._callState)}isScreenSharingControlEnabled(){return this._enabled}isInternalViewerControlEnabled(){return!this._clientConfiguration.externalViewerControlInitialization}isInternalSharerControlEnabled(){return!this._clientConfiguration.externalSharerControlInitialization}_disposeRenderer(e){this._disposeControlCapturer(e);for(const e of this._screenSharingVideoRendererSubscriptions)e.dispose();this._screenSharingVideoRendererSubscriptions=[],this._screenSharingVideoRenderer=null}setRenderer(e,t){this._logger.info("setRenderer");const i=be();if(this._disposeRenderer(i),!e)return Promise.resolve();const n=t||this._rendererAdapter.getTarget(e);return Wt((()=>{this._setViewingRenderer(e,n)}))}_isDataChannelActive(){return this._dataChannelAdapter.isActive()&&this._dataChannelAvailable}_raiseScreenSharingControlCapableEvent(e,t,i){if(this._enabled&&this._isDataChannelActive()){this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=true, capable=${e}, role=${this._role}`);const n={capable:e,id:t,disabledBySharer:i};this.event("sharingControlCapable").raise(n)}else{this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=false, capable=${e}, role=${this._role}`);const i={capable:!1,id:t};this.event("sharingControlCapable").raise(i)}}initControlForSharer(e){this._logger.info(`initControlForSharer() negotiationTag: ${e}`),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(),ap),this._initiateSharerSessionTelemetry(e)}enableControlInjector(e){this._logger.info(`enableControlInjector() trackId: ${e}`),this._canEnableGiveControl()?this._controlInjector.enableInjector(e).catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})):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 e=this._getDataSourceIdForParticipantLeg(this._controlRequest),t=this._controlRequest;this._clearControlRequest(),this._raiseControlRequestCanceled(t),this._sendControlRejectRequest(t.causeId,5,t.participant,e)}if(this._controllerParticipant){const e={inControl:!1,id:this._controllerParticipant.participant.id,terminatedReason:5};this._recordSharerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerParticipant.participant,this._controllerSourceId))),this.event("sharingControlChanged").raise(e)}this._finalizeSharerSessionTelemetry(),this._teardownSharerRemoteControl(),this._controlInjector.disableInjector().catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})),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,np.each)(this._participantSubscriptions,(e=>{e.dispose()})),this._participantSubscriptions={}}_initiateViewerSessionTelemetry(e,t,i){if(!i&&!t)return null;if(!i&&(0,np.find)(this._completedViewerSessions,(e=>t===e)))return null;if(this._currentViewerSessionTelemetry){if(this._currentViewerSessionTelemetry.negotiationTag===t)return null;this._finalizeViewerSessionTelemetry(t)}return this._logger.info(`Initiating new viewer session telemetry for ${t}`),this._currentViewerSessionTelemetry=new lp(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),t,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId(),e),this._currentViewerSessionTelemetry.callStateChanged(this._callState),this._isDataChannelActive()&&this._currentViewerSessionTelemetry.dataChannelAvailable(!0),this._currentViewerSessionTelemetry}_recordViewerSessionTelemetry(e,t=!0){this._currentViewerSessionTelemetry?e&&e(this._currentViewerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeViewerSessionTelemetry(e){if(!this._currentViewerSessionTelemetry)return;this._currentViewerSessionTelemetry.shutdownSession(e);const t=this._currentViewerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_viewer_session",t),this._currentViewerSessionTelemetry.negotiationTag&&this._completedViewerSessions.push(this._currentViewerSessionTelemetry.negotiationTag),this._currentViewerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentViewerSessionTelemetry.messagesFromUnknownSender).length&&rp.RootToolsManager.logExternalForDDL("ScreenSharingControl_viewer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentViewerSessionTelemetry=null}_initiateSharerSessionTelemetry(e){if(this._currentSharerSessionTelemetry){if(this._currentSharerSessionTelemetry.negotiationTag===e)return null;this._finalizeSharerSessionTelemetry(this._currentSharerSessionTelemetry.negotiationTag)}this._logger.info(`Initiating new sharer session telemetry for ${e}`),this._currentSharerSessionTelemetry=new cp(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),e,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId()),this._isDataChannelActive()&&this._currentSharerSessionTelemetry.dataChannelAvailable(!0)}_recordSharerSessionTelemetry(e,t=!0){this._currentSharerSessionTelemetry?e&&e(this._currentSharerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeSharerSessionTelemetry(e){if(!this._currentSharerSessionTelemetry)return;this._currentSharerSessionTelemetry.shutdownSession(e);const t=this._currentSharerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_sharer_session",t),this._currentSharerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentSharerSessionTelemetry.messagesFromUnknownSender).length&&rp.RootToolsManager.logExternalForDDL("ScreenSharingControl_sharer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentSharerSessionTelemetry=null}_recordSessionTelemetry(e){e&&(this._currentSharerSessionTelemetry&&e(this._currentSharerSessionTelemetry),this._currentViewerSessionTelemetry&&e(this._currentViewerSessionTelemetry))}_sendTelemetryEvent(e,t){this._logger.info(`Sending event ${e}: `),Object.keys(t).forEach((e=>{this._logger.info(` ${e} => ${t[e]}`)})),this._telemetryLoggers?.media?.sendEvent({eventName:e,props:t})}reportSharingSessionChangeForViewer(e,t){t&&this._initiateViewerSessionTelemetry(e,t,!1)}initControlForViewer(e,t){if(this._logger.info(`initControlForViewer(${De(e?.id)}, ${t})`),e){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=t,void(this._pendingSharer=e);this._logger.info(`role is changing from=${this._role} to=2`),this._role=2,this._sharerParticipant?this._sharerParticipant.id!==e.id&&(this._logger.info(`initControlForViewer: sharer switched, new sharer id=${De(e.id)}`),this._availableHandshakeSent=!1,4===this.controlState&&this._terminateControl(!1)):(this._logger.info(`initControlForViewer: setting sharer to id=${De(e.id)}`),this._sharerParticipant=e,this._availableHandshakeSent=!1),this._initiateViewerSessionTelemetry(e,t,!0),this._enabled&&this._isDataChannelActive()&&!this._availableHandshakeSent&&(this._resetControlState(),this._sharerParticipant=e,this._logger.info("initControlForViewer: sending Available message to sharer"),this._startAvailableHandshake())}else this._logger.warn("initControlForViewer: Sharer undefined, ignoring")}shutdownControlForViewer(e){if(this._logger.info(`shutdownControlForViewer() isViewing: ${this._isViewing()}`),this._pendingSharer=null,(!e||e.id===this._sharerParticipant?.id)&&this._isViewing()){if(this._logger.info(`shutdownControlForViewer: sharerParticipant id=${e?De(e.id):null}`),1===this.controlState){if(this._sharerParticipant){const e=this._getSharerDataSourceId();this._sendRequest({action:2,terminatedReason:6,causeId:this._controlCauseId},e)}else this._logger.warn("shutdownControlForViewer: sharer participant is null");const e={inControl:!1,id:ap,terminatedReason:6};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:e,details:""}))):this._logger.error("shutdownControlForViewer: Unexpected, no promise could be resolved, controlState=RequestSent")}else if(4===this.controlState){const e={inControl:!1,id:ap,terminatedReason:6};this._recordViewerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerSourceId,!1))),this.event("sharingControlChanged").raise(e)}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=, isCapable=false`),this._raiseScreenSharingControlCapableEvent(!1,ap)):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(e){this._clearControlRequest(),this._controlRequest=e,this._registerParticipantListener(e),3===e.participantState&&(this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${De(e.participant.id)}`),this.event("sharingIncomingControlRequest").raise(e.participant.id))}_clearControlRequest(){this._logger.info("_clearControlRequest()"),this._stopListeningToParticipantChanges(this._controlRequest),this._controlRequest=null}_stopListeningToParticipantChanges(e){this._controlRequestSubscription&&(this._logger.info(`_stopListeningToParticipantChanges: stopping tracking changes for ${De(e.participant.id)}`),this._controlRequestSubscription.dispose(),this._controlRequestSubscription=null)}_registerParticipantListener(e){this._logger.info(`_registerParticipantListener: tracking changes for ${De(e.participant.id)}`),this._logger.info(`request.participantState: ${e.participantState} | request.participant.state: ${e.participant.state}`),this._controlRequestSubscription=e.participant.changed((()=>{if(e.participant.state!==e.participantState)switch(this._logger.info(`request.participantState about to changed from: ${e.participantState} to: ${e.participant.state}`),e.participantState=e.participant.state,e.participantState){case 3:this.event("sharingIncomingControlRequest").raise(e.participant.id),this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${De(e.participant.id)}`);break;case 0:case 5:case 4:this.denyControlRequest().catch((e=>{this._logger.info(`It is ok if denyControlRequest rejects here as screensharing may have just been stopped. Err: ${e}`)})),this._logger.info(`_registerParticipantListener: participant ${De(e.participant.id)} is no longer connected. resetting`),this._clearControlRequest(),this._raiseControlRequestCanceled(e);break;case 1:case 2:case 6:case 7:this._logger.info(`participantState: ${e.participantState}, participantId: ${De(e.participant.id)}`);break;default:this._logger.error(`_registerParticipantListener: Unexpected participantState ${e.participantState} unhandled`)}}))}_resetControllerParticipant(e){this._controllerParticipantSubscription&&(this._logger.info(`_resetControllerParticipant: stopping tracking changes for ${De(this._controllerParticipant.participant.id)}`),this._controllerParticipantSubscription.dispose(),this._controllerParticipantSubscription=null),e&&(this._logger.info(`_resetControllerParticipant: tracking changes for ${De(e.participant.id)}`),this._controllerParticipantSubscription=e.participant.changed((()=>{3!==e.participant.state&&this.handleParticipantRemoved(e.participant.id)}))),this._controlCauseId=e?.causeId??null,this._controllerParticipant=e}handleParticipantRemoved(e){if(this._participantSubscriptions[e]&&(this._logger.info(`handleParticipantRemoved(): Stopping tracking state changes for ${De(e)}`),this._participantSubscriptions[e].dispose(),delete this._participantSubscriptions[e]),this._isSharing()){if(this._controllerParticipant&&this._controllerParticipant.participant.id===e){this._logger.info("handleParticipantRemoved: controller left call, tearing down control session"),this._teardownSharerRemoteControl(),this.controlState=0;const t=5;this._recordSharerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,t,this._controllerParticipant.participant,this._controllerSourceId,!0))),this._resetControllerParticipant();const i={inControl:!1,id:e,terminatedReason:t};this.event("sharingControlChanged").raise(i)}this._raiseScreenSharingControlCapableEvent(!1,e)}else if(this._sharerParticipant&&this._sharerParticipant.id===e&&4===this.controlState){this._logger.info("handleParticipantRemoved: sharer left call, tearing down control session"),this._teardownViewerRemoteControl(),this.controlState=0;const e={inControl:!1,id:ap,terminatedReason:6};this.event("sharingControlChanged").raise(e)}}callStateChanged(e){this._callState=e,this._recordSessionTelemetry((t=>t.callStateChanged(e))),this.isScreenSharingControlEnabled()&&this._handleCallState(e)}setIsEscalationInProgress(e){this.isEscalationInProgress=e}_getHandshakeDelay(){if(!this._config.handshakeSendDelay?.minParticipantThreshold)return 0;let e=0;if(this._call.participants.length>=this._config.handshakeSendDelay.minParticipantThreshold)for(const t of this._call.participants)t.endpoints?.endpointDetails.some((e=>"interactive"===e.appliedInteractivityLevel))&&e++;if(e<=this._config.handshakeSendDelay.minParticipantThreshold)return 0;const t=Math.ceil((e-this._config.handshakeSendDelay.minParticipantThreshold)/this._config.handshakeSendDelay.increaseEveryN);return Math.min(this._config.handshakeSendDelay.maxDelay,t*this._config.handshakeSendDelay.delayPerN)}_handleCallState(e){switch(e){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(e,t){null!==this._controlCapturer&&this._controlCapturer.updateVideoSize(e,t)}_onRenderStarted(){const e={action:11,terminatedReason:0};if(this._sharerParticipant){const t=this._getSharerDataSourceId();this._sendRequest(e,t)}else this._logger.error("Attempted to send sharing rendered message to null sharerParticipant")}_setViewingRenderer(e,t){try{this._screenSharingVideoRenderer=e,this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeVideoSizeChangedEvent(this._screenSharingVideoRenderer,((e,t)=>{this._videoSizeChanged(e,t)}))),this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeRenderStartedEvent(this._screenSharingVideoRenderer,(()=>{this._onRenderStarted()})));let i=1;e.streamSize&&e.streamSize.width>0&&e.streamSize.height>0&&(i=e.streamSize.width/e.streamSize.height),this._controlCapturer=new ip.SlimCoreElectronControlCapturer(this._logger,t,!0,i),4===this.controlState?(this._logger.info("_setViewingRenderer: detected local state is controlling"),this._setupViewerRemoteControl()):this._teardownViewerRemoteControl()}catch(e){this._logger.error(`_setViewingRenderer: unable to set _screenSharingVideoRenderer error=${e}`)}}_onDataChannelStatusChanged(e){this._logger.info(`_onDataChannelStatusChanged(): Data channel status=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e?this._dataChannelAvailable||(this._dataChannelAvailable=!0,this._recordSessionTelemetry((e=>e.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,ap)))):this._dataChannelAvailable&&(this._recordSessionTelemetry((e=>e.dataChannelAvailable(!1))),this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(3),this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!1,ap))}_isSharing(){return 1===this._role}_isViewing(){return 2===this._role}_handleAvailableRequest(e,t,i){if(this._isSharing())return this._enabled&&this._availableAckEnabled&&this._canEnableGiveControl()?t?.id?void(this._allowControlForUser&&"function"==typeof this._allowControlForUser?this._allowControlForUser(t).then((n=>{n?this._acceptAvailableRequest(e.handshakeId,t,i):this._rejectAvailableRequest(e.handshakeId,i,1)})):this._acceptAvailableRequest(e.handshakeId,t,i)):(this._logger.info("Unknown sender. Rejecting available ack"),void this._rejectAvailableRequest(e.handshakeId,i,10)):(this._logger.info(`Rejecting available ack - enabled=${this._enabled}, availableAck=${this._availableAckEnabled}, controlInjector=${this._canEnableGiveControl()}`),void this._rejectAvailableRequest(e.handshakeId,i,9));this._logger.warn(`Ignoring available request since role=${this._role} is not sharing. Expecting for viewer side retries`)}_acceptAvailableRequest(e,t,i){this._raiseScreenSharingControlCapableEvent(!0,t.id),this._participantSubscriptions[t.id]||(this._logger.info(`Tracking participant status for ${De(t.id)}`),this._participantSubscriptions[t.id]=t.changed((()=>{3!==t.state&&(this._logger.info(`Participant ${De(t.id)} is not connected. removing`),this.handleParticipantRemoved(t.id))}))),this._logger.info(`Acking Available for handShake:${i}:${e}`),this.event("controlAvailableHandshake").raise(e,i,3),this._sendRequest({action:9,terminatedReason:0,handshakeId:e},i)}_rejectAvailableRequest(e,t,i){this._logger.info(`Rejecting Available for handShake:${t}:${e}`),this.event("controlAvailableHandshake").raise(e,t,7,this._getAvailableHandshakeTerminatedFromControlTerminated(i)),this._sendRequest({action:10,terminatedReason:i,handshakeId:e},t)}processProtocolMessage(e,t,i,n){return Wt((()=>{this._processProtocolMessage(e,t,i,n)}))}_raiseControlRequestCanceled(e){this.event("sharingIncomingControlRequestCancelled").raise(e.participant.id)}_handleControlRequest(e,t,i,n){this._recordSharerSessionTelemetry((i=>i.controlRequest(n,e,t))),this._enabled?this._controlRequest?(this._logger.warn("Sharer is already processing a control request...rejecting new requests"),this._sendControlRejectRequest(n,3,e,t)):this._controllerParticipant&&this._controllerParticipant.participant===e?this._controllerParticipant.participantId&&this._controllerParticipant.participantId!==i?(this._logger.warn(`rejecting control request from second endpoint. participantId: ${i}`),this._sendControlRejectRequest(n,3,e,t)):(this._logger.warn("Got control request for someone already in control"),this._resetControllerParticipant(),this._resetControlRequest({participant:e,participantState:e.state,participantId:i,causeId:n})):e?(this._logger.info(`resetControlRequest for participantId: ${i}`),this._resetControlRequest({participant:e,participantState:e.state,participantId:i,causeId:n})):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(n,9,e,t))}_handleAcceptRequest(e,t){if(1===this.controlState){const i=this._sendRequest({action:5,terminatedReason:0},t);this._logger.info(`_handleAcceptRequest controlMessage.action: ${hp(e.action)} _sendRequest isSent: ${i}`),i?(this._setupViewerRemoteControl(),this.controlState=4,this._requestControlPromise?this._requestControlPromise.resolve():this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${hp(e.action)}`),this._recordViewerSessionTelemetry((e=>e.requestControlAccepted(this._controlCauseId,t)))):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=${gp(this.controlState)} action=${hp(e.action)}`),this._cancelRequestControlTimer()}else this._logger.warn(`AcceptRequest message received in controlState=${gp(this.controlState)}`)}_handleRejectRequest(e,t){if(1===this.controlState){this._logger.info(`_handleRejectRequest: controlState: ${gp(this.controlState)}, about to be changed to: ${gp(0)}`),this.controlState=0;const i={inControl:!1,id:ap,terminatedReason:e.terminatedReason};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:i,details:""}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${hp(e.action)}`),this._recordViewerSessionTelemetry((i=>i.requestControlRejected(this._controlCauseId,e.terminatedReason,t))),this._cancelRequestControlTimer(),this._controlCauseId=null}else this._logger.warn(`RejectRequest message received in controlState=${gp(this.controlState)} reason=${e.terminatedReason}`)}_handleCancelControlRequest(e,t){if(this._logger.info(`_handleCancelControlRequest action=${hp(e.action)} sender=${t}, controlRequest participantId: ${this._controlRequest.participantId}, controlRequest participantState: ${this._controlRequest.participantState}:`),this._controlRequest){const i=this._controlRequest;this._logger.info(`_handleCancelControlRequest action=${hp(e.action)} sender=${t}, about to raise: _raiseControlRequestCanceled state: ${this._controlRequest.participantState} `),this._recordSharerSessionTelemetry((n=>n.controlRequestRejected(e.causeId,e.terminatedReason,i.participant,t))),this._clearControlRequest(),this._raiseControlRequestCanceled(i)}}_handleGiveControl(e,t,i){const n=this._sendRequest({action:5,terminatedReason:0},t);if(this._logger.info(`_handleGiveControl: controlMessage.action: ${hp(e.action)} _sendRequest isSent: ${n}`),this._controlCauseId=e.causeId,n){this._setupViewerRemoteControl(),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(4)}`),this.controlState=4,this._recordViewerSessionTelemetry((e=>e.controlGiven(this._controlCauseId,t)));const i={inControl:!0,id:ap,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(i)}}_handleAck(e,t,i){if(2===this.controlState)if(this._controllerParticipant&&this._controllerParticipant.participant.id===t.id){const t=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);i!==t&&this._logger.warn(`acknowledging source id: ${i} does not match requesting source id: ${t}`),this._logger.info(`Setting up remote control for controller source id=${t}`),this._setupSharerRemoteControl(t),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(3)}`),this.controlState=3;const n={inControl:!0,id:this._controllerParticipant.participant.id,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(n),this._grantControlPromise?(this._grantControlPromise.resolve(),this._cancelGrantControlTimer(),this._recordSharerSessionTelemetry((e=>e.giveControlSucceeded(this._controlCauseId,this._controllerParticipant.participant,t)))):this._acceptControlPromise?(this._acceptControlPromise.resolve(),this._cancelAcceptControlTimer(),this._recordSharerSessionTelemetry((e=>e.controlRequestAccepted(this._controlCauseId,this._controllerParticipant.participant,t)))):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForControlAck action=${hp(e.action)}`)}else t?this._logger.warn(`Ignoring ack from participant that does not match controller id=${De(t.id)}`):this._logger.warn(`Ignoring ack from null participant source id=${i}`);else 5===this.controlState?(this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(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=${hp(e.action)}`)):this._logger.warn(`Unexpected ack in control controlState=${gp(this.controlState)}`)}_handleTerminate(e,t,i){let n;this._isViewing()?(this._teardownViewerRemoteControl(),n=ap,this._recordViewerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,i,!0)))):(this._teardownSharerRemoteControl(),t?n=t.id:this._logger.error("Got terminate message but could not find a sender participant!"),this._recordSharerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerParticipant.participant,i,!0)))),this._logger.info(`controlMessage action: ${hp(e.action)}, controllerId: ${n}`),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(0)}`),this.controlState=0,this._resetControllerParticipant();const r={inControl:!1,id:n,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(r),8===e.action&&this._sendRequest({action:5,terminatedReason:0},i)}_handleAvailableAck(e){this._terminateAvailableHandshake&&(this._logger.info(`_handleAvailableAck: terminate available handshake reason: 1,handshakeId: ${e.handshakeId}`),this._terminateAvailableHandshake(1,e.handshakeId)),2===this._role?this._raiseScreenSharingControlCapableEvent(!0,ap):this._logger.info(`Ignoring AvailableAck as viewer session is not initialized, role: ${this._role}`)}_handleAvailableNack(e){this._logger.info(`_handleAvailableNack: action=${hp(e.action)} terminate reason: ${pp(e.terminatedReason)}`),this._viewerSessionLastTerminatedReason=e.terminatedReason,10!==e.terminatedReason?(this._terminateAvailableHandshake&&(this._terminateAvailableHandshake(this._getAvailableHandshakeTerminatedFromControlTerminated(e.terminatedReason),e.handshakeId),this._logger.info(`_handleAvailableNack: terminateAvailableHandshake reason=${pp(e.terminatedReason)}`)),1===e.terminatedReason?(this._logger.warn("_handleAvailableNack: control terminate reason: SharerDenied"),this._raiseScreenSharingControlCapableEvent(!0,ap,!0)):this._raiseScreenSharingControlCapableEvent(!1,ap)):this._logger.warn("_handleAvailableNack: control terminate reason: UnknownSender")}_handleRenderedAtViewer(e,t){this._raiseRenderedAtViewer&&(t?(this._logger.info(`raiseRenderedAtViewer senderId=${De(t.id)}, action=${hp(e.action)}`),this._raiseRenderedAtViewer(t.id)):this._logger.error("Got RenderedAtViewer message but could not find a sender participant!"))}_processProtocolMessage(e,t,i,n){let r;this._recordSessionTelemetry((e=>e.recordProtocolMessage(t,n)));try{r=JSON.parse(e)}catch(e){return void this._logger.error("Error parsing controlMessage")}switch(t||this._logger.warn(`protocol message from unknown sender with sourceId=${n}`),this._logger.info(`_processProtocolMessage action=${hp(r.action)}, sourceId=${n}`),r.action){case 0:this._handleAvailableRequest(r,t,n);break;case 1:this._handleControlRequest(t,n,i,r.causeId);break;case 3:this._handleAcceptRequest(r,n);break;case 4:this._handleRejectRequest(r,n);break;case 2:this._handleCancelControlRequest(r,n);break;case 6:this._handleGiveControl(r,n,t);break;case 5:this._handleAck(r,t,n);break;case 8:case 7:this._handleTerminate(r,t,n);break;case 9:this._handleAvailableAck(r);break;case 10:this._handleAvailableNack(r);break;case 11:this._handleRenderedAtViewer(r,t);break;default:this._logger.error(`Unknown request action received on control protocol data sink, action=${hp(r.action)}`)}}_getAvailableHandshakeTerminatedFromControlTerminated(e){switch(e){case 10:return 6;case 1:return 7;default:return 0}}_sendRequest(e,t){if(t<0)return this._logger.warn(`Unexpected: invalid sourceID=${t}`),!1;this._logger.info(`_sendRequest() action=${hp(e.action)} recipient sourceid=${t}`);const i={type:0,message:JSON.stringify(e)},n=[t];return this._dataChannelAdapter.sendProtocolMessage(function(e){const t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}(JSON.stringify(i)),n),!0}async processControlMessage(e,t){if(t===this._controllerSourceId){if(3===this.controlState)return this._processControlMessage(e,t);this._logger.debug(`Ignoring control message, wrong controlState. Expected: RemoteControlling, got: ${gp(this.controlState)}`)}else this._logger.debug(`Ignoring control message, wrong sourceId. Expected: ${t}, got: ${this._controllerSourceId}`)}_processControlMessage(e,t){return this._controlInjector.injectRawInput(e,t)}_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(e){this._logger.info(`_setupSharerRemoteControl() sourceId=${e}`),this._controllerSourceId=e,this._controlInjector.showVirtualCursor(e).catch((t=>{const i={reason:3,detail:JSON.stringify({sourceId:e,errorMsg:t})};this.event("sharingControlError").raise(i)}))}_teardownSharerRemoteControl(){this._logger.info("_teardownSharerRemoteControl()"),this._controllerSourceId=null,this._controlInjector.showVirtualCursor(0).catch((e=>{const t={reason:3,detail:JSON.stringify({sourceId:0,errorMsg:e})};this.event("sharingControlError").raise(t)}))}_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(e,t){if(t)switch(e){case"mouseControlEvent":this._sendControlEvent(Vg.encodeMouseEvent(t));break;case"keyboardControlEvent":this._sendControlEvent(Vg.encodeKeyboardEvent(t));break;default:return void this._logger.error("sendRemoteControlEvent: Invalid type=",e)}else this._logger.error("sendRemoteControlEvent: Invalid argument.")}_sendControlEvent(e){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: ${gp(this.controlState)})`);const t=[this._getSharerDataSourceId()];this._dataChannelAdapter.sendControlMessage(e,t)}_setCapturerMode(e){this._logger.info(`_setCapturerMode() capturerMode=${e}`),this._controlCapturer?(this._controlCapturer.setCaptureMode(e),this._clearCapturerEventSubscriptions(),1===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{0===e&&this.event("sharingRendererClicked").raise()})):2===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})):3===e&&(this._mouseControlEventSubscription=this._controlCapturer.on("mouseControlEvent",(e=>{this._sendControlEvent(Vg.encodeMouseEvent(e))})),this._keyboardControlEventSubscription=this._controlCapturer.on("keyboardControlEvent",(e=>{this._sendControlEvent(Vg.encodeKeyboardEvent(e))})),this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})))):this._logger.info("_controlCapturer not set, relying on external controlCapturer")}setPointerImage(e,t){return this._logger.warn("setPointerImage is deprecated. Use setLocalPointerImage or setRemotePointerImage"),e?this.setRemotePointerImage(e,t):this.setLocalPointerImage(t)}setLocalPointerImage(e){return 0===e.length?Promise.reject(new Error("setLocalPointerImage invalid image length")):this._setPointerImage(0,e)}async setRemotePointerImage(e,t){if(!e)throw new Error("setRemotePointerImage participant is null");if(0===t.length)throw new Error("setRemotePointerImage invalid image length");const i=this._getParticipantsDataSourceIds(e);if(0===i.length)throw new Error("setRemotePointerImage unable to map participant to sourceIds");this._logger.info(`set pointer image for ${i.length} sources`);for(const e of i)await this._setPointerImage(e,t)}_setPointerImage(e,t){return this._isSharing()||this._logger.warn("_setPointerImage called when not sharing"),this._controlInjector.setPointerImage(e,t)}startPointerMode(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`startPointerMode called in bad control controlState=${gp(this.controlState)}`)):this._isViewing()?Wt((()=>{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=${gp(this.controlState)}`)):this._isViewing()?Wt((()=>{this._setCapturerMode(1)})):Promise.reject(new Error("stopPointerMode when not viewing"))}_startAvailableHandshake(){const e=this._getSharerDataSourceId(),t=mi(),i=this._getHandshakeDelay(),n=Math.floor(Math.random()*i);if(this._logger.info(`_startAvailableHandshake() - handshakeId: ${e}:${t} ${n>0?`delay: ${n}ms maxDelay: ${i}ms`:""}}`),this._terminateAvailableHandshake&&(this._logger.warn("Replacing existing availble handshake"),this._terminateAvailableHandshake(4)),this._recordViewerSessionTelemetry((e=>e.startHandshake(t))),e<0)this._logger.warn(`_startAvailableHandshake() - sharer: ${De(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(t);else{const r=()=>{this.event("controlAvailableHandshake").raise(t,e,1),this._sendRequest({action:0,terminatedReason:0,handshakeId:t},e)||this._logger.error("Failed to send Available message to sharer, will retry after backoff"),this._waitForAvailableAck(t)};n>0?(this._delayedSendHandshakeTimer=window.setTimeout(r,n),this._recordViewerSessionTelemetry((e=>e.delayHandshakeSending(t,n,i)))):r()}this._availableHandshakeSent=!0,this._terminateAvailableHandshake=(i=0,n)=>{this._logger.info(`_terminateAvailableHandshake() - handshakeId: ${e}:${t}, status: ${i}`),1===i?this._recordViewerSessionTelemetry((e=>e.handshakeSucceeded(t,this._retryAttempt))):(this._logger.error(`GTC handshake terminated with code ${i}, last terminated reason: ${pp(this._viewerSessionLastTerminatedReason)}`),rp.RootToolsManager.logExternalForDDL(`GTC handshake terminated with code ${i},`,this._viewerSessionLastTerminatedReason.toString()),this._recordViewerSessionTelemetry((e=>e.handshakeFailed(t,this._retryAttempt,i)))),this._terminateAvailableHandshake=null,this.event("controlAvailableHandshake").raise(t,e,1===i?5:6,i),n&&n!==t&&this._logger.warn(`AvailableSeries: Got handshake from another series - expected: ${t}, received: ${n}`),this._availableAckTimer&&(clearTimeout(this._availableAckTimer),this._availableAckTimer=null),this._delayedSendHandshakeTimer&&(clearTimeout(this._delayedSendHandshakeTimer),this._delayedSendHandshakeTimer=null),this._retryAttempt=0}}_waitForAvailableAck(e){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 t=this._getSharerDataSourceId();if(this._retryAttempt<=6)t>=0?(this._logger.info(`Re-sending Available message handshakeId: ${t}:${e}`),this.event("controlAvailableHandshake").raise(e,t,2),this._sendRequest({action:0,terminatedReason:0,handshakeId:e},t)):this._logger.warn(`_waitForAvailableAck() - sharer: ${De(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(e);else{if(this._logger.error("Reached Available retry limit! Control capability will be false"),this._terminateAvailableHandshake)this._terminateAvailableHandshake(5);else{const e={reason:4,detail:JSON.stringify({sourceId:t,errorMsg:`Timed out after ${this._retryAttempt} tries`})};this.event("sharingControlError").raise(e)}this._raiseScreenSharingControlCapableEvent(!1,ap)}}),2e3*++this._retryAttempt)}requestControl(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`requestControl called in bad controlState=${gp(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 e=this._controlCauseId=be();this._logger.info(`_requestControl(), controlState: ${this.controlState}, controlCauseId: ${e}`),this._requestControlPromise=new Kt;const t=()=>{this._requestControlPromise=null};this._requestControlPromise.promise.then(t,t);const i=this._getSharerDataSourceId();if(!this._sendRequest({action:1,terminatedReason:0,causeId:e},i)){const e={inControl:!1,id:ap,terminatedReason:7};return this._requestControlPromise.reject(new Error),this._logger.error("_requestControl(): failed to send the request."),Promise.reject(new Error(JSON.stringify({controlInfo:e,details:""})))}return this._recordViewerSessionTelemetry((t=>t.requestControl(e,i))),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:e},i)||this._logger.error("Failed to send the cancel control request");const t={inControl:!1,id:ap,terminatedReason:2};this._recordViewerSessionTelemetry((n=>n.requestControlRejected(e,t.terminatedReason,i))),this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:t,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=${gp(this.controlState)}`);this._requestControlTimer=null}),3e4),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=${gp(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 e=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},e))return Promise.reject(new Error("Failed to send cancel control request"));{const t={inControl:!1,id:ap,terminatedReason:8};this._recordViewerSessionTelemetry((i=>i.requestControlRejected(this._controlCauseId,t.terminatedReason,e))),this._controlCauseId=null,this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:t,details:""})))}return new Promise(((e,t)=>{e()}))}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 Kt;const e=()=>{this._acceptControlPromise=null};if(this._acceptControlPromise.promise.then(e,e),this._controllerParticipant){this._logger.warn("_acceptControlRequest called while another participant already has control - terminating control");try{await this._terminateControl(!1)}catch(t){this._logger.error("_acceptControlRequest: failed to gracefully terminate control of previous controller",t)}this._resetControllerParticipant()}const t=this._getDataSourceIdForParticipantLeg(this._controlRequest),i=this._controlRequest.participant.id,n=this._controlRequest.causeId,r=this._controlRequest.participant;return this._sendControlAcceptRequest(n,r,t)?(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:n},t)||this._logger.error("Failed to send the TerminateNoAck request");const e={inControl:!1,id:i,terminatedReason:4};this._recordSharerSessionTelemetry((i=>i.controlRequestRejected(n,e.terminatedReason,r,t))),this.event("sharingControlChanged").raise(e),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=${gp(this.controlState)}`);this._acceptControlTimer=null}),sp),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(e,t,i){const n=this._sendRequest({action:3,terminatedReason:0,causeId:e},i);return this._recordSharerSessionTelemetry((n=>n.controlRequestAccept(e,t,i))),n}_sendControlRejectRequest(e,t,i,n){const r=this._sendRequest({action:4,terminatedReason:t},n);return this._recordSharerSessionTelemetry((r=>r.controlRequestRejected(e,t,i,n))),r}_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 e=this._getDataSourceIdForParticipantLeg(this._controlRequest),t=this._sendControlRejectRequest(this._controlRequest.causeId,1,this._controlRequest.participant,e);return this._clearControlRequest(),t?Promise.resolve():Promise.reject(new Error("Failed to send the deny control requst"))}grantControl(e){return this._enabled?this._isDataChannelActive()?this._controlRequest?Promise.reject(new Error("grantControl called while control request pending")):this._isSharing()?e?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(e):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(e){this._logger.info("_grantControl()"),this._grantControlPromise=new Kt;const t=()=>{this._grantControlPromise=null};if(this._grantControlPromise.promise.then(t,t),3===this.controlState){if(this._controllerParticipant.participant?.id===e.id)return this._logger.warn("_grantControl called for participant who already has control"),this._grantControlPromise.resolve(),new Promise(((e,t)=>{e()}));{this._logger.warn("_grantControl called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const e=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},e)||this._logger.error("Failed to send the terminateNoAck request")}}const i=this._mapParticipantToSourceId(e),n=be(),r=this._sendRequest({action:6,terminatedReason:0,causeId:n},i);if(this._recordSharerSessionTelemetry((t=>t.giveControl(n,e,i))),!r)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 s=this._getParticipantIdForDataSourceId(e,i);return this._resetControllerParticipant({participant:e,participantState:e.state,participantId:s,causeId:n}),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},i)||this._logger.error("Failed to send the terminateNoAck request"),this._recordSharerSessionTelemetry((t=>t.giveControlFailed(n,4,e,i))),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=${gp(this.controlState)}`),this._grantControlTimer=null}),sp),this._grantControlPromise.promise}_cancelGrantControlTimer(){this._grantControlTimer&&(this._grantControlPromise&&this._grantControlPromise.reject(new Error("cancelled by _cancelGrantControlTimer")),clearTimeout(this._grantControlTimer),this._grantControlTimer=null)}_mapParticipantToSourceId(e){return this._dataChannelAdapter.isActive()?Ud(e,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getParticipantsDataSourceIds(e){const t=[];try{if(e?.endpoints?.endpointDetails){if(1===e.endpoints.endpointDetails.length){const i=e.endpoints.endpointDetails[0];if(!i?.mediaStreams)return t.push(Ur),t}for(const i of e.endpoints.endpointDetails)if(i?.mediaStreams)for(const e of i.mediaStreams)if(3===Nd(e.type)){if(t.push(e.sourceId),t.length>=8)return this._logger.error("Excessive amount of data streams"),t;break}}}catch(e){this._logger.error(`_getParticipantsDataSourceIds caught exception error=${e}`)}return t}_getParticipantIdForDataSourceId(e,t){return Bd(e,3,t)}_getDataSourceIdForParticipantId(e,t){return this._dataChannelAdapter.isActive()?function(e,t){if(!e?.endpoints)return-1;const i=e.endpoints.endpointDetails.find((e=>e?.participantId===t));if(!i?.mediaStreams)return Ud(e,3);const n=i.mediaStreams.find((({type:e})=>3===Nd(e)));return n?n.sourceId:-1}(e,t):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getDataSourceIdForParticipantLeg(e){return this._getDataSourceIdForParticipantId(e.participant,e.participantId)}_getSharerDataSourceId(){const e=Hd(this._sharerParticipant);return e?this._getDataSourceIdForParticipantId(this._sharerParticipant,e):(this._logger.warn("Unable to identify the sharer participantId, falling back to first data channel"),this._mapParticipantToSourceId(this._sharerParticipant))}getLocalEndpointDataSourceId(){const e=Ld(this._call,this._participantId);if(e?.mediaStreams){const t=e.mediaStreams.find((({type:e})=>3===Nd(e)));return t?.sourceId??-1}return-1}terminateControl(e){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,e)}_terminateControl(e,t){this._logger.info("_terminateControl()"),this._terminateControlPromise=new Kt;const i=()=>{this._terminateControlPromise=null};this._terminateControlPromise.promise.then(i,i);let n=0;const r=e?8:7;let s,a;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(),n=t??6,s=this._getSharerDataSourceId(),this._recordViewerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,n,s))),a=ap,this._logger.info(`Terminating remote control reason: ${pp(n)}, recipient: ${s}, controllerId: ${a}`)}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(),n=t??5,s=this._getDataSourceIdForParticipantLeg(this._controllerParticipant),this._recordSharerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,n,this._controllerParticipant.participant,s))),a=De(this._controllerParticipant.participant.id),this._logger.info(`Terminating control on the sharer side, reason: ${pp(n)}, recipient: ${s}, controllerId: ${a}`)}const o={action:r,terminatedReason:n};if(!this._sendRequest(o,s)){if(e)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=e?5:0;const l={inControl:!1,id:a,terminatedReason:o.terminatedReason};return this._logger.info(`raising event sharingControlChanged reason=${pp(l.terminatedReason)} controlState=${gp(this.controlState)}`),this.event("sharingControlChanged").raise(l),e?(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},s)||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=${gp(this.controlState)}`),this._terminateControlTimer=null}),sp),this._terminateControlPromise.promise):(this._terminateControlPromise.resolve(),new Promise(((e,t)=>{e()})))}_cancelTerminateControlTimer(){this._terminateControlTimer&&(this._terminateControlPromise&&this._terminateControlPromise.reject(new Error("cancelled by _cancelTerminateControlTimer")),clearTimeout(this._terminateControlTimer),this._terminateControlTimer=null,this._logger.info("_cancelTerminateControlTimer()"))}_disposeControlCapturer(e=be()){this._logger.info(`_disposeControlCapturer causeId: ${e}`),this._clearCapturerEventSubscriptions(),this._controlCapturer&&(this._controlCapturer.dispose(e),this._controlCapturer=null)}dispose(e){this._logger.info(`dispose causeId: ${e}`),this._dataChannelAdapter.dispose(e),this._resetControlState(),this._disposeRenderer(e),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer(),this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._call=null,this._resetParticipantSubscriptions(),this._finalizeViewerSessionTelemetry(),this._finalizeSharerSessionTelemetry(),super.dispose(e)}};function up(e){switch(e){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 hp(e){switch(e){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 gp(e){switch(e){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 pp(e){switch(e){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 mp(e){switch(e){case 1:return"Sharer";case 2:return"Viewer";default:return"Unknown"}}var fp=(e=>(e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT",e[e.MIDDLE=2]="MIDDLE",e[e.BACK=3]="BACK",e[e.FORWARD=4]="FORWARD",e))(fp||{}),vp=(e=>(e[e.SCAN_CODE=0]="SCAN_CODE",e[e.VIRTUAL_KEY=1]="VIRTUAL_KEY",e[e.RECOGNITION_INPUT=2]="RECOGNITION_INPUT",e))(vp||{}),Sp=class{constructor(e){this.logger=e}toEdgeControlMouseEvent(e){let t;switch(e.type){case 0:return{event:this.toMouseMoveEvent(e),apiName:"injectMouseMoveEvent"};case 1:return{event:this.toMouseWheelEvent(e),apiName:"injectMouseWheelEvent"};case 2:return{event:this.toMouseButtonPressedEvent(e),apiName:"injectMouseButtonEvent"};default:throw t=`Uncovered mouse control event type. Event: ${e}`,this.logger.error(t),Error(t)}}toEdgeControlKeyboardEvent(e){return{event:{repeat:e.repeat,keyUp:e.keyUp,codeType:vp[e.codeType],keyCode:e.code},apiName:"injectKeyEvent"}}toMouseMoveEvent(e){return{xPos:e.xPos,yPos:e.yPos}}toMouseWheelEvent(e){return{wheelButtonDown:e.wheelButtonDown,wheelRotation:e.wheelRotation}}toMouseButtonPressedEvent(e){return{xPos:e.xPos,yPos:e.yPos,button:fp[e.buttonType],buttonDown:e.buttonDown}}};async function yp(e,t,i){return new Promise(((n,r)=>{const s=Buffer.from(e,"base64"),a=document.createElement("canvas").getContext("2d"),o=new Blob([s],{type:"image/png"});let l=new Image;l.onload=()=>{a.drawImage(l,0,0,l.width,l.height,0,0,t,i);const e=a.getImageData(0,0,t,i);window.URL.revokeObjectURL(l.src),l=null,n(Array.from(e.data))},l.onerror=e=>{r(e)},l.src=window.URL.createObjectURL(o)}))}var Cp,Tp,Ep="ncbjelpjchkpbikbpkcchkhkblodoama",bp=class{constructor(e){this.logger=e}async sendInjectInputEventMessage(e,t){return this.logger.info("EdgeControlInjectorApi - sendInjectInputEventMessage"),new Promise(((i,n)=>{window.top.chrome.runtime.sendMessage(Ep,{api:e,deviceId:this.virtualInputDeviceId,event:t},(e=>{e.error?n(e.error.message):i(0)}))}))}async createInputDeviceId(e,t,i){this.virtualInputDeviceId&&this.logger.warn("EdgeControlInjectorApi - createInputDeviceId virtual input already exists.");try{this.virtualInputDeviceId=await this.sendCreateInputDeviceMessage(e,i)}catch(e){this.logger.error(`EdgeControlInjectorApi - createInputDevice failed, error: ${JSON.stringify(e)}`),t()}}async sendSetLocalUserAvatarMessage(e){const t=await this.generateAvatarBitmap(e);return new Promise(((e,i)=>{const n=window.top;t&&n.chrome.runtime.sendMessage(Ep,{api:"setLocalUserAvatar",avatarBitmap:t},(t=>{t.error?i(t.error.message):e()}))}))}async sendCloseVirtualInputDeviceMessage(){const e=this.virtualInputDeviceId;return e?(this.logger.info("EdgeControlInjectorApi - sendCloseVirtualInputDeviceMessage called"),new Promise(((t,i)=>{const n=window.top;n.chrome.runtime.sendMessage(Ep,{api:"closeInputDevice",deviceId:e},(e=>{e?e.error?i(e.error.message):(this.virtualInputDeviceId=null,t(e.deviceId)):i(n.chrome.runtime.lastError.message)}))}))):(this.logger.info("EdgeControlInjectorApi - VirtualInputDevice does not exists, nothing to close."),Promise.resolve())}async sendCreateInputDeviceMessage(e,t){this.logger.info("EdgeControlInjectorApi - sendCreateInputDeviceMessage called");const i=await this.generateAvatarBitmap(t);return new Promise(((t,n)=>{const r=window.top,s=e=>{e?e.deviceId?t(e.deviceId):e.error?n(e.error.message):n("Error: Unexpected response from API"):n(r.chrome.runtime.lastError.message)};i?r.chrome.runtime.sendMessage(Ep,{api:"createInputDevice",mediaStreamTrackId:e,avatarBitmap:i},s):r.chrome.runtime.sendMessage(Ep,{api:"createInputDevice",mediaStreamTrackId:e},s)}))}async generateAvatarBitmap(e){if(!e)return null;try{const t=32;return{width:t,height:t,data:await yp(e,t,t)}}catch(e){return this.logger.error(`EdgeControlInjectorApi - generateAvatarBitmap error: ${JSON.stringify(e)}, continue without avatar.`),null}}},_p=class{constructor(e,t,i){this.logger=e,this.sharingTrackId=t,this.onInitErrorCallback=i,this.images=new Map,this.controlEventConverter=new Sp(e),this.edgeApi=new bp(this.logger)}showVirtualCursor(e,t){if(this.logger.info(`EdgeControlInjector - showVirtualCursor, id: ${e} sharingTrackId: ${this.sharingTrackId}`),t){this.edgeApi.createInputDeviceId(this.sharingTrackId,this.onInitErrorCallback,this.images[e]);const t=this.images[0];t?this.edgeApi.sendSetLocalUserAvatarMessage(t):this.logger.error("EdgeControllerInjector - local avatar is missing, continue without local avatar")}else this.edgeApi.sendCloseVirtualInputDeviceMessage()}setAvatar(e,t){this.logger.info(`${e} EdgeControlInjector - setAvatar, id: ${e}, data: ${JSON.stringify(t)}`),this.images[e]=t}async injectMouseEvent(e,t){this.logger.info(`${e} EdgeControlInjector - injectMouseEvent ${JSON.stringify(t)}`);const i=this.controlEventConverter.toEdgeControlMouseEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}async injectKeyboardEvent(e,t){const i=this.controlEventConverter.toEdgeControlKeyboardEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}injectClipboardText(e,t){return this.logger.info(`${e} EdgeControlInjector - injectClipboardText is unimplemented`),Promise.resolve(0)}dispose(e){this.logger.info("EdgeControlInjector - dispose"),this.edgeApi.sendCloseVirtualInputDeviceMessage()}},Ip="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?.getUserMedia,wp=(e=>(e.AVD="43",e.Citrix="44",e.VMware="45",e))(wp||{});function Ap(){return!!Tp}function Pp(){return Tp}function Rp(){navigator.getUserMedia=function(e,t,i){return navigator.mediaDevices.getUserMedia(e).then(t).catch(i)}}"undefined"!=typeof window&&"undefined"!=typeof navigator&&(Cp=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 Mp={window:Cp},Dp=class{constructor(e){this.logger=e,this.activeSourceId=0,this.pendingPointerImages=new Map}static create(e,t){return e.config.enableGiveControl?Ap()||window.ControlInjector?new Op(t):Ot.isBrowser("EdgeAnaheim")?new kp(t):new Np(t):new Np(t)}async enableInjector(e){this.injector&&this.logger.warn("Control injector already present when enabling injector");try{this.injector=this.createInjector(e)}catch(e){throw this.logger.error(`Control injector creation failed: ${e}`),e}this.pendingPointerImages.forEach(((e,t)=>{this.injector.setAvatar(t,e)})),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(e,t){this.injector?this.injector.setAvatar(e,t):this.pendingPointerImages.set(e,t)}async showVirtualCursor(e){if(this.logger.info(`showVirtualCursor ${e} ${this.activeSourceId}`),!this.injector)throw new Error("Control injector not present");e?(this.activeSourceId&&this.injector.showVirtualCursor(this.activeSourceId,!1),this.injector.showVirtualCursor(e,!0),this.activeSourceId=e):this.activeSourceId&&(this.injector.showVirtualCursor(this.activeSourceId,!1),this.activeSourceId=0)}async injectRawInput(e,t){if(!this.injector)throw new Error("Control injector not present");const i=this.injector;return new Promise(((n,r)=>{let s,a;const o=Vg.decodeEventType(e);switch(o){case 1:s=Vg.decodeMouseEvent(e),i.injectMouseEvent(t,s).then((e=>0===e?n():r()));break;case 0:a=Vg.decodeKeyboardEvent(e),i.injectKeyboardEvent(t,a).then((e=>0===e?n():r()));break;default:this.logger.error(`Invalid event type in raw input: ${o}`),r()}}))}},kp=class extends Dp{constructor(e){super(e.createChild("EdgeControlInjector")),this.edgeVirtualInputSupported=!1,async function(e){return new Promise(((t,i)=>{e.info("EdgeControlInjectorApi - sendIsVirtualInputSupportedMessage");const n=window.top;n.chrome.runtime.sendMessage(Ep,{api:"isVirtualInputSupported"},(e=>{e?e.error?t(e.error.message):t(e):i(n.chrome.runtime.lastError?.message)}))}))}(e).then((t=>{this.edgeVirtualInputSupported=t,e.info(`Edge supports virtual input device: ${JSON.stringify(this.edgeVirtualInputSupported)}`)})).catch((t=>{e.info(`Edge IsVirtualInputSupported: ${JSON.stringify(t)}`)}))}canBeEnabled(){return this.edgeVirtualInputSupported}createInjector(e){if(!this.edgeVirtualInputSupported)return void this.logger.info("Edge doesn't support give control");const t=new _p(this.logger,e,(()=>{this.logger.error("An error occured, disabling control injector."),this.disableInjector()}));return this.logger.info("Edge ControlInjector created"),t}},Op=class extends Dp{constructor(e){super(e.createChild("WindowControlInjector"))}canBeEnabled(){return!!window.ControlInjector}createInjector(e){const t=window.ControlInjector(e);return this.logger.info("Window ControlInjector created"),t}},Np=class extends Dp{constructor(e){super(e.createChild("NoopControlInjector"))}canBeEnabled(){return!1}createInjector(){throw new Error("Control injector creation is disabled")}},Lp=class{constructor(e){this.logger=e,this.logger.info("RendererAdapter")}getTarget(e){return e.target}subscribeVideoSizeChangedEvent(e,t){const i=e;return i.streamSize&&t(i.streamSize.width,i.streamSize.height),i.renderer.on("onVideoSizeChanged",t)}subscribeRenderStartedEvent(e,t){return e.renderer.on("onVideoStarted",((e,i)=>t()))}},xp=class extends gt{constructor(e,t){super(e),this.logger=e,this._call=t}isActive(){return!(!this.protocolSendFunc||!this.controlSendFunc)}sendProtocolMessage(e,t){return this.protocolSendFunc?this.protocolSendFunc(e,t):(this.logger.error("Cannot send protocol message, ProtocolHandler hasn't started"),Promise.resolve())}sendControlMessage(e,t){return this.controlSendFunc?this.controlSendFunc(e,t):(this.logger.error("Cannot send control message, ControlHandler hasn't started"),Promise.resolve())}getProtocolHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ProtocolHandler started for ${e}`),this.protocolSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ProtocolHandler stopped for ${e}`);const t=this.isActive();this.protocolSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(1===e){const e=JSON.parse(function(e){return String.fromCharCode.apply(null,e)}(t)),n=this._call.mapDataChannelSourceIdToParticipant(i);let r;return n&&(r=Bd(n,3,i)),this.event("protocolMessage").raise(e.message,n,r,i)}}}}getControlHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ControlHandler started for ${e}`),this.controlSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ControlHandler stopped for ${e}`);const t=this.isActive();this.controlSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(2===e)return this.event("controlMessage").raise(t,i)}}}},Fp=class extends dp{constructor(e,t,i,n,r,s){const a={disableAudit:r.getEcsConfig("SkypeCalling","gtcAuditDisabled")??!1},o=r.getEcsConfig("SkypeCalling","gtcHandshakeSendDelay");if(o)try{a.handshakeSendDelay=JSON.parse(o)}catch(t){e.error(`Failed to parse ecs config gtcAvailableAckDelay: ${tt(t)}`)}super(e.createChild("ScreenSharingControl"),i,n,a),this.dataChannel=t;const l=Dp.create(s,e),c=new Lp(this._logger),d=new xp(this._logger,i);this.setAdapters(l,c,d)}setupDataHandlers(){this.dataChannel.addHandler(1,this.getProtocolHandler()),this.dataChannel.addHandler(2,this.getControlHandler())}startOrStopControlForViewer(e,t,i){if(e&&"nonInteractive"!==i?.appliedInteractivityLevel){if(t&&0===this.role){const e=t.streams[1].find((e=>e.isAvailable))?.negotiationTag;this.initControlForViewer(t,e)}}else 2===this.role&&this.shutdownControlForViewer()}getProtocolHandler(){return this._dataChannelAdapter.getProtocolHandler()}getControlHandler(){return this._dataChannelAdapter.getControlHandler()}};function Up(e){switch(e){case 1:return"specified";case 0:return"all";case 3:return"attendees";case 2:return"presenters";case 4:return"self";default:return"none"}}var Bp={};h(Bp,{addReceiveDirectionality:()=>Jp,allowDataChannel:()=>mm,areNegotiatedDirectionsAcceptable:()=>Xp,areNegotiatedDirectionsFulfilled:()=>em,areSendDirectionsFulfilled:()=>tm,canUseWebrtc1_0:()=>pm,convertToCodecInfo:()=>vm,getAllowedCodecs:()=>fm,getSrtpInfo:()=>im,hasReceiveDirectionality:()=>Kp,hasSendDirectionality:()=>Wp,invertModalities:()=>qp,ipAddressConverter:()=>ym,ipV4RegExp:()=>Hp,ipV6RegExp:()=>$p,ipv4AddressConverter:()=>Tm,ipv6AddressConverter:()=>Cm,isOnHold:()=>Yp,mediaTypeToModality:()=>am,modalityToMediaType:()=>sm,negotiateDirectionality:()=>Gp,negotiateModalities:()=>Qp,parseCandidateString:()=>rm,preferSdesSrtp:()=>gm,printMediaStream:()=>Sm,removeChangedSendDirection:()=>nm,removeSendDirectionality:()=>zp,scrubConstraints:()=>hm,scrubDevices:()=>um,scrubObjectExcludingFields:()=>cm,scrubObjectFields:()=>lm,scrubSelectedDevices:()=>dm,sendStreamsToModalities:()=>om,shouldDisableAudioSendersTroughSetParams:()=>bm,shouldDisableVideoSendersTroughSetParams:()=>Em});var Vp=class e extends Vi{constructor(e){super(),this.isAudioOutputSelectionSupportedValue=!1,e.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===Gi.MEDIA_ERROR.webGlRendererError?void 0:this.renderer;try{const e=document.createElement("canvas").getContext("webgl"),t=e?.getExtension("WEBGL_debug_renderer_info"),i=t&&e.getParameter(t.UNMASKED_RENDERER_WEBGL);return this.renderer=i,i}catch{return void(this.renderer=Gi.MEDIA_ERROR.webGlRendererError)}}async isRollbackSupported(){let e;try{if(e=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection({sdpSemantics:"unified-plan"}),e){const t=await e.createOffer();await e.setLocalDescription(t),await e.setLocalDescription({type:"rollback"}),this.isRollbackSupportedValue=!0}}catch(e){this.isRollbackSupportedValue=!1}finally{e?.close()}}static async isCodecsSupported(e){const t={format:"annexb"},i=["no-preference","prefer-software","prefer-hardware"],n=[];for(const r of e)for(const e of i){const i=await(window.VideoEncoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t,width:1280,height:720})),s=await(window.VideoDecoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t}));if(i||s){const e={name:r,mode:i?.config.hardwareAcceleration,encode:i?.supported,decode:s?.supported};n.push(e)}}return n}static async hasH264CodecSupport(e){const t="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",i=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection;if(!i)return!1;try{return await i.setRemoteDescription({sdp:"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",type:"offer"}),!0}catch(t){return e.error("H264 not supported",t),!1}finally{try{i.close()}catch(e){}}}static hasMediaApi(){return navigator.getUserMedia&&"undefined"!=typeof RTCPeerConnection}static hasCapabilitiesApi(){return!!Mp.window.RTCRtpReceiver?.getCapabilities}static isAudioOutputSelectionSupportedByBrowser(){return!!Mp.window?.HTMLAudioElement?.prototype.setSinkId}updateConfig(){const t=e.isAudioOutputSelectionSupportedByBrowser();t!==this.isAudioOutputSelectionSupportedValue&&(this.isAudioOutputSelectionSupportedValue=t,this.event("isAudioOutputSelectionSupportedChanged").raise())}static hasUnifiedPlanSupport(){let e;try{e=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection({sdpSemantics:"unified-plan"})}catch(e){return!1}let t=!1;return e&&(t=!!e.addTransceiver,e.close()),t}static hasEncodedStreamsApi(){return!!RTCRtpReceiver.prototype.createEncodedStreams||e.hasScriptTransformApi()}static hasScriptTransformApi(){return!!window.RTCRtpScriptTransform}static isWakeLockSupported(){return!!window.navigator.wakeLock}},Hp=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})?$/),$p=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 jp(e){switch(e){case Gi.MEDIA_STATE.send:return Gi.MEDIA_STATE.receive;case Gi.MEDIA_STATE.receive:return Gi.MEDIA_STATE.send;default:return e}}function Gp(e,t){const i=Wp(e)&&Wp(t),n=Kp(e)&&Kp(t);return i&&n?Gi.MEDIA_STATE.sendReceive:i?Gi.MEDIA_STATE.send:n?Gi.MEDIA_STATE.receive:e===Gi.MEDIA_STATE.inactive&&t||e&&t===Gi.MEDIA_STATE.inactive?Gi.MEDIA_STATE.inactive:void 0}function qp(e){const t={},i=jp(e.audio);i&&(t.audio=i);const n=jp(e.video);n&&(t.video=n);const r=jp(e.sharing);r&&(t.sharing=r);const s=jp(e.data);return s&&(t.data=s),t}function zp(e){return e===Gi.MEDIA_STATE.sendReceive?Gi.MEDIA_STATE.receive:void 0}function Wp(e){return e===Gi.MEDIA_STATE.send||e===Gi.MEDIA_STATE.sendReceive}function Kp(e){return e===Gi.MEDIA_STATE.receive||e===Gi.MEDIA_STATE.sendReceive}function Jp(e){return Kp(e)?e:e===Gi.MEDIA_STATE.send?Gi.MEDIA_STATE.sendReceive:Gi.MEDIA_STATE.receive}function Yp(e){return!(e.audio!==Gi.MEDIA_STATE.inactive||e.video&&e.video!==Gi.MEDIA_STATE.inactive||e.sharing&&e.sharing!==Gi.MEDIA_STATE.inactive)}function Qp(e,t){const i={},n=Gp(e.audio,t.audio);n&&(i.audio=n);const r=Gp(e.video,t.video);r&&(i.video=r);const s=Gp(e.sharing,t.sharing);s&&(i.sharing=s);const a=Gp(e.data,t.data);return a&&(i.data=a),i}function Zp(e,t,i,n){const r=Wp(t)&&Wp(i)||!Wp(t)&&!Wp(n);let s=!n||Kp(t)&&Kp(i)||!Kp(t)&&!Kp(n);return e.config.fixExtraNegotiation&&(s=s||Kp(t)&&!Kp(i)&&!Kp(n)),r&&s}function Xp(e,t,i,n){return Zp(e,t.audio,i.audio,n.audio)&&Zp(e,t.video,i.video,n.video)&&Zp(e,t.sharing,i.sharing,n.sharing)&&Zp(e,t.data,i.data,n.data)}function em(e,t){function i(e,t){const i=Wp(e)===Wp(t),n=Kp(e)===Kp(t)||Kp(e)&&!t;return i&&n}return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function tm(e,t){const i=(e,t)=>Wp(e)===Wp(t);return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function im(e){const t={dtls:!1,sdes:!1};return t.dtls=!!e.fingerprint,e.media.forEach((e=>{t.dtls=t.dtls||!!e.fingerprint,t.sdes=t.sdes||!!e.crypto})),t}function nm(e,t){if(!t||Xi(t))return e;const i={};return qi(e,((e,n)=>{n===Gi.MODALITY.data?i[n]=function(e,t){return Wp(e)&&!Wp(t)?t:e}(e,t[n]):i[n]=function(e,t){return Wp(e)&&!Wp(t)?zp(e)||t:e}(e,t[n])})),i}function rm(e){const t=(e||"").split(" ");return{component:t[1],protocol:t[2],priority:t[3],ip:t[4],port:t[5],type:t[7]}}function sm(e){switch(e){case"audio":return"Audio";case"video":return"Video";case"sharing":return"ScreenShare";default:return null}}function am(e){switch(e){case"Audio":return"audio";case"Video":return"video";case"ScreenShare":return"sharing";default:return null}}function om(e){const t={};return en(e).forEach((i=>t[i]=!!e[i])),t}function lm(e,t,i){if(!e)return e;const n={...e};for(const[r,s]of Object.entries(e))"object"==typeof s?n[r]=lm(s,t):s&&t.includes(r)&&(n[r]=i?i(s):De(s));return n}function cm(e,t,i){if(!e)return e;const n={...e};for(const[r,s]of Object.entries(e))"object"==typeof s?n[r]=cm(s,t):s&&!t.includes(r)&&(n[r]=i?i(s):De(s));return n}function dm(e){return e?cm(e,[]):e}function um(e,t){if(!e)return e;const i=lm(e,["deviceId","groupId","guid"]);return lm(i,["label"],(e=>fn(e,t)))}function hm(e){return lm(e,["sourceId","deviceId"])}function gm(e,t){return!(!e.config.webrtcForceSdesForS1||!e.config.checkSupportForWebrtc_1_0||e.mediaConfig.simulcastSessionEnabled)||(t?e.config.preferSdesSrtpPstn:e.config.preferSdesSrtp)}function pm(e){return!e||Vp.hasUnifiedPlanSupport()}function mm(e){return!!e.configProvider.mediaConfig.simulcastSessionEnabled&&(e.config.isPstnCall?e.configProvider.config.enableDataChannelPstn:e.configProvider.config.enableDataChannel)}function fm(e,t){switch(t){case Gi.MEDIA_TYPE.audio:return e.config.allowedAudioCodecs;case Gi.MEDIA_TYPE.video:return e.config.allowedVideoCodecs;default:return[]}}function vm(e){return e.map((e=>{const t={codec:e.mimeType.split("/").pop(),rate:e.clockRate};return e.channels&&(t.encoding=e.channels),e.sdpFmtpLine&&(t.fmtpLine=e.sdpFmtpLine),t}))}function Sm(e){return`${e?.id}:${JSON.stringify(e?.getTracks().map((e=>e.id)))}}`}function ym(e){try{if(Hp.test(e))return Tm(e);if($p.test(e))return Cm(e)}catch(t){return e}return e}function Cm(e){let t,i=e.lastIndexOf("]")+1,n="",r="";i>0?(t=e.substring(0,i),r=e.substring(i)):(t=e,i=t.length);const s=t.lastIndexOf(":");if(t.includes(".")){const e=Tm(t.substring(s+1,i-1-s));n=t.substring(0,s+1)+e}else s<t.length-1||":"===t[s-1]&&t.match(/:/g).length<7?n=t.substring(0,s+1)+"x":7===t.match(/:/g).length&&(n=t.substring(0,s)+"0:x");return n?r?n+"]"+r:"["===e.substring(0,1)?(n=n.substring(1),n):n:e}function Tm(e){const t=e.substring(0,e.lastIndexOf(".")+1)+"x",i=e.lastIndexOf(":");return i>0?t+e.substring(i):t}function Em(e,t,i){return!(!t&&!i)&&(i?e.config.disableSendersTroughSetParametersVideo&&(i===Gi.MODALITY.sharing||i===Gi.MODALITY.video):e.config.disableSendersTroughSetParametersVideo&&("Video"===t.mediaType||"ScreenShare"===t.mediaType))}function bm(e,t){return e.config.disableSendersTroughSetParametersAudio&&"Audio"===t.mediaType}var _m=Z,Im=Z,wm={maxOutgoingResolution:({settings:e})=>Mm(e),maxParticipantResolutions:({settings:e})=>Rm(e),maxIncomingStreams:({settings:e})=>km(e),maxSimulcastLayers:({settings:e})=>Om(e),outgoingVideoLimit:({settings:e,constraints:t})=>Dm(e,t)},Am=(e,t,i)=>(e.info(`Converting settings to constraints and mapping, [requestedConstraints=${JSON.stringify(i)}], [settings=${JSON.stringify(t)}]`),Pm((0,Im.cloneDeep)(i),(0,Im.cloneDeep)(t))),Pm=(e,t)=>Object.keys(e).reduce(((i,n)=>{const r=wm[n]?wm[n]({constraints:e,settings:t}):void 0;return r&&(i[n]=r),i}),{}),Rm=e=>e.multiviewResolutionLimits,Mm=e=>e.outgoingVideoLimit?.maxResolution,Dm=(e,t)=>{const i=t?.outgoingVideoLimit;if(!i)return;const{outgoingVideoLimit:n={}}=nn(e);if("number"==typeof i)return n?.maxResolution;const r=Object.keys(i).reduce(((e,t)=>{const i=n?.[t];return i&&(e[t]=i),e}),{});return Object.keys(r).length?r:void 0},km=e=>e.numVideoChannelsGvc,Om=e=>{const t=e.specCompliantSimulcast,i=t.video?.layerScaleFactors,n=t.sharing?.layerScaleFactors,r=i?.length?Math.max(...i):1,s=n?.length?Math.max(...i):1;return Math.min(r,s)},Nm=Z,Lm={maxIncomingStreams:Nm.isNumber,maxSimulcastLayers:Nm.isNumber,maxOutgoingResolution:Nm.isNumber,maxParticipantResolutions:e=>!!Wi(e)&&(!!(0,Nm.isNumber)(e)||"more"in e&&Object.values(e).every((e=>(0,Nm.isNumber)(e)))),outgoingVideoLimit:e=>!!Wi(e)&&(e=>!!(0,Nm.isNumber)(e)||!!(e=>{const t=["maxResolution","maxBitrate","maxFramerate"],i=e=>t.includes(e),n=Object.entries(e);return 0!==n.length&&n.every((([e,t])=>(0,Nm.isNumber)(t)&&i(e)))})(e)&&!Xi(e))(e)};function xm(e,t){if(Array.isArray(e))return t.slice()}var Fm=(e,t)=>{for(const i in t){const n=e[i],r=t[i];e[i]="object"==typeof r?Fm({...n},r):Ki(n,r)}return e},Um=class{constructor(e,t,i,n,r,s,a){this.logger=e,this.defaultSettings=t,this._mediaConfig=i,this._userAgentConfig=n,this._countryCode=r,this.platformCallConstraintsProvider=s,this.currentCallConstraints=a,this.mergedConstraints={},this.callConstraintsTelemetry=[],this.iceTransportPolicy=Gi.ICE_TRANSPORT_POLICY.all,this.validIceTransportPolicies=[Gi.ICE_TRANSPORT_POLICY.all,Gi.ICE_TRANSPORT_POLICY.relay],this.mergeConstraintsTelemetryWithGlobal(),this.mergedConstraints=this.mergeConstraintsWithGlobal(this.currentCallConstraints),this.settings=this.mergeSettings((0,_m.cloneDeep)(this.defaultSettings))}get config(){return this.settings}get mediaConfig(){return this._mediaConfig}get userAgentConfig(){return this._userAgentConfig}get countryCode(){return this._countryCode}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};Sn(this.callConstraintsTelemetry,i,this.config.numCallConstraintsEvents)}getCallConstraintsTelemetry(){return this.callConstraintsTelemetry}getCallConstraints(){return this.mergedConstraints}setCallConstraints(e={}){this.addCallConstraintsTelemetryEvent(e,"requested"),this.logger.safe.debug("Saving new call constraints",JSON.stringify(e));const t=this.transformConstraints((e=>(e=JSON.parse(JSON.stringify(e)),Object.entries(Lm).reduce(((t,[i,n])=>(n(e[i])&&(t[i]=e[i]),t)),{})))(e));return this.logger.safe.debug("Validated call constraints",JSON.stringify(t)),this.mergedConstraints=this.mergeConstraintsWithGlobal(t),this.settings=this.mergeSettings((0,_m.cloneDeep)(this.defaultSettings)),Am(this.logger,this.settings,t)}getIceTransportPolicy(){return this.settings.iceTransportPolicyForced||this.iceTransportPolicy}setIceTransportPolicy(e){this.validIceTransportPolicies.includes(e)?(this.logger.info(`Setting transport policy to ${this.iceTransportPolicy}`),this.iceTransportPolicy=e):this.logger.debug(`Unknown incoming transport policy, using ${this.iceTransportPolicy}`)}overrideMaxSessionBandwidth(e){return this.defaultSettings.maxBandwidthInKbps!==e&&(this.defaultSettings.maxBandwidthInKbps=e,this.settings.maxBandwidthInKbps=e,this.mediaConfig.maxBandwidthInKbps=e,!0)}transformConstraints(e){const t=(0,_m.cloneDeep)(e);return"maxOutgoingResolution"in t&&(t.outgoingVideoLimit={maxResolution:t.maxOutgoingResolution},delete t.maxOutgoingResolution),"number"==typeof t.outgoingVideoLimit&&(t.outgoingVideoLimit={maxResolution:t.outgoingVideoLimit}),t}mergeConstraintsTelemetryWithGlobal(){this.platformCallConstraintsProvider.callConstraintsTelemetry.forEach((e=>Sn(this.callConstraintsTelemetry,e,this.defaultSettings.numCallConstraintsEvents)))}mergeConstraintsWithGlobal(e={}){const t=this.transformConstraints(this.platformCallConstraintsProvider.constraints);if(!Object.keys(t).length)return e;const i=(0,_m.cloneDeep)(e);return Fm(i,t),this.logger.safe.debug(`Merging call constraints ${JSON.stringify(e)} and global constraints ${JSON.stringify(t)}. Result: ${JSON.stringify(i)}`),i}mergeSettings(e){if(!e.enablePlatformCallConstraints||!e.enablePlatformCallConstraintsPerCall)return e;const t=qn(this.logger,e,this.mergedConstraints);return this.logger.safe.info(`Merging settings with platform call constraints: ${tt(t)}`),(0,_m.assign)({},e,t,xm)}},Bm=Z,Vm=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing],Hm=class{constructor(e,t,i,n,r){this.peerConnection=t,this.mediaManager=i,this.reinvitelessContext=r,this.entityTransceiverMap=new Map,this.logger=e.createChild("TM"),this.configProvider=n.configProvider,this.isMultiparty=n.config.isConference,this.isPstnCall=n.config.isPstnCall,this.isParkedCall=n.config.isParkedCall,this.numVideoChannels=this.isMultiparty&&this.configProvider.config.numVideoChannelsGvc||1,n.configProvider.config.enableRollbackHandler&&this.mediaManager.setRollbackUpdateHandler(this.handleMediaEntitiesRollback.bind(this))}getTransceivers(){return this.peerConnection.getTransceivers().filter(Gm)}assureTransceivers(e){this.assureNegotiatedOrder(),this.addModalities(e),this.logTransceiversInfo("assureTransceivers"),this.setDirections(e)}syncTransceivers(e){this.syncWithMediaEntities(),this.setDirections(e)}assureNegotiatedOrder(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{-1!==Vm.indexOf(t.getModality())&&(qm(this.entityTransceiverMap.get(t),e)||this.createTransceiverForEntity(t))}))}addModalities(e){const t=this.mediaManager.isEmpty();this.isMultiparty||!t||this.isPstnCall||(e.video=e.video||"inactive",e.sharing=e.sharing||"inactive"),this.configProvider.config.webrctRemoveVideoModalitiesForPstn&&this.isPstnCall&&!this.isParkedCall&&(delete e.video,delete e.sharing);for(const i of Vm){if(this.mediaManager.getMediaEntitiesByModality(i)[0]||!e[i])continue;const n=i===Gi.MODALITY.video?this.numVideoChannels:1;(0,Bm.times)(n,(e=>{const n=this.mediaManager.createMediaEntity(i);n.setExtension("reinviteless",t&&this.reinvitelessContext.maxStreamsForModality[i]>e),this.createTransceiverForEntity(n)}))}}createTransceiverForEntity(e){const t=e.getModality();this.logger.safe.info(`createTransceiver: modality=${t}`);const i=t===Gi.MODALITY.audio?Gi.MEDIA_TYPE.audio:Gi.MEDIA_TYPE.video,n=e.getSimulcastContext(),r=this.createTransceiver(i,n);this.setCodecPreferences(r,i,!0),this.setExtensionPreferences(r,t),this.entityTransceiverMap.set(e,r),e.setExtension("unnegotiatedModality",!0)}setCodecPreferences(e,t,i){const n=fm(this.configProvider,t);if(!n?.length||!Vp.hasCapabilitiesApi()||this.configProvider.config.filterCodecsInSdp)return;const r=Mp.window.RTCRtpReceiver.getCapabilities(t);if(!r)return;const s=[];if(i)for(const e of n){const t=r.codecs.filter((t=>$m(e,t)));s.push(...t)}else for(const e of r.codecs)n.some((t=>$m(t,e)))&&s.push(e);s.length&&e.setCodecPreferences&&e.setCodecPreferences(s)}setExtensionPreferences(e,t){if(!this.configProvider.config.headerExtensionsToUpdate?.[t])return;if(!e.getHeaderExtensionsToNegotiate||!e.setHeaderExtensionsToNegotiate)return void this.logger.safe.debug("setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate is not supported");const i=this.configProvider.config.headerExtensionsToUpdate[t],n=e.getHeaderExtensionsToNegotiate();for(const e of n){const t=i.find((t=>t.uri===e.uri));t&&(e.direction=t.direction)}try{e.setHeaderExtensionsToNegotiate(n)}catch(e){this.logger.safe.error(`setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate failed, err ${tt(e)}`)}}async createSender(e,t,i){const n=await this.associateTrackWithTransceiver(e,t,i);if(!n)throw new Error(`Transceiver for modality=${i} is not found`);const r=this.findEntityForTransceiver(n),s=i!==Gi.MODALITY.sharing||r?.getExtension("reinviteless")?Gi.MEDIA_STATE.sendReceive:Gi.MEDIA_STATE.send;return n.direction=s,this.logger.safe.info(`Replace track completed direction:${n.direction} for transceiver mid=${n.mid}`),n.sender}removeSender(e){this.removeSenderInternal(e,!1)}async removeSenderAsync(e){return this.removeSenderInternal(e,!0)}removeSenderInternal(e,t){if("closed"===(this.peerConnection.connectionState||this.peerConnection.iceConnectionState))return void this.logger.safe.info("Not removing sender from pc, connection is closed");const i=this.getTransceivers().find((t=>t.sender===e));if(!i)throw new Error(`Transceiver for sender with track=${e.track?.id} is not found`);const n=this.findEntityForTransceiver(i),r=!!n?.getExtension("reinviteless");this.logger.safe.info(`Remove sender with track=${e.track?.id} for transceiver mid=${i.mid}, reinviteless=${r}, doAsync=${t}`);let s=Promise.resolve();return r&&t?s=i.sender.replaceTrack(null):this.peerConnection.removeTrack(e),t?s:void 0}createTransceiver(e,t){const i={direction:"inactive"};return this.addSimulcastEnvelopeIfNeeded(i,t),this.peerConnection.addTransceiver(e,i)}addSimulcastEnvelopeIfNeeded(e,t){t?.shouldUseSimulcast()&&(e.sendEncodings=(0,Bm.times)(t.config.layerScaleFactors.length,(e=>{const i={rid:`${t.ridList[e]}`,scaleResolutionDownBy:t.config.layerScaleFactors[e]};if(this.configProvider.config.specCompliantSimulcast?.disableTilde&&(i.active=!1),t.config.layerScalabilityModes?.length>0){const n=t.config.layerScalabilityModes[e];void 0!==n&&n.length>0?i.scalabilityMode=n:this.logger.safe.warn(`Scalability mode was not set for rid: ${i.rid}`)}return this.logger.safe.debug(`Added layer ${e} with rid: ${i.rid} SF: ${i.scaleResolutionDownBy} SM: ${i.scalabilityMode}`),i})))}async associateTrackWithTransceiver(e,t,i){const n=this.findAvailableTransceiverToSend(i);if(n){this.logger.safe.info(`Associate track=${e?.id} (${i}) with existing transceiver mid=${n.mid}`);try{if(this.isMultiparty&&Em(this.configProvider,void 0,i)){this.logger.safe.info(`Disabling encodings for transceiver mid=${n.mid}`);const e=n.sender.getParameters();e.encodings.forEach((e=>e.active=!1)),await n.sender.setParameters(e)}await n.sender.replaceTrack(e),this.configProvider.config.useSetStreamsForSender&&n.sender.setStreams&&n.sender.setStreams(t)}catch(e){throw this.logger.safe.error(`replaceTrack failed, err ${JSON.stringify(e)}`),e}return n}return null}syncWithMediaEntities(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{let i=this.entityTransceiverMap.get(t);i=qm(i,e)?i:e.find((e=>e.mid===t.getMid())),this.entityTransceiverMap.set(t,i)})),this.logTransceiversInfo("syncWithMediaEntities")}getTransceiversByModality(e){return this.mediaManager.getMediaEntitiesByModality(e).map((e=>this.entityTransceiverMap.get(e))).filter(Gm)}setDirections(e){const t=!Yp(e);for(const i of Vm)for(const[n,r]of this.getTransceiversByModality(i).entries()){const s=this.findEntityForTransceiver(r);if(s?.getExtension("reinviteless")&&t){r.direction="sendrecv";continue}const a=e[i]||Gi.MEDIA_STATE.inactive;r.direction=0===n&&r.currentDirection?a:jm(a)}this.logTransceiversInfo("setDirections")}handleMediaEntitiesRollback(e,t){e.forEach((e=>{const i=this.entityTransceiverMap.get(e),n=t.find((t=>t.getMid()===e.getMid()));this.entityTransceiverMap.set(n,i)})),this.logTransceiversInfo("handleMediaEntitiesRollback")}findAvailableTransceiverToSend(e){const t=this.mediaManager.getMediaEntitiesByModality(e)[0];return this.entityTransceiverMap.get(t)}findEntityForTransceiver(e){for(const[t,i]of this.entityTransceiverMap)if(i===e)return t}logTransceiversInfo(e){let t=`${e}: transceivers details:`;for(const e of Vm){const i=this.getTransceiversByModality(e);t+=` ${e}(${i.length}) [${i.map((e=>`mid=${e.mid}, direction=${e.direction}`)).join(";")}]`}this.logger.safe.debug(t)}};function $m(e,t){return!(!(0,Bm.isUndefined)(e.channels)&&e.channels!==t.channels||!(0,Bm.isUndefined)(e.clockRate)&&e.clockRate!==t.clockRate||!(0,Bm.isUndefined)(e.mimeType)&&e.mimeType.toLowerCase()!==t.mimeType.toLowerCase()||!(0,Bm.isUndefined)(e.sdpFmtpLine)&&-1===t.sdpFmtpLine.toLowerCase().indexOf(e.sdpFmtpLine.toLowerCase()))}function jm(e){let t=e;return Wp(e)&&(t=zp(e)),t||Gi.MEDIA_STATE.inactive}function Gm(e){return e&&"stopped"!==e.direction&&!e.stopped}function qm(e,t){return Gm(e)&&-1!==t.indexOf(e)}var zm=class extends Vi{constructor(e,t,i){super(),this.configProvider=e,this.workerProvider=t,this.logger=i,this.transformsCollections=new Map}async initialize(){return this.configProvider.config.useInsertableStreams&&this.workerProvider&&Vp.hasEncodedStreamsApi()&&(this.worker=new mf(this.workerProvider,this.logger)),this.worker?this.worker.initialize():Promise.resolve()}initTransformsCollection(e,t,i){const n=Vp.hasScriptTransformApi()||this.workerProvider;if(!this.configProvider.config.useInsertableStreams||!Vp.hasEncodedStreamsApi()||n&&!this.isWorkerLoaded()||null===e.track)return null;if(!this.transformsCollections.has(e)){const n=this.worker?new Km(this.worker,e):new Wm(e);this.transformsCollections.set(e,{collection:n,mediaType:i,objType:t})}const r=this.transformsCollections.get(e);return this.event("onTransformsCollectionCreated").raise(r),r.collection}clearTransformsCollection(e){const t=this.transformsCollections.get(e);t&&(this.event("onTransformsCollectionCleared").raise(t),t.collection.clearTransforms())}dispose(){for(const e of this.transformsCollections.values())this.event("onTransformsCollectionCleared").raise(e),e.collection.clearTransforms();this.transformsCollections.clear(),this.worker?.dispose(),super.dispose()}isWorkerLoaded(){return!!this.worker?.isWorkerLoaded()}},Wm=class{constructor(e){const{readable:t,writable:i}=e.createEncodedStreams();this.streamTransformer=new Ef(t,i)}addTransform(e){e.createBaseInstance(this.streamTransformer)}clearTransforms(){this.streamTransformer.clearTransforms()}},Km=class{constructor(e,t){if(this.workerHandler=e,this.clientId=t.track.id,Vp.hasScriptTransformApi())return void(t.transform=new RTCRtpScriptTransform(this.workerHandler.worker,{clientId:this.clientId}));const{readable:i,writable:n}=t.createEncodedStreams(),r=[i,n];this.workerHandler.sendTransformCommand(this.clientId,{operation:"init",readable:i,writable:n},r)}addTransform(e){e.createWorkerInstance(this.workerHandler,this.clientId)}clearTransforms(){this.workerHandler.sendTransformCommand(this.clientId,{operation:"clear"})}},Jm=class{constructor(e,t=!1){this.logger=e,this.disabled=t,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(e){this.disabled=!1,this.mixerImp?.setupMixer(this.audioContext,this.destination,e)}setMixerType(e,t){this.mixerImp?.mixerType!==e&&(this.mixerImp?.reset(),this.mixerImp=this.createMixer(e),this.disabled||this.mixerImp.setupMixer(this.audioContext,this.destination,t))}setStreamSources(e){this.disabled||this.mixerImp.setStreamSources?.(e)}setParticipantSpatialAudioPositions(e){this.mixerImp.setParticipantSpatialAudioPositions?.(e)}createMixer(e){switch(e){case 0:return new Qm;case 1:return new Zm(this.logger.createChild("MixingStreamsMixer"));case-1:return new Ym;default:throw new Error(`unknown mixer type: ${e}`)}}},Ym=class{constructor(){this.mixerType=-1}reset(){}setupMixer(e,t,i){}},Qm=class{constructor(){this.mixerType=0}reset(){this.sourceNode.disconnect()}setupMixer(e,t,i){this.sourceNode=e.createMediaStreamSource(i[0]),this.sourceNode.connect(t)}},Zm=class{constructor(e){this.logger=e,this.sourcePositions=new Map,this.sourceNodes=[],this.pannerNodes=[],this.mixerType=1}reset(){this.logger.safe.info("resetting SpatialMultiStreamMixer");for(const e of this.sourceNodes)e.disconnect();this.sourceNodes=[];for(const e of this.pannerNodes)e.disconnect();this.pannerNodes=[]}setupMixer(e,t,i){(this.sourceNodes.length||this.pannerNodes.length)&&this.reset();for(const n of i){const i=e.createMediaStreamSource(n),r=new PannerNode(e,{panningModel:"HRTF"});i.connect(r),r.connect(t),this.sourceNodes.push(i),this.pannerNodes.push(r)}this.logger.safe.info(`setupMixer is done for ${i.length} streams.`)}setStreamSources(e){for(let t=0;t<e.length;t++)this.setStreamPosition(t,e[t])}setParticipantSpatialAudioPositions(e){this.sourcePositions=new Map(e.map((e=>[e.sourceId,e])))}setStreamPosition(e,t){const i=this.sourcePositions.get(t)??{sourceId:t,x:0,y:0},n=this.pannerNodes[e];n?(n.positionX.value=i.x,n.positionY.value=i.y):this.logger.warn(`panner node for stream ${e} is not found`)}},Xm=class extends Vi{constructor(e){super(),this.logger=e,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(e,t){this.logger.safe.debug(`setup ${e} streams with extra Comfort Noise stream: ${t}`),this.mediaStreams=[];const i=[];for(;e--;){const e=new MediaStreamTrackGenerator({kind:"audio"});i.push(e),this.streams.push(new MediaStream([e]))}const n=t?new MediaStreamTrackGenerator({kind:"audio"}):null;return this.cnStream=n?new MediaStream([n]):null,this.event("onStreamsChanged").raise(),{streams:i.map((e=>e.writable)),cnStream:n?.writable}}setStreamSources(e){this.isNegotiated&&this.event("onStreamSourcesUpdated").raise(e)}setConfiguredState(e){this.isConfigured!==e&&(this.isConfigured=e,this.event("onConfiguredStateChanged").raise(this.isConfigured))}setNegotiatedState(e){this.isNegotiated!==e&&(this.isNegotiated=e,this.event("onActiveStateChanged").raise(this.isNegotiated))}setDetectedCodec(e){this.activeCodec!==e&&(this.activeCodec=e,this.event("onActiveCodecChanged").raise(this.activeCodec))}},ef=class e{constructor(){this.context=new AudioContext({sampleRate:5e4})}dispose(){this.context.close()}createTimerPort(){return new AudioWorkletNode(this.context,"encodedStreamsWorklet",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[1]}).port}static async create(t){const i=new e;return await i.context.audioWorklet.addModule(t),i}},tf={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}},nf=class{constructor(e,t,i,n){this.worker=e,this.clientId=t,this.transformType=i,this.listener=n,this.worker.subscribeClient(this.clientId,this.transformType,(e=>this.processMsg(e))),this.worker.sendTransformCommand(this.clientId,{operation:"add",transformType:this.transformType})}dispose(){this.worker.unsubscribeClient(this.clientId),this.worker.sendTransformCommand(this.clientId,{operation:"clear"})}processMsg(e){if(this.listener&&e.name in this.listener)return this.listener[e.name].apply(this.listener,e.args);throw`unexpected message received for transform type ${this.transformType}: ${JSON.stringify(e)}`}},rf=class extends nf{constructor(e,t,i){super(e,t,2,i)}init(e,t){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e,t]}})}setTimerWorkletPort(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setTimerWorkletPort",args:[e]}},[e])}setCodec(e,t){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e,t]}})}passWriteableStreams(e,t){const i=e.concat(t);this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"passWriteableStreams",args:[e,t]}},i)}setAvailableStreams(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setAvailableStreams",args:[e]}})}setRecvPayloads(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setRecvPayloads",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}sendApiRecordingData(){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"sendApiRecordingData",args:[]}})}},sf=class extends Vi{constructor(e,t,i,n){super(),this.logger=e,this.maxNumOfStreamsFactor=i,this.statsProvider=new af,this.contributingSources=[],this.unmixedAudioProvider=new Xm(this.logger),this.codec="None",this.recvPayloads=[],this.initCompleted=!1,this.enabledApiRecording=!1,this.timerWorkletNode=null;try{this.enabledApiRecording="true"===localStorage.getItem("enableApiRecording")}catch{}this.streamMixer=new Jm(this.logger,n),this.unmixedAudioProvider.setConfiguredState(!!t.mediaConfig.spatialAudioEnabled),this.wasmHealerPullStrategy=t.config.useInsertableStreams?.audioWasmCodec?.wasmHealerPullStrategy||-1,this.injectWebMA()}get stream(){return this.streamMixer.stream}dispose(){super.dispose(),this.streamMixer.dispose(),this.imp?.dispose(),this.timerWorkletNode?.then((e=>e.dispose())),this.timerWorkletNode=null,this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM decoder transform"),e.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(e){this.logger.warn("WASM decoder could only be instantiated in worker")}createWorkerInstance(e,t){this.logger.info(`Creating TimerWorkletNode from url: ${e.timerWorkletUrl}`),this.timerWorkletNode=ef.create(e.timerWorkletUrl),this.imp=function(e,t,i){return new rf(e,t,i)}(e,t,this),this.imp.init(this.enabledApiRecording,this.wasmHealerPullStrategy)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.initCompleted)return this.logger.safe.debug("Decoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}setRecvPayloads(e){this.recvPayloads=e,this.initCompleted?this.imp.setRecvPayloads(e):this.logger.safe.debug("Decoder is not initialized yet, postponing Recv payload setting")}negotiationCompleted(e){this.logger.safe.debug(`Negotiation completed, negotiated=${e}`),this.unmixedAudioProvider.setNegotiatedState(e),e||(this.codec="None",this.imp?.setCodec(this.codec,this.streamMixer.isSingleInputStream()))}setParticipantSpatialAudioPositions(e){this.streamMixer.setParticipantSpatialAudioPositions(e)}disableStreamsMixer(e){e?this.streamMixer.stopMixing():this.streamMixer.startMixing(this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[]))}getStatsProvider(){return this.statsProvider}getUnmixedAudioProvider(){return this.unmixedAudioProvider}configureSpatialAudio(e){this.unmixedAudioProvider.setConfiguredState(e)}async storeApiRecording(){if(this.enabledApiRecording&&this.initCompleted)return this.recordingCompletePromise?.resolve(),this.recordingCompletePromise=new Kt,this.imp.sendApiRecordingData(),this.recordingCompletePromise.promise}initDone(e,t){if(this.healerCapabilities=t,this.logger.safe.info(`Init done, errorCode=${e}`),0!==e)return void this.event("initFailed").raise(e);this.logger.safe.info(`healerCapabilities=${JSON.stringify(t)}`),this.initCompleted=!0;const i=Math.floor(this.healerCapabilities.maxNumStreamsPerPacket*this.maxNumOfStreamsFactor),n=this.unmixedAudioProvider.setupStreams(i,!0);this.imp.passWriteableStreams(n.streams,n.cnStream),this.setCodecInternal(),this.imp.setRecvPayloads(this.recvPayloads)}requestTimerWorkletPort(){this.timerWorkletNode?.then((e=>this.imp?.setTimerWorkletPort(e.createTimerPort())))}usedDecoderChanged(e){this.logger.safe.info(`Used decoder changed to custom=${e}, configured codec=${this.codec}`),this.event("usedDecoderChanged").raise(e),this.unmixedAudioProvider.setDetectedCodec(this.codec)}packetReceived(e,t,i,n){this.statsProvider.ssrc=t,this.statsProvider.addPushStats(e,n),this.contributingSources.length===i.length&&this.contributingSources.every(((e,t)=>e===i[t]))||(this.contributingSources=i,this.event("contributingSourcesChanged").raise(i))}newDataWrittenToStreams(e){const t=Array.from(new Int32Array(e));this.unmixedAudioProvider.setStreamSources(t),this.streamMixer.setStreamSources(t);const i=t.reduce(((e,t,i)=>(0===t&&e.push(i),e)),[]);this.imp?.setAvailableStreams(i)}packetDecoded(e,t,i){this.statsProvider.addPullStats(e,t,i,i.extra.samplingRatekHz*this.healerCapabilities.frameLengthMs)}apiRecordingAvailable(e,t,i){if(this.logger.safe.debug(`API recording available: errorCode=${e}, name=${t}, buffer length=${i.byteLength}`),this.recordingCompletePromise?.resolve(),0===i.byteLength)return;const n=new Blob([i],{type:"application/octet-stream"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=t,s.click()}setCodecInternal(){this.streamMixer.setMixerType(function(e){switch(e){case"SatinFB":return 0;case"MUCHv2":return 1;case"None":return-1;default:throw new Error(`unknown codec: ${e}`)}}(this.codec),this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[])),this.imp.setCodec(this.codec,this.streamMixer.isSingleInputStream()),this.statsProvider.codecName=this.codec}injectWebMA(){const e=window.webMA;e&&(e.wasmDecoder={debugLogging:e=>this.imp?.debugLogging(e),sendApiRecordingData:()=>this.imp?.sendApiRecordingData()})}removeWebMA(){const e=window.webMA;e&&delete e.wasmDecoder}},af=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 of(0,1e3),this.packetPullProccesingTimes=new of(0,1e3),this.numOfStreamsCounter=new of(0,10),this.pullProcessingTimePerStreamNumber={},this.packetPullTimings=new of(0,1e3)}get codecName(){return this.codec}set codecName(e){this.codec=e}addPushStats(e,t){this.decoderStats.pushCount++,this.decoderStats.pushErrCount+=0!==e?1:0,this.inboudStats.jitterBufferDelay+=t.webrtc.jitterBufferDelay,this.customHealerStats.packetDurationInMs=t.extra.packetDurationInMs,this.packetPushProccesingTimes.addSample(t.extra.processingTime),this.customHealerStats.cnpPushCount=t.extra.totalCountCNPackets,this.customHealerStats.redPacketsCount+=0!==t.extra.redundancyTimestampOffset?1:0}addPullStats(e,t,i,n){var r;this.decoderStats.pullCount++,this.decoderStats.pullErrCount+=0!==e?1:0,this.inboudStats.audioLevel=i.webrtc.audioLevel,this.inboudStats.totalAudioEnergy=i.webrtc.totalAudioEnergy,this.inboudStats.jitterBufferEmittedCount=i.webrtc.jitterBufferEmittedCount,this.inboudStats.totalSamplesReceived=i.webrtc.totalSamplesReceived,this.inboudStats.concealedSamples=i.webrtc.concealedSamples,this.inboudStats.silentConcealedSamples=i.webrtc.silentConcealedSamples,this.numOfStreamsCounter.addSample(t),this.customHealerStats.FECPayloadDecodedSamples=i.extra.FECPayloadDecodedSamples,this.customHealerStats.numSamplesPerFrame=n,this.customHealerStats.pullAdspPayloadType=i.extra.pullAdspPayloadType,this.customHealerStats.concealSamples=i.extra.concealSamples,this.customHealerStats.stretchSamples=i.extra.stretchSamples,this.customHealerStats.healedSamples=i.extra.healedSamples,this.customHealerStats.decodedSamples=i.extra.decodeSamples,this.packetPullProccesingTimes.addSample(i.extra.processingTime),this.customHealerStats.cnpPullCount=i.extra.totalCountCNGeneratedFrames,this.customHealerStats.cngSamples=i.extra.cngSamples,(r=this.pullProcessingTimePerStreamNumber)[t]??(r[t]=new of(0,200)),this.pullProcessingTimePerStreamNumber[t].addSample(i.extra.processingTime),this.packetPullTimings.addSample(i.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 e of Object.keys(this.pullProcessingTimePerStreamNumber))this.customHealerStats.pullProcessingTimePerStreamNumber[e]=this.pullProcessingTimePerStreamNumber[e].getFrequencies();return this.customHealerStats}getDecoderStats(){return this.decoderStats}},of=class{constructor(e,t){this.minSample=e,this.maxSample=t,this.frequencyDict={}}addSample(e){if(void 0===e)return;const t=Math.min(this.maxSample,Math.max(this.minSample,e));this.frequencyDict[t]=(this.frequencyDict[t]??0)+1}getFrequencies(){return{...this.frequencyDict}}},lf=class extends nf{constructor(e,t,i){super(e,t,3,i)}init(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e]}})}setCodec(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}},cf=["SatinFB"],df=class extends Vi{constructor(e){super(),this.logger=e,this.codec="None",this.injectWebMA()}getCodecName(){return this.codec}dispose(){super.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM encoder transform"),e.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(e){this.logger.warn("WASM encoder could only be instantiated in worker")}createWorkerInstance(e,t){this.imp=function(e,t,i){return new lf(e,t,i)}(e,t,this),this.imp.init(cf)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.encodersInitCodes)return this.logger.safe.debug("Encoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}isCodecAllowed(e){return cf.includes(e)}negotiationCompleted(e){e||(this.codec="None",this.imp?.setCodec(this.codec))}initDone(e){this.logger.safe.info(`initDone: ${JSON.stringify(e)}`),this.encodersInitCodes=e,this.setCodecInternal()}packetEncoded(e){0!==e&&this.logger.safe.info(`encode failed: ${e}`)}setCodecInternal(){const e=this.encodersInitCodes[this.codec]??-2147024809;if("None"!==this.codec&&0!==e)return this.logger.safe.error(`WASM encoder is failed to init codec ${this.codec}, err code: ${e}`),void this.event("initCodecFailed").raise(e);this.event("codecChanged").raise(this.codec),this.imp.setCodec(this.codec)}injectWebMA(){const e=window.webMA;e&&(e.wasmEncoder={debugLogging:e=>this.imp?.debugLogging(e)})}removeWebMA(){const e=window.webMA;e&&delete e.wasmEncoder}},uf=Z,hf=class extends Vi{constructor(e,t,i){super(),this.encStreamsManager=e,this.logger=t,this.configProvider=i,this.isEnabled=!1,this.sessionStats=new pf,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(e,t){if(!e||!this.codecContext||!this.codecConfig?.enable)return;this.isEnabled=!0;const i=this.codecConfig.maxNumOfStreamsFactor||1;this.decoderImp=new sf(this.logger.createChild("AudioWasmDecoder"),this.configProvider,i,t),this.codecConfig.enableSend&&(this.encoderImp=new df(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(e){if(!this.isEnabled)return;const t=this.decoderImp?.getUnmixedAudioProvider()?.configured?"MUCHv2":this.codecConfig.codec||"None";this.codecContext.codec!==t&&(this.codecContext.initSendFailed=!1),this.codecContext.lastUsedCodec=this.codecContext.codec,this.codecContext.codec=t,this.codecContext.enabledLocally=!this.codecContext.initFailed&&"None"!==t,this.codecContext.enabledForSend=this.codecContext.enabledLocally&&!this.codecContext.initSendFailed&&!!this.codecConfig?.enableSend&&this.encoder?.isCodecAllowed(t),this.logger.safe.info(`Audio codec state: context=${JSON.stringify(this.codecContext)}`),this.codecContext.initFailed||!e&&this.codecContext.disabledRemotely||(this.sessionStats.toggleState("None"!==t),this.decoderImp?.setCodec(t),this.encoderImp?.setCodec(this.codecContext.enabledForSend?t:"None"))}negotiationCompleted(){if(!this.isEnabled)return!1;const e=this.codecContext.enabledLocally&&!this.codecContext.disabledRemotely;return this.decoderImp?.negotiationCompleted(e),this.encoderImp?.negotiationCompleted(e),this.sessionStats.negotiationCompleted(e,this.codecContext.enabledForSend),e}configureSpatialAudio(e,t){return!!this.isEnabled&&(this.decoderImp?.configureSpatialAudio(e),(e&&"MUCHv2"!==this.codecContext.codec||!e&&"MUCHv2"===this.codecContext.codec)&&this.event("negotiationNeeded").raise(t),!0)}subscribeToStreamManagerEvents(e){this.subs.push(e.on("onTransformsCollectionCreated",(e=>this.handleTransformsCollectionCreated(e))),e.on("onTransformsCollectionCleared",(e=>this.handleTransformsCollectionCleared(e))))}handleTransformsCollectionCreated(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.activateTransform(e.collection):this.encoderImp&&"Sender"===e.objType&&this.encoderImp.activateTransform(e.collection))}handleTransformsCollectionCleared(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.deactivateTransform():this.encoderImp&&"Sender"===e.objType&&this.encoderImp.deactivateTransform())}subscribeToCodecsEvents(){this.decoderImp&&this.subs.push(this.decoderImp.on("initFailed",(e=>this.handleCodecInitFailed("decoder",e)))),this.encoderImp&&this.subs.push(this.encoderImp.on("initCodecFailed",(e=>this.handleCodecInitFailed("encoder",e))))}unsubscribeFromEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}handleCodecInitFailed(e,t){"decoder"===e?this.codecContext.initFailed=!0:this.codecContext.initSendFailed=!0;const i=be();this.logger.safe.warn(`[${i}] Audio ${e} init failed ${t}`),this.sessionStats.initFailed(t,e),this.event("negotiationNeeded").raise(i)}},gf=class e{constructor(){this.sessionEvents={negotiationAttempts:[],toggleCount:0,negotiatedCount:0,failedNegotiationCount:0,decoderInitError:0,encoderInitError:0}}toggleState(t){this.sessionEvents.toggleCount++,this.inProgressNegotiation={ts:Date.now(),enabled:t,negotiated:!1,sendEnabled:!1},Sn(this.sessionEvents.negotiationAttempts,this.inProgressNegotiation,e.maxStoreNegotiations)}negotiationCompleted(e,t){this.inProgressNegotiation&&(this.sessionEvents.negotiatedCount+=e?1:0,this.sessionEvents.failedNegotiationCount+=this.inProgressNegotiation.enabled&&!e?1:0,this.inProgressNegotiation.negotiated=e,this.inProgressNegotiation.sendEnabled=t,this.inProgressNegotiation=void 0)}initFailed(e,t){"decoder"===t?this.sessionEvents.decoderInitError=e:this.sessionEvents.encoderInitError=e}getSessionEvents(){return(0,uf.clone)(this.sessionEvents)}};gf.maxStoreNegotiations=5;var pf=gf,mf=class{constructor(e,t){this.workerProvider=e,this.logger=t,this.clientsMap=new Map,this.loaded=!1,this.initDefer=new Kt;try{this.worker=e.getWorker(this.logger),this.worker.onmessage=e=>this.handleEvent(e.data),this.worker.onerror=e=>{this.logger.safe.error(`error inside worker: ${e.message}`),this.initDefer.resolve()}}catch(e){this.logger.safe.error("failed to create worker"),this.initDefer.resolve()}}get timerWorkletUrl(){return this.workerProvider.getTimerWorkletUrl()}initialize(){return Promise.race([this.initDefer.promise,Yt(5e3).then((()=>{this.loaded??this.logger.safe.warn("worker initialization timeout")}))])}isWorkerLoaded(){return this.loaded}sendTransformCommand(e,t,i=[]){const n={type:"transform",clientId:e,payload:t};this.worker?.postMessage(n,i)}subscribeClient(e,t,i){const n=this.clientsMap.get(e)??new Map;n.set(t,i),this.clientsMap.set(e,n)}unsubscribeClient(e){this.clientsMap.delete(e)}dispose(){this.worker?.postMessage({type:"generic",payload:{operation:"dispose"}}),this.worker?.terminate()}handleEvent(e){switch(e.type){case"init":this.initDefer.resolve(),this.loaded=!0,this.logger.safe.info("worker initialized");break;case"transform":{const t=this.clientsMap.get(e.payload.clientId),i=t?.get(e.payload.event.transformType);i?i(e.payload.event):this.logger.safe.error(`received event for unknown Client ${e.payload.clientId} or transformType ${e.payload.event.transformType}: ${e.payload.event.name}`)}break;case"log":switch(e.level){case"debug":this.logger.safe.debug(e.msg);break;case"info":this.logger.safe.info(e.msg);break;case"warn":this.logger.safe.warn(e.msg);break;case"error":this.logger.safe.error(e.msg);break;default:this.logger.safe.error(`unknown log level ${e.level}`)}break;default:this.logger.safe.error(`received unsupported event from worker ${e.type}`)}}},ff=class{constructor(e){this.logger=e,this.transformType=0}transform(e){return this.processChunk(e),e}dispose(){}getStartCodeSize(e){const t=e.getUint32(0);return 1===t?4:256==(4294967040&t)?3:0}processChunk(e){if("key"!==e.type)return;const t=this.isH264KeyFrame(e.data)?`${this.getH264Profile(e.data)}(H264)`:"unknown";this.logger.info(`keyframe metadata: ${JSON.stringify(e.getMetadata())}, profile=${t}`)}isH264KeyFrame(e){if(e.byteLength<7)return!1;const t=new DataView(e),i=this.getStartCodeSize(t);return!!i&&7==(31&t.getUint8(i))}getH264Profile(e){const t=new DataView(e),i=this.getStartCodeSize(t);return(16777215&t.getUint32(i)).toString(16)}},vf=class extends nf{constructor(e,t){super(e,t,0,void 0)}},Sf=class{constructor(e){this.logger=e}createBaseInstance(e){this.imp=new ff(this.logger.safe),e.addTransform(this.imp)}createWorkerInstance(e,t){this.imp=new vf(e,t)}},yf=class{constructor(){this.transformType=1,this.muted=!1}transform(e){return this.muted?null:e}mute(e){this.muted=e}dispose(){}},Cf=class extends nf{constructor(e,t){super(e,t,1,void 0)}mute(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"mute",args:[e]}})}},Tf=class{constructor(e){this.logger=e}createBaseInstance(e){this.imp=new yf,e.addTransform(this.imp)}createWorkerInstance(e,t){this.imp=new Cf(e,t)}mute(e){this.logger.safe.info(`Dropping audio chunks: ${e}`),this.imp.mute(e)}},Ef=class{constructor(e,t){this.transforms=[];const i=new TransformStream({transform:(e,t)=>{let i=e;for(const e of this.transforms)if(i=e.transform(i),!i)return;t.enqueue(i)}});e.pipeThrough(i).pipeTo(t)}clearTransforms(){for(const e of this.transforms)e.dispose();this.transforms=[]}addTransform(e){this.transforms.push(e)}getTransform(e){return this.transforms.find((t=>t.transformType===e))}},bf=class extends gt{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(e){this.unsubscribeFromStreamEvents(),this.sessionAudioProvider=e,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",(e=>this.event("onStreamSourcesUpdated").raise(e))),this.sessionAudioProvider.on("onConfiguredStateChanged",(e=>this.event("onConfiguredStateChanged").raise(e))),this.sessionAudioProvider.on("onActiveStateChanged",(e=>this.event("onActiveStateChanged").raise(e))),this.sessionAudioProvider.on("onActiveCodecChanged",(e=>this.event("onActiveCodecChanged").raise(e))))}unsubscribeFromStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},_f=class extends gt{constructor(e,t,i,n,r){super(),this.allowVirtualDeviceInCall=e,this.defaultDeviceManager=t,this.logger=i,this.callStats=n,this.isMediaSending=r,this.stats=[],this.selectedVirtualDevice={camera:void 0,screenshare:void 0},this.subs=[this.defaultDeviceManager.on("onVirtualDevicesChanged",(()=>this.handleRegisteredDeviceChange()))],this.logger.info(`allowVirtualDeviceInCall: ${e}`)}get isVirtualDeviceEnabled(){return this.allowVirtualDeviceInCall}selectDevices(e){const t=this.defaultDeviceManager.getRegisteredDevices(),i=t.find((t=>t.id===e.camera)),n=t.find((t=>t.id===e.screenshare));this.logger.info(`Selecting virtual devices, camera: ${i?.id}, screenshare: ${n?.id}`);const r={camera:this.selectedVirtualDevice.camera?.id,screenshare:this.selectedVirtualDevice.screenshare?.id};e.camera!==r.camera||e.screenshare!==r.screenshare?(this.selectedVirtualDevice={camera:i,screenshare:n},this.addToCallStat({type:"VirtualDeviceSelected",payload:this.selectedVirtualDevice}),this.event("onSelectedVirtualDevicesChanged").raise(e,r)):this.logger.info("Virtual Device did not change.")}getSelectedDevices(){return Object.entries(this.selectedVirtualDevice).reduce(((e,[t,i])=>(e[t]=i?.id,e)),{})}getDeviceManager(e){return this.allowVirtualDeviceInCall?this.getDeviceManagersForVirtualDevice(e)[0]:this.defaultDeviceManager}getDeviceManagersForVirtualDevice(e){return"Video"===e&&this.selectedVirtualDevice.camera?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.camera.getDeviceManagers()):"ScreenShare"===e&&this.selectedVirtualDevice.screenshare?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.screenshare.getDeviceManagers()):(this.logger.info(`Using default DM, type: ${e}`),[this.defaultDeviceManager])}getDefaultDeviceManager(){return this.defaultDeviceManager}dispose(){this.stats=[],this.subs.forEach((e=>e.dispose())),super.dispose()}hasDevice(e){return this.defaultDeviceManager.id===e||[...this.selectedVirtualDevice.camera?.getDeviceManagers()??[],...this.selectedVirtualDevice.screenshare?.getDeviceManagers()??[]].some((t=>t?.id===e))}addToCallStat(e){const t=this.stats.push(e);this.callStats.appendCallDeviceManagerInfo({events:JSON.stringify(t)})}handleRegisteredDeviceChange(){const e=this.defaultDeviceManager.getRegisteredDevices(),{camera:t,screenshare:i}=this.selectedVirtualDevice;let n=!1,r=!1;t&&(n=e.some((e=>e.id===t.id)),this.logger.info(`Selected camera(${t.id}) in call, isCameraValid:${n}`)),i&&(r=e.some((e=>e.id===i.id)),this.logger.info(`Selected SS(${i.id}) in call, isScreenShareValid:${r}`)),this.selectDevices({camera:n?t.id:void 0,screenshare:r?i.id:void 0})}isModalityEnabled(e){return this.isMediaSending(Yh(e))}},If=class{constructor(e,t){this.logger=e,this.configProvider=t,this.debounceMap=new Map,this.enabledViaApi=!1,this.configProvider.config.remoteUFD?.enabledViaApi&&this.init()}init(){this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&(this.enabledViaApi=!0,this.logger.info(`Remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`))}raiseIfNeeded(e,t,i){if(this.shouldBeRaised(e,t))if(this.configProvider.config.localUFDDebounceTime)i(this.getState(e));else{clearTimeout(this.debounceMap.get(e.type));const t=setTimeout(i,this.configProvider.config.remoteUFD.debounceTime,this.getState(e));this.debounceMap.set(e.type,t)}}dispose(){for(const e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.enabledViaApi=!1}shouldBeRaised(e,t){return!(!this.configProvider.config.remoteUFD?.enabled||!this.enabledViaApi||t>this.configProvider.config.remoteUFD.maxParticipantNumber||!this.configProvider.config.remoteUFD.list[e.type])}getState(e){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify([e])}}},wf={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:Gi.MEDIA_EVENT_FIELDS,lowBattery:Gi.MEDIA_EVENT_FIELDS},Af=class extends gt{constructor(e){super(),this.configProvider=e}setDiagnosticsReport(e){this.diagnosticsReport=e}setEventType(e){if(!this.configProvider.config.smallCallTelemetry.enable)return;const t=Object.keys(this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary),i=this.getLastKnownMediaSessionStats();if(i&&(t?.forEach((t=>{if(t===e){const n=this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary[t],r={eventType:e,data:this.buildFromDictionary(i,n)};this.setTerminationCodeAndSubCodeToSuccess(r.data),this.event("sendSmallCallTelemetry").raise(r)}})),"reconnect"===e||"rejectNegotiation"===e||"visibilityHidden"===e||"lowBattery"===e)){const t={eventType:e,data:this.buildFromDictionary(i,wf[e])};void 0===t.data.metrics.TerminationReason_code&&this.setTerminationCodeAndSubCodeToSuccess(t.data),this.event("sendSmallCallTelemetry").raise(t)}}getEndCallSmallTelemetry(e){const t=this.getLastKnownMediaSessionStats(),i=this.buildFromDictionary(t,Gi.MEDIA_EVENT_FIELDS);return e&&(i.metrics.TerminationReason_code=Ar,i.metrics.TerminationReason_subCode=xr),{eventType:e?"tabClosed":"endCall",data:i}}getSmallTelemetryOnBatteryLow(){const e=this.getLastKnownMediaSessionStats(),t=this.buildFromDictionary(e,Gi.MEDIA_EVENT_FIELDS);return this.setTerminationCodeAndSubCodeToSuccess(t),{eventType:"lowBattery",data:t}}getLastKnownMediaSessionStats(){if(!this.diagnosticsReport)return;const e=this.diagnosticsReport.rawRootRef.sessions.length;return this.diagnosticsReport.getSessionTelemetry(this.diagnosticsReport.rawRootRef.sessions[e-1]?.sessionId)}buildFromDictionary(e,t){const i={Extensions:{},metrics:{}};if(!e)return i;for(const n in t)e[n]&&(i[n]={},t[n].forEach((t=>{void 0!==e[n][t]&&(i[n][t]=e[n][t])})));return i}setTerminationCodeAndSubCodeToSuccess(e){void 0===e.metrics.TerminationReason_code&&(e.metrics.TerminationReason_code=Ar,e.metrics.TerminationReason_subCode=Ar)}},Pf=class extends gt{constructor(e,t){super(),this.diagnostics=e,this.configProvider=t,this.hasSentLowBatteryEvent=!1,navigator?.getBattery?.().then((e=>{this.batteryManager=e,e.addEventListener("levelchange",this.onLevelChange.bind(this))}))}dispose(){this.batteryManager&&this.batteryManager.removeEventListener("levelchange",this.onLevelChange)}onLevelChange(e){const t=100*e.level;this.diagnostics.setBatteryLevel(t),t<=this.configProvider.config.lowBatteryThreshold&&!this.hasSentLowBatteryEvent&&(this.event("batteryStatusChanged").raise(t),this.hasSentLowBatteryEvent=!0)}},Rf=e=>`${e.type}:${e.mediaType}`,Mf=class{constructor(e,t){this.logger=e,this.configProvider=t,this.timestamps={},this.lastSentUFDValues=new Map,this.disabledUFDs=new Set}shouldRaise(e,t,i){if(!this.isEnabled(e,t,i))return!1;const n=Rf(e);if("Good"!==e.value&&this.shouldUFDBeDisabled(n)&&!this.disabledUFDs.has(n)&&(this.logger.info(`Disabling remote UFD: ${JSON.stringify(e)}`),this.disabledUFDs.add(n),setTimeout((()=>{this.disabledUFDs.delete(n)}),this.configProvider.config.remoteUFD.disableInterval)),this.disabledUFDs.has(n)&&"Good"!==e.value)return!1;const r=this.lastSentUFDValues.get(n);return!(this.disabledUFDs.has(n)&&"Good"===e.value&&(!r||"Good"===r))}registerSentUFDs(e){e.forEach((e=>{const t=Rf(e);this.lastSentUFDValues.set(t,e.value)}))}shouldUFDBeDisabled(e){var t;const i=this.configProvider.config.remoteUFD.maxNumberOfBadUFDsForThrottling;(t=this.timestamps)[e]??(t[e]=[]);const n=this.timestamps[e];return rt(n,Date.now(),i),!(n.length<i)&&n[i-1]-n[0]<this.configProvider.config.remoteUFD.throttlingTimeInterval}isEnabled(e,t,i){return!(!this.configProvider.config.remoteUFD?.enabled||!i||t>this.configProvider.config.remoteUFD.maxParticipantNumber||!this.configProvider.config.remoteUFD.list[e.type])}},Df=class{constructor(e,t,i){this.logger=e,this.configProvider=t,this.publishState=i,this.bundledUFDs=new Map,this.sentBundleWindow=[],this.enabledViaApi=!1,this.configProvider.config.remoteUFD?.enabledViaApi&&this.init()}raiseIfNeeded(e,t){const i=Rf(e);if(!this.remoteUFDFilter?.shouldRaise(e,t,this.enabledViaApi))return;const n=this.bundledUFDs.get(i);"Good"===e.value&&n&&"Good"!==n.value?this.bundledUFDs.delete(i):this.bundledUFDs.set(i,e)}dispose(){this.enabledViaApi=!1,this.bundledUFDs.clear(),clearTimeout(this.bundleInterval)}init(){!this.enabledViaApi&&this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&(this.enabledViaApi=!0,this.logger.info(`Initialized with remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`),this.remoteUFDFilter=new Mf(this.logger,this.configProvider),this.bundleInterval=window.setInterval((()=>this.sendUfdBundle()),this.configProvider.config.remoteUFD.bundlingInterval))}sendUfdBundle(){if(!this.bundledUFDs.size)return;if(this.sentBundleWindow.length>=this.configProvider.config.remoteUFD.maxNumberOfBundles){if(this.sentBundleWindow[0]+this.configProvider.config.remoteUFD.bundlingWindowInterval>Date.now())return;this.sentBundleWindow.shift()}const e=this.getState();this.logger.info(`Sending remote UFDs: ${e.content}`),this.remoteUFDFilter.registerSentUFDs(Array.from(this.bundledUFDs.values())),this.publishState(e),this.bundledUFDs.clear(),this.sentBundleWindow.push(Date.now())}getState(){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify(Array.from(this.bundledUFDs.values()))}}},kf=[1,2,9,10,11,12,30,27,28],Of="remote",Nf=class extends gt{constructor(e,t){super(),this.isStreaming=e,this.mediaType=t}},Lf=class e extends gt{constructor(t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S){super(n),this.signalingAgent=t,this.mediaAgent=i,this.logger=n,this.telemetryLoggers=r,this.currentUserSkypeIdentity=s,this.groupId=a,this.threadId=o,this.ecsProvider=d,this.trouterService=u,this.accountConfiguration=h,this.vdi3diagnostics=S,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 Wh({mediaStates:[Gh(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=e.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=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,{voicemailResourcePath:t.callVoicemailStartOptions.voicemailResourcePath,voicemailItemId:t.callVoicemailStartOptions.voicemailItemId,callToVoicemail:!0},Date.now()-r,e),this.getSignalingSessionCallOptions=e=>{const t={suppressDialout:!e.callStartOptions.ringOthers,isPreheatOnly:!(1&~e.callStartOptions.preheatFlags),onBehalfOf:this.onBehalfOfMri,onBehalfOfUserDisplayName:this.onBehalfOfUserDisplayName,callQueueContext:e.callStartOptions?.callQueueContext,muted:!(1&~e.callStartOptions.muteFlags),invitationType:e.invitationType,participantsToNudge:e.participantsToNudge,routingFlags:e.callStartOptions&&e.callStartOptions.routingFlags,parkContext:e.parkContext,pickupCode:e.pickupCode,scenario:e.callStartOptions&&e.callStartOptions.scenario,callUsesMixer:this.callUsesMixer,clientEndpointCapabilities:e.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:e.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:e.meetingPreferences,alternateId:e.callStartOptions?e.callStartOptions.alternateId:null,meetingRegistrationId:e.callStartOptions?e.callStartOptions.meetingRegistrationId:"",participantPin:e.callStartOptions?e.callStartOptions.participantPin:"",additionalEndpointProperties:e.callStartOptions?.additionalEndpointProperties||null,publishedStates:e.callStartOptions?.publishedStates||null,targetApplicationType:e.callStartOptions?.targetApplicationType,isHuddleGroupCall:e.callStartOptions?.isHuddleGroupCall,captchaContentJson:e.callStartOptions?.captchaContentJson,customHeaderContext:e.callStartOptions?.customHeaderContext,participationPreferences:e.callStartOptions?.participationPreferences,callingLineIdentity:e.callStartOptions?e.callStartOptions.callingLineIdentity:null,participantPropertyBag:e.callStartOptions?e.callStartOptions.participantPropertyBag:null},i=e.callStartOptions?.invitationDataJson;if(i)try{t.invitationData=JSON.parse(i)}catch(e){throw new Error(`Invalid JSON in invitationData: ${i}`)}return t},this.startOutgoingCall=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,this.getSignalingSessionCallOptions(t),Date.now()-r,e),this.joinGivenConversation=(e,t,i,n,r,s)=>{const a=!(1&~t.callStartOptions.muteFlags),o=!(1&~t.callStartOptions.preheatFlags),l=t.callStartOptions?.invitationDataJson,c=t.callStartOptions?.sharedLineCallInvitationContentJson;this.logger.info(`[${e}][joinGivenConversation] muted=${a}, isPreheatOnly=${o},\n sharedLineCallInvitationContentJson=${c}, invitationDataJson=${l},\n captchaContentJson=${!!t?.callStartOptions?.captchaContentJson}`);const d={muted:a,isPreheatOnly:o,clientEndpointCapabilities:t.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:t.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:t.meetingPreferences,meetingRegistrationId:t.callStartOptions?t.callStartOptions.meetingRegistrationId:"",participantPin:t.callStartOptions?t.callStartOptions.participantPin:"",additionalEndpointProperties:t?.callStartOptions?.additionalEndpointProperties,applyServerMute:t?.applyServerMute,publishedStates:t?.callStartOptions.publishedStates,invitationData:t?.callStartOptions.invitationDataJson,captchaContentJson:t?.callStartOptions.captchaContentJson,callQueueContext:t?.callStartOptions.callQueueContext,participationPreferences:t?.callStartOptions.participationPreferences,participantPropertyBag:t?.callStartOptions.participantPropertyBag};if(c)try{d.sharedLineCallInvitationContent=JSON.parse(c)}catch(e){throw new Error(`Invalid JSON in sharedLineCallInvitationContent: ${c}`)}if(l)try{d.invitationData=JSON.parse(l)}catch(e){throw new Error(`Invalid JSON in invitationDataJson: ${l}`)}return this.signalingSession.joinGivenConversation(s,this.callId,i,n,Date.now()-r,d,e)},this.getParticipantByLegId=(e,t,i)=>{this.logger.info(`getMriByParticipantLegId[${i}] participantLegId ${e}`);for(const i of t.participants)for(const t of i.endpoints.endpointDetails)if(t&&t.participantId&&t.participantId===e)return i;return null},this.executeCallTransfer=(e,t,i,n)=>{this._setTransferState(1);const r=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return 0===i?this.signalingSession.transferCallAsync(e,"TransferTypeStandard",void 0,n,t):2===i&&this.signalingSession.transferCallAsync(e,"TransferTypeVoicemail",void 0,n,t),r},this.executeConsultCallTransfer=(e,t,i,n,r)=>{this._setTransferState(1);const s=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,n,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return this.signalingSession.consultTransferCallAsync(e,t,i,n,r),s},this.createUpdateParticipantPromise=(e,t)=>this._callOperationHandler.createPendingOperation("UpdateParticipantsProperties",e,t),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=(e,t,i,n)=>{i.logFailure(e);let r,s={code:2,success:!1,fatal:!0},a=7;throw ph("SendAttach",e)&&(r={code:500,subCode:4105,phrase:"CallEndReasonAttachFailed"}),ph("ProcessIncomingCallRequest",e)&&(r={code:406,subCode:4103,phrase:"CallEndReasonBadNotificationPayload"},s={code:0,success:!1,fatal:!0}),gh(zs,e)&&(a=47),e?.error&&e.error.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer&&(r={code:ys,subCode:3111,phrase:"CallEndReasonIncompatibleOffer"}),this.callTelemetry.updateOperationData("Acknowledge",{phases:n,error:$e(e)},t),this._callOperationHandler.maybeRejectOperation("Acknowledge",s,void 0,t),this.stopInternal({rejectReason:r,causeId:t,terminatedReason:a}),s},this._onAcknowledgeSuccess=(e,t,i)=>(e.logSuccess("success"),this.callTelemetry.updateOperationData("Acknowledge",{phases:t},i),{code:1,success:!0}),this._processOfferedModalities=(e,t)=>{this.handleOfferedModalities(e,t);const i=this.callUsesMixer?void 0:{modalityOverride:e};return this.updateMediaModalities(i,t)},this._handleOfferProcessingError=(e,t,i)=>(i.logFailure(`handleOfferProcessingError=${e}`),e?.error?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer?(this.callTelemetry.recordEvent("IncompatibleOffer",void 0,t),this.signalingSession.supportsNewOfferRequest()?(this.newOfferRequestDeferred=new Kt,this.attachToCallAndGetOffer.promise.then((()=>this.mediaSession.rejectNegotiationAsync(e.error,t))).then((()=>this.signalingSession.requestNewOffer(this.mediaSession.getAcceptedTypes(),t))).then((()=>this.newOfferRequestDeferred.promise)).then((e=>this.mediaSession.processOfferAsync(e,t))).catch((e=>(this.callTelemetry.recordEvent("NewOfferFailed",je(e),t),Promise.reject(e))))):Promise.reject(e)):Promise.reject(e)),this._trySendProvisionalMediaAnswer=e=>Promise.resolve(void 0).then((()=>this.mediaSession.createAnswerAsync(!0,e))).then((e=>e.blob?(this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",void 0,be(),{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.signalingSession.setProvisionalAnswerAsync(e).then((()=>this.mediaAcknowledgmentOperation))):Promise.resolve(void 0))),this.checkForCallIdUpdate=(e,t)=>{if(this.callId!==e){this.logger.info(`[${t}][checkForCallIdUpdate] old=${this.callId}, new=${e}`),this.setCallId(e);try{this.event("callIdChanged").raise(this.callId)}catch(e){this.logger.error(`Error raising call ID change: ${e}`)}this.raiseChanged()}},this.handleRemoteParticipantStateInOneToOneCall=e=>{if(!this.callUsesMixer&&3===this.state){const t=this.participants[0];t&&t.setState(3,void 0,e)}},this.handleRemoteParticipantJoinedInOneToOneCall=(e,t)=>{if(!this.callUsesMixer&&3===this.state){const i=this.participants.filter((t=>t.id===e.id))[0];i?i.setState(3,void 0,t):this.logger.logFailure(`[${t}][handleRemoteParticipantJoinedInOneToOneCall]unable to find particpant ${De(e.id)}`)}},this.handleRemoteParticipantStateInObservingCall=(e,t,i)=>{const n=t.isLobby;if(8===this.state){const t=n?7:3;e.setState(t,void 0,i)}},this.getTelemetryFromPhaseExecution=e=>{const t={phase:e.phase,phases:e.phases,code:e.error&&e.error.code,subCode:e.error&&e.error.subCode,message:e.error&&e.error.message,error:e.error};return(t.code||t.message)&&delete t.error,t},this._setTransferState=e=>{this.transferState!==e&&(this.logger.info(`Transfer: state set: ${e}`),this._transferState=e,this.callTelemetry.recordEvent("_SetTransferState",{state:e}),this.raiseChanged())},this._setParkState=e=>{this.parkState!==e&&(this.logger.info(`Parking: state set: ${e}`),this._parkState=e,this.callTelemetry.recordEvent("_SetParkState",{state:e}),this.raiseChanged())},this.prepareNegotiationResultForTelemtry=e=>({isComplete:e.isComplete,activeModalities:e.activeModalities,configuredModalities:e.configuredModalities,initiator:De(e.initiator),attemptedModalities:e.attemptedModalities,offeredModalities:e.offeredModalities}),this.prepareTelemetryForOfferAnswer=e=>e&&e.mediaContent&&{isRenegotiation:!!e.renegotiation,isEscalation:!!e.mediaContent.isTwoPartyToMultiPartyEscalation,mediaTypes:e.mediaTypes,newOffer:e.mediaContent.newOffer},this.updateLocalParticipantEndpoints=e=>{const t=this.logger.createFnLogger("updateLocalParticipantEndpoints",""),i=[];(0,Ws.forEach)(e,(e=>{const t=Hh(e,this.getSelfClientEndpointCapabilities());i.push(t)})),this.endpoints.endpointDetails=i;const n=this.getDataChannelSourceId();-1!==n&&this.dataChannel&&this.dataChannel.setDataChannelSourceId(n),t.info(`selfEndpointDetails=${Qe(this.endpoints)}`)},this.handleParticipantsMutedUpdated=(e,t)=>{const i=this.logger.createFnLogger("handleParticipantsMutedUpdated",t);if(void 0!==e?.info){this.logger.info(`handleParticipantsMutedUpdated: number of infos: ${Object.keys(e.info).length}`);for(const t of Object.keys(e.info)){const n=this.getParticipant(t);n?n.handleServerMutedInfoUpdate(e.info[t]):i.info(`Cannot find local participant ${De(t)}`)}}else i.info("Ignored, no mute participant info.")},this.handleSelfUnmuteUpdatedInfo=(e,t)=>{const i=this.logger.createFnLogger("handleSelfUnmuteUpdatedInfo",t);if(void 0!==e?.info)for(const n of Object.keys(e.info)){const r=e.info[n];if(n===this.localSignalingParticipant.id){const e=(0,Ws.find)(r,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===e){i.info(`Cannot find local participant ${De(n)}`);continue}const s=(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(t=>t.participantId===e.participantId));tg(this.logger,s,e,!1)&&this.handleSelfServerMutedState(t)}}else i.info("Ignored, no unmute participant info.")},this.state=0,this.terminatedReason=0,this.callStats=new Uh,this.callDeviceManager=this.createCallDeviceManager(),this.callTelemetry=new Tr(this.logger,this._callCreationTime),this.collectMediaStatsDeferred=new Kt,this.setCallId(l),this.setGroupId(a),this.setThreadId(o),this.setMessageId(g),this.setSkypeId(this.currentUserSkypeIdentity.id),this.setParticipantId(c),this.setCallOrigin(0),this.vdi3diagnostics&&this.callStats.setRpcSessionId(this.vdi3diagnostics.getRPCSessionId()),this.logger=this.logger.createChild((()=>{const e=(this.endpointId||"").substr(0,8),t=(this.participantId||"").substr(0,8);return`Web/${this.instanceNumber}[${this.callId}][${e}][${t}][${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(c),this.signalingSession.setLocationInfo(p,m,v),this.streamManager=new Lg(this.participantId,null,this.callStats.localStats,this.logger),this.mediaAgent&&(this.dataChannel=new tp(this.logger),this.dataChannel.on("remoteUserEventsReceived",((e,t)=>this.event("remoteUserEventsReceived").raise(e,t))),this.dataChannel.on("onDataChannelStateUpdated",(e=>{"Failed"===e&&(this.logger.error("onDataChannelStateUpdated: datachannel creation failed, will remove data modality"),this.mediaStateConfigurationHelper.removeModality(3),this.updateSignalingDSHMessageSubscription(!0),this.updateMediaModalities())})),this.screenSharingControl=new Fp(this.logger,this.dataChannel,this,this.telemetryLoggers,this.ecsProvider,this.mediaAgent.getConfigProvider()),this.mediaAgent.handleSendMidCallTelemetry(this.sendMidCallTelemetry.bind(this)),this.remoteUFDHandler=this.mediaAgent.getConfigProvider().config.remoteUFD?.remoteUFDHandlerV2?new Df(this.logger.createChild("remoteUFDHandlerV2"),this.mediaAgent.getConfigProvider(),this.publishState.bind(this)):new If(this.logger.createChild("remoteUFDHandler"),this.mediaAgent.getConfigProvider()),this.smallCallTelemetry=new Af(this.mediaAgent.getConfigProvider()),this.smallCallTelemetry.on("sendSmallCallTelemetry",(e=>this.reportSmallCallEvent(e))));const y={enableErrorConversion:this.ecsProvider.getEcsConfig("SkypeCalling","enableErrorConversion")};this._deferUsingMicrotask=this.ecsProvider.getEcsConfig("SkypeCalling","deferUsingMicrotask"),cg.instance.setDeferToQueueMicrotask(this._deferUsingMicrotask),cg.instance.setLogger(n),this.logger.info(`operationHandlerEcsConfig: ${JSON.stringify(y)}`),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 as(this.logger,this.callTelemetry,y,void 0,((e,t)=>{this.preconditions(e,t)})),this._participantOperationHandler=new as(this.logger,this.callTelemetry,y),this.setMeetingData(f),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 e=this.signalingSession?.participantManager?.localParticipant?.participantId;this._participantId=e||this._participantId}catch(e){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(e){this._isAudioStreamConnected!==e&&(this._isAudioStreamConnected=e,this._wasAudioStreamConnected=this._wasAudioStreamConnected||e,this.raiseChanged())}setMeetingRole(e){e!==this.localSignalingParticipant.meetingRole&&(this.logger.info(`changing self role to [${e}]`),this.localSignalingParticipant.meetingRole=e,this.event("meetingRoleUpdated").raise(e))}setAdvancedMeetingRole(e){e!==this.localSignalingParticipant.advancedMeetingRole&&(this.logger.info(`changing self advanced meeting role to [${e}]`),this.localSignalingParticipant.advancedMeetingRole=e,this.event("advancedMeetingRoleUpdated").raise(e))}setMeetingRoles(e){(0,Ws.isEqual)(e,this.localSignalingParticipant.meetingRoles)||(this.logger.info(`changing self meeting roles to [${e}]`),this.localSignalingParticipant.meetingRoles=e,this.event("meetingRolesUpdated").raise(e))}setParticipantType(e){e!==this.localSignalingParticipant.participantType&&(this.logger.info(`changing self participant user type to [${e}]`),this.localSignalingParticipant.participantType=e,this.event("participantTypeUpdated").raise(e))}setPropertyBag(e){e&&!(0,Ws.isEqual)(e,this.localSignalingParticipant.propertyBag)&&(this.logger.info(`changing self participant property bag to [${e}]`),this.localSignalingParticipant.propertyBag=e,this.event("propertyBagUpdated").raise(e))}setPropertyRosterVersion(e){e!==this.localSignalingParticipant.version&&(this.logger.info(`changing self participant property version to [${e}]`),this.localSignalingParticipant.version=e,this.event("propertyRosterVersionUpdated").raise(e))}setMaskedIdentityDetails(e=!1,t,i){this.localSignalingParticipant.isIdentityMasked===e&&this.localSignalingParticipant.maskedIdSeqNumber===t&&this.localSignalingParticipant.maskedId===i||(this.localSignalingParticipant.isIdentityMasked=e,this.localSignalingParticipant.maskedIdSeqNumber=t,this.localSignalingParticipant.maskedId=i,this.logger.info(`self participant masked identity details updated to [${JSON.stringify(this.maskedIdentityDetails)}]`),this.event("maskedIdentityDetailsUpdated").raise(this.maskedIdentityDetails))}setIsSomeoneStreamingVideo(e){this.logger.debug(`setting isSomeoneStreamingVideo to [${e}]`),this.isSomeoneStreamingVideo=e}setJoinAsStreamingUser(e){e!==this.joinAsStreamingUser&&(this.logger.info(`setting self join as streaming user to [${e}]`),this.joinAsStreamingUser=e)}setOtpIdentity(e){e!==this.otpIdentity&&(this.logger.info("setting self participant optIdentity"),this.otpIdentity=e)}get spamRiskLevel(){return this._spamRiskLevel}set spamRiskLevel(e){e&&(this._spamRiskLevel=e)}isMultiVBSSEnabled(){return this.maxVbssChannels>=1}get spamStirAttestation(){return this._spamStirAttestation}set spamStirAttestation(e){e&&(this._spamStirAttestation=e)}getScreenHandle(e){if(!this.sharedScreenHandle){const t=!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled,i=!!this.mediaSession&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&!this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing,n=this.mediaStateConfigurationHelper.isSending(0)&&i&&t,r=3===e?.getType()?e?.getDeviceId():void 0,s=this.callDeviceManager.getDeviceManager(Jh(2));s.setAudioSharingRequested(n),this.sharedScreenHandle=s.createDevicesHandle({audio:n,sharing:!0},"pluginlessCall:getScreenHandle()",r),this.sharedScreenHandle.on("onStreamStateChanged",((e,t)=>this.onSharingStreamStateChanged(e)))}return this.sharedScreenHandle}setCallOrigin(e){this.logger.info(`Set call origin to ${e}`),this._origin=e,this.callTelemetry.setCallOrigin(e),this.callTelemetry.recordEvent("_SetCallOrigin",{origin:e})}setMediaLegId(e){this._mediaLegId=e,this.callStats.setMediaLegId(e)}setCallId(e){this.callTelemetry.setCallId(e),this.callStats.setCallId(e),this._callId=e}setEndpointId(e){this._endpointId=e,this.logger.info(`[endpointId=${qe(this._endpointId,8)}]`),this.callTelemetry.setEndpointId(e),this.callStats.setEndpointId(e)}setFailureType(e){this.callTelemetry.setFailureType(e),this.failureType=e}setParticipantId(e){this._participantId!==e&&(this._participantId=e,this.logger.info(`[participantId=${this._participantId}]`),this.callTelemetry.setParticipantId(this.participantId),this.event("callLegIdChanged").raise(this.participantId))}setDisplayName(e,t=be()){this.logger.info(`[${t}][setDisplayName] displayName=${qe(e,4)}`),this.localSignalingParticipant.displayName=e,"anonymous"===this.participantType&&(this.callStats.setDisplayName(e),this.callTelemetry.setDisplayName(e),this.signalingSession.setDisplayName(e))}setCallerMri(e){this.callerMri=e,this.logger.info(`[callerMri=${De(this.callerMri)}]`)}setDisplayNameSource(e){this.displayNameSource=e,this.logger.info(`[displayNameSource=${this.displayNameSource}]`)}setTransferorMri(e){const t=uh(e);t!==this.transferorMri&&(this.transferorMri=t,this.logger.info(`transferorMri: ${De(this.transferorMri)}`),this.raiseChanged())}setGroupId(e,t=be()){this.logger.info(`[${t}][setGroupId] groupId=${De(e)}`),this.groupId!==e&&(this.groupId=e,this.callTelemetry.setGroupId(e),this.event("groupIdChanged").raise(e))}setMeetingData(e){if(e){if(e.meetingCode&&(!this.meetingData||this.meetingData&&e.meetingCode!==this.meetingData.meetingCode)){const t=e.meetingCode;this.logger.info(`[setMeetingData] meetingCode=${!!t}`),this.callTelemetry.setMeetingCode(t),this.signalingSession.setMeetingCode(t)}if(e.meetingUrl&&(!this.meetingData||this.meetingData&&e.meetingUrl!==this.meetingData.meetingUrl)){const t=e.meetingUrl.split("?")[0];this.logger.info(`[setMeetingData] meetingUrl=${!!e.meetingUrl}`),this.callTelemetry.setMeetingUrl(t),this.signalingSession.setMeetingUrl(t)}}this.meetingData=e}setHuddleGroupCall(e){this.isHuddleGroupCall!==!!e&&(this.logger.info(`[setHuddleGroupCall] new isHuddleGroupCall=${e}`),this.isHuddleGroupCall=e,this.callTelemetry.setIsHuddleGroupCall(!0))}onConversationStartTimeChanged(e,t=be()){if(this.logger.info(`onConversationStartTimeChanged: Conv start time=${e}`),e&&this._rawConversationStartTime!==e){this.logger.info(`[${t}][onConversationStartTimeChanged] rawConvStartTime=${e}`);try{this.conversationStartTime=new Date(e),this._rawConversationStartTime=e,this.callTelemetry.setConversationStartTime(e)}catch(t){this.logger.warn(`Failed to parse the raw conv start timestamp. Error: ${t}, rawConvStartTime: ${e}`)}}}setComplianceRecordingContent(e,t){try{if(!(0,Ws.isEqual)(this.complianceRecordingContent,t)){this.complianceRecordingContent=t;const i=t?JSON.stringify(t):"";this.callTelemetry.setComplianceRecordingContentLength(i.length),this.logger.info(`[${e}][setComplianceRecordingContent] complianceRecordingContentLength=${i.length}`)}}catch(t){this.logger.error(`[${e}][setComplianceRecordingContent] ${t}`)}}setThreadId(e,t=be()){this.threadId!==e&&(this.logger.info(`[${t}][setThreadId] threadId=${xe(e)}`),this.threadId=e,this.callTelemetry.setThreadId(e))}setBackroomThreadId(e,t=be()){this.backroomThreadId!==e&&(this.logger.info(`[${t}][setBackroomThreadId] backroomThreadId=${xe(e)}`),this.backroomThreadId=e,this.callTelemetry.setBackroomThreadId(e))}setStreamThreadId(e,t=be()){this.streamThreadId!==e&&(this.logger.info(`[${t}][setStreamThreadId] streamThreadId=${xe(e)}`),this.streamThreadId=e,this.callTelemetry.setStreamThreadId(e))}setLobbyThreadId(e,t=be()){this.lobbyThreadId!==e&&(this.logger.info(`[${t}][setLobbyThreadId] lobbyThreadId=${xe(e)}`),this.lobbyThreadId=e,this.callTelemetry.setLobbyThreadId(e))}setMeetingLayoutDetails(e,t=be()){(0,Ws.isEqual)(this.meetingLayoutDetails,e)||(this.logger.info(`[${t}][meetingLayoutDetails updated]`),this.meetingLayoutDetails=e,this.event("meetingLayoutChanged").raise(this.meetingLayoutDetails))}setCompositionServiceDetails(e,t=be()){(0,Ws.isEqual)(this.compositionServiceDetails,e)||(this.logger.info(`[${t}][compositionServiceDetails updated]`),this.compositionServiceDetails=e,this.event("compositionServiceDetailsChanged").raise(this.compositionServiceDetails),this.callTelemetry.setCompositionServiceState(e?.state))}setMessageId(e,t=be()){this.logger.info(`[${t}][setMessageId] messageId=${De(e)}`),this.messageId=e,this.callTelemetry.setMessageId(e)}setSkypeId(e,t=be()){this.skypeId!==e&&(this.logger.info(`[${t}][setSkypeId]`),this.skypeId=e,this.callTelemetry.setSkypeId(e))}setCallType(e,t){const i=this.logger.createFnLogger("setCallType",t);i.info(`current=${this.callType}, newValue: ${e}`),2!==this.callType||1!==e?e!==this.callType&&(this.callType=e,this.callTelemetry.setCallType(e),2===e&&this.callStats.localStats.call.event(2),this.raiseChanged()):i.logFailure("De-escalating to P2P should not happen!")}setConversationType(e,t){this.logger.createFnLogger("setConversationType",t).info(`current=${this.conversationType}, newValue=${e}`),e!==this.conversationType&&(this.conversationType=e,this.callTelemetry.setConversationType(e),this.raiseChanged())}setCallUsesMixer(e,t){this.callUsesMixer!==!!e&&(this.logger.info(`[${t}][setCallUsesMixer] new value=${e}`),this.callUsesMixer=e,this.callTelemetry.recordEvent("_CallUsesMixer",{newValue:e},t),this.dataChannel.setConfigProviderView(this.mediaSession?.getSessionConfig()))}_setMaxVbssChannels(e,t){this.logger.createFnLogger("MaxVbssChannels",t).info(`current=${this.maxVbssChannels}, newValue=${e}`),e!==this.maxVbssChannels&&(this.maxVbssChannels=e,this.callTelemetry.recordEvent("_setMaxVbssChannels",{MaxVbssChannels:e},t),this.raiseChanged())}setIsEscalationInProgress(e,t){this.logger.info(`[${t}][setIsEscalationInProgress] currentValue=${this.isEscalationInProgress}, newValue=${e}`),this.isEscalationInProgress=e,this.allowScreenSharingControl()&&this.screenSharingControl.setIsEscalationInProgress(e),this.callTelemetry.recordEvent("_EscalationInProgress",void 0,t)}setFromApplicationType(e,t){e&&(this.fromApplicationType=e,this.callTelemetry.recordEvent("_SetFromApplicationType",{fromApplicationType:e},t))}setCalleeAlternateId(e,t){e&&(this.calleeAlternateId=e,this.callTelemetry.recordEvent("_SetCalleeAlternateId",{hasCalleeAlternateId:!!e},t))}setEnableCaptcha(e){e!==this.localSignalingParticipant.enableCaptcha&&(this.logger.info(`setting self participant to enable captcha to [${e}]`),this.localSignalingParticipant.enableCaptcha=e,this.enableCaptcha=e)}processCallStartOptions(e,t){const i=this.logger.createFnLogger("_ProcessCallStartOptions",t);try{1&e.preheatFlags&&(this.isPreheatEnabled=!0)}catch(e){i.logFailure(e)}}getlocalScreenShareStream(){return(0,Ws.find)(this.localMediaStreams,(e=>2===e.mediaType))}setRoutingTimeout(e){this.routingTimeout=e,this.logger.info(`[routingTimeout=${this.routingTimeout}]`)}setMeetingLayout(e,t){const i=this.logger.createFnLogger("SetMeetingLayout",e);return Promise.resolve().then((()=>this.signalingSession.setMeetingLayoutAsync(e,t))).catch((e=>(i.logFailure(je(e)),Promise.reject(ns(e))))).then((()=>this._callOperationHandler.waitForOperation("SetMeetingLayout",e))).catch((t=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:$e(t)},e),i.logFailure(t),t}))}async selectDevices(e){this.callDeviceManager.isVirtualDeviceEnabled?this.callDeviceManager.selectDevices(e):this.logger.error("allowVirtualDeviceInCall not enabled.")}async getSelectDevices(){return this.callDeviceManager.getSelectedDevices()}createStage(e){throw new Error("Method not implemented.")}updateDisplayName(e){this.logger.info("updating displayName"),this.setDisplayName(e),this.signalingSession.participantManager.localParticipant.displayName=e}init(e){if(this.logger.info(`init callInitOptions:${function(e){const t={mediaPeerType:e.mediaPeerType,threadId:xe(e.threadId)};return ze(e.messageId)&&(t.messageId=e.messageId),ze(e.enableGroupCallMeetupGeneration)&&(t.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration),ze(e.endpointMetadata)&&(t.endpointMetadata=e.endpointMetadata),ze(e.onBehalfOf)&&(t.onBehalfOf=De(e.onBehalfOf)),ze(e.onBehalfOfUserDisplayName)&&(t.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName),ze(e.emergencyContent)&&(t.emergencyContent=e.emergencyContent),ze(e.isEmergency)&&(t.isEmergency=e.isEmergency),ze(e.broadcastContext)&&(t.broadcastContext=e.broadcastContext),e.meetingInfo&&(t.meetingInfo={tenantId:e.meetingInfo.tenantId,organizerId:De(e.meetingInfo.organizerId)},ze(e.meetingInfo.meetingType)&&(t.meetingInfo.meetingType=e.meetingInfo.meetingType),ze(e.meetingInfo.replyChainMessageId)&&(t.meetingInfo.replyChainMessageId=e.meetingInfo.replyChainMessageId)),e.transferContext&&(t.transferContext={transferorMri:De(e.transferContext.transferorMri),targetMri:De(e.transferContext.targetMri),context:ke(e.transferContext.context)},ze(e.transferContext.transferType)&&(t.transferContext.transferType=e.transferContext.transferType)),Ge(t)}(e)}`),this.signalingSessionCallOptions={teamsMessageId:e.messageId,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration,meetingInfo:e.meetingInfo,emergencyContent:e.emergencyContent?JSON.parse(e.emergencyContent):void 0,broadcastContext:e.broadcastContext,endpointMetadata:e.endpointMetadata},this.setMessageId(e.messageId),this.onBehalfOfMri=e.onBehalfOf,this.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName,e.threadId&&(this.setThreadId(e.threadId),this.signalingSession.setThreadId(e.threadId)),this.groupId&&this.signalingSession.setGroupId(this.groupId),this.signalingSession.setCallOptions(this.signalingSessionCallOptions),e.transferContext){switch(this.logger.info("Transfer: Call.init, set transferContext",function(e){return function(e){const t=JSON.stringify(e),i=JSON.parse(t);return i&&(ng(e,i,[],ig.pii.Omit),ng(e,i,["transferorMri","targetMri"],ig.pii.Mri),ng(e,i,void 0,ig.pii.UserName)),JSON.stringify(i)}(ke(e))}(e.transferContext)),this.signalingSession.setTransferContext(e.transferContext.context),e.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: ${e.transferContext.transferType} doesn't have a switch option`)}e.transferContext.context.callAcceptanceCallback?this._transferredCallAcceptanceCallback=e.transferContext.context.callAcceptanceCallback:this.logger.info("[failed]Transfer: Missing transferred call acceptance callback"),e.transferContext.transferorMri&&this.setTransferorMri(e.transferContext.transferorMri)}this.setIsEmergency(!!e.isEmergency),this.raiseChanged()}async initAsync(e){return this.init(e)}getIncomingRawAudioStream(e=be()){if(!this.mediaSession)throw this.logger.error("can not execute getIncomingRawAudioStream as there is no mediaSession"),new Error("NoMediaSession");return this.mediaSession.getIncomingRawAudioStream(e)}getUnmixedAudioProvider(){return this.unmixedAudioProvider?Promise.resolve(this.unmixedAudioProvider):Promise.reject("No audio provider available")}setDeviceManager(e){}async startVideo(e,t=be()){return this.startStopVideo(!0,t,e)}async stopVideo(e,t=be()){return this.startStopVideo(!1,t,e)}async dumpVideoSourceImages(){return Promise.reject(60)}async hold(e,t=be(),i,n){const r=this.logger.createFnLogger("Hold",t);return r.info(`[Hold][${t}] negotiationTag ${e} hold options: ${Ge(i)}`),4===this.state?(r.logFailure("Trying to put a call on hold which is already held state, early resolving the promise"),Promise.resolve(void 0)):i?.isLocal?this.localHold(t,i,n):this.holdWithRenegotiate(t,i)}async holdWithRenegotiate(e,t){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t):(this.logger.logFailure(`[Hold][${e}] 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(e,t,i){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t,i):(this.logger.logFailure(`[LocalHold][${e}] 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(e,t=be()){const i=this.logger.createFnLogger("Unhold",t);return 3===this.state?(i.logFailure("Trying to resume a call which is already in connected state, early resolving the promise"),Promise.resolve(void 0)):4===this.state?(i.info(`current hold state ${this.requestedHoldState}`),this.setHold(!1,t)):(i.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(e,t){const i=e.isOneToOneCall(),n=3===this.state,r=4===e.state,s=i&&n&&r;return this.logger.info(`[${t}][canMerge] Call ${e.callId} isOneToOne ${i} isCallConnected ${n} call.state ${this.state} isMergeOnHold ${r} mergeCall.state ${e.state} CanMerge result: ${s}`),s}async updateEndpointMetadata(e,t=be()){return this.signalingSession.updateEndpointMetadata(e,t)}async sendDtmfTone(e){if(this.mediaSession){const t=this.toneToString(e);return t?(this.logger.info(`[${Wr}][sendDtmfTone]DtmfTone: <omitted>`),Promise.resolve(this.mediaSession.sendDtmf(t))):Promise.reject(new Error("Unsupported DtmfTone"))}return Promise.reject(new Error("no mediaSession"))}async setAudioUsageMode(e){return Promise.reject(60)}async setAudioMidcallConfig(e,t){return Promise.reject(60)}async setAudioMidcallConfigJson(e,t=be()){if(!e)return Promise.reject(60);Wi(e.enableSpatialAudio)&&this.mediaSession?.configureSpatialAudio(e.enableSpatialAudio,t),e.noiseSuppressionMode&&await this.setNoiseSuppressionMode(e.noiseSuppressionMode,e.enableAEC)}async setParticipantSpatialAudioPositions(e,t=be()){const i=e.map((e=>({sourceId:this.participants.find((t=>t.id===e.participantId))?.audio.id,x:e.x,y:e.y})));return this.mediaSession?.setParticipantSpatialAudioPositions(i,t)}async setNoiseSuppressionMode(e,t){return this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe||this.mediaSession.getSessionConfig().config.wasmdns.enableNoiseSuppression?"Auto"===e?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,t))):this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,this.mediaSession.getSessionConfig().config.wasmvqe.enableAec))):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,t))):Promise.resolve()}setInitialTelemetry(e,t,i,n){let r,s,a,o,l;switch(e){case"Subscribe":case"SubscribeWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("SUBSCRIBE"),i||this.callTelemetry.setOperationVariant(e,"CCWM"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i});break;case"Acknowledge":0!==this.state&&8!==this.state&&this.callTelemetry.maybeRecordOperationSuccess(e,{code:4}),this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("callee"),this.signalingSession.setInitialTelemetry(e,{causeId:n});break;case"JoinCall":case"JoinWithMeetingData":this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("join"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),s=!(1&~t.callStartOptions.muteFlags),a=!(1&~t.callStartOptions.preheatFlags),o={muted:s,isPreheatOnly:a},this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,joinCallOptions:o,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCall":case"StartWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),l=t.callStartOptions,this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,callStartOptions:l,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,startCallOptions:t.callStartOptions,offerGenerationTime:Date.now()-t.callStartTime})}}async setHold(e,t,i,n){const r=this.logger.createFnLogger("setHold",t,`hold=${e}`);if(!this.canToggleAudio||this.callHoldResumeDeferred)return Promise.reject(new Error("can not set hold as it is already in progress"));this.callHoldResumeDeferred=new Kt,this.isHoldInProgress=e,this.canToggleAudio=!1,this.canToggleVideo=!1,this.canToggleScreenSharing=!1,this.requestedHoldState=e;const s=()=>{this.canToggleAudio=!0,this.canToggleScreenSharing=!0,this.canToggleVideo=!0};r.info(`start, holdOptions: ${JSON.stringify(i)}`);const a=this.callHoldResumeDeferred.promise,o=e?"Hold":"Unhold",l={debugContent:{clientScenario:this.convertClientScenario(n)}};try{if(e?this.isMuteOnHold=i&&i.isLocal&&5!==this.state:this.prepareModalitiesForResume(t),!this.isMuteOnHold){const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t),this.updateScreenSharingState(e,t)}e&&(this.prepareModalitiesForHold(t),5===this.state&&this.finishCallHoldResume(),this.setCallState(4,t)),this.isMuteOnHold&&this.setMuteOnHold(e,t),s();const n={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(o,n,null,t,l)}catch(i){this.callTelemetry.recordOperationFailure(o,{error:$e(i)},null,t,l),r.logFailure(i),s(),this.callHoldResumeDeferred?.reject(new Error(`Failed setting hold state to ${e}`)),this.callHoldResumeDeferred=null}return a}transferCall(e){return this.logger.warn("transferCall is deprecated, please use callBlindTransfer instead"),this.callBlindTransfer(e)}callBlindTransfer(e,t=be(),i){return this.executeCallTransfer(e,t,0,i)}callSafeTransfer(e,t=be(),i){return this.executeCallTransfer(e,t,0,i)}transferCallToVoicemail(e,t=be()){return this.executeCallTransfer(e.transferTargetMri,t,2,void 0)}callConsultativeTransfer(e,t=be(),i,n){const r=this.logger.createFnLogger("ConsultativeTransfer",t);let s;e.participants.length>1?(s=this.getParticipantByLegId(i,e),s||(r.warn("getParticipantByLegId did not find a match in the participants list, defaulting to first participant"),s=e.participants[0])):s=e.participants[0];const a=s&&s.acceptedBy||s&&s.id;return r.info(`transferTargetParticipantLegId: ${i} targetMri: ${De(a)}`),this.executeConsultCallTransfer(e.callId,a,i,t,n)}async consultativeTransferWithPickupCode(e,t){const i=this.logger.createFnLogger("ConsultativeTransferWithPickupCode",t);if(i.info(`pickup code: ${e}`),!e||isNaN(Number(e)))return i.info("pickup code cannot be empty"),Promise.reject(ns("TransactionDisallowed"));const n=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),r=`4:${mr}`,s={unparkContent:{pickupCode:Number(e)}};return this.signalingSession.transferCallAsync(r,"TransferTypeStandard",s,{disableForwardingAndUnanswered:!1},t),n}callRedirect(e,t=be()){return this.logger.createFnLogger("CallRedirect",t).info(`redirectOptions: ${JSON.stringify(e)}`),this.stopInternal({terminatedReason:75,redirectOptions:e,causeId:t}).then((()=>({code:302,subCode:3020,phrase:js,resultCategories:["Success"]})))}convertParkContext(e){switch(e){case 1:return"sharedLinePark";case 4:return"sharedLineParkV2";case 0:return"teamPark";case 3:return"serverHoldV2";case 5:return"callPark";default:return"serverHold"}}convertClientScenario(e){switch(e){case 0:return"breakoutRoom";case 1:return"musicOnHoldV2";case 2:return"sharedLineAppearanceV2";default:return}}park(e,t=be()){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [ParkCall] start - context ${e} parkType ${i}`),5===e?(this.callTelemetry.recordOperation(`${co(i)}`,t),this._pendingParkPromise=this._callOperationHandler.createPendingOperation("CallParkV2",void 0,t)):this._pendingParkPromise=this._callOperationHandler.waitForOperation("ParkCall"),"serverHoldV2"!==i&&"callPark"!==i&&this._setParkState(1),this.signalingSession.parkCallAsync(i,t).catch((e=>{this.logger.info(`[${t}] [ParkCall] error in parkCallAsync (synchronous error) : ${$e(e)}. Hold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("ParkCall",{error:$e(e)},t)})),this._pendingParkPromise}async unpark(e,t){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [UnparkCall] start - context ${e} parkType ${i}`),this._pendingUnparkPromise=this._callOperationHandler.waitForOperation("UnparkCall"),this.signalingSession.unparkAsync(i,t).catch((e=>{this.logger.info(`[${t}] [UnparkCall] error in unparkAsync (synchronous error) : ${$e(e)}. Unhold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UnparkCall",{error:$e(e)},t)})),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(e=!1){if(e){const e=(this.state,[0,1]);return 1===this.callType&&e.includes(this.participants.length)}return 1===this.callType&&1===this.participants.length}setMuteOnHold(e,t){this.mediaSession.muteHold(e,t),e||(this.computeCallState(t),this.isMuteOnHold=!1),this.finishCallHoldResume()}finishCallHoldResume(e){e?this.callHoldResumeDeferred?.reject(e):this.callHoldResumeDeferred?.resolve(),this.isHoldInProgress=!1,this.callHoldResumeDeferred=null}computeCallState(e){let t=3;this._callInLobby?t=10:this.signalingSession.participantManager.localParticipant.isStaging&&(t=13),this.logger.info(`[${e}][computeCallState] the call state will be set to ${t}`),this.setCallState(t,e)}async prepareModalitiesForResume(e){this.mediaStateConfigurationHelper.isSending(1)&&await this.turnOnLocalVideoPreview(e)}async prepareModalitiesForHold(e){await this.turnOffLocalVideoPreview(e)}updateMediaState(e,t){this.setVideoOn(e.video===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.video===this.mediaAgent.constants.MEDIA_STATE.send,t),this.setAudioOn(e.audio===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.audio===this.mediaAgent.constants.MEDIA_STATE.send,t)}updateScreenSharingState(e,t){this.setScreenSharingOn(e.sharing===this.mediaAgent.constants.MEDIA_STATE.send,t)}onSharingStreamStateChanged(t){const i=be();this.logger.info(`[${i}] Sharing stream state moved to ${t}`);const n={mediaType:2,mediaDirection:1,mediaStreamState:e.streamingStatetoMediaStreamState(t)};this.event("mediaStreamStateChanged").raise(n),this.callStats.localStats.screenShare.streamStateChanged(t),"stopped"===t&&(this.canToggleScreenSharing=!0,this.stopScreenSharing(),"screenSharingCall"!==this.conversationType||this.participants.some((e=>3===e.state))||this.stop(!0,i))}async startScreenSharing(e,t,i,n=be()){this.allowScreenSharingControl()&&(this.screenSharingControl.isInternalViewerControlEnabled()&&this.screenSharingControl.shutdownControlForViewer(),this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(i));const r=this.logger.createFnLogger("StartScreenSharing",n);return r.info(`started. negotiationTag is ${i}`),this.canToggleScreenSharing?this.isScreenSharingOn?(r.logSuccess("Resolving early because screen sharing is already on"),Promise.resolve()):(this.screenSharingRenegotiationDeferred&&(r.logFailure("called before the renegotiation deferred for the previous one has been closed"),this.screenSharingRenegotiationDeferred.resolve()),this.screenSharingRenegotiationDeferred=new Kt,this.callStats.localStats.newSession(2),this.callStats.localStats.screenShare.start(),this.mediaStateConfigurationHelper.isDisabled(2)&&r.info("sharing modality was skipped till now. Adding it now"),this.canToggleScreenSharing=!1,this.callStats.localStats.screenShare.event(0),this.getScreenHandle(e).acquire().then((()=>(r.logSuccess("sharing stream acquired"),this.mediaStateConfigurationHelper.enableModality(2),this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this._delayedElevationPending&&!this._delayedElevationQueued?this.triggerDelayedReconnectIfNeeded(n):Promise.resolve()))).then((()=>this.updateMediaModalities(void 0,n,i))).then((()=>(r.logSuccess("updateMediaModalities done"),this.callStats.localStats.screenShare.negotiationStateChanged("started"),this.setScreenSharingOn(!0,n),this.canToggleScreenSharing=!0,this.screenSharingRenegotiationDeferred.promise))).then((()=>{this.enableControlInjector(),this.callStats.localStats.screenShare.negotiationStateChanged("completed")})).catch((e=>{this.callTelemetry.updateOperationData("StartScreenSharing",{error:$e(e)},n),this.setScreenSharingOn(!1,n),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!0,this.disposeSharingScreenHandle();const t=e.error;throw t&&491===t.code?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),r.logFailure("starting screen sharing failure with reason glare")):"ScreenSharingStopped"===e.reason?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","sharingStopped"),r.logFailure("expected starting screen sharing failure with reason stopped")):(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","other"),r.logFailure(e)),e}))):Promise.reject(new Error("cannot start screen sharing"))}async stopScreenSharing(e,t,i=be()){const n=this.logger.createFnLogger("StopScreenSharing",i);if(n.info(`started. negotiationTag is ${t}`),!this.canToggleScreenSharing)throw n.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,i,t),this.canToggleScreenSharing=!0,this.callStats.localStats.screenShare.stop(),this.disposeSharingScreenHandle(),this.mediaAgent.getDeviceManager().shareSystemSound(!1),this.mediaAgent.getDeviceManager().setAudioSharingRequested(!1);try{this.setScreenSharingOn(!1,i)}catch(e){throw n.logFailure(e),this.callTelemetry.updateOperationData("StopScreenSharing",{error:$e(e)},i),e}}else n.logFailure("screensharing is not on, ignore this operation")}async startDataChannel(e,t=be()){if(!this.allowDataChannel())throw new Error("startDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.enableModality(3),await this.updateMediaModalities({},t)}async stopDataChannel(e,t=be()){if(!this.allowDataChannel())throw new Error("stopDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.removeModality(3),await this.updateMediaModalities({},t)}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 e=this.mediaSession?.getSessionConfig()?.config;return e?!this.allowDataChannel()||e.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(e){this.signalingSession.updateDominantSpeakerHistoryMessageSubscription(e),e&&this.mediaSession?.getDiagnostics?.().dshDiagnostics.setCurrentActiveStrategy("signaling")}async sendUserEvents(e,t){return this.dataChannel.sendUserEvents(e,t)}async shareSystemSound(e,t=be()){const i=this.logger.createFnLogger("ShareSystemSounds",t,`shareSystemSound=${e}`);if(!(this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing))return i.error("shareSystemSound not allowed"),Promise.reject(60);try{return void this.mediaAgent.getDeviceManager().shareSystemSound(e)}catch{return i.error("shareSystemSound failed with device error"),Promise.reject(58)}}async mute(e=mi()){return this.isMuted?Promise.reject(ns("TransactionDisallowed")):this.muteUnmute(!0,e)}async unmute(e=mi()){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")&&await this._callOperationHandler.waitForOperation("_PromotionToRealtime"),this.muteUnmute(!1,e)}async muteSpeaker(e=be()){return this.muteUnmuteSpeaker(!0,e)}async unmuteSpeaker(e=be()){return this.muteUnmuteSpeaker(!1,e)}async getSpeakerVolume(e=be()){return await this.mediaSession.getSpeakerVolume(e)}async setSpeakerVolume(e,t=be()){return this.mediaSession.setSpeakerVolume(e,t)}async muteParticipants(t,i,n=mi()){const r=this.logger.createFnLogger("MuteParticipants",n,`muteScope=${t}`);r.info(`callParticipants count=${i.length}`);const s=e.convertMuteScope(t);if(void 0===s)return r.logFailure(`Unrecognized ${t}`),Promise.reject(new Error("Unrecognized muteScope"));if(fh(this.state,[11,12]))return r.logFailure("Can not mute/unmute during preheat call"),Promise.reject(60);const a=[];return i.forEach((e=>{a.push(e.id)})),this.signalingSession.muteAsync(s,a,n).then((e=>this.handleParticipantsMutedUpdated(e,n))).catch((e=>(this.callTelemetry.updateOperationData("MuteParticipants",{error:$e(e)},n),r.logFailure(e),e?.endCode?Promise.reject(e.endCode):Promise.reject(e))))}async startAudio(e,t=be()){const i=this.logger.createFnLogger("StartAudio",t);if(this.receiveOnlyAudioOnCallStart=!1,3!==this.state)return i.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(t)}catch(e){return i.logFailure(e),Promise.reject(25)}const n=await this.startStopAudio(!0,t);return await this.signalingSession.recordTelemetryForStartAudio(n),{code:n}}async stopAudio(e,t=be()){const i=this.logger.createFnLogger("StopAudio",t);if(3!==this.state)return i.logFailure("Cannot stopAudio when call is not connected"),Promise.reject(60);this.mediaStateConfigurationHelper.removeModality(0);const n=await this.startStopAudio(!1,t);return await this.turnOffLocalVideoPreview(t),await this.signalingSession.recordTelemetryForStopAudio(n),{code:n}}assimilate(e,t,i,n=be()){return Promise.reject(new Error("Not implemented"))}async merge(e,t,i=be()){const n=this.logger.createFnLogger("MergeCall",i);n.error(`merge callId ${e.callId} callMergeOptions ${JSON.stringify(t)}`);const r=this.canMerge(e,i);if(!r)return n.info(`Error. ${je(r)}`),Promise.reject(ns("TransactionDisallowed"));const s=[];return e.participants.forEach((e=>{s.push(this._callOperationHandler.createPendingOperation("MergeCall",e.id,i))})),(await this.mergeCallByAddParticipantWithReplaces(t,e.participants,e,1,"MergeCall",i,s,void 0))[0]}async mergeParticipants(e,t,i,n,r){const s=this.logger.createFnLogger("MergeParticipants",n),a=[];if(!e)return Promise.reject(ns("Invalid callToMerge"));if(0===t.length)return Promise.reject(ns("Invalid participantIds"));const o=[];for(const i of t){let t=xd(e,i);if(!t&&Ld(e,i)&&(s.info("found self endpoint, use localSignalingParticipant"),t=this.localSignalingParticipant),t){const e=mi(),r={id:t.id,participantId:e,replacementParticipantId:i,nonMaskedId:t.nonMaskedId};a.push(r),o.push(this._callOperationHandler.createPendingOperation("MergeParticipant",e,n))}else{const e={code:406,subCode:5201,phrase:`participantLegId ${i} is invalid!`};o.push(Promise.reject(ns(e)))}}return this.mergeCallByAddParticipantWithReplaces(i,a,e,3,"MergeParticipant",n,o,r)}async mergeWithPickupCode(e,t,i=be()){const n=this.logger.createFnLogger("MergeWithPickupCode",i);if(n.info(`mergeWithPickupCode: pickup code: ${e}, groupId: ${De(t.groupId)}, threadId: ${xe(t.threadId)} messageId: ${t.messageId}`),!e||isNaN(Number(e)))return n.info("mergeWithPickupCode: pickup code cannot be empty"),Promise.reject(ns("mergeWithPickupCode: pickup code cannot be empty"));const r={additionalData:t.additionalData,groupId:t.groupId,threadId:t.threadId,messageId:t.messageId,replacementType:2,pickupCode:Number(e)},s={id:`4:${mr}`};return Promise.resolve().then((()=>Promise.all(this.signalingSession.addParticipantsAsync([s],r,i)))).then((e=>(e.length>0&&this.signalingNotifications.onParticipantJoined(e[0],i),Promise.resolve({code:0,subCode:0,phrase:"TransactionComplete"})))).catch((e=>{n.logFailure(`Participant was not added to call, error=${je(e)}`);const t=this._handleParticipantOperationFailure("MergeWithPickupCode",e,i,null,!0).reason;return Promise.reject(e?e.endCode:t||0)}))}async setMaxVideoChannels(e){return Promise.reject(60)}async setMaxVbssChannels(e){return Promise.reject(60)}async stop(e=!1,t=be(),i,n){const r=this.logger.createFnLogger("StopAudio",t);if(6===this.state)return r.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 r.logFailure("Trying to stop a call which is already Disconnected"),Promise.reject(new Error("cannot stop call in Disconnected state"));if(this.disposedPromise)return r.logFailure("Call already ended"),Promise.reject("Call already ended");let s=0;1===this.state&&(s=10);const a=n?{clientReasonSubCode:n.clientSubCode,clientReasonPhrase:n.clientPhrase}:{};n?.clientSubCode===Dr&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.enabled&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.clientPhrases.includes(n?.clientPhrase)&&(a.code=Pr,a.subCode=Dr,a.phrase="CallEndReasonVDIdisconnect",a.resultCategories=["UnexpectedClientError"],s=4);const o={terminatedReason:s,forEveryone:e,causeId:t,...i,rejectReason:a};return this.stopInternal(o)}publishState(e,t){const i=ho(e.type),n=this.getPluginlessPublishLevel(e.level),r=e.participantIds&&e.participantIds.length>0?"specified":void 0;return this.callTelemetry.setOperationVariant("PublishState","specified"===r?`${i}Specified`:`${i}None`,t),this.signalingSession.publishStateAsync(i,n,t,e.content,r,e.participantIds)}publishStatesForEveryone(e,t){const i=ho(e.type),n=this.getPluginlessPublishLevel(e.level);return this.callTelemetry.setOperationVariant("PublishState",`${i}All`),this.signalingSession.publishStateAsync(i,n,t,e.content,"all")}removeState(e,t){return this.signalingSession.removeStateAsync(t,"specified",void 0,e.stateIds).then((e=>Promise.resolve()))}removeStatesForEveryone(e,t){const i=ho(e.type);return this.signalingSession.removeStateAsync(t,"all",i,void 0).then((e=>Promise.resolve()))}updateMeetingSettings(e,t){return this.signalingSession.updateMeetingSettingsAsync({allowRaiseHands:e.allowRaiseHands,attendeeRestrictions:e.attendeeRestrictions,lockMeeting:e.lockMeeting,breakoutRoomsEnabled:e.breakoutRoomsEnabled,allowPresentersToManageBreakoutRooms:e.allowPresentersToManageBreakoutRooms,disableMdpClientAudioRecording:e.disableMdpClientAudioRecording,refreshSettings:e.refreshSettings,aiInterpretationEnabled:e.aiInterpretationEnabled,groupCopilotDetails:e.groupCopilotDetails},t)}updateMeetingGroups(e,t){this.logger.info(`[UpdateMeetingGroups][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("UpdateMeetingGroups",e),n={fromGroup:t.fromGroup,toGroup:t.toGroup,scope:Up(t.scope)};return t.participants&&(n.participants=function(e){const t=[];for(const i in e)if(e[i].participantLegIdMap)for(const n in e[i].participantLegIdMap){const r=e[i].participantLegIdMap[n].endpointId;t.push({id:i,mri:i,participantId:n,...r&&{endpointId:r}})}else t.push({id:i,mri:i});return t}(t.participants)),this.signalingSession.updateMeetingsGroupsAsync(e,n).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingGroups] error in updateMeetingGroups (synchronous error) : ${$e(t)}. updateMeetingGroupsPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingGroups",{error:$e(t)},e)})),i}updateMeetingLiveState(e,t){return this.logger.info(`[UpdateMeetingLiveState][${e}] options ${Ge(t)}`),this.signalingSession.updateMeetingLiveStateAsync(e,t).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingLiveState] error in updateMeetingLiveState (synchronous error) : ${$e(t)}. promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingLiveState",{error:$e(t)},e)})),this._callOperationHandler.waitForOperation("UpdateMeetingLiveState",e)}updateMeetingStates(e,t=be()){var i;this.logger.info(`[UpdateMeetingStates][${t}]`);const n={},r=[];e.operationId=e.operationId||t;for(const s of Object.keys(e.meetingStates)){const a=e.operationId+"_"+s;r.push(a);const o=this._callOperationHandler.createPendingOperation("UpdateMeetingStates",a,t);n[i=e.operationId]??(n[i]={}),n[e.operationId][s]=o,this.callTelemetry.recordOperation("UpdateMeetingStates",t,a)}return Promise.resolve().then((()=>this.signalingSession.updateMeetingStatesAsync(t,e))).then((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{data:$e(e)},t,i)})).catch((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{error:$e(e)},t,i);this.logger.logFailure(e)})).then((()=>n))}async updateParticipantInterpretationState(e,t){if(this.logger.info(`[UpdateParticipantInterpretationState][${e}] options ${Ge(t)}`),0===t.length)return Promise.reject(ns("Invalid UpdateParticipantInterpretationState options"));const i=this.signalingSession.updateParticipantInterpretationStateAsync(e,t),n=[];t.forEach((t=>{n.push(this._callOperationHandler.createPendingOperation("UpdateParticipantInterpretationState",t.id,e))}));for(let n=0;n<i.length;n++){const r=i[n],s=t[n];r.then((()=>{this.logger.logSuccess(`updateParticipantInterpretationState succeeded for [id=${De(s.id)}]`);const t={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("UpdateParticipantInterpretationState",t,s.id,e),this._callOperationHandler.maybeResolveOperation("UpdateParticipantInterpretationState",t,s.id,e)})).catch((t=>{this.logger.error(`[${e}] [UpdateParticipantInterpretationState] error in updateParticipantInterpretationState (synchronous error) : ${$e(t)}. updateParticipantInterpretationStatePromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateParticipantInterpretationState",{error:$e(t)},e);const i=this._handleParticipantOperationFailure("UpdateParticipantInterpretationState",t,e,s.id).reason,n=t?.endCode||i||0;this._callOperationHandler.maybeRejectOperation("UpdateParticipantInterpretationState",n,s.id,e)}))}return Promise.resolve(n)}async updateParticipantsProperties(e,t){const i=this.logger.createFnLogger("UpdateParticipantsProperties",t);if(i.info(`options ${De(Ge(e))}`),!e)return Promise.reject(ns("Invalid input: UpdateParticipantsPropertiesContext"));const n={},r=e.scope,s=e.operationId,a=new Set;if("self"===r){const i=this.signalingSession.participantManager.localParticipant.id;for(const r in e.propertyBag){const e=Pu(i,s,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},a.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,De(e))}}else{if("specified"!==r||!this._isUpdatePropertiesSpecifiedAllowedByEcs)return Promise.reject("This scope is not supported.");{const i=e.participants;for(const e of i){const i=e.id;for(const r in e.propertyBag){const e=Pu(i,s,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},a.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,De(e))}}}}return i.info(`promises created: ${De(Ge(n))}`),this.signalingSession.updateParticipantsPropertiesAsync(e,a,s,t).catch((e=>{const r=je(e);i.info(`[failed][reason=${r}]`);const s={...e};this.callTelemetry.updateOperationData("UpdateParticipantsProperties",{error:$e(r)},t);for(const e of Object.keys(n))this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",s,e,t)})),Promise.resolve().then((()=>n))}joinMeetingGroup(e,t){this.logger.info(`[JoinMeetingGroup][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("JoinMeetingGroup",e),n={..."meetingGroupId"in t&&{meetingGroupId:t.meetingGroupId},..."meetingGroupLabel"in t&&{meetingGroupLabel:t.meetingGroupLabel},...t.groupPreferences&&{groupPreferences:t.groupPreferences}};return this.signalingSession.joinMeetingGroupAsync(e,n).catch((t=>{const i=$e(t);this.logger.info(`[${e}] [JoinMeetingGroup] error in joinMeetingGroup (synchronous error) : ${i}. joinMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("JoinMeetingGroup",{error:i},e)})),i}leaveMeetingGroup(e,t){this.logger.info(`[LeaveMeetingGroup][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("LeaveMeetingGroup",e),n={meetingGroupId:t.meetingGroupId};return this.signalingSession.leaveMeetingGroupAsync(e,n).catch((t=>{const i=$e(t);this.logger.info(`[${e}] [LeaveMeetingGroup] error in leaveMeetingGroup (synchronous error) : ${i}. leaveMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("LeaveMeetingGroup",{error:i},e)})),i}sendMessages(e,t){var i,n;this.logger.info(`[SendMessages][${e}]`);const r={};for(const s of t)if(0===s.scope){const t=this._callOperationHandler.createPendingOperation("SendMessages",s.operationId,e);r[s.operationId]={all:t},this.callTelemetry.recordOperation("SendMessages",e,s.operationId)}else if(1===s.scope)for(const t in s.to)if("participant"===s.to[t].level){const n=wu(t,s.operationId),a=this._callOperationHandler.createPendingOperation("SendMessages",n,e);r[i=s.operationId]??(r[i]={}),r[s.operationId][t]=a,this.callTelemetry.recordOperation("SendMessages",e,n)}else if("endpoint"===s.to[t].level)for(const i in s.to[t].participantLegIdMap){const t=Au(i,s.operationId),a=this._callOperationHandler.createPendingOperation("SendMessages",t,e);r[n=s.operationId]??(r[n]={}),r[s.operationId][i]=a,this.callTelemetry.recordOperation("SendMessages",e,t)}return this.signalingSession.sendProxiedMessageAsync(e,t).then((e=>{for(const t of e)t.then((e=>{this._callOperationHandler.maybeResolveOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)})).catch((e=>{this._callOperationHandler.maybeRejectOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)}));return r}))}async updateMonitorSession(e,t=be()){this.logger.info(`updateMonitorSession: monitorActionType: ${e.monitorActionType}, monitorData: ${e.monitorData}`);const i=function(e){switch(e){case 0:return"Monitor";case 1:return"Whisper";case 2:return"Barge";case 3:return"Takeover";default:return}}(e.monitorActionType);if(void 0===i){const t={code:Rr,subCode:Or,phrase:`Invalid monitor action type ${e.monitorActionType}`};return Promise.reject(t)}const n={monitorActionType:i,monitorData:e.monitorData},r=this._callOperationHandler.waitForOperation("UpdateMonitorSession","",t);return this.signalingSession.updateMonitorSessionAsync(n,t).catch((e=>{const i=$e(e);this.logger.info(`[${t}] [UpdateMonitorSession] error in updateMonitorSession (synchronous error): ${JSON.stringify(i)}. updateMonitorSessionPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMonitorSession",{error:i},t)})),r}switchInterpreterGroup(e){return Promise.reject(new Error("Not implemented"))}setLiveInterpretationAttributes(e,t){return Promise.reject(new Error("Not implemented"))}async updateMeetingRoles(e,t,i=be()){return 3===this.state&&this.signalingSession.hasOwnProperty("updateMeetingRolesAsync")?this.signalingSession.updateMeetingRolesAsync(e,t,i):Promise.reject({code:Rr,subCode:kr,phrase:"ActionNotAllowed"})}stopInternal(e){const t=this.logger.createFnLogger("stopInternal",e.causeId),i=e.terminatedReason||0;let n=e.rejectReason&&(e.rejectReason.code||e.rejectReason.subCode)?e.rejectReason:this.getRejectionInfoFromTerminatedReason(i);if(e.rejectReason&&(n||(n={}),n.clientReasonSubCode=e.rejectReason.clientReasonSubCode,n.clientReasonPhrase=e.rejectReason.clientReasonPhrase),t.info(`started, terminatedReason=${i}, rejectReason=${Ge(n)}`),6===this.state)return t.logFailure("Trying to stop a call which is already Disconnecting"),this.disconnectingPromise;if(7===this.state)return t.logFailure("Trying to stop a call which is already Disconnected"),this.disconnectingPromise;this.setCallState(6,e.causeId,i);const r={causeId:e.causeId,forEveryone:e.forEveryone,scope:this.mapEndpointScope(e.scope),redirectOptions:e.redirectOptions&&zh(e.redirectOptions)};return 1===e.scope&&(n.code=Ar,n.subCode=Lr,n.phrase="EndedByRemoteEndpoint"),this.disconnectingPromise=Promise.all([this.cleanUpMedia(e.causeId,n).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((i=>{throw t.logFailure(`cleanUpMedia failed with reason=${je(i)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(i)},e.causeId),i})),this.signalingSession.endAsync(n,r).catch((e=>{throw t.logFailure(`endAsync failed with reason=${je(e)}`),e}))]).catch((i=>{throw t.logFailure(i),this.cleanUp(e.causeId,n),i})).then((()=>this.cleanUp(e.causeId,n))).catch((t=>{throw this.callTelemetry.updateOperationData("StopCall",{error:$e(t)},e.causeId),this.setCallState(7,e.causeId,i),t})),this.disconnectingPromise}async cleanUp(e,t){return this.logger.info(`[${e}][cleanup]start`),this.disposedPromise||(this.disposedPromise=this.cleanUpFinalize(e,t),this._getCallEndOperation().catch(wr).then((()=>{const t={code:Rr,subCode:Nr};this._callOperationHandler.rejectPendingOperations(61,e,t),this._participantOperationHandler.rejectPendingOperations(47,e,t)}))),this.disposedPromise}async cleanUpMedia(e,t){return this.mediaDisposedPromise||(this.callTelemetry.recordOperation("_MediaCleanUp",e),this.mediaDisposedPromise=(async()=>{this.callDeviceManager?.dispose(),this.callDeviceManager=null,this.turnOffLocalVideoPreview(e),this.localVideoContainer=null,this.disposeContentSharingSessions(),this.disposeSharingScreenHandle();const i=this.mediaSession;if(this.reportMediaStats=!!i,!i)return;this.unmixedAudioProvider.dispose(),this.dataChannel.dispose(),this.screenSharingControl.dispose(e),this.remoteUFDHandler.dispose(),this.mediaSession=null,this.streamManager.setMediaSession(null,e),this.participants?.forEach((t=>{t.setMediaSession(null,e)}));const n=i.terminate(e,t);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(t),this.screenSharingRenegotiationDeferred=null,this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.removeModality(0),this.mediaStateConfigurationHelper.removeModality(3),this.mediaStateConfigurationHelper.removeModality(2),this.batteryStatus?.dispose(),i?.getSessionConfig()?.config?.useOneDsLogger&&i.getSessionConfig().config.addTelemetryReportingCallback&&window.removeEventListener("beforeunload",this.beforeUnloadTelemetrySender);try{await n}finally{await this.collectCallStats(i),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(i.getMediaControlPlaneInstance()?.getTelemetryReport()))}})()),this.mediaDisposedPromise}async cleanUpFinalize(e,t){try{await this.cleanUpMedia(e,t)}catch(t){this.logger.info(`[${e}][cleanUpMedia] failure: ${je(t)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(t)},e)}this.callTelemetry.recordOperationSuccess("_MediaCleanUp");const i=this.reportCallEndStats(this.reportMediaStats);this.mediaSession?.getSessionConfig().config.waitReportStatsAtCallStop&&await i}async createContentSharingSession(e,t,i,n,r=be()){if(this.signalingSession.signalingAgentConfig.checkAttendeeRoleInCreateContentSharing&&"attendee"===(this.advancedMeetingRole||this.meetingRole)){const e={terminatedReason:8,terminatedReasonCode:403,terminatedReasonSubCode:0,errorMessage:"Failed due to insufficient permissions"};return Promise.reject(e)}const s=new Bg(this.callTelemetry,this.logger,this.signalingSession,e,t,n,i);return this.contentSharingSessions.push(s),s.changed((()=>this.removeContentSessionIfEnded(s))),this.event("contentSharingChanged").raise(),Promise.resolve(s)}stopWithBeacon(e=be()){if(6===this.state||7===this.state)return!0;this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&(this.callEndDiagnosticsInfo={callControllerCode:Ar,callControllerSubCode:xr},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.setCallState(6,e,1));const t=this.signalingSession.endWithBeacon(e);return this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&this.setCallState(7,e,1),t}disposeContentSharingSessions(){this.contentSharingSessions.forEach((e=>{e.dispose(),this.removeContentSessionIfEnded(e)})),this.event("contentSharingChanged").raise()}isPreheatedOnly(){return!!(12===this.state||2===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall")||9===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))}removeContentSessionIfEnded(e){7!==e.contentSharingStatus&&8!==e.contentSharingStatus||(this.logger.info("stopping the content sharing session."),(0,Ws.remove)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.contentSharingGuid)).length&&this.event("contentSharingChanged").raise())}getRejectionInfoFromTerminatedReason(e){switch(e){case 53:return{code:ys,subCode:3112,phrase:"MediaWhitelistingIssue"};case 4:return{code:ys,subCode:this._wasAudioStreamConnected?3101:3100,phrase:this._wasAudioStreamConnected?"CallEndReasonMediaDropAfterConnectError":"CallEndReasonMediaDropDuringConnectError"};case 47:return{code:ys,subCode:3111,phrase:"CallEndReasonMediaOfferProcessingError"};case 38:return{code:ys,subCode:3108,phrase:"RetargetNotSupported"};case 10:return{code:603,subCode:0,phrase:$s};case 25:return{code:Ds,subCode:3110,phrase:"CallEndReasonMediaError"};case 58:return{code:ys,subCode:Ls,phrase:"CallEndReasonMediaPermissionError"};case 7:return{code:Ds,subCode:0,phrase:"CallEndReasonUnknown"};case 0:case 1:return{code:0,subCode:0,phrase:$s};case 75:return{code:302,subCode:3020,phrase:js,resultCategories:["Success"]};case 77:return{code:0,subCode:58e4,phrase:"CallEndReasonSuspended"}}return null}async acknowledge(e,t,i=be()){const n=this.logger.createFnLogger("Acknowledge",i),r=Date.now();if(this.setInitialTelemetry("Acknowledge",{callStartTime:r},"",i),0!==this.state&&8!==this.state)throw new Error(`Trying to acknowledge a call that has already been acted on ${this.state}`);n.info(`isMultiParty=${e.isMultiParty}`),n.info(`fromMixer=${e.fromMixer}`),n.info(`participantId=${e.participantId}`),n.info(`callType=${e.callType}`),this.attachToCallAndGetOffer=new Kt,this.setCallType(e.isMultiParty?2:1,i),this.setCallUsesMixer(!!e.fromMixer,i),this.setCallerMri(uh(e.callerId)),this.setDisplayNameSource(e.displayNameSource),this.setTransferorMri(e.transferorId),this.transferorType=e.transferorType,this.transferorDisplayName=e.transferorDisplayName,this.incomingCallType=e.callType,this.consultativeCallId=e.consultativeCallId,this.callQueueInfo=e.callQueueInfo,this.setFromApplicationType(e.fromApplicationType,i),this.setCalleeAlternateId(e.calleeAlternateId,i),this.setRoutingTimeout(e.routingTimeout),this.callStats.localStats.startCall();const s=mh(n);try{if(s.executeSync("ProcessIncomingCallRequest",(()=>this.signalingSession.processIncomingCallRequest(e,t,i))),this.setParticipantId(this.participantId),s.executeSync("ResolvePotentialConflict",(()=>this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)))===this.signalingSession)return Promise.reject({code:7,success:!1});const r=async()=>{s.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(i))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled());const e=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 t=await s.execute("WaitForMediaOffer",(()=>e?Promise.resolve(e):this.attachToCallAndGetOffer.promise));let r;try{r=await s.execute("ProcessOffer",(()=>this.mediaSession.processOfferAsync(t,i)))}catch(e){r=await this._handleOfferProcessingError(e,i,n)}await s.execute("ProcessOfferedModalities",(()=>this._processOfferedModalities(r,i)))},a=(()=>s.execute("SendAttach",(()=>this.signalingSession.sendAttachToCall(i))).then((()=>this.setCallState(1,i))))();return await Promise.all([a,r()]).catch((async e=>{throw await a,e})),await s.execute("TrySendingProvisionalAnswer",(()=>this._trySendProvisionalMediaAnswer(i))),s.executeSync("OnAcknowledgeSuccess",(()=>this._onAcknowledgeSuccess(n,s.getTelemetryData(),i)))}catch(e){return this._onAcknowledgeError(e,i,n,s.getTelemetryData())}}_onMessageIdChanged(e,t){e&&this.messageId!==e&&this.setMessageId(e,t)}async accept(e,t=be()){const i=this.logger.createFnLogger("Accept",t);if(i.info(`accept, answerMediaType: ${e.answerMediaType},\n withVideo: ${e.withVideo},\n muted: ${e.muted},\n getSendMediaModalities: ${JSON.stringify(e.sendMediaModalities)},\n clientEndpointCapabilities: ${e.clientEndpointCapabilities},\n muteFlags: ${e.muteFlags}`),1!==this.state)throw new Error("Only calls in Notified state can be accepted");this.setCallOptions({callStartOptions:e,callStartTime:Date.now()}),this.setSessionIceTransportPolicy(e?.mediaConfiguration);const n=this._callOperationHandler.createPendingOperation("_ConnectCall",void 0,t);this.callStats.localStats.audio.start();const r=mh(i);this.mediaSession.createAudioElement(t);const s=e.muted||!(1&~e.muteFlags),a=!(2&~e.muteFlags);this.setMuted(s?2:this.isServerMuted?1:0,t),this.setSpeakerMuted(a,t),this.setCallState(2,t),this.connectCallPromise=this._callOperationHandler.waitForOperation("Accept");try{e.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient(),this.mediaStateConfigurationHelper.setCallAcceptOptions(e),this.mediaStateConfigurationHelper.isSending(1)&&await r.execute("StartVideoSafe",(()=>this.startVideoSafe(t))),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,t);const s=await r.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,t))),a=r.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(s))),o=await r.execute("evaluateEndpointStatesForAccept",(()=>this.evaluateEndpointStatesForAccept(2===this._muteState,e?.additionalEndpointProperties,t)));await r.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,t)));const l=r.execute("handleEndpointStatesForAccept",(()=>this.handleEndpointStatesForAccept(o,t)));i.info("Queued the handleEndpointStatesForAccept");const c=await r.execute("CreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t)));await r.execute("Accept",(()=>this.signalingSession.acceptAsync(c,a,e.clientEndpointCapabilities,t))),await r.execute("WaitForConnect",(()=>n)),this.handleRemoteParticipantStateInOneToOneCall(t),await r.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t))),await l,this.callTelemetry.updateOperationData("Accept",{phases:r.getTelemetryData()},t)}catch(e){let n=7,r={};throw this.callTelemetry.updateOperationData("Accept",this.getTelemetryFromPhaseExecution(e),t),e?.error&&(r={...e.error}),gh(qs,e)&&(n=47),this.mediaSession?.getSessionConfig().config.stopCallOnAcceptFailure&&this.stopInternal({terminatedReason:n,causeId:t,rejectReason:r}),e.terminatedReason=n,i.logFailure(e),e}}async reject(e=be(),t){const i=t?{clientReasonSubCode:t.clientSubCode,clientReasonPhrase:t.clientPhrase}:{};return 1!==this.state?Promise.reject(60):this.stopInternal({terminatedReason:10,causeId:e,rejectReason:i})}async join(e,t={},i=be()){const n=Date.now();return this.setInitialTelemetry("JoinCall",{callStartOptions:t,callStartTime:n},e.conversationUrl,i),this.setCallerMri(uh(e.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinCall"),this.signalingSession.signalingAgentConfig.enableSplitConversationEndUrl&&this.signalingSession.setFsmState(wa.SIGNALING_FSM_STATE.OUTGOING),this.joinOrStartCall({callStartOptions:qh(t),callStartTime:n},this.joinGivenConversation,i,e.conversationUrl)}async joinPreheatedCall(e,t){const i=this.logger.createFnLogger("JoinPreheatedCall",t),n=this.isServerMuted||!(1&~e.muteFlags),r=!(2&~e.muteFlags),s=mh(i);this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinPreheatedCall");try{const a={endpointProperties:{preheatProperties:0}};this.setCallState(2,t),!this.isCallModeStreaming()&&n&&(a.state={isMuted:!0}),i.info(`captchaContentJson=${!!e.captchaContentJson} publishedStates=${!!e.publishedStates} muteFlags=${e.muteFlags}}`),await this.signalingSession.updateEndpointState(a,t,e.publishedStates,e.captchaContentJson),this.computeCallState(t),this.isCallModeStreaming()||(n||(await s.execute("UnmuteInput",(()=>this.mediaSession.unmuteInputAsync(t))),this.setMuted(0,t)),r||(await s.execute("UnmuteOutput",(()=>this.mediaSession.unmuteOutputAsync(t))),this.setSpeakerMuted(!1,t)))}catch(e){const n=7;let r;return i.logFailure(`error: ${n} ${je(e)}`),is(e)?r=e:(ph("UnmuteInput",e)||ph("UnmuteOutput",e))&&(r={code:ks,subCode:3115,phrase:je(e),causeId:t}),this.callTelemetry.updateOperationData("JoinPreheatedCall",{phases:s.getTelemetryData(),error:$e(e)},t),this.stopInternal({causeId:t,terminatedReason:n,rejectReason:r}),Promise.reject(r)}}async start(e={},t=be()){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCall",{callStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCall"),this.signalingSession.signalingAgentConfig.enableSplitConversationEndUrl&&this.signalingSession.setFsmState(wa.SIGNALING_FSM_STATE.OUTGOING),this.joinOrStartCall({callStartOptions:qh(e),callStartTime:i},this.startOutgoingCall,t)}async startCallToVoicemail(e,t=be()){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCallToVoiceMail",{callVoicemailStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallToVoiceMail"),this.joinOrStartCall({callVoicemailStartOptions:e,callStartTime:i},this.startVM,t)}async joinCallWithoutCallModality(e,t={},i=be()){const n=Date.now();this.setCallerMri(e.groupCallInitiator),this.setCallType(2,i);const r={callStartOptions:qh(t),callStartTime:n};return this.setInitialTelemetry("Subscribe",r,e.conversationUrl,i),0!==this.state?(this.logger.info(`[${i}][joinCallWithoutCallModality]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,i),this.signalingSession.subscribeToCall(e.conversationUrl,this.callId,t.clientEndpointCapabilities,{meetingRegistrationId:t.meetingRegistrationId,participantPin:t.participantPin,clientEndpointDebugContent:t.clientEndpointDebugContent,additionalEndpointProperties:t.additionalEndpointProperties},i).catch((e=>is(e)?(this.logger.info(`[${i}][joinCallWithoutCallModality] ${je(e)}`),Promise.reject(e)):Promise.reject(Vh(e)))),this._callOperationHandler.waitForOperation("Subscribe",void 0,i))}startWithMeetingData(e,t){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartWithMeetingData",{callStartOptions:t,callStartTime:i},"",e),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartWithMeetingData"),this.joinOrStartCall({callStartOptions:qh(t),callStartTime:i,meetingPreferences:{shouldResurrect:t.shouldResurrect}},this.startOutgoingCall,e)}joinWithMeetingData(e,t,i){const n=Date.now();return this.setInitialTelemetry("JoinWithMeetingData",{callStartOptions:i,callStartTime:n},t.conversationUrl,e),this.setCallerMri(uh(t.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinWithMeetingData"),this.joinOrStartCall({callStartOptions:qh(i),callStartTime:n,meetingPreferences:{shouldResurrect:i.shouldResurrect}},this.joinGivenConversation,e,t.conversationUrl)}subscribeWithMeetingData(e,t,i){const n=Date.now();this.setCallerMri(t.groupCallInitiator),this.setCallType(2,e);const r={callStartOptions:qh(i),callStartTime:n};return this.setInitialTelemetry("SubscribeWithMeetingData",r,t.conversationUrl,e),0!==this.state?(this.logger.info(`[${e}][subscribeWithMeetingData]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,e),this.signalingSession.subscribeToCall(t.conversationUrl,this.callId,i.clientEndpointCapabilities,{meetingPreferences:{shouldResurrect:i.shouldResurrect},meetingData:this.meetingData,meetingRegistrationId:i.meetingRegistrationId,participantPin:i.participantPin,additionalEndpointProperties:i.additionalEndpointProperties},e).catch((t=>is(t)?(this.logger.info(`[${e}][subscribeWithMeetingData] ${je(t)}`),Promise.reject(t)):Promise.reject(Vh(t)))),this._callOperationHandler.waitForOperation("SubscribeWithMeetingData",void 0,e))}async startCallWithNudge(e,t={},i=be()){this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallWithNudge");const n=Date.now();if(this.logger.info(`[${i}][startCallWithNudge]startCallWithNudge for participants: ${function(e){try{return e.map(De)}catch(e){return[]}}(e)}`),this.participants.length)return Promise.reject(48);if(t.isCast&&t.isHuddleGroupCall)return this.logger.logFailure(`isCast: ${t.isCast} isHuddleGroupCall: ${t.isHuddleGroupCall}`),Promise.reject(new Error("isCast or isHuddleGroupCall can only be set exclusively."));const r={};return r.callStartOptions=qh(t),r.invitationType=wa.INVITATION_TYPE.NUDGE,r.participantsToNudge=e,r.callStartTime=n,this.setInitialTelemetry("StartCallWithNudge",r,"",i),this.joinOrStartCall(r,this.startOutgoingCall,i)}async startAndUnpark(e,t,i={},n=be()){this.setCallerMri(dh+this.currentUserSkypeIdentity.id);const r=this.logger.createFnLogger("StartCallAndUnpark",n),s=Date.now();this.setInitialTelemetry("StartCallAndUnpark",{callStartTime:s},"",n),r.info(`startAndUnpark for context: ${e}, pickupCode :${t}`),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallAndUnpark");const a={};switch(a.callStartOptions=qh(i),a.pickupCode=t,a.parkContext=mr,e){case 0:a.parkContext="*11";break;case 1:a.parkContext="*12";break;case 5:a.parkContext="*14";break;case 2:a.parkContext=mr;break;default:throw new Error(`[startAndUnpark] unsupported ParkContext name: ${e}`)}return this.addParticipant(`4:${a.parkContext}`).catch((e=>r.logFailure("Failed to add participant to unparked call"))),this.joinOrStartCall(a,this.startOutgoingCall,n)}async admitParticipant(e,t=be()){const i=hh(e),n=this.getParticipant(i),r=this._getParticipantLegId(n),s=r?{participantLegId:r}:{};if(n&&7!==n.state){const i={code:0,subCode:3552,phrase:"Participant is not in lobby state"};return this.callTelemetry.maybeRecordOperationSuccess("AdmitParticipant",i,e,t,s),Promise.reject(i)}return this.admitParticipantToCall(i,t,r)}admit(e,t){return this.signalingSession.admitAsync(t)}async callMeBack(e,t,i=be()){const n=hh(`${dh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri);return this.addCallMeBackParticipant(e,t||n,i)}async addParticipant(e,t={},i=be()){return(await this.addParticipantsImpl([e],t,i,"addParticipant"))[0]}async addParticipants(e,t={},i=be()){return this.addParticipantsImpl(e,t,i,"addParticipants")}async addParticipantsImpl(e,t={},i=be(),n){if(this.logger.info(`[${i}][${n}] start`),this.isEmergency&&0===this.state&&(0!==this.participants.length||1!==e.length))return Promise.reject(new Error("Only 1 participant (the emergency operator) may be added to unstarted emergency calls"));if(t.participantInvitationData)try{JSON.stringify(t.participantInvitationData)}catch(e){throw this.logger.info(`[${i}][${n}] ${e}`),e}const r=[],s=[];if(e.forEach((e=>{const t=this.getOrCreateParticipant(e,i,!0);0===t.state||4===t.state?(s.push(t),r.push(this._participantOperationHandler.createPendingOperation("AddParticipant",t.id,i))):3===t.state?r.push(Promise.resolve(t)):this._participantOperationHandler.hasPendingOperationWithOperationId("AddParticipant",t.id)&&r.push(this._participantOperationHandler.waitForOperation("AddParticipant",t.id))})),0===s.length)return Promise.resolve(r);const a=!!t.disableUnmute,o=this.addParticipantsToCall(s,i,t.participantInvitationData,t.groupId,t.threadId,t.messageId,a,t.alternateId,t.customHeaderContext,t.callingLineIdentity);return(0,Ws.zip)(o,s).forEach((async([e,t])=>{try{await e;const n=this._getParticipantLegId(this.getParticipant(t.id)),r=n?{participantLegId:n}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},t.id,i,r),this._participantOperationHandler.maybeResolveOperation("AddParticipant",t,t.id,i)}catch(e){this._participantOperationHandler.maybeRejectOperation("AddParticipant",e,t.id,i)}})),this.raiseChanged(this._participantChangedEventSkipConfig),Promise.resolve(r)}async nudgeParticipants(e,t,i={},n=be()){return 2!==this.state&&3!==this.state?Promise.reject(48):this.signalingSession.nudgeParticipantsAsync({participantsIds:t,causeId:n,invitationData:i.participantInvitationData,newGroupId:i.groupId,newThreadId:i.threadId,newMessageId:i.messageId})}mapRemoveEndpointScope(e){switch(e){case 0:return"specified";case 1:return"all";default:return"none"}}mapEndpointScope(e){return 1===e?"all":"none"}async removeParticipant(e,t=be(),i,n){const r=this.logger.createFnLogger("removeParticipant",t);r.info("start");const s=this.mapRemoveEndpointScope(n);return this.signalingSession.removeParticipantAsync({id:e,endpointId:i},t,s).catch((i=>{r.logFailure(`Participant was not removed from call, error=${i}`);const n=this._handleParticipantOperationFailure("RemoveParticipant",i,t,e).reason;return Promise.reject(n||38)}))}async cancelNudge(e,t){throw new Error("Method not implemented.")}async searchParticipants(e,t){return this.signalingSession.searchParticipantsAsync(e.searchQueryOptions,t)}async getAllParticipants(e,t){return this.signalingSession.getAllParticipantsAsync(e.scope,t)}set dominantSpeakerInfo(e){this.internalDominantSpeakerInfo=e}get dominantSpeakerInfo(){return this.internalDominantSpeakerInfo?this.internalDominantSpeakerInfo:this.mediaSession?.getSessionConfig().config.emptyInitialDSH?{speakerList:[],timestamp:null,noCurrentDominantSpeaker:!1}:{speakerList:this.participants.filter((e=>3===e.state)).map((e=>e.id)),timestamp:null,noCurrentDominantSpeaker:!1}}set slowedDownActiveTalkerInfo(e){(0,Ws.isEqual)(this.internalSlowedDownActiveTalkerInfo?.speakerList,e.speakerList)||(this.internalSlowedDownActiveTalkerInfo=e,this.raiseChanged())}get slowedDownActiveTalkerInfo(){return this.internalSlowedDownActiveTalkerInfo}startVideoSafe(e){return this.startVideo(e).catch((t=>{this.logger.info(JSON.stringify(t),"startVideoSafe",e)}))}async joinOrStartCall(e,t,i,n){const r=this.logger.createFnLogger("joinOrStartCall",i);if(0!==this.state&&8!==this.state&&!e.isPromotingToRealtime){const e="Trying to start a call that has already been acted on";return r.logFailure(e),Promise.reject(60)}if(this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)===this.signalingSession)return Promise.reject(57);this.callStats.localStats.startCall();const s=8===this.state||1!==this.participants.length;r.info(`isMultiparty=${s}, reason: participants.length=${this.participants.length}`),this.setCallType(s?2:1,i),this.setCallUsesMixer(s,i),this._setMaxVbssChannels(e?.callStartOptions?.maxVbssChannels,i),this.setCallOptions(e);const a=e.callStartOptions||{};if(1&~a.preheatFlags){const e=!!a&&(a.muted||!(1&~a.muteFlags)),t=a?.muteFlags?!(2&~a.muteFlags):this.isSpeakerMuted;this.setMuted(e?2:this.isServerMuted?1:0,i),this.setSpeakerMuted(t,i),this.setCallState(2,i)}else this.setMuted(2,i),this.setSpeakerMuted(!0,i),this.setCallState(11,i);const o=((e,t,i,n,r)=>{if(e){if(e.meetingUrl)return"MeetingUrl";if(e.meetingCode)return"MeetingCode"}return t||i?"ThreadContext":n?"GroupId":r?"Awareness":""})(this.meetingData,this.threadId,this.messageId,this.groupId,!!n);this.callTelemetry.setJoinedFrom(o),this.signalingSession.setJoinedFrom(o),this.setHuddleGroupCall(!!e.callStartOptions?.isHuddleGroupCall);const l=this._callOperationHandler.createPendingOperation("_ConnectCall","",i);return l.catch(wr),await this.joinOrStartWithMedia(e,t,e.callStartTime,l,i,n),e.callStartOptions?.meetingRegistrationId&&this.callTelemetry.setHasMeetingRegistrationId(!0),e.callStartOptions?.participantPin&&this.callTelemetry.setHasParticipantPin(!0),l}setSessionIceTransportPolicy(e){const t=e?.connectionType;let i=Gi.ICE_TRANSPORT_POLICY.all;switch(t){case"AllSupported":i=Gi.ICE_TRANSPORT_POLICY.all;break;case"NoDirectConnection":i=Gi.ICE_TRANSPORT_POLICY.relay}this.mediaSession?.getSessionConfig().setIceTransportPolicy?.(i)}async joinOrStartWithMedia(e,t,i,n,r,s){const a=this.logger.createFnLogger("joinOrStartWithMedia",r);this.callStats.localStats.audio.start();const o=e.callStartOptions,l=o&&1&o.preheatFlags;if(this._startCallPhase=mh(a),e.callStartOptions?.sendMediaModalities&&(this.mediaStateConfigurationHelper=new Wh(e.callStartOptions.sendMediaModalities)),this._preferredMpLocation){e.callStartOptions=e.callStartOptions||{};const t=e.callStartOptions.clientEndpointDebugContent?JSON.parse(e.callStartOptions.clientEndpointDebugContent):{};e.callStartOptions.clientEndpointDebugContent=JSON.stringify({preferredMpLocation:this._preferredMpLocation,...t})}try{o&&!l&&this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)&&this.mediaStateConfigurationHelper.isSending(2)&&(this.setCallUsesMixer(!0,r),await this.getScreenHandle().acquire()),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,r),this.callUsesMixer||this.mediaStateConfigurationHelper.disableModality(2),a.info(`skipSharingModality=${!this.callUsesMixer}`),this._startCallPhase.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(r,o?.mediaConfiguration))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.getSessionConfig().config.alwaysNegotiateDataChannel&&this.mediaStateConfigurationHelper.enableModality(3),this.setSessionIceTransportPolicy(e?.callStartOptions?.mediaConfiguration),this.mediaSession.createAudioElement(r),this.callUsesMixer||s||this.isOneToOnePSTNCall()||e.callVoicemailStartOptions||this.setIsSomeoneStreamingVideo(!0);const c=this._callOperationHandler.createPendingOperation("_WaitForAnswer","",r,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});c.catch(wr);let d=!1;e.isPromotingToRealtime?(this.isSpeakerMuted=!0,d=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r)))):o&&(l?(d=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r))),this.setMuted(2,r),this.setCallUsesMixer(!0,r)):this.mediaStateConfigurationHelper.isSending(1)&&await this._startCallPhase.execute("StartVideoSafe",(()=>this.startVideoSafe(r)))),o?.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient();const u=await this._startCallPhase.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,r)));if(!this.mediaSession?.createOfferAsync)throw{error:"NoMediaSession",phase:"CreateOffer"};const h=await this._startCallPhase.execute("CreateOffer",(()=>this.mediaSession.createOfferAsync(r))),g=this._startCallPhase.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(this.calculateModalityDirections({},r))));if(this.mediaStateConfigurationHelper.isSending(2)&&this.updateScreenSharingState(u,r),d||(await this._startCallPhase.execute("MuteUnmute",(()=>this.muteUnmute(2===this._muteState,r))),await this._startCallPhase.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,r)))),this._startCallPhase.executeSync("CallStart",(()=>t(r,e,h,g,i,s))),await this._startCallPhase.execute("WaitForConnect",(()=>n)),!this.isCallModeStreaming()||e.isPromotingToRealtime){const e=await this._startCallPhase.execute("WaitForAnswer",(()=>c));if(!this.mediaSession?.processAnswerAsync)throw{error:"NoMediaSession",phase:"ProcessAnswer"};await this._startCallPhase.execute("ProcessAnswer",(()=>this.mediaSession.processAnswerAsync(e,r,!1))),await this._startCallPhase.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(r)))}this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},r),this._startCallPhase=void 0,2!==o?.screenshareDirection&&4!==o?.screenshareDirection||(this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(""),this.enableControlInjector())}catch(e){this.catchJoinOrStartCallError(e,r,a)}}catchJoinOrStartCallError(e,t,i){let n,r=0;throw i.logFailure(je(e)),e?.error&&(n={...e.error}),ph("MuteInput",e)?(r=7,n={code:ks,subCode:3113,phrase:je(e),causeId:t}):ph("MuteOutput",e)?(r=7,n={code:ks,subCode:3114,phrase:je(e),causeId:t}):e?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer||gh(qs,e)?r=47:e?.type===this.mediaAgent.constants.MEDIA_ERROR.permissionDeniedError?(r=58,n={code:ys,subCode:Ls,phrase:je(e),causeId:t}):ph("WaitForAnswer",e)||ph("WaitForConnect",e)?r=e.error:gh(Gs,e)&&(r=7),this.callTelemetry.updateOperationData("_ConnectCall",this.getTelemetryFromPhaseExecution(e),t),this._startCallPhase=void 0,this.callSetupFailed=!0,Promise.all([this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",r,"",t),this._callOperationHandler.maybeRejectOperation("_ConnectCall",r,"",t)]).then((()=>{this.isPromotingToRealtime()||this.stopInternal({causeId:t,terminatedReason:r,rejectReason:n})})).catch(wr),r}addCallMeBackParticipant(e,t,i){const n=this._participantOperationHandler.waitForOperation("CallMeBack",e),r=this.logger.createFnLogger("CallMeBack",i),s={id:e,assertedId:t};return this.signalingSession.callMeBackAsync(s).then((()=>{r.logSuccess(`successfully executed call me back, participantId = ${De(e)}`),this._participantOperationHandler.resolveOperation("CallMeBack",0,e)})).catch((n=>{r.logFailure(`Call me back failed, participantId = ${De(e)}, error = ${n}`),this._handleParticipantOperationFailure("CallMeBack",n,i,t,!1);const s=this._processError(n);let a={};s&&(a={...s}),a.failureReason=s.reason?s.reason:11,this._participantOperationHandler.rejectOperation("CallMeBack",a,e)})),n}addParticipantsToCall(e,t,i,n,r,s,a,o,l,c){const d=this.logger.createFnLogger("addParticipantsToCall",t);e.forEach((e=>{e.setState(1,void 0,t)}));const u=e.map((e=>({id:e.mri})));d.info(`participantIds=${e.map((e=>De(e.id)))}, disableUnmute=${a}`);const h={additionalData:i,groupId:n,threadId:r,messageId:s,disableUnmute:a,alternateId:o,customHeaderContext:l,callingLineIdentity:c};try{const e=this.signalingSession.addParticipantsAsync(u,h,t);return(0,Ws.zip)(e,u).map((async([e,i])=>{try{const n=await e;this.signalingNotifications.onParticipantJoined(n,t);const r=this._getParticipantLegId(this.getParticipant(i.id)),s=r?{participantLegId:r}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},n.id,t,s)}catch(e){const n=this._handleParticipantOperationFailure("AddParticipant",e,t,i.id).reason;throw this._removeParticipant(i,t,n),n}}))}catch(e){return d.logFailure(`Participants was not added to call, error=${e}`),(0,Ws.range)(u.length).map((()=>Promise.reject(1)))}}async mergeCallByAddParticipantWithReplaces(e,t,i,n,r,s,a,o){const l=this.logger.createFnLogger("mergeCallByAddParticipantWithReplaces",s),c=this.convertClientScenario(o),d={additionalData:e.additionalData,groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,callIdToReplace:i.callId,replacementType:n,clientScenario:c},u=await this.signalingSession.addParticipantsAsync(t,d,s);for(let e=0;e<u.length;e++){const i=3===n?t[e].participantId:t[e].id;try{await u[e],l.logSuccess(` [participantInfos id =${De(t[e].id)}]`);const n={debugContent:{replacementParticipantLegId:t[e].replacementParticipantId||void 0,clientScenario:c},participantLegId:t[e].participantId},a={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(r,a,i,s,n),this._callOperationHandler.maybeResolveOperation(r,a,i,s)}catch(n){l.logFailure(`Participant was not added to call, error=${$e(n)}`);const a=this._handleParticipantOperationFailure(r,n,s,i,!0,c).reason;this._removeParticipant(t[e],s,a);const o=n?n.endCode:a||0;this._callOperationHandler.maybeRejectOperation(r,o,i,s)}}return Promise.resolve(a)}admitParticipantToCall(e,t,i){const n=this.logger.createFnLogger("admitParticipantToCall",t),r={id:e};return n.info("start"),this.signalingSession.admitParticipantAsync(r,t).then((r=>{n.info(`successfully admitted participant to call, participantId = ${De(e)}`);const s=i?{participantLegId:i}:{};this.callTelemetry.recordOperationSuccess("AdmitParticipant",{code:0,subCode:0,phrase:""},e,t,s)})).catch((i=>{n.logFailure(`Participant was not admitted to call, error=${i}`);const r=this._handleParticipantOperationFailure("AdmitParticipant",i,t,e);return Promise.reject(r)}))}_processError(t){let i;const n={reason:i};if(t?.endCode){const r=$h(t.endCode.code,t.endCode.subCode);i=e.getParticipantReasonFromTerminatedReason(r),n.reason=i,n.code=t.endCode.code,n.subCode=t.endCode.subCode,n.resultCategories=t.endCode.resultCategories,n.phrase=t.endCode.phrase}else n.phrase=`${t}`;return this.logger.info(`_processError error=${t} telemetryData=${JSON.stringify(n)}`),n}_handleParticipantOperationFailure(e,t,i,n,r=!0,s){this.callTelemetry.updateOperationData(e,{error:$e(t)},i,n);const a=this._processError(t),o=this.getParticipant(n);a.code&&o&&(o.callEndDiagnosticsInfo={callControllerCode:a.code,callControllerSubCode:a.subCode,phrase:a.phrase,resultCategories:a.resultCategories});try{if(r){const t={debugContent:{clientScenario:s},participantLegId:this._getParticipantLegId(o)||void 0};this.callTelemetry.recordOperationFailure(e,a,n,i,t)}}catch(e){this.logger.info(`_handleParticipantOperationFailure error during recordOperationFailure ${e}`)}return a}_getParticipantLegId(e){return(0,Ws.has)(e,"endpoints.endpointDetails")&&e.endpoints.endpointDetails.length&&e.endpoints.endpointDetails[0].participantId?e.endpoints.endpointDetails[0].participantId:null}isOneToOnePSTNCall(e=!1){const t=this.signalingSession.isIncomingCall?this.callerMri:this.participants.length>0?this.participants[0].id:"";return this.isOneToOneCall(e)&&(0,Ws.startsWith)(t,"4:")&&(!this.incomingCallType||!this.callUsesMixer)}isParkedCall(){return this.isOneToOnePSTNCall()&&!!this.callOptions?.parkContext}async updateMediaModalities(e={},t=be(),i){let n;const r=this.logger.createFnLogger("updateMediaModalities",t);return r.info(`callUsesMixer=${this.callUsesMixer},isSomeoneSharing=${this.isSomeoneSharing},isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),r.info(`options=${Ge(e)},requestHoldState=${this.requestedHoldState},requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}`),n=e.modalityOverride?e.modalityOverride:this.requestedHoldState&&!this.isMuteOnHold?this.getMediaModalitiesForHold(t):this.calculateModalityDirections(e?.offered,t),r.info(`modalities=${Ge(n)}`),await this.mediaSession.configureModalitiesAsync(n,t,i),n}calculateModalityDirections(e={},t){const i=this.logger.createFnLogger("calculateModalityDirections",t);i.info(`callUsesMixer=${this.callUsesMixer}, isEscalationInProgress=${this.isEscalationInProgress}`);const n={audio:this.calculateAudioDirection(e.audio,i),video:this.calculateVideoDirection(e.video,i),sharing:this.calculateSharingDirection(e.sharing,i),data:this.calculateDataDirection(e.data,i)};return i.info(`done, modalities=${Ge(n)}`),this.deleteExtraneousModalities(n,t),n}calculateAudioDirection(e,t){return t.info(`calculateAudioDirection, offer=${e}, requestedAudioState=${this.mediaStateConfigurationHelper.isSending(0)}`),this.receiveOnlyAudioOnCallStart?(t.info("calculateAudioDirection, direction=recvonly, receiveOnlyAudioOnCallStart=true"),"recvonly"):this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)||"inactive"===e?"inactive":this.mediaSession.getAllowedModalities().audio.some((e=>e===ug||e===gg))?"sendrecv":"sendonly"===e?"inactive":"recvonly"}calculateVideoDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(1);if(t.info(`calculateVideoDirection, offer=${e}, requestedVideoState=${i}, isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),this.mediaStateConfigurationHelper.isInactiveOrDisabled(0))return"inactive";let n=i,r=this.isSomeoneStreamingVideo||this.callUsesMixer||this.isEscalationInProgress;return e&&(n=n&&("sendrecv"===e||"sendonly"===e),r=r&&("sendrecv"===e||"recvonly"===e)),n?"sendrecv":r?"recvonly":"inactive"}calculateSharingDirection(e,t){return t.info(`calculateSharingDirection, offer=${e}, requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}, isSomeoneSharing=${this.isSomeoneSharing}`),"inactive"===e?"inactive":this.mediaStateConfigurationHelper.isSending(2)?"sendonly":this.isSomeoneSharing||this.callUsesMixer||this.isEscalationInProgress?"recvonly":void 0}calculateDataDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(3);if(t.info(`calculateDataDirection, offer=${e}, dataEnabled=${i}`),this.allowDataChannel())return i?"inactive"===e?"inactive":"sendrecv":void 0;t.info("calculateDataDirection, disabling data since ECS flag prohibits it")}getMediaModalitiesForHold(e){this.logger.info(`[${e}][getMediaModalitiesForHold]`);const t="inactive",i={audio:t,video:t,data:this.allowDataChannel()?t:void 0,sharing:t};return this.deleteExtraneousModalities(i,e),i}deleteExtraneousModalities(e,t){!Wp(e.video)&&this.mediaStateConfigurationHelper.isDisabled(1)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping videoModality`),delete e.video),!Wp(e.sharing)&&this.mediaStateConfigurationHelper.isDisabled(2)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping sharingModality`),delete e.sharing)}getSignalingMediaTypes(e){const t=[];return e.audio&&e.audio!==this.mediaAgent.constants.MEDIA_STATE.inactive&&t.push("Audio"),(e=>e===this.mediaAgent.constants.MEDIA_STATE.send||e===this.mediaAgent.constants.MEDIA_STATE.sendReceive)(e.video)&&t.push("Video"),e.sharing===this.mediaAgent.constants.MEDIA_STATE.send?t.push("ScreenSharer"):e.sharing===this.mediaAgent.constants.MEDIA_STATE.receive&&t.push("ScreenViewer"),t}enableControlInjector(){if(this.allowScreenSharingControl())if(this.getlocalScreenShareStream()){const e=this.mediaSession?.getLocalMediaTrackId("ScreenShare")??"";this.screenSharingControl.enableControlInjector(e)}else this.logger.warn("enableControlInjector: no local screenshare stream found")}createCallDeviceManager(){return new _f(this.mediaAgent.getConfigProvider().config.allowVirtualDeviceInCall,this.mediaAgent.getDeviceManager(),this.logger.createChild("CallDeviceManager"),this.callStats,(e=>this.isMediaSending(e)))}initializeSignalingSession(t){if(this.signalingSession)return void this.logger.info("Session already exists!");const i=wa.CALL_STATUS;if(this.localSignalingParticipant={id:hh(`${dh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri),displayName:this.currentUserSkypeIdentity.displayName,endpointDetails:[],languageId:null,participantId:t,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 e=this.accountConfiguration.serviceUrls.calling_conversationServiceUrl,t=this.accountConfiguration.serviceUrls.calling_uploadLogRequestUrl;this.signalingAgent.updateUrls(e,t,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:(e,t,i)=>{this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} reason=${Ge(t)} callMode=${this.callMode}`);const n=e?t:{code:0,subCode:0};if(this.callTelemetry.recordEvent("PromotionCompleted",{reason:n},i),e){const e=Vh(t);this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",e,"",i),this._callOperationHandler.maybeRejectOperation("_CallStartOrJoinInitiated",e,"",i),this._callOperationHandler.maybeRejectOperation("_ConnectCall",e,"",i),this.promotionCompletedDeferred?.reject(e)}else this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,i),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,i);this.participants.forEach((e=>{e.applyCachedMediaStreams(i)}))},onCallStatusChanged:(e,t,n=be())=>{const r=this.logger.createFnLogger("onCallStatusChanged",n);let s=`[status=${e}]`;if(t&&(s+=`[reason=${Ge(t)}]`,void 0!==t.code&&(this.callEndDiagnosticsInfo={callControllerCode:t.code,callControllerSubCode:t.subCode,phrase:t.phrase,resultCategories:t.resultCategories},(t.overflowJoinInformation||t.registrationInformation)&&(this.callEndDiagnosticsInfo.additionalDiagnostics={overflowInformation:t.overflowJoinInformation,registrationInformation:t.registrationInformation}))),r.info(s),this.callTelemetry.recordEvent("_SignalingStateChanged",{status:e,reason:t},n),e===i.CONNECTING)this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n);else if(e===i.RINGING)2===this.audioStreamState?(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n)))):this.participants.forEach((e=>e.setState(2,void 0,n))),this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n);else if(e===i.CONNECTED_FOR_ROSTER_ONLY)this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("SubscribeWithMeetingData",void 0,void 0,n);else if(e===i.CONNECTED){this._callIsSetupComplete=!0;const e=this.getLocalSignalingEndpointDetails();(e?.isLobby||e?.streamLobby)&&(this._callInLobby=!0,this.updateCapabilities(n,!0));const t=this.signalingSession.participantManager.localParticipant.isStaging;if(11===this.state)this.setCallState(12,n);else if(this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))r.info("wait for joinPreheatedCall to resolved");else if(this._callInLobby)r.info("[inLobby] Override Connected state from signaling agent"),this.setCallState(10,n);else if(t)this.setCallState(13,n);else{if(3===this.state&&!this._callOperationHandler.hasPendingOperation("_CallStartOrJoinInitiated")&&!this._callOperationHandler.hasPendingOperation("_ConnectCall"))return void r.info("Return: Don't re-send setup telemetry if call was already connected and operations are completed");this.setCallState(3,n),this.handleRemoteParticipantStateInOneToOneCall(n)}this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,n),this.reportTsCallingTelemetry(!0)}else if(e===i.LOCAL_TERMINATED||e===i.REMOTE_TERMINATED){let s=this.callSetupFailed?7:Vh(t);if(8===this.state&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData"]))return this.signalingSession.resetState(),this._callOperationHandler.maybeRejectOperation("Subscribe",s,void 0,n),this._callOperationHandler.maybeRejectOperation("SubscribeWithMeetingData",s,void 0,n),void r.info("Subscribe failed, there is pending start/join operation, ignore call end message");if(1!==s&&t?.code===ys&&t?.subCode===Ls&&(s=58,r.info(`[terminated][reason=${Ge(t)}]`)),(2===this.state||6===this.state||8===this.state)&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData","Subscribe","SubscribeWithMeetingData"])){const e={code:this.callEndDiagnosticsInfo.callControllerCode,subCode:this.callEndDiagnosticsInfo.callControllerSubCode,phrase:this.callEndDiagnosticsInfo.phrase,reason:s};this._callOperationHandler.maybeRejectOperations(["Accept","JoinCall","JoinWithMeetingData","JoinPreheatedCall","StartCall","StartCallAndUnpark","StartCallToVoiceMail","StartCallWithNudge","StartWithMeetingData","Subscribe","SubscribeWithMeetingData"],s,void 0,n,e)}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")&&t.pickupCode&&0===t.code&&this._callOperationHandler.resolveOperation("CallParkV2",""+t.pickupCode,void 0,n),1!==s&&this.mediaRelayWhiteListingIssue&&(s=53,r.info(`[terminated][reason=${Ge(t)}]`)),this._callOperationHandler.maybeRejectOperation("CallParkV2",s,"",n),this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",s,"",n),this._callOperationHandler.maybeRejectOperation("_ConnectCall",s,"",n);const a=this.mediaSession?.getSessionConfig().config.setDisconnectAfterCleanUp;if(a?this.setTerminatedReason(s):this.setCallState(7,n,s),this.participants.forEach((e=>e.setState(4,void 0,n))),!this.disconnectingPromise){const s={...t,remoteTerminated:e===i.REMOTE_TERMINATED};this.disconnectingPromise=this.cleanUp(n,s).catch((e=>{r.logFailure(`Error when cleaning up the call, callId = ${this.callId}, error = ${e}`)}))}a&&this.disconnectingPromise.finally((()=>{7!==this.state&&this.setCallState(7,n,s)}))}},onOffer:(e,t=be())=>{const i=this.logger.createFnLogger("onOffer",t);i.info(`${Ge((0,Ws.omit)(ke(e),"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnOffer",this.prepareTelemetryForOfferAnswer(e),t),e.transferor?.details?.id&&this.setTransferorMri(e.transferor.details.id),e.transferor?.transferorType&&(this.transferorType=e.transferor.transferorType),e.transferor?.details?.displayName&&(this.transferorDisplayName=e.transferor.details.displayName),this.clientTransferContext=e.clientTransferContext,this.customHeaderContext=e.customHeaderContext,this.invitationData=e.invitationData,this.spamRiskLevel=e.riskLevel,this.spamStirAttestation=e.stirAttestation,e.mediaContent.isTwoPartyToMultiPartyEscalation&&this.setIsEscalationInProgress(!0,t),e.renegotiation?this.requestedHoldState&&this._pendingParkPromise?this.renegotiateIncoming(e.mediaContent,t):this._delayedElevationPending||this._delayedElevationQueued?(this.signalingSession.rejectRenegotiationAsync({},t),this.triggerDelayedReconnectIfNeeded(t,"onOffer")):this._callOperationHandler.executeChained((()=>this.renegotiateIncoming(e.mediaContent,t)),"_RenegotiateIncoming",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}):(i.info("resolving attach / offer promise"),this.attachToCallAndGetOffer.resolve(e.mediaContent))},onNewOffer:(e,t=be())=>{const i=this.logger.createFnLogger("onNewOffer",t);this.newOfferRequestDeferred?(i.info("onNewOffer"),this.newOfferRequestDeferred.resolve(e.mediaContent)):i.info("callback received but new offer was not requested")},onAnswer:(e,t=be())=>{const i=this.logger.createFnLogger("onAnswer",t);if(i.info(`${Ge((0,Ws.omit)(e,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnAnswer",this.prepareTelemetryForOfferAnswer(e),t),e.renegotiation)i.info("resolving previous renegotiation promise"),this.renegotiationAnswerDeferred.resolve(e.mediaContent);else if(i.info("resolving final answer promise"),e.provisional){const i=this.isOneToOnePSTNCall()&&(0,Ws.startsWith)(e.remoteParticipantId,"4:");this.mediaSession.processAnswerAsync(e.mediaContent,t,!0,i)}else this._callOperationHandler.maybeResolveOperation("_WaitForAnswer",e.mediaContent,void 0,t),this.handleRemoteParticipantStateInOneToOneCall(t);e.provisional||!e.mediaContent.fromMixer||this.callUsesMixer||this._callOperationHandler.executeChained((async()=>{this.setCallUsesMixer(!0,t),this.mediaStateConfigurationHelper.isDisabled(2)&&this.mediaStateConfigurationHelper.removeModality(2),await this.updateMediaModalities(void 0,t);const e=!(this.isSomeoneSharing||this.isScreenSharingOn||this.isVideoOn);return(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.callElevationDelayReconnectPSTN:this.mediaSession.getSessionConfig().config.callElevationDelayReconnect)&&e?(i.info("Delayed elevation: pending"),this._delayedElevationPending=!0,Promise.resolve()):this.mediaSession.reconnectAsync(t,!0)}),"_CallEscalatedToConference",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})},onMediaAcknowledgementSuccess:(e,t=be())=>{this.logger.info(`isRenegotiation: ${e}`,"onMediaAcknowledgementSuccess",t),this._callOperationHandler.resolveOperation("_MediaAcknowledgment",void 0,void 0,t)},onMediaAcknowledgementFailure:(e,t,i=be())=>{this.logger.createFnLogger("onMediaAcknowledgementFailure",i).logFailure(Ge(t)),this._callOperationHandler.rejectOperation("_MediaAcknowledgment",t,i)},onMediaRenegotiationRejection:(e,t=be())=>{this.logger.createFnLogger("onMediaRenegotiationRejection",t).logFailure(Ge(e)),this.renegotiationAnswerDeferred.reject(e)},onRosterHandlingComplete:()=>{this.logger.info(`[onRosterHandlingComplete] ${this._publishedStatesModified}`),0!==this._publishedStatesModified&&(this.processPublishedStates(),this._publishedStatesModified=0)},onMeetingGroupDetailsUpdated:(e,t=be())=>{this.meetingGroupDetails!==e&&(this.callTelemetry.recordEvent("_UpdateMeetingGroupDetails",e,t),this.logger.info(`[${t}][onMeetingGroupDetailsUpdated] update meetingGroupDetails from ${JSON.stringify(this.meetingGroupDetails)} to ${JSON.stringify(e)}`),this.meetingGroupDetails=e,this.raiseChanged())},onSelfParticipantUpdated:(e,t=be())=>{this.logger.info(`[${t}][onSelfParticipantUpdated]`),this.updateLocalParticipant(e,t),this.raiseChanged()},onParticipantMriUpdated:(e,t,i=be())=>{this.logger.info(`[${i}][onParticipantMriUpdated]`);const n=this.getParticipant(e);n&&(n.id=t,this.raiseChangedDeferred())},onParticipantUpdated:(t,i=be())=>{this.logger.info(`[${i}][onParticipantUpdated]: ${rg(t)}`);const n=this.getOrCreateParticipant(t.id,i,!0);n.displayName=t.displayName;const r=e.getStreamsFromEndpoints(t.endpointDetails,this.isMultiVBSSEnabled()),s=(0,Ws.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||r.length>0||s?(this.updateParticipantStreams(n,t,r,i),this.updateCallParticipantFromSignalingParticipant(n,t,i)):n.setState(3,void 0,i),n.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),this.calculateIsSomeoneStreaming(i),this.raiseChangedDeferred()},onParticipantRemoved:(e,t=be(),i=!1)=>{if(this.logger.info(`[${t}][onParticipantRemoved]`),i){const i=this.getParticipant(e.id);this.callTelemetry.recordOperationSuccess("_ParticipantJoined",null,i?.id,t,{participantJoinedButReplaced:"Participant joined with original MRI and replaced with participant of RNL MRI"})}else this.callTelemetry.recordOperationSuccess("RemoveParticipant",null,e.id,t),this._participantOperationHandler.maybeRejectOperation("AddParticipant",1,e.id,t);this._removeParticipant(e,t),this.removePublishedStatesByParticipant(e.id),this.calculateIsSomeoneStreaming(t)},onParticipantJoined:(t,i=be())=>{this.logger.info(`[${i}][onParticipantJoined]`);const n=!this.getParticipant(t.id),r=this.getOrCreateParticipant(t.id,i,!1);r.displayName=t.displayName,0===r.state&&r.setState(1,void 0,i);const s=e.filterVirtualEndpoints(t.endpointDetails),a=e.getStreamsFromEndpoints(s,this.isMultiVBSSEnabled()),o=(0,Ws.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||a.length>0||o?(this.updateParticipantStreams(r,t,a,i),this.updateCallParticipantFromSignalingParticipant(r,t,i),this.calculateIsSomeoneStreaming(i)):(this.handleRemoteParticipantJoinedInOneToOneCall(t,i),this.handleRemoteParticipantStateInObservingCall(r,t,i),t.acceptedBy&&t.acceptedBy!==t.id&&(r.acceptedBy=t.acceptedBy)),this.callTelemetry.recordOperationSuccess("_ParticipantJoined",Er(t.endpointDetails),r.id,i),r.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),n&&this.event("participantAdded").raise(r),this.raiseChangedDeferred()},onCallModeChanged:(e,t)=>{this.callTelemetry.recordEvent("_CallModeChanged",{newCallMode:e,oldCallMode:this._callMode},t),this.logger.info(`onCallModeChanged[${t}]: new=${e} old=${this._callMode} `),e&&this._callMode!==e&&(this._callMode=e,this.isCallModeStreaming()&&this.cleanUpDueToStreaming(t),1===this._callMode&&(this.participants.forEach((e=>{e.applyCachedMediaStreams(t)})),this.promotionCompletedDeferred?.resolve()),this.monitorCallStart(),this.updateCapabilities(t),this.raiseChanged())},getRemoteParticipantCollection:()=>this.participants.map((e=>e.toCafeParticipant())),onReTargetCompletedSuccess:e=>{const t=this.logger.createFnLogger("onReTargetCompletedSuccess",e);t.info(`started, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetSuccess",void 0,e),this.callStats.localStats.call.event(3);const i=this.isEscalationInProgress;this.screenSharingControl&&this.screenSharingControl.shutdownControlForViewer(),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.completeEscalationAsync(e).then((()=>(t.logSuccess("completeEscalationAsync"),this.callTelemetry.recordEvent("_WebOnEscalationSuccess",void 0,e),this.handleCallEscalation(i,e),this.updateMediaStatus(e)))).catch((i=>{t.logFailure(`completeEscalationAsync, error=${je(i)}`),this.setIsEscalationInProgress(!1,e),this.callTelemetry.recordEvent("_WebOnEscalationFailure",$e(i),e),this.stopInternal({causeId:e,terminatedReason:47})}))},onReTargetCompletedFailure:(e,t)=>{this.logger.createFnLogger("onReTargetCompletedFailure",t).logFailure(`reason=${je(e)}, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetFailure",$e(e),t),this.isEscalationInProgress&&(this.setIsEscalationInProgress(!1,t),this.setCallUsesMixer(!1,t),this.updateMediaStatus(t)),this.callStats.localStats.call.event(4),this.mediaSession.rejectEscalationAsync(e,t)},onChatModalitySetupFailed:e=>{this.logger.debug(`onChatModalitySetupFailed: ${e}`)},onConversationUpdated:(e,t)=>{this.logger.info(`onConversationUpdated[${t}]: ${JSON.stringify(ke(e,["organizerId","meetingData"]))}`),this.setConversationType(e.conversationType,t),this._onMessageIdChanged(e.teamsMessageId,t),this.setGroupId(e.groupId,t),this.setThreadId(e.threadId,t),this.setBackroomThreadId(e.backroomThreadId,t),this.setStreamThreadId(e.streamThreadId,t),this.setLobbyThreadId(e.lobbyThreadId,t),this.setCallType(e.isMultiParty?2:1,t),this.setMeetingLayoutDetails(e.meetingLayoutDetails,t),this.setCompositionServiceDetails(e.compositionServiceDetails,t),this._commandUrlPresence=e.commandUrlPresence,this.updateCapabilities(t),this.region=e.region,this.setMeetingData(e.meetingData),this.meetingInfo=e.meetingInfo,this.callLimits=e.callLimits,this.setComplianceRecordingContent(t,e.complianceRecordingContent),this.setHuddleGroupCall(e.isHuddleGroupCall),this.onConversationStartTimeChanged(e.conversationStartTime,t),this.raiseChanged()},onMeetingDetailsUpdated:e=>{this.meetingDetails=e,this.mediaSession&&!this.enableRealtimeTelemetry&&this.meetingDetails.meetingCapability?.enableRealtimeTelemetry&&(this.mediaSession.enableTeamsRealTimeTelemetry(),this.enableRealtimeTelemetry=!0),this.raiseChanged()},onMeetingStatesUpdated:e=>{(0,Ws.isEqual)(e,this.meetingStates)||(this.meetingStates=e,this.logger.info(`[onMeetingStatesUpdated] meetingStates updated to ${JSON.stringify(this.meetingStates)}`),this.raiseChanged())},onParticipantCountsUpdated:e=>{(0,Ws.isEqual)(e,this.participantCounts)||(this.participantCounts={...fr,...e},this.event("participantCountsUpdated").raise(this.participantCounts),this.mediaSession?.processNotification("ParticipantCountChanged",{count:e.totalParticipants}))},updateIsSharedLineAppearanceV2Activated:e=>{this.isSharedLineAppearanceV2Activated!==e&&(this.logger.info(`_updateIsSharedLineAppearanceV2Activated: new value is ${e}`),this.isSharedLineAppearanceV2Activated=e,this.event("sharedLineAppearanceV2ActivatedChanged").raise(this.isSharedLineAppearanceV2Activated))},onBroadcastMeetingUpdated:e=>{e&&(this.broadcastMeeting&&this.broadcastMeeting.metadataChanged(JSON.stringify(e)),this.broadcastMetadata=e,this.raiseChanged())},onBroadcastMeetingConnected:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingConnected]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&(0===e.code?this._callOperationHandler.resolveOperation("AddBroadcastModality",e,t):this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t))},onBroadcastMeetingEnded:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingEnded]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t),this.signalingSession.endBroadcastMeeting(t)},onTransferRequested:(e,t)=>{const i=this.logger.createFnLogger("onTransferRequested",t);i.info("Transfer: onTransferRequested, target participant",rg(e.target));let n="",r="",s=0;"voicemail"===e.target.endpointType&&(s=2);try{n=e.target.id,r=e.transferor.details.id,e&&e.parkType&&"none"!==e.parkType&&(s=1)}catch(e){return i.logFailure(e),this.callTelemetry.recordEvent("_OnTransferRequestedInvalid"),void this.signalingSession.signalTransferCompletedAsync({code:jh(7)})}const a=this.convertToTransferType(s,e.parkType),o={transferContext:{transferorMri:r,targetMri:n,transferType:s,context:{target:e.target,transferor:e.transferor,transferContext:e.transferContext,newCallModalities:e.newCallModalities,links:e.links,replacementDetails:e.replacementDetails,isConsultative:e.isConsultative,callAcceptanceCallback:()=>{i.logSuccess("Transfer: callAcceptanceCallback called"),this.signalingSession.signalTransferAcceptedAsync(a)}}},onCompleted:e=>{i.logSuccess("Transfer: onCompleted called"),this.signalingSession.signalTransferCompletedAsync({code:jh(e)})}};this.callTelemetry.recordEvent("_OnTransferRequested",{transferType:s}),this.event("transferRequested").raise(o)},onTransferredCallAcceptance:e=>{const t=this.logger.createFnLogger("onTransferredCallAcceptance",e);this._transferredCallAcceptanceCallback&&(t.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback())},onTransferAccepted:e=>{this.logger.info("Transfer: onTransferAccepted"),this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&this._setTransferState(2),this._callOperationHandler.hasPendingOperation("BlindTransfer")&&this._callOperationHandler.maybeResolveOperation("_CallTransferInProgress",void 0,void 0,e),this._callOperationHandler.hasPendingOperation("ParkCall")&&this._setParkState(2)},onTransferCompleted:(e,t)=>{const i=this.logger.createFnLogger("onTransferCompleted",t);i.info("Transfer: onTransferCompleted");const n=e.transferCompletion,r=Vh(n);if(n&&(i.info(`Transfer: Call Transfer Code: ${n.code}`),0===n.code)){if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.resolveOperation("_CallTransferInProgress",void 0,void 0,t),this._setTransferState(3)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:0,subCode:0,phrase:"TransactionComplete"};this._callOperationHandler.resolveOperation("ConsultativeTransferWithPickupCode",e,void 0,t),this._setTransferState(3)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation&&(this.serverHoldLocation=e.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("ParkCall",e.unparkContent.pickupCode,void 0,t),i.logSuccess(`pickupCode=${e.unparkContent.pickupCode}`),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",32,t),i.logFailure(`terminatedReason=${r}`),this._setParkState(4)))}else{if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.rejectOperation("_CallTransferInProgress",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setTransferState(4)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:n.code,subCode:n.subCode,resultCategories:n.resultCategories};this._callOperationHandler.rejectOperation("ConsultativeTransferWithPickupCode",e,void 0,t)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(this._callOperationHandler.rejectOperation("ParkCall",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setParkState(4))}},onParkCompleted:(e,t)=>{this.logger.createFnLogger("onParkCompleted",t).info(`transactionEnd ${je(e)}`),this._callOperationHandler.hasPendingOperation("CallParkV2")?0===e.code&&void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("CallParkV2",""+e.unparkContent?.pickupCode,void 0,t),this.callTelemetry.maybeRecordOperationSuccess("CallParkV2"),this.serverHoldLocation=e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation,this.parkAdditionalContextJson=JSON.stringify(e.unparkContent.CallParkAdditionalContext)):this._callOperationHandler.rejectOperation("CallParkV2",e,t):this._callOperationHandler.hasPendingOperation("ParkCall")&&(0===e.code?(this._callOperationHandler.resolveOperation("ParkCall","",void 0,t),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",e,t),this._setParkState(4)))},onUnparkCompleted:(e,t)=>{this.logger.createFnLogger("onUnparkCompleted",t).info(`transactionEnd ${je(e)}`),this._callOperationHandler.hasPendingOperation("UnparkCall")&&(0===e.code?this._callOperationHandler.resolveOperation("UnparkCall",e,void 0,t):this._callOperationHandler.rejectOperation("UnparkCall",e,t))},onIncomingCallReplacement:(e,t)=>{const i=this.logger.createFnLogger("onIncomingCallReplacement",t);this.callTelemetry.recordEvent("_onIncomingCallReplacement",{},t),e.callNotification.callType="replaces",e.callNotification.consultativeCallId=this.callId,i.info(`consultativeCallId=${this.callId}`),e.body={gp:e,evt:Bs.INCOMING_SKYPE_NGC_CALL,nsp:void 0},this.event("replacementRequested").raise(e)},onContentSharingStopped:e=>{this.logger.debug("ScreenSharing: onContentSharingStopped");for(const t of this.contentSharingSessions)t.contentSharingGuid===e.correlationId&&(t.contentSharingStatus=7)},onContentSharingStarted:e=>{this.logger.debug("ScreenSharing: onContentSharingStarted");const t=new Bg(this.callTelemetry,this.logger.createChild("ContentSharingSession"),this.signalingSession,e.correlationId||mi(),e.contentIdentifier,e.sessionState,e.subject,e.sessionId);t.contentSharingStatus=2,this.contentSharingSessions.push(t),t.changed((()=>this.removeContentSessionIfEnded(t))),this.event("contentSharingChanged").raise()},onContentSharingUpdated:e=>{this.logger.debug("ScreenSharing: onContentSharingUpdated");const t=(0,Ws.find)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.correlationId));t?(e.presenter&&(t.presenterId=e.presenter),e.subject&&t.subject!==e.subject&&(t.subject=e.subject),e.sessionState&&t.contentSharingState!==e.sessionState&&(t.contentSharingState=e.sessionState),3===t.contentSharingStatus&&this.localSignalingParticipant.id!==e.presenter?t.contentSharingStatus=5:5===t.contentSharingStatus&&this.localSignalingParticipant.id===e.presenter&&(t.contentSharingStatus=3)):this.logger.warn("onContentSharingUpdated: session not found")},onWebRtcMediaNotification:(e,t)=>{this.mediaSession?.processNotification(e,t)},onCorrelationIdUpdated:(e,t)=>this.checkForCallIdUpdate(e,t),onUnmuteRequested:e=>{},onCallForwarded:e=>{e&&e.destinationType!==this.forwardingDestinationType&&(this.forwardingDestinationType=e.destinationType,this.raiseChanged())},onPSTNBalanceUpdate:e=>{},isOneToOnePstnCall:()=>this.isOneToOnePSTNCall(),onUpdateMeetingLiveStateCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingLiveStateCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingLiveState",i)},onUpdateMeetingStatesCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingStatesCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingStates",i)},onUpdateMeetingGroupsCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingGroupsCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingGroups",i)},onSetMeetingLayoutCompleted:(e,t,i)=>{this.logger.info(`[onSetMeetingLayoutCompleted] causeId [${t}] operationId: ${i}`),this.onOperationCompleteCommonHandler(e,t,"SetMeetingLayout")},onJoinMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"JoinMeetingGroup",i)},onLeaveMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"LeaveMeetingGroup",i)},onBreakoutDetailsUpdated:(e,t)=>{this.logger.info(`[onBreakoutDetailsUpdated] [${t}]`),this.breakoutDetails=e,this.raiseChanged()},onIncomingProxiedMessages:(e,t)=>{this.logger.info(`[onIncomingProxiedMessages] [${t}] payload ${je(e,!0)}`),this.event("incomingProxiedMessages").raise(e)},onUpdateParticipantsPropertiesCompleted:(e,t,i)=>{this.logger.createFnLogger("onUpdateParticipantsPropertiesCompleted",i).info(`promisesToResolve ${De(Ge(e))}`);for(const t of Object.keys(e))e[t].code===Ar?this._callOperationHandler.maybeResolveOperation("UpdateParticipantsProperties",e[t],t,i):this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",e[t],t,i)},onUpdateMonitorSessionCompleted:(e,t)=>{this.logger.info(`[onUpdateMonitorSessionCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMonitorSession")},onNudgeToJoinRealtime:e=>{this.logger.info("[onNudgeToJoinRealtime]",e),this.callTelemetry.recordEvent("NudgeToJoinRealTime",e),this.canPromoteToRealTime(1)&&this.promoteToRealtime(1,e).then((()=>this.logger.info(`[onNudgeToJoinRealtime][${e}] completed`))).catch((t=>this.logger.info(`[onNudgeToJoinRealtime][${e}] failed to auto promote: ${je(t)}`)))},onConversationTypeUpdated:(e,t)=>{this.logger.info(`[onConversationTypeUpdated] [${t}] conversationType ${e}`),this.setConversationType(e,t)}};const n=Object.create(this.localSignalingParticipant);this.signalingSession=this.signalingAgent.getNewSignalingSession(n,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(t,i,n,r){const s=e.getNegotiationTagsFromEndpoints(i.endpointDetails);t.updateStreams(n,r,this.isCallModeStreaming(),s,this.isMultiVBSSEnabled());const a=this.getStreamInformationMap(i);this.logger.info(`[updateParticipantStreams]: streaming mode with new streamInfoMap: ${Ge(a)}`);const o={callId:this.callId,participantId:this.participantId,endpointId:this.endpointId};this.meetingData&&(o.meetingId=this.meetingData.meetingCode);const l=this.telemetryLoggers?this.telemetryLoggers.tlePlayer:null;t.useUmsStream(a,this._liveStreamConfigProvider,o,this.threadId,l,r)}cleanUpDueToStreaming(e){this.logger.info(`cleanUpDueToStreaming[${e}]: cleaning streams and media and canceling cc operations`),this.cancelAllCallingOperationsDueToStreaming(e);const t={code:0,subCode:3099,phrase:"DowngradeToStreamingClient"};this.participants.forEach((t=>t.updateStreams([],e,this.isMultiVBSSEnabled()))),this.cleanUpMedia(e,t).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((t=>{this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(t)},e)})).finally((()=>{this.mediaDisposedPromise=null})),this.finishCallHoldResume(t),this.renegotiationAnswerDeferred?.reject(t),this.newOfferRequestDeferred?.reject(t),this._parkState=0,this._transferState=0,this.isServerMuted||(this._muteState=0),this.isSpeakerMuted=!1,this.requestedHoldState=!1,this.isMuteOnHold=!1}cancelAllCallingOperationsDueToStreaming(e){this._callOperationHandler.maybeRejectPendingOperationsWithPredicate(74,e,((e,t)=>(0,Ws.some)(t?.preconditionTags,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))))}onOperationCompleteCommonHandler(e,t,i,n){0===e.code?this._callOperationHandler.maybeResolveOperation(i,e,n,t):this._callOperationHandler.maybeRejectOperation(i,e,n,t)}convertToTransferType(e,t){let i="none";return 1===e&&t&&"none"!==t?"teamPark"===t?i="TransferTypeTeamPark":"sharedLinePark"===t?i="TransferTypeSharedLinePark":"serverHold"===t&&(i="TransferTypeServerHold"):0===e?i="TransferTypeStandard":2===e?i="TransferTypeVoicemail":this.logger.info(`Irrelevant combination of transferTye: ${e} and parkType: ${t}`),i}raiseChangedDeferred(e){(!this.raiseChangedDefer||this.raiseChangedDefer.isSkippable&&!e)&&(cg.instance.runDeferredWithoutDedup((()=>{delete this.raiseChangedDefer,this.raiseChanged(e)}),"Call.raiseChanged"),this.raiseChangedDefer={isSkippable:!!e})}static getStreamsFromEndpoints(t,i){if(!t)return[];const n=e.filterVirtualEndpoints(t);return n.forEach((e=>{e.mediaStreams=i?e.mediaStreams:e.mediaStreams?.filter((e=>e.type!==Sg)),(0,Ws.forEach)(e.mediaStreams,(t=>{t.participantId=e.participantId,t.endpointId=e.endpointId}))})),(0,Ws.flatMap)(n,(e=>e&&e.mediaStreams||[]))}preconditions(e,t){this.logger.info(`check call mode currentMode is ${this.callMode} operationName is ${e}`),(0,Ws.some)(t,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))&&this.isCallModeStreaming(!0)}mapCallSetupIntent(e){switch(e){case 0:return"None";case 1:return"AutoPromotion";case 2:return"PromotionWithAudio";case 3:return"PromotionWithVideo";default:return"Unknown"}}async promoteToRealtime(e,t){this.logger.info(`[${t}][promoteToRealtime] started with intent=${e}`);const i=this.getPromoteToRealtimeCallOptions(e,this.callOptions);this.callTelemetry.updateOperationData("_PromotionToRealtime",{intent:e},t),this.callTelemetry.recordEvent("StartPromotion",{intent:this.mapCallSetupIntent(e)},t);try{this.promotionCompletedDeferred=new Kt,await Promise.all([this.joinOrStartCall(i,this.joinGivenConversation,t,void 0),this.promotionCompletedDeferred.promise])}catch(e){throw this.logger.logFailure(`[${t}][promoteToRealtime] failed with reason=${je(e)}`),this.cleanUpDueToStreaming(t),this.signalingSession.cleanUpDueToStreaming(t),e}}async promoteToRealtimeAndUnmute(e){return this.logger.info(`[${e}][promoteToRealtimeAndUnmute]`),this.isPromotingToRealtime()?(this.logger.info(`[${e}][promoteToRealtimeAndUnmute] already promoting to realtime.`),this._callOperationHandler.waitForOperation("_PromotionToRealtime").then((()=>this.muteUnmute(!1,e)))):this.canPromoteToRealTime(2)?(this.unmutePendingPromise=new Kt,setTimeout((()=>{this.unmutePendingPromise?.reject("promoteToRealtime unmute timed out")}),1e3*this.signalingSession.signalingAgentConfig.csaTimeoutConfiguration.promotionUnmuteTimeoutSec),Promise.all([this.promoteToRealtime(2,e),this.unmutePendingPromise.promise]).then((()=>{})).finally((()=>this.unmutePendingPromise=null))):Promise.reject("manual promotion with audio is not allowed")}isPromotingToRealtime(){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")}getPromoteToRealtimeCallOptions(e,t){let i,n=1;1===e?i={value:!0,mediaTypes:["audio"]}:3===e?(i={value:!0,mediaTypes:["audio"]},n=4):2===e&&(i={value:!1});const r={...t.callStartOptions,sendMediaModalities:{mediaStates:[Gh(0,4),Gh(1,n)].filter((e=>null!=e))},preheatFlags:0};return{...t,callStartOptions:r,applyServerMute:i,isPromotingToRealtime:!0,callStartTime:Date.now()}}canPromoteToRealTime(e){const t=this.logger.createChild("[canPromoteToRealTime]");return t.info(`[promoteType:${e}]`),this.isCallModeStreaming()?this.isPromotingToRealtime()?(t.info("already promoting to realtime"),!1):1===e||2===e:(t.info("cant promote since call mode is not streaming"),!1)}isCallModeStreaming(e=!1){if(2===this.callMode){if(!e)return!0;throw this.logger.info("reject check callmode"),{code:499,subCode:3551,phrase:"TransactionNotAllowedForStreamMode"}}return!1}setCallOptions(e){this.receiveOnlyAudioOnCallStart=!!e.callStartOptions?.receiveOnlyAudioOnCallStart,this.callOptions=e,this.logger.info(`callOptions: ${Ge(function(e){const t={};Kh(e.callStartTime)&&(t.callStartTime=e.callStartTime),Kh(e.callVoicemailStartOptions)&&(t.callVoicemailStartOptions=e.callVoicemailStartOptions),Kh(e.invitationType)&&(t.invitationType=e.invitationType),Kh(e.meetingPreferences)&&(t.meetingPreferences=e.meetingPreferences),Kh(e.parkContext)&&(t.parkContext=e.parkContext),Kh(e.pickupCode)&&(t.pickupCode=e.pickupCode),Kh(e.participantsToNudge)&&(t.participantsToNudgeSize=e.participantsToNudge.length);const i=e.callStartOptions;if(i){const e={};Kh(i.additionalEndpointProperties)&&(e.additionalEndpointProperties=i.additionalEndpointProperties),Kh(i.clientEndpointCapabilities)&&(e.clientEndpointCapabilities=i.clientEndpointCapabilities),Kh(i.connectionType)&&(e.connectionType=i.connectionType),Kh(i.invitationDataJson)&&(e.invitationDataJson=i.invitationDataJson),Kh(i.isCast)&&(e.isCast=i.isCast),Kh(i.isHuddleGroupCall)&&(e.isHuddleGroupCall=i.isHuddleGroupCall),Kh(i.label)&&(e.label=i.label),Kh(i.maxVideoChannels)&&(e.maxVideoChannels=i.maxVideoChannels),Kh(i.maxVbssChannels)&&(e.maxVbssChannels=i.maxVbssChannels),Kh(i.mediaConfiguration)&&(e.mediaConfiguration=i.mediaConfiguration),Kh(i.muteFlags)&&(e.muteFlags=i.muteFlags),Kh(i.muted)&&(e.muted=i.muted),Kh(i.negotiationTag)&&(e.negotiationTag=i.negotiationTag),Kh(i.preheatFlags)&&(e.preheatFlags=i.preheatFlags),Kh(i.ringOthers)&&(e.ringOthers=i.ringOthers),Kh(i.routingFlags)&&(e.routingFlags=i.routingFlags),Kh(i.scenario)&&(e.scenario=i.scenario),Kh(i.screenshareDirection)&&(e.screenshareDirection=i.screenshareDirection),Kh(i.sendMediaModalities)&&(e.sendMediaModalities=i.sendMediaModalities),Kh(i.sharedLineCallInvitationContentJson)&&(e.sharedLineCallInvitationContentJson=i.sharedLineCallInvitationContentJson),Kh(i.targetApplicationType)&&(e.targetApplicationType=i.targetApplicationType),Kh(i.captchaContentJson)&&(e.captchaContentJson=i.captchaContentJson),Kh(i.callQueueContext)&&(e.callQueueContext=i.callQueueContext),Kh(i.clientEndpointDebugContent)&&(e.clientEndpointDebugContentSize=i.clientEndpointDebugContent.length),Kh(i.alternateId)&&(e.alternateId=De(i.alternateId)),Kh(i.callKey)&&(e.callKeySize=i.callKey.length),Kh(i.encryptedKey)&&(e.encryptedKeySize=i.encryptedKey.length),t.callStartOptions=e}return t}(e))}`)}getSelfClientEndpointCapabilities(){return this.callOptions?.callStartOptions?.clientEndpointCapabilities}getLocalSignalingEndpointDetails(){return(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(e=>e?.endpointId===this._endpointId))}getStreamInformationMap(e){const t={};return e&&this.accountConfiguration?.clientSupportsUms&&(0,Ws.forEach)(e.endpointDetails,(e=>{e?.streamInformation&&e.participantId&&e.participantId!==this._participantId&&(t[e.participantId]=e.streamInformation)})),t}updateSATInfo(e=[]){const t=this.mediaSession?.getSessionConfig().config.slowedDownTalkerInfoAggregationTime;if(!t||t<0)return;const i=Date.now(),n=i-1e3*t;this.activeTalkersHistory=this.activeTalkersHistory.filter((({timestamp:e})=>e>n)).concat({speakers:e.map((e=>e.id)),timestamp:i});const r=Object.entries(this.activeTalkersHistory.reduce(((e,{speakers:t})=>{for(const i of t)e[i]??(e[i]=0),e[i]++;return e}),{})).sort((([,e],[,t])=>t-e)).map((([e])=>e));this.slowedDownActiveTalkerInfo={speakerList:r,timestamp:new Date(i)}}enableRemoteUFDs(e){this.logger.info((e?"Enabling":"Disabling")+" remote UFDs"),e?this.remoteUFDHandler.init():this.remoteUFDHandler.dispose()}setPlatformCallConstraints(e){this.setCallConstraints(e).catch((e=>{this.logger.error(e)}))}setCallConstraints(e){return this.mediaSession?(this.logger.info(`Applying platform constraints to current call ${JSON.stringify(e)}`),this.mediaSession.setCallConstraints(e,be())):(this.logger.info("Saving platform constraints until media session is created"),this.temporaryCallConstraints=e,new Promise(((e,t)=>{this.resolveTemporaryCallConstraints=e,this.rejectTemporaryCallConstraints=t})))}initializeMediaSession(t,i){if(this.mediaSession)return;const n=this.logger.createFnLogger("initializeMediaSession",t),r=((e,t)=>{const i={};return Object.keys(t).forEach((n=>{i[n]=(...i)=>t[n]&&e()&&t[n](...i)})),i})((()=>!this.isCallModeStreaming()||this.isPromotingToRealtime()),{onSessionErrorOccurred:(e,t=be())=>{n.error(`[${t}][onSessionErrorOccurred]: ${Ge(e)}`);const i=[this.mediaAgent.constants.MEDIA_ERROR.iceConnectionError,this.mediaAgent.constants.MEDIA_ERROR.internalError];(0,Ws.includes)(i,e.type)&&this.event("mediaConnectionFailed").raise(),this.callTelemetry.recordEvent("SessionError",{type:e.type},t)},onNegotiationRequired:(e=be(),t)=>{this.executeNegotiation(e,"onNegotiationRequired",!0,t)},onContributingSourcesChanged:e=>{const t=this.mediaSession?.getSessionConfig().config.contributingSourcesLogInterval,i=t&&Date.now()>=this.lastContributingSourceReport+t,r=i?new Map(e.map((e=>[e,"<unknown>"]))):new Map,s=[];for(const t of this.participants){const n=e.some((e=>t.hasAudioSource(e))),a=n?1:0;t.updateVoiceLevel(a),n&&(s.push(t),i&&r.set(t.audio.id,De(t.id)))}this.updateSATInfo(s),i&&(n.info(`[onContributingSourcesChanged], ${e.length?Array.from(r).join(";"):"none"}`),this.lastContributingSourceReport=Date.now())},onDominantSpeakerChanged:(e,t)=>{const i=be(),r=[],s=[];e.forEach((e=>{const t=(0,Ws.find)(this.participants,(t=>t.hasAudioSource(e)));t?(r.push(t.id),s.push(De(t.id))):s.push(this.streamManager.audio.id===e?"<self>":"<unknown>")})),n.info(`[${i}][onDominantSpeakerChanged], msidList = ${e} => speakerList = ${s}, timestamp = ${t}`),this.dominantSpeakerInfo={speakerList:r,timestamp:t,noCurrentDominantSpeaker:!1},this.event("dominantSpeakerChanged").raise(),this.raiseChanged(this._dominantSpeakerChangedEventSkipConfig)},onAudioStateChanged:(t,i)=>{const n=be(),r=this.logger.createFnLogger("onAudioStateChanged",n);r.info(Ge(t)),this.callStats.localStats.audio.streamStateChanged(t.stream,t.direction);const s=e.streamingStatetoMediaStreamState(t.stream);if(this.audioStreamState=s,!s)return;this.callTelemetry.recordEvent("AudioStateChanged",{state:t,reason:i},n),2===s&&2===this.state&&(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n))));const a={mediaType:0,mediaDirection:e.streamingDirectionToMediaDirectionMapping(t.direction),mediaStreamState:s};if(this.event("mediaStreamStateChanged").raise(a),!this.isCallSetupTelemetrySent&&this.mediaSession?.getSessionConfig().config.sendCallStartupTelemetry&&this.sendCallSetupTelemetry(),0===a.mediaDirection&&(this.isAudioStreamConnected=(0,Ws.includes)([2,1],a.mediaStreamState)),(0,Ws.includes)([3,4],a.mediaStreamState)&&(r.logFailure(`audio stream state changed to ${t.stream} with reason ${i}`),!i||["timeout","connection-dropped","connectivity-check-failure","suspended"].indexOf(i)>=0)){this.event("mediaConnectionFailed").raise();const e="suspended"===i?77:this.mediaRelayWhiteListingIssue?53:4;this.mediaRelayWhiteListingIssue&&this.callTelemetry.recordEvent("_MediaWhiteListingIssueDetected"),this.stopInternal({causeId:n,terminatedReason:e})}},onQualityChanged:t=>{const i={type:e.convertQualityEventType(t.type),value:e.convertQualityLevel(t.value),isLocalSource:t.isLocalSource,mediaType:e.convertMediaType(t.mediaType)};this.muteUnmuteWorkaround(i),32===i.type&&(this.mediaRelayWhiteListingIssue=3===i.value,this.mediaRelayWhiteListingIssue&&this.event("mediaConnectionWhitelistingWarning").raise()),5===i.type&&3===i.value&&this.trouterService.checkConnection(!0),this.callTelemetry.recordEvent("AudioQualityChanged",i),this.remoteUFDHandler.raiseIfNeeded(t,this.participantCounts?.totalParticipants,(e=>{this.publishState(e,be())})),this.event("callQualityChanged").raise(i)},onOptimalVideoReceiversCountChanged:e=>{n.debug(`onOptimalVideoReceiversCountChanged: ${e}`),this.optimalVideoCount!==e&&(this.optimalVideoCount=e,this.raiseChanged())},onDataChannelUpdated:e=>{const t=be();n.debug(`[${t}] onDataChannelUpdated`),this.dataChannel.registerSessionDataChannel(e,t)},onUpdateMediaDescriptionsRequired:(e,t)=>{this.executeNegotiation(e,"onUpdateMediaDescriptionsRequired",!1,t)},onRealtimeTelemetryReport:()=>{this.reportTelemetryEvents([{eventName:Ah.realtimeTelemetry,props:{user_object_id:{value:dh+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:e=>this.updateSignalingDSHMessageSubscription(e)});this.callTelemetry.recordEvent("CreatingConference","",t),this.callDeviceManager||(n.info(`[${t}][initializeMediaSession] Creating new callDeviceManager`),this.callDeviceManager=this.createCallDeviceManager());const s={maxReinvitelessMediaForVBSSMultiparty:this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb(),maxReinvitelessMediaForVideoMultiparty:this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()};this.callTelemetry.recordEvent("_ReinvitelessConfig",{reinvitelessConfig:s},t);const a=this.mediaAgent?.getConfigProvider().config.identifyOneToOneCallWithoutParticipants;this.mediaSession=new Xh(this.mediaAgent.createSession(r,this.signalingSession,{isConference:this.callUsesMixer,isPstnCall:this.isOneToOnePSTNCall(a),isParkedCall:this.isParkedCall(),reinvitelessConfig:s},this.callDeviceManager,this.smallCallTelemetry,i),this.signalingSession),this.batteryStatus=new Pf(this.mediaSession.getDiagnostics(),this.mediaAgent.getConfigProvider()),this.batteryStatus.on("batteryStatusChanged",(()=>this.reportSmallCallEvent(this.smallCallTelemetry?.getSmallTelemetryOnBatteryLow()))),this.temporaryCallConstraints&&(n.info(`Applying saved call constraints to current call ${JSON.stringify(this.temporaryCallConstraints)}`),this.mediaSession.setCallConstraints(this.temporaryCallConstraints,be()).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","",t),this.streamManager.setMediaSession(this.mediaSession,t),this.participants.forEach((e=>{e.setMediaSession(this.mediaSession,t)}));const o=this.mediaSession.getSessionConfig()?.config;o?.useOneDsLogger&&o?.addTelemetryReportingCallback&&(this.beforeUnloadTelemetrySender=()=>{this.sendLastKnownStats()},window.addEventListener("beforeunload",this.beforeUnloadTelemetrySender)),this.screenSharingControl&&this.allowDataChannel()&&this.screenSharingControl.setupDataHandlers(),this.unmixedAudioProvider=new bf}executeNegotiation(e,t,i,n){const r=this.logger.createFnLogger(t,e);if(this.isCallModeStreaming()||this.isEscalationInProgress)return void r.info(`ignored due to being in streaming=${this.isCallModeStreaming()},\n isEscalationInProgress=${this.isEscalationInProgress}`);const s=be();3===this.state||4===this.state||5===this.state||10===this.state||this.isPreheatedOnly()?(r.info(`started, state: ${this.state}, runNegotiation: ${i}`),i?(this.callTelemetry.recordEvent("NegotiationRequired","",e),this._callOperationHandler.executeChained((()=>this.renegotiateOutgoing(e,n)),"_RenegotiateOutgoing",s,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})):(this.callTelemetry.recordEvent("UpdateMediaDescriptions","",e),this._callOperationHandler.executeChained((()=>this.updateMediaDescriptions(e,n)),"_UpdateMediaDescriptions",void 0,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}))):r.info(`not started, state: ${this.state}`)}async muteUnmuteWorkaround(e){if(this.mediaSession?.getSessionConfig().config.enableMuteSpeakerUnmuteSpeakerWorkaround&&!this.isSpeakerMuted&&25===e.type&&3===e.value&&0===e.mediaType){this.logger.log("Performing muteSpeaker->unmuteSpeaker workaround");const e=be();await this.muteSpeaker(e),await this.unmuteSpeaker(e)}}sendLastKnownStats(){if(this.tsCallingTelemetryReported)return;this.callEndDiagnosticsInfo={callControllerCode:Ar,callControllerSubCode:xr},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo);const e=this.callTelemetry.getShortEvent();e.Code=this.callEndDiagnosticsInfo.callControllerCode,e.SubCode=this.callEndDiagnosticsInfo.callControllerSubCode;let t="csa_conversation_callmodality";if(this.reportTelemetryEvents([{eventName:t,props:e}],"signaling","skypecosi_concore_web"),t=this._callIsSetupComplete?"in_call_session":"call_setup_session",this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(!0)}],"signaling","skypecosi_concore_web_ts_calling"),this.mediaSession){const e=this.mediaSession.getLastKnownStats(!0);this.callStats.setMediaStats(e),this.reportSmallCallEvent(null,!0),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web")}this.reportVDITelemetryEvents()}reportSmallCallEvent(e,t){this.reportTelemetryEvents(this.callStats.buildShortCallEvent(e??this.smallCallTelemetry?.getEndCallSmallTelemetry(t)),"media","mdsc")}invertDirectionality(e){switch(e){case this.mediaAgent.constants.MEDIA_STATE.sendReceive:return gg;case this.mediaAgent.constants.MEDIA_STATE.send:return hg;case this.mediaAgent.constants.MEDIA_STATE.receive:return ug;default:return null}}completeNegotiationAsync(e){const t=this.logger.createFnLogger("completeNegotiationAsync",e),i=this.mediaSession.completeNegotiationAsync(e).then((i=>{t.info(`activeModalities=${i&&Object.keys(i.activeModalities)}`);const n=this.mediaSession.getSessionConfig().config.avoidFakeStreamsDuringEscalation&&this.isEscalationInProgress;if(!this.callUsesMixer&&!n){if(this.mediaStateConfigurationHelper.isSending(3)&&i.initiator){const t=i.offeredModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive,n=i.activeModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive;t&&!n&&(this.logger.info(`[${e}][completeNegotiationAsync] Disabling data modality as it was not wanted by remote`),this.mediaStateConfigurationHelper.removeModality(3))}const t=this.participants[0],n=t?.endpoints?.endpointDetails.length&&t.endpoints.endpointDetails[0].mediaStreams?.length;if(t&&!n){const n=(e,t,i)=>({participantId:Of,endpointId:"remote",type:e,direction:this.invertDirectionality(t),sourceId:i,serverMuted:!1}),r=[];r.push(n(pg,i.activeModalities.audio,1)),i.activeModalities.video&&r.push(n(mg,i.activeModalities.video,2)),i.activeModalities.sharing&&r.push(n(fg,i.activeModalities.sharing,3)),t.updateStreams(r,e,this.isMultiVBSSEnabled()),!this.callIsHeld()&&this.calculateIsSomeoneStreaming(e)}}if(t.logSuccess(Ge(i)),this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&i?.activeModalities?.audio){const t=i.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||i.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(t?2:this.isServerMuted?1:0,e)}return i}));return i.catch((i=>{t.logFailure(i),this.callTelemetry.recordEvent("_CompleteNegotiationFailed",{e:i},e)})),i}async renegotiateOutgoing(e,t){this.renegotiationAnswerDeferred=new Kt;const i=this.logger.createFnLogger("renegotiateOutgoing",e),n=this.inLocalHold()?this.getMediaModalitiesForHold(e):this.calculateModalityDirections({},e);if(this._delayedElevationPending&&!this._delayedElevationQueued){if(Wp(n.video)||Wp(n.sharing))return i.info("mediaModalities",n),void await this.triggerDelayedReconnectIfNeeded(e,"renegotiateOutgoing");i.info("Delayed elevation (renegotiateOutgoing): no outgoing video or sharing, skipping elevation for now")}i.info("start");const r=mh(i);try{try{const i=await r.execute("MediaCreateOffer",(()=>this.mediaSession.createOfferAsync(e,t))),s=this.getSignalingMediaTypes(n);await r.execute("SignalingStartNegotiation",(()=>this.signalingSession.startRenegotiationAsync(i,s,e)));const a=await r.execute("SignalingRenegotiationAnswer",(()=>this.renegotiationAnswerDeferred.promise));await r.execute("MediaProcessAnswer",(()=>this.mediaSession.processAnswerAsync(a,e,!1)));const o=await r.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(e)));this.onNegotiationCompletion(o,!0,n,e,r.getTelemetryData())}catch(t){if(i.logFailure(t),!t.phase)throw this.callTelemetry.recordEvent("OutgoingNegotiationFailure",t,e),t;let r="unknown";const s=this.mediaAgent.constants.RENEGOTIATION_ERROR;if(r=s.local,"SignalingRenegotiationAnswer"===t.phase||"SignalingStartNegotiation"===t.phase){const e=415;r=491===t.error.code?s.glare:t.error.code===e?s.media:s.signaling}else"MediaCreateOffer"===t.phase&&t.error.type===this.mediaAgent.constants.MEDIA_ERROR.noNetworkError&&(r=s.media);if(this.callTelemetry.recordEvent("OutgoingNegotiationFailure",this.getTelemetryFromPhaseExecution(t),e),t.error.message?.includes("The requested call does not exist"))throw new Error("Call drop due to remote replying with call not found");i.logFailure(r);const a={type:r,detail:t.error};await this.mediaSession.rejectNegotiationAsync(a,e),this.onNegotiationFailure(t.error,r,e,n)}}catch(t){i.logFailure(t),this.callTelemetry.recordEvent("NegotiationFatalError",$e(t),e),this.stopInternal({causeId:e,terminatedReason:47})}}async renegotiateIncoming(e,t){this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",null,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.mediaAcknowledgmentOperation.catch(wr);const i=this.logger.createFnLogger("renegotiateIncoming",t);if(i.info("start"),e.newOffer&&!this.mediaAgent.getCapabilities().retargeting)return i.logFailure("Retarget offer received, but pluginless has no support for retarget"),void this.stopInternal({causeId:t,terminatedReason:38});const n=mh(i);try{const i=await n.execute("MediaProcessOffer",(()=>this.mediaSession.processOfferAsync(e,t)));this.handleOfferedModalities(i,t),2===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForResume(t);const r=await this.updateMediaModalities({offered:i},t);1===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForHold(t),this.updateMediaState(r,t),this.isRenegotiationHoldOrResume(r)&&this.updateScreenSharingState(r,t);const s=await n.execute("MediaCreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t))),a=this.getSignalingMediaTypes(r);await n.execute("SignalingAcceptRenegotiation",(()=>this.signalingSession.acceptRenegotiationAsync(s,a,t))),await n.execute("SignalingMediaAcknowledgement",(()=>this.mediaAcknowledgmentOperation));const o=await n.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t)));this.onNegotiationCompletion(o,!1,i,t,n.getTelemetryData())}catch(e){try{if(!e.phase||"CompleteNegotiation"===e.phase)throw this.callTelemetry.recordEvent("IncomingNegotiationFailure",e,t),e;const n=e;this.callTelemetry.recordEvent("IncomingNegotiationFailure",this.getTelemetryFromPhaseExecution(e),t);const r={type:this.mediaAgent.constants.RENEGOTIATION_ERROR.local,detail:e.error};if("SignalingAcceptRenegotiation"===n.phase||"SignalingMediaAcknowledgement"===n.phase)return i.logFailure("Error in renegotiateIncoming() -> rejecting media negotiation"),r.type=this.mediaAgent.constants.RENEGOTIATION_ERROR.signaling,this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),void await this.mediaSession.rejectNegotiationAsync(r,t);this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),await this.mediaSession.rejectNegotiationAsync(r,t),await this.signalingSession.rejectRenegotiationAsync(void 0,t)}catch(e){i.logFailure(e),this.callTelemetry.recordEvent("NegotiationFatalError",$e(e),t),this.stopInternal({causeId:t,terminatedReason:47})}}}async updateMediaDescriptions(e,t){const i=this.logger.createFnLogger("updateMediaDescriptions",e);i.info("start");try{const n=await this.mediaSession.startMediaDescriptionsUpdateAsync(e,t);i.info(`send updateMediaDesriptions, descriptions=${Ge(n)}`),await this.signalingSession.updateMediaDescriptionsAsync(e,n);const r=await this.mediaSession.completeMediaDescriptionsUpdateAsync(e);if(this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&r?.appliedModalities?.audio){const t=r.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||r.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(t?2:this.isServerMuted?1:0,e)}this.onUpdateMediaDescriptionsCompletion(r,e)}catch(t){i.logFailure(t),this.callTelemetry.recordEvent("UpdateMediaDescriptionsFailure",t,e);const n=await this.mediaSession.rejectMediaDescriptionsUpdateAsync(e,!0);this.onUpdateMediaDescriptionsFailure(t,n,e)}}handleCallEscalation(e,t){const i=this.logger.createFnLogger("handleCallEscalation",t);if(i.info(`current callType=${this.callType}, escalationInProgress=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e){const e=this.participants[0];e&&e.audio.participantId===Of?e.updateStreams([{type:pg,direction:"inactive",sourceId:null,serverMuted:!1},{type:mg,direction:"inactive",sourceId:null,serverMuted:!1},{type:fg,direction:"inactive",sourceId:null,serverMuted:!1}],t,this.isMultiVBSSEnabled()):i.info("no 1-1 participant found, stream update ignored"),this.setCallType(2,t),this.setCallUsesMixer(!0,t),this.setIsEscalationInProgress(!1,t),this.callTelemetry.recordEvent("_EscalationCompleted",void 0,t),this.raiseChanged()}}async reportTsCallingTelemetry(e){if(this.tsCallingTelemetryReported)return;await this.connectCallPromise.catch(wr);const t=e?"call_setup_session":"in_call_session";this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(e)}],"signaling","skypecosi_concore_web_ts_calling"),e?this.callTelemetry.switchToInCallTelemetry():this.tsCallingTelemetryReported=!0}async sendMidCallTelemetry(e){this.mediaSession&&e?.length&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(!0)),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildMidCallTelemetry(e),"media","mdsc_mid_call_telemetry"))}sendCallSetupTelemetry(){this.mediaSession&&(this.collectCallStats(this.mediaSession),this.reportCallSetupStats(),this.isCallSetupTelemetrySent=!0)}collectCallStats(e){const t=()=>this.collectMediaStatsDeferred.resolve();return e.getStatsAsync(!1).then((e=>this.callStats.setMediaStats(e))).then(t,t)}reportCallSetupStats(){this.collectMediaStatsDeferred.promise.then((()=>{this.reportTelemetryEvents(this.callStats.buildFromCallSetupStats(this.signalingSession.baseMessagingChannelUrl),"media","mdsc"),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new Kt}))}async reportCallEndStats(e){this.callTelemetry.setTerminationState(this.state),this.callTelemetry.setTerminationReason(this.terminatedReason),this.callStats.localStats.endCall(this.terminatedReason),e&&this.mediaAgent.getConfigProvider().config?.smallCallTelemetry?.enable&&this.reportSmallCallEvent(null),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.reportTsCallingTelemetry(!this._callIsSetupComplete),e&&(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 Kt}async reportVDITelemetryEvents(){this.vdi3diagnostics&&this.reportTelemetryEvents([{eventName:"vdi_webrtc_session",props:await this.callStats.buildVDItelemetryReport(this.vdi3diagnostics)}],"media","mdsc")}reportTelemetryEvents(e,t,i){const n=this.telemetryLoggers?this.telemetryLoggers[t]:null;n?e.forEach((e=>n.sendEvent({eventName:`${i?`${i}_`:""}${e.eventName}`,props:e.props}))):this.logger.debug(`reportTelemetryEvents no logger for tenant ${t}`)}onLocalPreviewSizeChanged(e,t){this.logger.debug(`onLocalPreviewSizeChanged: ${e}x${t}`)}onLocalPreviewStateChanged(e){this.logger.debug(`onLocalPreviewStateChanged: ${e}`),this.callStats.localStats.video.streamStateChanged(e.stream)}async configureVideoModalitiesAsync(e,t,i){if(!this.mediaSession)return this.logger.warn("Tried to configure modalities after call end"),Promise.resolve();e&&this._delayedElevationPending&&!this._delayedElevationQueued&&await this.triggerDelayedReconnectIfNeeded(t,"configureVideoModalitiesAsync"),await this.updateMediaModalities(void 0,t,i),e||this.turnOffLocalVideoPreview(t),this.setVideoOn(e,t)}turnOffLocalVideoPreview(e){return this.localVideoRenderer&&(this.localVideoRenderer.dispose(),this.localVideoRenderer=null),this.disposeLocalVideoHandle(),Promise.resolve(void 0)}turnOnLocalVideoPreview(e){return this.mediaSession?.getSessionConfig().config.useDeviceHandleForLocalVideo?this.acquireLocalVideo(e):(this.localVideoContainer||(this.localVideoContainer=document.createElement("div")),this.turnOnLocalVideoPreviewUsingRenderer(e))}acquireLocalVideo(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e);if(!this.mediaStateConfigurationHelper.isSending(1))return Promise.reject("could not start video preview, not configured to send");try{this.disposeLocalVideoHandle();const e=this.callDeviceManager.getDeviceManager(Jh(1));return this.localVideoHandle=e.createDevicesHandle({video:!0},"pluginlessCall:acquireLocalVideo()"),this.localVideoHandle.on("onStreamStateChanged",(e=>this.onLocalPreviewStateChanged({stream:e}))),this.localVideoHandle.acquire()}catch(e){return t.logFailure(e),void this.disposeLocalVideoHandle()}}turnOnLocalVideoPreviewUsingRenderer(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e),i=this.mediaStateConfigurationHelper.isSending(1);if(!i||!this.localVideoContainer)return Promise.reject(`could not start video preview: requestedVideoState=${i}, localVideoContainer=${this.localVideoContainer}`);this.turnOffLocalVideoPreview(e);const n=Wt((()=>{this.localVideoRenderer=this.callDeviceManager.getDeviceManager(Jh(1)).createPreviewRenderer(this.localVideoContainer,"Video"),this.localVideoRenderer.on("onVideoSizeChanged",((e,t)=>this.onLocalPreviewSizeChanged(e,t))),this.localVideoRenderer.on("onVideoStateChanged",(e=>this.onLocalPreviewStateChanged(e)))})).then((()=>this.localVideoRenderer.startVideoAsync(e)));return n.catch((e=>t.logFailure(e))),n}async startStopVideo(e,t,i){const n=this.logger.createFnLogger(e?"startVideo":"stopVideo",t);return n.info("start"),this.canToggleVideo?(e?(this.callStats.localStats.newSession(1),this.callStats.localStats.video.start()):this.callStats.localStats.video.stop(),e&&this.mediaStateConfigurationHelper.isDisabled(1)&&n.info("Video modality was skipped till now. Adding it now."),e?this.mediaStateConfigurationHelper.enableModality(1):this.mediaStateConfigurationHelper.removeModality(1),this.canToggleVideo=!1,this.videoTogglePromise=(async()=>{try{let n=!1;e&&(await this.turnOnLocalVideoPreview(t),n=!0),await this.configureVideoModalitiesAsync(n,t,i)}catch(e){throw n.logFailure(e),this.mediaStateConfigurationHelper.removeModality(1),await this.configureVideoModalitiesAsync(!1,t,i),e}finally{this.canToggleVideo=!0}})(),this.videoTogglePromise):e===this.mediaStateConfigurationHelper.isSending(1)?(await this.videoTogglePromise,void this.turnOnLocalVideoPreview(t)):(n.logFailure(`video switching is in progress ${e}]`),Promise.reject({reason:1}))}async startStopAudio(e,t){const i=this.logger.createFnLogger(e?"startAudio":"stopAudio",t);try{const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t)}catch(e){return i.logFailure(e),9}return 0}updateEndpointStateForMute(e,t){try{this.signalingSession.updateEndpointState({state:{isMuted:e}},t).catch((e=>{this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}))}catch(e){this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}}async handleServerMutedState(e){const t=this.logger.createFnLogger(`handleServerMutedState, isServerMuted=${!!this.isServerMuted}`,e);if(!this.isServerMuted){const i=3===this._muteState;if(1===this._muteState||i)try{t.info("is unmuting, as we are no longer server muted"),await this.handleMuteUnmuteOnMediaSession(!1,e),this.setMuted(0,e),this.unmutePendingPromise?.resolve(),i&&this.updateEndpointStateForMute(!1,e)}catch(e){throw t.logFailure(e),e}}if(this.isServerMuted&&0===this._muteState){t.info("is muting, as we are unmuted");try{await this.handleMuteUnmuteOnMediaSession(!0,e),this.setMuted(1,e)}catch(e){throw t.logFailure(e),e}}}async handleMuteUnmuteOnMediaSession(e,t){const i=this.logger.createFnLogger(`handleMuteUnmuteOnMediaSession, value=${!!e}`,t);if(this.mediaSession?.getAllowedModalities&&!this.isServerMuted){const n=this.isMuted||this.isServerMuted,r=this.mediaSession.getAllowedModalities().audio.some((e=>e===ug||e===gg));(n&&r||!n&&!r)&&(i.info(`updating audio modalities: Muted ${n} -> ${e}; audioAllowed = ${r}`),await this.updateMediaModalities(void 0,t))}return e?(i.info("mediaSession.muteInputAsync"),await(this.mediaSession?.muteInputAsync(t))):e||(i.info("mediaSession.unmuteInputAsync"),await(this.mediaSession?.unmuteInputAsync(t))),Promise.resolve()}canMuteOthers(){const e=this._enableUserMeetingRolesCheckForClientCapability&&this.meetingRoles?.some((e=>"attendee"===e))||"attendee"===(this.advancedMeetingRole||this.meetingRole),t=this._enableEndpointMeetingRoleCheckForClientCapability&&!!this.endpoints?.endpointDetails.find((e=>this._endpointId===e.endpointId))?.endpointMeetingRoles?.some((e=>"attendee"===e));return!e&&!t}updateCapabilities(e,t=!1){let i=!1,n=!1;fh(this.state,[11,12])||(this.isServerMuted&&!this._callInLobby?2&this._commandUrlPresence&&(i=!0):this.isMuted&&(i=!0),n=!!(1&this._commandUrlPresence)&&this.canMuteOthers()),this._capabilities.canUnmuteSelf===i&&this._capabilities.canMuteOthers===n||(this._capabilities.canUnmuteSelf=i,this._capabilities.canMuteOthers=n,this.logger.info(`[${e}][updateCapabilities] Computed self capabilities: ${JSON.stringify(this._capabilities)}`),t&&this.raiseChanged())}async evaluateEndpointStatesForAccept(e,t,i){const n=this.logger.createFnLogger(`evaluateEndpointStatesForAccept, isMuted=${!!e}`,i),r={};try{await this.handleMuteUnmuteOnMediaSession(e,i),Object.assign(r,{state:{isMuted:e}}),n.info("is updating endpointState for mute"),t&&(Object.assign(r,{endpointProperties:{additionalEndpointProperties:t}}),n.info("is updating endpointState for additionalEndpointProperties"))}catch(e){throw n.logFailure(e),ns(e)}return r}async handleEndpointStatesForAccept(e,t){const i=this.logger.createFnLogger("handleEndpointStatesForAccept",t);try{await this.signalingSession.updateEndpointState(e,t)}catch(e){throw i.logFailure(e),ns(e)}}async muteUnmute(e,t){const i=this.logger.createFnLogger(`muteUnmute, value=${!!e} isServerMuted=${this.isServerMuted} inLobby=${this._callInLobby}`,t);if(fh(this.state,[11,12]))return i.logFailure("Can not mute/unmute during preheat call"),Promise.reject(ns("TransactionDisallowed"));const n=!e&&(!this.isServerMuted||this._callInLobby);try{if((e||n)&&await this.handleMuteUnmuteOnMediaSession(e,t),e)this.setMuted(2,t),i.info("is updating endpointState for mute"),this.updateEndpointStateForMute(!0,t);else{if(!n)return i.info("is unmuting on server"),2===this._muteState&&this.setMuted(3,t),this.isCallModeStreaming()?this.promoteToRealtimeAndUnmute(t):this.signalingSession.unmuteAsync(t).then((e=>{this.handleSelfUnmuteUpdatedInfo(e,t)}));i.info("is updating endpointState for unmute"),this.setMuted(0,t),this.updateEndpointStateForMute(!1,t)}}catch(e){throw i.logFailure(e),ns(e)}}async muteUnmuteSpeaker(e,t){this.setSpeakerMuted(e,t),this.mediaSession&&(e?await this.mediaSession.muteOutputAsync(t):await this.mediaSession.unmuteOutputAsync(t))}getParticipant(e){return this.participants.filter((t=>t.isSameParticipantsMri(e)))[0]}getOrCreateParticipant(e,t,i){let n=this.getParticipant(e);return n||(n=new Ug(e,this.mediaSession,this.logger,this.callStats.localStats,this.callTelemetry,t),n.changed((()=>this.onParticipantChanged(n))),this.participants.push(n),i&&this.event("participantAdded").raise(n),this.monitorCallStart(),n)}onParticipantChanged(e){this.event("participantUpdated").raise(e),this.raiseChangedDeferred(this._participantChangedEventSkipConfig)}setCallState(e,t,i=0){if(this.state===e)return;const n=this.logger.createFnLogger("setCallState",t);n.info(`currentState=${this.state}, newState=${e}, terminatedReason=${this.terminatedReason}`),(Ch[this.state].indexOf(e)>=0||(n.logFailure("invalid state transition"),7===e))&&(this.callTelemetry.recordEvent("_SetCallState",{state:e,reason:i},t),this.state=e,this.callStats.localStats.call.callStateChanged(e),6===e&&this._startCallPhase&&(this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},t),this._startCallPhase=void 0),7===e&&this.setTerminatedReason(i),3===e&&(this.callGotConnected=!0,this.callHeldAt=null),this.callIsHeld()&&!this.callHeldAt&&(this.callHeldAt=new Date),n.logSuccess(`changed to ${e}, terminatedReason: ${this.terminatedReason}, failureType=${this.failureType}`),this.screenSharingControl.callStateChanged(this.state),this.monitorCallStart(),this.event("callStateChanged").raise(),this.updateCapabilities(t),this.raiseChanged(),this.callTelemetry.recordEvent("_RaiseCallStateChangeEvent",{state:e,reason:i},t))}setTerminatedReason(e){if(this.terminatedReason=e,!(0,Ws.includes)(kf,e)){const e=44===this.terminatedReason,t=55===this.terminatedReason,i=56===this.terminatedReason;this.setFailureType(!this.callGotConnected||!this._wasAudioStreamConnected||e||t||i?0:1)}}setMediaStream(e,t,i){if(e){if(!(0,Ws.find)(this.localMediaStreams,(e=>e.mediaType===i))){const e=new Nf(t,i);this.logger.info(`setMediaStream ${JSON.stringify(e)}`),this.localMediaStreams.push(e)}}else this.logger.info(`setMediaStream removing ${i}`),(0,Ws.remove)(this.localMediaStreams,(e=>e.mediaType===i))}setVideoOn(e,t){this.logger.info(`[${t}]videoOn=${e}`),this.isVideoOn=e,this.setMediaStream(this.isVideoOn,!0,1),this.callTelemetry.recordEvent("_SetLocalVideo",{value:e},t),this.raiseChanged()}setAudioOn(e,t){this.logger.info(`[${t}]audioOn=${e}`),this.setMediaStream(e,!0,0),this.callTelemetry.recordEvent("_SetLocalAudio",{value:e},t)}setScreenSharingOn(e,t){this.logger.info(`[${t}]screenSharingOn=${e}`),this.isScreenSharingOn=e,this.setMediaStream(this.isScreenSharingOn,this.isScreenSharingOn,2),this.callTelemetry.recordEvent("_SetScreenSharing",{screenSharingOn:e},t),this.event("userActivityChanged").raise(),this.raiseChanged()}disposeSharingScreenHandle(){this.sharedScreenHandle&&(this.sharedScreenHandle.dispose(),this.sharedScreenHandle=null)}disposeLocalVideoHandle(){this.localVideoHandle?.dispose(),this.localVideoHandle=null}setMuted(e,t){this._muteState!==e&&(this._muteState=e,this.callTelemetry.recordEvent("_SetMuted",{isMuted:e},t),this.logger.info(`[${t}]participantMuteState:${e}, isMuted: ${this.isMuted}`),this.updateCapabilities(t),this.raiseChanged(),this.event("muteStateChanged").raise(this.isMuted,t))}setSpeakerMuted(e,t){this.logger.info(`[${t}]speakerMute=${e}]`),this.isSpeakerMuted=e,this.raiseChanged()}monitorCallStart(){3!==this.state||!this.participants.length&&2!==this.callMode||this.callStartedAt||(this.callStartedAt=new Date)}_removeParticipant(e,t,i=0){const n=this.logger.createFnLogger("removeParticipant",t);n.info(`mri=${rg(e)}`);const r=(0,Ws.remove)(this.participants,(t=>t.isSameParticipantsMri(e.id)))[0];r?(r.setState(4,i,t),this.event("participantRemoved").raise(r)):n.logFailure(`unable to remove participant ${De(e.id)}`),this.raiseChanged(this._participantChangedEventSkipConfig)}setIsSomeoneSharing(e,t){const i=this.isSomeoneSharing!==e&&!(e&&this.screenSharingRenegotiationDeferred&&this.callUsesMixer);i&&(this.isSomeoneSharing=e);let n=i;if(this.callUsesMixer&&this.mediaSession?.getSessionConfig().config.enableStopSharingWithIncomingOffer&&(n||(n=t)),!this.isMultiVBSSEnabled()&&n&&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 e=this.localSignalingParticipant.endpointDetails.find((e=>this._endpointId===e.endpointId)),t=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,t,e)}}handleOfferedModalities(e,t){const i=this.mediaAgent.constants.MEDIA_STATE,n=this.logger.createFnLogger("handleOfferedModalities",t);try{n.info(`offeredModalities=${Ge(e)}`)}catch(e){n.logFailure(e)}e.hasOwnProperty("video")||this.mediaStateConfigurationHelper.isSending(1)?e.hasOwnProperty("video")&&!this.mediaStateConfigurationHelper.isSending(1)&&this.mediaStateConfigurationHelper.removeModality(1):this.mediaStateConfigurationHelper.disableModality(1),e.hasOwnProperty("sharing")||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.disableModality(2),e.sharing!==i.receive||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.removeModality(2),e.data===i.sendReceive&&this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.isReivitelessEnabled()||(this.setIsSomeoneSharing(e.sharing===i.receive,!0),this.setIsSomeoneStreamingVideo(e.video===i.receive||e.video===i.sendReceive))}getRenegotiationOfferType(e){if(e)if(5===this.state){if("sendrecv"===e.audio)return 2}else if(this.modalitiesAreHold(e))return 1;return 0}isRenegotiationHoldOrResume(e){return 1===this.getRenegotiationOfferType(e)||2===this.getRenegotiationOfferType(e)}isReivitelessEnabled(){return(this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()>0||this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb()>0)&&this.callUsesMixer}isValidHoldResumeCallState(e){return[3,5,10,13].includes(e)}onNegotiationCompletion(e,t,i={},n,r){const s=this.logger.createFnLogger("onNegotiationCompletion",n);s.info(`byLocal=${t}, result=${Ge(e)}`),this.callTelemetry.recordEvent("NegotiationCompletion",{phaseTelemetryBag:r,...this.prepareNegotiationResultForTelemtry(e)},n);const a=this.isOneToOneCall();if(a&&!this.callUsesMixer){const t=this.modalitiesAreHold(e.activeModalities)?5:3;this.participants[0].setState(t,void 0,n),s.info(`isOneToOneCall: participant[0] state set to ${t}`)}const o=this.modalitiesAreHold(e.configuredModalities),l=this.modalitiesAreHold(e.activeModalities);let c;const d=this.signalingSession.participantManager.localParticipant.isStaging;s.info(`isStaging= ${d}`),this.requestedHoldState?(o&&l||s.info(`Not expected modalities when processing local hold: ${o} ${l}`),4!==this.state&&s.info(`Not expected state when processing local hold: ${this.state}, switching back to LocalHold`)):t||this.callHoldResumeDeferred?!o&&l?c=5:o||l||this._callInLobby||this.isPreheatedOnly()||(c=d?13:3):4===this.state||this._callInLobby||this.isPreheatedOnly()||(c=a&&5===this.participants[0].state?5:d?13:3),c&&this.setCallState(c,n),this.callHoldResumeDeferred&&(s.info(`isHoldInProgress=${this.isHoldInProgress}, state=${this.state}, completed=${l}`),this.isHoldInProgress?l&&this.finishCallHoldResume():this.inLocalHold()||this.finishCallHoldResume(this.isValidHoldResumeCallState(c)?void 0:new Error(`Call state changed to ${c} instead of Connected, Lobby, Staging or RemoteHold`))),this.requestedHoldState||(this.setIsSomeoneSharing((0,Ws.some)(this.participants,(e=>(0,Ws.some)(e.streams[1],(e=>e.isAvailable))))),this.setIsSomeoneStreamingVideo((0,Ws.some)(this.participants,(e=>(0,Ws.some)(e.streams[0],(e=>e.isAvailable))))));const u=i&&i.sharing===this.mediaAgent.constants.MEDIA_STATE.send,h=e?.activeModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(this.resolveScreenSharingRenegotiation(n,u,h,e.isComplete),this.retryOutgoingRenegotiation.retry){const e=this.retryOutgoingRenegotiation.causeId;this._callOperationHandler.executeChained((()=>this.updateMediaModalities(void 0,e)),"_Renegotiate",e,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.retryOutgoingRenegotiation.retry=!1}}onUpdateMediaDescriptionsFailure(e,t,i){const n=t?.requestedModalities.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.screenSharingRenegotiationDeferred&&n&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}onUpdateMediaDescriptionsCompletion(e,t){this.logger.createFnLogger("onUpdateMediaDescriptionsCompletion",t).info(`result=${Ge(e)}`),this.callTelemetry.recordEvent("UpdateMediaDescriptionsCompletion",e,t);const i=e?.requestedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send,n=e?.appliedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.resolveScreenSharingRenegotiation(t,i,n,!0)}resolveScreenSharingRenegotiation(e,t,i,n){const r=this.logger.createFnLogger("resolveScreenShareRenegotiation",e);if(r.info(`invoked with wasSharingOfferred: ${t}, isSharingActive: ${i}, isComplete: ${n}`),this.screenSharingRenegotiationDeferred)if(t&&i)r.info("resolving screenSharingRenegotiationDeferred"),this.screenSharingRenegotiationDeferred.resolve(),this.screenSharingRenegotiationDeferred=null;else if(this._enableResolveScreenSharingWhenNegotiationComplete&&n&&!this.retryOutgoingRenegotiation.retry&&this.canToggleScreenSharing){const e=new Error(`screenSharing error: wasSharingOfferred: ${t}, isSharingActive: ${i}`);r.info(`reject screenSharingRenegotiationDeferred ${e}`),this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null}}async updateMediaStatus(e){if(this.calculateIsSomeoneStreaming(e),this.mediaSession){const t=await this.updateMediaModalities(void 0,e);this.callTelemetry.updateOperationData("_UpdateLocalMediaStatus",t,e)}}calculateIsSomeoneStreaming(e){let t=!1,i=!1;for(const e of this.participants)if(t||(t=(0,Ws.some)(e.streams[1],(e=>e.isAvailable))),i||(i=(0,Ws.some)(e.streams[0],(e=>e.isAvailable))),t&&i)break;this._delayedElevationPending&&(t||i)&&this.triggerDelayedReconnectIfNeeded(e,"roster update"),this.setIsSomeoneSharing(t),this.setIsSomeoneStreamingVideo(i)}async triggerDelayedReconnectIfNeeded(e,t=""){this.logger.info(`Delayed elevation (${t}): 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(e,!0,(()=>{this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.mediaSession?.getDiagnostics()?.registerElevation("completed")}))):this.logger.info(`Delayed elevation: was not queued, pending=${this._delayedElevationPending} isQueued=${this._delayedElevationQueued}`)}onNegotiationFailure(e,t,i,n){const r=n&&n.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(t===this.mediaAgent.constants.RENEGOTIATION_ERROR.glare)return this.screenSharingRenegotiationDeferred&&r&&this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),void(this.retryOutgoingRenegotiation={retry:!0,causeId:i});this.finishCallHoldResume(e),this.screenSharingRenegotiationDeferred&&r&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}static getParticipantReasonFromTerminatedReason(e){switch(e){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(e){if(!e.endpointDetails)return!1;for(const t of e.endpointDetails)if(!Fd(t))return!1;return!0}updateCallParticipantFromSignalingParticipant(t,i,n){if((0,Ws.every)(i.endpointDetails,(e=>e?.isLobby||e?.streamLobby)))return void t.setState(7,void 0,n);const r=(0,Ws.some)(i.endpointDetails,(e=>e?.streamInformation)),s=i.endpointDetails&&(0,Ws.some)(i.endpointDetails,(e=>e.mappedTo)),a=e.filterVirtualEndpoints(i.endpointDetails),o=a&&a[0].mediaStreams,l=this.isRemoteParticipantInStaging(i);if(o&&o.length>0){const e=o.every((e=>"inactive"===e.direction));let i=e?5:l?8:3;1!==this.state||e||this.callUsesMixer||(i=2),this.logger.info(`[updateCallParticipantFromSignalingParticipant]: with mediaStreams is not empty, ParticipantState is set to ${i}`),t.setState(i,void 0,n)}else if(o||s||r){const e=l?8:3;this.logger.info(`[updateCallParticipantFromSignalingParticipant]: ParticipantState is set to ${e}, mediaStreams=${!!o}, hasMappedEndpoints=${s}, hasPlayerStreams=${r}`),t.setState(e,void 0,n)}}handleSelfServerMutedState(t){const i=e.filterVirtualEndpoints(this.localSignalingParticipant.endpointDetails),n=(0,Ws.find)(i,(e=>this._endpointId===e.endpointId)),r=n&&n.mediaStreams,s=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),a=n&&(n.stream||n.streamLobby);if(a){const e=a.serverMuted??!1;n.serverMuteVersion=0,e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.isServerMuted&&this.setMuted(1,t))}else if(s&&s.length>0){const e=s.some((e=>e.serverMuted));e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.handleServerMutedState(t))}}checkIfIncomingServerMutedIsUpdated(e){const t=(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===t)return;const i=(0,Ws.find)(e.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));eg(this.logger,t,i)}convertWiredPublishedState(e){if(!e)return;const t=uo(e.stateType);return{content:e.content,stateType:t,typeRank:e.typeRank,stateId:e.stateId}}updatePublishedStateModified(e,t){e!==this.currentUserSkypeIdentity.id||t&&t!==this.participantId?this._publishedStatesModified=2|this._publishedStatesModified:this._publishedStatesModified=1|this._publishedStatesModified}updatePublishedStates(e){try{let t=[];(0,Ws.forEach)(e.publishedStates,(e=>{t.push(this.convertWiredPublishedState(e))})),(0,Ws.isEqual)(this._participantPublishedStatesMap[e.id],t)||(0!==t.length||void 0!==this._participantPublishedStatesMap[e.id]&&null!==this._participantPublishedStatesMap[e.id])&&(this._participantPublishedStatesMap[e.id]=t,this.updatePublishedStateModified(e.id));const i=[];(0,Ws.forEach)(e.endpointDetails,(n=>{i.push(n.participantId),t=[],(0,Ws.forEach)(n.publishedStates,(i=>{const r=this.convertWiredPublishedState(i);if(this._endpointPublishedStatesMap[e.id]||(this._endpointPublishedStatesMap[e.id]={},this._endpointPublishedStatesMap[e.id][n.participantId]=[]),"clientMediaUfd"===r.stateType)try{const e=JSON.parse(JSON.stringify(r.content));this.mediaSession.registerRemoteQualityStateChangedEvent(e,n.participantId)}catch(e){this.logger.error(`Error while parsing state.content for ClientMediaUFD: ${e}`)}t.push(r)})),this._endpointPublishedStatesMap[e.id]&&!(0,Ws.isEqual)(this._endpointPublishedStatesMap[e.id][n.participantId],t)&&(0!==t.length||null!==this._endpointPublishedStatesMap[e.id][n.participantId]&&void 0!==this._endpointPublishedStatesMap[e.id][n.participantId])&&(this._endpointPublishedStatesMap[e.id][n.participantId]=t,this.updatePublishedStateModified(e.id,n.participantId))})),this._endpointPublishedStatesMap[e.id]&&Object.keys(this._endpointPublishedStatesMap[e.id]).forEach((t=>{i.some((e=>e===t))||(delete this._endpointPublishedStatesMap[e.id][t],this.updatePublishedStateModified(e.id,t))}))}catch(e){this.logger.error(`updatePublishedStates ${JSON.stringify(e)}`)}this.logger.info(`updatePublishedStates ${Ne(this._participantPublishedStatesMap)}`),this.logger.info(`updatePublishedStates ${Ne(this._endpointPublishedStatesMap)}`)}removePublishedStatesByParticipant(e){this._endpointPublishedStatesMap[e]&&delete this._endpointPublishedStatesMap[e],this._participantPublishedStatesMap[e]&&delete this._participantPublishedStatesMap[e],this.updatePublishedStateModified(e)}findOrCreateTypeState(e){let t=this._publishedStates.typeStates.findIndex((t=>t.type===e));if(-1===t){const i={participantStates:[],type:e};this._publishedStates.typeStates.push(i),t=this._publishedStates.typeStates.length-1}return t}processPublishedStates(){this.logger.info(`processPublishedStates ${Ne(this._participantPublishedStatesMap)}`),this.logger.info(`processPublishedStates ${Ne(this._endpointPublishedStatesMap)}`);try{this._publishedStates||(this._publishedStates={typeStates:[]}),this._publishedStates.typeStates=[];for(const e of Object.keys(this._participantPublishedStatesMap)){const t=this._participantPublishedStatesMap[e];(0,Ws.forEach)(t,(t=>{const i=this.findOrCreateTypeState(t.stateType),n={id:e,publishedState:{content:t.content,stateId:t.stateId,typeRank:t.typeRank}};this._publishedStates.typeStates[i].participantStates.push(n)}))}for(const e of Object.keys(this._endpointPublishedStatesMap))for(const t of Object.keys(this._endpointPublishedStatesMap[e]))this._endpointPublishedStatesMap[e][t].forEach((i=>{const n=this.findOrCreateTypeState(i.stateType),r={id:t,publishedState:{content:i.content,stateId:i.stateId,typeRank:i.typeRank}},s={id:e,endpoints:[r]},a=this._publishedStates.typeStates[n].participantStates.filter((t=>t.id===e));a&&a.length>0?(a[0].endpoints||(a[0].endpoints=[]),a[0].endpoints.push(r)):this._publishedStates.typeStates[n].participantStates.push(s)}));this.event("publishedStatesChanged").raise(this._publishedStates),this.raiseChanged()}catch(e){this.logger.error(`processPublishedStates ${e}}`)}}updateLocalParticipant(t,i){const n=this.logger.createFnLogger("updateLocalParticipant",i);this.checkIfIncomingServerMutedIsUpdated(t),this.localSignalingParticipant.endpointDetails=t.endpointDetails,this.localSignalingParticipant.role=t.role,this.setMeetingRole(t.meetingRole),this.setAdvancedMeetingRole(t.advancedMeetingRole),this.setMeetingRoles(t.meetingRoles),this.setParticipantType(t.participantType),this.setDisplayName(t.displayName),this.setPropertyBag(t.propertyBag),this.setPropertyRosterVersion(t.version),this.setMaskedIdentityDetails(t.isIdentityMasked,t.maskedIdSeqNumber,t.maskedId),this.setOtpIdentity(t.otpIdentity),this.localSignalingParticipant.tenantId=t.tenantId,this.localSignalingParticipant.isLobby=t.isLobby,t.joinAsStreamingUser&&(this.localSignalingParticipant.joinAsStreamingUser=t.joinAsStreamingUser,this.setJoinAsStreamingUser(t.joinAsStreamingUser)),void 0!==t.enableCaptcha&&this.setEnableCaptcha(t.enableCaptcha),this.callTelemetry.setTenantId(t.tenantId),this.callStats.setTenantId(t.tenantId);const r=this.localSignalingParticipant.isLobby;t.endpointDetails&&this.updateLocalParticipantEndpoints(t.endpointDetails),this.updatePublishedStates(t),this.handleSelfServerMutedState(i);const s=this.getLocalSignalingEndpointDetails();this._callInLobby=r||!!s?.streamLobby,this.signalingSession.participantManager.localParticipant.isStaging=t.isStaging;const a=this.signalingSession.participantManager.localParticipant.isStaging;n.info(`callInLobby = ${r}, callSetupComplete = ${this._callIsSetupComplete}, callIsHeld = ${this.callIsHeld()}, isStaging = ${a}`),!this._callIsSetupComplete||this.callIsHeld()||fh(this.state,[11,12])||(r?this.setCallState(10,i):a&&fh(this.state,[3,13,10,9,2])?this.setCallState(13,i):this.setCallState(3,i));const o=e.getStreamsFromEndpoints(t.endpointDetails,this.isMultiVBSSEnabled());if(this.callTelemetry.recordEvent("_UpdateLocalParticipantStream",function(e){let t=[];return e.forEach((e=>{try{let i=t.find((t=>t.participantId===e.participantId&&t.endpointId===e.endpointId));i||(i={participantId:e.participantId,endpointId:e.endpointId},t.push(i)),"audio"!==e.type&&"audioteleconference"!==e.type||(i.serverMuted=e.serverMuted),i[e.type]=e.direction}catch(e){t=[]}})),t}(o),i),this.streamManager.updateStreams(o,i),this.updateCapabilities(i,!0),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const e=t.endpointDetails.find((e=>this._endpointId===e.endpointId)),i=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,i,e)}}modalitiesAreHold(e){return!(e.audio&&"inactive"!==e.audio||e.video&&"inactive"!==e.video||e.sharing&&"inactive"!==e.sharing)}toneToString(e){switch(e){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(e){switch(e){case"started":return 0;case"active":return 2;case"inactive":return 1;case"stopped":return 3;default:return 4}}static streamingDirectionToMediaDirectionMapping(e){switch(e){case"send":return 1;case"receive":return 0;default:return}}static convertMuteScope(e){switch(e){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(e){const t={};return e.muteFlags&&(t.muteMicrophone=!!(1&e.muteFlags),t.muteSpeaker=!!(2&e.muteFlags)),Object.keys(t).length?t:void 0}reconnect(){const e=be();return this.mediaSession.reconnectAsync(e)}async provideCallQualityFeedback(e,t,i,n){}async showCQFInfo(e,t){throw new Error("Not implemented")}async isCqfRendered(e){}async provideCallQualityFeedbackEx(e,t,i,n,r,s){}testTriggerMediaRelayWhiteListingIssue(){this.logger.info("Simulating media relay whitelisting issue for test purposes");const e=this.mediaSession.mediaSession.callback;e.onQualityChanged({type:"NetworkRelaysNotReachable",value:"Bad",isLocalSource:!0,mediaType:"Audio"}),e.onAudioStateChanged({direction:"send",stream:"failed",content:"audio"})}async getMediaTelemetry(e=!1){return this.mediaSession&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(e)),this.appendInfoToCallStats()),this.callStats.buildMediaTelemetry()}getMediaSessionStats(){return this.mediaSession?.getMediaStatsReport()}async getMediaSessionStatsAsync(){return this.mediaSession?.getMediaStatsReport()}async getAudioSendStats(){return this.mediaSession?.getAudioSenderStats()}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(e){this.logger.info(`Overwriting call state for test purposes: ${this.state} -> ${e} `),this.state=e}testSetCallType(e){this.logger.info(`Overwriting call state for test purposes: ${this.callType} -> ${e} `),this.callType=e}addGroupModality(e,t=be()){const i=this.logger.createFnLogger("AddGroupModality",t);if(!e.threadId&&!e.groupId)return Promise.reject(ns("No threadId/groupId was provided."));if(6===this.state||7===this.state)return i.info(`Not adding modality because CallState is ${this.state} groupId=${De(e.groupId)}, threadId = ${xe(e.threadId)} messageId = ${e.messageId}`),Promise.reject(ns("TransactionDisallowed"));let n;if(e.additionalData)try{n=JSON.stringify(e.additionalData)}catch(t){i.logFailure(`additionalData: ${e.additionalData} is not valid Json, error: ${t}`);const n={code:ps,subCode:0,phrase:`additionalData is not valid Json, error: ${t}`};return Promise.reject(n)}if(i.info(`groupId=${De(e.groupId)}, threadId = ${xe(e.threadId)} messageId = ${e.messageId} additionalData = ${De(n)}`),this._enableAddModalityGeneric){const n={groupContext:{id:e.groupId},groupChat:{threadId:e.threadId,messageId:e.messageId}};return this.signalingSession.addModalityAsync(n,t).catch((e=>(i.logFailure(je(e)),Promise.reject(e))))}{const r={groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,additionalData:n};return this.signalingSession.addGroupModalityAsync(r,t).catch((e=>(i.logFailure(je(e)),Promise.reject(e))))}}addBroadcastModality(e,t){const i=this.logger.createFnLogger("AddBroadcastModality",t);return Promise.resolve().then((()=>{this.signalingSession.addBroadcastModalityAsync(e,t)})).catch((e=>(i.logFailure(je(e)),Promise.reject(ns(e))))).then((()=>this._callOperationHandler.waitForOperation("AddBroadcastModality"))).catch((e=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:$e(e)},t),i.logFailure(e),e}))}static convertQualityEventType(e){switch(e){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(e){switch(e){case"Unknown":return 0;case"Good":return 1;case"Poor":return 2;case"Bad":return 3;default:return}}static convertMediaType(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2;case"Data":return 3;default:return}}getPluginlessPublishLevel(e){switch(e){case"user":return"user";case"endpoint":return"endpoint";default:throw"Invalid level type."}}setIsEmergency(e){this.logger.info(`Set isEmergency:${e}`),this.isEmergency=e,this.callTelemetry.setIsEmergency(e)}static filterVirtualEndpoints(e){return e&&(0,Ws.filter)(e,(e=>!e.mappedTo))}mapDataChannelSourceIdToParticipant(e){let t=null;return t=1===this.callType?this.participants[0]:(0,Ws.find)(this.participants,(t=>t.hasSourceId(3,e))),t?.id?this.logger.info(`ParticipantId: ${De(t.id)} to SourceId: ${e}`):this.logger.warn(`No Participant found for SourceId: ${e}`),t}getDataChannelSourceId(){const e=(0,Ws.find)(this.endpoints.endpointDetails,(e=>null!==e&&e.participantId===this._participantId));if(!e)return this.logger.warn(`No participantLeg found for participantId: ${this._participantId}`),-1;if(!e.mediaStreams)return this.logger.warn(`ParticipantLeg ${this._participantId} does not have valid mediaStreams`),-1;const t=(0,Ws.find)(e.mediaStreams,(e=>3===Nd(e.type)));return t?t.sourceId:(this.logger.warn(`participantLeg ${this._participantId} has no data channel`),-1)}initializeLiveStreamConfigProvider(){const e="MDN_MIDDLELANE_TEAMS",t=this.ecsProvider.getEcsConfig(e,"liveStream"),i=this.ecsProvider.getEcsConfig("ConfigIDs",e);this._liveStreamConfigProvider=new Ut(t,null,i,this.logger.createChild("LiveStreamConfigProvider"))}isMediaSending(e){return this.mediaStateConfigurationHelper.isSending(e)}async setAudioStreamConnectedAsync(e){this.isAudioStreamConnected=e}async setSpamRiskLevelAsync(e){this.spamRiskLevel=e}async setSpamStirAttestationAsync(e){this.spamStirAttestation=e}async setDominantSpeakerInfoAsync(e){this.dominantSpeakerInfo=e}async setSlowedDownActiveTalkerInfoAsync(e){this.slowedDownActiveTalkerInfo=e}};Lf.instanceCount=0,Lf.getNegotiationTagsFromEndpoints=e=>{if(!e)return;const t=new Map;return Lf.filterVirtualEndpoints(e).forEach((e=>{t.set(e.endpointId,e.negotiationTag)})),t},m([Gr("SetMeetingLayout"),f(0,Wr)],Lf.prototype,"setMeetingLayout",1),m([Gr("Initialize",{type:"Sync",convertError:!0,idempotencyLevel:"NoOp"})],Lf.prototype,"init",1),m([Gr("StartVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startVideo",1),m([Gr("StopVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopVideo",1),m([Gr("DumpVideoSourceImages")],Lf.prototype,"dumpVideoSourceImages",1),m([f(1,Wr)],Lf.prototype,"hold",1),m([Gr("Hold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"holdWithRenegotiate",1),m([Gr("LocalHold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"localHold",1),m([Gr("Unhold",{waitFor:["Hold","LocalHold"],preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"unhold",1),m([Gr("UpdateEndpointMetadata"),f(1,Wr)],Lf.prototype,"updateEndpointMetadata",1),m([Gr("SendDtmfTone",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"sendDtmfTone",1),m([Gr("SetAudioUsage")],Lf.prototype,"setAudioUsageMode",1),m([Gr("SetAudioMidcallConfig")],Lf.prototype,"setAudioMidcallConfig",1),m([Gr("SetAudioMidcallConfigJon",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setAudioMidcallConfigJson",1),m([Gr("SetParticipantSpatialAudioPositions",{waitFor:"_ElectronSlimcoreReady",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setParticipantSpatialAudioPositions",1),m([Gr("BlindTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callBlindTransfer",1),m([Gr("SafeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callSafeTransfer",1),m([Gr("TransferToVoicemail",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"transferCallToVoicemail",1),m([Gr("ConsultativeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callConsultativeTransfer",1),m([Gr("ConsultativeTransferWithPickupCode",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"consultativeTransferWithPickupCode",1),m([Gr("CallRedirect",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callRedirect",1),m([Gr("ParkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"park",1),m([Gr("UnparkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"unpark",1),m([Gr("getTechnicalInformationJson",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"getTechnicalInformationJson",1),m([Gr("StartScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(3,Wr)],Lf.prototype,"startScreenSharing",1),m([Gr("StopScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Wr)],Lf.prototype,"stopScreenSharing",1),m([Gr("StartDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startDataChannel",1),m([Gr("StopDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopDataChannel",1),m([Gr("ShareSystemSounds",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"shareSystemSound",1),m([Gr("Mute",{waitFor:"JoinPreheatedCall",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Yr),f(0,Wr)],Lf.prototype,"mute",1),m([Gr("Unmute",{waitFor:["JoinPreheatedCall"]}),f(0,Yr),f(0,Wr)],Lf.prototype,"unmute",1),m([Gr("MuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"muteSpeaker",1),m([Gr("UnmuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"unmuteSpeaker",1),m([Gr("GetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"getSpeakerVolume",1),m([Gr("SetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setSpeakerVolume",1),m([Gr("MuteParticipants",void 0),f(2,Yr),f(2,Wr)],Lf.prototype,"muteParticipants",1),m([Gr("StartAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startAudio",1),m([Gr("StopAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopAudio",1),m([Gr("Assimilate"),f(3,Wr)],Lf.prototype,"assimilate",1),m([f(2,Wr)],Lf.prototype,"merge",1),m([Gr("MergeParticipants"),f(1,zr),f(3,Wr)],Lf.prototype,"mergeParticipants",1),m([Gr("MergeWithPickupCode"),f(0,zr),f(2,Wr)],Lf.prototype,"mergeWithPickupCode",1),m([Gr("SetMaxVideoChannels")],Lf.prototype,"setMaxVideoChannels",1),m([Gr("SetMaxVbssChannels")],Lf.prototype,"setMaxVbssChannels",1),m([Gr("StopCall"),f(1,Wr),f(3,Jr)],Lf.prototype,"stop",1),m([Gr("PublishState"),f(1,zr)],Lf.prototype,"publishState",1),m([Gr("PublishState"),f(1,zr)],Lf.prototype,"publishStatesForEveryone",1),m([Gr("RemoveState"),f(1,zr)],Lf.prototype,"removeState",1),m([Gr("RemoveState"),f(1,zr)],Lf.prototype,"removeStatesForEveryone",1),m([Gr("UpdateMeetingSettings"),f(1,zr)],Lf.prototype,"updateMeetingSettings",1),m([Gr("UpdateMeetingGroups"),f(0,zr)],Lf.prototype,"updateMeetingGroups",1),m([Gr("UpdateMeetingLiveState"),f(0,zr)],Lf.prototype,"updateMeetingLiveState",1),m([Gr("UpdateMeetingStates"),f(1,zr)],Lf.prototype,"updateMeetingStates",1),m([Gr("UpdateParticipantInterpretationState"),f(0,zr)],Lf.prototype,"updateParticipantInterpretationState",1),m([Gr("UpdateParticipantsProperties")],Lf.prototype,"updateParticipantsProperties",1),m([Gr("JoinMeetingGroup"),f(0,zr)],Lf.prototype,"joinMeetingGroup",1),m([Gr("LeaveMeetingGroup"),f(0,zr)],Lf.prototype,"leaveMeetingGroup",1),m([Gr("SendMessages"),f(0,zr)],Lf.prototype,"sendMessages",1),m([Gr("UpdateMonitorSession"),f(1,Wr)],Lf.prototype,"updateMonitorSession",1),m([Gr("SwitchInterpreterGroup")],Lf.prototype,"switchInterpreterGroup",1),m([Gr("SetLiveInterpretationAttributes")],Lf.prototype,"setLiveInterpretationAttributes",1),m([Gr("UpdateMeetingRole")],Lf.prototype,"updateMeetingRoles",1),m([Gr("CreateContentSharingSession"),f(4,Wr)],Lf.prototype,"createContentSharingSession",1),m([Gr("StopCallWithBeacon",{type:"Sync"}),f(0,Wr)],Lf.prototype,"stopWithBeacon",1),m([Gr("Acknowledge",{type:"Chained",convertError:!0,idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Wr)],Lf.prototype,"acknowledge",1),m([Gr("Accept",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"accept",1),m([Gr("Reject",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr),f(1,Jr)],Lf.prototype,"reject",1),m([Gr("JoinCall",{type:"Chained",idempotencyLevel:"Error"}),f(1,Kr),f(2,Wr)],Lf.prototype,"join",1),m([Gr("JoinPreheatedCall",{waitFor:"_CallStartOrJoinInitiated"})],Lf.prototype,"joinPreheatedCall",1),m([Gr("StartCall",{type:"Chained",idempotencyLevel:"Error"}),f(0,Kr),f(1,Wr)],Lf.prototype,"start",1),m([Gr("StartCallToVoiceMail",{type:"Chained",idempotencyLevel:"Error"}),f(1,Wr)],Lf.prototype,"startCallToVoicemail",1),m([Gr("Subscribe",{type:"Chained",idempotencyLevel:"Error"}),f(2,Wr)],Lf.prototype,"joinCallWithoutCallModality",1),m([Gr("StartWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"startWithMeetingData",1),m([Gr("JoinWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"joinWithMeetingData",1),m([Gr("SubscribeWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"subscribeWithMeetingData",1),m([Gr("StartCallWithNudge",{type:"Chained",idempotencyLevel:"Error"}),f(1,Kr),f(2,Wr)],Lf.prototype,"startCallWithNudge",1),m([Gr("StartCallAndUnpark",{type:"Chained",idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Kr),f(3,Wr)],Lf.prototype,"startAndUnpark",1),m([qr("AdmitParticipant"),f(0,zr),f(1,Wr)],Lf.prototype,"admitParticipant",1),m([Gr("Admit")],Lf.prototype,"admit",1),m([qr("CallMeBack"),f(0,zr),f(2,Wr)],Lf.prototype,"callMeBack",1),m([f(0,zr),f(2,Wr)],Lf.prototype,"addParticipant",1),m([qr("AddParticipants"),f(0,zr),f(2,Wr)],Lf.prototype,"addParticipants",1),m([f(0,zr),f(2,Wr)],Lf.prototype,"addParticipantsImpl",1),m([qr("NudgeParticipants"),f(0,zr),f(3,Wr)],Lf.prototype,"nudgeParticipants",1),m([qr("RemoveParticipant"),f(0,zr),f(1,Wr)],Lf.prototype,"removeParticipant",1),m([qr("CancelNudge"),f(0,zr),f(0,Wr)],Lf.prototype,"cancelNudge",1),m([Gr("SearchParticipants"),f(1,zr),f(1,Wr)],Lf.prototype,"searchParticipants",1),m([Gr("GetAllParticipants"),f(1,zr),f(1,Wr)],Lf.prototype,"getAllParticipants",1),m([Gr("_PromotionToRealtime"),f(1,Wr)],Lf.prototype,"promoteToRealtime",1),m([f(0,Wr)],Lf.prototype,"turnOffLocalVideoPreview",1),m([Gr("_StartPreviewVideo"),f(0,Wr)],Lf.prototype,"turnOnLocalVideoPreview",1),m([f(0,Wr)],Lf.prototype,"acquireLocalVideo",1),m([f(0,Wr)],Lf.prototype,"turnOnLocalVideoPreviewUsingRenderer",1),m([Gr("_UpdateLocalMediaStatus",{type:"Chained"}),f(0,Wr)],Lf.prototype,"updateMediaStatus",1),m([f(0,Wr)],Lf.prototype,"calculateIsSomeoneStreaming",1),m([Gr("_Reconnect")],Lf.prototype,"reconnect",1),m([Gr("AddGroupModality"),f(1,Wr)],Lf.prototype,"addGroupModality",1),m([Gr("AddBroadcastModality")],Lf.prototype,"addBroadcastModality",1);var xf=Lf,Ff=p(ce()),Uf=new RegExp("/callAgent/","i"),Bf=class{constructor(e,t){this.signalingAgentProvider=e,this.callRegistry=t}handleMessage(e){if(!e.eventId){if(e.url.search(Uf)>-1){const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}if(e.eventId in Hs){this.callRegistry.logUploadNotification(e);const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}},Vf=class{constructor(e,t,i){this.callRegistry=e,this.recentInvitations=[],this.logger=t.createChild("IncomingCallMessageHandler"),this.ecsProvider=i}handleMessage(e){const t=this.handleIncomingCall(e);return t?{isHandled:t,resultCode:200}:{isHandled:t}}handleIncomingCall(e){const t=be(),i=this.logger.createFnLogger("handleIncomingCall",t);if(this.isProxiableNotification(e))return this.callRegistry.proxyPushNotification(e),!0;if(!this.isIncomingCallMessage(e))return!1;let n;this.callRegistry.pushHandlingStarted(t);try{if(e?.body?.gp&&!Xe(e.body.gp))i.info("unencoded payload, skipping decoding."),n=e.body.gp;else{const t=$f(e,i);n=JSON.parse(t)}n.body=e.body}catch(e){return this.callRegistry.pushHandlingEnded(t,{result:"Failed to parse incoming call notification payload",code:ps,subCode:3080,participantId:"",callId:"",resultCategories:["UnexpectedServerError"]}),i.logFailure(`Error parsing notification payload: ${e}`),!1}const r=this.isCallTransferNotification(e)?this.buildTransferCallPayload(n):this.buildNGCCallPayload(n);if(!r)return this.callRegistry.pushHandlingEnded(t,{result:"Failed to get incoming call notification payload",code:ps,subCode:3081,participantId:"",callId:"",resultCategories:["UnexpectedClientError"]}),!1;if(this.callRegistry.calls.some((e=>e.callId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the call registry, callId = ${r.convoCallId}, participantId = ${r.participantId}`),this.callRegistry.pushHandlingEnded(t,{result:"Failed due to duplicate call filtered because it was in the call registry",code:ks,subCode:3082,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["ExpectedError"]}),!1;const s=this.isCallReplacementNotification(e);if(i.log(`replacementCall=${s}`),!s&&this.recentInvitations.some((e=>e.convoCallId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the recent calls list, callId = ${r.convoCallId}, participantId = ${r.participantId}`),this.callRegistry.pushHandlingEnded(t,{result:"Failed due to duplicate call filtered because it was in the recent calls list",code:ks,subCode:3083,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["ExpectedError"]}),!1;5===this.recentInvitations.length&&this.recentInvitations.shift(),this.recentInvitations.push({convoCallId:r.convoCallId,participantId:r.participantId});let a=this.callRegistry.calls.find((e=>e.callId===r.convoCallId&&8===e.state));if(!a)if(r.groupId)try{a=this.callRegistry.createCallWithGroupId(r.groupId,r.convoCallId,r.participantId,t)}catch(e){this.callRegistry.pushHandlingEnded(t,{result:"Failed to create incoming call notification with groupId",code:ps,subCode:3084,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["UnexpectedClientError"]})}else try{a=this.callRegistry.createCall(r.conversationId,r.convoCallId,r.participantId,void 0,t)}catch(e){this.callRegistry.pushHandlingEnded(t,{result:"Failed to create incoming call notification",code:ps,subCode:3084,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["UnexpectedClientError"]})}a.init({threadId:r.conversationId,messageId:r.messageId,mediaPeerType:2});const o=()=>{this.callRegistry.pushHandlingEnded(t,{code:wa.HTTP_STATUS_CODES.OK,subCode:0,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["Success"]})},l=e=>{const i=a.callEndDiagnosticsInfo,n=i?i.callControllerSubCode:3085+e.code;this.callRegistry.pushHandlingEnded(t,{result:"Failed to acknowledge incoming call notification",code:i?.callControllerCode||ks,subCode:n,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:i?.resultCategories||["UnexpectedClientError"]})};return this.callRegistry.testEndpointMetadata?a.acknowledge(r,this.callRegistry.testEndpointMetadata,t).then(o).catch(l):a.acknowledge(r,void 0,t).then(o).catch(l),!0}isIncomingCallMessage(e){return Object.keys(Bs).some((t=>Bs[t]===e.eventId))?e.eventId!==Bs.INCOMING_TFL_TFW_CALL||this.ecsProvider?.getEcsConfig("SkypeCalling","enableTFWTFLOneToOneCall"):this.isCallTransferNotification(e)}isCallTransferNotification(e){return e.callNotification&&("transfer"===e.callNotification.callType||"replaces"===e.callNotification.callType)}isCallReplacementNotification(e){return e.callNotification&&"replaces"===e.callNotification.callType}isProxiableNotification(e){return Object.keys(Vs).some((t=>Vs[t]===e.eventId))}buildTransferCallPayload(e){const t={body:e.body,callerId:e.callNotification.from.id,displayNameSource:po(e.callNotification.from.displayNameSource),groupId:null,conversationId:null,convoCallId:e.debugContent.callId,isMultiParty:e.conversationInvitation?.isMultiParty,fromMixer:e.callNotification.fromMixer,ngcCall:!0,participantId:e.callNotification.to.participantId,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,consultativeCallId:e.callNotification.consultativeCallId,messageId:null,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,calleeAlternateId:e.callNotification.to?.calleeAlternateId};return this.logger.info("Incoming transfer paylod",We(t,["callerId","transferorId"])),t}buildNGCCallPayload(e){if(!e.callNotification)return this.logger.error("Missing callNotification in parsed incoming NGC call payload"),null;const t={groupId:e.groupContext?.id,conversationId:e.groupChat?.threadId,messageId:e.groupChat?.messageId,callerId:e.callNotification.from.id,displayNameSource:po(e.callNotification.from.displayNameSource),isMultiParty:e.conversationInvitation.isMultiParty,fromMixer:e.callNotification.fromMixer,convoCallId:e.debugContent.callId,participantId:e.debugContent.participantId,ngcCall:!0,body:e.body,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,fromApplicationType:e.callNotification.fromApplicationType,calleeAlternateId:e.callNotification.to?.calleeAlternateId,routingTimeout:e.callNotification.routingTimeout};return this.logger.info("Incoming NGC paylod",We(t,["callerId","transferorId"])),t}},Hf=class extends gt{constructor(e,t,i,n,r,s=null,a,o,l){super(),this.trouterService=e,this.signalingAgentProvider=t,this.mediaAgent=i,this.callingLogger=n,this.telemetryLoggers=r,this.ecsProvider=s,this.skypeIdentity=a,this.oneDsTelemetryLoggers=o,this.vdi3diagnostics=l,this.calls=[],this.isDisposing=!1,this._disposedPromise=new Kt,this.testEndpointMetadata=null,this._disconnectingPromiseDefers=new Map,this.skypeIdentity&&(this.identity=this.skypeIdentity.id),this.callSubscriptionsMap=new Map,this.logger=new ct(this.callingLogger).createChild(`CallRegistry/${be()}`),this.registryTelemetry=new Cr(this.logger,(new Date).getTime()),this._callOperationHandler||(this._callOperationHandler=new as(this.logger,this.registryTelemetry,{},(e=>{this._publishTelemetry(e)})));const c=this.mediaAgent.getConfig().disconnectOnPageHide;this._windowUninitEvent=c?"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(e,t,i=be()){return this.logger.createFnLogger("init",i).info("init"),this.login(e)}uninit(){return this.logout()}login(e,t=be()){return this.logger.createFnLogger("login",t).info("login"),this.skypeIdentity=e,this.identity=this.skypeIdentity.id,this.initialize(t)}initialize(e=be(),t){const i=this.logger.createFnLogger("initialize",e),n=t&&t.applicationType?t.applicationType:"null";i.info(`initialize with applicationType: ${n}`),this.accountConfiguration=t,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(t),this.incomingCallMessageHandler=new Vf(this,this.logger,this.ecsProvider),this.trouterService.registerMessageHandler(new Bf(this.signalingAgentProvider,this)),this.trouterService.registerMessageHandler(this.incomingCallMessageHandler),i.info("Call registry init, endpointMetadata",this.testEndpointMetadata);try{this.windowUninitListener=()=>{this._disregardWindowUninitEvents||this.stopCallsWithBeacon()},window.addEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){i.logFailure(`Not adding beforeunload listener: ${e}`)}return Promise.resolve(void 0)}logout(e=be()){const t=this.logger.createFnLogger("logout",e);t.info("logout");try{this.trouterService.clearMessageHandlers(),window.removeEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){t.info(`Not removing beforeunload listener: ${e}`)}return Promise.resolve(void 0)}_publishTelemetry(e){if(!this.telemetryLoggers?.signaling)return;this.registryTelemetry.setSkypeId(this.identity);try{const e=this.signalingAgentProvider.getSignalingAgent();this.registryTelemetry.setEndpointId(e.endpointId)}catch(e){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));this.telemetryLoggers.signaling.sendEvent({eventName:"skypecosi_concore_web_ts_calling_registry",props:this.registryTelemetry.getEvent(null,e)})}async dispose(e=be()){const t=this.logger.createFnLogger("dispose",e);if(t.info("dispose"),this.isDisposing)return t.warn("call registry is already in disposing stage!"),this._disposedPromise.promise;this.isDisposing=!0;const i=()=>{this.calls=[],this.event("disposed").raise(),super.dispose(),this._disposedPromise.resolve()},n=this.calls.map((e=>e.stop())),r=()=>this.logout();return this.clearCallSubscription(),this.signalingAgentProvider.getSignalingAgent().resetAuthTokenManager(),Promise.all(n).then(r,r).then(i,i),this._disposedPromise.promise}get disposePromise(){return this._disposedPromise.promise}createCallAsync(e){const t=this.logger.createFnLogger("createCallAsync",e.causeId),i=`callId:${e.callId}, localParticipantId: ${De(e.localParticipantId)},\n causeId:${e.causeId}, type:${e.type}, `;switch(e.type){case"MeetingData":i.concat(`meetingUrl:${!!e.meetingData?.meetingUrl}, meetingCode:${!!e.meetingData?.meetingCode}`);break;case"GroupId":i.concat(`groupId:${De(e.groupId)}`);break;case"ThreadId":i.concat(`threadId:${xe(e.threadId)}, messageId:${e.messageId}`);break;default:throw new Error("Invalid type in passing parameter.")}t.info(i);const n=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers,r=this._getCurrentCall(e,t);if(r){if(6===r.state){const e=new Kt;return this._disconnectingPromiseDefers.set(r.callId,e),e.promise}return Promise.resolve(r)}return Promise.resolve(this._createNewCall(e,n,t))}createCallWithMeetingData(e,t,i,n){const r=this.logger.createFnLogger("createCallWithMeetingData",n);if(r.info(`meetingData:${!!e}, callId:${t}, localParticipantId: ${De(i)}`),!e)return r.info("meetingData cannot be null"),null;const s=this._generateCreateCallOptions(n,t,i,null,null,null,e),a=this._getCurrentCall(s,r);if(a)return a;const o=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(s,o,r)}createCall(e,t,i,n,r=be()){return this._createCall(e,t,i,n,r)}createCallWithGroupId(e,t,i,n){return this._createCall("",t,i,void 0,n,e)}_createNewCall(e,t,i){let n=null,r=null,s=null,a=null;switch(e.type){case"MeetingData":a=e.meetingData;break;case"GroupId":n=e.groupId;break;case"ThreadId":r=e.threadId,s=e.messageId}const o=new xf(this.signalingAgentProvider.getSignalingAgent(),this.mediaAgent,new ct(this.callingLogger),t,this.skypeIdentity,n,r,e.callId,e.localParticipantId,this.ecsProvider,this.trouterService,this.accountConfiguration,s,this.locationInfoContent,this.networkInfoContent,a,this.areaContent,this.vdi3diagnostics);o.on("callStateChanged",(async()=>{if(7===o.state&&this._createNewCallInDisconnectedState){const n=this._disconnectingPromiseDefers.get(o.callId);n&&(this._disconnectingPromiseDefers.delete(o.callId),n.resolve(this._createNewCall(e,t,i))),this._invokeDeleteCallInDisconnectedState&&setTimeout((()=>{this.deleteCall(o)}),0)}})),this.calls.push(o),this.event("callAdded").raise(o),this.raiseChanged(),i.info(`Created new call with id ${o.callId}`);const l=o.on("replacementRequested",(e=>{this.incomingCallMessageHandler.handleMessage(e)}));return this.addCallSubscriptionToMap(o,l),o}_getCurrentCall(e,t){let i=null;return"MeetingData"===e.type&&(i=this.getCallUsingMeetingData(e.meetingData,e.callId,e.localParticipantId,void 0,void 0,e.causeId),i)?(t.info("Call Registry has an entry for this call's meeting data"),i):(i=this.getCall(e.callId,e.localParticipantId,e.causeId),i?(t.info("Call Registry has an entry for this callId, participantId"),i):"ThreadId"===e.type&&(i=this.getCallUsingThreadIdMessageId(e.threadId,e.callId,e.messageId,e.causeId),i)?(t.info("Call Registry has an entry for this threadId, messageId"),i):"GroupId"===e.type&&(i=this.calls.find((t=>t.groupId===e.groupId)),i)?(t.info("Call Registry has an entry for this groupId"),i):i)}_generateCreateCallOptions(e,t,i,n,r,s,a){let o=null;return o=n?{type:"GroupId",callId:t,localParticipantId:i,causeId:e,groupId:n}:r?{type:"ThreadId",callId:t,localParticipantId:i,causeId:e,threadId:r,messageId:s}:{type:"MeetingData",callId:t,localParticipantId:i,causeId:e,meetingData:a},o}_createCall(e,t,i,n,r=be(),s){const a=this.logger.createFnLogger("createCall",r);a.info(`threadId:${xe(e)}, callId:${t}, localParticipantId: ${De(i)}, messageId:${n}, groupId:${De(s)}`);const o=this._generateCreateCallOptions(r,t,i,s,e,n,null),l=this._getCurrentCall(o,a);if(l)return l;const c=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(o,c,a)}getCall(e,t,i=be()){const n=this.logger.createFnLogger(`getCall[callId=${e}][participantId=${De(t)}]`,i);if(!e)return n.logFailure("callId is undefined"),null;const r=this.calls.find((t=>t.callId===e));return r&&n.info("Call Registry already has an entry for this call"),r}async deleteCallAsync(e){return Wt((()=>this.deleteCall(e)))}deleteCall(e){const t=this.calls.indexOf(e);return-1!==t&&(this.callSubscriptionsMap.get(e).forEach((e=>{e.dispose()})),this.callSubscriptionsMap.delete(e),this.calls.splice(t,1),this.event("callRemoved").raise(e),this.raiseChanged(),!0)}async setConfiguration(e){this.accountConfiguration=e,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(e)}updateDisplayName(e){return this.skypeIdentity.displayName=e,this.calls.forEach((t=>{t.updateDisplayName(e)})),Promise.resolve()}fireIntent(e,t){return Promise.resolve()}getCallState(e,t){return Promise.reject("Not implemented")}getSetup(){}getEcsConfig(){return Promise.reject()}updateSkypeToken(e){this.logger.debug("CallRegistry.updateSkypeToken() called but not supported in the current set up.")}updateToken(e,t,i,n,r){this.logger.info(`[updateToken], causeId = ${n} tokenType = ${t.tokenType}, factorsJson = ${e}, tokenExpiredTime = ${r}`);try{return this.signalingAgentProvider.getSignalingAgent().updateToken(e,t,i,n,r),Promise.resolve({code:0})}catch(t){return this.logger.info(`Failed to update token with ${e}, error is ${t}`),Promise.reject(ns(`Failed to update token with ${e}, error is ${t}`))}}onTokenRequired(e){const{requestMetadataJson:t,factorsJson:i,tokenType:n,invalidToken:r}=e;this.logger.info(`[onTokenRequired], tokenType ${n}, factorsJson ${i}, requestMetadataJson ${JSON.stringify(t)}`),this.event("tokenRequired").raise(i,n,t,r)}pushHandlingStarted(e){this.logger.info(`handleIncomingCallStarted, causeId=${e}`),this.event("pushHandlingStarted").raise(e)}pushHandlingEnded(e,t){this.logger.info(`pushHandlingEnded, causeId=${e}`),this.event("pushHandlingEnded").raise(e,t)}debugInformation(e){const t=e?`CallInformation\n * CallId=${e.callId}`:void 0;return Promise.resolve(t)}setLocationInfo(e,t,i=be()){if(this.logger.info(`setLocationInfo, ${i}, infoType:${e}, contentJson ${t?"is set":"is undefined"}`),t)try{JSON.parse(t)}catch(e){return Promise.reject(`invalid contentJson: ${e}`)}return this.locationInfoType=e,1===this.locationInfoType&&(this.locationInfoContent=t,this.logger.info(`locationInfoContent set to ${this.locationInfoContent}`)),2===this.locationInfoType&&(this.networkInfoContent=t,this.logger.info(`networkInfoContent set to ${this.networkInfoContent}`)),3===this.locationInfoType&&(this.areaContent=t,this.logger.info(`areaContent set to ${this.areaContent}`)),this.event("locationInfoSet").raise(e,t),Promise.resolve()}createDownloader(){return null}async getUnassembledLocalRecordingSessions(e=be()){return Promise.reject("Not implemented")}submitBrbReport(e,t){return Promise.reject("Not implemented")}extendBrbFeedback(e,t){return Promise.reject("Not implemented")}proxyPushNotification(e){this.logger.info(`Proxying push notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:$f(e,this.logger)};this.event("proxiedPushNotification").raise(t)}catch(e){this.logger.error(`Error proxying push notification: ${e}`)}}logUploadNotification(e){this.logger.info(`Log upload notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:$f(e,this.logger)};this.event("logUploadNotification").raise(t)}catch(e){this.logger.error(`Error raising log upload notification: ${e}`)}}sendPush(e,t,i,n){const r={id:e},s=[];return t.forEach((e=>{s.push({id:e})})),this.signalingAgentProvider.getSignalingAgent().sendPushAsync(r,s,i,n)}enableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!1}disableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!0}async enableWindowUninitEventHandlerAsync(){this.enableWindowUninitEventHandler()}async disableWindowUninitEventHandlerAsync(){this.disableWindowUninitEventHandler()}getCallUsingThreadIdMessageId(e,t,i,n){this.logger.info(`[getCallUsingThreadIdMessageId][${n}] threadID: ${xe(e)} callId: ${t} messageId: ${i}`);let r=null;return e&&(r=this.calls.find((n=>n.threadId===e&&(t&&n.callId===t||null!=i&&n.messageId===i))),r)?(this.logger.logFailure(`[getCallUsingThreadIdMessageId][${n}]Call Registry already has an entry for threadId: ${xe(r.threadId)}, callId: ${r.callId}, messageId: ${r.messageId}`),r):r}getCallUsingMeetingData(e,t,i,n,r,s=be()){const a=this.logger.createFnLogger("getCallUsingMeetingData",s);if(a.info(`[callId=${t}][participantId=${De(i)}] meetingData: ${!!e} \n threadId: ${xe(n)} messageId: ${r}`),!t)return a.logFailure("callId is undefined"),null;let o;for(const i of this.calls){if(i.callId===t){o=i;break}if(Ir(i.meetingData,e,s,this.logger)){o=i;break}}return o}stopCallsWithBeacon(){for(const e of this.calls)e.stopWithBeacon()}addCallSubscriptionToMap(e,t){this.callSubscriptionsMap.set(e,(this.callSubscriptionsMap.get(e)||[]).concat(t))}clearCallSubscription(){this.callSubscriptionsMap.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.callSubscriptionsMap.clear()}};function $f(e,t){const i=t.createFnLogger("decodeNotificationPayload");let n="{}";if(e?.body?.gp)i.info("using notification.body.gp"),n=function(e){const t=new TextDecoder("utf-8"),i=atob(e),n=Uint8Array.from(i,(e=>e.charCodeAt(0)));return t.decode(n)}(e.body.gp);else if(e?.body?.cp){i.info("using notification.body.cp");const t=atob(e.body.cp);n=Ff.inflate(t,{to:"string"})}return n}m([Gr("Initialize",{enableInstantTelemetry:!0})],Hf.prototype,"initialize",1),m([Gr("Logout",{enableInstantTelemetry:!0})],Hf.prototype,"logout",1);var jf=Z,Gf=class{constructor(e){this.deviceManager=e}get childDeviceManagers(){return this.deviceManager.getRegisteredDevices()}createPreview(e,t){return this.executeOnVirtualDeviceManager((t=>e(t,"Video")),t)}getRawDeviceMediaStream(e,t,i){return this.executeOnVirtualDeviceManager((i=>i.getRawDeviceMediaStream(e,t)),i)}setDeviceEffectsAsync(e,t){return this.executeOnVirtualDeviceManager((e=>e.setVideoEffects(t)),e)}setRawMediaStream(e,t,i){this.executeOnVirtualDeviceManager((i=>i.setRawMediaStream(e,t)),i)}unsetRawMediaStream(e,t){this.executeOnVirtualDeviceManager((t=>t.unsetRawMediaStream(e)),t)}getVirtualDevice(e){return this.childDeviceManagers.find((t=>t.id===e))}executeOnVirtualDeviceManager(e,t){return this.getVirtualDevice(t).getDeviceManagers().map((t=>e(t)))}},qf=class e extends gt{constructor(e){super(),this._deviceManager=e,this.virtualDeviceAdapter=new Gf(this._deviceManager),e.on("onDevicesChanged",(e=>{const t=this._deviceManager.getDeviceDescriptions(e),i=this._mapDevices(t);this._raiseDevicesChanged(i)})),e.on("onSelectedDevicesChanged",(e=>this._raiseDevicesChanged())),e.on("onPermissionStateChanged",(()=>this.event("onPermissionStateChanged").raise())),e.on("onVideoEffectsEvent",((e,t)=>this.event("videoEffectsEvent").raise(e,t))),e.on("onVideoEffectApplied",(()=>this.event("videoEffectApplied").raise())),e.on("onEffectsError",((e,t,i)=>this.event("onEffectsError").raise(Yh(e),t,i)))}get isAudioOutputSelectionSupported(){return this._deviceManager.isAudioOutputSelectionSupported}getPermissionState(e){return"camera"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("camera")):"microphone"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("microphone")):"unknown"}async getPermissionStateAsync(e){return this.getPermissionState(e)}askDevicePermission(e){return this._deviceManager.askDevicePermission?this._deviceManager.askDevicePermission(e):Promise.resolve({audio:!0,video:!0})}enumerateDevicesAsync(){return this._deviceManager.enumerateDevicesAsync().then((e=>this._mapDevices(e)))}getPreferredCamera(){throw new Error("Not implemented")}selectDevices(e){if(Object.keys(e).some((e=>this.isVirtualDevice(e))))throw new Error("Virtual Device selection on DM is not supported");const t=(0,jf.assign)({},this._deviceManager.getSelectedDevices(),e);this._deviceManager.selectDevices(t)}selectDevicesAsync(e){return Wt((()=>this.selectDevices(e)))}getSelectedDevices(){return this._deviceManager.getSelectedDevices()}getSelectedDevicesAsync(){return Wt((()=>this.getSelectedDevices()))}getDeviceNameAsync(e){return this._deviceManager.getDeviceNameAsync(e)}getSpeakerDeviceDomIdAsync(e,t){return this._deviceManager.getSpeakerDeviceDomIdAsync(e)}mapBrowserDevices(e,t){return Promise.reject(new Error("Not implemented"))}async setDeviceEffectsAsync(e,t){if(!this.isVirtualDevice(e))return this._deviceManager.setVideoEffects(t);Promise.all(this.virtualDeviceAdapter.setDeviceEffectsAsync(e,t))}getDeviceEffectsCapabilityAsync(e,t){return this._deviceManager.effectsManager.getEffectsCapability("Video")}setBackgroundImageAsync(e,t,i){return this._deviceManager.effectsManager.configure("Video",{imagePath:t,headers:i})}getImagePropertyAsync(e){return Promise.reject(new Error("Not implemented"))}getMicrophoneGeometryArrayInfoAsync(e){return Promise.reject(new Error("Not implemented"))}transformImageAsync(e,t,i,n){return Promise.reject(new Error("Not implemented"))}setAudioProcessingFlags(e){return this._deviceManager.setAudioProcessingFlags(e)}async sendMessageDeviceVideoEffectsAsync(e,t){return await this._deviceManager.sendMessageDeviceVideoEffectsAsync(e,t)}sendMessageDeviceVideoExtensibilityAsync(e,t){return Promise.reject(new Error("Not implemented"))}setVideoCaptureConfigAsync(e,t){return Promise.reject(new Error("Not implemented"))}captureVideoFrameWithoutEffectsAsync(e,t,i){return Promise.reject(new Error("Not implemented"))}enableSignLanguageDetectionAsync(e,t){return Promise.reject(new Error("Not implemented"))}downloadAiModel(e,t){return Promise.reject(new Error("Not implemented"))}getSpeakerVolume(){return Promise.reject(new Error("Not implemented"))}getSpeakerSystemVolume(){return Promise.reject(new Error("Not implemented"))}setSpeakerVolume(e){return Promise.reject(new Error("Not implemented"))}setSpeakerSystemVolume(e){return Promise.reject(new Error("Not implemented"))}unmuteMicrophone(){return Promise.reject(new Error("Not implemented"))}unmuteSpeaker(){return Promise.reject(new Error("Not implemented"))}getNrgLevelsForDeviceTuner(e){return Promise.reject(new Error("Not implemented"))}async getNrgLevelPollerForDeviceTuner(e){return await this._deviceManager.getNrgLevelPollerForDeviceTuner()}setAudioEffectsAsync(e,t){return this._deviceManager.setAudioEffects(t)}getAudioFeatureCapability(e){return this._deviceManager.effectsManager.getEffectsCapability("Audio")}getAudioFeatureProviderName(){return Promise.resolve(this._deviceManager.effectsManager.getAudioEffectsProviderName())}getMicrophoneVolume(){return Promise.reject(new Error("Not implemented"))}setMicrophoneVolume(e){return Promise.reject(new Error("Not implemented"))}setDeviceTelemetryData(e,t,i,n=0){return Promise.reject(new Error("Not implemented"))}getSourceFormats(e){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(e,t){return Promise.reject(new Error("Not implemeted"))}unregisterDerivedSource(e){return Promise.reject(new Error("Not implemeted"))}startPreview(e,t,i){const n=new _g,r=(async()=>{if("camera"===t.kind&&this.isVirtualDevice(t.device))return this.virtualDeviceAdapter.createPreview(this.startRenderer.bind(this,n,e,i),t.device)[0];if("sharing"===t.kind)return this.startRenderer(n,e,i,this._deviceManager,"ScreenShare");if("camera"!==t.kind||!(0,jf.isUndefined)(t.device))throw new Error("Not yet supported");return this.startRenderer(n,e,i,this._deviceManager,"Video")})();return{instance:n,promise:r}}async createPreview(e,t,i){const{instance:n,promise:r}=this.startPreview(e,t,i);return await r,n}async createPreviewRenderer(e,t){return this.createPreview(e,{kind:"camera"},t)}async createScreenSharingPreviewRenderer(e,t){return this.createPreview(e,{kind:"sharing"},t)}getRawDeviceMediaStream(e,t,i){const n=Jh(e);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.getRawDeviceMediaStream(n,t,i)[0]:this._deviceManager.getRawDeviceMediaStream(n,t)}setRawMediaStream(e,t,i){const n=Jh(t);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.setRawMediaStream(e,n,i):this._deviceManager.setRawMediaStream(e,n)}unsetRawMediaStream(e,t){const i=Jh(e);return this.isVirtualDevice(t)?this.virtualDeviceAdapter.unsetRawMediaStream(i,t):this._deviceManager.unsetRawMediaStream(i)}createAudioRenderer(){return this._deviceManager.createAudioRenderer()}startAudioLoopbackDevice(e){return Promise.reject(new Error("Not implemented"))}async dispose(e){return this._deviceManager.dispose(e)}async registerCompositeVideoDevice(e,t,i){return this._deviceManager.registerVirtualDevice(e,t,i)}async unregisterCompositeVideoDevice(e){return this._deviceManager.unregisterVirtualDevice(e)}async createAudioPlayer(){return Promise.reject(new Error("Not implemented"))}_raiseDevicesChanged(e){(e?Promise.resolve(e):this.enumerateDevicesAsync()).then((e=>{this.raiseChanged(),this.event("devicesChanged").raise(e)}))}getPermissionStateHelper(e){switch(e){case"granted":return"granted";case"denied":return"denied";case"prompt":return"prompt";default:return"unknown"}}_mapDevices(e){return e?.map((e=>this._mapDeviceDesc(e)))}_mapDeviceDesc(t){const i=e._mapDeviceType(t.kind);return 6===i?{id:t.id,label:t.label,kind:i,position:0,defaultVideoId:t.id,devicesIds:[]}:1===i?{id:t.id,browserId:t.browserId,label:t.label,kind:i,position:e._mapCameraPosition(t.position)}:4===i?{id:null,browserId:null,label:t.label,kind:i,formFactor:t.formFactor,isPcInternalDevice:t.isPcInternalDevice,microphoneId:t.microphoneId,speakerId:t.speakerId}:{id:t.id,browserId:"default_output_device"===t.browserId?"default":t.browserId,label:t.label,kind:i,isSystemDefault:!!t.isSystemDefault}}static _mapDeviceType(e){switch(e){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 '${e}'`)}}static _mapCameraPosition(e){switch(e){case"front":return 1;case"back":return 2;case"external":return 3;default:return 0}}isVirtualDevice(e){return e&&this._deviceManager.getRegisteredDevices().some((t=>t.id===e))}async startRenderer(e,t,i,n,r){try{e.initialize(t,n,r),await e.startVideoAsync(),i&&(e.setScalingMode(i.scalingMode),e.setVideoMirroring(!i.ignoreMirroring))}catch(t){throw e.dispose(),t}}},zf=Q,Wf=Q,Kf=class extends Wf.AbstractLogAppender{constructor(e){super(new Wf.StandardLogFormatter(Wf.SLF_Flags.Component)),this._logger=e}log(e,t,i,n){if(!this._logger)return;const r=e.level<=Wf.LogLevel.Debug4?this._logger.debug:e.level<=Wf.LogLevel.Debug2?this._logger.log:e.level<=Wf.LogLevel.Debug1?this._logger.info:e.level<=Wf.LogLevel.Warning?this._logger.warn:this._logger.error;r&&r.apply(this._logger,[this.formatter().format(e,t,i,n)])}},Jf=Q,Yf=p(me()),Qf=["CorrelationId","agent_environment_id","UserInfo_TenantId","participant_id","endpoint_id","mediaLegId","metrics_ConfigIds","ts_calling_version","uiVersion"],Zf={video:[...Qf,"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:[...Qf,"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"]},Xf=class extends gt{constructor(){super(...arguments),this.stabilizationTimeInAvg=2e4}send(e){e&&setTimeout((()=>{this.event("sendMidCallTelemetry").raise(Zf[e])}),this.stabilizationTimeInAvg)}},ev=class extends gt{constructor(e,t){super(),this._telemetryService=e,this._ecsProvider=t,this._ecsProvider.on("OnECSChanged",(()=>Jf.RootToolsManager.OnEcsChange()))}fetchEcsConfig(e,t){return Yf.Resolved().then((()=>this._ecsProvider.getEcsConfig(e,t)))}sendTelemetry(e,t){this._telemetryService.getGenericTelemetryLogger&&e?this._telemetryService.getGenericTelemetryLogger(e).sendEvent({eventName:"rt_log",props:t}):this._telemetryService.sendEvents([{eventName:"rt_log",props:t}])}sendMidCallTelemetry(e){Object.keys(Zf).includes(e)&&this.event("onMidCallTelemetry").raise(e)}},tv=Z,iv=class e{constructor(t){this._prefix=t,this._children=[],this._useConsoleLogger=!1,this.createChild=(t,i)=>{const n="function"==typeof t?"":t,r=new e((this._prefix||"")+n);return this._children.push(r),this._useConsoleLogger&&r.useConsoleLogger(),r},this.createFnLogger=(t,i,...n)=>{const r=`[${i}][${t}]`,s=new e((this._prefix||"")+r);return this._children.push(s),this._useConsoleLogger&&s.useConsoleLogger(),s}}logInfo(){}logFailure(){}logSuccess(){}log(...e){}debug(...e){}info(...e){}warn(...e){}error(...e){}useConsoleLogger(){this._useConsoleLogger=!0;const e=(...e)=>{console.info(this._prefix||"",...e)};this.log=e,this.debug=e,this.info=e,this.warn=e,this.error=e,(0,tv.each)(this._children,(e=>e.useConsoleLogger()))}},nv=class{constructor(e){this.configProvider=e,this.window=Mp.window,this.updateCapabilityOverrides(),this.configProviderSub=e.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 e;this.configProvider.config.capabilities&&(e=this.configProvider.config.capabilities),this.overrides=e||{}}hasMediaCapture(){return!!this.window.navigator.getUserMedia}getCapability(e){return void 0!==this.overrides[e]?!!this.overrides[e]:this.hasMediaCapture()&&this.hasWebRtc()}hasWebRtc(){return void 0!==this.window.RTCPeerConnection}},rv=class e extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.diagnostics=i,this.eventStates=new Map,this.debounceMap=new Map,this.logger.safe.info("Initialized")}signalEvent(e,t,i="Audio",n=!0,r=be(),s,a){const o={type:e,value:t,isLocalSource:n,mediaType:i,deviceManagerId:s,diagnosticData:a};this.shouldRaiseEvent(o)&&this.diagnostics.registerQualityChangedEvent(o);const l=Rf(o),c=this.eventStates.get(l);if(this.configProvider.config.localUFDDebounceTime&&c){clearTimeout(this.debounceMap.get(l));const e=setTimeout(this.raiseEvent.bind(this),this.configProvider.config.localUFDDebounceTime,o,r);this.debounceMap.set(l,e)}else this.raiseEvent(o,r)}raiseEvent(e,t){const i=Rf(e);this.shouldRaiseEvent(e)&&(this.eventStates.set(i,e),this.logger.safe.info(`[${t}] Raising UFD ${e.type} for ${e.mediaType}: ${e.value}`),this.event("onQualityChanged").raise(e))}signalDeviceEvent(t,i,n,r){const s=e.getQualityEventType(t,n,this.configProvider);s?this.signalEvent(s,i,n,void 0,be(),r):this.logger.warn(`Unknown device quality event type: ${t}`)}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 e=Rf(this.lastWhitelistingUFD);this.eventStates.delete(e)}this.lastWhitelistingUFD=void 0}applyCurrentState(e){this.cancelPendingWhitelistingUFD();let t=0;for(const i of this.eventStates.values())"Good"!==i.value&&(e(i),t++);t>0&&this.logger.safe.info(`Applied ${t} UFDs`)}reset(){this.logger.safe.info("Resetting UFD states");for(const[t,i]of this.eventStates.entries())e.persistent.has(i.type)||this.eventStates.delete(t);this.lastWhitelistingUFD=void 0}shouldRaiseEvent(t){const i=Rf(t),n=this.eventStates.get(i);return n&&n.value===t.value?!(!this.configProvider.config.alwaysRaiseBadDeviceEvents||!e.deviceQualityEvents.has(t.type)||"Good"===t.value):!(!n&&"Good"===t.value||("NetworkRelaysNotReachable"===t.type?(this.lastWhitelistingUFD=t,1):"NetworkRecvQuality"===t.type&&!this.configProvider.config.webrtcStatNetworkDetectionEnabled))}static getQualityEventType(e,t,i){switch(e){case 0:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartFailed";case 1:return"DeviceRenderNotFunctioning";case 2:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartTimedOut";case 3:return"DeviceCaptureMute";case 4:switch(t){case"ScreenShare":return"ScreenshareRecordingDisabled";case"Audio":return i.config.enableSignalingAudioPermissionDeniedUFD?"AudioCapturePermissionDenied":"DeviceCaptureNotMuteButSilent";case"Video":return"VideoCapturePermissionDenied";default:return}default:return}}};rv.persistent=new Set(["ZeroCaptureDevicesEnumerated","ZeroRenderDevicesEnumerated"]),rv.deviceQualityEvents=new Set(["DeviceCaptureNotFunctioning","VideoCapturerDeviceStartFailed","VideoCapturerDeviceStartTimedOut","DeviceCaptureMute","ScreenshareRecordingDisabled","DeviceCaptureNotMuteButSilent","VideoCapturePermissionDenied"]);var sv=rv,av=Z,ov="object",lv="undefined",cv="prototype",dv=Object,uv=dv[cv];function hv(e,t){return e||t}function gv(e,t){return e[t]}var pv,mv=void 0,fv=null,vv="function",Sv="object",yv="prototype",Cv="__proto__",Tv="undefined",Ev="constructor",bv="Symbol",_v="length",Iv="name",wv="call",Av="toString",Pv=hv(Object),Rv=gv(Pv,yv),Mv=hv(String),Dv=gv(Mv,yv),kv=hv(Math),Ov=hv(Array),Nv=gv(Ov,yv),Lv=gv(Nv,"slice");function xv(e,t){try{return{v:e.apply(this,t)}}catch(e){return{e}}}function Fv(e){return function(t){return typeof t===e}}function Uv(e){var t="[object "+e+"]";return function(e){return!(!e||function(e){return Rv[Av].call(e)}(e)!==t)}}function Bv(e){return typeof e===Tv||e===Tv}function Vv(e){return e===fv||Bv(e)}function Hv(e){return!!e||e!==mv}function $v(e){return!pv&&(pv=["string","number","boolean",Tv,"symbol","bigint"]),e!==Sv&&-1!==pv.indexOf(e)}var jv=Fv("string"),Gv=Fv(vv);function qv(e){return!(!e&&Vv(e)||!e||typeof e!==Sv)}var zv=gv(Ov,"isArray"),Wv=Uv("Date"),Kv=Fv("number"),Jv=Fv("boolean"),Yv=Uv("Error");function Qv(e){return!!(e&&e.then&&Gv(e.then))}function Zv(e){return!(!e||function(e,t){var i=xv(e);return i.e?t:i.v}((function(){return!(e&&0+e)}),!e))}var Xv=gv(Pv,"getOwnPropertyDescriptor");function eS(e,t){return!!e&&Rv.hasOwnProperty[wv](e,t)}var tS=hv(gv(Pv,"hasOwn"),(function(e,t){return eS(e,t)||!!Xv(e,t)}));function iS(e,t,i){if(e&&qv(e))for(var n in e)if(tS(e,n)&&-1===t[wv](i||e,n,e[n]))break}var nS={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function rS(e){var t={};if(t[nS.c]=!0,t[nS.e]=!0,e.l){t.get=function(){return e.l.v};var i=Xv(e.l,"v");i&&i.set&&(t.set=function(t){e.l.v=t})}return iS(e,(function(e,i){t[nS[e]]=Bv(i)?t[nS[e]]:i})),t}var sS=gv(Pv,"defineProperty"),aS=gv(Pv,"defineProperties");function oS(e,t,i){return sS(e,t,rS(i))}function lS(e,t){var i={};return iS(t,(function(e,t){i[e]=rS(t)})),aS(e,i)}function cS(e,t,i,n,r){var s={};return iS(e,(function(e,n){dS(s,e,t?n:e,r),dS(s,n,i?n:e,r)})),n?n(s):s}function dS(e,t,i,n){sS(e,t,{value:i,enumerable:!0,writable:!!n})}var uS=hv(Mv);function hS(e,t){var i="",n=Rv[Av][wv](e);"[object Error]"===n&&(e={stack:uS(e.stack),message:uS(e.message),name:uS(e.name)});try{i=(i=JSON.stringify(e,fv,t?"number"==typeof t?t:4:mv))&&i.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||uS(e)}catch(e){i=" - "+hS(e,t)}return n+": "+i}function gS(e){throw new Error(e)}function pS(e){throw new TypeError(e)}var mS=gv(Pv,"freeze"),fS=gv(Pv,"assign"),vS=gv(Pv,"keys");function SS(e){return mS&&iS(e,(function(e,t){(zv(t)||qv(t))&&SS(t)})),CS(e)}var yS,CS=hv(mS,(function(e){return e})),TS=hv(gv(Pv,"getPrototypeOf"),(function(e){return e[Cv]||fv})),ES=cS({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},0,0,CS),bS="__tsUtils$gblCfg";function _S(){var e;return typeof globalThis!==Tv&&(e=globalThis),e||typeof self===Tv||(e=self),e||typeof window===Tv||(e=window),e||typeof i===Tv||(e=i),e}function IS(){if(!yS){var e=xv(_S).v||{};yS=e[bS]=e[bS]||{}}return yS}var wS=AS;function AS(e,t,i){var n=t&&t[e];return function(t){var r=t&&t[e]||n;if(r||i){var s=arguments;return(r||i).apply(t,r?Lv[wv](s,1):s)}pS('"'+uS(e)+'" not defined for '+hS(t))}}var PS=gv(kv,"max"),RS=wS("slice",Dv),MS=wS("substring",Dv),DS=AS("substr",Dv,(function(e,t,i){return Vv(e)&&pS("Invalid "+hS(e)),i<0?"":((t=t||0)<0&&(t=PS(t+e[_v],0)),Bv(i)?RS(e,t):RS(e,t,t+i))}));function kS(e,t){return MS(e,0,t)}var OS,NS,LS,xS="_urid";function FS(e){return{description:uS(e),toString:function(){return bv+"("+e+")"},_polyfill:!0}}function US(e){var t=function(){if(!OS){var e=IS();OS=e.gblSym=e.gblSym||{k:{},s:{}}}return OS}();if(!tS(t.k,e)){var i=FS(e),n=vS(t.s).length;i[xS]=function(){return n+"_"+i[Av]()},t.k[e]=i,t.s[i[xS]()]=uS(e)}return t.k[e]}function BS(){LS=IS()}function VS(e){return sS({toJSON:function(){return e}},"v",{value:e})}var HS,$S="window";function jS(e,t){var i;return function(){return!LS&&BS(),(!i||LS.lzy)&&(i=VS(xv(e,t).v)),i.v}}function GS(e){return!LS&&BS(),(!HS||!1===e||LS.lzy)&&(HS=VS(xv(_S).v||fv)),HS.v}function qS(e,t){var i=HS&&!1!==t?HS.v:GS(t);return i&&i[e]?i[e]:e===$S?QS():fv}function zS(){return!!YS()}var WS,KS,JS,YS=jS(qS,["document"]),QS=jS(qS,[$S]),ZS=jS(qS,["navigator"]),XS=jS((function(){return!!xv((function(){return process&&(process.versions||{}).node})).v}));function ey(){return WS=VS(xv(qS,[bv]).v)}function ty(e){var t=(LS.lzy?0:WS)||ey();return t.v?t.v[e]:mv}function iy(e,t){var i=ES[e];!LS&&BS();var n=(LS.lzy?0:WS)||ey();return n.v?n.v[i||e]:t?mv:function(e){var t;!NS&&(NS={});var i=ES[e];return i&&(t=NS[i]=NS[i]||FS(bv+"."+i)),t}(e)}function ny(e,t){!LS&&BS();var i=(LS.lzy?0:WS)||ey();return i.v?i.v(e):t?fv:FS(e)}function ry(e){return!LS&&BS(),((KS=(LS.lzy?0:KS)||VS(xv(ty,["for"]).v)).v||US)(e)}function sy(e){return!!e&&Gv(e.next)}function ay(e,t,i){if(e&&(sy(e)||(!JS&&(JS=VS(iy(3))),e=e[JS.v]?e[JS.v]():null),sy(e))){var n=mv,r=mv;try{for(var s=0;!(r=e.next()).done&&-1!==t[wv](i||e,r.value,s,e);)s++}catch(t){n={e:t},e.throw&&(r=fv,e.throw(n))}finally{try{r&&!r.done&&e.return&&e.return(r)}finally{if(n)throw n.e}}}}function oy(e,t,i){return e.apply(t,i)}function ly(e,t){return!Bv(t)&&e&&(zv(t)?oy(e.push,e,t):sy(t)||function(e){return!function(e){return e===fv||!Hv(e)}(e)&&Gv(e[iy(3)])}(t)?ay(t,(function(t){e.push(t)})):e.push(t)),e}function cy(e,t,i){if(e)for(var n=e[_v]>>>0,r=0;r<n&&(!(r in e)||-1!==t[wv](i||e,e[r],r,e));r++);}var dy=wS("indexOf",Nv);function uy(e,t,i){return(e&&e.slice||Lv).apply(e,Lv[wv](arguments,1))}var hy,gy=AS("includes",Nv,(function(e,t,i){return-1!==dy(e,t,i)})),py=hv(gv(Pv,"create"),(function(e){if(!e)return{};var t=typeof e;function i(){}return t!==Sv&&t!==vv&&pS("Prototype must be an Object or function: "+hS(e)),i[yv]=e,new i}));function my(e,t){return(Pv.setPrototypeOf||function(e,t){var i;!hy&&(hy=VS(((i={})[Cv]=[],i instanceof Array))),hy.v?e[Cv]=t:iS(t,(function(t,i){return e[t]=i}))})(e,t)}function fy(e,t){t&&(e[Iv]=t)}function vy(e,t,i){var n=i||Error,r=n[yv][Iv],s=Error.captureStackTrace;return function(e,t,i){function n(){this[Ev]=t,xv(oS,[this,Iv,{v:e,c:!0,e:!1}])}return xv(oS,[t,Iv,{v:e,c:!0,e:!1}]),(t=my(t,i))[yv]=i===fv?py(i):(n[yv]=i[yv],new n),t}(e,(function(){var i=this,a=arguments;try{xv(fy,[n,e]);var o=oy(n,i,Lv[wv](a))||i;if(o!==i){var l=TS(i);l!==TS(o)&&my(o,l)}return s&&s(o,i[Ev]),t&&t(o,a),o}finally{xv(fy,[n,r])}}),n)}function Sy(){return(Date.now||yy)()}function yy(){return(new Date).getTime()}var Cy,Ty,Ey,by=AS("trim",Dv,function(e){return function(t){return Vv(t)&&pS("strTrim called ["+hS(t)+"]"),t&&t.replace&&(t=t.replace(e,"")),t}}(/^\s+|(?=\s)\s+$/g));function _y(e){if(!e||typeof e!==Sv)return!1;Ey||(Ey=!QS()||QS());var t=!1;if(e!==Ey){Ty||(Cy=Function[yv][Av],Ty=Cy[wv](Pv));try{var i=TS(e);(t=!i)||(eS(i,Ev)&&(i=i[Ev]),t=i&&typeof i===vv&&Cy[wv](i)===Ty)}catch(e){}}return t}function Iy(e){return e.value&&Ry(e),!0}var wy=[function(e){var t=e.value;if(zv(t)){var i=e.result=[];return i.length=t.length,e.copyTo(i,t),!0}return!1},Ry,function(e){return e.type===vv},function(e){var t=e.value;return!!Wv(t)&&(e.result=new Date(t.getTime()),!0)}];function Ay(e,t,i,n){var r=i.handler,s=i.path?n?i.path.concat(n):i.path:[],a={handler:i.handler,src:i.src,path:s},o=typeof t,l=!1,c=!1;t&&o===Sv?l=_y(t):c=t===fv||$v(o);var d={type:o,isPrim:c,isPlain:l,value:t,result:t,path:s,origin:i.src,copy:function(t,n){return Ay(e,t,n?a:i,n)},copyTo:function(t,i){return Py(e,t,i,a)}};return d.isPrim?r&&r[wv](i,d)?d.result:t:function(e,t,i,n){var r;return cy(e,(function(e){if(e.k===t)return r=e,-1})),r||(r={k:t,v:t},e.push(r),n(r)),r.v}(e,t,0,(function(e){oS(d,"result",{g:function(){return e.v},s:function(t){e.v=t}});for(var t=0,n=r;!(n||(t<wy.length?wy[t++]:Iy))[wv](i,d);)n=fv}))}function Py(e,t,i,n){if(!Vv(i))for(var r in i)t[r]=Ay(e,i[r],n,r);return t}function Ry(e){var t=e.value;if(t&&e.isPlain){var i=e.result={};return e.copyTo(i,t),!0}return!1}function My(e,t,i,n,r,s,a){return function(e,t){return cy(t,(function(t){!function(e,t){Py([],e,t,{handler:void 0,src:t,path:[]})}(e,t)})),e}(function(e){return Ay([],e,{handler:void 0,src:e})}(e)||{},Lv[wv](arguments))}var Dy=function(e){return function(t){return t[e]}}(_v);function ky(){return Sy()}var Oy=AS("endsWith",Dv,(function(e,t,i){jv(e)||pS("'"+hS(e)+"' is not a string");var n=jv(t)?t:uS(t),r=!Bv(i)&&i<e[_v]?i:e[_v];return MS(e,r-n[_v],r)===n})),Ny=wS("indexOf",Dv),Ly=AS("startsWith",Dv,(function(e,t,i){jv(e)||pS("'"+hS(e)+"' is not a string");var n=jv(t)?t:uS(t),r=i>0?i:0;return MS(e,r,r+n[_v])===n})),xy="ref",Fy="unref",Uy="hasRef";function By(e,t,i){var n=zv(t),r=n?t.length:0,s=(r>0?t[0]:n?mv:t)||setTimeout,a=(r>1?t[1]:mv)||clearTimeout,o=i[0];i[0]=function(){l.dn(),oy(o,mv,Lv[wv](arguments))};var l=function(e,t){var i,n=!0,r=e?t(fv):fv;function s(){return n=!1,r&&r[Fy]&&r[Fy](),i}function o(){r&&function(e){oy(a,mv,[e])}(r),r=fv}function l(){return r=t(r),n||s(),i}return(i={cancel:o,refresh:l})[Uy]=function(){return r&&r[Uy]?r[Uy]():n},i[xy]=function(){return n=!0,r&&r[xy]&&r[xy](),i},i[Fy]=s,{h:i=sS(i,"enabled",{get:function(){return!!r},set:function(e){!e&&r&&o(),e&&!r&&l()}}),dn:function(){r=fv}}}(e,(function(e){if(e){if(e.refresh)return e.refresh(),e;oy(a,mv,[e])}return oy(s,mv,i)}));return l.h}function Vy(e,t){return By(!0,mv,Lv[wv](arguments))}(GS()||{}).Symbol,(GS()||{}).Reflect;var Hy,$y=function(e,t){return($y=dv.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)};function jy(e,t){function i(){this.constructor=e}"function"!=typeof t&&null!==t&&pS("Class extends value "+String(t)+" is not a constructor or null"),$y(e,t),e[cv]=null===t?py(t):(i[cv]=t[cv],new i)}function Gy(e,t){for(var i=0,n=t.length,r=e.length;i<n;i++,r++)e[r]=t[i];return e}var qy="constructor",zy="prototype",Wy="function",Ky="_dynInstFuncs",Jy="_isDynProxy",Yy="_dynClass",Qy="_dynInstChk",Zy=Qy,Xy="_dfOpts",eC="_unknown_",tC="__proto__",iC="_dyn"+tC,nC="__dynProto$Gbl",rC="_dynInstProto",sC="useBaseInst",aC="setInstFuncs",oC=Object,lC=oC.getPrototypeOf,cC=oC.getOwnPropertyNames,dC=GS(),uC=dC[nC]||(dC[nC]={o:(Hy={},Hy[aC]=!0,Hy[sC]=!0,Hy),n:1e3});function hC(e){return e&&(e===oC[zy]||e===Array[zy])}function gC(e){return hC(e)||e===Function[zy]}function pC(e){var t;if(e){if(lC)return lC(e);var i=e[tC]||e[zy]||(e[qy]?e[qy][zy]:null);t=e[iC]||i,eS(e,iC)||(delete e[rC],t=e[iC]=e[rC]||e[iC],e[rC]=i)}return t}function mC(e,t){var i=[];if(cC)i=cC(e);else for(var n in e)"string"==typeof n&&eS(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function fC(e,t,i){return t!==qy&&typeof e[t]===Wy&&(i||eS(e,t))&&t!==tC&&t!==zy}function vC(e){pS("DynamicProto: "+e)}function SC(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function yC(e,t,i,n,r){if(!hC(e)){var s=i[Ky]=i[Ky]||py(null);if(!hC(s)){var a=s[t]=s[t]||py(null);!1!==s[Zy]&&(s[Zy]=!!r),hC(a)||mC(i,(function(t){fC(i,t,!1)&&i[t]!==n[t]&&(a[t]=i[t],delete i[t],(!eS(e,t)||e[t]&&!e[t][Jy])&&(e[t]=function(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&eS(i,Yy)){var s=e[Ky]||py(null);if((r=(s[i[Yy]]||py(null))[t])||vC("Missing ["+t+"] "+Wy),!r[Qy]&&!1!==s[Zy]){for(var a=!eS(e,t),o=pC(e),l=[];a&&o&&!gC(o)&&!SC(l,o);){var c=o[t];if(c){a=c===n;break}l.push(o),o=pC(o)}try{a&&(e[t]=r),r[Qy]=1}catch(e){s[Zy]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=pC(t)[e]),typeof n!==Wy&&vC("["+e+"] is not a "+Wy),n}(t,e,i)).apply(this,arguments)};return i[Jy]=1,i}(e,t)))}))}}}function CC(e,t){return eS(e,zy)?e.name||t||eC:((e||{})[qy]||{}).name||t||eC}function TC(e,t,i,n){eS(e,zy)||vC("theClass is an invalid class definition.");var r=e[zy];(function(e,t){if(lC){for(var i=[],n=pC(t);n&&!gC(n)&&!SC(i,n);){if(n===e)return!0;i.push(n),n=pC(n)}return!1}return!0})(r,t)||vC("["+CC(e)+"] not in hierarchy of ["+CC(t)+"]");var s=null;eS(r,Yy)?s=r[Yy]:(s="_dynCls$"+CC(e,"_")+"$"+uC.n,uC.n++,r[Yy]=s);var a=TC[Xy],o=!!a[sC];o&&n&&void 0!==n[sC]&&(o=!!n[sC]);var l=function(e){var t=py(null);return mC(e,(function(i){!t[i]&&fC(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[Jy]&&n){var s=e[Ky]||{};!1!==s[Zy]&&(r=(s[t[Yy]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var s=py(null);mC(i,(function(e){s[e]=r(t,i,e)}));for(var a=pC(e),o=[];a&&!gC(a)&&!SC(o,a);)mC(a,(function(e){!s[e]&&fC(a,e,!lC)&&(s[e]=r(t,a,e))})),o.push(a),a=pC(a);return s}(r,t,l,o));var c=!!lC&&!!a[aC];c&&n&&(c=!!n[aC]),yC(r,s,t,l,!1!==c)}TC[Xy]=uC.o;var EC,bC=function(e){return cS(e,1,0,CS)},_C=function(e){return function(e){var t={};return iS(e,(function(e,i){dS(t,e,i[1]),dS(t,i[0],i[1])})),CS(t)}(e)},IC=bC({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),wC="toLowerCase",AC="blkVal",PC="length",RC="rdOnly",MC="notify",DC="warnToConsole",kC="throwInternal",OC="setDf",NC="watch",LC="logger",xC="apply",FC="push",UC="splice",BC="hdlr",VC="cancel",HC="initialize",$C="identifier",jC="removeNotificationListener",GC="addNotificationListener",qC="isInitialized",zC="getNotifyMgr",WC="getPlugin",KC="pollInternalLogs",JC="name",YC="time",QC="processNext",ZC="getProcessTelContext",XC="enabled",eT="stopPollingInternalLogs",tT="unload",iT="onComplete",nT="version",rT="loggingLevelConsole",sT="createNew",aT="teardown",oT="messageId",lT="message",cT="isAsync",dT="diagLog",uT="_doTeardown",hT="update",gT="getNext",pT="setNextPlugin",mT="protocol",fT="userAgent",vT="split",ST="nodeType",yT="replace",CT="type",TT="handler",ET="status",bT="getResponseHeader",_T="getAllResponseHeaders",IT="isChildEvt",wT="data",AT="getCtx",PT="setCtx",RT="complete",MT="urlString",DT="sendPOST",kT="headers",OT="timeout",NT="setRequestHeader",LT="traceId",xT="spanId",FT="traceFlags",UT="Promise",BT="rejected";function VT(e,t){return HT(e,(function(e){return t?t({status:"fulfilled",rejected:!1,value:e}):e}),(function(e){return t?t({status:BT,rejected:!0,reason:e}):e}))}function HT(e,t,i,n){var r=e;try{if(Qv(e))(t||i)&&(r=e.then(t,i));else try{t&&(r=t(e))}catch(e){if(!i)throw e;r=i(e)}}finally{n&&function(e,t){t&&(Qv(e)?e.finally?e.finally(t):e.then((function(e){return t(),e}),(function(e){throw t(),e})):t())}(r,n)}return r}var $T,jT=["pending","resolving","resolved",BT],GT="dispatchEvent";function qT(e){var t;return e&&e.createEvent&&(t=e.createEvent("Event")),!!t&&t.initEvent}var zT,WT="unhandledRejection",KT=WT.toLowerCase(),JT=[],YT=0;function QT(e){return Gv(e)?e.toString():hS(e)}function ZT(e,t,i){var n,r,s=uy(arguments,3),a=0,o=!1,l=[],c=YT++,d=!1,u=null;function h(t,i){try{return JT.push(c),d=!0,u&&u.cancel(),u=null,e((function(e,r){l.push((function(){try{var s=2===a?t:i,o=Bv(s)?n:Gv(s)?s(n):s;Qv(o)?o.then(e,r):s?e(o):3===a?r(o):e(o)}catch(e){r(e)}})),o&&p()}),s)}finally{JT.pop()}}function g(){return jT[a]}function p(){if(l.length>0){var e=l.slice();l=[],d=!0,u&&u.cancel(),u=null,t(e)}}function m(e,t){return function(i){if(a===t){if(2===e&&Qv(i))return a=1,void i.then(m(2,1),m(3,1));a=e,o=!0,n=i,p(),d||3!==e||u||(u=Vy(f,10))}}}function f(){if(!d)if(d=!0,XS())process.emit(WT,n,r);else{var e=QS()||GS();!zT&&(zT=VS(xv(qS,[UT+"RejectionEvent"]).v)),function(e,t,i,n){var r=YS();!$T&&($T=VS(!!xv(qT,[r]).v));var s=$T.v?r.createEvent("Event"):n?new Event(t):{};if(i&&i(s),$T.v&&s.initEvent(t,!1,!0),s&&e[GT])e[GT](s);else{var a=e["on"+t];if(a)a(s);else{var o=qS("console");o&&(o.error||o.log)(t,hS(s))}}}(e,KT,(function(e){return oS(e,"promise",{g:function(){return r}}),e.reason=n,e}),!!zT.v)}}return sS(r={then:h,catch:function(e){return h(void 0,e)},finally:function(e){var t=e,i=e;return Gv(e)&&(t=function(t){return e&&e(),t},i=function(t){throw e&&e(),t}),h(t,i)}},"state",{get:g}),!LS&&BS(),!!((LS.lzy?0:WS)||ey()).v&&(r[iy(11)]="IPromise"),r.toString=function(){return"IPromise "+g()+(o?" - "+QT(n):"")},function(){Gv(i)||pS(UT+": executor is not a function - "+QT(i));var e=m(3,0);try{i.call(r,m(2,0),e)}catch(t){e(t)}}(),r}function XT(e){return function(t){var i=uy(arguments,1);return e((function(e,i){try{var n=[],r=1;ay(t,(function(t,s){t&&(r++,HT(t,(function(t){n[s]=t,0==--r&&e(n)}),i))})),0==--r&&e(n)}catch(e){i(e)}}),i)}}function eE(e,t){return ZT(eE,function(e){var t=Kv(e)?e:0;return function(e){Vy((function(){!function(e){cy(e,(function(e){try{e()}catch(e){}}))}(e)}),t)}}(t),e,t)}var tE,iE,nE=XT(eE),rE=function(e){return function(t){var i=uy(arguments,1);return Qv(t)?t:e((function(e){e(t)}),i)}}(eE),sE=function(e){return function(t){var i=uy(arguments,1);return e((function(e,i){i(t)}),i)}}(eE);function aE(e,t){!tE&&(tE=VS(xv(qS,[UT]).v||null));var i=tE.v;if(!i)return eE(e);Gv(e)||pS(UT+": executor is not a function - "+hS(e));var n=0,r=new i((function(t,i){e((function(e){n=2,t(e)}),(function(e){n=3,i(e)}))}));return sS(r,"state",{get:function(){return jT[n]}}),r}function oE(e,t){return!iE&&(iE=VS(aE)),iE.v.call(this,e,t)}var lE,cE,dE=XT(oE),uE="reject",hE="Rejected",gE=0,pE={};function mE(){}function fE(e,t,i){!pE[e]&&(pE[e]=vy(e));var n=Sy();return new pE[e]("Task [".concat(t.id,"] ").concat(i||"","- ").concat(t.st?"Running":"Waiting",": ").concat(function(e,t){return(e-t||"0")+" ms"}(n,t.st||t.cr)))}function vE(e,t){var i=Sy()-t;cy(e,(function(e){(e&&!e.rj&&e.st&&e.st<i||!e.st&&e.cr&&e.cr<i)&&e&&e[uE](e.rj||fE("Aborted",e,"Stale "))}))}function SE(e,t){var i=dy(e,t);-1!==i&&e.splice(i,1)}function yE(e,t){var i,n,r=[],s=[],a=6e5,o=a/10,l=0,c=(t?t+".":"")+gE++;e=e||oE;var d=function(){var e=Dy(r)+Dy(s)>0;a>0&&(n||(n=Vy((function(){vE(r,a),vE(s,a),n&&(n.enabled=Dy(r)+Dy(s)>0)}),o)).unref(),n&&(n.enabled=e))},u=function(e,t){return e.st=Sy(),r.push(e),d(),function(i,n){var r=function(t){e.rj=e.rj||t||fE(hE,e),e[uE]=mE,g(e),i=null,n&&n(t),n=null},s=e.id;if(e.rj)r(e.rj);else{e[uE]=r;try{var a=t(s);e.to&&Qv(a)&&(e.t=Vy((function(){r(fE("Timeout",e))}),e.to)),HT(a,(function(t){g(e);try{i&&i(t)}catch(e){n&&n(e)}n=null,i=null}),r)}catch(e){r(e)}}}},h=function(t,i,n){return s.push(t),d(),e((function(e,r){VT(i.p,(function(){SE(s,t),u(t,n)(e,r)}))}))},g=function(e){SE(r,e),e.t&&e.t.cancel(),e.t=null,i&&i===e&&(i=null,Dy(r)+Dy(s)===0&&(n&&n.cancel(),n=null))},p={idle:!0,queue:function(t,n,r){var s,a=c+"."+l++;n&&(a+="-("+n+")");var o=((s={id:a,cr:Sy(),to:r})[uE]=function(e){o.rj=e||fE(hE,o),o[uE]=mE},s);return o.p=i?h(o,i,t):e(u(o,t)),i=o,o.p},setStaleTimeout:function(e,t){n&&n.cancel(),n=null,a=e,o=t||e/10,d()}};return oS(p,"idle",{g:function(){return Dy(r)+Dy(s)===0}}),function(e,t,i){cE=cE||{toString:function(){return"[[SchedulerState]]"}},sS(e,lE=lE||{toString:function(){return"[[SchedulerName]]"}},{get:function(){return c}}),sS(e,cE,{get:i})}(p,0,(function(){return{l:i,r,w:s}})),p}iy(11);var CE=void 0,TE="",EE="channels",bE="core",_E="createPerfMgr",IE="disabled",wE="extensionConfig",AE="extensions",PE="processTelemetry",RE="priority",ME="eventsSent",DE="eventsDiscarded",kE="eventsSendRequest",OE="perfEvent",NE="offlineEventsStored",LE="offlineBatchSent",xE="offlineBatchDrop",FE="getPerfMgr",UE="domain",BE="path",VE=/-([a-z])/g,HE=/([^\w\d_$])/g,$E=/^(\d+[\w\d_$])/;function jE(e){return!Vv(e)}function GE(e){var t=e;return t&&jv(t)&&(t=(t=(t=t[yT](VE,(function(e,t){return t.toUpperCase()})))[yT](HE,"_"))[yT]($E,(function(e,t){return"_"+t}))),t}function qE(e,t){return!(!e||!t)&&-1!==Ny(e,t)}function zE(e){return e&&e.toISOString()||""}function WE(e){return Yv(e)?e[JC]:TE}function KE(e,t,i,n,r){var s=i;return e&&((s=e[t])===i||r&&!r(s)||n&&!n(i)||(s=i,e[t]=s)),s}function JE(e,t,i,n,r){e&&t&&i&&(!1!==r||Bv(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return Gv(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][xC](n,e)}}(i,n))}function YE(e,t,i,n){return e&&t&&qv(e)&&zv(i)&&cy(i,(function(i){jv(i)&&JE(e,i,t,i,n)})),e}function QE(e){return e&&fS&&(e=dv(fS({},e))),e}function ZE(e,t,i,n,r,s){var a=arguments,o=a[0]||{},l=a[PC],c=!1,d=1;for(l>0&&Jv(o)&&(c=o,o=a[d]||{},d++),qv(o)||(o={});d<l;d++){var u=a[d],h=zv(u),g=qv(u);for(var p in u)if(h&&p in u||g&&tS(u,p)){var m=u[p],f=void 0;if(c&&m&&((f=zv(m))||_y(m))){var v=o[p];f?zv(v)||(v=[]):_y(v)||(v={}),m=ZE(c,v,m)}void 0!==m&&(o[p]=m)}}return o}function XE(e){try{return e.responseText}catch(e){}return null}function eb(e,t){return e?"XMLHttpRequest,Status:"+e[ET]+",Response:"+XE(e)||0:t}function tb(e,t){return t&&(Kv(t)?e=[t].concat(e):zv(t)&&(e=t.concat(e))),e}var ib="withCredentials";function nb(e,t,i){if(!e[i]&&t&&t[bT]){var n=t[bT](i);n&&(e[i]=by(n))}return e}function rb(e,t){var i={};return e[_T]?i=function(e){var t={};return jv(e)&&cy(by(e)[vT](/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=by(e.substring(0,i))[wC](),r=by(e.substring(i+1));t[n]=r}else t[by(e)]=1}})),t}(e[_T]()):t&&(i=nb(i,e,"time-delta-millis"),i=nb(i,e,"kill-duration"),i=nb(i,e,"kill-duration-seconds")),i}var sb="JSON",ab="XMLHttpRequest",ob=null,lb=null,cb=null,db=null;function ub(e,t){var i=!1;if(e){try{if(!(i=t in e)){var n=e[cv];n&&(i=t in n)}}catch(e){}if(!i)try{i=!Bv((new e)[t])}catch(e){}}return i}function hb(e){return typeof location===ov&&location?location:qS("location")}function gb(){return Boolean(typeof JSON===ov&&JSON||null!==qS(sb))}function pb(){var e=ZS();return!(!e||!e.product)&&"ReactNative"===e.product}function mb(){var e=ZS();if(e&&(e[fT]!==lb||null===ob)){var t=((lb=e[fT])||TE)[wC]();ob=qE(t,"msie")||qE(t,"trident/")}return ob}function fb(e){return null!==db&&!1!==e||(db=!!ZS()&&Boolean(ZS().sendBeacon)),db}function vb(e){var t=!1;try{t=!!qS("fetch");var i=qS("Request");t&&e&&i&&(t=ub(i,"keepalive"))}catch(e){}return t}function Sb(){var e=!1;try{e=!!qS(ab)}catch(e){}return e}var yb=4294967296,Cb=4294967295,Tb=123456789,Eb=987654321,bb=!1,_b=Tb,Ib=Eb;function wb(e){var t=0,i=qS("crypto")||qS("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&Cb),0===t&&mb()&&(bb||function(){try{var e=2147483647&Sy();!function(e){e<0&&(e>>>=0),_b=Tb+e&Cb,Ib=Eb-e&Cb,bb=!0}((Math.random()*yb^e)+e)}catch(e){}}(),t=function(){var e=((Ib=36969*(65535&Ib)+(Ib>>16)&Cb)<<16)+(65535&(_b=18e3*(65535&_b)+(_b>>16)&Cb))>>>0&Cb;return e>>>=0}()&Cb),0===t&&(t=Math.floor(yb*Math.random()|0)),e||(t>>>=0),t}function Ab(e){void 0===e&&(e=22);for(var t=wb()>>>0,i=0,n=TE;n[PC]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(wb()<<2&4294967295|3&t)>>>0,i=0);return n}var Pb="3.2.1",Rb="."+Ab(6),Mb=0;function Db(e){return 1===e[ST]||9===e[ST]||!+e[ST]}function kb(e,t){return void 0===t&&(t=!1),GE(e+Mb+++(t?"."+Pb:TE)+Rb)}function Ob(e){var t={id:kb("_aiData-"+(e||TE)+"."+Pb),accept:function(e){return Db(e)},get:function(e,i,n,r){var s=e[t.id];return s?s[GE(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{Db(t)&&oS(t,e.id,{e:!1,v:i})}catch(e){}}return i}(t,e))[GE(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return t}function Nb(e){return e&&qv(e)&&(e.isVal||e.fb||tS(e,"v")||tS(e,"mrg")||tS(e,"ref")||e.set)}function Lb(e,t,i){var n,r=i.dfVal||Hv;if(t&&i.fb){var s=i.fb;zv(s)||(s=[s]);for(var a=0;a<s[PC];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,uS(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function xb(e,t,i){var n,r=i;return i&&Nb(i)&&(r=Lb(e,t,i)),r&&(Nb(r)&&(r=xb(e,t,r)),zv(r)?(n=[])[PC]=r[PC]:_y(r)&&(n={}),n&&(iS(r,(function(i,r){r&&Nb(r)&&(r=xb(e,t,r)),n[i]=r})),r=n)),r}function Fb(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;Nb(h)?(r=h.isVal,s=h.set,c=h[RC],d=h[AC],o=h.mrg,!(l=h.ref)&&Bv(l)&&(l=!!o),a=Lb(e,t,h)):a=n,d&&e[AC](t,i);var g=!0,p=t[i];!p&&Vv(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?xb(e,t,a):a:(_y(u)||zv(a))&&o&&a&&(_y(a)||zv(a))&&iS(a,(function(t,i){Fb(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[RC](t,i)}var Ub=ry("[[ai_dynCfg_1]]"),Bb=ry("[[ai_blkDynCfg_1]]"),Vb=ry("[[ai_frcDynCfg_1]]");function Hb(e){var t;return e&&(zv(e)?(t=[])[PC]=e[PC]:_y(e)&&(t={}),t)?(iS(e,(function(e,i){t[e]=Hb(i)})),t):e}function $b(e){if(e){var t=e[Ub]||e;if(t.cfg&&(t.cfg===e||t.cfg[Ub]===t))return t}return null}function jb(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[Vb])||i[Bb]||(n=_y(i)||zv(i))),n}function Gb(e){pS("InvalidAccess:"+e)}var qb=["push","pop","shift","unshift","splice"],zb=function(e,t,i,n){e&&e[kC](3,108,"".concat(i," [").concat(t,"] failed - ")+hS(n))};function Wb(e,t){var i=Xv(e,t);return i&&i.get}function Kb(e,t,i,n){if(t){var r=Wb(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===dy(r.h,t)&&r.h[FC](t),e.trk(t,r))},clr:function(e){var t=dy(r.h,e);-1!==t&&r.h[UC](t,1)}},s=!0,a=!1;function o(){s&&(a=a||jb(o,e,n),n&&!n[Ub]&&a&&(n=Yb(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},oS(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&Gb("["+i+"] is read-only:"+hS(t)),s&&(a=a||jb(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){iS(n,(function(e){n[e]=l?l[e]:CE}));try{iS(l,(function(t,i){Kb(e,n,t,i)})),l=n}catch(t){zb((e.hdlr||{})[LC],i,"Assigning",t),a=!1}}else n&&n[Ub]&&iS(n,(function(t){var i=Wb(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&jb(o,e,l);!c&&d&&(l=Yb(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function Jb(e,t,i,n){if(t){var r=Wb(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(_y(e)||zv(e)))try{e[Bb]=!0}catch(e){}}(t)}catch(t){zb((e.hdlr||{})[LC],i,"Blocking",t)}try{Kb(e,t,i,t[i]),r=Wb(t,i)}catch(t){zb((e.hdlr||{})[LC],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function Yb(e,t,i,n){try{iS(t,(function(i,n){Kb(e,t,i,n)})),t[Ub]||(sS(t,Ub,{get:function(){return e[BC]}}),function(e,t,i){zv(t)&&cy(qb,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[xC](this,n);return Yb(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){zb((e.hdlr||{})[LC],i,n,t)}return t}var Qb="[[ai_",Zb="]]";function Xb(e,t,i){var n,r=$b(t);if(r)return r;var s,a=kb("dyncfg",!0),o=t&&!1!==i?t:Hb(t),l=((n={uid:null,cfg:o})[LC]=e,n[MC]=function(){s[MC]()},n.set=function(t,i,n){try{t=Kb(s,t,i,n)}catch(t){zb(e,i,"Setting value",t)}return t[i]},n[OC]=function(e,t){return t&&iS(t,(function(t,i){Fb(l,e,t,i)})),e},n[NC]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return oS(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return Jb(s,e,t,(i={},i[0]=!0,i))[t]},n[RC]=function(e,t){var i;return Jb(s,e,t,(i={},i[1]=!0,i))[t]},n[AC]=function(e,t){var i;return Jb(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Bv(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return oS(l,"uid",{c:!1,e:!1,w:!1,v:a}),Yb(s=function(e){var t,i,n=ny(Qb+"get"+e.uid+Zb),r=ny(Qb+"ro"+e.uid+Zb),s=ny(Qb+"rf"+e.uid+Zb),a=ny(Qb+"blkVal"+e.uid+Zb),o=ny(Qb+"dtl"+e.uid+Zb),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(cy(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[OC].bind(e),ref:e.ref.bind(e),rdOnly:e[RC].bind(e)})}catch(t){var s=e[LC];throw s&&s[kC](1,107,hS(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c[VC](),c=null;var t=[];if(cy(e,(function(e){if(e&&(e[o]&&(cy(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[FC](e)}})),l)try{u()}catch(e){t[FC](e)}t[PC]>0&&function(e,t){EC||(EC=vy("AggregationError",(function(e,t){t[PC]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw cy(t,(function(e,t){i+="\n".concat(t," > ").concat(hS(e))})),new EC(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[AC]=a,t[BC]=e,t.add=function(e){if(e&&e.h[PC]>0){l||(l=[]),c||(c=Vy((function(){c=null,u()}),0));for(var t=0;t<e.h[PC];t++){var i=e.h[t];i&&-1===dy(l,i)&&l[FC](i)}}},t[MC]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===dy(i,t)&&i[FC](t)}},i=t}(l),o,"config","Creating"),l}function e_(e,t,i,n){var r=Xb(i,e||{},n);return t&&r[OC](r.cfg,t),r}function t_(e,t,i){var n=e[Ub]||e;return!n.cfg||n.cfg!==e&&n.cfg[Ub]!==n?(function(e,t){e?(e[DC](t),e[kC](2,108,t)):Gb(t)}(i,"Not dynamic - "+hS(e)),e_(e,null,i)[NC](t)):n[NC](t)}function i_(e,t){if(e&&e[tT])return e[tT](t)}function n_(e,t,i){var n;return i||(n=oE((function(e){i=e}))),e&&Dy(e)>0?VT(i_(e[0],t),(function(){n_(uy(e,1),t,i)})):i(),n}var r_="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function s_(e){return{mrg:!0,v:e}}function a_(e){return{isVal:jv,v:uS(e||TE)}}var o_,l_,c_=[ME,DE,kE,OE],d_=null;function u_(e,t){return function(){var i=arguments,n=h_(t);if(n){var r=n.listener;r&&r[e]&&r[e][xC](r,i)}}}function h_(e){var t=d_;return t||!0===e.disableDbgExt||(t=d_||function(){var e=qS("Microsoft");return e&&(d_=e.ApplicationInsights),d_}()),t?t.ChromeDbgExt:null}var g_="warnToConsole",p_={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},m_=((l_={})[0]=null,l_[1]="errorToConsole",l_[2]=g_,l_[3]="debugToConsole",l_);function f_(e){return e?'"'+e[yT](/\"/g,TE)+'"':TE}function v_(e,t){var i=typeof console!==lv?console:qS("console");if(i){var n="log";i[e]&&(n=e),Gv(i[n])&&i[n](t)}}var S_=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[oT]=e,r[lT]=(i?"AI: ":"AI (Internal): ")+e;var s=TE;gb()&&(s=(gb()?JSON||qS(sb):null).stringify(n));var a=(t?" message:"+f_(t):TE)+(n?" props:"+f_(s):TE);r[lT]+=a}return e.dataType="MessageData",e}();function y_(e,t){return(e||{})[LC]||new E_(t)}var C_,T_,E_=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};TC(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[oT];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[FC](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new S_(23,c,!1);e.queue[FC](u),1===t?e.errorToConsole(c):e[DC](c)}}}function d(e,i){var n=h_(t||{});n&&n[dT]&&n[dT](e,i)}a=function(t){return t_(e_(t,p_,e).cfg,(function(e){var t=e.cfg;i=t[rT],n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[kC]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new S_(n,r,o,a);if(s)throw hS(u);var h=m_[t]||g_;if(Bv(u[lT]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[oT];!l[g]&&i>=t&&(e[h](u[lT]),l[g]=!0)}else i>=t&&e[h](u[lT]);c(t,u)}},e.debugToConsole=function(e){v_("debug",e),d("warning",e)},e[DC]=function(e){v_("warn",e),d("warning",e)},e.errorToConsole=function(e){v_("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[tT]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function b_(e){return e||new E_}function __(e,t,i,n,r,s){void 0===s&&(s=!1),b_(e)[kC](t,i,n,r,s)}function I_(e,t){b_(e)[DC](t)}var w_,A_="toGMTString",P_="toUTCString",R_="cookie",M_="expires",D_="isCookieUseDisabled",k_="disableCookiesUsage",O_="_ckMgr",N_=null,L_=null,x_=null,F_={},U_={},B_=((C_={cookieCfg:s_((T_={},T_[UE]={fb:"cookieDomain",dfVal:jE},T_.path={fb:"cookiePath",dfVal:jE},T_.enabled=CE,T_.ignoreCookies=CE,T_.blockedCookies=CE,T_)),cookieDomain:CE,cookiePath:CE})[k_]=CE,C_);function V_(){!w_&&(w_=function(){var e={};return!LS&&BS(),e.b=LS.lzy,sS(e,"v",{configurable:!0,get:function(){var t=YS();return LS.lzy||sS(e,"v",{value:t}),e.b=LS.lzy,t}}),e}())}function H_(e){return!e||e.isEnabled()}function $_(e,t){return!!(t&&e&&zv(e.ignoreCookies))&&-1!==dy(e.ignoreCookies,t)}function j_(e,t){var i=t[XC];if(Vv(i)){var n=void 0;Bv(e[D_])||(n=!e[D_]),Bv(e[k_])||(n=!e[k_]),i=n}return i}function G_(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=t.cookieCfg;i=n&&n[O_]?n[O_]:q_(t)}return i||(i=function(e,t){var i=q_[O_]||U_[O_];return i||(i=q_[O_]=q_(e,t),U_[O_]=i),i}(t,(e||{})[LC])),i}function q_(e,t){var i,n,r,s,a,o,l,c,d;e=e_(e||U_,null,t).cfg,a=t_(e,(function(t){t[OC](t.cfg,B_),n=t.ref(t.cfg,"cookieCfg"),r=n[BE]||"/",s=n[UE],o=!1!==j_(e,n),l=n.getCookie||Y_,c=n.setCookie||Q_,d=n.delCookie||Q_}),t);var u=((i={isEnabled:function(){var i=!1!==j_(e,n)&&o&&z_(t),r=U_[O_];return i&&r&&u!==r&&(i=H_(r)),i},setEnabled:function(e){o=!1!==e,n[XC]=e},set:function(e,t,i,a,o){var l=!1;if(H_(u)&&!function(e,t){return!!(t&&e&&zv(e.blockedCookies)&&-1!==dy(e.blockedCookies,t))||$_(e,t)}(n,e)){var d={},h=by(t||TE),g=Ny(h,";");if(-1!==g&&(h=by(kS(t,g)),d=W_(MS(t,g+1))),KE(d,UE,a||s,Zv,Bv),!Vv(i)){var p=mb();if(Bv(d[M_])){var m=Sy()+1e3*i;if(m>0){var f=new Date;f.setTime(m),KE(d,M_,K_(f,p?A_:P_)||K_(f,p?A_:P_)||TE,Zv)}}p||KE(d,"max-age",TE+i,null,Bv)}var v=hb();v&&"https:"===v[mT]&&(KE(d,"secure",null,null,Bv),null===L_&&(L_=!function(e){return!(!jv(e)||!qE(e,"CPU iPhone OS 12")&&!qE(e,"iPad; CPU OS 12")&&!(qE(e,"Macintosh; Intel Mac OS X 10_14")&&qE(e,"Version/")&&qE(e,"Safari"))&&(!qE(e,"Macintosh; Intel Mac OS X 10_14")||!Oy(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!qE(e,"Chrome/5")&&!qE(e,"Chrome/6")&&(!qE(e,"UnrealEngine")||qE(e,"Chrome"))&&!qE(e,"UCBrowser/12")&&!qE(e,"UCBrowser/11"))}((ZS()||{})[fT])),L_&&KE(d,"SameSite","None",null,Bv)),KE(d,BE,o||r,null,Bv),c(e,J_(h,d)),l=!0}return l},get:function(e){var t=TE;return H_(u)&&!$_(n,e)&&(t=l(e)),t},del:function(e,t){var i=!1;return H_(u)&&(i=u.purge(e,t)),i},purge:function(e,i){var n,r=!1;if(z_(t)){var s=((n={})[BE]=i||"/",n[M_]="Thu, 01 Jan 1970 00:00:01 GMT",n);mb()||(s["max-age"]="0"),d(e,J_(TE,s)),r=!0}return r}})[tT]=function(e){a&&a.rm(),a=null},i);return u[O_]=u,u}function z_(e){if(null===N_){N_=!1,!w_&&V_();try{var t=w_.v||{};N_=void 0!==t[R_]}catch(t){__(e,2,68,"Cannot access document.cookie - "+WE(t),{exception:hS(t)})}}return N_}function W_(e){var t={};return e&&e[PC]&&cy(by(e)[vT](";"),(function(e){if(e=by(e||TE)){var i=Ny(e,"=");-1===i?t[e]=null:t[by(kS(e,i))]=by(MS(e,i+1))}})),t}function K_(e,t){return Gv(e[t])?e[t]():null}function J_(e,t){var i=e||TE;return iS(t,(function(e,t){i+="; "+e+(Vv(t)?TE:"="+t)})),i}function Y_(e){var t=TE;if(!w_&&V_(),w_.v){var i=w_.v[R_]||TE;x_!==i&&(F_=W_(i),x_=i),t=by(F_[e]||TE)}return t}function Q_(e,t){!w_&&V_(),w_.v&&(w_.v[R_]=e+"="+t)}var Z_={perfEvtsSendAll:!1};function X_(e){e.h=null;var t=e.cb;e.cb=[],cy(t,(function(e){xv(e.fn,[e.arg])}))}function eI(e,t,i,n){cy(e,(function(e){e&&e[t]&&(i?(i.cb[FC]({fn:n,arg:e}),i.h=i.h||Vy(X_,0,i)):xv(n,[e]))}))}var tI=function(){function e(t){var i,n;this.listeners=[];var r=[],s={h:null,cb:[]},a=e_(t,Z_);n=a[NC]((function(e){i=!!e.cfg.perfEvtsSendAll})),TC(e,this,(function(e){oS(e,"listeners",{g:function(){return r}}),e[GC]=function(e){r[FC](e)},e[jC]=function(e){for(var t=dy(r,e);t>-1;)r[UC](t,1),t=dy(r,e)},e[ME]=function(e){eI(r,ME,s,(function(t){t[ME](e)}))},e[DE]=function(e,t){eI(r,DE,s,(function(i){i[DE](e,t)}))},e[kE]=function(e,t){eI(r,kE,t?s:null,(function(i){i[kE](e,t)}))},e[OE]=function(e){e&&(!i&&e[IT]()||eI(r,OE,null,(function(t){e[cT]?Vy((function(){return t[OE](e)}),0):t[OE](e)})))},e[NE]=function(e){e&&e[PC]&&eI(r,NE,s,(function(t){t[NE](e)}))},e[LE]=function(e){e&&e[wT]&&eI(r,LE,s,(function(t){t[LE](e)}))},e[xE]=function(e,t){if(e>0){var i=t||0;eI(r,xE,s,(function(t){t[xE](e,i)}))}},e[tT]=function(e){var t,i=function(){n&&n.rm(),n=null,r=[],s.h&&s.h[VC](),s.h=null,s.cb=[]};if(eI(r,"unload",null,(function(i){var n=i[tT](e);n&&(t||(t=[]),t[FC](n))})),t)return oE((function(e){return VT(dE(t),(function(){i(),e()}))}));i()}}))}return e.__ieDyn=1,e}(),iI="ctx",nI="ParentContextKey",rI="ChildrenContextKey",sI=function(){function e(t,i,n){var r,s=this;s.start=Sy(),s[JC]=t,s[cT]=n,s[IT]=function(){return!1},Gv(i)&&oS(s,"payload",{g:function(){return!r&&Gv(i)&&(r=i(),i=null),r}}),s[AT]=function(t){return t?t===e[nI]||t===e[rI]?s[t]:(s[iI]||{})[t]:null},s[PT]=function(t,i){t&&(t===e[nI]?(s[t]||(s[IT]=function(){return!0}),s[t]=i):t===e[rI]?s[t]=i:(s[iI]=s[iI]||{})[t]=i)},s[RT]=function(){var t=0,i=s[AT](e[rI]);if(zv(i))for(var n=0;n<i[PC];n++){var r=i[n];r&&(t+=r[YC])}s[YC]=Sy()-s.start,s.exTime=s[YC]-t,s[RT]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),aI=function(){function e(t){this.ctx={},TC(e,this,(function(e){e.create=function(e,t,i){return new sI(e,t,i)},e.fire=function(e){e&&(e[RT](),t&&Gv(t[OE])&&t[OE](e))},e[PT]=function(t,i){t&&((e[iI]=e[iI]||{})[t]=i)},e[AT]=function(t){return(e[iI]||{})[t]}}))}return e.__ieDyn=1,e}(),oI="CoreUtils.doPerf";function lI(e,t,i,n,r){if(e){var s=e;if(s[FE]&&(s=s[FE]()),s){var a=void 0,o=s[AT](oI);try{if(a=s.create(t(),n,r)){if(o&&a[PT]&&(a[PT](sI[nI],o),o[AT]&&o[PT])){var l=o[AT](sI[rI]);l||(l=[],o[PT](sI[rI],l)),l[FC](a)}return s[PT](oI,a),i(a)}}catch(e){a&&a[PT]&&a[PT]("exception",e)}finally{a&&s.fire(a),s[PT](oI,o)}}}return i()}function cI(){var e=dI();return MS(e,0,8)+"-"+MS(e,8,12)+"-"+MS(e,12,16)+"-"+MS(e,16,20)+"-"+MS(e,20)}function dI(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=TE,n=0;n<4;n++)i+=t[15&(e=wb())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&wb())|0];return DS(i,0,8)+DS(i,9,4)+"4"+DS(i,13,3)+r+DS(i,16,3)+DS(i,19,12)}function uI(e,t,i){return!(!e||e[PC]!==t||e===i||!e.match(/^[\da-f]*$/i))}function hI(e){return uI(e,32,"00000000000000000000000000000000")}function gI(e){return uI(e,16,"0000000000000000")}var pI=Ob("plugin");function mI(e){return pI.get(e,"state",{},!0)}function fI(e,t){for(var i,n=[],r=null,s=e[gT]();s;){var a=s[WC]();if(a){r&&r[pT]&&a[PE]&&r[pT](a);var o=!!(i=mI(a))[qC];a[qC]&&(o=a[qC]()),o||n[FC](a),r=a,s=s[gT]()}}cy(n,(function(n){var r=e[bE]();n[HC](e.getCfg(),r,t,e[gT]()),i=mI(n),n[bE]||i[bE]||(i[bE]=r),i[qC]=!0,delete i[aT]}))}function vI(e){return e.sort((function(e,t){var i=0;if(t){var n=t[PE];e[PE]?i=n?e[RE]-t[RE]:1:n&&(i=-1)}else i=e?1:-1;return i}))}var SI,yI="_hasRun",CI="_getTelCtx",TI=0;function EI(e,t,i,n){var r=null,s=[];t||(t=e_({},null,i[LC])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[WC]()===i)return e;e=e[gT]()}return wI([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[gT]():null,!e){var t=s;t&&t[PC]>0&&(cy(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){__(i[LC],2,73,"Unexpected Exception during onComplete - "+hS(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return y_(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&iS(i,(function(e,i){if(Vv(n[e])){var r=t.cfg[e];!r&&Vv(r)||(n[e]=r)}Fb(t,n,e,i)})),t[OC](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Vv(s[i])?!a[i]&&Vv(a[i])||(r=a[i]):r=s[i],r||!Vv(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[WC]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[FC]({func:e,self:Bv(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[wE];!s&&i&&(s={}),r[wE]=s,(s=t.ref(r,wE))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function bI(e,t,i,n){var r=e_(t),s=EI(e,r,i,n),a=s.ctx;return a[QC]=function(e){var t=s._next();return t&&t[PE](e,a),!t},a[sT]=function(e,t){return void 0===e&&(e=null),zv(e)&&(e=wI(e,r.cfg,i,t)),bI(e||a[gT](),r.cfg,i,t)},a}function _I(e,t,i){var n=e_(t.config),r=EI(e,n,t,i),s=r.ctx;return s[QC]=function(e){var t=r._next();return t&&t[tT](s,e),!t},s[sT]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=wI(e,n.cfg,t,i)),_I(e||s[gT](),t,i)},s}function II(e,t,i){var n=e_(t.config),r=EI(e,n,t,i).ctx;return r[QC]=function(e){return r.iterate((function(t){Gv(t[hT])&&t[hT](r,e)}))},r[sT]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=wI(e,n.cfg,t,i)),II(e||r[gT](),t,i)},r}function wI(e,t,i,n){var r=null,s=!n;if(zv(e)&&e[PC]>0){var a=null;cy(e,(function(e){if(s||n!==e||(s=!0),s&&e&&Gv(e[PE])){var o=function(e,t,i){var n,r=null,s=Gv(e[PE]),a=Gv(e[pT]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=mI(e);return!n[aT]&&!n[IE]&&(a&&e[pT](r),e[PE](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[QC](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=mI(e),s=e[bE]||r[bE];!e||s&&s!==t.core()||r[aT]||(r[bE]=null,r[aT]=!0,r[qC]=!1,e[aT]&&!0===e[aT](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[cT])||t[QC](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=mI(e),s=e[bE]||r[bE];!e||s&&s!==t.core()||r[aT]||e[hT]&&!0===e[hT](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[QC](i)},_id:n=e?e[$C]+"-"+e[RE]+"-"+TI++:"Unknown-0-"+TI++,_setNext:function(e){r=e}};function l(){var n;return e&&Gv(e[CI])&&(n=e[CI]()),n||(n=bI(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[$C]:"TelemetryPluginChain",d=t[yI];return d||(d=t[yI]={}),t.setNext(r),e&&lI(t[bE](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:TE;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||__(t[dT](),1,73,"Plugin ["+c+"] failed during "+s+" - "+hS(e)+", run flags: "+hS(d))}}),a,o),l}return CS(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?wI([n],t,i):r}function AI(){var e=[];return{add:function(t){t&&e[FC](t)},run:function(t,i){cy(e,(function(e){try{e(t,i)}catch(e){__(t[dT](),2,73,"Unexpected error calling unload handler - "+hS(e))}})),e=[]}}}function PI(){var e=[];return{run:function(t){var i=e;e=[],cy(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){__(t,2,73,"Unloading:"+hS(e))}}))},add:function(t){t&&ly(e,t)}}}var RI,MI="getPlugin",DI=((SI={})[wE]={isVal:jE,v:{}},SI),kI=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||bI(null,{},a[bE]);t=n&&n[MI]?r[sT](null,n[MI]):r[sT](null,n)}return t}function l(e,t,r){e_(e,DI,y_(t)),!r&&t&&(r=t[ZC]()[gT]());var s=n;n&&n[MI]&&(s=n[MI]()),a[bE]=t,i=bI(r,e,t,s)}function c(){t=!1,a[bE]=null,i=null,n=null,s=PI(),r=AI()}c(),TC(e,a,(function(e){e[HC]=function(e,i,n,r){l(e,i,r),t=!0},e[aT]=function(t,i){var a,o=e[bE];if(o&&(!t||o===t[bE]())){var l,d=!1,u=t||_I(null,o,n&&n[MI]?n[MI]():n),h=i||((a={reason:0})[cT]=!1,a);return e[uT]&&!0===e[uT](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[dT]()),!0===l&&u[QC](h),c())}},e[hT]=function(t,i){var r=e[bE];if(r&&(!t||r===t[bE]())){var s,a=!1,o=t||II(null,r,n&&n[MI]?n[MI]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[gT]()))}},JE(e,"_addUnloadCb",(function(){return r}),"add"),JE(e,"_addHook",(function(){return s}),"add"),oS(e,"_unloadHooks",{g:function(){return s}})})),a[dT]=function(e){return o(e)[dT]()},a[qC]=function(){return t},a.setInitialized=function(e){t=e},a[pT]=function(e){n=e},a[QC]=function(e,t){t?t[QC](e):n&&Gv(n[PE])&&n[PE](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),OI=function(e){function t(){var i,n,r=e.call(this)||this;function s(){i=0,n=[]}return r.identifier="TelemetryInitializerPlugin",r.priority=199,s(),TC(t,r,(function(e,t){e.addTelemetryInitializer=function(e){return function(e,t,i){var n={id:t,fn:i};return ly(e,n),{remove:function(){cy(e,(function(t,i){if(t.id===n.id)return e[UC](i,1),-1}))}}}(n,i++,e)},e[PE]=function(t,i){(function(e,t,i){for(var n=!1,r=e[PC],s=0;s<r;++s){var a=e[s];if(a)try{if(!1===a.fn[xC](null,[t])){n=!0;break}}catch(e){__(i,2,64,"Telemetry initializer failed: "+WE(e),{exception:hS(e)},!0)}}return!n})(n,t,i?i[dT]():e[dT]())&&e[QC](t,i)},e[uT]=function(){s()}})),r}return jy(t,e),t.__ieDyn=1,t}(kI),NI="Plugins must provide initialize method",LI="SDK is still unloading...",xI=SS(((RI={cookieCfg:{}})[AE]={rdOnly:!0,ref:!0,v:[]},RI[EE]={rdOnly:!0,ref:!0,v:[]},RI[wE]={ref:!0,v:{}},RI[_E]=CE,RI.loggingLevelConsole=0,RI.diagnosticLogInterval=CE,RI));function FI(e,t){return new aI(t)}function UI(e,t){var i=!1;return cy(t,(function(t){if(t===e)return i=!0,-1})),i}function BI(e,t,i,n){i&&iS(i,(function(i,r){n&&_y(r)&&_y(t[i])&&BI(e,t[i],r,n),n&&_y(r)&&_y(t[i])?BI(e,t[i],r,n):e.set(t,i,r)}))}function VI(e,t){var i=null,n=-1;return cy(e,(function(e,r){if(e.w===t)return i=e,n=r,-1})),{i:n,l:i}}var HI=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P;TC(e,this,(function(e){function R(e){return w&&w[XC]||P||(e||n&&n.queue[PC]>0)&&(A||(A=!0,j(t[NC]((function(e){var t=e.cfg.diagnosticLogInterval;t&&t>0||(t=1e4);var i=!1;w&&(i=w[XC],w[VC]()),(w=function(e,t){return By(!1,mv,Lv[wv](arguments))}(F,t)).unref(),w[XC]=i})))),w[XC]=!0),w}function M(){var e={};_=[];var t=function(t){t&&cy(t,(function(t){if(t[$C]&&t[nT]&&!e[t.identifier]){var i=t[$C]+"="+t[nT];_[FC](i),e[t.identifier]=t}}))};t(h),u&&cy(u,(function(e){t(e)})),t(d)}function D(){i=!1,(t=e_({},xI,e[LC])).cfg[rT]=1,oS(e,"config",{g:function(){return t.cfg},s:function(t){e.updateCfg(t,!1)}}),oS(e,"pluginVersionStringArr",{g:function(){return _||M(),_}}),oS(e,"pluginVersionString",{g:function(){return I||(_||M(),I=_.join(";")),I||TE}}),oS(e,"logger",{g:function(){return n||(n=new E_(t.cfg),t[LC]=n),n},s:function(e){t[LC]=e,n!==e&&(i_(n,!1),n=e)}}),e[LC]=new E_(t.cfg),b=[];var y=e.config[AE]||[];y.splice(0,y[PC]),ly(y,b),p=new OI,r=[],i_(s,!1),s=null,a=null,o=null,i_(l,!1),l=null,c=null,d=[],u=null,h=null,g=!1,m=null,f=kb("AIBaseCore",!0),v=AI(),C=null,T=null,S=PI(),E=[],I=null,_=null,P=!1,w=null,A=!1}function k(){var i=bI(L(),t.cfg,e);return i[iT](R),i}function O(t){var i=function(e,t,i){var n,r=[],s=[],a={};return cy(i,(function(t){(Vv(t)||Vv(t[HC]))&&gS(NI);var i=t[RE],n=t[$C];t&&i&&(Vv(a[i])?a[i]=n:I_(e,"Two extensions have same priority #"+i+" - "+a[i]+", "+n)),!i||i<500?r[FC](t):s[FC](t)})),(n={})[bE]=r,n[EE]=s,n}(e[LC],0,d);c=null,I=null,_=null,h=vI(ly(h=(u||[])[0]||[],i[EE]));var n=ly(vI(i[bE]),h);b=CS(n);var r=e.config[AE]||[];r.splice(0,r[PC]),ly(r,b);var s=k();h&&h[PC]>0&&fI(s[sT](h),n),fI(s,n),t&&V(t)}function N(e){var t=null,i=null,n=[];return cy(b,(function(t){if(t[$C]===e&&t!==p)return i=t,-1;t.getChannel&&n[FC](t)})),!i&&n[PC]>0&&cy(n,(function(t){if(!(i=t.getChannel(e)))return-1})),i&&(t={plugin:i,setEnabled:function(e){mI(i)[IE]=!e},isEnabled:function(){var e=mI(i);return!e[aT]&&!e[IE]},remove:function(e,t){var n;void 0===e&&(e=!0);var r=[i],s=((n={reason:1})[cT]=e,n);x(r,s,(function(e){e&&O({reason:32,removed:r}),t&&t(e)}))}}),t}function L(){if(!c){var i=(b||[]).slice();-1===dy(i,p)&&i[FC](p),c=wI(vI(i),t.cfg,e)}return c}function x(i,n,r){if(i&&i[PC]>0){var s=_I(wI(i,t.cfg,e),e);s[iT]((function(){var e=!1,t=[];cy(d,(function(n,r){UI(n,i)?e=!0:t[FC](n)})),d=t,I=null,_=null;var n=[];u&&(cy(u,(function(t,r){var s=[];cy(t,(function(t){UI(t,i)?e=!0:s[FC](t)})),n[FC](s)})),u=n),r&&r(e),R()})),s[QC](n)}else r(!1)}function F(){if(n&&n.queue){var t=n.queue.slice(0);n.queue[PC]=0,cy(t,(function(t){var i,n=((i={})[JC]=m||"InternalMessageId: "+t[oT],i.iKey=T,i[YC]=zE(new Date),i.baseType=S_.dataType,i.baseData={message:t[lT]},i);e.track(n)}))}}function U(e,t,i,n){var r=1,s=!1,a=null;function o(){r--,s&&0===r&&(a&&a[VC](),a=null,t&&t(s),t=null)}return n=n||5e3,h&&h[PC]>0&&k()[sT](h).iterate((function(t){if(t.flush){r++;var s=!1;t.flush(e,(function(){s=!0,o()}),i)||s||(e&&null==a?a=Vy((function(){a=null,o()}),n):o())}})),s=!0,o(),!0}function B(){var i;j(t[NC]((function(t){if(t.cfg.enablePerfMgr){var n=t.cfg[_E];i!==n&&(n||(n=FI),function(e,t,i){var n;e?!(n=e[t])&&Vv(n)&&(n=Bv(i)?{}:i,e[t]=n):n=Bv(i)?{}:i}(t.cfg,_E,n),i=n,o=null),a||o||!Gv(n)||(o=n(e,e[zC]()))}else o=null,i=null})))}function V(t){var i=II(L(),e);i[iT](R),e._updateHook&&!0===e._updateHook(i,t)||i[QC](t)}function H(t){var i=e[LC];i?(__(i,2,73,t),R()):gS(t)}function $(t){var i=e[zC]();i&&i[DE]([t],2)}function j(e){S.add(e)}D(),e._getDbgPlgTargets=function(){return[b]},e[qC]=function(){return i},e[HC]=function(r,a,o,l){g&&gS(LI),e[qC]()&&gS("Core cannot be initialized more than once"),r=(t=e_(r,xI,o||e[LC],!1)).cfg,j(t[NC]((function(e){T=e.cfg.instrumentationKey;var t=e.ref(e.cfg,wE);iS(t,(function(i){e.ref(t,i)})),Vv(T)&&gS("Please provide instrumentation key")}))),y=function(e,t,i,n){return t.add(e[NC]((function(e){var t=e.cfg.disableDbgExt;!0===t&&n&&(i[jC](n),n=null),i&&!n&&!0!==t&&(n=function(e){if(!o_){o_={};for(var t=0;t<c_[PC];t++)o_[c_[t]]=u_(c_[t],e)}return o_}(e.cfg),i[GC](n))}))),n}(t,S,(s=l)&&e[zC](),y),B(),e[LC]=o;var c=r[AE];if((d=[])[FC].apply(d,Gy(Gy([],a),c)),u=r[EE],O(null),h&&0!==h[PC]||gS("No "+EE+" available"),u&&u[PC]>1){var p=e[WC]("TeeChannelController");p&&p.plugin||__(n,1,28,"TeeChannel required")}(function(e,t,i){cy(t,(function(t){var n=t_(e,t.w,i);delete t.w,t.rm=function(){n.rm()}}))})(r,E,n),E=null,i=!0,e.releaseQueue(),e[KC]()},e.getChannels=function(){var e=[];return h&&cy(h,(function(t){e[FC](t)})),CS(e)},e.track=function(t){lI(e[FE](),(function(){return"AppInsightsCore:track"}),(function(){null===t&&($(t),gS("Invalid telemetry item")),!t[JC]&&Vv(t[JC])&&($(t),gS("telemetry name required")),t.iKey=t.iKey||T,t[YC]=t[YC]||zE(new Date),t.ver=t.ver||"4.0",!g&&e[qC]()?k()[QC](t):r[FC](t)}),(function(){return{item:t}}),!t.sync)},e[ZC]=k,e[zC]=function(){return s||(s=new tI(t.cfg),e._notificationManager=s),s},e[GC]=function(t){e.getNotifyMgr()[GC](t)},e[jC]=function(e){s&&s[jC](e)},e.getCookieMgr=function(){return l||(l=q_(t.cfg,e[LC])),l},e.setCookieMgr=function(e){l!==e&&(i_(l,!1),l=e)},e[FE]=function(){return a||o||null},e.setPerfMgr=function(e){a=e},e.eventCnt=function(){return r[PC]},e.releaseQueue=function(){if(i&&r[PC]>0){var e=r;r=[],cy(e,(function(e){k()[QC](e)}))}},e[KC]=function(e){return m=e||null,P=!1,w&&w[VC](),R(!0)},e[eT]=function(){P=!0,w&&w[VC](),F()},YE(e,(function(){return p}),["addTelemetryInitializer"]),e[tT]=function(t,r,a){var o;void 0===t&&(t=!0),i||gS("SDK is not initialized"),g&&gS(LI);var c,d=((o={reason:50})[cT]=t,o.flushComplete=!1,o);t&&!r&&(c=oE((function(e){r=e})));var u=_I(L(),e);return u[iT]((function(){S.run(e[LC]),n_([l,s,n],t,(function(){D(),r&&r(d)}))}),e),F(),U(t,(function(t){d.flushComplete=t,g=!0,v.run(u,d),e[eT](),u[QC](d)}),6,a),c},e[WC]=N,e.addPlugin=function(e,t,i,n){if(!e)return n&&n(!1),void H(NI);var r=N(e[$C]);if(r&&!t)return n&&n(!1),void H("Plugin ["+e[$C]+"] is already loaded!");var s={reason:16};function a(t){d[FC](e),s.added=[e],O(s),n&&n(!0)}if(r){var o=[r.plugin];x(o,{reason:2,isAsync:!!i},(function(e){e?(s.removed=o,s.reason|=32,a()):n&&n(!1)}))}else a()},e.updateCfg=function(i,n){var r;if(void 0===n&&(n=!0),e[qC]()){r={reason:1,cfg:t.cfg,oldCfg:My({},t.cfg),newConfig:My({},i),merge:n},i=r.newConfig;var s=t.cfg;i[AE]=s[AE],i[EE]=s[EE]}t._block((function(e){var t=e.cfg;BI(e,t,i,n),n||iS(t,(function(n){tS(i,n)||e.set(t,n,CE)})),e[OC](t,xI)}),!0),t[MC](),r&&V(r)},e.evtNamespace=function(){return f},e.flush=U,e.getTraceCtx=function(e){return C||(C=function(){var e={};return{getName:function(){return e[JC]},setName:function(t){e[JC]=t},getTraceId:function(){return e[LT]},setTraceId:function(t){hI(t)&&(e[LT]=t)},getSpanId:function(){return e[xT]},setSpanId:function(t){gI(t)&&(e[xT]=t)},getTraceFlags:function(){return e[FT]},setTraceFlags:function(t){e[FT]=t}}}()),C},e.setTraceCtx=function(e){C=e||null},e.addUnloadHook=j,JE(e,"addUnloadCb",(function(){return v}),"add"),e.onCfgChange=function(n){return function(e){return oS({rm:function(){e.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(e)+">"}})}(i?t_(t.cfg,n,e[LC]):function(e,t){var i=VI(e,t).l;return i||(i={w:t,rm:function(){var i=VI(e,t);-1!==i.i&&e[UC](i.i,1)}},e[FC](i)),i}(E,n))},e.getWParam=function(){return zS()||t.cfg.enableWParam?0:-1}}))}return e.__ieDyn=1,e}(),$I="",jI="&NoResponseBody=true",GI="POST",qI=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p=0;TC(e,this,(function(e,m){var f=!0;function v(e,t){__(n,2,26,"Failed to send telemetry.",{message:e}),y(t,400,{})}function S(e){v("No endpoint url is provided for the batch",e)}function y(e,t,i,n){try{e&&e(t,i,n)}catch(e){}}function C(e,t){var i=ZS(),n=e[MT];if(!n)return S(t),!0;n=e[MT]+(h?jI:$I);var s=e[wT],a=r?s:new Blob([s],{type:"text/plain;charset=UTF-8"});return i.sendBeacon(n,a)}function T(e,t,i){var a=e[wT];try{if(a)if(C(e,t))!function(e,t){y(t,200,{},"")}(0,t);else{var l=s&&s.beaconOnRetry;l&&Gv(l)?l(e,t,C):(o&&o[DT](e,t,!0),__(n,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(e){r&&I_(n,"Failed to send telemetry using sendBeacon API. Ex:"+hS(e)),y(t,r?0:400,{},$I)}}function E(e,i,n){var a,o,l,c=e[kT]||{};!n&&t&&(a=oE((function(e,t){o=e,l=t}))),r&&n&&e.disableXhrSync&&(n=!1);var d=e[MT];if(!d)return S(i),void(o&&o(!1));var u=function(e,t,i,n,r,s){function a(e,t,i){try{e[t]=i}catch(e){}}void 0===n&&(n=!1),void 0===r&&(r=!1);var o=new XMLHttpRequest;return n&&a(o,"Microsoft_ApplicationInsights_BypassAjaxInstrumentation",n),i&&a(o,ib,i),o.open(e,t,!r),i&&a(o,ib,i),!r&&s&&a(o,"timeout",s),o}(GI,d,f,!0,n,e[OT]);function h(t){var n=s&&s.xhrOnComplete;if(n&&Gv(n))n(t,i,e);else{var a=XE(t);y(i,t[ET],rb(t,r),a)}}return r||u[NT]("Content-type","application/json"),cy(vS(c),(function(e){u[NT](e,c[e])})),u.onreadystatechange=function(){r||(h(u),4===u.readyState&&o&&o(!0))},u.onload=function(){r&&h(u)},u.onerror=function(e){y(i,r?u[ET]:400,rb(u,r),r?$I:eb(u)),l&&l(e)},u.ontimeout=function(){y(i,r?u[ET]:500,rb(u,r),r?$I:eb(u)),o&&o(!1)},u.send(e[wT]),a}function b(e,i,n){var a,o,l,c,d=e[MT],u=e[wT],m=r?u:new Blob([u],{type:"application/json"}),v=new Headers,C=u[PC],T=!1,E=!1,b=e[kT]||{},_=((a={method:GI,body:m})[r_]=!0,a);e.headers&&vS(e.headers)[PC]>0&&(cy(vS(b),(function(e){v.append(e,b[e])})),_[kT]=v),f&&r&&(_.credentials="include"),n&&(_.keepalive=!0,p+=C,r?2===e._sendReason&&(T=!0,h&&(d+=jI)):T=!0);var I=new Request(d,_);try{I[r_]=!0}catch(e){}if(!n&&t&&(o=oE((function(e,t){l=e,c=t}))),!d)return S(i),void(l&&l(!1));function w(e){y(i,r?0:400,{},r?$I:e)}function A(e,t,n){var r=e[ET],a=s.fetchOnComplete;a&&Gv(a)?a(e,i,n||$I,t):y(i,r,{},n||$I)}try{VT(fetch(r?d:I,r?_:null),(function(t){if(n&&(p-=C,C=0),!E)if(E=!0,t.rejected)w(t.reason&&t.reason[lT]),c&&c(t.reason);else{var i=t.value;try{r||i.ok?r&&!i.body?(A(i,null,$I),l&&l(!0)):VT(i.text(),(function(t){A(i,e,t.value),l&&l(!0)})):(w(i.statusText),l&&l(!1))}catch(t){w(hS(t)),c&&c(t)}}}))}catch(e){E||(w(hS(e)),c&&c(e))}return T&&!E&&(E=!0,y(i,200,{}),l&&l(!0)),r&&!E&&e[OT]>0&&g&&g.set((function(){E||(E=!0,y(i,500,{}),l&&l(!0))}),e[OT]),o}function _(e,t,i){var a=QS(),o=new XDomainRequest,l=e[wT];o.onload=function(){var i=XE(o),n=s&&s.xdrOnComplete;n&&Gv(n)?n(o,t,e):y(t,200,{},i)},o.onerror=function(){y(t,400,{},r?$I:function(e){return e?"XDomainRequest,Response:"+XE(e)||0:void 0}(o))},o.ontimeout=function(){y(t,500,{})},o.onprogress=function(){};var c=a&&a.location&&a.location[mT]||"",d=e[MT];if(d){if(!r&&0!==d.lastIndexOf(c,0)){var u="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return __(n,2,40,". "+u),void v(u,t)}var h=r?d:d[yT](/^(https?:)/,"");o.open(GI,h),e[OT]&&(o[OT]=e[OT]),o.send(l),r&&i?g&&g.set((function(){o.send(l)}),0):o.send(l)}else S(t)}function I(){p=0,i=!1,t=!1,n=null,r=null,s=null,a=null,o=null,l=!1,c=!1,d=!1,u=!1,h=!1,g=null}I(),e[HC]=function(t,r){n=r,i&&__(n,1,28,"Sender is already initialized"),e.SetConfig(t),i=!0},e._getDbgPlgTargets=function(){return[i,r,a,t]},e.SetConfig=function(e){try{if(s=e.senderOnCompleteCallBack||{},a=!!e.disableCredentials,r=!!e.isOneDs,t=!!e.enableSendPromise,l=!!e.disableXhr,c=!!e.disableBeacon,d=!!e.disableBeaconSync,g=e.timeWrapper,h=!!e.addNoResponse,u=!!e.disableFetchKeepAlive,o={sendPOST:E},r||(f=!1),a){var i=hb();i&&i.protocol&&"file:"===i.protocol[wC]()&&(f=!1)}return!0}catch(e){}return!1},e.getSyncFetchPayload=function(){return p},e.getSenderInst=function(e,t){return e&&e[PC]?function(e,t){for(var i,n=0,r=null,s=0;null==r&&s<e[PC];)n=e[s],l||1!==n?2!==n||!vb(t)||t&&u?3!==n||!fb()||(t?d:c)||(r=T):r=b:(null===cb&&(cb=typeof XDomainRequest!==lv)&&Sb()&&(cb=cb&&!ub(qS(ab),"withCredentials")),cb?r=_:Sb()&&(r=E)),s++;return r?((i={_transport:n,_isSync:t})[DT]=r,i):null}(e,t):null},e.getFallbackInst=function(){return o},e[uT]=function(e,t){I()}}))}return e.__ieDyn=1,e}(),zI="attachEvent",WI="addEventListener",KI="detachEvent",JI="removeEventListener",YI="events",QI="visibilitychange",ZI="pagehide",XI="pageshow",ew="unload",tw="beforeunload",iw=kb("aiEvtPageHide"),nw=kb("aiEvtPageShow"),rw=/\.[\.]+/g,sw=/[\.]+$/,aw=1,ow=Ob("events"),lw=/^([^.]*)(?:\.(.+)|)/;function cw(e){return e&&e[yT]?e[yT](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,TE):e}function dw(e,t){var i;if(t){var n=TE;zv(t)?(n=TE,cy(t,(function(e){(e=cw(e))&&("."!==e[0]&&(e="."+e),n+=e)}))):n=cw(t),n&&("."!==n[0]&&(n="."+n),e=(e||TE)+n)}var r=lw.exec(e||TE)||[];return(i={})[CT]=r[1],i.ns=(r[2]||TE).replace(rw,".").replace(sw,TE)[vT](".").sort().join("."),i}function uw(e,t,i){void 0===i&&(i=!0);var n=ow.get(e,YI,{},i),r=n[t];return r||(r=n[t]=[]),r}function hw(e,t,i,n){e&&t&&t[CT]&&(e[JI]?e[JI](t[CT],i,n):e[KI]&&e[KI]("on"+t[CT],i))}function gw(e,t,i,n){for(var r=t[PC];r--;){var s=t[r];s&&(i.ns&&i.ns!==s.evtName.ns||n&&!n(s)||(hw(e,s.evtName,s[TT],s.capture),t[UC](r,1)))}}function pw(e,t){return t?dw("xx",zv(t)?[e].concat(t):[e,t]).ns[vT]("."):e}function mw(e,t,i,n,r){var s;void 0===r&&(r=!1);var a=!1;if(e)try{var o=dw(t,n);if((a=function(e,t,i,n){var r=!1;return e&&t&&t[CT]&&i&&(e[WI]?(e[WI](t[CT],i,n),r=!0):e[zI]&&(e[zI]("on"+t[CT],i),r=!0)),r}(e,o,i,r))&&ow.accept(e)){var l=((s={guid:aw++,evtName:o})[TT]=i,s.capture=r,s);uw(e,o.type)[FC](l)}}catch(e){}return a}function fw(e,t,i,n,r){if(void 0===r&&(r=!1),e)try{var s=dw(t,n),a=!1;(function(e,t,i){if(t[CT])gw(e,uw(e,t[CT]),t,i);else{var n=ow.get(e,YI,{});iS(n,(function(n,r){gw(e,r,t,i)})),0===vS(n)[PC]&&ow.kill(e,YI)}})(e,s,(function(e){return!((!s.ns||i)&&e[TT]!==i||(a=!0,0))})),a||hw(e,s,i,r)}catch(e){}}function vw(e,t,i,n){var r=!1;return t&&e&&e[PC]>0&&cy(e,(function(e){e&&(i&&-1!==dy(i,e)||(r=function(e,t,i){var n=!1,r=QS();r&&(n=mw(r,e,t,i),n=mw(r.body,e,t,i)||n);var s=YS();return s&&(n=mw(s,e,t,i)||n),n}(e,t,n)||r))})),r}function Sw(e,t,i){e&&zv(e)&&cy(e,(function(e){e&&function(e,t,i){var n=QS();n&&(fw(n,e,t,i),fw(n.body,e,t,i));var r=YS();r&&fw(r,e,t,i)}(e,t,i)}))}function yw(e,t,i){var n=pw(iw,i),r=vw([ZI],e,t,n);return t&&-1!==dy(t,QI)||(r=vw([QI],(function(t){var i=YS();e&&i&&"hidden"===i.visibilityState&&e(t)}),t,n)||r),!r&&t&&(r=yw(e,null,i)),r}function Cw(e,t,i){var n=pw(nw,i),r=vw([XI],e,t,n);return!(r=vw([QI],(function(t){var i=YS();e&&i&&"visible"===i.visibilityState&&e(t)}),t,n)||r)&&t&&(r=Cw(e,null,i)),r}var Tw,Ew="",bw="version",_w="properties",Iw="initialize",ww="logger",Aw="timings",Pw="pollInternalLogs",Rw="value",Mw="kind",Dw="length",kw="processTelemetryStart",Ow="1DS-Web-JS-4.2.1",Nw=uv.hasOwnProperty,Lw=((Tw={})[0]=0,Tw[2]=6,Tw[1]=1,Tw[3]=7,Tw[4098]=6,Tw[4097]=1,Tw[4099]=7,Tw);function xw(e){return!(e===Ew||Vv(e))}function Fw(e,t,i){var n=-1;if(!Bv(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=Lw[jw(e)]||-1;-1!==n&&-1!==r?n|=r:6===r&&(n=r)}return n}function Uw(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||Ew}function Bw(e){void 0===e&&(e="D");var t=cI();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,Ew)),t}function Vw(e,t,i,n,r){var s={},a=!1,o=0,l=arguments[Dw],c=arguments;for(Jv(c[0])&&(a=c[0],o++);o<l;o++)iS(c[o],(function(e,t){a&&t&&qv(t)?zv(t)?(s[e]=s[e]||[],cy(t,(function(t,i){t&&qv(t)?s[e][i]=Vw(!0,s[e][i],t):s[e][i]=t}))):s[e]=Vw(!0,s[e],t):s[e]=t}));return s}var Hw=ky;function $w(e,t){var i=e;i[Aw]=i[Aw]||{},i[Aw][kw]=i[Aw][kw]||{},i[Aw][kw][t]=Hw()}function jw(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===ov&&(t=4,zv(e)?(t=4096,e[Dw]>0&&(t|=jw(e[0]))):Nw.call(e,"value")&&(t=8192|jw(e[Rw])))}return t}function Gw(e){return e>0}var qw=SS({endpointUrl:"https://browser.events.data.microsoft.com/OneCollector/1.0/",propertyStorageOverride:{isVal:function(e){return!e||e.getProperty&&e.setProperty||gS("Invalid property storage override passed."),!0}}}),zw=function(e){function t(){var i=e.call(this)||this;return TC(t,i,(function(e,t){e[Iw]=function(i,n,r,s){lI(e,(function(){return"AppInsightsCore.initialize"}),(function(){try{t[Iw](e_(i,qw,r||e[ww],!1).cfg,n,r,s)}catch(t){var a=e[ww],o=hS(t);-1!==o.indexOf("channels")&&(o+="\n - Channels must be provided through config.channels only!"),__(a,1,514,"SDK Initialization Failed - no telemetry will be sent: "+o)}}),(function(){return{config:i,extensions:n,logger:r,notificationManager:s}}))},e.track=function(i){lI(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n[Aw]=n[Aw]||{},n[Aw].trackStart=Hw(),function(e){return!!(e&&Kv(e)&&e>=1&&e<=4)}(n.latency)||(n.latency=1);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=Ow;var s=n.baseData=n.baseData||{};s[_w]=s[_w]||{};var a=s[_w];a[bw]=a[bw]||e.pluginVersionString||Ew}t.track(n)}),(function(){return{item:i}}),!i.sync)},e[Pw]=function(e){return t[Pw](e||"InternalLog")}})),i}return jy(t,e),t.__ieDyn=1,t}(HI),Ww=bC({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),Kw=bC({Normal:1,Critical:2}),Jw="REAL_TIME",Yw="",Qw="drop",Zw="requeue",Xw="no-cache, no-store",eA="application/x-json-stream",tA="cache-control",iA="content-type",nA="client-version",rA="client-id",sA="time-delta-to-apply-millis",aA="upload-time",oA="apikey",lA="AuthMsaDeviceTicket",cA="WebAuthToken",dA="AuthXToken",uA="msfpc",hA="trace",gA="user",pA="allowRequestSending",mA="firstRequestSent",fA="shouldAddClockSkewHeaders",vA="getClockSkewHeaderValue",SA="setClockSkew",yA="length",CA="concat",TA="iKey",EA="count",bA="events",_A="push",IA="split",wA="splice",AA="toLowerCase",PA="hdrs",RA="useHdrs",MA="initialize",DA="setTimeoutOverride",kA="clearTimeoutOverride",OA="overrideEndpointUrl",NA="avoidOptions",LA="enableCompoundKey",xA="disableXhrSync",FA="disableFetchKeepAlive",UA="useSendBeacon",BA="alwaysUseXhrOverride",VA="serializeOfflineEvt",HA="getOfflineRequestDetails",$A="createPayload",jA="createOneDSPayload",GA="payloadBlob",qA="headers",zA="_thePayload",WA="urlString",KA="batches",JA="sendType",YA="addHeader",QA="canSendRequest",ZA="sendQueuedRequests",XA="isCompletelyIdle",eP="setUnloading",tP="sendSynchronousBatch",iP="_transport",nP="getWParam",rP="isBeacon",sP="timings",aP="isTeardown",oP="isSync",lP="data",cP="_sendReason",dP="setKillSwitchTenants",uP="_backOffTransmission",hP="identifier",gP="eventsLimitInMem",pP="autoFlushEventsLimit",mP="baseData",fP="sendAttempt",vP="latency",SP="sync";function yP(e){var t=(e.ext||{}).intweb;return t&&xw(t[uA])?t[uA]:null}function CP(e){for(var t=null,i=0;null===t&&i<e[yA];i++)t=yP(e[i]);return t}var TP=function(){function e(t,i){var n=i?[][CA](i):[],r=this,s=CP(n);r[TA]=function(){return t},r.Msfpc=function(){return s||Yw},r[EA]=function(){return n[yA]},r[bA]=function(){return n},r.addEvent=function(e){return!!e&&(n[_A](e),s||(s=yP(e)),!0)},r[IA]=function(i,r){var a;if(i<n[yA]){var o=n[yA]-i;Vv(r)||(o=r<o?r:o),a=n[wA](i,o),s=CP(n)}return new e(t,a)}}return e.create=function(t,i){return new e(t,i)},e}(),EP=function(){function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",s=!1;TC(e,this,(function(e){e[pA]=function(){return t},e[mA]=function(){n&&(n=!1,s||(t=!1))},e[fA]=function(){return i},e[vA]=function(){return r},e[SA]=function(e){s||(e?(r=e,i=!0,s=!0):i=!1,t=!0)}}))}return e.__ieDyn=1,e}(),bP=function(){function e(){var t={};TC(e,this,(function(e){e[dP]=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&cy(e,(function(e){t[_A](by(e))})),t}(e[IA](","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),s=0;s<n[yA];++s)t[n[s]]=Sy()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=by(e);return void 0!==i[n]&&i[n]>Sy()||(delete i[n],!1)}}))}return e.__ieDyn=1,e}();function _P(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)}var IP,wP=2e6,AP=Math.min(wP,65e3),PP="metadata",RP="f",MP=/\./,DP=function(){function e(t,i,n,r,s,a){var o="data",l="baseData",c=!!r,d=!0,u=i,h={},g=!!a,p=s||Fw;TC(e,this,(function(e){function i(e,t){var i=h[e];return void 0===i&&(e.length>=7&&(i=Ly(e,"ext.metadata")||Ly(e,"ext.web")),h[e]=i),i}function r(e,t,s,a,o,l,d){iS(e,(function(e,h){var g=null;if(h||xw(h)){var p=s,m=e,f=o,v=t;if(c&&!a&&MP.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var T=S[C];v=v[T]=v[T]||{},p+="."+T,f&&f.push(T)}m=S[y-1]}}if(g=a&&i(p)||!u||!u.handleField(p,m)?function(e,t,i){if(!t&&!xw(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||zv(t))t={value:t};else if("object"!==n||Nw.call(t,"value")){if(Vv(t[Rw])||t[Rw]===Ew||!jv(t[Rw])&&!Kv(t[Rw])&&!Jv(t[Rw])&&!zv(t[Rw]))return null}else t={value:i?JSON.stringify(t):t};if(zv(t[Rw])&&!function(e){return e[Dw]>0}(t[Rw]))return null;if(!Vv(t[Mw])){if(zv(t[Rw])||!function(e){return 0===e||e>0&&e<=13||32===e}(t[Mw]))return null;t[Rw]=t[Rw].toString()}return t}(m,h,n):u.value(p,m,h,n)){var E=g.value;if(v[m]=E,l&&l(f,m,g),d&&"object"==typeof E&&!zv(E)){var b=f;b&&(b=b.slice()).push(m),r(h,E,p+"."+m,a,b,l,d)}}}}))}e.createPayload=function(e,t,i,n,r,s){return{apiKeys:[],payloadBlob:Yw,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendType:s,sendReason:r}},e.appendPayload=function(i,n,r){var s=i&&n&&!i.overflow;return s&&lI(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),s=i.payloadBlob,a=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?AP:wP,g=0,p=0;g<t.length;){var m=t[g];if(m){if(a>=r){i.overflow=n.split(g);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(s.length+v>u){i.overflow=n.split(g);break}s&&(s+="\n"),s+=f,++p>20&&(DS(s,0,1),p=0),o=!0,a++}else f?l.push(m):c.push(m),t.splice(g,1),g--}g++}if(l.length>0&&i.sizeExceed.push(TP.create(n.iKey(),l)),c.length>0&&i.failedEvts.push(TP.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=s,i.numEvents=a;var S=n.iKey();-1===dy(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),s},e.getEventBlob=function(e){try{return lI(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+function(e){if(e){var t=Ny(e,"-");if(t>-1)return kS(e,t)}return Ew}(e.iKey);var i,n={};g||(i=function(e,t,i){!function(e,t,i,n,r){if(r&&t){var s=e(r.value,r.kind,r.propertyType);if(s>-1){var a=t[PP];a||(a=t[PP]={f:{}});var o=a[RP];if(o||(o=a[RP]={}),i)for(var l=0;l<i.length;l++){var c=i[l];o[c]||(o[c]={f:{}});var d=o[c][RP];d||(d=o[c][RP]={}),o=d}o=o[n]={},zv(r.value)?o.a={t:s}:o.t=s}}}(p,n,e,t,i)});var s=e.ext;s&&(t.ext=n,iS(s,(function(e,t){r(t,n[e]={},"ext."+e,!0,null,null,!0)})));var a=t[o]={};a.baseType=e.baseType;var c=a[l]={};return r(e.baseData,c,l,!1,[l],i,d),r(e.data,a,o,!1,[],i,d),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))}return e.__ieDyn=1,e}();function kP(e,t){return{set:function(i,n){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return function(e,t,i){return By(!0,e,Lv[wv](arguments,1))}([e,t],i,n,r)}}}var OP="sendAttempt",NP="?cors=true&"+iA[AA]()+"="+eA,LP=((IP={})[1]=Zw,IP[100]=Zw,IP[200]="sent",IP[8004]=Qw,IP[8003]=Qw,IP),xP={},FP={};function UP(e,t,i){xP[e]=t,!1!==i&&(FP[t]=e)}function BP(e,t){var i=!1;if(e&&t){var n=vS(e);if(n&&n[yA]>0)for(var r=t[AA](),s=0;s<n[yA];s++){var a=n[s];if(a&&eS(t,a)&&a[AA]()===r){i=!0;break}}}return i}function VP(e,t,i,n){t&&i&&i[yA]>0&&(n&&xP[t]?(e[PA][xP[t]]=i,e[RA]=!0):e.url+="&"+t+"="+i)}UP(lA,lA,!1),UP(nA,nA),UP(rA,"Client-Id"),UP(oA,oA),UP(sA,sA),UP(aA,aA),UP(dA,dA);var HP,$P=function(){function e(t,i,n,r){var s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x=!1;TC(e,this,(function(e){function F(e,t){try{return L&&L.getSenderInst(e,t)}catch(e){}return null}function U(e,t,i){var n=XE(e);H(t,200,{},n),ie(n)}function B(e,t,i,n){var r={},s=e[qA];s&&s.forEach((function(e,t){r[t]=e})),function(e,i,n){H(t,e,i,n),ie(n)}(e.status,r,i||Yw)}function V(e,t,i){var n=XE(e);H(t,e.status,rb(e,!0),n),ie(n)}function H(e,t,i,n){try{e(t,i,n)}catch(e){__(u,2,518,hS(e))}}function $(e,t,i){var n=200,r=e[zA],s=e[WA]+(A?"&NoResponseBody=true":Yw);try{var a=ZS();if(r){var o=!!g.getPlugin("LocalStorage"),l=[],c=[];cy(r[KA],(function(e){if(l&&e&&e[EA]()>0)for(var t=e[bA](),i=0;i<t[yA];i++){if(!a.sendBeacon(s,S.getEventBlob(t[i]))){l[_A](e[IA](i));break}c[_A](e[i])}else l[_A](e[IA](0))})),c[yA]>0&&(r.sentEvts=c),o||ne(l,8003,r[JA],!0)}else n=0}catch(e){I_(u,"Failed to send telemetry using sendBeacon API. Ex:"+hS(e)),n=0}finally{H(t,n,{},Yw)}}function j(e){return 2===e||3===e}function G(e){return T&&j(e)&&(e=2),e}function q(){return!o&&c<i}function z(){var e=v;return v=[],e}function W(e,t,i){var n=!1;return e&&e[yA]>0&&!o&&h[t]&&S&&(n=0!==t||q()&&(i>0||l[pA]())),n}function K(e){var t={};return e&&cy(e,(function(e,i){t[i]={iKey:e[TA](),evts:e[bA]()}})),t}function J(e,i,n,r,s){if(e&&0!==e[yA])if(o)ne(e,1,r);else{r=G(r);try{var l=e,c=0!==r;lI(g,(function(){return"HttpManager:_sendBatches"}),(function(o){o&&(e=e.slice(0));for(var l=[],d=null,u=Hw(),g=h[r]||(c?h[1]:h[0]),p=g&&g[iP],m=w&&(T||j(r)||3===p||g._isSync&&2===p);W(e,r,i);){var f=e.shift();f&&f[EA]()>0&&(a.isTenantKilled(f[TA]())?l[_A](f):(d=d||S[$A](i,n,c,m,s,r),S.appendPayload(d,f,t)?null!==d.overflow&&(e=[d.overflow][CA](e),d.overflow=null,Z(d,u,Hw(),s),u=Hw(),d=null):(Z(d,u,Hw(),s),u=Hw(),e=[f][CA](e),d=null)))}d&&Z(d,u,Hw(),s),e[yA]>0&&(v=e[CA](v)),ne(l,8004,r)}),(function(){return{batches:K(l),retryCount:i,isTeardown:n,isSynchronous:c,sendReason:s,useSendBeacon:j(r),sendType:r}}),!c)}catch(e){__(u,2,48,"Unexpected Exception sending batch: "+hS(e))}}}function Y(e,t){var i={url:s,hdrs:{},useHdrs:!1};t?(i[PA]=Vw(i[PA],f),i.useHdrs=vS(i.hdrs)[yA]>0):iS(f,(function(e,t){FP[e]?VP(i,FP[e],t,!1):(i[PA][e]=t,i[RA]=!0)})),VP(i,rA,"NO_AUTH",t),VP(i,nA,Ow,t);var n=Yw;cy(e.apiKeys,(function(e){n[yA]>0&&(n+=","),n+=e})),VP(i,oA,n,t),VP(i,aA,Sy().toString(),t);var r=function(e){for(var t=0;t<e.batches[yA];t++){var i=e[KA][t].Msfpc();if(i)return encodeURIComponent(i)}return Yw}(e);if(xw(r)&&(i.url+="&ext.intweb.msfpc="+r),l[fA]()&&VP(i,sA,l[vA](),t),g[nP]){var a=g[nP]();a>=0&&(i.url+="&w="+a)}for(var o=0;o<m[yA];o++)i.url+="&"+m[o].name+"="+m[o].value;return i}function Q(e,t,i){e[t]=e[t]||{},e[t][d.identifier]=i}function Z(e,t,i,n){if(e&&e.payloadBlob&&e.payloadBlob[yA]>0){var r=!!R,s=h[e.sendType];!j(e[JA])&&e[rP]&&2===e.sendReason&&(s=h[2]||h[3]||s);var a=E;(e.isBeacon||3===s[iP])&&(a=!1);var o=Y(e,a);a=a||o[RA];var d=Hw();lI(g,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var h=0;h<e.batches[yA];h++)for(var m=e[KA][h][bA](),f=0;f<m[yA];f++){var v=m[f];if(y){var S=v[sP]=v[sP]||{};Q(S,"sendEventStart",d),Q(S,"serializationStart",t),Q(S,"serializationCompleted",i)}v[OP]>0?v[OP]++:v[OP]=1}ne(e[KA],1e3+(n||0),e[JA],!0);var C={data:e[GA],urlString:o.url,headers:o[PA],_thePayload:e,_sendReason:n,timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};a&&(BP(C[qA],tA)||(C[qA][tA]=Xw),BP(C[qA],iA)||(C[qA][iA]=eA));var T=null;s&&(T=function(t){l[mA]();var i=function(t,i){X(t,i,e,n)},r=e[aP]||e[oP];try{s.sendPOST(t,i,r),M&&M(C,t,r,e[rP])}catch(e){I_(u,"Unexpected exception sending payload. Ex:"+hS(e)),H(i,0,{})}}),lI(g,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(T)if(0===e[JA]&&c++,r&&!e.isBeacon&&3!==s[iP]){var t={data:C[lP],urlString:C[WA],headers:Vw({},C[qA]),timeout:C.timeout,disableXhrSync:C[xA],disableFetchKeepAlive:C[FA]},i=!1;lI(g,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{R(t,(function(e){i=!0,p||e[zA]||(e[zA]=e[zA]||C[zA],e[cP]=e[cP]||C[cP]),T(e)}),e.isSync||e[aP])}catch(e){i||T(C)}}))}else T(C)}))}),(function(){return{thePayload:e,serializationStart:t,serializationCompleted:i,sendReason:n}}),e[oP])}e.sizeExceed&&e.sizeExceed[yA]>0&&ne(e.sizeExceed,8003,e[JA]),e.failedEvts&&e.failedEvts[yA]>0&&ne(e.failedEvts,8002,e[JA])}function X(e,t,i,r){var s=9e3,o=null,d=!1,u=!1;try{var h=!0;if(typeof e!==lv){if(t){l[SA](t["time-delta-millis"]);var g=t["kill-duration"]||t["kill-duration-seconds"];cy(a[dP](t["kill-tokens"],g),(function(e){cy(i[KA],(function(t){if(t[TA]()===e){o=o||[];var n=t[IA](0);i.numEvents-=n[EA](),o[_A](n)}}))}))}if(200==e||204==e)return void(s=200);(!function(e){return!(e>=300&&e<500&&429!=e||501==e||505==e)}(e)||i.numEvents<=0)&&(h=!1),s=9e3+e%1e3}if(h){s=100;var p=i.retryCnt;0===i[JA]&&(p<n?(d=!0,te((function(){0===i[JA]&&c--,J(i[KA],p+1,i[aP],T?2:i[JA],5)}),T,_P(p))):(u=!0,T&&(s=8001)))}}finally{d||(l[SA](),ee(i,s,r,u)),ne(o,8004,i[JA])}}function ee(t,i,n,r){try{r&&d[uP]();var s=t[KA];200===i&&(s=t.sentEvts||t[KA],r||t[oP]||d._clearBackOff(),function(e){if(y){var t=Hw();cy(e,(function(e){e&&e[EA]()>0&&function(e,t){y&&cy(e,(function(e){Q(e[sP]=e[sP]||{},"sendEventCompleted",t)}))}(e[bA](),t)}))}}(s)),ne(s,i,t[JA],!0)}finally{0===t[JA]&&(c--,5!==n&&e.sendQueuedRequests(t[JA],n))}}function te(e,t,i){t?e():O.set(e,i)}function ie(e){var t=D;try{for(var i=0;i<t[yA];i++)try{t[i](e)}catch(e){__(u,1,519,"Response handler failed: "+e)}if(e){var n=JSON.parse(e);xw(n.webResult)&&xw(n.webResult[uA])&&C.set("MSFPC",n.webResult[uA],31536e3)}}catch(e){}}function ne(e,t,i,n){if(e&&e[yA]>0&&r){var s=r[function(e){var t=LP[e];return xw(t)||(t="oth",e>=9e3&&e<=9999?t="rspFail":e>=8e3&&e<=8999?t=Qw:e>=1e3&&e<=1999&&(t="send")),t}(t)];if(s){var a=0!==i;lI(g,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){te((function(){try{s.call(r,e,t,a,i)}catch(e){__(u,1,74,"send request notification failed: "+e)}}),n||a,0)}),(function(){return{batches:K(e),reason:t,isSync:a,sendSync:n,sendType:i}}),!a)}}}!function(){var e;s=null,a=new bP,o=!1,l=new EP,x=!1,c=0,d=null,u=null,h=null,g=null,p=!0,m=[],f={},v=[],S=null,y=!1,C=null,T=!1,E=!1,b=e,_=e,I=e,w=e,A=e,P=[],R=e,M=e,D=[],k=!1,O=kP(),N=!1,L=null}(),e[MA]=function(e,t,i){k||(g=t,C=t.getCookieMgr(),u=(d=i).diagLog(),ly(P,t_(e,(function(e){var n,r=e.cfg,a=e.cfg.extensionConfig[i.identifier];O=kP(a[DA],a[kA]),xw(r.anonCookieName)?function(e,t,i){for(var n=0;n<e[yA];n++)if(e[n].name===t)return void(e[n].value=i);e[_A]({name:t,value:i})}(m,"anoncknm",r.anonCookieName):function(e){for(var t=0;t<e[yA];t++)if("anoncknm"===e[t].name)return void e[wA](t,1)}(m),R=a.payloadPreprocessor,M=a.payloadListener;var o=a.httpXHROverride,l=a[OA]?a[OA]:r.endpointUrl;s=l+NP,E=!!Bv(a[NA])||!a[NA],y=!a.disableEventTimings;var c=a.valueSanitizer,d=a.stringifyObjects,f=!!r[LA];Bv(a[LA])||(f=!!a[LA]),b=a.xhrTimeout,_=!!a[xA],I=!!a[FA],A=!1!==a.addNoResponse,N=!!a.excludeCsMetaData,t.getPlugin("LocalStorage")&&(I=!0),x=!pb(),S=new DP(g,c,d,f,Fw,N),Vv(a[UA])||(x=!!a[UA]);var v=function(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!1,disableXhr:!1,disableBeacon:!x,disableBeaconSync:!x,disableFetchKeepAlive:I,timeWrapper:O,addNoResponse:A,senderOnCompleteCallBack:{xdrOnComplete:U,fetchOnComplete:B,xhrOnComplete:V,beaconOnRetry:$}}}catch(e){}return null}();L?L.SetConfig(v):(L=new qI)[MA](v,u);var C=o,T=a[BA]?o:null,P=a[BA]?o:null,D=[3,2];if(!o){p=!1;var k=[];pb()?(k=[2,1],D=[2,1,3]):k=[1,2,3],(o=F(k=tb(k,a.transports),!1))||I_(u,"No available transport to send events"),C=F(k,!0)}T||(T=F(D=tb(D,a.unloadTransports),!0)),w=!p&&(x&&fb()||!I&&vb(!0)),(n={})[0]=o,n[1]=C||F([1,2,3],!0),n[2]=T||C||F([1],!0),n[3]=P||F([2,3],!0)||C||F([1],!0),h=n}))),k=!0)},e.addResponseHandler=function(e){return D[_A](e),{rm:function(){var t=D.indexOf(e);t>=0&&D[wA](t,1)}}},e[VA]=function(e){try{if(S)return S.getEventBlob(e)}catch(e){}return Yw},e[HA]=function(){try{return Y(S&&S[$A](0,!1,!1,!1,1,0),E)}catch(e){}return null},e[jA]=function(e,i){try{var n=[];cy(e,(function(e){i&&(e=QE(e));var t=TP.create(e[TA],[e]);n[_A](t)}));for(var r=null;n[yA]>0&&S;){var s=n.shift();s&&s[EA]()>0&&(r=r||S[$A](0,!1,!1,!1,1,0),S.appendPayload(r,s,t))}var a=Y(r,E),o={data:r[GA],urlString:a.url,headers:a[PA],timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};return E&&(BP(o[qA],tA)||(o[qA][tA]=Xw),BP(o[qA],iA)||(o[qA][iA]=eA)),o}catch(e){}return null},e._getDbgPlgTargets=function(){return[h[0],a,S,h]},e[YA]=function(e,t){f[e]=t},e.removeHeader=function(e){delete f[e]},e[QA]=function(){return q()&&l[pA]()},e[ZA]=function(e,t){Bv(e)&&(e=0),T&&(e=G(e),t=2),W(v,e,0)&&J(z(),0,!1,e,t||0)},e[XA]=function(){return!o&&0===c&&0===v[yA]},e[eP]=function(e){T=e},e.addBatch=function(e){if(e&&e[EA]()>0){if(a.isTenantKilled(e[TA]()))return!1;v[_A](e)}return!0},e.teardown=function(){v[yA]>0&&J(z(),0,!0,2,2),cy(P,(function(e){e&&e.rm&&e.rm()})),P=[]},e.pause=function(){o=!0},e.resume=function(){o=!1,e[ZA](0,4)},e[tP]=function(e,t,i){e&&e[EA]()>0&&(Vv(t)&&(t=1),T&&(t=G(t),i=2),J([e],0,!1,t,i||0))}}))}return e.__ieDyn=1,e}(),jP=1e4,GP="eventsDiscarded",qP=void 0,zP=SS({eventsLimitInMem:{isVal:Gw,v:jP},immediateEventLimit:{isVal:Gw,v:500},autoFlushEventsLimit:{isVal:Gw,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:function(e){return e&&e.sendPOST},v:qP},overrideInstrumentationKey:qP,overrideEndpointUrl:qP,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:qP,clearTimeoutOverride:qP,payloadPreprocessor:qP,payloadListener:qP,disableEventTimings:qP,valueSanitizer:qP,stringifyObjects:qP,enableCompoundKey:qP,disableOptimizeObj:!1,transports:qP,unloadTransports:qP,useSendBeacon:qP,disableFetchKeepAlive:qP,avoidOptions:!1,xhrTimeout:qP,disableXhrSync:qP,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:Kv,v:6},maxUnloadEventRetryAttempts:{isVal:Kv,v:2},addNoResponse:qP,excludeCsMetaData:qP}),WP=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="4.2.1";var r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R=!1,M=[],D=!1,k=0,O=0,N={},L=Jw;return TC(t,n,(function(e,t){function n(){(function(e,t){Sw([tw,ew,ZI],null,t)})(0,T),function(e,t){var i=pw(iw,t);Sw([ZI],null,i),Sw([QI],null,i)}(0,T),function(e,t){var i=pw(nw,t);Sw([XI],null,i),Sw([QI],null,i)}(0,T)}function x(e){var t="";return e&&e[yA]&&cy(e,(function(e){t&&(t+="\n"),t+=e})),t}function F(e){var t="";try{V(e),t=u[VA](e)}catch(e){}return t}function U(e){"beforeunload"!==(e||QS().event).type&&(S=!0,u[eP](S)),K(2,2)}function B(e){S=!1,u[eP](S)}function V(e){e.ext&&e.ext[hA]&&delete e.ext[hA],e.ext&&e.ext[gA]&&e.ext[gA].id&&delete e.ext[gA].id,v&&(e.ext=QE(e.ext),e[mP]&&(e[mP]=QE(e[mP])),e[lP]&&(e[lP]=QE(e[lP])))}function H(e,t){if(e[fP]||(e[fP]=0),e[vP]||(e[vP]=1),V(e),e[SP])if(c||D)e[vP]=3,e[SP]=!1;else if(u)return v&&(e=QE(e)),void u[tP](TP.create(e[TA],[e]),!0===e[SP]?1:e[SP],3);var i=e[vP],n=O,r=a;4===i&&(n=k,r=s);var o=!1;if(n<r)o=!Q(e,t);else{var l=1,d=20;4===i&&(l=4,d=1),o=!0,function(e,t,i,n){for(;i<=t;){var r=J(e,t,!0);if(r&&r[EA]()>0){var s=r[IA](0,n),a=s[EA]();if(a>0)return 4===i?k-=a:O-=a,ae(GP,[s],IC.QueueFull),!0}i++}return Z(),!1}(e[TA],e[vP],l,d)&&(o=!Q(e,t))}o&&se(GP,[e],IC.QueueFull)}function $(e,t,i){var n=X(e,t,i);return u[ZA](t,i),n}function j(){return O>0}function G(){if(m>=0&&X(m,0,f)&&u[ZA](0,f),k>0&&!l&&!D){var e=N[L][2];e>=0&&(l=z((function(){l=null,$(4,0,1),G()}),e))}var t=N[L][1];!o&&!r&&t>=0&&!D&&(j()?o=z((function(){o=null,$(0===d?3:1,0,1),d++,d%=2,G()}),t):d=0)}function q(){i=null,R=!1,M=[],r=null,D=!1,k=0,s=500,O=0,a=jP,N={},L=Jw,o=null,l=null,c=0,d=0,h={},g=0,w=!1,p=0,m=-1,f=null,v=!0,S=!1,y=6,C=2,T=null,A=null,P=!1,E=kP(),u=new $P(500,2,1,{requeue:ne,send:oe,sent:le,drop:ce,rspFail:de,oth:ue}),ie(),h[4]={batches:[],iKeyMap:{}},h[3]={batches:[],iKeyMap:{}},h[2]={batches:[],iKeyMap:{}},h[1]={batches:[],iKeyMap:{}},he()}function z(e,t){0===t&&c&&(t=1);var i=1e3;return c&&(i=_P(c-1)),E.set(e,t*i)}function W(){return null!==o&&(o.cancel(),o=null,d=0,!0)}function K(e,t){W(),r&&(r.cancel(),r=null),D||$(1,e,t)}function J(e,t,i){var n=h[t];n||(n=h[t=1]);var r=n.iKeyMap[e];return!r&&i&&(r=TP.create(e),n.batches[_A](r),n.iKeyMap[e]=r),r}function Y(t,i){u[QA]()&&!c&&(g>0&&O>g&&(i=!0),i&&null==r&&e.flush(t,(function(){}),20))}function Q(e,t){v&&(e=QE(e));var i=e[vP],n=J(e[TA],i,!0);return!!n.addEvent(e)&&(4!==i?(O++,t&&0===e[fP]&&Y(!e.sync,p>0&&n[EA]()>=p)):k++,!0)}function Z(){for(var e=0,t=0,i=function(i){var n=h[i];n&&n[KA]&&cy(n[KA],(function(n){4===i?e+=n[EA]():t+=n[EA]()}))},n=1;n<=4;n++)i(n);O=t,k=e}function X(t,i,n){var r=!1,s=0===i;return!s||u[QA]()?lI(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=4;i>=t;){var n=h[i];n&&n.batches&&n.batches[yA]>0&&(cy(n[KA],(function(t){u.addBatch(t)?r=r||t&&t[EA]()>0:e=e[CA](t[bA]()),4===i?k-=t[EA]():O-=t[EA]()})),n[KA]=[],n.iKeyMap={}),i--}e[yA]>0&&se(GP,e,IC.KillSwitch),r&&m>=t&&(m=-1,f=0)}),(function(){return{latency:t,sendType:i,sendReason:n}}),!s):(m=m>=0?Math.min(m,t):t,f=Math.max(f,n)),r}function ee(e,t){$(1,0,t),Z(),te((function(){e&&e(),M[yA]>0?r=z((function(){r=null,ee(M.shift(),t)}),0):(r=null,G())}))}function te(e){u[XA]()?e():r=z((function(){r=null,te(e)}),.25)}function ie(){(N={})[Jw]=[2,1,0],N.NEAR_REAL_TIME=[6,3,0],N.BEST_EFFORT=[18,9,0]}function ne(t,i){var n=[],r=y;S&&(r=C),cy(t,(function(t){t&&t[EA]()>0&&cy(t[bA](),(function(t){t&&(t[SP]&&(t[vP]=4,t[SP]=!1),t[fP]<r?($w(t,e[hP]),H(t,!1)):n[_A](t))}))})),n[yA]>0&&se(GP,n,IC.NonRetryableStatus),S&&K(2,2)}function re(t,i){var n=I||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){__(e.diagLog(),1,74,t+" notification failed: "+i)}}function se(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[yA]>0&&re(e,[t][CA](i))}function ae(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[yA]>0&&cy(t,(function(t){t&&t[EA]()>0&&re(e,[t.events()][CA](i))}))}function oe(e,t,i){e&&e[yA]>0&&re("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])}function le(e,t){ae("eventsSent",e,t),G()}function ce(e,t){ae(GP,e,t>=8e3&&t<=8999?t-8e3:IC.Unknown)}function de(e){ae(GP,e,IC.NonRetryableStatus),G()}function ue(e,t){ae(GP,e,IC.Unknown),G()}function he(){p=_?0:Math.max(1500,a/6)}q(),e._getDbgPlgTargets=function(){return[u,i]},e[MA]=function(r,o,l){lI(o,(function(){return"PostChannel:initialize"}),(function(){t[MA](r,o,l),I=o.getNotifyMgr();try{T=pw(kb(e[hP]),o.evtNamespace&&o.evtNamespace()),e._addHook(t_(r,(function(t){var r=t.cfg,l=bI(null,r,o);i=l.getExtCfg(e[hP],zP),E=kP(i[DA],i[kA]),v=!i.disableOptimizeObj&&!!qS("chrome"),b=i.ignoreMc1Ms0CookieProcessing,function(e){var t=e[nP];e[nP]=function(){var i=0;return b&&(i|=2),i|t.call(e)}}(o),a=i[gP],s=i.immediateEventLimit,g=i[pP],y=i.maxEventRetryAttempts,C=i.maxUnloadEventRetryAttempts,_=i.disableAutoBatchFlushLimit,he(),A=i.overrideInstrumentationKey,P=!!i.disableTelemetry,w&&n();var c=r.disablePageUnloadEvents||[];w=function(e,t,i){return function(e,t,i,n){var r=!1;return t&&e&&zv(e)&&!(r=vw(e,t,i,n))&&i&&i[PC]>0&&(r=vw(e,t,null,n)),r}([tw,ew,ZI],e,t,i)}(U,c,T),w=yw(U,c,T)||w,w=Cw(B,r.disablePageShowEvents,T)||w}))),u[MA](r,e.core,e)}catch(t){throw e.setInitialized(!1),t}}),(function(){return{theConfig:r,core:o,extensions:l}}))},e.processTelemetry=function(t,i){$w(t,e[hP]),i=i||e._getTelCtx(i);var n=t;P||R||(A&&(n[TA]=A),H(n,!0),S?K(2,2):G()),e.processNext(n,i)},e.getOfflineSupport=function(){try{var e=u&&u[HA]();if(u)return{getUrl:function(){return e?e.url:null},serialize:F,batch:x,shouldProcess:function(e){return!P},createPayload:function(e){return null},createOneDSPayload:function(e){if(u[jA])return u[jA](e,v)}}}catch(e){}return null},e._doTeardown=function(e,t){K(2,2),R=!0,u.teardown(),n(),q()},e.setEventQueueLimits=function(e,t){i[gP]=a=Gw(e)?e:jP,i[pP]=g=Gw(t)?t:0,he();var n=O>e;if(!n&&p>0)for(var r=1;!n&&r<=3;r++){var s=h[r];s&&s[KA]&&cy(s[KA],(function(e){e&&e[EA]()>=p&&(n=!0)}))}Y(!0,n)},e.pause=function(){W(),D=!0,u.pause()},e.resume=function(){D=!1,u.resume(),G()},e._loadTransmitProfiles=function(e){W(),ie(),L=Jw,G(),iS(e,(function(e,t){var i=t[yA];if(i>=2){var n=i>2?t[2]:0;if(t[wA](0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t[_A](n),N[e]=t}}))},e.flush=function(e,t,i){var n;if(void 0===e&&(e=!0),!D)if(i=i||1,e)t||(n=oE((function(e){t=e}))),null==r?(W(),X(1,0,i),r=z((function(){r=null,ee(t,i)}),0)):M[_A](t);else{var s=W();$(1,1,i),t&&t(),s&&G()}return n},e.setMsaAuthTicket=function(e){u[YA](lA,e)},e.setAuthPluginHeader=function(e){u[YA](cA,e)},e.removeAuthPluginHeader=function(){u.removeHeader(cA)},e.hasEvents=j,e._setTransmitProfile=function(e){L!==e&&void 0!==N[e]&&(W(),L=e,G())},YE(e,(function(){return u}),["addResponseHandler"]),e[uP]=function(){c<4&&(c++,W(),G())},e._clearBackOff=function(){c&&(c=0,W(),G())}})),n}return jy(t,e),t.__ieDyn=1,t}(kI),KP="locale",JP="ver",YP="name",QP=_C({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"]}),ZP=_C({id:[0,"id"],ver:[1,JP],appName:[2,YP],locale:[3,KP],expId:[4,"expId"],env:[5,"env"]}),XP=_C({domain:[0,"domain"],browser:[1,"browser"],browserVer:[2,"browserVer"],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),eR=_C({locale:[0,KP],localId:[1,"localId"],id:[2,"id"]}),tR=_C({osName:[0,YP],ver:[1,JP]}),iR=_C({ver:[0,JP],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),nR=_C({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,"serviceName"]}),rR=_C({popSample:[0,"popSample"],eventFlags:[1,"eventFlags"]}),sR=_C({tz:[0,"tz"]}),aR=_C({sessionId:[0,"sesId"]}),oR=_C({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),lR=_C({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),cR=_C({traceId:[0,"traceID"],traceName:[1,YP],parentId:[2,"parentID"]}),dR=_C({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function uR(){return void 0===HP&&(HP=!!gR(0)),HP}function hR(){return uR()?gR(0):null}function gR(e){var t,i,n=null;try{var r=GS();if(!r)return null;i=new Date,(n=0===e?r.localStorage:r.sessionStorage)&&Gv(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}function pR(){return this.getId()}function mR(e){this.setId(e)}var fR=function(){function e(){TC(e,this,(function(e){e.setId=function(t){e.customId=t},e.getId=function(){return jv(e.customId)?e.customId:e.automaticId}}))}return e._staticInit=void oS(e.prototype,"id",{g:pR,s:mR}),e}(),vR="ai_session",SR=function(){function e(t,i,n){var r,s,a,o=y_(t),l=G_(t);TC(e,this,(function(t){var c=t_(i,(function(){a=i,t.config=a}));function d(){var e=l.get(s());if(e&&Gv(e.split))u(e);else{var i=function(e,t){var i=hR();if(null!==i)try{return i.getItem(t)}catch(t){HP=!1,__(e,1,503,"Browser failed read of local storage. "+t)}return null}(o,s());i&&u(i)}t.automaticSession.getId()||h()}function u(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){__(o,1,510,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&__(o,2,517,"AI session renewal date is 0, session will be reset.")}function h(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid;!Bv(n)&&n?Jv(n)?e.setId(Bw()):e.setId(Bw(n)):e.setId(Ab(a.idLength||22)),e.acquisitionDate=i,e.renewalDate=i,g(e.getId(),e.acquisitionDate,e.renewalDate),uR()||__(o,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function g(e,i,n){var a=i+t.config.sessionExpirationMs,o=n+t.config.sessionRenewalMs,c=new Date,d=[e,i,n];a<o?c.setTime(a):c.setTime(o);var u=t.config.cookieDomain||null;l.set(s(),d.join("|")+";expires="+c.toUTCString(),null,u),r=(new Date).getTime()}n&&n.add(c),s=function(){return t.config.namePrefix?vR+t.config.namePrefix:vR},t.automaticSession=new fR,t.update=function(){t.automaticSession.getId()||d();var i=t.automaticSession,n=t.config,s=(new Date).getTime(),a=s-i.acquisitionDate>n.sessionExpirationMs,o=s-i.renewalDate>n.sessionRenewalMs;a||o?h():(!r||s-r>e.cookieUpdateInterval)&&(i.renewalDate=s,g(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;!function(e,t,i){!function(e,t,i){var n=hR();if(null!==n)try{return n.setItem(t,i),!0}catch(t){HP=!1,__(e,1,504,"Browser failed write to local storage. "+t)}}(o,s(),[e,t,i].join("|"))}(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.cookieUpdateInterval=6e4,e}(),yR=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function CR(e,t){void 0===t&&(t=yR);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)TR(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function TR(e,t){if(void 0===t&&(t=yR),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}function ER(){return this.getExpId()}var bR=function(){function e(t,i,n){var r,s=null,a=yR.slice(0),o=null;TC(e,this,(function(e){if(function(t){var s=t_(t,(function(){r=i&&i.getCookieMgr(),o=t||{},e.env=o.env||function(e){var t,i={},n=YS();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var s=t[r];s.name&&0===s.name.toLowerCase().indexOf(e)&&(i[s.name.replace(e,"")]=s.content)}}return i}("awa-").env}));n&&n.add(s)}(t),zS()){var l=YS().documentElement;l&&(e.locale=l.lang)}function c(e){e!==s&&(s=CR(e,a))}e.getExpId=function(){return o.expId?function(e){return c(e),s}(o.expId):(c(Uw(r,"Treatments")),s)}}))}return e.validateAppExpId=CR,e._staticInit=void oS(e.prototype,"expId",{g:ER}),e}(),_R=function(){},IR=function(){};function wR(){return this.getMsfpc()}function AR(){return this.getAnid()}var PR=function(){function e(t,i,n){var r;TC(e,this,(function(e){(function(t){var s=t_(t,(function(){r=i&&i.getCookieMgr();var n=t||{};n.serviceName&&(e.serviceName=n.serviceName)}));n&&n.add(s)})(t),e.getMsfpc=function(){return Uw(r,"MSFPC")},e.getAnid=function(){return Uw(r,"ANON").slice(0,34)}}))}var t;return e._staticInit=(oS(t=e.prototype,"msfpc",{g:wR}),void oS(t,"anid",{g:AR})),e}(),RR=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},MR={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},DR={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},kR="([\\d,_,.]+)",OR="Unknown",NR=[{r:MR.WINPHONE,os:"Windows Phone"},{r:MR.WINRT,os:"Windows RT"},{r:MR.WIN,os:"Windows"},{r:MR.IOS,os:"iOS"},{r:MR.ANDROID,os:"Android"},{r:MR.LINUX,os:"Linux"},{r:MR.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:MR.OSX,os:"Mac OS X"}];function LR(e,t){var i=e.match(new RegExp(t+" ([\\d,.]+)"));return i?DR[i[1]]?DR[i[1]]:i[1]:OR}function xR(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null}var FR=function(e,t){var i=null,n=null,r=null,s=null,a=t_(e,(function(){if((e||{}).populateOperatingSystemInfo){var t=ZS()||{},r=e.userAgent||t.userAgent||"",s=(e.userAgentData||{}).platform||(t.userAgentData||{}).platform;if(r){var a=function(e){for(var t=0;t<NR.length;t++){var i=NR[t];if(i.r&&e.match(i.r))return i.os;if(i.s&&-1!==e.indexOf(i.s))return i.os}return OR}(r.toLowerCase());i=a,n=function(e,t){return"Windows"===t?LR(e,"Windows NT"):"Android"===t?LR(e,t):"Mac OS X"===t?function(e){var t=e.match(new RegExp("Mac OS X "+kR));if(t){var i=t[1].replace(/_/g,".");if(i){var n=xR(i);return n?i.split(n)[0]:i}}return OR}(e):"iOS"===t?function(e){var t=e.match(new RegExp("OS "+kR));if(t){var i=t[1].replace(/_/g,".");if(i){var n=xR(i);return n?i.split(n)[0]:i}}return OR}(e):OR}(r,a)}i&&i!==OR||!jv(s)||(i=s)}}));t&&t.add(a),oS(this,"name",{s:function(e){r=e},g:function(){return r||i}}),oS(this,"ver",{s:function(e){s=e},g:function(){return s||n}})},UR="MicrosoftApplicationsTelemetryDeviceId",BR=function(){function e(t,i,n){var r,s=0;TC(e,this,(function(e){e.seq=s,e.epoch=wb(!1).toString(),e.getSequenceId=function(){return++s};var a=t_(t,(function(t){r=i&&i.getCookieMgr();var n=t.cfg.propertyStorageOverride;if(r.isEnabled()||n){var s=function(e,t,i){return t?t.getProperty(i)||"":Uw(e,i)}(r,n,UR);s||(s=cI()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(r,n,UR,s),e.installId=s}else r.purge(UR)}));n&&n.add(a)}))}return e.__ieDyn=1,e}(),VR=function(e,t,i,n,r){var s=this;s.traceId=t||dI();var a=t_(e,(function(){var t=e;if(t.enableDistributedTracing&&!i&&(i=dI().substring(0,16)),s.parentId=s.parentId||i,t.enableApplicationInsightsTrace&&!n){var r=hb();r&&r.pathname&&(n=r.pathname)}s.name=s.name||n}));r&&r.add(a)},HR="setLocalId";function $R(){return this.getLocalId()}function jR(e){this[HR](e)}var GR=function(){function e(t,i,n,r){var s,a,o;TC(e,this,(function(l){if(function(i){var c=t_(i,(function(){if(o=n&&n.getCookieMgr(),s=i,a=null,o&&o.isEnabled()&&(d(),s.enableApplicationInsightsUser)){var r=Uw(o,e.userCookieName);if(r){var c=r.split(e.cookieSeparator);c.length>0&&(l.id=c[0])}if(!l.id){l.id=Ab(t&&!Bv(t.idLength)?t.idLength:22);var u=zE(new Date);l.accountAcquisitionDate=u;var h=[l.id,u],g=s.cookieDomain?s.cookieDomain:void 0;o.set(e.userCookieName,h.join(e.cookieSeparator),31536e3,g)}}}));r&&r.add(c)}(i),"undefined"!=typeof navigator){var c=navigator;l.locale=c.userLanguage||c.language}function d(){if(!s.hashIdentifiers&&!s.dropIdentifiers){var e=Uw(o,"MUID");e&&(a="t:"+e)}return a}l.getLocalId=function(){return a||d()},l[HR]=function(e){a=e}}))}return e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void oS(e.prototype,"localId",{g:$R,s:jR}),e}(),qR=function(e,t){var i=this;i.popSample=100;var n=t_(e,(function(){i.eventFlags=0,e.hashIdentifiers&&(i.eventFlags=1048576|i.eventFlags),e.dropIdentifiers&&(i.eventFlags=2097152|i.eventFlags),e.scrubIpOnly&&(i.eventFlags=4194304|i.eventFlags)}));t&&t.add(n)},zR=["Required","Analytics","SocialMedia","Advertising"],WR="([\\d,.]+)",KR="Unknown",JR="Edg/",YR=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:JR,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"}],QR=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function ZR(e,t){return t.indexOf(e)>-1}function XR(e,t){for(var i=0;i<t.length;i++)if(e==t[i].brand)return t[i].version;return null}function eM(){return this.getUserConsent()}var tM=function(){function e(t,i,n){var r=G_(i),s=t||{},a=null,o=null,l=null,c=null,d=null,u=null,h=null;TC(e,this,(function(e){!function(e){var t=t_(e,(function(){if((s=e).populateBrowserInfo){var t=s.userAgent,i=(s.userAgentData||{}).brands;if(t!==a||i!==o){if(!t||!i||0===i.length){var n=ZS();n&&(t=t||n.userAgent||"",i=i||(n.userAgentData||{}).brands)}(function(e,t){if(zv(t))try{for(var i=0;i<QR.length;i++){var n=XR(QR[i].br,t);if(n)return d=QR[i].b,void(u=n)}}catch(e){}if(e){var r=function(e){if(e)for(var t=0;t<YR.length;t++)if(ZR(YR[t].ua,e))return YR[t].b;return KR}(e);d=r,u=function(e,t){return"MSIE"===t?function(e){var t=e.match(new RegExp("MSIE "+WR));if(t)return t[1];var i=e.match(new RegExp("rv:"+WR));return i?i[1]:void 0}(e):function(e,t){"Safari"===e?e="Version":"Edge"===e&&ZR(JR,t)&&(e="Edg");var i=t.match(new RegExp(e+"/"+WR));return i||"Opera"===e&&(i=t.match(new RegExp("OPR/"+WR)))?i[1]:KR}(t,e)}(e,r)}})(t,i),a=t,o=i}}h=Jv(s.gpcDataSharingOptIn)?s.gpcDataSharingOptIn:null}));n&&n.add(t)}(t);var i=hb();if(i){var g=i.hostname;g&&(e.domain="file:"===i.protocol?"local":g)}var p=function(){var e={h:0,w:0},t=QS();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e}();e.screenRes=p.w+"X"+p.h,e.getUserConsent=function(){return s.userConsented||!!Uw(r,s.userConsentCookieName||"MSCC")},e.getUserConsentDetails=function(){var e=null;try{var t=s.callback;if(t&&t.userConsentDetails){var i=t.userConsentDetails();if(i){e=s.disableConsentDetailsSanitize?i:{};for(var n=0;n<zR.length;n++){var r=zR[n];e[r]=i[r]||!1}}}return null!==h&&((e=e||{}).GPC_DataSharingOptIn=!!h),e?JSON.stringify(e):null}catch(e){}},lS(e,{userConsent:{g:e.getUserConsent},browser:{s:function(e){l=e},g:function(){return l||d}},browserVer:{s:function(e){c=e},g:function(){return c||u}},gpcDataSharingOptIn:{g:function(){return h},s:function(e){h=Jv(e)?e:null,s.gpcDataSharingOptIn=h}}})}))}return e._staticInit=void oS(e.prototype,"userConsent",{g:eM}),e}();function iM(e,t,i,n,r){var s=t.ext[QP[e]];if(s)try{iS(n,(function(e,t){if(jv(t)||Kv(t)||Jv(t)){var n=s[i[e]];!r&&(n||jv(n)||Kv(n)||Jv(n))&&(t=n),s[i[e]]=t}}))}catch(e){}return s}var nM,rM=function(){function e(t,i,n,r){TC(e,this,(function(e){e.app=new bR(i,n,r),e.cloud=new _R,e.user=new GR(t,i,n,r),e.os=new FR(i,r),e.web=new tM(i,n,r);var s=new BR(t,n,r),a=new PR(i,n,r),o=new qR(i,r);e.loc=new RR,e.device=new IR;var l=new SR(n,i,r);e.session=new fR;var c=void 0,d=function(e,t){var i=e||{};return{getName:function(){return i.name},setName:function(e){t&&t.setName(e),i.name=e},getTraceId:function(){return i.traceId},setTraceId:function(e){t&&t.setTraceId(e),hI(e)&&(i.traceId=e)},getSpanId:function(){return i.parentId},setSpanId:function(e){t&&t.setSpanId(e),gI(e)&&(i.parentId=e)},getTraceFlags:function(){return i.traceFlags},setTraceFlags:function(e){t&&t.setTraceFlags(e),i.traceFlags=e}}}(new VR(i,c,c,c,r),g()),u=!(i||{}).eventContainExtFields;function h(){var t=e.session;if(t&&jv(t.customId))return t.customId;l.update();var i=l.automaticSession;if(i){var n=i.getId();n&&jv(n)&&(t.automaticId=n)}return t.automaticId}function g(){var e=d;return n&&n.getTraceCtx&&(e=n.getTraceCtx(!1)||d),e}e.getTraceCtx=function(){return d},e.getSessionId=h,e.applyApplicationContext=function(t){var i,n=e.app;iM(4,t,ZP,((i={})[0]=n.id,i[1]=n.ver,i[2]=n.name,i[3]=n.locale,i[4]=n.getExpId(),i[5]=n.env,i),u)},e.applyUserContext=function(t){var i,n=e.user;iM(0,t,eR,((i={})[1]=n.getLocalId(),i[0]=n.locale,i[2]=n.id,i),u)},e.applyWebContext=function(t){var i,n=e.web;iM(3,t,XP,((i={})[0]=n.domain,i[1]=n.browser,i[2]=n.browserVer,i[3]=n.screenRes,i[5]=n.getUserConsentDetails(),i[4]=n.getUserConsent(),i),u)},e.applyOsContext=function(t){var i,n=e.os;iM(5,t,tR,((i={})[0]=n.name,i[1]=n.ver,i),u)},e.applySdkContext=function(e){var t;iM(6,e,iR,((t={})[2]=s.installId,t[1]=s.getSequenceId(),t[3]=s.epoch,t),u)},e.applyIntWebContext=function(e){var t;iM(7,e,nR,((t={})[0]=a.getMsfpc(),t[1]=a.getAnid(),t[2]=a.serviceName,t),u)},e.applyUtcContext=function(e){var t,i=((t={})[0]=o.popSample,t);o.eventFlags>0&&(i[1]=o.eventFlags),iM(8,e,rR,i,u)},e.applyLocContext=function(t){var i;iM(9,t,sR,((i={})[0]=e.loc.tz,i),u)},e.applySessionContext=function(e){var t;iM(4,e,aR,((t={})[0]=h(),t),u)},e.applyDeviceContext=function(t){var i,n=e.device;iM(1,t,oR,((i={})[0]=n.localId,i[2]=n.make,i[3]=n.model,i[1]=n.deviceClass,i),u)},e.applyCloudContext=function(t){var i,n=e.cloud;iM(10,t,lR,((i={})[0]=n.role,i[1]=n.roleInstance,i[2]=n.roleVer,i),u)},e.applyAITraceContext=function(e){var t;if(i.enableApplicationInsightsTrace){var n=g();n&&iM(2,e,cR,((t={})[0]=n.getTraceId(),t[1]=n.getName(),t[2]=n.getSpanId(),t),!1)}},e.applyDistributedTraceContext=function(e){var t,i=g();if(i){var n=((t={})[0]=i.getTraceId(),t[1]=i.getSpanId(),t),r=i.getTraceFlags();Vv(r)||(n[2]=r),iM(11,e,dR,n,!1)}}}))}return e.__ieDyn=1,e}(),sM=[QP[4],QP[0],QP[3],QP[5],QP[6],QP[7],QP[8],QP[9],QP[1],QP[2],QP[11],QP[10]],aM=SS({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:a_(),userAgentData:s_({brands:nM,mobile:nM,platform:nM}),userConsentCookieName:a_(),userConsented:!1,serviceName:a_(),env:a_(),expId:a_(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:a_(),namePrefix:a_(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:s_({userConsentDetails:null}),gpcDataSharingOptIn:nM,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),oM=function(e){function t(){var i,n,r,s=e.call(this)||this;return s.identifier="SystemPropertiesCollector",s.priority=3,s.version="4.2.1",TC(t,s,(function(e,t){function s(){i=null,n={}}function a(t){var n=e.identifier,s=e.core;e._addHook(t_(t,(function(){var e=bI(null,t,s);r=e.getExtCfg(n,aM)}))),i=new rM(t,r,s,e._unloadHooks),s&&s.setTraceCtx&&s.setTraceCtx(i.getTraceCtx())}s(),e.initialize=function(e,i,n){t.initialize(e,i,n),a(e)},e.processTelemetry=function(t,s){$w(t,e.identifier),s=e._getTelCtx(s);var a=t.ext=t.ext?t.ext:{};t.data=t.data?t.data:{},cy(sM,(function(e){a[e]=a[e]||{}})),i&&(i.applyUtcContext(t),i.applyApplicationContext(t),i.applyUserContext(t),i.applyWebContext(t),i.applyOsContext(t),i.applySdkContext(t),i.applyIntWebContext(t),i.applyLocContext(t),i.applySessionContext(t),i.applyDeviceContext(t),r.enableApplicationInsightsTrace&&i.applyAITraceContext(t),r.enableDistributedTracing&&i.applyDistributedTraceContext(t),i.applyCloudContext(t)),cy(vS(a),(function(e){0===vS(a[e]).length&&delete a[e]})),function(e,t){e&&iS(e,(function(e,i){t[e]||(t[e]=i)}))}(n,t.data),e.processNext(t,s)},e.getPropertiesContext=function(){return i},e.setProperty=function(e,t){n[e]=t},e._doTeardown=function(e,t){var n=(e||{}).core();if(n&&n.getTraceCtx&&i){var r=n.getTraceCtx(!1);r&&r===i.getTraceCtx()&&n.setTraceCtx(null)}s()},e._getDbgPlgTargets=function(){return[r]}})),s}return jy(t,e),t.__ieDyn=1,t}(kI),lM=function(e){this._setOverride=function(t,i){e.setOverride(t,i)},this._getOverride=function(t){return e.getOverride(t)}},cM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setId=function(e){s._setOverride(ZP.id,e)},s.getId=function(){return s._getOverride(ZP.id)},s.setVer=function(e){s._setOverride(ZP.ver,e)},s.getVer=function(){return s._getOverride(ZP.ver)},s.setName=function(e){s._setOverride(ZP.appName,e)},s.getName=function(){return s._getOverride(ZP.appName)},s.setLocale=function(e){s._setOverride(ZP.locale,e)},s.getLocale=function(){return s._getOverride(ZP.locale)},s.setEnv=function(e){s._setOverride(ZP.env,e)},s.getEnv=function(){return s._getOverride(ZP.env)},s.setExpId=function(e){s._setOverride(ZP.expId,bR.validateAppExpId(e))},s.getExpId=function(){return s._getOverride(ZP.expId)};var a=t_(i,(function(){i&&(Bv(i.env)||s.setEnv(i.env),Vv(i.expId)||s.setExpId(i.expId))}));return n&&n.add(a),r}return jy(t,e),t}(lM),dM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setRole=function(e){n._setOverride(lR.role,e)},n.getRole=function(){return n._getOverride(lR.role)},n.setRoleInstance=function(e){n._setOverride(lR.roleInstance,e)},n.getRoleInstance=function(){return n._getOverride(lR.roleInstance)},n.setRoleVer=function(e){n._setOverride(lR.roleVer,e)},n.getRoleVer=function(){return n._getOverride(lR.roleVer)},i}return jy(t,e),t}(lM),uM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setProperty=function(e,t){n._setOverride(e,t)},n.getProperty=function(e){return n._getOverride(e)},i}return jy(t,e),t}(lM),hM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(oR.localId,e)},n.getLocalId=function(){return n._getOverride(oR.localId)},n.setDeviceClass=function(e){n._setOverride(oR.deviceClass,e)},n.getDeviceClass=function(){return n._getOverride(oR.deviceClass)},n.setMake=function(e){n._setOverride(oR.make,e)},n.getMake=function(){return n._getOverride(oR.make)},n.setModel=function(e){n._setOverride(oR.model,e)},n.getModel=function(){return n._getOverride(oR.model)},i}return jy(t,e),t}(lM),gM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setTz=function(e){n._setOverride(sR.tz,e)},n.getTz=function(){return n._getOverride(sR.tz)},i}return jy(t,e),t}(lM),pM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r,a=null;s.setOsName=function(e){s._setOverride(tR.osName,e)},s.getOsName=function(){return s._getOverride(tR.osName)},s.setVer=function(e){s._setOverride(tR.ver,e)},s.getVer=function(){return s._getOverride(tR.ver)};var o=t_(i,(function(){!a&&i.userAgent&&i.populateOperatingSystemInfo&&(a=new FR(i,n)),a&&(s.setOsName(a.name),s.setVer(a.ver))}));return n&&n.add(o),r}return jy(t,e),t}(lM);function mM(e,t){if(e)for(var i=0;i<t.length;i++){var n=t[i];Vv(e[n])&&(e[n]={}),e=e[n]}return e}var fM,vM,SM=function(e){var t=this,i=[];t.setOverride=function(e,t){e&&i.push({key:e,value:t})},t.hasOverride=function(e){var t=!1;return cy(i,(function(i){i.key===e&&(t=!0)})),t},t.getOverride=function(e){var t;return cy(i,(function(i){i.key===e&&(t=i.value)})),t},t.applyOverrides=function(t,n){if(i.length>0)try{var r=mM(t,e);cy(i,(function(e){!function(e,t,i){if(e&&t){var n=t.split("."),r=n[n.length-1];n.length>1&&(e=mM(e,n.slice(0,-1))),Vv(i)?Bv(e[r])||delete e[r]:e[r]=i}}(r,e.key,e.value)}))}catch(e){}}},yM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(eR.localId,e)},n.getLocalId=function(){return n._getOverride(eR.localId)},n.setLocale=function(e){n._setOverride(eR.locale,e)},n.getLocale=function(){return n._getOverride(eR.locale)},n.setId=function(e){n._setOverride(eR.id,e)},n.getId=function(){return n._getOverride(eR.id)},i}return jy(t,e),t}(lM),CM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setDomain=function(e){s._setOverride(XP.domain,e)},s.getDomain=function(){return s._getOverride(XP.domain)},s.setBrowser=function(e){s._setOverride(XP.browser,e)},s.getBrowser=function(){return s._getOverride(XP.browser)},s.setBrowserVer=function(e){s._setOverride(XP.browserVer,e)},s.getBrowserVer=function(){return s._getOverride(XP.browserVer)},s.setScreenRes=function(e){s._setOverride(XP.screenRes,e)},s.getScreenRes=function(){return s._getOverride(XP.screenRes)},s.setUserConsent=function(e){s._setOverride(XP.userConsent,e)},s.getUserContext=function(){return s._getOverride(XP.userConsent)};var a=t_(i,(function(){i&&(Bv(i.userConsented)||s.setUserConsent(i.userConsented))}));return n&&n.add(a),r}return jy(t,e),t}(lM),TM="ext",EM=function(e,t,i,n){var r=this,s={};function a(e){for(var t="",i=0;i<e.length;i++)t&&(t+="_"),t+=e[i];return Bv(s[t])&&(s[t]=new SM(e)),t?s[t]:null}r.data=new uM(a(["data"])),r.app=new cM(a([TM,QP.AppExt]),t,n),r.user=new yM(a([TM,QP.UserExt])),r.os=new pM(a([TM,QP.OSExt]),t,n),r.web=new CM(a([TM,QP.WebExt]),t,n),r.device=new hM(a([TM,QP.DeviceExt])),r.loc=new gM(a([TM,QP.LocExt])),r.cloud=new dM(a([TM,QP.CloudExt])),r.applyOverrides=function(e,t){var i=vS(s);i&&i.length>0&&cy(i,(function(i){s[i].applyOverrides(e,t)}))}},bM=void 0,_M=SS({env:bM,expId:bM,populateOperatingSystemInfo:!1,userAgent:bM,userAgentData:s_({brands:bM,mobile:bM,platform:bM}),userConsented:bM}),IM="OverridePropertiesPlugin",wM=function(e){function t(){var i=e.call(this)||this;i.identifier=IM,i.priority=4,i.version="4.2.1";var n=null;return TC(t,i,(function(e,t){e.initialize=function(i,n,r){t.initialize(i,n,r),e._baseInit(i,n,r)},e.processTelemetry=function(t,n){$w(t,i.identifier),n=e._getTelCtx(n);var r=e.getOverrideContext();r&&r.applyOverrides(t,n),e.processNext(t,n)},e._baseInit=function(t,r,s){n=new EM(t,i._getTelCtx().getExtCfg(i.identifier,_M),r,e._unloadHooks)},e.setProperty=function(e,t){n&&n.data.setProperty(e,t)},e.getOverrideContext=function(){return n}})),i}return jy(t,e),t.__ieDyn=1,t}(kI),AM="_dropInst",PM=["channelConfiguration","propertyStorageOverride"];function RM(e,t){if(t)for(var i=vS(t),n=0;n<i.length;n++){var r=i[n];tS(e,r)||Ly(r,"Symbol(")||(e[r]=t[r])}}function MM(e,t,i){var n;return oS(e,t,{g:function(){return function(e){return e===fv||$v(typeof e)}(i)?i:(zv(i)?(zv(n)||(n=[]),n.length=i.length):qv(n)||(n={}),iS(i,(function(e,t){Ly(e,"Symbol(")||MM(n,e,t)})),n)}})}function DM(e,t){var i=null;if(t){t.endpointUrl&&(i=t.endpointUrl);var n=(t.extensionConfig||{})[e]||{};n.overrideEndpointUrl&&(i=n.overrideEndpointUrl)}return i}var kM=SS({cookieCfg:{},channelConfiguration:s_({}),propertyConfiguration:s_({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:s_({}),createPerfMgr:vM,loggingLevelConsole:0}),OM=SS({propertyConfiguration:s_({}),cookieCfg:s_({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:s_((fM={},fM[IM]=s_({}),fM)),createPerfMgr:vM,loggingLevelConsole:0}),NM=function(e){function t(i,n){var r=e.call(this)||this;return TC(t,r,(function(e,t){function r(e){var t=[];return e&&cy(e,(function(e){e.iKey===i&&t.push(e)})),t}function s(t){if(e[t]&&e.listeners)for(var i=0;i<e.listeners.length;i++){var n=e.listeners[i];if(n&&n[t])return!0}return!1}var a={eventsSent:function(t){if(s("eventsSent")){var i=r(t);i.length>0&&e.eventsSent(i)}},eventsDiscarded:function(t,i){if(s("eventsDiscarded")){var n=r(t);n.length>0&&e.eventsDiscarded(n,i)}},eventsSendRequest:function(t,i){s("eventsSendRequest")&&e.eventsSendRequest(t,i)},perfEvent:function(t){s("perfEvent")&&e.perfEvent(t)}};n.addNotificationListener(a)})),r}return jy(t,e),t.__ieDyn=1,t}(tI),LM=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m=null,f=null;TC(e,this,(function(e){function v(){t=e_({},kM,null),i=[],n=null,r=null,s=[],a=[],o={},l=null,c=null,d=null,h=null,g=null,p=!1,t.cfg.loggingLevelConsole=1,u=new E_(t.cfg),oS(e,"sharedConfig",{g:function(){return p&&C(),t.cfg}})}function S(e,i){var n;if(void 0===i&&(i=null),e){(!function(e){return e.pause&&e.teardown&&e.flush}(e)?s:a).push(e);var r=e.identifier,o=t.cfg.extensionConfig;t.setDf(o,((n={})[r]={ref:!0,v:i||{}},n))}return e}function y(e){var n=t.cfg;i=[],l=S(new oM,n.propertyConfiguration),i.push(l),n.extensions&&cy(n.extensions,(function(e){Gv(e)||S(e)})),e&&cy(e,(function(e){e&&!Gv(e)&&i.push(S(e))}))}function C(){n||(p||__(e.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),t.cfg.instrumentationKey=t.cfg.instrumentationKey||"_not_defined_",r=new tI,(n=new xM(e,e.diagLog(),r)).initialize(t.cfg,i),n.isInitialized()&&(lS((t=$b(n.config)).cfg,{channelConfiguration:{g:function(){return t.cfg.extensionConfig[c.identifier]}},propertyConfiguration:{g:function(){return t.cfg.extensionConfig[l.identifier]}}}),c&&(d=DM(c.identifier,t.cfg))),m&&n.setCookieMgr(m))}function T(i,n){var r=[],s=t.cfg,a={};if(iS(s.extensionConfig,(function(e,t){e===c.identifier||e===l.identifier||Ly(e,"Symbol(")||(e!==IM?MM(a,e,t):(a[e]={},RM(a[e],t)))})),n){n.extensions&&n.extensions.length>0&&(r=ly(r,n.extensions));var o=n.extensionConfig;o&&(tS(o,c.identifier)&&vS(o).length>0&&__(e.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),RM(a,o))}var d={instrumentationKey:i,channels:E(n),extensions:r,extensionConfig:a};return RM(d,n),d}function E(e){var i=t.cfg,n=[[]];return i.channels&&cy(i.channels,(function(e,t){Gv(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),e&&e.channels&&cy(e.channels,(function(e,t){Gv(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),n}function b(e){var t=[];return i&&i.length>0&&(t=t.concat(i)),e&&e.length>0&&(t=t.concat(e)),t}v(),e.diagLog=function(){return u||(u=new E_(t.cfg)),u},e.getCookieMgr=function(){return C(),m||n.getCookieMgr()},e.setCookieMgr=function(e){m=e,n&&n.setCookieMgr(e)},e.getPerfMgr=function(){return g||t&&t.cfg.enablePerfMgr&&(g=f||new aI(e.getNotifyMgr())),g},e.setPerfMgr=function(e){f=e,g=e},e.create=function(i,r){p?__(e.diagLog(),2,514,"Shared Manager has already been initialized."):(t=e_(function(e){if(e&&zv(e.extensionConfig)){var t=e.extensionConfig,i={};iS(t,(function(e,t){Gv(t)||Ly(e,"Symbol(")||(i[e]=t)})),e.extensionConfig=i}return e}(i?ZE({},i):{}),kM,null),n=null,function(){var e=t.cfg,i=e.channels,n=new WP,r=n.identifier,s=!1;c=null,d=null,cy(i,(function(e){s||cy(e,(function(e){if(!Gv(e)&&(S(e),e.identifier===r))return c=e,s=!0,-1}))})),s||(c=S(n,e.channelConfiguration),i.length>0?ly(i[0],c):e.channels.push([c]))}(),y(r),p=!0)},e.getInst=function(e){return(o[e]||{}).inst},e.newInst=function(i,s,a){var l=e.getInst(i);if(l)return __(e.diagLog(),2,514,"Instance already exists for ["+i+"]"),l;if(C(),n.isInitialized()){var u=T(i,s);if(c){var h=DM(c.identifier,u);d&&h&&d!==h&&__(e.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+d+"] is different from configured ["+h+"] shared will be used!")}var g=new NM(i,r);if(l=new xM(e,e.diagLog(),g),o[i]={iKey:i,inst:l,notifyMgr:g},l.setPerfMgr(e.getPerfMgr()),l.initialize(u,b(a)),l.isInitialized()){var p=l.config;lS(p,{propertyConfiguration:{g:function(){return p.extensionConfig[IM]}}});try{delete p.endpointUrl,delete p.channelConfiguration,delete p.propertyStorageOverride}catch(t){__(e.diagLog(),2,108,"Failed to remove unused defaults!")}iS(t.cfg,(function(e,t){tS(p,e)||Ly(e,"Symbol(")||gy(PM,e)||MM(p,e,t)}))}else __(e.diagLog(),2,520,"Failed to initialize new instance!"),l=null,delete o[i]}return l},e.getSharedPlugin=function(e){C();var t=null,i=n.getPlugin(e);return i&&(t=i.plugin),t},e.getPropertyManager=function(){return C(),l},e.getPostChannel=function(){return C(),c},e.getNotifyMgr=function(){return h||(h=new tI),h},e.unload=function(e,t,i){var r,s=vS(o),a=s.length+1,l={reason:50,isAsync:e,flushComplete:!1};function c(e,i){0==--a&&(v(),t&&t(i))}return e&&!t&&(r=oE((function(e){t=e}))),n&&(cy(s,(function(t){!function(e,t,i,n){var r=o[e];r&&(r.inst&&r.inst.isInitialized()?r.inst.unload(t,(function(e){i&&i(0,e)}),n):i&&i(0,{reason:50,isAsync:t,flushComplete:!1}))}(t,e,(function(e,t){c(0,t)}),i)})),n.isInitialized()&&(n.unload(e,(function(e){c(0,l=e)}),i),n=null)),c(0,l),r},e.addUnloadHook=function(e){C(),n.addUnloadHook(e)},e.addSharedPlugin=function(e,t,i,r){return C(),n.addPlugin(e,t,i,r)},e.updateCfg=function(e,t){return C(),n.updateCfg(e,t)},e.evtNamespace=function(){return C(),n.evtNamespace()},e.addUnloadCb=function(e){C(),n.addUnloadCb(e)},e.onCfgChange=function(e){return C(),n.onCfgChange(e)},e[AM]=function(e){e&&o.iKey&&delete o[e]}}))}return e.__ieDyn=1,e}(),xM=function(e){function t(i,n,r){var s,a=e.call(this)||this,o=i;return TC(t,a,(function(e,t){e.getSharedPropertyManager=function(){return o.getPropertyManager()},e.getSharedPostChannel=function(){return o.getPostChannel()},e.getOverridePropertyManager=function(){return s},e.initialize=function(i,a){lI(e,(function(){return"ApplicationInsights:initialize"}),(function(){var o=[s=new wM];a&&(o=o.concat(a));var l=i.propertyConfiguration||{};if(i.propertyConfiguration)try{delete i.propertyConfiguration}catch(e){i.propertyConfiguration={}}i.extensionConfig=i.extensionConfig||{},i.extensionConfig[s.identifier]=l,i=e_(i,OM,n||e.logger,!1).cfg;try{t.initialize(i,o,n,r)}catch(t){__(e.logger,1,514,"Failed to initialize SDK."+hS(t))}}),(function(){return{config:i,extensions:a}}))},e.unload=function(i,n,r){return o[AM]&&o[AM]((e.config||{}).instrumentationKey),t.unload(i,n,r)}})),a}return jy(t,e),t.__ieDyn=1,t}(zw),FM=class{constructor(e){this.key=e.config.bwSeedOptions.localStorageKey||"bwSeed";const t=localStorage.getItem(this.key);parseInt(t)||localStorage.setItem(this.key,e.config.bwSeedOptions.constValue.toString())}getSeed(){const e=localStorage.getItem(this.key),t=parseInt(e);return isNaN(t)?void 0:t}saveSeed(e){localStorage.setItem(this.key,e.toString())}static localStorageAvailable(){try{const e=window.localStorage,t="someKey",i="someValue";return e.setItem(t,i),e.removeItem(t),!0}catch(e){return!1}}},UM=class e{constructor(t){e.value??(e.value=t.config.bwSeedOptions.constValue)}getSeed(){return e.value}saveSeed(t){e.value=t}},BM=class{constructor(e){this.value=e}addValue(e){}getAggregated(){return this.value}},VM=class{addValue(e){this.value=e}getAggregated(){return this.value}},HM=class{constructor(e){this.size=e,this.items=[]}clear(){this.items=[]}},$M=class extends HM{get isFull(){return this.items.length>=this.size}add(e){return this.isFull&&this.items.shift(),this.items.push(e),!0}},jM=class extends HM{add(e){return!(this.items.length>=this.size||(this.items.push(e),0))}},GM=class{constructor(e){this.values=new $M(e)}addValue(e){this.values.add(e)}getAggregated(){return Math.floor(Yi(this.values.items))}},qM=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(e){(e||0===e)&&(this.total+=e,this.duration++,this.max=Math.max(e,this.max),0!==e&&(this.minNonZero=Math.min(e,this.minNonZero)))}},zM=class{constructor(){this.sampleCounts={}}get min(){const e=Object.keys(this.sampleCounts).map(Number).filter((e=>e>0));return e.length>0?Math.min(...e):0}get max(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?Math.max(...e):0}get mode(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?e.reduce(((e,t)=>this.sampleCounts[t]>this.sampleCounts[e]?t:e),e[0]):0}captureSample(e){var t;if(void 0!==e){const i=`${e}`;(t=this.sampleCounts)[i]??(t[i]=0),this.sampleCounts[i]++}}},WM=class{get delta(){if(void 0!==this.cur&&void 0!==this.last)return this.cur-this.last}captureSample(e,t){void 0!==e&&(void 0!==this.cur&&(this.last=this.cur),this.cur=e)}},KM=class{constructor(e=0){this.precision=e}get delta(){if(void 0!==this.currentSample&&void 0!==this.prevSample){let e=1;return void 0!==this.currentTimestamp&&void 0!==this.prevTimestamp&&(e=(this.currentTimestamp-this.prevTimestamp)/1e3),e&&mn((this.currentSample-this.prevSample)/e,this.precision)}}captureSample(e,t){if(this.currentTimestamp!==t){if(void 0===e)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=t,this.currentSample=e}}},JM=class{constructor(){this.startTime=Date.now()}get elapsed(){return mn((Date.now()-this.startTime)/1e3,0)}},YM=class{constructor(e){this.numOfHistogramSamples=e,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 qM}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 nn(this.timestampBuckets)}get counts(){return nn(this.countBuckets)}set active(e){if(!this.current&&e)this.current=new JM;else if(this.current&&!e){const e=this.current.elapsed;this.averager.captureSample(e),this.totalActiveDuration+=e;for(const t of Object.keys(Gi.HISTOGRAM_BATCH))if(e<=Gi.HISTOGRAM_BATCH[t]){this.countBuckets[t]++,Sn(this.timestampBuckets[t],this.current.startTime,this.numOfHistogramSamples);break}this.eventCount++,this.current=void 0}}},QM=class{constructor(){this.sampleChangeCount=0,this.sampleDurations={}}get durations(){return nn(this.sampleDurations)}get sortedDurations(){return Object.keys(this.sampleDurations).sort(((e,t)=>this.sampleDurations[t]-this.sampleDurations[e]))}get durationRatios(){const e={};let t=0;for(const e in this.sampleDurations)t+=this.sampleDurations[e];for(const i in this.sampleDurations)e[i]=mn(this.sampleDurations[i]/t*100);return e}get changeCount(){return this.sampleChangeCount}captureSample(e){this.sampleDurations[e]||(this.sampleDurations[e]=0),this.sampleDurations[e]++,e!==this.lastSample&&(this.sampleChangeCount++,this.lastSample=e)}},ZM=class{constructor(e,t){this.validTimeBetweenFramesArrival=e,this.invalidFPSAboveMax=t,this.lastSampleTimestamp=-1,this.fpsHarmonicSumWeigtsTs=0,this.fpsHarmonicWeigtedSumsFramePerDelayTs=0}captureSample(e){const t=Date.now();if(e>0&&this.lastSampleTimestamp>0){const i=t-this.lastSampleTimestamp;if(this.lastSampleTimestamp=t,i<0||i>this.validTimeBetweenFramesArrival||e>this.invalidFPSAboveMax)return;const n=i/e;this.fpsHarmonicSumWeigtsTs+=i,this.fpsHarmonicWeigtedSumsFramePerDelayTs+=i*n}(this.lastSampleTimestamp<0||0===e)&&(this.lastSampleTimestamp=t)}get harmonicMean(){return this.fpsHarmonicWeigtedSumsFramePerDelayTs>0?1e3*this.fpsHarmonicSumWeigtsTs/this.fpsHarmonicWeigtedSumsFramePerDelayTs:0}},XM=class{constructor(e){this.samplesNum=e,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(e){void 0===e||e<0||(Sn(this.samples,e,this.samplesNum),this.sortedSamples=nn(this.samples).sort(((e,t)=>e-t)),this.lastReport={avg:this.getAvg(),median:this.calculatePercentile(50),p90:this.calculatePercentile(90),max:this.calculatePercentile(100),volatilityPercent:this.getVolatility()})}getAvg(){return Yi(this.samples)}getVolatility(){const e=this.getAvg();if(0===e)return 0;let t=0;return this.samples.forEach((i=>{t+=Math.abs(i-e)})),mn(t/this.samples.length*100/e,2)}calculatePercentile(e){if(e<0||e>100)throw new Error("Percentile must be between 0 and 100");const t=e/100*(this.sortedSamples.length-1),i=Math.floor(t),n=Math.ceil(t),r=t-i;return n>=this.sortedSamples.length?this.sortedSamples[i]:this.sortedSamples[i]*(1-r)+this.sortedSamples[n]*r}},eD=class{constructor(){this.duration=0,this.reportAggr={avg:0,max:0,median:0,p90:0,volatilityPercent:0}}captureSample(e){!e||e.avg<0||(this.reportAggr={avg:this.reportAggr.avg+e.avg,max:Math.max(this.reportAggr.max,e.max),median:this.reportAggr.median+e.median,p90:this.reportAggr.p90+e.p90,volatilityPercent:this.reportAggr.volatilityPercent+e.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}}},tD=class{constructor(e,t=0){this.overshootType=e,this.allowedOvershoot=t,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(e,t){const i=mn(e-t);i>this.allowedOvershoot&&(0===this.lastAllowed||t===this.lastAllowed||!this.current&&t>this.lastAllowed)?(this.totalOvershootDuration++,this.current?(this.current.min=Math.min(this.current.min,i),this.current.max=Math.max(this.current.max,i)):this.current={timestamp:Date.now(),min:i,max:i,type:this.overshootType}):this.current&&(this.current.duration=Date.now()-this.current.timestamp,this.past.push(this.current),this.current=void 0),this.lastAllowed=t}},iD=class{constructor(e=!1){this.disableNormalization=e,this.prevLost=0,this.prevReceived=0,this.minPackets=100}calculate(e,t){if(void 0===e||void 0===t)return;const i=e-this.prevReceived,n=t-this.prevLost;if(i+n<this.minPackets)return;this.prevReceived=e,this.prevLost=t;const r=n*(this.disableNormalization?1:this.minPackets)/(n+i);return r>(this.disableNormalization?1:this.minPackets)?0:r}},nD=class{constructor(){this.capturedSamples=[]}captureSample(e){e&&this.capturedSamples.push(e)}calculateStd(){if(!this.capturedSamples.length)return;const e=this.capturedSamples.reduce(((e,t)=>e+t),0)/this.capturedSamples.length,t=this.capturedSamples.map((t=>(t-e)**2)),i=t.reduce(((e,t)=>e+t),0)/t.length;return mn(Math.sqrt(i),2)}getFirst(){return this.capturedSamples[0]}getLast(){if(this.capturedSamples.length)return this.capturedSamples[this.capturedSamples.length-1]}calculatePercentile(e){if(!this.capturedSamples.length)return;const t=this.capturedSamples.sort(((e,t)=>e-t)),i=(t.length-1)*e,n=Math.floor(i),r=i-n;return void 0!==t[n+1]?t[n]+r*(t[n+1]-t[n]):t[n]}};function rD(e){if(!e)return;const t=["libvpx","ffmpeg"];let i=!0;for(const n of t)if(e.toLowerCase().includes(n)){i=!1;break}return i}var sD=class{constructor(e){this.samplesCount=e,this.capturedSamples=[]}captureSample(e){void 0!==e&&Sn(this.capturedSamples,e,this.samplesCount)}getRate(){if(!this.capturedSamples.length)return;const e=this.samplesCount/this.capturedSamples.length;return this.capturedSamples.reduce(((e,t)=>e+t))*e/this.samplesCount}},aD=class{constructor(e=5){this.limit=e,this.curWidth=0,this.curHeight=0,this.resolutionSwitches=[]}captureSample(e,t){e===this.curWidth&&t===this.curHeight||(Sn(this.resolutionSwitches,`${e}x${t}`,this.limit),this.curWidth=e,this.curHeight=t)}get switches(){if(this.resolutionSwitches.length)return this.resolutionSwitches}};function oD(e,t,i){return e&&t?Math.ceil(e/Gi.MACROBLOCK_SIZE)*Math.ceil(t/Gi.MACROBLOCK_SIZE)*i:0}var lD=class{constructor(){this.macroblockRateAveragerReceived=new qM,this.macroblockRateAveragerDecoded=new qM,this.maxDecoderLoss=0,this.decoderLoss=0}captureSample(e,t){this.macroblockRateAveragerReceived.captureSample(e),this.macroblockRateAveragerDecoded.captureSample(t);let i=this.maxDecoderLoss;e&&(i=(e-t)/e*100),this.decoderLoss=i,this.maxDecoderLoss=Math.max(i,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)}}},cD=class{constructor(){this.codecReport={}}captureSample(e,t){var i,n;const r=e.split("/").pop();return void 0===this.activeMsi||this.activeMsi!==t?(this.activeMsi=t,this.previousCodec=r,void((i=this.codecReport)[t]??(i[t]={[r]:1,codecSwitchCounter:0}))):this.previousCodec!==r?((n=this.codecReport[t])[r]??(n[r]=0),this.codecReport[t][r]++,this.codecReport[t].codecSwitchCounter++,void(this.previousCodec=r)):void this.codecReport[t][r]++}get report(){return this.codecReport}},dD=class{constructor(e=5){this.limit=e,this.curPowerEfficientCodecState=!1,this.powerEfficientCodecEvents=[],this.powerEfficientCodecEventOnCount=0,this.powerEfficientCodecEventOffCount=0}captureSample(e,t){if(e!==this.curPowerEfficientCodecState){const i={timestamp:Date.now(),powerEfficient:e,frameHeight:t};Sn(this.powerEfficientCodecEvents,i,this.limit),this.curPowerEfficientCodecState=e,e?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}},uD=class{constructor(){this.bandwidthAverager=new qM}addValue(e){this.bandwidthAverager.captureSample(e)}getAggregated(){return Math.floor(this.bandwidthAverager.avg)}},hD=class{constructor(e){this.configProvider=e,this.aggregator=this.getAggregator(),this.storage=this.getStorage(),this.cappingValue=this.configProvider.config.bwSeedOptions.cappingValue,this.minValue=this.configProvider.config.bwSeedOptions.minValue??-1}getSeed(){const e=this.storage.getSeed()??-1;return this.cappingValue>0?Math.min(Math.max(e,this.minValue),this.cappingValue):Math.max(e,this.minValue)}saveSeed(e){this.aggregator.addValue(e);const t=this.aggregator.getAggregated();this.storage.saveSeed(t)}getAggregator(){switch(this.configProvider.config.bwSeedOptions.aggregation){case"avg":return this.configProvider.config.bwSeedOptions.aggregateLastN>0?new GM(this.configProvider.config.bwSeedOptions.aggregateLastN):new uD;case"last":return new VM;default:return new BM(this.configProvider.config.bwSeedOptions.constValue)}}getStorage(){return this.configProvider.config.bwSeedOptions.useLocalStorage&&FM.localStorageAvailable()?new FM(this.configProvider):new UM(this.configProvider)}},gD=Z;function pD(e,t){const i=e.width/e.height,n=(0,gD.clone)(e);return i>t?n.width=Math.floor(e.height*t):i<t&&(n.height=Math.floor(e.width/t)),n}var mD=class e{constructor(e,t,i=!0,n=!1,r){this.audio=e,this.video=t,this.withTimeout=i,this.withEffect=n,this.withOverridenStream=r}clone(){const t=nn(this.video),i=nn(this.audio);return new e(i,t,this.withTimeout,this.withEffect,this.withOverridenStream)}},fD=class{constructor(e){this.logger=e}dispose(){}updateVideoConstraints(e,t,i){const n=this.calculateConstraints(t,i);this.logger.safe.info(`Calculated constraints: ${JSON.stringify(n)} from capabilities: ${JSON.stringify(t)}`);const r=n.resolution,s=n.fps,a=r&&(!dn(r.width,e.video.minWidth,e.video.maxWidth)||!dn(r.height,e.video.minHeight,e.video.maxHeight)),o=e.video.fps!==s;if(!a&&!o)return e;const l=e.clone();return a&&this.setResolution(l,r),o&&(l.video.fps=s),l}updateResolution(e,t){const i=e.clone();return this.setResolution(i,t),i}setResolution(e,t){e.video.maxWidth=t.width,e.video.minWidth=t.width,e.video.maxHeight=t.height,e.video.minHeight=t.height}getKey(e){return e.video?Xi(e.video)?"video":e.video.deviceId&&e.video.minWidth&&e.video.minHeight?`${e.video.deviceId}x${e.video.minWidth}x${e.video.minHeight}`:e.video.minWidth&&e.video.minHeight?`${e.video.minWidth}x${e.video.minHeight}`:e.video.deviceId?`${e.video.deviceId}`:(this.logger.safe.error(`Cannot create key for constraints: ${hm(e)}`),""):"audio"}convertConstraints(e,t={}){if(!e)return null;const i=nn(t);return e?.deviceId&&(i.deviceId=e.deviceId),i}},vD=class{constructor(){this.MAX_SHARING_WIDTH=1920,this.MAX_SHARING_HEIGHT=1080}getResolutionTable(e,t){const i=this.constraintToMaxResolution(e,t);return this.generateResolutionTable(i)}constraintToMaxResolution(e,t){const i=this.getPortraitOrLandscapeMaxResolution(e),n=pD({width:e.width,height:e.height},t),r=i.width/n.width,s=i.height/n.height,a=Math.min(r,s);return this.resizeResolution(n,a)}resizeResolution(e,t){return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}getPortraitOrLandscapeMaxResolution(e){return e.width>e.height?{width:this.MAX_SHARING_WIDTH,height:this.MAX_SHARING_HEIGHT}:{width:this.MAX_SHARING_HEIGHT,height:this.MAX_SHARING_WIDTH}}ceilToMackroblockSize(e){const t=e.width,i=e.height;return{width:Math.ceil(t/Gi.MACROBLOCK_SIZE)*Gi.MACROBLOCK_SIZE,height:Math.ceil(i/Gi.MACROBLOCK_SIZE)*Gi.MACROBLOCK_SIZE}}generateResolutionTable(e){return[1,2/3,1/3,1/6].map((t=>this.resizeResolution(e,t))).map((e=>this.ceilToMackroblockSize(e)))}},SD=class{constructor(e){this.logger=e,this.FPS_TABLE=[15,7.5,3.75,1.875],this.resolutionTableCalculator=new vD,this.initialAspectRatio=null}calculateConstraints(e,t){this.initialAspectRatio||(this.initialAspectRatio=t.width/t.height);const i=this.resolutionTableCalculator.getResolutionTable(t,this.initialAspectRatio);let n={resolution:i[i.length-1],fps:this.FPS_TABLE[this.FPS_TABLE.length-1]};return i.some((t=>{const i=this.getFs(t);return this.FPS_TABLE.some((r=>{const s=this.getMbps(i,r);return i<=e.maxFs&&r<=e.maxFps&&s<=e.maxMbps&&(n={resolution:t,fps:r},!0)}))}))?this.logger.safe.info(`Calculated resolution: ${JSON.stringify(n)}`):this.logger.safe.error(`None of available resolutions are suitable: ${JSON.stringify(i)}. Fallback to: ${JSON.stringify(n)}`),n}getMbps(e,t){return e*t}getFs(e){return Math.ceil(e.width/Gi.MACROBLOCK_SIZE)*Math.ceil(e.height/Gi.MACROBLOCK_SIZE)}},yD=class{constructor(e,t){this.logger=e,this.maxCapabilities=t}ensureValidity(e){this.throwIfMissing(e);const t=this.calculateMissing(e);return this.maxCapabilities&&this.applyMaxCapabilities(t),this.logger.safe.info(`Validating capabilities ${JSON.stringify(t)}`),t}throwIfMissing(e){if(!e.maxFs&&!e.maxMbps&&!e.maxFps||e.maxFs&&!e.maxMbps&&!e.maxFps||!e.maxFs&&e.maxMbps&&!e.maxFps||!e.maxFs&&!e.maxMbps&&e.maxFps)throw new Error(`Missing video capabilities ${JSON.stringify(e)}`)}calculateMissing(e){const t=tn(e);return!e.maxFs&&e.maxMbps&&e.maxFps&&(t.maxFs=e.maxMbps/e.maxFps),e.maxFs&&!e.maxMbps&&e.maxFps&&(t.maxMbps=e.maxFs*e.maxFps),e.maxFs&&e.maxMbps&&!e.maxFps&&(t.maxFps=e.maxMbps/e.maxFs),t}applyMaxCapabilities(e){this.maxCapabilities.maxFs&&(e.maxFs=Math.min(e.maxFs,this.maxCapabilities.maxFs)),this.maxCapabilities.maxMbps&&(e.maxMbps=Math.min(e.maxMbps,this.maxCapabilities.maxMbps)),this.maxCapabilities.maxFps&&(e.maxFps=Math.min(e.maxFps,this.maxCapabilities.maxFps))}},CD=class extends fD{constructor(e,t){super(e),this.initialConstraints={maxWidth:1920,minWidth:1920,maxHeight:1080,minHeight:1080,fps:15},this.maxCapabilities={maxFs:8160,maxFps:15},this.validator=new yD(this.logger.createChild("CV"),this.maxCapabilities),this.constraintsCalculator=new SD(this.logger.createChild("CC")),t.config.resizeModeForSharing&&(this.initialConstraints.resizeMode=t.config.resizeModeForSharing)}createConstraintsObject(e){if(!e.sharing)throw new Error(`Sharing constraints are not presented: ${JSON.stringify(e)}`);const t=this.convertConstraints(e.sharing,this.initialConstraints),i=e.audio?e.audio:null;return i?.deviceId===Gi.SYSTEM_AUDIO_SOURCE_ID&&delete i.deviceId,new mD(i,t,!1,!1,e.withOverridenStream)}generatePolicies(e){return[e]}calculateConstraints(e,t){this.logger.safe.info(`Stream resolution is ${JSON.stringify(t)}`);const i=this.validator.ensureValidity(e);return this.constraintsCalculator.calculateConstraints(i,t)}},TD=class extends CD{constructor(e,t,i){super(e,i);const n=t.screen.width/t.screen.height;n<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 r=pD({width:this.initialConstraints.maxWidth,height:this.initialConstraints.maxHeight},n);[this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[r.width,r.height],r=pD({width:this.initialConstraints.minWidth,height:this.initialConstraints.minHeight},n),[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[r.width,r.height]}},ED=class extends fD{constructor(e,t){super(t),this.configProvider=e}get currentMaxFS(){return this.streamConstraintsMaxFS??this.configProvider.config.webrtcCameraOpenFs}createConstraintsObject(e){const t={};void 0!==e.audioProcessingFlags&&(Ot.isEngine("Chromium","ChromiumAVD")?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags),this.configProvider.config.useGoogPrefixAudioConstraints&&(t.googAutoGainControl=!!(1&e.audioProcessingFlags),t.googAutoGainControl2=!!(1&e.audioProcessingFlags),t.googEchoCancellation=!!(2&e.audioProcessingFlags),t.googHighpassFilter=!!(4&e.audioProcessingFlags),t.googNoiseSuppression=!!(4&e.audioProcessingFlags),t.googTypingNoiseDetection=!!(4&e.audioProcessingFlags))):Ot.isEngine("Safari","Firefox")?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags)):this.logger.warn(`Unsupported browser engine for audio processing flags ${Ot.getBrowserInfo().engine}`));const i=this.convertConstraints(e.audio,t);this.streamConstraintsMaxFS=e.videoMaxFS;const n=this.convertConstraints(e.video,this.initialVideoConstraints(this.currentMaxFS));return new mD(i,n,e.withTimeout,e.withEffect,e.withOverridenStream)}calculateConstraints(e){const t=Math.min(e.maxFs,this.currentMaxFS);return{resolution:Hn.Send.getResolutionByFs(t),fps:e.maxFps}}initialVideoConstraints(e){const t=Hn.Send.getResolutionByFs(e);return{maxWidth:t.width,minWidth:t.width,maxHeight:t.height,minHeight:t.height,fps:this.configProvider.config.maxCameraOpenFps}}},bD=class{static getProvider(e,t,i){if("ScreenShare"===e){const e=i.createChild("SharingCP");return Ot.isBrowser("Safari")?new TD(e,Mp.window,t):new CD(e,t)}return new ED(t,i.createChild("VideoCP"))}},_D=class{constructor(e,t,i){this.error=e,this.constraints=t,this.configProvider=i,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 e;switch(this.error.name){case"SourceUnavailableError":case"TrackStartError":case"NotReadableError":case"AbortError":e={type:Gi.MEDIA_ERROR.sourceUnavailableError,detail:`media device is already used by another process: ${tt(this.error)}`};break;case"ConstraintNotSatisfiedError":case"OverconstrainedError":e={type:Gi.MEDIA_ERROR.constraintNotSatisfiedError,detail:`could not obtain constrained media stream: ${tt(this.error)}`};break;case"DevicesNotFoundError":case"NotFoundError":e=this.configProvider.config.permissionDeniedUFDWorkaround?{type:Gi.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${tt(this.error)}`}:{type:Gi.MEDIA_ERROR.devicesNotFoundError,detail:`specified device not found: ${tt(this.error)}`};break;case"NotAllowedError":e=this.permissionDeniedBySystemErrorMsg.some((e=>e===this.error.message))?{type:Gi.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${tt(this.error)}`}:{type:Gi.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${tt(this.error)}`};break;case"PermissionDeniedError":case"PermissionDismissedError":e={type:Gi.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.extensionNotFoundError:e={type:Gi.MEDIA_ERROR.extensionNotFoundError,detail:`extension is not found: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.chromeRuntimeNotDefinedError:e={type:Gi.MEDIA_ERROR.chromeRuntimeNotDefinedError,detail:`chrome runtime is not defined: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.sharingCancelledError:e=this.getSharingCancelledError(this.error);break;case Gi.MEDIA_ERROR.mediaStreamRequestTimedOut:e={type:Gi.MEDIA_ERROR.mediaStreamRequestTimedOut,detail:"Media Stream request timed out."};break;default:e=this.error.message===Gi.MEDIA_ERROR.sharingCancelledError?this.getSharingCancelledError(this.error):{type:Gi.MEDIA_ERROR.mediaStreamRequestError,detail:`media stream request error: ${tt(this.error)}`}}return e.isAudio=!!this.constraints.audio,e.detail+=` constraints: ${tt(hm(this.constraints))}`,e.message=e.detail,e}getSharingCancelledError(e){return{type:Gi.MEDIA_ERROR.sharingCancelledError,detail:`screen sharing cancelled: ${tt(e)}`}}},ID=class{constructor(e,t){this.logger=e,this.configProvider=t}static isSupported(){return!0}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be applied: ${JSON.stringify(hm(t))}`),new Promise(((e,i)=>{Mp.window.navigator.getUserMedia(t,e,i)})).catch((t=>{throw new _D(t,e,this.configProvider).getMediaError()}))}applyConstraints(e,t){if(!e?.getVideoTracks()?.[0])return Promise.reject("No video tracks found");const i=e.getVideoTracks()[0];return this.applyConstraintsForTrack(i,t)}applyConstraintsForTrack(e,t){const i=this.constraintsAdapter.toTrackConstraints(t);return e.applyConstraints?(this.logger.safe.info(`Apply constraints: ${JSON.stringify(i)} on ${JSON.stringify(e.id)}`),e.applyConstraints(i).catch((e=>{throw new _D(e,t,this.configProvider).getMediaError()}))):Promise.reject("track.applyConstraints() is not supported")}},wD=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};return e.audio&&(t.audio=nn(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Gi.MEDIA_DEVICE.defaultId&&(t.audio.deviceId=e.audio.deviceId)),e.video&&(t.video={mandatory:{}},e.video.deviceId&&(t.video.mandatory.sourceId=e.video.deviceId),e.video.minWidth&&(t.video.mandatory.minWidth=e.video.minWidth),e.video.maxWidth&&(t.video.mandatory.maxWidth=e.video.maxWidth),e.video.minHeight&&(t.video.mandatory.minHeight=e.video.minHeight),e.video.maxHeight&&(t.video.mandatory.maxHeight=e.video.maxHeight),e.video.fps&&(t.video.mandatory.maxFrameRate=e.video.fps,this.configProvider.config.setMinFpsForWebkit&&(t.video.mandatory.minFrameRate=this.configProvider.config.minCameraOpenFps,t.video.mandatory.idealFrameRate=e.video.fps)),Xi(t.video.mandatory)&&delete t.video.mandatory),t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},AD=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};if(e.audio&&(t.audio=nn(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Gi.MEDIA_DEVICE.defaultId&&(t.audio.deviceId={exact:e.audio.deviceId})),e.video){t.video={width:{},height:{},frameRate:{}},e.video.deviceId&&(t.video.deviceId={exact:e.video.deviceId}),e.video.minWidth&&(t.video.width.min=e.video.minWidth),e.video.maxWidth&&(t.video.width.max=e.video.maxWidth),e.video.minHeight&&(t.video.height.min=e.video.minHeight),e.video.maxHeight&&(t.video.height.max=e.video.maxHeight),e.video.fps&&(t.video.frameRate.max=e.video.fps,t.video.frameRate.min=this.configProvider.config.minCameraOpenFps,t.video.frameRate.ideal=e.video.fps);for(const e in t.video)Xi(t.video[e])&&delete t.video[e]}return t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},PD=class{toGumConstraints(e){if(!e?.video)throw new Error(`constraints cannot be applied: ${e}`);const t={video:{}},i=e.video.deviceId&&e.video.deviceId!==Gi.DISPLAY_SOURCE_ID;return e.video.resizeMode&&(t.video.resizeMode=e.video.resizeMode),i&&(t.video.deviceId={exact:e.video.deviceId}),e.video.maxWidth&&(t.video.width={max:e.video.maxWidth},i&&(t.video.width.ideal=e.video.maxWidth)),e.video.maxHeight&&(t.video.height={max:e.video.maxHeight},i&&(t.video.height.ideal=e.video.maxHeight)),e.video.fps&&(t.video.frameRate=e.video.fps),e.audio&&(t.audio=!e.audio.deviceId||{deviceId:{exact:e.audio.deviceId}}),t}toTrackConstraints(e){const t=navigator.mediaDevices.getSupportedConstraints();if(!t)throw new Error("Constraints are not supported by browser");const i={};return t.width&&e.video.minWidth&&(i.width=e.video.minWidth),t.height&&e.video.minHeight&&(i.height=e.video.minHeight),t.frameRate&&e.video.fps&&(i.frameRate=e.video.fps),i.resizeMode=e.video.resizeMode,i}},RD=class extends ID{constructor(e,t){if(super(t.createChild("WebRTCProvider"),e),this.timeoutId=null,void 0!==navigator.webkitGetUserMedia&&void 0!==webkitRTCPeerConnection&&Ap()){if(!this.configProvider.config.overrideGumFromWebkit||!Ip)return void(this.constraintsAdapter=new wD(e));this.logger.safe.info("Overriding getUserMedia from webkit"),Rp()}this.constraintsAdapter=new AD(e)}getStream(e){if(!e.withTimeout||!this.configProvider.config.gumRequestTimeout)return super.getStream(e);const t=this.startGumRequestTimer(e),i=super.getStream(e).then((t=>{if(!this.timeoutId)throw this.stopStreamAfterTimeout(t,e),this.getMediaStreamTimeoutError(e);return this.stopGumRequestTimer(),t}));return Promise.race([t,i]).catch((e=>{throw this.stopGumRequestTimer(),e}))}getMediaStreamTimeoutError(e){const t={name:Gi.MEDIA_ERROR.mediaStreamRequestTimedOut,message:`Media stream request timed out. Constraints: ${tt(hm(e))}`};return new _D(t,e,this.configProvider).getMediaError()}startGumRequestTimer(e){return new Promise(((t,i)=>{this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,i(this.getMediaStreamTimeoutError(e))}),this.configProvider.config.gumRequestTimeout)}))}stopGumRequestTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}stopStreamAfterTimeout(e,t){this.logger.safe.info(`Stopping media stream acquired after timeout: ${JSON.stringify(e.id)} with constraints: ${JSON.stringify(t)}`);try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${tt(e)}`)}}},MD=class extends ID{constructor(e,t){super(e.createChild("WebRTCDispProvider"),t),this.constraintsAdapter=new PD}static isSupported(){return!!window.navigator.mediaDevices.getDisplayMedia}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be used: ${JSON.stringify(t)}`),Promise.resolve().then((()=>e.video?.deviceId&&e.video?.deviceId!==Gi.DISPLAY_SOURCE_ID?Mp.window.navigator.mediaDevices.getUserMedia(t):Mp.window.navigator.mediaDevices.getDisplayMedia(t))).catch((t=>{throw new _D(t,e,this.configProvider).getMediaError()}))}},DD=class{constructor(e){this.detail=e}getStream(e){throw this.getError(e)}applyConstraints(e,t){throw this.getError(t)}applyConstraintsForTrack(e,t){throw this.getError(t)}getError(e){return{type:Gi.MEDIA_ERROR.unsupportedStream,detail:this.detail,message:this.detail,isAudio:!!e.audio}}},kD=class{static getStreamProvider(e,t,i){return"ScreenShare"===e?MD.isSupported()?new MD(i,t):(i.error("GUM stream provider cannot be created for display stream"),new DD("Sharing not supported")):new RD(t,i)}},OD=[30,15,7.5,3.75,1.875];function ND(e){return e?.getVideoTracks?.()[0]?LD(e.getVideoTracks()[0]):null}function LD(e){const t=e?.getSettings?.();return t?{width:t.width,height:t.height}:null}function xD(e){return e?.getVideoTracks?.()[0]?FD(e.getVideoTracks()[0]):0}function FD(e){const t=e?.getSettings?.();return t?cn(OD,t.frameRate,!0):0}var UD=class extends Vi{constructor(e,t,i,n,r,s,a){super(a),this.id=e,this.masterStream=t,this.currentConstraints=i,this.constraintsProvider=n,this.streamProvider=r,this.configProvider=s,this._isDisposed=!1,this.masterStreamSubscriptions=[],this.mixerSubscriptions=[],this.parentId=t.id,this.logger=a.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}getMasterStream(){return this.masterStream}dispose(e){this._isDisposed||(this._isDisposed=!0,this.logger.safe.info(`dispose: ${e}`),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(e){if(!this.mediaTrack)return!1;const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t||!this.configProvider.config.recoverOnStreamUnmute&&this.currentConstraints===t)return!1;const i=async e=>{try{return await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t,!0}catch(t){if(e)throw this.logger.safe.error(`Apply constraints error: ${JSON.stringify(t)}`),t;return this.logger.safe.warn(`Apply constraints failed and will be re-tried, error ${JSON.stringify(t)}`),!1}},n=this.currentConstraints.withEffect&&this.configProvider.config.effectsApplyConstraintsRetryMs;return!await i(!n)&&n&&(await Yt(this.configProvider.config.effectsApplyConstraintsRetryMs),await i(!0)),!0}start(){return this.masterStream.start()}clone(e){return this.masterStream||this.logger.safe.error(`clone: master stream is null, reason: ${e}`),this.masterStream.getClient(`streamclient: ${e}`)}setMuted(e,t){this.isMuted=e,this.applyState(t)}setHold(e,t){this.isHold=e,this.applyState(t)}isSameStream(e){return this.parentId===e.parentId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=LD(this.mediaTrack),i=t?.width?t:e,n=`Track resolution is ${i.width}x${i.height}.`;return t?.width?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=FD(this.mediaTrack);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}update(e){e?this.mediaTrack?this.logger.safe.error(`Media track is already created: ${this.mediaTrack.id}`):(this.mediaTrack=this.getTrackByMediaType(e,this.mediaType),this.updateTrackConstraints(),this.subscribeOnMediaTrackEvents(this.mediaTrack),this.hasMasterAudio=e&&e.getAudioTracks().length>0,this.hasMasterVideo=e&&e.getVideoTracks().length>0,this.hasMasterAudio&&this.hasMasterVideo&&(this.rawMediaStream=e),this.logger.safe.info(`Updated: ${Sm(e)}`)):this.logger.safe.error("No master media stream, skipping update")}resetEffectsOutputConstraints(e){this.masterStream.resetEffectsOutputConstraints(e)}async updateTrackConstraints(){if("ScreenShare"!==this.mediaType)return;const e=this.masterStream.getResolution();if(e){const t=this.currentConstraints.clone();t.video.maxWidth=e.width,t.video.minWidth=e.width,t.video.maxHeight=e.height,t.video.minHeight=e.height;try{await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t}catch(e){this.logger.safe.error(`Apply constraints error: ${JSON.stringify(e)}`)}}}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}applyState(e){void 0!==this.mediaTrack?.enabled&&(this.mediaTrack.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`[${e}] Track ${JSON.stringify(this.mediaTrack.id)} enabled state set to => ${this.mediaTrack.enabled}`))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`),this.event("onStreamClientEnded").raise(this,t)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`),this.event("onStreamClientMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.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((e=>e.dispose())),this.mixerSubscriptions=[]}subscribeOnMasterStreamEvents(){this.masterStreamSubscriptions.push(this.masterStream.on("onStreamStarted",((e,t)=>this.event("onStreamClientStarted").raise(this,t))),this.masterStream.on("onStreamError",((e,t)=>this.event("onStreamClientError").raise(this,t))),this.masterStream.on("onStreamTrackMuted",((e,t)=>this.event("onStreamClientMuted").raise(this,t))),this.masterStream.on("onStreamDisposing",(e=>this.dispose())),this.masterStream.on("onStreamQualityChanged",((e,t,i,n)=>this.event("onStreamQualityChanged").raise(this,t,i,n))),this.masterStream.on("onStreamTrackEnded",((e,t)=>this.event("onStreamClientEnded").raise(this,t))))}unsubscribeFromMasterStreamEvents(){this.masterStreamSubscriptions.forEach((e=>e.dispose())),this.masterStreamSubscriptions=[]}hasAudio(){return this.hasMasterAudio}hasVideo(){return this.hasMasterVideo}isActive(){return this.mediaTrack?.enabled&&!this.mediaTrack?.muted&&"live"===this.mediaTrack?.readyState}onVideoStreamQualityChanged(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.masterStream.onVideoStreamQualityChanged(e,t,i)}isDisposed(){return this._isDisposed}},BD=class extends Vi{constructor(e,t,i,n,r,s){super(s),this.stream=e,this.constraints=t,this.constraintsProvider=i,this.gumStreamProvider=n,this.configProvider=r,this.logger=s,this.clients=[],this.streams=[],this.clientId=0,this.mediaStreamSubscription=this.stream.on("onStreamAcquired",(()=>this.onStreamAcquired()))}getClient(){const e=new UD(this.clientId++,this.stream,this.constraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger);return this.addClient(e),e}disposeClient(e){this.removeClient(e),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((e=>e.id)))}`),this.streams.forEach((e=>this.disposeStream(e))),super.dispose()}getOrCreateStream(){const e=this.streams.length?this.streams[this.streams.length-1]:this.stream.rawStream;if(!e)return null;const t=e.clone();return this.logger.safe.info(`Cloned: ${Sm(e)} -> ${Sm(t)}`),this.resetStream(t),this.streams.push(t),t}addClient(e){this.updateClient(e),this.clients.push(e)}updateClient(e){const t=this.getOrCreateStream();t&&e.update(t)}removeClient(e){const t=this.clients.indexOf(e);this.clients.splice(t,1)}addStream(){this.clients.forEach((e=>this.updateClient(e)))}disposeStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Stopping track: ${JSON.stringify(e.id)}`),e.stop()}))}onStreamAcquired(){this.addStream()}resetStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Resetting state for track: ${e.id}`),e.enabled=!0}))}},VD=class{constructor(){}getPolicies(e){if(e.audio&&!e.video&&this.hasAudioProcessingConstraints(e))return[e,new mD({deviceId:e.audio.deviceId},null)];if(!e.video)return[e];const t=this.getSuitableResolutions(e).map((t=>this.getConstraintsForResolution(e,t))),i=e.audio,n={deviceId:e.video.deviceId},r=new mD(i,n,e.withTimeout);return t.push(r),t}getSuitableResolutions(e){return Hn.Send.getResolutions().filter((t=>t.width<=e.video.maxWidth&&t.height<=e.video.maxHeight)).reverse()}getConstraintsForResolution(e,t){const i=e.clone();return i.video.minWidth=t.width,i.video.minHeight=t.height,i}hasAudioProcessingConstraints(e){const t=e&&e.audio;return t&&(void 0!==t.echoCancellation||void 0!==t.autoGainControl||void 0!==t.noiseSuppression)}},HD=class{static getStrategy(e,t,i,n,r,s){return s?new qD(i,n):"Video"===e?new GD(t,i,n,r):new jD(t,i,n)}},$D=class{constructor(e,t,i){this.gumStreamProvider=e,this.serialQueue=t,this.logger=i}getStream(e){return this.logger.safe.info(`Requesting stream with constraints: ${JSON.stringify(hm(e))}`),this.serialQueue.add((()=>this.request(e)))}},jD=class extends $D{constructor(e,t,i){super(e,t,i.createChild("SimpleStrat"))}request(e){return this.gumStreamProvider.getStream(e)}},GD=class extends $D{constructor(e,t,i,n){super(e,t,i.createChild("MultStrat")),this.policyGenerator=new VD}request(e){const t=this.policyGenerator.getPolicies(e);return this.makeRequests(t)}makeRequests(e){const t=e[0];return this.logger.safe.info(`Requesting media stream with policy: ${JSON.stringify(t)}`),this.makeRequestWithPolicy(t).catch((t=>{const i=e.slice(1);if(i.length&&Gi.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("Could not obtain constrained media stream, will attempt weaker policy"),this.makeRequests(i);throw t}))}makeRequestWithPolicy(e){return this.gumStreamProvider.getStream(e)}},qD=class extends $D{constructor(e,t){super(null,e,t.createChild("WithOveriddenStreamStart"))}request(e){return new Promise(((t,i)=>t(e.withOverridenStream)))}},zD=class e extends Vi{constructor(t,i,n,r,s){super(r),this.serialQueue=i,this.configProvider=n,this.effectManager=s,this.gumRequestTime=0,this.id=e.streamId++,this.logger=r.createChild(`MediaStream:${this.id}`),this.mediaType=this.getMediaType(t),this.initialize(t)}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(e){this.event("onStreamDisposing").raise(this),this.stopMediaStream(e).catch((e=>{this.event("onStreamError").raise(this,e)})).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(e){this.clientGenerationStrategy.disposeClient(e)}getClient(e){return this.logger.safe.debug(`getClient: ${e}`),this.clientGenerationStrategy.getClient()}getOriginalMediaStream(){return this.originalMediaStream}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=ND(this.mediaStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=xD(this.mediaStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}resetEffectsOutputConstraints(e){const t=ND(this.originalMediaStream);this.effectManager.resetOutputConstraints("Video",{width:Math.min(e.width,t.width||Number.MAX_SAFE_INTEGER),height:Math.min(e.height,t.height||Number.MAX_SAFE_INTEGER)})}initialize(e){this.constraintsProvider=bD.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(e),this.gumStreamProvider=kD.getStreamProvider(this.mediaType,this.configProvider,this.logger),this.mediaStreamRequestStrategy=HD.getStrategy(this.mediaType,this.gumStreamProvider,this.serialQueue,this.logger,this.configProvider,!!this.currentConstraints.withOverridenStream),this.clientGenerationStrategy=new BD(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(e){try{await this.getOrCreateMediaStream(e),this.event("onStreamStarted").raise(this,this.currentConstraints)}catch(e){throw this.event("onStreamError").raise(this,e),e}}async getOrCreateMediaStream(e){if(this.mediaStream)return Promise.resolve();const t=this.getRequestStartTimestamp(),i=await this.mediaStreamRequestStrategy.getStream(e);return this.gumRequestTime=this.getRequestDuration(t),this.handleMediaStreamRequestSuccess(i,e)}async handleMediaStreamRequestSuccess(e,t){this.logger.safe.info(`Media stream acquired: ${Sm(e)} with constraints: ${JSON.stringify(hm(t))}`),this.originalMediaStream=e,this.subscribeToTrackEvents(this.originalMediaStream),this.currentConstraints=t,this.mediaStream=await this.applyEffects(e),this.applyState(this.mediaStream),this.event("onStreamAcquired").raise(this,this.gumRequestTime,"Audio"!==this.mediaType&&this.getResolution()||void 0)}async applyEffects(e){switch(this.mediaType){case"Video":return this.getVideoEffectStream(e);case"Audio":return this.startNoiseSuppression(e);case"ScreenShare":return this.delayScreenShare(e)}return e}async delayScreenShare(e){return this.configProvider.config.useDelayedScreenShareStream?this.effectManager.startEffect("ScreenShare",e):e}async startNoiseSuppression(e){return this.configProvider.config.applyAudioEffectOnDemand&&!this.currentConstraints.withEffect?e:(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",e))}async getVideoEffectStream(e){if(!this.currentConstraints.withEffect||this.currentConstraints.withOverridenStream&&this.configProvider.config.useRawMediaApiForVideoEffects)return e;this.sub=this.effectManager.on("onVideoStreamQualityChanged",((e,t,i)=>this.onVideoStreamQualityChanged(e,t,i)));const t=await this.effectManager.startEffect("Video",e);return this.logger.safe.info(`Media stream switched: ${Sm(e)} -> ${Sm(t)}`),t}subscribeToTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=e=>{this.logger.safe.info(`Track ${t.id} ended: ${JSON.stringify(e)}`),this.event("onStreamTrackEnded").raise(this,e)},t.onmute=()=>{this.logger.safe.info(`Track ${t.id} muted`),this.event("onStreamTrackMuted").raise(this,!0)},t.onunmute=()=>{this.logger.safe.info(`Track ${t.id} unmute`),this.event("onStreamTrackMuted").raise(this,!1)})}unsubscribeFromTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=null,t.onmute=null,t.onunmute=null)}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}removeVideoEffectStream(){this.sub?.dispose(),this.effectManager.stopEffect("Video",this.mediaStream)}applyState(e){e.getAudioTracks()?.forEach((e=>this.applyAudioState(e)));const t=e.getVideoTracks()[0];this.applyVideoState(t)}applyAudioState(e){e&&(this.hasNonDefaultAudioProcessingConstraints()||"ScreenShare"===this.mediaType?this.applyContentHint(e,"music"):this.configProvider.config.defaultAudioContentHint&&this.applyContentHint(e,this.configProvider.config.defaultAudioContentHint),e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`))}applyVideoState(e){e&&("ScreenShare"===this.mediaType&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(e,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(e.id)}`))}applyContentHint(e,t){this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t}hasNonDefaultAudioProcessingConstraints(){const e=this.currentConstraints.audio;if(e){const t=this.configProvider.config.defaultAudioProcessingFlags;let i;return void 0===e.echoCancellation&&void 0===e.autoGainControl&&void 0===e.noiseSuppression||(i=0,void 0!==e.echoCancellation&&(i+=e.echoCancellation?2:0),void 0!==e.autoGainControl&&(i+=e.autoGainControl?1:0),void 0!==e.noiseSuppression&&(i+=e.noiseSuppression?4:0)),i!==t}return!1}getRequestStartTimestamp(){return Date.now()}getRequestDuration(e){return 0===e?0:Date.now()-e}stopMediaStream(e){return this.mediaStreamStartPromise?(this.logger.safe.info(`Queueing media stream stop: ${e}`),this.serialQueue.add((()=>this.stopMediaStreamInternal()))):Promise.resolve()}stopOneMediaStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${tt(e)}`)}}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(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.event("onStreamQualityChanged").raise(this,e,t,i)}};zD.streamId=0;var WD=zD,KD=class{static getStrategy(e){switch(e.config.diagnostics.performanceMonitoring.monitoringStrategy){case"decodeTime":default:return new JD(e);case"renderedFps":return new YD(e);case"rendererVolatility":return new QD(e)}}},JD=class{constructor(e){this.configProvider=e,this.decodeThresholds=this.configProvider.config.diagnostics.performanceMonitoring.decodeThresholds,this.defaultThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultThrehold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.decodeThresholds[n]||this.defaultThreshold,s=e.decodeTimeTracker.getReport();return s.median>r.maxDecodeTime&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),s.median<r.maxDecodeTime&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},YD=class{constructor(e){this.configProvider=e,this.fpsDiffThresholds=this.configProvider.config.diagnostics.performanceMonitoring.fpsDiffThresholds,this.defaultFpsDiffThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultFpsDiffThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.fpsDiffThresholds[n]||this.defaultFpsDiffThreshold,s=e.incomingFps.getReport(),a=e.rendererFps.getReport(),o=s.median-a.median;return o>=r.fpsDiff&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),o<r.fpsDiff&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},QD=class{constructor(e){this.configProvider=e,this.volatilityThresholds=this.configProvider.config.diagnostics.performanceMonitoring.volatilityThresholds,this.defaultVolatilityThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultVolatilityThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.volatilityThresholds[n]||this.defaultVolatilityThreshold,s=e.rendererFps.getReport(),a=e.incomingFps.getReport(),o=Math.abs(s.volatilityPercent-a.volatilityPercent);return r&&o>=r&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),o<r&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},ZD=class{constructor(e,t){this.streamClient=e,this.logger=t,this.rawBaseClient=new wg((()=>this.getStream()),(()=>this.activeRawInputMediaStreamClient?.dispose()),t)}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)}},XD=class{constructor(e,t){this.logger=e,this.raiseTelemetryEvent=t,this.handlerMap=new Map([["Audio",new Map],["Video",new Map],["ScreenShare",new Map]])}dispose(e){this.logger.info(`disposing IRawStream ${e}`),this.handlerMap.get(e).forEach((e=>e.client().dispose()))}disposeAll(){this.logger.info("Dispose All clients"),this.handlerMap.forEach((e=>e.forEach((e=>e.client().dispose()))))}notifyChange(e){this.handlerMap.get(e).forEach((e=>{e.disposeActiveMediaStreamClient(),e.client().notifyStreamChange()}))}createIRawStreamClient(e,t){this.logger.info(`Create new IRawStream client for ${t}`);const i=new ZD(e,this.logger);return this.handlerAdded(i,t),i.client()}handlerAdded(e,t){const i=e.client();this.setClientSubscription(i,t),this.handlerMap.get(t).set(i.clientId,e)}deleteRawStreamManagerById(e,t){this.logger.info(`Deleting from map: ${t}`),this.handlerMap.get(t).delete(e)}setClientSubscription(e,t){this.logger.info(`Setting subscription on IRawStream client for ${t}`),e.on("clientDisposed",(i=>{this.deleteRawStreamManagerById(e.clientId,t),this.raiseTelemetryEvent("IRawStream_client_disposed",{mediaType:t,clientId:i})})),e.on("rawStreamRequested",(e=>{this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})})),e.on("notifiedOnStreamChanged",(e=>this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})))}},ek=class extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.audioRendererDiagnostics=i,this.window=Mp.window,this.isMuted=!1,this.isPlayingAllowed=!1,this.hadPlaybackError=!1,this.id=sn(),this.onAudioError=e=>{const t=e&&e.target||this.audio;if(this.hadPlaybackError=!0,t?.error){const e=t.error.code,i=`error with rendering audio code: ${e}, message: ${t.error.message}`;this.event("onAudioPlaybackError").raise(e,Gi.MEDIA_ERROR.audioPlaybackError,i),this.logger.safe.error(i)}else this.logger.safe.error("error with audio rendering")},this.onAudioPaused=async()=>{if(this.configProvider.config.audioRendererRestartOnPause&&this.canPlay&&!this.isMuted){const e=be();this.logger.safe.info(`[${e}] audio playback is paused by OS, resuming it`),await this.startStream(e)}},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(e,t){return this.isMuted=e,e?this.stopStream(t):this.startStream(t)}async getSpeakerVolume(e){const t=this.audio?.volume??0;return this.logger.safe.info(`[${e}] get speaker volume: ${t}`),t}async setSpeakerVolume(e,t){this.assureAudioElement(t),this.audio.volume=e,this.logger.safe.info(`[${t}] set speaker volume: ${e}`)}getStream(){return this.stream}getDeviceId(){return this.deviceId}async play(e){if(this.stream=e,this.isPlayingAllowed=!0,!this.isMuted)return this.startStream()}stop(){this.stopStream(),this.isPlayingAllowed=!1}async setOutputDevice(e,t=be()){if(this.audio)if(this.configProvider.config.disableAudioOutputSelection)this.logger.safe.warn(`[${t}] audio-output selection is disabled, disableAudioOutputSelection: true`);else if(this.audio.setSinkId){if(e&&e!==this.currentSinkId){this.logger.safe.info(`[${t}] setting audio output device ID to ${De(e)}`),this.deviceId=e;try{this.configProvider.config.audioSetSinkIdWorkaround&&this.stream&&!this.stream.active?(this.audio.srcObject=null,await this.audio.setSinkId(e),this.audio.srcObject=this.stream):await this.audio.setSinkId(e),this.currentSinkId=e}catch(e){this.logger.safe.warn(`[${t}] setSinkId operation was aborted with error ${tt(e)}`)}this.configProvider.config.audioRendererRestartOnDeviceError&&this.hadPlaybackError&&!this.isMuted&&(this.audioRendererDiagnostics?.registerReopenRequest(e),this.logger.safe.info(`[${t}] audio playback error happened, restarting audio stream on new device`),await this.startStream(t),this.hadPlaybackError=!1)}}else this.logger.safe.warn(`[${t}] setting output device is not supported`);else this.deviceId=e}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(e=be()){if(this.canPlay)try{await this.assureAudioElement(e),this.logger.safe.info(`[${e}] 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(t){this.logger.safe.warn(`[${e}] play operation was aborted with error ${tt(t)}`)}}async assureAudioElement(e=be()){if(!this.audio)return this.logger.safe.info(`[${e}] 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,e)}stopStream(e=be()){this.audio&&this.canPlay&&(this.detachGainNode(),this.configProvider.config.audioRendererUsePauseOnDetach?(this.logger.safe.info(`[${e}] Pausing with stream: ${this.stream?.id}`),this.audio.pause()):(this.logger.safe.info(`[${e}] Detaching from stream: ${this.stream?.id}`),this.audio.srcObject=null),this.event("onAudioStateChanged").raise(null,this.id))}attachToGainNode(e,t){this.audioContext=new Mp.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(e),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t,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(e,t){this.detachGainNode(),this.attachToGainNode(e,t)}},tk=class{constructor(e){this.logger=e,this.queue=Promise.resolve()}add(e,t=be()){let i;i=e instanceof Kt?()=>e.promise:e;const n=this.queue.then(i);return this.queue=n.catch((e=>{if(this.queue){let i="";e instanceof TypeError&&(i=e.stack),this.logger.safe.error(`[${t}] Error from promiseQueue! ${tt(e)} ${i}`)}})),n}dispose(){this.queue=null}},ik=Z,nk=(e=>(e[e.NONE=0]="NONE",e[e.VIDEO=1]="VIDEO",e[e.AUDIO=2]="AUDIO",e))(nk||{});function rk(e,t){const{rid:i,ssrc:n,frameWidth:r,frameHeight:s,framesPerSecond:a,keyFramesEncoded:o,nackCount:l,firCount:c,pliCount:d,encoderImplementation:u,qualityLimitationReason:h}=e.outboundRTP,{cameraOpenResolution:g,bitrate:p,encodeTime:m,frameRateEncoded:f,frameRateSent:v,qp:S}=e.extensions??{},{mimeType:y}=t.codec??{},{lossRate:C}=t.extensions??{},{audioLevel:T}=t.mediaSource??{};return{rid:{overlayTab:1,values:[i],hideUndefined:!0},cameraSize:{overlayTab:1,format:"{0}x{1}",values:[g?.width,g?.height]},inputSize:{overlayTab:1,format:"{0}x{1}",values:[e.mediaSource?.width,e.mediaSource?.height]},sentSize:{overlayTab:1,format:"{0}x{1}",values:[r,s]},ssrc:{overlayTab:1,values:[n]},fps:{overlayTab:1,text:"FPS(i/e/s)",format:"{0}/{1}/{2}",values:[a,f,v],lowerThreshold:7,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{overlayTab:1,format:"{0} kbps",values:[sk(p)],lowerThreshold:24},encodeTime:{overlayTab:1,format:"{0} ms",values:[m],upperThreshold:15},keyFramesEncoded:{overlayTab:1,text:"KFs",values:[o]},qp:{overlayTab:1,values:[S]},nacksFirsPlisRecv:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[l,c,d],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"encoder",values:[u],highlightUndefined:!0},qualityLimitationReason:{overlayTab:1,text:"limited",values:[h],fixedValueThreshold:"none"},bwe:{overlayTab:1,format:"{0} kbps",values:[sk(e.transport?.selectedCandidatePair?.availableOutgoingBitrate)],lowerThreshold:100},audioCodec:{overlayTab:2,values:[y?.split("/").pop()]},audioLevel:{overlayTab:2,values:[mn(T,4)]},lossRate:{overlayTab:2,values:[mn(C,4)]}}}function sk(e){return e&&Math.floor((e||0)/1e3)}var ak=class{constructor(e){this.container=e,this.formatRegexPattern=new RegExp(/{(\d+)}/g),this.elements={},this.previousSamples={},this.overlayTab=1,this.createTableCell=(e,t,i)=>{this.elements[e]=document.createElement("td"),this.elements[e].title=e,this.addElementStyle(e,i),this.elements[t].appendChild(this.elements[e])},this.topElement=e.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=function(e){const t=Object.keys(nk).filter((e=>isNaN(Number(e)))),i=(e+1)%t.length;return nk[t[i]]}(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(e,t){for(const i of Object.keys(e)){const n=e[i];n.overlayTab===this.overlayTab&&(n.hideUndefined&&n.values.every((e=>!e))||this.createTableRow(i,n,t))}}createTableRow(e,t,i){this.elements[e]||(this.elements[e]=document.createElement("tr"),this.table.appendChild(this.elements[e]));const n=`${e}-title`,r=`${e}-${i}`,s=this.formatValue(t),a=this.previousSamples[r]!==s;this.previousSamples[r]=s;const o=function(e){const{values:t,lowerThreshold:i,upperThreshold:n,highlightUndefined:r,fixedValueThreshold:s,allowedDeviationThreshold:a}=e;for(const e of t){if(void 0===e&&null===e&&r)return!0;if(s&&s!==e)return!0;if(null==e||!(0,ik.isNumber)(e))return!1;if(i&&Number(e)<=i)return!0;if(n&&Number(e)>=n)return!0;if(a){const i=(0,ik.mean)(t),n=i*a;if(Math.abs(Number(e)-i)>n)return!0}}return!1}(t)||!(!t.highlightChange||!a);this.elements[n]||(this.createTableCell(n,e,!1),this.elements[n].innerText=t.text?t.text:e),this.createTableCell(r,e,!t.suppressHighlighting&&o),this.elements[r].innerText=s}clearTable(){for(;this.table.hasChildNodes();)this.table.removeChild(this.table.lastChild);this.elements={}}getOverlayTab(){return this.overlayTab}addElementStyle(e,t){this.elements[e].style.color=t?"#F72F35":"#FBF719",this.elements[e].style.fontSize="smaller",this.elements[e].style.lineHeight="1",this.elements[e].style.padding="0px 1px 0px 1px",this.elements[e].style.maxWidth="60px",this.elements[e].style.overflow="hidden",this.elements[e].style.whiteSpace="nowrap",this.elements[e].style.textOverflow="ellipsis"}formatValue(e){const{values:t,format:i,undefinedFallback:n="N/A"}=e;return i?i.replace(this.formatRegexPattern,((e,i)=>t?.[i]?.toString()??n.toString())):t?.[0]?.toString()??n.toString()}},ok=class{constructor(e,t,i){this.container=t,this.renderer=i,this.subs=[],e&&!this.overlay&&(this.overlay=new ak(this.container),this.rendererStats={msid:()=>this.renderer.getLocalMsi(),sourceId:()=>this.renderer.getMsi()},this.subs.push(this.renderer.on("onVideoSizeChanged",((e,t)=>this.rendererStats.streamSize={width:e,height:t}))),this.subs.push(this.renderer.on("onRendererSizeChanged",((e,t)=>this.rendererStats.rendererSize={width:Math.ceil(t.width),height:Math.ceil(t.height)}))))}setStats(e,t){this.overlay&&(this.overlay.clearTable(),this.overlay.createTableColumn(function(e,t,i){const{ssrc:n,keyFramesDecoded:r,nackCount:s,firCount:a,pliCount:o,decoderImplementation:l,packetsLost:c}=e.inboundRTP,{frameRateReceived:d,frameRateDecoded:u,bitrate:h,decodeTime:g,isFrozen:p}=e.extensions??{},{sourceId:m,msid:f,streamSize:v,rendererSize:S}=i,y=e.renderer?.modality===Gi.MODALITY.sharing,{audioLevel:C}=t.inboundRTP,{mimeType:T}=t.codec??{},{healedRatio:E,lossRate:b}=t.extensions??{};return{streamSize:{overlayTab:1,format:"{0}x{1}",values:[v?.width,v?.height],undefinedFallback:0},rendererSize:{overlayTab:1,format:"{0}x{1}",values:[S?.width,S?.height],undefinedFallback:0},ssrc:{overlayTab:1,values:[n]},msid:{overlayTab:1,text:"sourceId/msid",format:"{0}/{1}",values:[m(),f()]},fps:{overlayTab:1,text:"FPS(r/d)",format:"{0}/{1}",values:[d,u],highlightUndefined:!0,lowerThreshold:1,upperThreshold:45,allowedDeviationThreshold:.2,suppressHighlighting:y},bitrate:{overlayTab:1,format:"{0} kbps",values:[sk(h)],lowerThreshold:24,suppressHighlighting:y},decodeTime:{overlayTab:1,format:"{0} ms",values:[g],upperThreshold:15,highlightUndefined:!0,suppressHighlighting:y},keyFramesDecoded:{overlayTab:1,text:"KFs",values:[r]},nacksFirsPlisSent:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[s,a,o],undefinedFallback:0,highlightChange:!0},packetsLost:{overlayTab:1,text:"lost",values:[c],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"decoder",values:[l],highlightUndefined:!0},isFrozen:{overlayTab:1,values:[p?"YES":"NO"],fixedValueThreshold:"NO"},audioCodec:{overlayTab:2,values:[T?.split("/").pop()]},audioLevel:{overlayTab:2,values:[mn(C,4)]},healedRatio:{overlayTab:2,values:[mn(E,4)],upperThreshold:.2},lossRate:{overlayTab:2,values:[mn(b,4)],upperThreshold:.1}}}(e,t,this.rendererStats),e.inboundRTP.id))}dispose(){this.subs.forEach((e=>e.dispose())),this.subs=[],this.overlay?.dispose(),this.overlay=null,this.container=null,this.renderer=null}},lk=class{constructor(e,t){this.container=t,e&&!this.overlay&&(this.overlay=new ak(this.container))}setStats(e,t){if(!this.overlay)return;if(this.overlay.clearTable(),2===this.overlay.getOverlayTab())return void this.overlay.createTableColumn(rk(e,t),e.outboundRTP.id);const i=[e,...e.altLayouts??[]];for(const e of i)this.overlay.createTableColumn(rk(e,t),e.outboundRTP.id)}dispose(){this.overlay?.dispose(),this.overlay=null,this.container=null}},ck=class e extends Vi{constructor(t,i,n){const r=i.createChild(""+e.rendererId++);super(r),this.container=t,this.configProvider=n,this.video=this.container.ownerDocument.createElement("video"),this.lastNotifiedVideoWidth=0,this.lastNotifiedVideoHeight=0,this.isVideoAttached=!1,this.onVideoDataUpdated=()=>{let e=this.video.videoWidth,t=this.video.videoHeight;(e<32||t<32)&&(e=t=0),this.lastNotifiedVideoWidth===e&&this.lastNotifiedVideoHeight===t||(this.lastNotifiedVideoWidth=e,this.lastNotifiedVideoHeight=t,this.event("onVideoSizeChanged").raise(e,t)),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=e=>{e.preventDefault()},this.logger=r,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(e){this.stream!==e&&(this.stream&&(this.video.srcObject=null),e&&(this.video.hidden=0===e.getVideoTracks().length,this.video.srcObject=e,this.isVideoAttached||(this.container.appendChild(this.video),this.isVideoAttached=!0)),this.stream=e)}setScalingMode(e){this.video.style.objectFit=function(e){switch(e){case"crop":return"cover";case"stretch":return"fill";default:return"contain"}}(e)}getMediaStream(){return this.stream}getTrackId(){return this.stream?.getTracks()[0]?.id??void 0}async captureFrame(){const e=this.stream;if(!e)throw this.logger.safe.error("Mediastream not found"),new Error("Mediastream not found");const t=e.getVideoTracks?.()?.[0]?.getSettings(),i=t?.width,n=t?.height;if(!i||!n)throw this.logger.safe.error("Failed to get video track width/height"),new Error("Failed to get video track width/height");const r=this.getImageData(i,n);return{getSize:()=>({width:i,height:n}),isMirrored:()=>!1,getImageData:()=>r}}playVideo(){this.video?.paused&&this.video.play().catch((e=>{this.logger.safe.error(`Play video error: ${e}`)}))}getImageData(e,t){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=e,this.canvas.height=t,this.context.drawImage(this.video,0,0,e,t),this.context.getImageData(0,0,e,t)}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)}};ck.rendererId=0;var dk=ck,uk=class extends dk{constructor(e,t,i,n,r){super(e,i.createChild("local"),n),this.mediaStreamProvider=t,this.mediaType=r,this.isDisposed=!1,this.serialQueue=new tk(this.logger.createChild("rendererQueue")),this.logger.safe.info("ctor"),this.overlayStats=new lk(this.configProvider.config.showStatsInCall,e)}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(e){this.configProvider.config.localPreviewMirroringSupported&&(this.getVideoElement().style.transform=e?"scaleX(-1)":void 0)}startVideoAsync(e=be()){return this.logger.safe.info(`[${e}] starting local video`),this.event("onRendererStarted").raise(this),this.serialQueue.add((()=>this.restartVideo()),e)}updateStreamAsync(e=be()){return this.logger.safe.info(`[${e}] updating local video`),this.serialQueue.add((()=>this.restartVideo()),e)}onDiagnosticUpdated(e){e.video?.send?.length&&e.audio?.send?.length&&this.overlayStats.setStats(e.video.send[0],e.audio.send[0])}async restartVideo(){try{let e;if("Video"===this.mediaType)e=await this.mediaStreamProvider.getVideoStream(!1,"localVideoRenderer");else{if("ScreenShare"!==this.mediaType)throw new Error("Not yet supported");e=await this.mediaStreamProvider.getDisplayStream("localSSRenderer")}if(await e.start(),this.isDisposed)throw e.dispose(),new Error("local video renderer is disposed");this.attachStream(e)}catch(e){throw this.mediaStreamProvider.raiseTelemetryEvent("video_preview_error",{mediaType:this.mediaType,error:tt(e)}),e}}attachStream(e){if(this.mediaStream!==e)if(this.mediaStream?.parentId!==e?.parentId){this.logger.safe.info(`attach media stream ${e?.id}`);try{this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),e&&super.attachMediaStream(e.rawStream),this.mediaStream=e}catch(t){throw e&&e.dispose(),t}}else e.dispose()}},hk=class extends Vi{constructor(e,t,i){super(i),this.mediaStream=e,this.logger=i,this.mediaStreamSubscriptions=[],this.isHold=!1,this.isMuted=this.mediaStream.getMuted(),this._isDisposed=!1,this.originalId=e.id,this.subscribeOnMediaStreamEvents(),this.update(t),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(e){e&&(this.gumStream=e,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 e=this.mediaStream.getClient();return this.isMuted&&e.setMuted(!0),this.isHold&&e.setHold(!0),e}applyCapabilities(e){return this.mediaStream.applyCapabilities(e)}setMuted(e,t=be()){this.isMuted=e||this.mediaStream.getMuted(),this.logger.safe.info(`[${t}] setMuted => ${this.isMuted}`),this.enableDisableTracks()}setHold(e){this.isHold=e,this.enableDisableTracks()}start(){return this.mediaStream.start()}hasAudio(){return this.mediaStream.hasAudio()}hasVideo(){return this.mediaStream.hasVideo()}hasDisplay(){return this.mediaStream.hasDisplay()}isSameStream(e){return this.parentId===e.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",((e,t)=>{this.event("onStreamClientStarted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamError",((e,t)=>{this.event("onStreamClientError").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackMuted",((e,t)=>{this.event("onStreamClientMuted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackEnded",((e,t)=>{this.event("onStreamClientEnded").raise(this,t)})))}unsubscribeFromMediaStreamEvents(){this.mediaStreamSubscriptions.forEach((e=>e.dispose())),this.mediaStreamSubscriptions=[]}enableDisableTracks(){this.gumStream?this.gumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`Track ${JSON.stringify(e.id)} enabled state set to => ${e.enabled}`))})):this.logger.safe.warn("gumStream stream doesn't exist")}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}},gk=class e extends Vi{constructor(t,i,n,r){super(n),this.streamConstraints=t,this.serialQueue=i,this.configProvider=r,this.clientId=0,this.clients=[],this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.isMuted=!1,this.isHold=!1,this.gumStartTime=0,this.streamId=e.streamGeneration++,this.logger=n.createChild(`MediaStream:${this.streamId}`),this.mediaType=this.getMediaType(this.streamConstraints),this.constraintsProvider=bD.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(t)}get id(){return this.streamId}get rawStream(){return this.currentGumStream}get deviceId(){return this.rawStream?.getTracks()?.[0]?.getSettings?.()?.deviceId??null}applyCapabilities(e){if(this.currentGumStream){const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t)return Promise.resolve(!1);if(this.currentConstraints!==t){this.currentConstraints=t;const e=this.currentConstraints;return this.hasDisplay()?this.applyConstraints(this.currentConstraints).then((()=>an(this.currentConstraints,e))).catch((e=>(this.logger.safe.error(`Apply constraints error: ${tt(e)}`),!1))):this.applyConstraintsInternal().then((()=>an(this.currentConstraints,e)))}}return Promise.resolve(!1)}getClient(){let e;this.currentGumStream?(e=this.getClone(),this.clientGumStreams.push({[this.constraintsProvider.getKey(this.currentConstraints)]:e})):this.clientGumStreams.push({});const t=new hk(this,e,this.logger.createChild("Client:"+this.clientId++));return this.clients.push(t),t}getClone(){return this.hasDisplay()?this.currentGumStream:this.currentGumStream.clone()}setMuted(e){this.isMuted=e,this.clients.forEach((t=>{t.setMuted(e)})),this.enableDisableTracks()}getMuted(){return this.isMuted}setHold(e){this.isHold=e,this.clients.forEach((t=>{t.setHold(e)})),this.enableDisableTracks()}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(){for(let e=this.clients.length-1;e>=0;e--)this.clients[e].dispose()}disposeClient(e){const t=this.clients.indexOf(e);t>=0&&(this.clients.splice(t,1),this.streamsDump.push(this.clientGumStreams[t]),this.clientGumStreams.splice(t,1),0===this.clients.length)&&this.disposeStream()}async disposeStream(){this.event("onStreamDisposing").raise(this);try{await this.stopGumStream(),this.event("onStreamDisposed").raise(this)}catch(e){this.event("onStreamError").raise(this,e)}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!==Gi.DISPLAY_SOURCE_ID}hasDisplay(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId===Gi.DISPLAY_SOURCE_ID}getVideoDeviceId(){return this.currentConstraints.video.deviceId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=ND(this.currentGumStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=xD(this.currentGumStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}async startStream(e){let t;t=e.video?this.applyConstraintsInternal():this.updateGumStreamInternal(e);try{await t,this.event("onStreamStarted").raise(this,e)}catch(e){throw this.event("onStreamError").raise(this,e),e}}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}updateClients(e){const t=this.constraintsProvider.getKey(e);this.clients.forEach(((e,i)=>{this.clientGumStreams[i][t]||(this.clientGumStreams[i][t]=this.getClone()),e.update(this.clientGumStreams[i][t])}))}applyConstraints(e){const t=this.getGumStreamProvider();return Promise.all(this.clients.map((i=>t.applyConstraints(i.rawStream,e)))).then((()=>{}))}applyConstraintsInternal(){return new Promise(((e,t)=>{this.logger.safe.info(`applying stream constraints: ${JSON.stringify(hm(this.currentConstraints))}`);const i=new Kt;this.clients.forEach((e=>{e.onApplyConstraints&&e.onApplyConstraints(i.promise)}));const n=this.serialQueue.add((()=>{const e=(new VD).getPolicies(this.currentConstraints);return this.mediaStreamStartPromise=this.updateGumStreamInternal(e[0]),e.slice(1).forEach((e=>{this.mediaStreamStartPromise=this.mediaStreamStartPromise.catch((t=>{if(Gi.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("could not obtain constrained media stream, will attempt weaker policy"),this.updateGumStreamInternal(e);throw t.constraints=e,t}))})),this.mediaStreamStartPromise})).then((()=>{i.resolve()})).catch((e=>{throw this.logger.safe.error(`failed to apply constraints: ${JSON.stringify(hm(e.constraints))} error: ${tt(e)}`),i.reject(e),e}));e(n)}))}enableDisableTracks(){this.currentGumStream&&this.currentGumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!("audio"===e.kind&&this.isMuted||this.isHold),this.logger.safe.info(`control media stream track kind: ${e.kind} enabled: ${e.enabled} muted: ${e.muted}`))}))}getGumStreamProvider(){return kD.getStreamProvider(this.mediaType,this.configProvider,this.logger.createChild("MSProvider"))}async updateGumStreamInternal(e){this.logger.safe.info(`querying user media for stream: ${JSON.stringify(e)}`),this.logger.safe.info("Getting GUM stream");const t=await this.getGumStream(e);this.logger.safe.info("Updating gum stream audio tracks"),this.updateGumStreamAudioTracks(t),this.currentGumStream=t,this.logger.safe.info("Updating stream constraints"),this.updateConstraints(e,t),this.logger.safe.info("Caching GUM stream"),this.cacheGumStream(this.currentConstraints,t),this.updateClients(this.currentConstraints),this.updateGumStreamVideoTracks(t),this.enableDisableTracks(),this.logger.safe.info("media stream updated");const i=this.stopRequestCalculation();this.event("onStreamAcquired").raise(this,i,(this.hasVideo()||this.hasDisplay())&&this.getResolution()||void 0)}async getGumStream(e){const t=this.gumStreams[this.constraintsProvider.getKey(e)];if(t)return t;const i=this.getGumStreamProvider();return this.startRequestCalculation(),i.getStream(e)}updateGumStreamAudioTracks(e){e.getAudioTracks().forEach((e=>{e.onended=e=>{this.logger.safe.info(`Audio stream track ended: ${JSON.stringify(e.error?.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},e.onmute=()=>{this.logger.safe.info("Audio stream track muted"),this.event("onStreamTrackMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info("Audio stream track unmuted"),this.event("onStreamTrackMuted").raise(this,!1)},e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`)}))}updateGumStreamVideoTracks(e){const[t]=e.getVideoTracks();t&&(t.onmute=e=>{this.logger.safe.error(`Video stream track muted: ${JSON.stringify(hm(this.currentConstraints))}; ${JSON.stringify(e)}`)},t.onended=e=>{this.logger.safe.info(`Video stream track ended: ${JSON.stringify(hm(this.currentConstraints))}; ${JSON.stringify(e?.error.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},this.hasDisplay()&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(t,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(t.id)}`))}cacheGumStream(e,t){const i=this.constraintsProvider.getKey(e);this.gumStreams[i]!==t&&(this.gumStreams[i]&&(this.logger.safe.info(`Stream cache hit for ${i}, stopping old stream`),this.stopOneGumStream(this.gumStreams[i])),this.gumStreams[i]=t)}updateConstraints(e,t){this.currentConstraints=e.video?this.constraintsProvider.updateResolution(e,this.getResolution()):e,this.logger.safe.info(`Stream constraints updated: ${JSON.stringify(this.currentConstraints)}`)}applyContentHint(e,t){["","text","detail","motion"].indexOf(t)<0?this.logger.safe.error(`Cannot apply content hint: ${t}`):(this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t)}startRequestCalculation(){this.gumStartTime=Date.now()}stopRequestCalculation(){if(0===this.gumStartTime)return 0;const e=Date.now()-this.gumStartTime;return this.gumStartTime=0,e}stopGumStream(){return this.mediaStreamStartPromise?(this.logger.safe.info("queueing media stream stop"),this.serialQueue.add((()=>{this.stopGumStreamInternal()}))):Promise.resolve()}stopOneGumStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.onended=null,e.onmute=null,e.stop()})),this.logger.safe.info("media stream stopped")}catch(e){this.logger.safe.warn(`failed to stop media stream: ${tt(e)}`)}}stopGumStreamInternal(){this.currentGumStream&&([...this.clientGumStreams,...this.streamsDump,this.gumStreams].forEach((e=>{qi(e,(e=>{this.stopOneGumStream(e)}))})),this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.currentGumStream=null)}};gk.streamGeneration=0;var pk=gk,mk=class e extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.effectsManager=i,this.cachedStreamsSubs=new Map,this.cachedStreamsMap=new Map,this.mediaStreamSerialQueue=new tk(this.logger),this.couldUseWebrtc_1_0=!1}getMediaStream(e,t){this.logger.safe.info(`retrieving media stream: ${JSON.stringify(hm(e))}`),this.cachedStreamsMap.size||(this.couldUseWebrtc_1_0=pm(this.configProvider.config.checkSupportForWebrtc_1_0));let i=this.getSuitableStream(e);i||(this.logger.safe.info(`cached stream is not found. Creating a new one with constraints: ${tt(hm(e))}`),i=this.createCachedStream(e)),this.logger.safe.info(`starting cached stream id=${i.id}`,t);const n=i.getClient(t);return n.start().catch((e=>{this.logger.safe.error(`could not start media stream: ${i.id}, total streams: ${this.cachedStreamsMap.size}, error: ${tt(e)}`),this.removeStream(i)})),n}dispose(){this.cachedStreamsSubs&&(this.cachedStreamsSubs.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.cachedStreamsSubs=null),this.cachedStreamsMap&&(this.cachedStreamsMap.forEach((e=>e.dispose("MSM dispose"))),this.cachedStreamsMap=null),this.mediaStreamSerialQueue&&(this.mediaStreamSerialQueue.dispose(),this.mediaStreamSerialQueue=null),super.dispose()}getCachedStreams(){return this.cachedStreamsMap}getActiveConstraints(){const e={audio:!1,video:!1,sharing:!1};return this.cachedStreamsMap.forEach(((t,i)=>{i.audio&&(e.audio=!0),i.video&&(e.video=!0),i.sharing&&(e.sharing=!0)})),e}onDevicesChanged(t){this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t)?this.logger.safe.info("Device list is empty, permission workaround enabled"):this.cachedStreamsMap.forEach(((e,i)=>{if(!i.sharing){const e=this.isDeviceOutdated(i.audio,t),n=this.isDeviceOutdated(i.video,t);(e||n)&&this.cachedStreamsMap.delete(i)}}))}getSuitableStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{this.isSuitable(this.addDeviceIdIfNecessary(i,n),e)&&(t=n)})),t&&this.cachedStreamsMap.get(t)}addDeviceIdIfNecessary(e,t){if(!e.deviceId)return t;const i=this.cloneStreamConstraints(t);return t.audio&&void 0===t.audio.deviceId&&(i.audio.deviceId=e.deviceId),t.video&&void 0===t.video.deviceId&&(i.video.deviceId=e.deviceId),t.sharing&&(i.sharing.deviceId=Gi.DISPLAY_SOURCE_ID),i}cloneStreamConstraints(e){return{...nn(e),withOverridenStream:e.withOverridenStream}}createCachedStream(e){const t=this.createStream(e);return this.event("onStreamCreated").raise(t.id,t.mediaType),this.subscribeOnStreamEvents(t),this.logger.safe.info(`created media stream, id: ${t.id} total: ${this.cachedStreamsMap.size}`),this.cachedStreamsMap.set(e,t),t}disposeCurrentDeviceStream(t){for(const[i,n]of this.cachedStreamsMap.entries())t.sharing||i.sharing||(e.deviceChanged(t.audio,i.audio)||e.deviceChanged(t.video,i.video))&&n.dispose("MSM dispose oneStreamPerDeviceType")}createStream(e){return this.configProvider.config.oneStreamPerDeviceType&&this.couldUseWebrtc_1_0&&this.disposeCurrentDeviceStream(e),this.configProvider.config.webrtcSimulcastSessionEnabled&&Vp.hasApplyConstraints()&&this.couldUseWebrtc_1_0?new WD(e,this.mediaStreamSerialQueue,this.configProvider,this.logger,this.effectsManager):new pk(e,this.mediaStreamSerialQueue,this.logger,this.configProvider)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamAcquired",((e,t,i)=>this.onStreamAcquired(e,t,i)))),t.push(e.on("onStreamDisposing",(e=>this.onStreamDisposing(e)))),this.cachedStreamsSubs.set(e,t)}unsubscribeFromStreamEvents(e){this.cachedStreamsSubs.get(e).forEach((e=>e.dispose())),this.cachedStreamsSubs.delete(e)}removeStream(e){this.logger.safe.info(`release media stream generation: ${e.id} cached: ${this.cachedStreamsMap.size}`),this.cachedStreamsSubs.has(e)?(this.unsubscribeFromStreamEvents(e),this.cachedStreamsMap.delete(this.getConstraintsForStream(e)),this.getStreamsCountByType("Audio")||this.effectsManager.stopEffect("Audio"),this.cachedStreamsMap.size||this.event("onAllStreamsRemoved").raise()):this.logger.safe.warn(`skipping unknown stream ${e.id}`)}getConstraintsForStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{e===i&&(t=n)})),t}isSuitable(e,t){const i=!(!e.withOverridenStream||!t.withOverridenStream),n=i||t.sharing||this.isAcceptable(e.audio,t.audio)&&e.audioProcessingFlags===t.audioProcessingFlags,r=i||this.isAcceptable(e.video,t.video),s=this.configProvider.config.requireUserActionForAudioSharing&&t.sharing&&!!e.audio!=!!t.audio,a=this.isAcceptable(e.sharing,t.sharing),o=a&&this.isAcceptable(e.audio,t.audio),l=s?o:a,c=e.withEffect===t.withEffect,d=e.withOverridenStream?.id===t.withOverridenStream?.id;return!t.force&&n&&r&&l&&c&&d}isAcceptable(e,t){return!e&&!t||e&&t&&e.deviceId===t.deviceId}isDeviceOutdated(e,t){return e?.deviceId&&!t.some((t=>t.deviceId===e.deviceId))}onStreamDisposing(e){this.logger.safe.info(`onStreamDisposing event ${e.id}`),this.event("onStreamDisposing").raise(e.id,e.mediaType),this.removeStream(e)}onStreamAcquired(e,t,i){const n="Audio"===e.mediaType?void 0:!!e.rawStream.getAudioTracks()[0],r="ScreenShare"===e.mediaType?this.getSharingSource(e):void 0,s="Audio"===e.mediaType||n?e.rawStream?.getAudioTracks?.()[0]?.getSettings?.()?.sampleRate:void 0;this.event("onStreamAcquired").raise({id:e.id,mediaType:e.mediaType,timestamp:t,resolution:i,withAudio:n,source:r,sampleRate:s})}getSharingSource(e){const t=e.rawStream.getVideoTracks()[0],i=t.getConstraints();if(i?.deviceId)return"camera";const n=t.getSettings();return n?.displaySurface??"unknown"}static deviceChanged(e,t){return!(!e||!t)&&e.deviceId!==t.deviceId}static isDeviceListEmpty(e){return e.every((e=>""===e.label))}getStreamsCountByType(e){let t=0;return this.cachedStreamsMap.forEach((i=>{t+=i.mediaType===e?1:0})),t}},fk=class{constructor(e){this.configProvider=e,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(e){this.data.permissionStates=e}setSelectedDevices(e,t){const i={microphone:fn(e.microphone?.label,this.configProvider.config.devices.piiSafeWords),camera:fn(e.camera?.label,this.configProvider.config.devices.piiSafeWords),speaker:fn(e.speaker?.label,this.configProvider.config.devices.piiSafeWords)};this.rawUsedDevices={microphone:e.microphone?.label,camera:e.camera?.label,speaker:e.speaker?.label},this.data.usedDevices&&(this.data.deviceSelectionChangeCount++,t&&this.data.deviceSelectionChangeCountFromInterface++),this.data.usedDevices=i}setDeviceList(e,t,i){this.data.deviceList=e.map((e=>({label:fn(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.type}))),i&&(this.data.deviceDebugStrings=nn(i)),this.data.devicesCount.microphone=e.filter((e=>"microphone"===e.type)).length,this.data.devicesCount.camera=e.filter((e=>"camera"===e.type)).length,this.data.devicesCount.speaker=e.filter((e=>"speaker"===e.type)).length,this.data.devicesCount.compositeAudio=e.filter((e=>"compositeAudio"===e.type)).length,this.data.devicesChangeCount++,t&&this.data.devicesPollChangeCount++}registerDeviceTelemetryEvent(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.data.latestCameraOpenResolution=t.resolution)}"Audio"===e.payload.mediaType&&("stream_acquired"===e.eventType&&(this.data.audioSourceNumOfReopenRequests++,this.data.audioSourceNumOfSuccessfulReopens++),"stream_error"===e.eventType&&this.data.audioSourceNumOfReopenRequests++),rt(this.data.deviceTelemetryEvents,e,this.configProvider.config.diagnostics.collectionLimits.numDeviceEvents)}logAudioDeviceError(e,t){switch(e){case"reconnect_on_audio_playback_error":{const e=this.getAudioPlaybackErrorCode(t.error);this.registerAudioRenderError(e);break}case"enumeration_failed":this.registerAudioRenderError(1),this.registerAudioCaptureError(1);break;case"permissions_state_changed":"denied"===t.microphone&&this.registerAudioCaptureError(0x800000000000);break;case"stream_ended_error":this.registerAudioCaptureError(4194304)}}getAudioPlaybackErrorCode(e){switch(e){case 3:return 4194304;case 4:return 128;default:return 0x8000000000000000}}registerVideoEffectsEvent(e){rt(this.data.videoEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numVideoEffectsEvents)}registerAudioEffectsEvent(e){rt(this.data.audioEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numAudioEffectsEvents)}registerWorkerEvent(e){rt(this.data.workerEvents,e,this.configProvider.config.diagnostics.collectionLimits.numWorkerEvents)}registerAudioCaptureError(e){const t={timestamp:Date.now(),audioDeviceErrorFlag:e};rt(this.data.audioCaptureDeviceErrorFlags,t,this.configProvider.config.diagnostics.collectionLimits.numAudioCaptureErrors)}registerAudioRenderError(e){const t={timestamp:Date.now(),audioDeviceErrorFlag:e};rt(this.data.audioRenderDeviceErrorFlags,t,this.configProvider.config.diagnostics.collectionLimits.numAudioRenderErrors)}getObjectRef(){return this.data}},vk=class{constructor(e,t,i,n,r){this.deviceId=e,this.label=t,this.kind=i,this.groupId=n,this.capabilities=r,this.type=this.getType(this.kind),this.guid=`${this.type}:${this.deviceId}`,this.isSystemDefault=this.deviceId===Gi.MEDIA_DEVICE.defaultId}toDeviceDesc(){return{id:this.guid,browserId:this.deviceId,label:this.label,kind:this.type}}getType(e){switch(e){case Gi.MEDIA_DEVICE_KIND.audioInput:return Gi.MEDIA_DEVICE.microphone;case Gi.MEDIA_DEVICE_KIND.audioOutput:return Gi.MEDIA_DEVICE.speaker;case Gi.MEDIA_DEVICE_KIND.videoInput:return Gi.MEDIA_DEVICE.camera;case Gi.MEDIA_DEVICE_KIND.compositeAudio:return Gi.MEDIA_DEVICE.compositeAudio;case Gi.MEDIA_DEVICE_KIND.virtualDevice:return Gi.MEDIA_DEVICE.virtualDevice;default:throw new Error(`Device kind to recognized: ${e}`)}}},Sk=class extends vk{constructor(e,t,i,n){super(e,t,i,n)}},yk=class extends vk{constructor(e,t,i,n,r){super(e,t,i,n,r)}toDeviceDesc(){const e=super.toDeviceDesc();return e.isSystemDefault=this.isSystemDefault,e}},Ck=class extends vk{constructor(e,t,i,n,r){if(super(e,t,i,n,r),this.position="unknown",r&&r.facingMode&&1===r.facingMode.length)switch(r.facingMode[0]){case"user":this.position="front";break;case"environment":this.position="back"}}toDeviceDesc(){const e=super.toDeviceDesc();return e.position=this.position,e}},Tk=class extends vk{constructor(e,t,i,n,r,s){super(null,i,n,""),this.micDevice=e,this.speakerDevice=t,this.formFactor=r,this.isPcInternalDevice=s,this.guid=null,this.isSystemDefault=!1}get micDeviceId(){return this.micDevice.guid}get speakerDeviceId(){return this.speakerDevice.guid}toDeviceDesc(){const e=super.toDeviceDesc();return e.microphoneId=this.micDeviceId,e.speakerId=this.speakerDeviceId,e.formFactor=this.formFactor,e.isPcInternalDevice=this.isPcInternalDevice,e}};function Ek(e){const t=e.getCapabilities&&e.getCapabilities();switch(t&&(delete t.groupId,delete t.deviceId),e.kind){case Gi.MEDIA_DEVICE_KIND.audioInput:case Gi.MEDIA_DEVICE_KIND.audioOutput:return new yk(e.deviceId,e.label,e.kind,e.groupId,t);case Gi.MEDIA_DEVICE_KIND.videoInput:return new Ck(e.deviceId,e.label,e.kind,e.groupId,t);default:throw new Error(`Device kind is not recognized: ${e.kind}`)}}function bk(e,t,i){return new Tk(e,t,i,"compositeAudio",0,!1)}function _k(e){switch(e){case Gi.MEDIA_DEVICE.microphone:return Gi.MEDIA_DEVICE_KIND.audioInput;case Gi.MEDIA_DEVICE.speaker:return Gi.MEDIA_DEVICE_KIND.audioOutput;case Gi.MEDIA_DEVICE.camera:return Gi.MEDIA_DEVICE_KIND.videoInput;default:throw new Error(`Device type to recognized: ${e}`)}}function Ik(e,t){let i=999,n=null;if(e.length>0&&t.length>0)for(const r of e)for(const e of t){const t=pn(r.label,e.label);t<i&&(i=t,n={microphone:r,speaker:e})}return n}function wk(e,t){if(e===t)return e;let i=gn(e,t);i=i.trim().replace(/^\((.+)\)$/,"$1");let n="",r="",s=0;const a=[Ak(e),Ak(t)];if(0===a[0]||0===a[1])return i;for(let e=0;e<i.length;e++)if("("===i[e])s++,r+=i[e];else if(")"===i[e]){if(!(s>0))break;s--,r+=i[e],n+=r,r=""}else s>0?r+=i[e]:n+=i[e];const o=Ak(n);return o!==a[0]&&o!==a[1]||(n=n.replace(/\w+\s?\((.+)\)/,"$1"),n=wk(i,n)),n.trim()}function Ak(e){const t=["(",")"];let i=0;for(let n=0;n<e.length;n++)t.some((t=>e[n]===t))&&i++;return i}var Pk={microphone:"",camera:"",speaker:"",compositeAudio:"",audioIngestDevice:"",virtualDevice:""},Rk=class extends Vi{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.debugInfo=Pk,this.lists=new Map,this.lists.set(Gi.MEDIA_DEVICE.microphone,[]),this.lists.set(Gi.MEDIA_DEVICE.camera,[]),this.configProvider.userAgentConfig.isAudioOutputSelectionSupported&&(this.lists.set(Gi.MEDIA_DEVICE.speaker,[]),this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,[])),e.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>this.onConfigUpdated())),this.logger.safe.info("Initialized")}get devices(){const e=[];return this.lists.forEach((t=>e.push(...t))),e}getDevicesByType(e){return this.lists.get(e)??[]}updateDevices(e,t=!1){if(an(this.latestRawList,e))return;this.latestRawList=e;const i=this.devices;this.debugInfo.microphone="microphone",this.debugInfo.camera="camera",this.debugInfo.speaker="speaker",this.debugInfo.compositeAudio="compositeAudio",this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.microphone,e.filter((e=>e.type===Gi.MEDIA_DEVICE.microphone))),this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.camera,e.filter((e=>e.type===Gi.MEDIA_DEVICE.camera))),this.lists.get(Gi.MEDIA_DEVICE.speaker)&&(this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.speaker,e.filter((e=>e.type===Gi.MEDIA_DEVICE.speaker))),this.lists.get(Gi.MEDIA_DEVICE.compositeAudio)&&this.updateCompositeAudioDeviceList(this.lists.get(Gi.MEDIA_DEVICE.microphone),this.lists.get(Gi.MEDIA_DEVICE.speaker)));const n=this.lists.get(Gi.MEDIA_DEVICE.compositeAudio)||[];this.lists.set(Gi.MEDIA_DEVICE.microphone,this.orderDeviceList(this.lists.get(Gi.MEDIA_DEVICE.microphone),n)),this.lists.get(Gi.MEDIA_DEVICE.speaker)&&this.lists.set(Gi.MEDIA_DEVICE.speaker,this.orderDeviceList(this.lists.get(Gi.MEDIA_DEVICE.speaker),n));const r=this.lists.get(Gi.MEDIA_DEVICE.microphone);this.setTopItemToDefault(r);const s=this.lists.get(Gi.MEDIA_DEVICE.speaker);this.setTopItemToDefault(s),an(i,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,t))}updateVirtualDeviceList(e){const t=this.lists.get(Gi.MEDIA_DEVICE.virtualDevice),i=e.map((e=>new Sk(e.id,e.label,"virtualDevice","")));an(t,i)?this.logger.safe.info("Device lists did not change."):(this.lists.set(Gi.MEDIA_DEVICE.virtualDevice,i),this.event("onDevicesChanged").raise(this.devices,!1))}updateActiveMicrophone(e){if(!e||e.deviceId===Gi.MEDIA_DEVICE.defaultId)return;const t=this.lists.get(Gi.MEDIA_DEVICE.microphone),i=t.findIndex((e=>e.isSystemDefault));-1!==i&&t[i]!==e?(this.logger.safe.info("Removing synthetic default microphone"),e.isSystemDefault=!0,t.splice(i,1),this.lists.set(Gi.MEDIA_DEVICE.microphone,t),this.event("onDevicesChanged").raise(this.devices,!1)):e.isSystemDefault=!0}updatePrimitiveDeviceList(e,t){const i={str:this.debugInfo[e]};this.lists.set(e,function(e,t,i,n,r={str:""}){r.str+=`|input(${t.length})`;let s=[];const a=[n.config.devices.blacklist[e],n.defaultConfig.devices.blacklist[e]];for(const e of a)try{const i=new RegExp(e,"i");s=t.filter((t=>e&&t.label.match(i)?(r.str+=`|-blacklisted(${t.label})`,!1):t.deviceId!==Gi.MEDIA_DEVICE.communicationsId||(r.str+="|-communications",!1)));break}catch(i){r.str+=`|filterError('${e}', ${tt(i)})`,s=t}if(s.length){const t=function(e,t,i){if(1===t.length)return i.str+="|default:only",t[0];const n=t.find((e=>e.isSystemDefault&&e.deviceId===Gi.MEDIA_DEVICE.defaultId));if(!n)return i.str+="|default:noSynthetic",t.find((e=>e.isSystemDefault))||t[0];{const r=t.filter((e=>e!==n));if(1===r.length)return i.str+="|default:firstNonDefault",r[0];if(""!==n.groupId){const e=r.filter((e=>e.groupId===n.groupId));if(1===e.length)return i.str+=`|default:groupId(${De(e[0].guid)})`,e[0]}const s=r.map((e=>e.label)),a=function(e,t){return t.reduce(((t,i)=>{const n=e.includes(i)?i.length:0;return t.length<n?i:t}),"")}(n.label,s),o=r.find((e=>e.label===a));if(o)return i.str+=`|default:label(${De(o.guid)})`,o;const l=e.find((e=>e.isSystemDefault));if(l){const e=r.find((e=>e.deviceId===l.deviceId));if(e)return i.str+=`|default:previousList(${De(e.guid)})`,e}}return i.str+="|default:anyOrNull",t.find((e=>e.isSystemDefault))||null}(i,s,r);if(t&&(t.isSystemDefault=!0,r.str+=`|default(${De(t.guid)})`),t&&t.deviceId!==Gi.MEDIA_DEVICE.defaultId&&s.length>1&&(s=s.filter((e=>e.deviceId!==Gi.MEDIA_DEVICE.defaultId||(r.str+="|-defaultId",!1)))),e===Gi.MEDIA_DEVICE.camera||t||(r.str+="|+syntheticDefault",s.unshift(function(e){const t={deviceId:Gi.MEDIA_DEVICE.defaultId,label:Gi.MEDIA_DEVICE.defaultDeviceLabel,kind:_k(e),groupId:"",toJSON:()=>JSON.stringify(t)};return Ek(t)}(e))),i.forEach((e=>{const t=s.find((t=>t.guid===e.guid));t&&!t.label&&e.label&&(r.str+=`|migrateLabel(${De(t.guid)})`,t.label=e.label)})),e===Gi.MEDIA_DEVICE.speaker){const e=s.filter((e=>""===e.label));e.length>1&&e.length===s.length&&(s=t?[t]:[s[0]],r.str+=`|-filteredEmptyLabels(${e.length})`)}}return s}(e,t,this.lists.get(e)||[],this.configProvider,i)),this.debugInfo[e]=i.str}updateCompositeAudioDeviceList(e,t){const i={str:this.debugInfo.compositeAudio};this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,function(e,t,i=.5,n={str:""}){const r=[];if(e.length&&t.length){const s=function(e,t,i={str:""}){const n=new Set;for(const i of[...e,...t])n.add(i.groupId);const r=[];for(const s of n.values()){let n=e.filter((e=>e.groupId===s)),a=t.filter((e=>e.groupId===s));if(n&&a)if(1===n.length&&1===a.length)r.push({microphone:n[0],speaker:a[0]}),i.str+=`|pairSimple(${De(n[0].guid)}, ${De(a[0].guid)})`;else if(n.length>1||a.length>1){let e=Ik(n,a);for(;e;)i.str+=`|pairComplex(${De(e.microphone.guid)}, ${De(e.speaker.guid)})`,r.push(e),n=n.filter((t=>t!==e.microphone)),a=a.filter((t=>t!==e.speaker)),e=Ik(n,a)}}return r}(e.filter((e=>""!==e.groupId)),t.filter((e=>""!==e.groupId)),n);s.length&&(r.push(...s.map((e=>bk(e.microphone,e.speaker,wk(e.microphone.label,e.speaker.label))))),n.str+=`|directMatched(${r.length})`);const a=r.length;r.push(...function(e,t,i,n){const r=[];return e.length&&t.length?(e.forEach((e=>{const s=t.filter((t=>t.groupId===e.groupId));if(!s.length)return void(n.str+=`|lbl_nocand(${De(e.guid)})`);let a=gn(e.label,s[0].label).length;const o=s.sort(((t,i)=>{const n=gn(e.label,t.label),r=gn(e.label,i.label);return n.length>a&&(a=n.length),r.length>a&&(a=r.length),r.length-n.length}));if(o.length){const t=a/e.label.length;t>i&&(r.push(bk(e,o[0],wk(e.label,o[0].label))),n.str+=`|lbl_matched(${De(e.guid)} & ${De(o[0].guid)}, ${Math.round(1e4*t)/100}%)`)}})),r):r}(e.filter((e=>!r.some((t=>t.micDeviceId===e.guid)))),t.filter((e=>!r.some((t=>t.speakerDeviceId===e.guid)))),i,n)),n.str+=`|otherMatched(${r.length-a})`}return r}(e,t,this.configProvider.config.devices.compositeLabelMatchingThreshold,i)),this.debugInfo.compositeAudio=i.str}orderDeviceList(e,t){return e.sort(((e,i)=>this.getDevicePriority(i,this.getCompositeAudioDeviceCounterpart(i,t))-this.getDevicePriority(e,this.getCompositeAudioDeviceCounterpart(e,t))))}getCompositeAudioDeviceCounterpart(e,t){const i=t.find((t=>t.micDeviceId===e.guid||t.speakerDeviceId===e.guid));return i?i[e.type===Gi.MEDIA_DEVICE.speaker?"micDevice":"speakerDevice"]:null}getDevicePriority(e,t){let i=0;return this.configProvider.config.devices.overrideDefault&&t&&(!e.isSystemDefault&&t.isSystemDefault?(this.debugInfo[e.type]+=`|overrideDefault(${De(e.guid)})`,i+=10):e.isSystemDefault&&!t.isSystemDefault&&"microphone"===e.type&&(i+=15)),e.isSystemDefault&&(i+=5),t&&(i+=1,t.isSystemDefault&&(i+=2)),i}setTopItemToDefault(e){e?.length&&(e.forEach((e=>e.isSystemDefault=!1)),e[0].isSystemDefault=!0)}onConfigUpdated(){let e=!1;this.configProvider.userAgentConfig.isAudioOutputSelectionSupported?this.lists.has(Gi.MEDIA_DEVICE.speaker)||(this.lists.set(Gi.MEDIA_DEVICE.speaker,[]),this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,[]),e=!0):(this.lists.has(Gi.MEDIA_DEVICE.speaker)&&(this.lists.delete(Gi.MEDIA_DEVICE.speaker),e=!0),this.lists.has(Gi.MEDIA_DEVICE.compositeAudio)&&(this.lists.delete(Gi.MEDIA_DEVICE.compositeAudio),e=!0)),e&&(this.logger.safe.info("Updating device list due to config update"),this.updateDevices(this.latestRawList||[]))}},Mk=class e extends Vi{constructor(t,i){super(i),this.pollingInterval=0,e.enumeratorUsers.add(this),e.initialize(this,t,i)}startDevicePolling(t){this.pollingInterval=t?e.configProvider.config.devices.pollingIntervalIdle:e.configProvider.config.devices.pollingIntervalActive,e.updatePollingTask()}stopDevicePolling(t){this.pollingInterval=t?0:e.configProvider.config.devices.pollingIntervalIdle,e.updatePollingTask()}dispose(){super.dispose(),this.stopDevicePolling(!0),e.enumeratorUsers.delete(this),0===e.enumeratorUsers.size&&(e.logger.safe.info("disposing"),e.initializeCalled=!1,e.isDeviceListAvailable=new Kt,e.list=void 0,e.window.navigator.mediaDevices.ondevicechange=void 0)}static get isPolling(){return 0!==e.currentPollingInterval}static initialize(t,i,n){e.initializeCalled||(e.initializeCalled=!0,e.window=Mp.window,e.configProvider=i,e.logger=n,e.list=new Rk(i,n.createChild("DeviceList")),i.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>e.enumerateDevices())),i.on("configUpdated",(()=>{void 0!==i.config.devices.pollingIntervalIdle&&null!==e.pollingTimer&&t.startDevicePolling(!0)})),i.config.devices.pollingIntervalIdle&&i.config.devices.idlePollingOnStart&&t.startDevicePolling(!0),e.window.navigator.mediaDevices&&(e.window.navigator.mediaDevices.ondevicechange=()=>{n.safe.info("enumerating due to ondevicechange callback"),e.enumerateDevices().catch((e=>{n.safe.error(`unable to enumerate ondevicechange: ${tt(e)}`)}))}),e.enumerateDevices())}static async enumerateDevices(t=!1){if(!e.window.navigator?.mediaDevices?.enumerateDevices){const t=new Error("device enumeration unsupported");throw e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.reject(t),t}if(e.enumerateDevicesPromise&&!t)return e.logger.safe.info("enumeration request postponed"),e.hasPendingUpdate=!0,void(e.isDeviceListAvailable.isPending&&Ot.isEngine("Firefox")&&e.isDeviceListAvailable.resolve());try{if(!e.enumerateDevicesPromise)if(e.configProvider.config.devices.enumerateDevicesTimeout){const t=Jt(e.configProvider.config.devices.enumerateDevicesTimeout);e.enumerateDevicesPromise=t.promise,e.window.navigator.mediaDevices.enumerateDevices().then(t.resolve,t.reject)}else e.enumerateDevicesPromise=e.window.navigator.mediaDevices.enumerateDevices();const i=await e.enumerateDevicesPromise;e.list.updateDevices(i.map((e=>Ek(e))),t),e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.resolve()}catch(t){const i=tt(t);throw e.logger.safe.warn(`error with enumerating devices: ${i}`),e.raiseFailedEnumeration(i),e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.reject(t),t}finally{e.enumerateDevicesPromise=void 0,e.hasPendingUpdate&&(e.hasPendingUpdate=!1,e.logger.safe.info("running postponed enumeration"),e.enumerateDevices())}}static updatePollingTask(){let t=Number.MAX_SAFE_INTEGER;for(const i of e.enumeratorUsers.values())i.pollingInterval<t&&(t=i.pollingInterval);if(t===Number.MAX_SAFE_INTEGER&&(t=0),(e.pollingTimer||e.currentPollingInterval!==t)&&e.pollingTimer&&(e.window.clearTimeout(e.pollingTimer),e.pollingTimer=void 0),e.currentPollingInterval=t,0===t)return;const i=async()=>{if(e.currentPollingInterval)try{await e.enumerateDevices(!0),e.pollingTimer=e.window.setTimeout(i,e.currentPollingInterval)}catch(t){throw e.pollingTimer=null,t}};e.logger.safe.info(`starting device polling with interval ${t}ms`),e.pollingTimer=1,i()}static raiseFailedEnumeration(t){for(const i of e.enumeratorUsers.values())i.event("onDeviceEnumerationfailed").raise(t)}};Mk.isDeviceListAvailable=new Kt,Mk.initializeCalled=!1,Mk.currentPollingInterval=0,Mk.hasPendingUpdate=!1,Mk.enumeratorUsers=new Set;var Dk=Mk,kk=class extends Vi{constructor(e,t,i){super(i),this.deviceList=e,this.configProvider=t,this.logger=i,this.userSelectedDevices={microphone:null,camera:null,speaker:null},this.currentlySelectedDevices={microphone:null,camera:null,speaker:null,audioIngestDevice:null},this.deviceList.on("onDevicesChanged",(e=>this.onDevicesChanged(e))),e.devices.length>0&&this.onDevicesChanged(e.devices),this.logger.safe.info("Initialized")}get selectedDevices(){return nn(this.currentlySelectedDevices)}selectDevices(e){let t=!1;if(qi(e,((e,i)=>{const n=this.getDeviceToSelect(i,this.deviceList.getDevicesByType("audioIngestDevice"===i?"microphone":i),e);"camera"===i&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i]),n?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i],t=!0),this.currentlySelectedDevices[i]=n})),t){const e=Zi(this.currentlySelectedDevices).map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed from public interface: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!0)}}getDeviceToSelect(e,t,i){let n;const r=this.userSelectedDevices[e];return i?n=t.find((e=>e.guid===i)):r&&(n=t.find((e=>e.guid===r))),"audioIngestDevice"===e?n:n||t[0]}onDevicesChanged(e){let t=!1;if(Object.keys(this.currentlySelectedDevices).forEach((i=>{const n="audioIngestDevice"===i?"microphone":i,r=e.filter((e=>e.type===n));if(r.length>0){const e=this.getDeviceToSelect(i,r);e?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.currentlySelectedDevices[i]=e,t=!0)}else this.currentlySelectedDevices[i]&&(this.currentlySelectedDevices[i]=null,t=!0)})),t){const e=Zi(this.currentlySelectedDevices).map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed due to device list change: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!1)}}},Ok=class extends Vi{constructor(e,t){super(e),this.logger=e,this.mediaStream=t,this.subs=[],this.subscribeOnMediaStreamEvents(t)}acquire(){return this.mediaStream?this.mediaStream.start().then((()=>this.logger.safe.info("Stream acquired"))).catch((e=>{throw this.logger.safe.warn(`Failed to acquire the stream: ${tt(e)}`),e})):Promise.reject("Disposed")}dispose(){this.logger.safe.info("Disposing stream"),this.unsubscribeFromMediaStreamEvents(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),super.dispose()}subscribeOnMediaStreamEvents(e){this.subs=[e.on("onStreamClientStarted",(()=>this.event("onStreamStateChanged").raise("active"))),e.on("onStreamClientMuted",((e,t)=>this.event("onStreamStateChanged").raise(t?"inactive":"active"))),e.on("onStreamClientEnded",(()=>this.event("onStreamStateChanged").raise("stopped"))),e.on("onStreamClientError",((e,t)=>{const i=t.type===Gi.MEDIA_ERROR.permissionDeniedError||t.type===Gi.MEDIA_ERROR.sharingCancelledError;this.event("onStreamStateChanged").raise(i?"cancelled":"failed")}))]}unsubscribeFromMediaStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},Nk=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive,Gi.MEDIA_STATE.send,Gi.MEDIA_STATE.sendReceive],Lk=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive],xk=class extends Vi{constructor(e,t,i){super(i),this.configProvider=e,this.deviceManager=t,this.logger=i,this.currentState={microphone:"unknown",camera:"unknown"},this.lastGum={audio:!1,video:!1},this.registeredTrackers=new Set,this.accessIssuePermissionOther={audio:!1,video:!1},this.window=Mp.window,this.permittedModalities={audio:Nk,video:Nk,sharing:Nk},this.initialize()}async initialize(){!Vp.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(e){return this.currentState[e]||"unknown"}isPermissionKnown(e){const t=this.getPermissionState(e);return"unknown"!==t&&"prompt"!==t}get browserPermittedModalities(){return this.permittedModalities}get knownPermissionStates(){return nn(this.currentState)}update(e,t){const i=nn(t);e.audio||delete i.audio,e.video||delete i.video;const n=nn(this.permittedModalities);qi(i,((e,t)=>{this.permittedModalities[t]=e?Nk:Lk})),an(n,this.permittedModalities)||this.event("onDevicesPermissionChanged").raise()}async askDevicePermission(e){const t=e?nn(e):{audio:!0,video:this.deviceManager.hasCamera()};if(this.accessIssuePermissionOther={audio:!1,video:!1},this.configProvider.config.permissions.rememberNegative&&(t.audio=t.audio&&this.permittedModalities.audio===Nk,t.video=t.video&&this.permittedModalities.video===Nk),t.sharing)throw new Error("askDevicePermission does not support sharing constraints.");const i={audio:!1,video:!1};this.lastGum={audio:!1,video:!1};const n=async(i,n,r)=>{const s={audio:!!i.audio,video:!!i.video,sharing:!0};return!(this.configProvider.config.permissions.adpRequestAVLast&&t.audio&&t.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(t,s),this.deviceManager.raiseTelemetryEvent("ask_device_permission",{constraints:e,resultConstraints:i,error:r,reason:n}),s};await this.initialize();const r=this.getPermissionState("microphone"),s=this.getPermissionState("camera");if(this.logger.safe.info(`Permission state { audio: ${r}, video: ${s} }`),this.configProvider.config.permissions.useNegativeInAdp&&(!t.audio||"denied"===r)&&(!t.video||"denied"===s))return n(i,"navigator_permissions_denied");if(this.configProvider.config.permissions.usePositiveInAdp&&(!t.audio||t.audio&&"granted"===r)&&(!t.video||t.video&&"granted"===s))return n(t,"navigator_permissions_granted");try{return n(this.getConstrainsWithPermissionError(await this.askDevicePermissionPrompt(t,this.configProvider.config.permissions.adpFallback)),"stream_acquisition")}catch(e){return n(i,"stream_acquisition",e)}}async askDevicePermissionPrompt(e,t=!0){const i={audio:!1,video:!1};try{const t=this.deviceManager.getMediaStream(e);return t&&(this.lastGum=nn(e),await t.start(),i.audio=t.hasAudio(),i.video=t.hasVideo(),this.disposeLater(t)),i}catch(n){if(e.audio&&e.video&&t){try{i.video=this.configProvider.config.permissions.adpFallbackVideo&&(await this.askDevicePermissionPrompt({video:!0})).video}catch(e){e.type!==Gi.MEDIA_ERROR.permissionDeniedError&&e.type!==Gi.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.video=!0)}try{i.audio=this.configProvider.config.permissions.adpFallbackAudio&&(await this.askDevicePermissionPrompt({audio:!0})).audio}catch(e){e.type!==Gi.MEDIA_ERROR.permissionDeniedError&&e.type!==Gi.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.audio=!0)}}else if(t)throw n;return i}}getConstrainsWithPermissionError(e){return this.configProvider.config.permissions.disableOnPermissionDeniedOnly?{audio:this.accessIssuePermissionOther.audio||e.audio,video:this.accessIssuePermissionOther.video||e.video}:e}disposeLater(e){setTimeout((()=>{e.dispose()}),this.configProvider.config.mediaStreamHoldInterval)}async registerPermissionTracker(e){if(!this.registeredTrackers.has(e))try{const t=await this.window.navigator.permissions.query({name:e});this.handlePermissionStateChanged(e,t.state),t.onchange=()=>this.handlePermissionStateChanged(e,t.state),this.registeredTrackers.add(e)}catch(t){this.logger.safe.error(`Error querying permissions for ${e}: ${tt(t)}`)}}handlePermissionStateChanged(e,t){if(this.logger.safe.info(`Permission state for ${e} changed ${this.currentState[e]} -> ${t}`),this.configProvider.config.permissions.enumerateDevicesAfterChange){this.logger.safe.info(`enumerateDevicesAfterChange: ${JSON.stringify(this.configProvider.config.permissions)}`),Dk.logger.safe.info("enumerating due to permission change");try{Dk.enumerateDevices()}catch(e){Dk.logger.safe.error(`unable to enumerate on permission change: ${tt(e)}`)}}this.currentState[e]=t,this.deviceManager.raiseTelemetryEvent("permissions_state_changed",this.knownPermissionStates),this.deviceManager.handlePermissionStateChange()}},Fk=class extends gt{constructor(e,t=sn()){super(),this.dms=e,this.label=t,this.id=sn(),this.receivedEvents=new Map,this.subscribeToDeviceManagers(e)}getDeviceManagers(){return this.dms}dispose(){super.dispose(),this.dms?.forEach((e=>e.dispose())),this.dms=null}subscribeToDeviceManagers(e){e.forEach(((e,t)=>{e.on("onVideoEffectsEvent",((...t)=>this.eventHandler("onVideoEffectsEvent",e,(()=>this.event("onVideoEffectsEvent").raise(...t))))),e.on("onVideoEffectApplied",((...t)=>this.eventHandler("onVideoEffectApplied",e,(()=>this.event("onVideoEffectApplied").raise(...t))))),e.on("onDeviceTelemetryEvent",(e=>this.event("onDeviceTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onVideoEffectsTelemetryEvent",(e=>this.event("onVideoEffectsTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise(`${this.id}/${t}`))),e.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))}))}eventHandler(e,t,i){let n=this.receivedEvents.get(e);if(n??(n=new Set),n.add(t),this.dms.every((e=>n.has(e))))return i(),void n.clear();this.receivedEvents.set(e,n)}},Uk=()=>(e,t,i)=>{const n=i.value;return i.value=function(...e){return this.serialQueue.add(n.bind(this,...e))},i},Bk=class{constructor(e,t,i){this.configProvider=e,this.statistics=t,this.logger=i}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 e=this.configProvider.config.webcv.webGLUnsupportedRenderers;let t=!1;const i=Vp.unmaskedGlRenderer;return i&&!e.some((e=>e===i))?t=!0:(this.statistics.setError("RendererIsNotSupported",`Blacklisted from ${JSON.stringify(e)}`),this.logger.info(`Unsupported renderer: ${tt(i)}`)),t}isWebGL2Supported(){try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return this.statistics.setError("WebGL2IsNotSupported"),this.logger.info("WebGL2 context is not supported"),!1;const t=e.getSupportedExtensions(),i=this.configProvider.config.webcv.webGLRequiredExtensions.filter((e=>!t.includes(e)));if(i.length>0)return this.statistics.setError("WebGL2RequiredExtensionsNotSupported","Required WebGL2 extensions not supported."),this.logger.info(`Unsupported WebGL2 extensions: ${tt(i)}`),!1}catch(e){return this.statistics.setError("WebGL2IsNotSupported",`Error: ${tt(e)}`),this.logger.error(`isWebGL2Supported: ${tt(e)}`),!1}return!0}},Vk=class{constructor(e){this.loadDuration=-1,this.error=new jM(e)}hasData(){return this.error.items.length>0||this.loadDuration>0}startLoadTimer(){this.loadStartTimestamp=Date.now()}stopLoadTimer(){this.loadDuration=Date.now()-this.loadStartTimestamp}clearErrors(){this.error.clear()}setError(e,t){this.error.add({type:e,message:t})}getReport(){return{loadDuration:this.loadDuration,error:this.error.items}}},Hk=class extends Vi{constructor(e,t,i,n){super(i),this.webcvProvider=e,this.configProvider=t,this.logger=i,this.wasmLoader=n,this.serialQueue=new tk(this.logger),this.videoEffectToWebCVEffectMapping={0:vh.VideoEffectType.Off,1:vh.VideoEffectType.BackgroundBlur,16:vh.VideoEffectType.BackgroundReplacement,512:vh.VideoEffectType.PresenterMode,256:vh.VideoEffectType.None,2048:vh.VideoEffectType.None,262144:vh.VideoEffectType.None},this.currentEffect=0,this.effectProviderSubs=[],this.statistics=new Vk(this.configProvider.config.effectsTelemetryBufferSize),this.processorType=vh.ProcessorType.Webgl2,this.queryMessageProcessor=new $k(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(e){throw Error(e)}}async dispose(){this.logger.safe.debug("Dispose"),this.effectProvider&&(this.effectProviderSubs.forEach((e=>e.dispose())),this.effectProviderSubs=null,await this.effectProvider.disposeAsync()),super.dispose()}async configure(e){if(this.logger.safe.debug(`Set config: ${JSON.stringify(e)}`),this.effectConfig={backgroundImageUrl:e.imagePath,headers:e.headers},this.effectProvider)return this.effectProvider.configureEffect(this.effectConfig);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setEffectAsync(e){if(this.currentEffect===e)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: ${e}`);const t=this.getWebCVEffect(e);if(!t)throw new Error(`Effect with type ${e} is not supported`);if(this.shouldCollectStats(e)&&this.notifyAboutLastSessionStats("EffectChanged"),this.currentEffect=e,this.effectProvider)try{await this.effectProvider.setEffectAsync(t)}catch(e){throw await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to apply ${t}, error:${tt(e)}`),e}else this.logger.safe.debug("WebCV is not initialized. Do nothing")}async processingVideoEffectMessage(e){let t={code:0,response:{effects:[]},type:"EnableEffects"};try{await this.init()}catch(e){return this.logger.error(`Failed to initialize WebCV, error:${tt(e)}`),this.notifyError("FailedToInitialize",`Initialization failed, error:${tt(e)}`),t}const i=this.currentEffect;this.logger.info(`Processing video effect request type: ${JSON.stringify(e.type)}`),t=await this.queryMessageProcessor.processVideoEffectMessage(e),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(i)&&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 t}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}`),!this.effectProvider)return this.logger.safe.debug("WebCV is not initialized. Do nothing"),e;let t=e;try{t=await this.effectProvider.setSourceAsync(e)}catch(e){await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to set source, error:${tt(e)}`)}return t}async removeSourceAsync(e){if(this.logger.safe.debug(`Remove source: ${e?e.id:"no stream"}`),this.effectProvider)return this.effectProvider.removeSourceAsync(e);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async getEffectsCapability(){let e=0;const t=await this.getCapability();this.logger.safe.debug(`Get capabilty with return: ${JSON.stringify(t)}`);for(const i of t)e|=i;return e}getStats(e){if(!this.effectProvider)return;const t=this.effectProvider.getStats(),i=this.statistics.getReport();return t||i.error.length?{timestamp:Date.now(),statsReason:e,...this.createTelemetryEvent(t,i)}:void 0}getVersion(){return this.effectProvider?.getVersion?.()??"Unknown"}async resetOutputConstraints(e,t=vh.EffectQualityChangeReason.ExternalParam){const i={...this.configProvider.config.webcv.qualityConfig};return i.outputResolution=e.height,this.effectProvider?.configureStreamProcessor(i,vh.EffectQualityChangeReason.ExternalParam)}createTelemetryEvent(e,t){return{payload:{version:this.getVersion(),...t,...e,isWasmEnabled:this.processorType===vh.ProcessorType.Wasm}}}notifyError(e,t){this.statistics.setError(e,t),this.notifyAboutLastSessionStats("EffectError")}notifyAboutLastSessionStats(e){const t=this.getStats(e);t&&this.event("onVideoEffectTelemetryEvent").raise(t)}async initializeVideoEffectProvider(){if(!this.webcvProvider)return this.logger.safe.debug("WebCV provider is not set"),null;this.statistics.startLoadTimer();const e=await this.webcvProvider.getVideoEffectProvider();if(this.statistics.stopLoadTimer(),!e)return this.statistics.setError("FailedToInitialize"),this.logger.safe.warn("WebCV is not initialized"),null;this.logger.safe.debug(`WebCV v${e.getVersion?.()} is initialized`);const t=await this.webcvProvider.getModelConfig();return await e.configureModel(t),this.configProvider.config.webcv.loadWorkerCallback=this.wasmLoader.getWorkerFunction("wasmcv"),this.configProvider.config.webcv.loadTimerWorkerCallback=this.wasmLoader.getWorkerFunction("timer"),await e.configure({...this.configProvider.config.webcv,processorType:this.processorType}),this.effectConfig&&await e.configureEffect(this.effectConfig),this.effectProviderSubs=[e.on("onEffectApplied",(()=>this.event("onMediaStreamUpdateRequested").raise("Video"))),e.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats("EffectStopped"))),e.on("onVideoEffectQualityChanged",(e=>this.event("onVideoEffectQualityChanged").raise(e))),e.on("onVideoStreamQualityChanged",(e=>this.event("onVideoStreamQualityChanged").raise(e.resolution,e.fps,e.reason))),e.on("onCapabilitiesChanged",(()=>this.event("onVideoEffectCapabilitiesChanged").raise())),e.on("onFirstFrameProcessed",(()=>this.onFirstFrameProcessed())),e.on("onErrorNotified",(e=>this.notifyError("WebcvProcessorError",e))),e.on("videoFreezeDetected",(e=>this.event("videoFreezeDetected").raise(e)))],e}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 e=new Bk(this.configProvider,this.statistics,this.logger.createChild("CapabilityChecker"));let t=[0];return e.isWasmEffectSupported()?(t=[0,1,16,262144,512,2048],this.processorType=vh.ProcessorType.Wasm):e.isWebgl2EffectSupported()&&(t=[0,1,16],this.processorType=vh.ProcessorType.Webgl2),t}getWebCVEffect(e){return this.videoEffectToWebCVEffectMapping[e]||vh.VideoEffectType.None}onFirstFrameProcessed(){this.event("onVideoEffectApplied").raise(),this.logger.safe.debug("onVideoEffectApplied event raised")}async handleFailedProcessing(){this.currentEffect=0;try{await this.effectProvider.setEffectAsync(vh.VideoEffectType.Off)}catch(e){this.notifyError("WebcvProcessorError",`Failed to handle error state, error:${tt(e)}`)}}shouldCollectStats(e){return 0!==this.currentEffect&&0!==e&&this.currentEffect!==e}};m([Uk()],Hk.prototype,"init",1),m([Uk()],Hk.prototype,"dispose",1),m([Uk()],Hk.prototype,"configure",1),m([Uk()],Hk.prototype,"setSourceAsync",1),m([Uk()],Hk.prototype,"removeSourceAsync",1),m([Uk()],Hk.prototype,"getEffectsCapability",1);var $k=class{constructor(e,t){this.configProvider=e,this.logger=t,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(e){this.shouldReconfigure=e}async processVideoEffectMessage(e){switch(e.type){case"EnableEffects":return await this.processEnableEffectsMessage(e);case"DisableEffects":return await this.processDisableEffectsMessage(e);case"QueryEffects":return await this.processQueryEffectsMessage(e);default:return this.logger.error(`Unsupported video effect message type: ${e.type}`),null}}async processEnableEffectsMessage(e){const t={code:0,response:{effects:[]},type:"EnableEffects"};for(let i=0;i<e.request.effects.length;i++){const n=e.request.effects[i];switch(n.type){case"BackgroundModification":if("Blur"===n.options.variant){this.currentEffects|=1;const e={type:"BackgroundModification",options:{variant:"Blur"}};t.response.effects.push(e),this.currentEffects&=-262673}else if("Replacement"===n.options.variant){this.currentEffects|=16;const e={type:"BackgroundModification",options:{variant:"Replacement",location:n.options.location}};this.shouldReconfigure=!0,this.currentEffectPayload.imageConfig={backgroundImageUrl:n.options.location,headers:n.options?.headers},t.response.effects.push(e),this.currentEffects&=-262658}else if("WeatherPerson"===n.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 e={type:"BackgroundModification",options:{variant:"WeatherPerson"}};t.response.effects.push(e),this.currentEffects&=-262162}else if("Bokeh"===n.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 e={type:"BackgroundModification",options:{variant:"Bokeh"}};t.response.effects.push(e),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,t.response.effects.push({type:"AutoAdjust"})}}return t}async processQueryEffectsMessage(e){const t={code:0,response:{effects:[]},type:"QueryEffects"};if(1&this.currentEffects){const e={type:"BackgroundModification",options:{variant:"Blur"},state:"On"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"Blur"},state:"Off"};t.response.effects.push(e)}if(262144&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Off"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Unavailable"};t.response.effects.push(e)}if(16&this.currentEffects){const e={variant:"Replacement",location:""};this.currentEffectPayload?.imageConfig&&(e.location=this.currentEffectPayload?.imageConfig.backgroundImageUrl);const i={type:"BackgroundModification",options:e,state:"On"};t.response.effects.push(i)}else{const e={type:"BackgroundModification",options:{variant:"Replacement",location:""},state:"Off"};t.response.effects.push(e)}if(512&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Off"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Unavailable"};t.response.effects.push(e)}if(256&this.currentEffects){const e={type:"TouchUp",state:"Unavailable",options:{strength:0}};t.response.effects.push(e)}if(2048&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"AutoAdjust",state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"AutoAdjust",state:"Off"};t.response.effects.push(e)}else{const e={type:"AutoAdjust",state:"Unavailable"};t.response.effects.push(e)}return t}async processDisableEffectsMessage(e){const t={code:0,response:{effects:[]},type:"DisableEffects"},i=e,n={effects:[]};for(let e=0;e<i.request.effects.length;e++){const t=i.request.effects[e];switch(t.type){case"BackgroundModification":if("Blur"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"Blur"}};n.effects.push(e),this.currentEffects&=-2}if("Bokeh"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"Bokeh"}};n.effects.push(e),this.currentEffects&=-262145}if("Replacement"===t.options.variant){const e={variant:"Replacement",location:""};void 0!==this.payload?.imageConfig&&(e.location=this.payload?.imageConfig.backgroundImageUrl);const t={type:"BackgroundModification",options:e};n.effects.push(t),this.currentEffects&=-17}if("WeatherPerson"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"}};n.effects.push(e),this.currentEffects&=-513}break;case"TouchUp":this.logger.error("TouchUp effect is not supported now"),n.effects.push({type:"TouchUp",options:{strength:0}}),this.currentEffects&=-257,this.currentEffectPayload.softfocusStrength=0;break;case"AutoAdjust":n.effects.push({type:"AutoAdjust"}),this.currentEffects&=-2049}}return t.response=n,t}},jk=class extends Vi{constructor(e,t,i,n,r,s){super(r),this.wasmdnsProvider=e,this.wasmaecProvider=t,this.wasmVqeProvider=i,this.configProvider=n,this.logger=r,this.wasmLoader=s,this.serialQueue=new tk(this.logger),this.stopped=!0,this.hasError=!1,this.isProviderReady=!1,this.statistics=new Vk(this.configProvider.config.effectsTelemetryBufferSize),this.currentEffect=Sh.AudioEffectType.Off,this.currentEffectCapability=0,this.audioEffectToWasmAudioEffectType={0:Sh.AudioEffectType.Off,1:Sh.AudioEffectType.NoiseSuppressionClassic,2:Sh.AudioEffectType.NoiseSuppressionDeep,4:Sh.AudioEffectType.EchoCancellationClassic,8:Sh.AudioEffectType.VoiceQualityEnhancementClassic,16:Sh.AudioEffectType.VoiceQualityEnhancementDeep},this.noiseSuppressionModeToWasmDnsEffectMapping={Off:Sh.AudioEffectType.Off,High:Sh.AudioEffectType.NoiseSuppressionDeep,Low:Sh.AudioEffectType.NoiseSuppressionClassic},this.wasmLoaderSub=this.wasmLoader?.on("onLoadError",(e=>{this.handleWasmLoaderError(e)}))}get isEffectEnabled(){return this.currentEffect!==Sh.AudioEffectType.Off}shouldFallbackToNativeProcessing(){return this.configProvider.config.wasmvqe.enableVqe||this.configProvider.config.wasmdns.enableNoiseSuppression?this.configProvider.config.wasmvqe.asyncInitialization&&!this.isProviderReady?(this.logger.safe.info("shouldFallbackToNativeProcessing: provider is not yet initialized"),!0):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(e,t){switch(e){case"High":return t?Sh.VqeMode.DeepVQE:Sh.VqeMode.DeepNS;case"Low":return t?Sh.VqeMode.SkypeVQE:Sh.VqeMode.SkypeNS;default:return t?Sh.VqeMode.SkypeAEC:Sh.VqeMode.Off}}vqeModeToNsMode(e){switch(e){case Sh.VqeMode.DeepVQE:case Sh.VqeMode.DeepNS:return"High";case Sh.VqeMode.SkypeVQE:case Sh.VqeMode.SkypeNS:return"Low";case Sh.VqeMode.SkypeAEC:case Sh.VqeMode.Off:default:return"Off"}}vqeModeToAudioEffectType(e){switch(e){case Sh.VqeMode.DeepVQE:return 16;case Sh.VqeMode.DeepNS:return 2;case Sh.VqeMode.SkypeVQE:return 8;case Sh.VqeMode.SkypeNS:return 1;case Sh.VqeMode.SkypeAEC:return 4;case Sh.VqeMode.Off:default:return 0}}audioEffectTypeToVqeMode(e){switch(e){case 16:return Sh.VqeMode.DeepVQE;case 2:return Sh.VqeMode.DeepNS;case 8:return Sh.VqeMode.SkypeVQE;case 1:return Sh.VqeMode.SkypeNS;case 4:return Sh.VqeMode.SkypeAEC;default:return Sh.VqeMode.Off}}async setSourceWithAsyncInitialization(e){if(this.hasError)return e;if(!this.isProviderReady)return this.logger.safe.info("Provider is not ready. Initializing provider async"),this.initialize(),e;if(this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),e;try{const t=await this.vqeProvider.setSourceAsync(e);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),t}catch(t){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${t})`),e}}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}, currentEffect = ${this.currentEffect}`),this.stopped||this.stop(),this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),e;if(await this.initializeProvider(),await this.configureEffect(),this.isProviderReady=!0,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const t=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${t}).`),this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${t}).`),e}if(!this.configProvider.config.wasmvqe.enableVqe&&!this.configProvider.config.wasmdns.enableNoiseSuppression)return e;if(this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((e,t)=>this.notifyError("WasmVqeProcessorError",e,t))),this.dnsProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onErrorNotified",(e=>this.notifyError("WasmDnsProcessorError",e))),this.aecProvider?.on("onErrorNotified",(e=>this.notifyError("WasmAecProcessorError",e)))],this.configProvider.config.wasmvqe.enableVqe)try{const t=await this.vqeProvider.setSourceAsync(e);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),t}catch(t){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${t})`),e}let t=e;try{t=await this.aecProvider.setSourceAsync(e),this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId))}catch(e){this.notifyError("WasmAecProcessorError",`setSourceAsync: Failed to asynchronously set source for AEC (${e})`)}try{return await this.dnsProvider.setSourceAsync(t)}catch(e){this.notifyError("WasmDnsProcessorError",`setSourceAsync: Failed to asynchronously set source for DNS (${e})`)}return t}setAecRefStream(e,t){try{if(!e&&this.rendererId!==t)return void this.logger.safe.debug(`Ref stream can't be set to null by renderer ${t}`);if(this.logger.safe.debug(`Setting the reference stream to: ${e?e.id:"Null"} requested by renderer ${t}`),this.aecRefStream=e,this.rendererId=t,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setAecRefStream: audio effect provider not initialized (${e}).`),void this.logger.safe.warn(`Unable to setAecRefStream for audio effects: audio effect provider not initialized (${e}).`)}this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider.setRefStream(e):this.configProvider.config.wasmdns.enableNoiseSuppression&&this.aecProvider.setRefStream(e)}catch(e){this.notifyError("WasmVqeProcessorError",`setRefStream: Failed to set reference stream for echo cancellation (${e})`)}}async setEffectAsync(e){const t=this.audioEffectToWasmAudioEffectType[e];if(this.currentEffect===t)return;const i=this.currentEffect===Sh.AudioEffectType.Off||t===Sh.AudioEffectType.Off;if(this.currentEffect=t,this.userNoiseSuppressionMode=this.audioEffectTypeToVqeMode(e),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";throw this.notifyError("FailedToInitialize",`setEffectAsync: audio effect provider not initialized (${e}).`),Error("FailedToInitialize")}try{this.configProvider.config.wasmvqe.enableVqe?await this.vqeProvider.setEffectAsync(t):this.configProvider.config.wasmdns.enableNoiseSuppression&&(await this.dnsProvider.setEffectAsync(t),await this.aecProvider.setEffectAsync(t)),this.configProvider.config.applyAudioEffectOnDemand&&this.configProvider.config.wasmvqe.enableVqe&&i&&this.requestStreamUpdate(),this.logger.safe.debug(`The audio effect was set to '${t}'`)}catch(e){throw this.notifyError("WasmVqeProcessorError",`setEffectAsync: Failed to apply '${t}' audio effect, error: ${tt(e)}`),e}}stop(){try{this.dnsProvider?.dispose(),this.dnsProvider=null,this.aecProvider?.dispose(),this.aecProvider=null,this.vqeProvider?.dispose(),this.vqeProvider=null,this.effectProviderSubs?.forEach((e=>e?.dispose())),this.effectProviderSubs=null,this.wasmLoaderSub?.dispose(),this.wasmLoaderSub=null,this.stopped=!0,this.isProviderReady=!1,this.logger.safe.debug("The audio effects provider was stopped.")}catch(e){this.logger.safe.error(`Failed to stop the audio effects provider (${e})`)}}dispose(){try{this.hasError=!1,this.stop(),super.dispose(),this.logger.safe.debug("The audio effects provider was disposed.")}catch(e){this.logger.safe.error(`dispose: Failed to dispose the audio effects provider (${e})`)}}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(){let e=this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider?.getStats():this.dnsProvider?.getStats();if(!e){if(!this.statistics.hasData())return null;e={}}return e.userNoiseSuppressionMethod=this.userNoiseSuppressionMode,{timestamp:Date.now(),...this.createTelemetryEvent(e)}}notifyError(e,t,i=!1){this.logger.error(`Audio effect error: ${e}, message: ${t}`),this.statistics.setError(e,t),this.notifyAboutLastSessionStats(),i&&(this.stop(),this.requestStreamUpdate(),this.hasError=!0),this.event("onEffectsError").raise("Audio",e,t)}async initialize(){this.stopped||this.stop(),this.statistics.startLoadTimer(),await this.initializeProvider(),this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((e,t)=>this.notifyError("WasmVqeProcessorError",e,t)))],await this.configureEffect(),this.isProviderReady=!0,this.statistics.stopLoadTimer(),this.requestStreamUpdate()}async initializeProvider(){if(this.configProvider.config.wasmvqe.enableVqe&&!this.vqeProvider)return this.logger.safe.debug("Initializing VQE provider ..."),void(this.vqeProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.VoiceQualityEnhancementDeep));this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.dnsProvider&&(this.logger.safe.debug("Initializing DNS provider ..."),this.dnsProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.NoiseSuppressionDeep)),this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.aecProvider&&(this.logger.safe.debug("Initializing AEC provider ..."),this.aecProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.EchoCancellationClassic))}async configureEffect(e){this.statistics.clearErrors();let t=e;if(!t){let e=this.configProvider.mediaConfig.noiseSuppressionMode;this.logger.safe.info(`Configuring the audio effect manager for Noise Suppression mode: ${e}`),"Auto"===e&&(e=this.configProvider.config.wasmvqe.enableVqe?this.vqeModeToNsMode(this.configProvider.config.wasmvqe.defaultVqeMode):this.configProvider.config.wasmdns.noiseSuppressionMode,this.logger.safe.info(`Overriding 'Auto' with ${e}`)),t={...this.configProvider.config.wasmdns,...this.configProvider.config.wasmvqe},t.noiseSuppressionMode=e}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&&(t.defaultVqeMode=this.userNoiseSuppressionMode),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorklet,t.loadWasmWorkerCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorker,this.logger.safe.debug("Configuring VQE audio effects ..."),await this.vqeProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${tt(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${tt(t)},\n under the following capability: ${this.currentEffectCapability}.`,!0)}else if(this.configProvider.config.wasmdns.enableNoiseSuppression){t.noiseSuppressionMode||(this.logger.safe.debug("configureEffect was called without a noiseSuppressionMode. Using noiseSuppressionMode from config provider ..."),t.noiseSuppressionMode=this.configProvider.mediaConfig.noiseSuppressionMode),this.currentEffect=this.noiseSuppressionModeToWasmDnsEffectMapping[t.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 ..."),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmDnsWorklet,await this.dnsProvider.configureEffect(t),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmAecWorklet,await this.aecProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${tt(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${tt(t)},\n under the following capability: ${this.currentEffectCapability}.`,!0)}}}async initializeAudioEffectProvider(e){if(!this.wasmVqeProvider&&e===Sh.AudioEffectType.VoiceQualityEnhancementDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmVqe package not available."),this.logger.safe.warn("WasmVqe package not available."),null;if(!this.wasmdnsProvider&&e===Sh.AudioEffectType.NoiseSuppressionDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmDns package not available."),this.logger.safe.warn("WasmDns package not available."),null;if(!this.wasmaecProvider&&e===Sh.AudioEffectType.EchoCancellationClassic)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmAec package not available."),this.logger.safe.warn("WasmAec package not available."),null;let t;try{this.configProvider.config.wasmvqe.enableVqe&&e===Sh.AudioEffectType.VoiceQualityEnhancementDeep&&(t=await this.wasmVqeProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===Sh.AudioEffectType.NoiseSuppressionDeep&&(t=await this.wasmdnsProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===Sh.AudioEffectType.EchoCancellationClassic&&(t=await this.wasmaecProvider.getAudioEffectProvider())}catch(e){this.logger.safe.warn(`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`),this.statistics.setError("FailedToInitialize",`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`)}return this.statistics.stopLoadTimer(),t?(e===Sh.AudioEffectType.VoiceQualityEnhancementDeep&&this.logger.safe.debug(`WasmVqe v${t.getVersion?.()} initialized!`),e===Sh.AudioEffectType.NoiseSuppressionDeep&&this.logger.safe.debug(`WasmDns v${t.getVersion?.()} initialized!`),e===Sh.AudioEffectType.EchoCancellationClassic&&this.logger.safe.debug(`WasmAec v${t.getVersion?.()} initialized!`),t):(this.logger.safe.warn("Unitialized Wasm audio effect provider."),null)}createTelemetryEvent(e){return{payload:{audioEffectsCapability:this.currentEffectCapability,version:this.getVersion(),isProviderReady:this.isProviderReady,...this.statistics.getReport(),...e}}}notifyAboutLastSessionStats(){const e=this.getStats();e&&this.event("onAudioEffectTelemetryEvent").raise(e)}handleWasmLoaderError(e){"wasmvqe"===e&&this.notifyError("FailedToInitialize","Error loading additional scripts",!0)}requestStreamUpdate(){this.hasError||(this.logger.warn("Requesting stream update"),this.event("onMediaStreamUpdateRequested").raise("Audio"))}};m([Uk()],jk.prototype,"setSourceWithAsyncInitialization",1),m([Uk()],jk.prototype,"setSourceAsync",1),m([Uk()],jk.prototype,"setAecRefStream",1),m([Uk()],jk.prototype,"setEffectAsync",1),m([Uk()],jk.prototype,"stop",1),m([Uk()],jk.prototype,"dispose",1);var Gk=class{constructor(e){this.logger=e}async setSourceAsync(e){let t=document.createElement("video");return t.srcObject=e,this.logger.info(`Stream settings before play: ${JSON.stringify(this.getSettings(e))}`),await t.play(),this.logger.info(`Stream settings after play: ${JSON.stringify(this.getSettings(e))}`),t.pause(),t.srcObject=null,t.remove(),t=null,e}getSettings(e){return e.getVideoTracks()?.[0]?.getSettings()}},qk=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.logger=t}isEffectEnabled(e){switch(e){case"Video":return this.videoEffectManager?.isEffectEnabled;case"Audio":return this.audioEffectManager?.isEffectEnabled;default:return!1}}shouldFallbackToNativeProcessing(e){return"Audio"===e&&this.audioEffectManager?.shouldFallbackToNativeProcessing()}addEffectManager(e,t){switch(e){case"Audio":this.addAudioEffectManagerAndSubscribe(t);break;case"Video":this.configProvider.config.waitForVideoEffectStreamStart&&(this.delayedVideoEffectManager=new Gk(this.logger.createChild("DelayedVideoEffectManager"))),this.addVideoEffectManagerAndSubscribe(t);break;case"ScreenShare":this.delayedScreenShareEffectManager=new Gk(this.logger.createChild("DelayedScreenShareEffectManager"))}}async startEffect(e,t){switch(e){case"Audio":return this.initAudioEffectsWithTimeout(t);case"Video":if(this.configProvider.config.waitForVideoEffectStreamStart){const e=await this.videoEffectManager.setSourceAsync(t);return this.delayedVideoEffectManager.setSourceAsync(e)}return this.videoEffectManager.setSourceAsync(t);case"ScreenShare":return this.delayedScreenShareEffectManager.setSourceAsync(t);default:return t}}async setEffectType(e,t){switch(e){case"Audio":return this.audioEffectManager?.setEffectAsync(t);case"Video":return this.videoEffectManager?.setEffectAsync(t)}}async processingVideoEffectMessage(e){return this.videoEffectManager.processingVideoEffectMessage(e)}stopEffect(e,t){switch(e){case"Audio":this.logger.safe.info("stopping audio effect"),this.audioEffectManager?.dispose();break;case"Video":this.logger.safe.info("stopping video effect"),this.videoEffectManager?.removeSourceAsync(t)}}resetOutputConstraints(e,t,i){"Video"===e&&this.videoEffectManager?.resetOutputConstraints(t,i)}getStats(e,t){switch(e){case"Audio":return this.audioEffectManager?.getStats();case"Video":return this.videoEffectManager?.getStats(t);default:return}}async configure(e,t){if("Video"===e)return this.videoEffectManager?.configure(t)}async getEffectsCapability(e){switch(e){case"Audio":return this.audioEffectManager?.getEffectsCapability();case"Video":return this.videoEffectManager?.getEffectsCapability();default:return 0}}setAecRefStream(e,t){return this.audioEffectManager.setAecRefStream(e,t)}vqeModeToAudioEffectType(e){return this.audioEffectManager.vqeModeToAudioEffectType(e)}nsModeToVqeMode(e,t){return this.audioEffectManager.nsModeToVqeMode(e,t)}getAudioEffectsProviderName(){let e="None";return this.configProvider.config.wasmvqe.enableVqe?e="DeepVqe":this.configProvider.config.wasmdns.enableNoiseSuppression&&(e="DNS"),e}dispose(){super.dispose(),this.audioEffectManager?.dispose(),this.audioEffectManager=null,this.videoEffectManager?.dispose(),this.videoEffectManager=null}async initAudioEffectsWithTimeout(e){return new Promise(((t,i)=>{const n=window.setTimeout((()=>{const i=`AudioEffects init timeout. Init took more then ${this.configProvider.config.wasmvqe.initializationTimeoutMs} ms`;this.logger.warn(i),this.audioEffectManager.notifyError("InitializationTimeout",i),t(e)}),this.configProvider.config.wasmvqe.initializationTimeoutMs);this.configProvider.config.wasmvqe.asyncInitialization?this.audioEffectManager.setSourceWithAsyncInitialization(e).then((e=>{clearTimeout(n),t(e)})):this.audioEffectManager.setSourceAsync(e).then((e=>{clearTimeout(n),t(e)}))}))}addAudioEffectManagerAndSubscribe(e){this.audioEffectManager||(this.audioEffectManager=new jk(e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.configProvider,this.logger.createChild("AudioEffectManager"),e.wasmLoader),this.audioEffectManager.on("onAudioEffectTelemetryEvent",(e=>{this.event("onAudioEffectTelemetryEvent").raise(e)})),this.audioEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})),this.audioEffectManager.on("onEffectsError",((e,t,i)=>{this.event("onEffectsError").raise(e,t,i)})))}addVideoEffectManagerAndSubscribe(e){this.videoEffectManager||(this.videoEffectManager=new Hk(e.webcvProvider,this.configProvider,this.logger.createChild("VideoEffectManager"),e.wasmLoader),this.videoEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})),this.videoEffectManager.on("onVideoEffectQualityChanged",(e=>{this.event("onVideoEffectQualityChanged").raise(e)})),this.videoEffectManager.on("onVideoStreamQualityChanged",((e,t,i)=>{this.event("onVideoStreamQualityChanged").raise(e,t,i)})),this.videoEffectManager.on("onVideoEffectCapabilitiesChanged",(()=>{this.event("onVideoEffectCapabilitiesChanged").raise()})),this.videoEffectManager.on("onVideoEffectTelemetryEvent",(e=>{this.event("onVideoEffectTelemetryEvent").raise(e)})),this.videoEffectManager.on("onVideoEffectApplied",(()=>{this.event("onVideoEffectApplied").raise()})),this.videoEffectManager.on("videoFreezeDetected",(e=>{this.event("videoFreezeDetected").raise(e)})))}},zk=class{constructor(e){this.audioContext=new Mp.window.AudioContext,e?(this.sourceNode=this.audioContext.createMediaStreamSource(e),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(e){return 1===e?this.analyzerNode?.getByteFrequencyData(this.freqs):0===e&&this.analyzerNode?.getByteTimeDomainData(this.freqs),this.freqs}getDataFloat(e){return 1===e?this.analyzerNode?.getFloatFrequencyData(this.ffreqs):0===e&&this.analyzerNode?.getFloatTimeDomainData(this.ffreqs),this.ffreqs}getInputLevel(){return this.analyzerNode?.getByteFrequencyData(this.freqs),function(e){return e.reduce(((e,t)=>e+t),0)/(e.length?e.length:1)}(this.freqs)}getInputLevelNormalized(e=65535,t=255){return Math.floor(this.getInputLevel()*e/t)}createAnalyserNode(e){const t=this.audioContext.createAnalyser();return t.fftSize=1024,t.smoothingTimeConstant=.1,e.connect(t),t}},Wk=class{constructor(e,t){this.getAudioStream=e,this.logger=t,this.initialized=!1,this.disposeCachedStream=!1}async init(){if(this.initialized=!0,!this.cachedStream)return this.createStream();this.createAnalyzer()}getInputLevel(){if(!this.initialized||!this.audioStreamAnalyzer)return 0;try{return this.audioStreamAnalyzer.getDataFloat(0).reduce(((e,t)=>Math.max(Math.abs(t),e)),0)}catch(e){return this.logger.error(JSON.stringify(e)),0}}getInputLevelNormalized(e,t){throw new Error("Method not implemented.")}dispose(e){this.logger.safe.info(`[${e}] AudioStreamAnalyzerWrapper disposed`),this.disposeStreamAnalyzer(),this.disposeStream(),this.initialized=!1}async updateStreamAfterDeviceChange(){this.initialized&&this.disposeCachedStream&&(this.disposeStream(),await this.createStream())}setStream(e,t){this.initialized?("AudioStreamAnalyzerWrapper"!==t&&this.disposeStream(),this.cachedStream=e,this.createAnalyzer()):this.cachedStream=e}createAnalyzer(){this.disposeStreamAnalyzer(),this.audioStreamAnalyzer=new zk(this.cachedStream.getMasterStream().rawStream),this.logger.safe.info("AudioStreamAnalyzerWrapper created")}async createStream(){await this.getAudioStream(!1,"AudioStreamAnalyzerWrapper"),this.disposeCachedStream=!0}disposeStreamAnalyzer(){this.audioStreamAnalyzer?.dispose(),this.audioStreamAnalyzer=null}disposeStream(){this.disposeCachedStream&&(this.cachedStream?.getMasterStream()?.dispose(),this.cachedStream?.dispose(),this.cachedStream=null,this.disposeCachedStream=!1)}},Kk=class e extends Vi{constructor(t,i,n,r,s,a,o,l,c,d){super(t),this.logger=t,this.configProvider=i,this.diagnostics=n,this.domOverrides=r,this.ufdManager=s,this.id=sn(),this.virtualDeviceRecord=new Map,this.deviceEnumerator=new Dk(this.configProvider,this.logger.createChild("DeviceEnumerator")),this.deviceSelection=new kk(Dk.list,this.configProvider,this.logger.createChild("DeviceSelection")),this.permissionManager=new xk(this.configProvider,{getMediaStream:e=>this.getMediaStream({...e,withEffect:!1,withTimeout:!0,force:!1,audioProcessingFlags:e.audio&&!e.video?this.getAudioProcessingFlags():void 0},"permissionManager"),hasCamera:()=>this.hasDeviceType("camera"),raiseTelemetryEvent:(e,t)=>this.raiseTelemetryEvent(e,t),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 XD(this.logger.createChild("RawDeviceStream"),this.raiseTelemetryEvent.bind(this)),this.customDeviceMediaStreamMap=new Map,this.clientAudioRenderers=new Map,this.audioStreamAnalyzerWrapper=new Wk(((e,t)=>this.getAudioStream(e,t)),this.logger.createChild("AudioStreamAnalyzerWrapper")),this.audioSharingRequested=!1,this.virtualDeviceSubs=new Map,this.effectsManagerInternal=new qk(this.configProvider,this.logger.createChild("EffectsManager")),this.effectsManagerInternal.addEffectManager("Audio",{wasmdnsProvider:o,wasmaecProvider:l,wasmVqeProvider:c,wasmLoader:d}),this.effectsManagerInternal.addEffectManager("Video",{webcvProvider:a,wasmLoader:d}),this.effectsManagerInternal.addEffectManager("ScreenShare",null),this.mediaStreamManager=new mk(this.logger.createChild("MediaStreamManager"),this.configProvider,this.effectsManager),this.deviceManagerSubscriptions=[this.permissionManager.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise())),Dk.list.on("onDevicesChanged",((e,t)=>this.onDevicesChanged(e,t))),this.deviceSelection.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),this.effectsManager.on("onAudioEffectTelemetryEvent",(e=>{this.diagnostics.registerAudioEffectsEvent(nn(e)),this.event("onAudioEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onMediaStreamUpdateRequested",(e=>this.onMediaStreamUpdateRequested(e,!0))),this.effectsManager.on("onVideoEffectQualityChanged",(e=>this.onVideoEffectsQualityEventHandler(e))),this.effectsManager.on("onVideoEffectTelemetryEvent",(e=>{this.diagnostics.registerVideoEffectsEvent(nn(e)),this.event("onVideoEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onVideoEffectApplied",(()=>{this.raiseTelemetryEvent("video_effect_applied",{}),this.event("onVideoEffectApplied").raise()})),this.effectsManager.on("onEffectsError",((e,t,i)=>this.event("onEffectsError").raise(e,t,i)))],this.subscribeOnStreamManagerEvents(),this.subscribeOnDeviceEnumeratorEvents(),this.deviceList.length&&this.onSelectedDevicesChanged(this.deviceSelection.selectedDevices,!1),this.createChildDeviceManager=t=>new e(t,i,new fk(i),r,s,a,o,l,c,d)}get deviceList(){return Dk.list.devices}get isDeviceListAvailable(){return Dk.isDeviceListAvailable}get isAudioOutputSelectionSupported(){return this.configProvider.userAgentConfig.isAudioOutputSelectionSupported}get effectsManager(){return this.effectsManagerInternal}createPreviewRenderer(e,t){const i=new uk(e,this,this.logger.createChild("videorenderer"),this.configProvider,t);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(i.getVideoElement()),this.subscribeOnRendererEvents(i),i}async askDevicePermission(e){await this.isDeviceListAvailable.promise;const t=await this.permissionManager.askDevicePermission(e);if(this.configProvider.config.devices.enumerateDevicesAfterADP)try{await Dk.enumerateDevices()}catch(e){this.logger.safe.warn(`Post-ADP device enumeration failed: ${tt(e)}`)}return t}getPermissionState(e){return this.permissionManager.getPermissionState(e)}handlePermissionStateChange(){this.diagnostics&&(this.diagnostics.permissionStates=this.permissionManager.knownPermissionStates),this.event("onPermissionStateChanged").raise()}onMediaStreamUpdateRequested(e,t=!1){if("Video"===e&&(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(e)));this.event("onStreamUpdateRequested").raise(e,t)}createAudioRenderer(){const e=new ek(this.logger.createChild("CustomAudioRenderer"),this.configProvider),t=e.id;this.clientAudioRenderers.set(t,e);const i=e.play.bind(e),n=e.stop.bind(e);return this.raiseTelemetryEvent("custom_audio_renderer_created",this.getSelectedDevices()),{play:i,stop:n,dispose:()=>{this.clientAudioRenderers.get(t)?.dispose(),this.clientAudioRenderers.delete(t)},setMuted:(t,i=be())=>e.setMuted(t,i),isMuted:()=>e.muted}}setAudioSharingRequested(e){this.audioSharingRequested=e}createDevicesHandle(e,t,i){const n=e.sharing?"ScreenShare":e.video?"Video":"Audio";return new Ok(this.logger.createChild("DevicesHandle"),this.getMediaStream({...e,...i&&{deviceId:i},withTimeout:!1,withEffect:!1,audioProcessingFlags:this.audioProcessingFlags,force:!1,withOverridenStream:this.customDeviceMediaStreamMap.get(n)?.active&&this.customDeviceMediaStreamMap.get(n)},t))}shareSystemSound(e){this.configProvider.config.postponeAudioMixerForAudioSharing&&(this.audioSharingRequested=e,this.event("onAudioSharingToggled").raise(e))}getAllowedModalities(){const e=tn(this.permissionManager.browserPermittedModalities);return this.hasDeviceType("microphone")||(e.audio=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive]),this.hasDeviceType("camera")||(e.video=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive]),e}getRawDeviceMediaStream(e,t){if("ScreenShare"!==e&&!this.hasDeviceType(this.getDeviceType(e)))throw new Error("NoInputDevice");this.audioSharingRequested=t;const i=this.getStreamHandlerByType(e);if(!i)return this.logger.safe.debug(`method not found for ${e}`),null;const n=this.rawDeviceStreamManager.createIRawStreamClient(i,e);return this.raiseTelemetryEvent("IRawStream_client_created",e),n}setRawMediaStream(e,t){if(!e)throw this.logger.error(`Could not set ${e} as to ${t}`),new Error("InvalidStream");this.customDeviceMediaStreamMap.set(t,e),this.onMediaStreamUpdateRequested(t),this.raiseTelemetryEvent("set_raw_outgoing_media_stream",t)}unsetRawMediaStream(e){this.customDeviceMediaStreamMap.get(e)?(this.customDeviceMediaStreamMap.delete(e),this.onMediaStreamUpdateRequested(e),this.raiseTelemetryEvent("unset_raw_outgoing_media_stream",e)):this.logger.safe.debug("no custom stream")}async setVideoEffects(e){return this.effectsManager.setEffectType("Video",e)}async sendMessageDeviceVideoEffectsAsync(e,t){return this.effectsManager.processingVideoEffectMessage(t)}async setAudioEffects(e){return this.effectsManager.setEffectType("Audio",e)}async getAudioStream(e,t,i=!1){const n=this.configProvider.config.devices.enumerateBeforeGettingStream;return n&&("always"!==n&&Dk.isPolling||await Dk.enumerateDevices()),this.getMediaStream({audio:!0,withTimeout:this.permissionManager.isPermissionKnown("microphone"),withEffect:!i&&this.effectsManager.isEffectEnabled("Audio"),audioProcessingFlags:this.getAudioProcessingFlags(),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Audio")?.active&&this.customDeviceMediaStreamMap.get("Audio")},t)}async getVideoStream(e,t,i=!1,n){const r=this.configProvider.config.devices.enumerateBeforeGettingStream;return r&&("always"!==r&&Dk.isPolling||await Dk.enumerateDevices()),this.getMediaStream({video:!0,withTimeout:this.permissionManager.isPermissionKnown("camera"),withEffect:!i&&this.configProvider.config.enableVideoEffects&&this.effectsManager.isEffectEnabled("Video"),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Video")?.active&&this.customDeviceMediaStreamMap.get("Video"),videoMaxFS:n},t)}getDisplayStream(e,t=!1){const i=!(!this.configProvider.config.enableAudioSharing||!this.audioSharingRequested);return this.getMediaStream({audio:i,sharing:!0,withTimeout:!1,withEffect:!1,audioProcessingFlags:i?0:void 0,force:!1,withOverridenStream:!t&&this.customDeviceMediaStreamMap.get("ScreenShare")?.active&&this.customDeviceMediaStreamMap.get("ScreenShare")},e)}async enumerateDevicesAsync(){return await this.isDeviceListAvailable.promise,this.getDeviceDescriptions(this.deviceList)}async getDeviceNameAsync(e){await this.isDeviceListAvailable.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.label??""}async getSpeakerDeviceDomIdAsync(e){await this.isDeviceListAvailable.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.deviceId??""}selectDevices(e){return this.pendingDevices?(this.logger.safe.info(`Overriding device selection until enumeration is complete with ${JSON.stringify(dm(this.pendingDevices))}`),void(this.pendingDevices=e)):this.isDeviceListAvailable.isPending?(this.logger.safe.info("Postponing device selection until enumeration is complete"),this.pendingDevices=e,void this.isDeviceListAvailable.promise.then((()=>{this.logger.safe.info("Performing postponed device selection");const e=this.pendingDevices;this.pendingDevices=null,this.selectDevices(e)}))):void this.deviceSelection.selectDevices(e)}getSelectedDevices(){return this.toSelectedDevices(this.deviceSelection.selectedDevices)}setAudioProcessingFlags(e){e!==this.audioProcessingFlags&&(this.logger.debug(`Setting audio processing flags: ${this.audioProcessingFlags} -> ${e}`),this.audioProcessingFlags=e,this.event("onStreamUpdateRequested").raise("Audio"))}getOutputDeviceId(){return this.selectedDevices.speaker?.deviceId}getDeviceDescriptions(e){return(e||this.deviceList).map((e=>e.toDeviceDesc()))}getDevicesCount(){return this.deviceList.reduce(((e,t)=>(e[t.type]++,e)),{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((e=>e.dispose())),this.deviceManagerSubscriptions=null,this.virtualDeviceSubs?.forEach((e=>e.forEach((e=>e.dispose())))),this.virtualDeviceSubs?.clear(),this.virtualDeviceSubs=null,this.virtualDeviceRecord?.forEach((e=>e.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(e,t){const i=e.length?e.map((({id:e},t)=>{const i=this.createChildDeviceManager(this.logger.createChild(`VirtualDevice-${t}`));return i.selectDevices({camera:e}),i})):[this.createChildDeviceManager(this.logger.createChild("VirtualDevice"))],n=new Fk(i,t),r=n.id,s=[n.on("onVideoEffectApplied",((...e)=>this.event("onVideoEffectApplied").raise(...e))),n.on("onVideoEffectsEvent",((...e)=>this.event("onVideoEffectsEvent").raise(...e))),n.on("onDeviceTelemetryEvent",((...e)=>this.event("onDeviceTelemetryEvent").raise(...e))),n.on("onVideoEffectsTelemetryEvent",((...e)=>this.event("onVideoEffectsTelemetryEvent").raise(...e))),n.on("onDevicesPermissionChanged",((...e)=>this.event("onDevicesPermissionChanged").raise(...e))),n.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))];return this.virtualDeviceSubs.set(r,s),this.virtualDeviceRecord.set(r,n),Dk.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.raiseTelemetryEvent("register_virtual_device",{deviceCount:i.length,id:r}),this.event("onVirtualDevicesChanged").raise(),r}async unregisterVirtualDevice(e){this.virtualDeviceRecord.has(e)?(this.virtualDeviceSubs.get(e).forEach((e=>e.dispose())),this.virtualDeviceSubs.delete(e),this.virtualDeviceRecord.get(e).dispose(),this.virtualDeviceRecord.delete(e),Dk.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.event("onVirtualDevicesChanged").raise(),this.raiseTelemetryEvent("unregister_virtual_device",{id:e})):this.logger.error(`No virtual device found with id ${e}`)}getRegisteredDevices(){return Array.from(this.virtualDeviceRecord.values())}async getNrgLevelPollerForDeviceTuner(){return await this.audioStreamAnalyzerWrapper.init(),this.audioStreamAnalyzerWrapper}getAudioProcessingFlags(){if(!this.effectsManager.shouldFallbackToNativeProcessing("Audio"))return this.audioProcessingFlags??this.configProvider.config.defaultAudioProcessingFlags;this.logger.safe.info("Applying netive audio processing flags")}disposeClientAudioRenderer(){this.clientAudioRenderers.size&&(this.clientAudioRenderers.forEach((e=>{e.dispose()})),this.clientAudioRenderers.clear(),this.raiseTelemetryEvent("custom_audio_renderer_disposed",this.getSelectedDevices()))}disposeRawStreamAccess(){this.rawDeviceStreamManager.disposeAll(),this.rawDeviceStreamManager=null}toSelectedDevices(e){return Object.entries(e).reduce(((e,[t,i])=>(i&&(e[t]=i.guid),e)),{})}getStreamConstraints(e){const t={deviceId:e?.deviceId||void 0};return this.configProvider.config.audioSampleRate&&(t.sampleRate=this.configProvider.config.audioSampleRate),t}hasDeviceType(e){return Zi(this.deviceList).some((t=>t.type===e))}getConstraints(e){if(!e.audio&&!e.video&&!e.sharing)throw new Error("requesting nothing");if(this.logger.safe.info(`retrieving media stream: ${JSON.stringify(e)}`),e.sharing){let t;const i=this.selectedDevices.audioIngestDevice;return t=i&&e.deviceId?{deviceId:i.deviceId}:e.audio&&!e.deviceId?{deviceId:Gi.SYSTEM_AUDIO_SOURCE_ID}:void 0,{audio:t,sharing:{deviceId:e.deviceId||Gi.DISPLAY_SOURCE_ID},withTimeout:e.withTimeout,withEffect:!1,audioProcessingFlags:e.audioProcessingFlags,force:!1,withOverridenStream:e.withOverridenStream}}const t=this.selectedDevices.microphone,i=this.selectedDevices.camera,n=e.audio&&t,r=e.video&&i;if(!n&&!r)throw{type:Gi.MEDIA_ERROR.noDeviceSelected,detail:`audio requested ${e.audio}, video requested: ${e.video} Devices: ${JSON.stringify(this.deviceList.map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords)))))}`};const s=this.getStreamConstraints(t),a=this.getStreamConstraints(i);let o=e.audioProcessingFlags;return void 0!==o&&e.audio&&!e.video&&t?.capabilities&&(t.capabilities.echoCancellation&&!t.capabilities.echoCancellation.includes(!!(2&o))&&(o^=2),t.capabilities.autoGainControl&&!t.capabilities.autoGainControl.includes(!!(1&o))&&(o^=1),t.capabilities.noiseSuppression&&!t.capabilities.noiseSuppression.includes(!!(4&o))&&(o^=4)),o!==e.audioProcessingFlags&&this.logger.safe.warn(`Unable to fulfill processing flags ${e.audioProcessingFlags}, using ${o} instead`),{audio:e.audio?s:void 0,video:e.video?a:void 0,withTimeout:e.withTimeout,withEffect:e.withEffect,audioProcessingFlags:o,force:e.force,withOverridenStream:e.withOverridenStream,videoMaxFS:e.videoMaxFS}}getMediaStream(e,t){const i=this.getConstraints(e),n=this.mediaStreamManager.getMediaStream(i,t);return this.subscribeOnStreamEvents(n),n.start().then((()=>{const i=n.hasAudio(),r=n.hasVideo();i&&(this.signalDeviceGood("Audio",n.rawTrack.muted),this.audioStreamAnalyzerWrapper.setStream(n,t)),r&&this.signalDeviceGood(n.mediaType,n.rawTrack.muted),this.permissionManager.update(e,e)})).catch((t=>this.handleUserMediaError(e,t))),n}signalDeviceGood(e,t){this.ufdManager.signalDeviceEvent(0,"Good",e,this.id),this.ufdManager.signalDeviceEvent(2,"Good",e,this.id),this.ufdManager.signalDeviceEvent(4,"Good",e,this.id),t||"Audio"!==e&&!this.configProvider.config.raiseVideoMuteUfd||this.ufdManager.signalDeviceEvent(3,"Good",e,this.id)}handleUserMediaError(e,t){const i=this.getMediaType(e),n=e.audio&&e.video,r=(e,t)=>{!n&&this.ufdManager.signalDeviceEvent(e,t,i,this.id)},s=e=>{!n&&"Audio"===i&&this.diagnostics.registerAudioRenderError(e)};switch(t.type){case Gi.MEDIA_ERROR.permissionDeniedError:"ScreenShare"!==i&&(r(4,"Bad"),s(0x800000000000),this.configProvider.config.permissions.persistOnDeniedError&&this.refreshPermissions(e));break;case Gi.MEDIA_ERROR.permissionDeniedBySystemError:r(4,"Bad"),s(0x800000000000);break;case Gi.MEDIA_ERROR.sourceUnavailableError:r(0,"Bad"),s(512);break;case Gi.MEDIA_ERROR.mediaStreamRequestTimedOut:r(2,"Bad"),s(35184372088832);break;default:this.logger.safe.error(`getMediaStream() error: ${tt(t)}`),r(0,"Bad"),s(4194304)}}refreshPermissions(e){const t=e.audio&&!e.video,i=!e.audio&&e.video;t?this.permissionManager.update({audio:!0},{audio:!1}):i&&this.permissionManager.update({video:!0},{video:!1})}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`mediaType is not defined for this constraint ${JSON.stringify(e)}`)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamClientStarted",((e,t)=>this.onStreamStarted(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),t.push(e.on("onStreamClientEnded",((e,t)=>this.onStreamEnded(e,t)))),t.push(e.on("onStreamClientMuted",((e,t)=>this.onStreamMuted(e,t)))),t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),this.configProvider.config.useRawMediaApiForVideoEffects&&t.push(e.on("onStreamClientDisposed",(e=>this.removeVideoEffectStream(e)))),this.streamSubscriptions.set(e,t)}async removeVideoEffectStream(e){if(e.getCurrentConstraints().withEffect){this.logger.safe.info(`this.activeVideoEffectSub: ${this.activeVideoEffectSub} to be disposed`),this.activeVideoEffectSub?.dispose();const e=await(this.activeVideoStreamForEffect?.getMediaStream());this.effectsManager.stopEffect("Video",e)}}unsubscribeFromStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}subscribeOnRendererEvents(e){const t=[];t.push(e.on("onRendererDisposed",(e=>this.onRendererDisposed(e)))),t.push(e.on("onRendererStarted",(e=>this.onRendererStarted(e)))),this.rendererSubscriptions.set(e,t)}unsubscribeFromRendererEvents(e){this.rendererSubscriptions.has(e)&&(this.rendererSubscriptions.get(e).forEach((e=>e.dispose())),this.rendererSubscriptions.delete(e))}subscribeOnStreamManagerEvents(){this.streamManagerSubscriptions=[],this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onAllStreamsRemoved",(()=>this.onAllStreamsRemoved()))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamAcquired",(e=>this.onStreamAcquired(e)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamCreated",((e,t)=>this.onStreamCreated(e,t)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamDisposing",((e,t)=>this.onMasterStreamDisposing(e,t))))}subscribeOnDeviceEnumeratorEvents(){this.deviceEnumerator.on("onDeviceEnumerationfailed",(e=>this.raiseTelemetryEvent("enumeration_failed",{error:e})))}unsubscribeFromStreamManagerEvents(){this.streamManagerSubscriptions.forEach((e=>e.dispose()))}async updateRenderersAsync(){try{await Promise.all(this.activeRenderers.map((e=>e.updateStreamAsync()))),this.logger.safe.info("Renderers updates finished")}catch(e){this.logger.safe.error(`Error updating renderers: ${tt(e)}`)}}onSelectedDevicesChanged(e,t){const i=this.selectedDevices;if(this.selectedDevices=e,this.diagnostics.setSelectedDevices(e,t),!("camera"in i^"camera"in this.selectedDevices||"microphone"in i^"microphone"in this.selectedDevices)){const e=this.toSelectedDevices(this.selectedDevices),t=this.toSelectedDevices(i);this.event("onSelectedDevicesChanged").raise(e,t),e.microphone!==t.microphone&&(this.rawDeviceStreamManager.notifyChange("Audio"),this.audioStreamAnalyzerWrapper.updateStreamAfterDeviceChange()),e.camera!==t.camera&&this.rawDeviceStreamManager.notifyChange("Video"),this.clientAudioRenderers.forEach((e=>{e.setOutputDevice(this.getOutputDeviceId())}))}const n=this.configProvider.config.devices.piiSafeWords;this.raiseTelemetryEvent("selected_devices_changed",{microphone:this.selectedDevices.microphone&&fn(this.selectedDevices.microphone.label,n),camera:this.selectedDevices.camera&&fn(this.selectedDevices.camera.label,n),speaker:this.selectedDevices.speaker&&fn(this.selectedDevices.speaker.label,n),fromInterface:t}),this.updateRenderersAsync()}onDevicesChanged(e,t){this.event("onDevicesChanged").raise(e,t),this.mediaStreamManager.onDevicesChanged(e),this.diagnostics.setDeviceList(e,t,this.getDeviceListDebugInfo());const i=this.getDevicesCount(),n=i.microphone>0,r=i.speaker>0;this.ufdManager.signalEvent("ZeroCaptureDevicesEnumerated",n?"Good":"Bad"),n||this.diagnostics.registerAudioCaptureError(1),this.isAudioOutputSelectionSupported&&(this.ufdManager.signalEvent("ZeroRenderDevicesEnumerated",r?"Good":"Bad"),r||this.diagnostics.registerAudioRenderError(1));const s=new Map;let a=1;this.raiseTelemetryEvent("devices_changed",{devices:e.map((e=>{const t=s.get(e.groupId)||a++;return s.set(e.groupId,t),{label:fn(e.label,this.configProvider.config.devices.piiSafeWords),isSystemDefault:e.isSystemDefault,kind:e.kind,type:e.type,capabilities:e.capabilities,groupId:`${t}`}})),debug:this.getDeviceListDebugInfo()})}getDeviceListDebugInfo(){return Dk.list.debugInfo}raiseTelemetryEvent(e,t){this.logger.safe.info(`Device event: ${e}: ${JSON.stringify(this.scrubPayload(e,t))}`);const i={eventType:e,timestamp:Date.now(),payload:t};this.diagnostics.registerDeviceTelemetryEvent(nn(i)),this.diagnostics.logAudioDeviceError(e,t),this.event("onDeviceTelemetryEvent").raise(i)}scrubPayload(e,t){return"devices_changed"===e?{devices:Zi(t.devices).map((e=>um(e,this.configProvider.config.devices.piiSafeWords))),debug:t.debug}:t}async onStreamStarted(e,t){if(this.permissionManager.browserPermittedModalities.audio.some((e=>e===Gi.MEDIA_STATE.send))||this.permissionManager.browserPermittedModalities.video.some((e=>e===Gi.MEDIA_STATE.send)))try{await Dk.enumerateDevices()}catch(e){this.logger.safe.warn(`onStreamStarted device enumeration failed: ${tt(e)}`)}if(e.rawTrack){switch(e.mediaType){case"Audio":this.deviceEnumerator.startDevicePolling(),this.updateActiveMicrophone(e,t);break;case"Video":this.deviceEnumerator.startDevicePolling()}this.configProvider.config.useRawMediaApiForVideoEffects&&e.getCurrentConstraints().withEffect&&(this.activeVideoEffectSub=this.effectsManager.on("onVideoStreamQualityChanged",((t,i,n)=>e.onVideoStreamQualityChanged(t,i,n))))}else this.logger.safe.warn(`stream:${e.id} is already disposed`)}updateActiveMicrophone(e,t){if(e.deviceId){const i=this.deviceList.find((t=>t.deviceId===e.deviceId));if(!i&&"default"!==e.deviceId)return void this.logger.safe.error("Active device not found",`Device id from track: '${De(e.deviceId)}', known devices: [${this.deviceList.map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))))}]}`,JSON.stringify(hm(t)));i&&"default"!==e.deviceId&&t.audio&&t.audio.deviceId===Gi.MEDIA_DEVICE.defaultId&&Dk.list.updateActiveMicrophone(i)}}onStreamDisposing(e){this.unsubscribeFromStreamEvents(e)}onStreamMuted(e,t){("Audio"===e.mediaType||this.configProvider.config.raiseVideoMuteUfd)&&this.ufdManager.signalDeviceEvent(3,t?"Bad":"Good",e.mediaType,this.id),"Audio"===e.mediaType&&this.event("onAudioStreamMuted").raise(t),this.raiseTelemetryEvent(t?"stream_muted":"stream_unmuted",e.mediaType)}onStreamEnded(e,t){t.error?(this.raiseTelemetryEvent("stream_ended_error",{mediaType:e.mediaType,error:{type:t.error.name,detail:t.error.message}}),"SourceUnavailableError"===t.error.name&&this.ufdManager.signalDeviceEvent(0,"Bad","Audio",this.id)):("Audio"!==e.mediaType&&"Video"!==e.mediaType||this.ufdManager.signalDeviceEvent(0,"Bad",e.mediaType,this.id),this.raiseTelemetryEvent("stream_ended",e.mediaType))}onStreamError(e,t){this.raiseTelemetryEvent("stream_error",{mediaType:e.mediaType,error:t})}onAllStreamsRemoved(){this.deviceEnumerator.stopDevicePolling(),this.audioSharingRequested=!1}onStreamAcquired({id:e,mediaType:t,timestamp:i,resolution:n,withAudio:r,source:s,sampleRate:a}){0!==i&&this.raiseTelemetryEvent("stream_acquired",{id:e,mediaType:t,timestamp:i,resolution:n,withAudio:r,source:s,sampleRate:a})}onStreamCreated(e,t){this.raiseTelemetryEvent("stream_created",{id:e,mediaType:t})}onMasterStreamDisposing(e,t){this.raiseTelemetryEvent("stream_disposed",{id:e,mediaType:t})}onRendererDisposed(e){Qi(this.activeRenderers,(t=>t===e)),this.domOverrides.onMediaElementRemoved?.(e.getVideoElement()),this.unsubscribeFromRendererEvents(e)}onRendererStarted(e){this.activeRenderers.push(e),this.event("onLocalRendererStarted").raise(e)}onVideoEffectsQualityEventHandler(e){const t=this.deviceSelection.selectedDevices.camera;if(t?.deviceId){const i={type:"onVideoEffectQualityChanged",payload:{message:e.message,effectType:e.effectType}};this.event("onVideoEffectsEvent").raise(t.deviceId,i)}}getDeviceType(e){if("Video"===e)return"camera";if("Audio"===e)return"microphone";throw new Error(`DeviceType for mediaType: ${e} doesn't exist`)}getStreamHandlerByType(e){return"Video"===e?()=>this.getVideoStream(!1,"rawStream",!0):"Audio"===e?()=>this.getAudioStream(!1,"rawStream",!0):"ScreenShare"===e?()=>Promise.resolve(this.getDisplayStream("rawStream",!0)):null}},Jk=Z,Yk=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:Gi.ALLOWED_CONTENT_TYPES.SDP_NGC,webrtcMediaContentType:Gi.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:[Gi.MEDIA_ERROR.iceConnectionError,Gi.MEDIA_ERROR.noNetworkError,Gi.MEDIA_ERROR.srtpError,Gi.MEDIA_ERROR.incompatibleOffer,Gi.MEDIA_ERROR.internalError].join(","),forceReconnectErrors:[Gi.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,webrtcSendBandwidthAlwaysReportAfterDrop:!1,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:Ww.Normal,eventLatencyRealTime:Ww.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,useRawMediaApiForVideoEffects:!1,waitForVideoEffectStreamStart:!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,asyncInitialization:!1,initializationTimeoutMs:1e4,backgroundMode:!1,performanceThresholdMs:8,performanceWindowDurationSecs:10,defaultVqeMode:Sh.VqeMode.Off,callType:Sh.CallType.Conference,audioUsageMode:Sh.AudioUsageMode.Default,performanceProfile:Sh.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:vh.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:vh.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,enabledStatsProcessors:{dataChannel:!0,transport:!0,audio:!0,video:!0,sharing:!0,bandwidth:!0,recvVideoStreamsCounter:!0,aggregated:!0,multiview:!0,simulcast:!0,networkInfo:!0,macroblockRate:!0},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:!0,useNewSendBandwidthCalculation:!0,useNewStatsForLocalVideoStreamWatcher:!0,useFallbackToNewExtensions:!0,logContributingSourcesError:!0,useTwoSampleVBSSFreezeDetection:!0,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:Gi.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:Gi.RES_TABLE.SEND,recvResolutionTableOverride:Gi.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,enabledViaApi:!1,maxParticipantNumber:20,debounceTime:1e3,list:{},remoteUFDHandlerV2:!0,maxNumberOfBadUFDsForThrottling:3,throttlingTimeInterval:6e4,disableInterval:6e4,bundlingInterval:6e3,maxNumberOfBundles:4,bundlingWindowInterval:6e4},fixOpusComfortNoise:!0,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,fixExtraNegotiation:!1}}getEnforcedSettings(){return{}}},Qk=class extends Yk{getInitialSettings(){const e=super.getInitialSettings();return e.oneStreamPerDeviceType=!0,e.removeUnsupportedVideoModality=!0,e.webrtcPranswerWaitForMediaPollingInterval=100,e.diagnostics.features.useLastSampleDeltaPerSecondConverter=!0,Ot.isFormFactor("Mobile")&&(e.webrtcCameraOpenFs=920,e.webrtcVideoCapabilityMaxFS=920),e}},Zk=class extends Yk{getEnforcedSettings(){return{useAudioAnalyzer:!1,enableAudioSharing:!1}}},Xk=class extends Qk{getEnforcedSettings(){const e={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 Ot.isVersionGreaterOrEqual("15.0")||(e.statsAllowAnyVideoSendTrack=!0),Ot.isVersionGreaterOrEqual("16.0")&&Ot.isFormFactor("Mobile")&&(e.enablePermissionsWorkaround=!0),Ot.isVersionGreaterOrEqual("17.0")&&Ot.isFormFactor("Mobile")&&(e.recoverOnStreamUnmute=!0,e.enablePlayVideoOnStreamUnmuteWorkaround=!0),e}},eO=class extends Qk{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}}},tO=class extends Yk{getEnforcedSettings(){const e={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"}],setMinFpsForWebkit:!0};return"43"===Pp()?(0,Jk.mergeWith)(e,{postponeAudioMixerForAudioSharing:!0,enableAudioSharing:!0,filterCodecsInSdp:!0,webrtcPranswerWaitForMediaPollingInterval:250,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!1}},localPreviewMirroringSupported:!0,webrtcContributingSourcesPollingStartDelay:3e3,devices:{setSinkImmediately:!1}}):"44"===Pp()?(0,Jk.mergeWith)(e,{postponeAudioMixerForAudioSharing:!0,enableAudioSharing:!0,disposeSendersSync:!0,disposeStreamsSync:!0,filterCodecsInSdp:!0,useInactiveAudioTrack:!0,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!0,minFsForSimulcast:[920]}},webrtcPranswerWaitForMediaPollingInterval:250,webrtcContributingSourcesPollingStartDelay:5e3}):"45"===Pp()?(0,Jk.mergeWith)(e,{setParametersMaxBitrateUndefined:!0,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!0,minFsForSimulcast:[920]}}}):e}},iO=class extends Qk{getEnforcedSettings(){const e={};return Ot.isVersionGreaterOrEqual("74.0")&&(e.webrtcSimulcastSessionEnabled=!0,e.webrtcAllowRestoreKeyframe=!0,e.enableAudioSharing=!0),Ot.isVersionGreaterOrEqual("122.0")&&(e.useKeyFrameApi=!0),Ot.isFormFactor("RoomAudioProcessing")&&(e.defaultAudioProcessingFlags=0,e.wasmvqe={enableAec:!1,enableVqe:!1,backgroundMode:!1},e.wasmdns={enableNoiseSuppression:!1,backgroundMode:!1}),(Ot.isBrowser("CiscoOS")||Ot.isBrowser("ZoomRoom"))&&(e.waitReportStatsAtCallStop=!0,e.setDisconnectAfterCleanUp=!0),Ot.isFormFactor("Mobile")&&(e.enableAudioSharing=!1,e.audioRendererFailedReconnectTimes=3,e.devices={pollingIntervalIdle:1e4}),Ot.isBrowser("SamsungTV")&&(e.useSetParametersToApplyCapabilities=!0),Ot.isVersionGreaterOrEqual("98.0")&&Ot.isFormFactor("Desktop")&&(e.specCompliantSimulcastMultiparty={video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!0,minFsForSimulcast:[920]},maxBrControlEnabled:!0,allowResLimit:!0,disableTilde:!1},e.extmapAllowMixedMultiparty=!0,e.enableVlaMultiparty=!0,e.allowRemoteVlaMultiparty=!0,e.enableNonAdvVlaMultiparty=!0,e.useMediaQualityControllerMultiparty=!0),Ot.isVersionGreaterOrEqual("100.0")&&(e.redReceiveEnabledMultiparty=!0),e.webcv={useWasmEffects:!0,processorType:vh.ProcessorType.Wasm},e}},nO=class{constructor(e){this.settings=e,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(e,t){this.maxBandwidthInKbps=Math.floor((e.maxBandwidthInBps||0)/1e3),this.isTransportUnbundled=this.settings.forceUnbundledTransport||this.settings.enableQosSupport&&(e.enableMediaQoS||!!e.mediaPortRanges),this._mediaPortRanges=e.mediaPortRanges,this.simulcastSessionEnabled=this.settings.webrtcSimulcastSessionEnabled&&pm(this.settings.checkSupportForWebrtc_1_0),this._noiseSuppressionMode=e.noiseSuppressionMode||"Auto",this._enableMediaBypass=this.settings.allowMediaBypass&&e.enableMediaBypass,this.webrtcRejectedFeatures=this._enableMediaBypass?"":this.settings.webrtcRejectedFeatures,this.webrtcRequiredFeatures=this._enableMediaBypass?"":this.settings.webrtcRequiredFeatures,this.spatialAudioEnabled=t?t.spatialAudioEnabled:e.enableSpatialAudio}get mediaBypassEnabled(){return this._enableMediaBypass}get noiseSuppressionMode(){return this._noiseSuppressionMode}get maxBandwidthInKbps(){return this._maxBandwidthInKbps}set maxBandwidthInKbps(e){this._maxBandwidthInKbps=e,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}},rO=class extends Vi{constructor(e,t,i={}){super(e),this.logger=e,this.platformCallConstraintsProvider=t,this.platformConfig=Ot.isEngine("ChromiumAVD")?new Zk:Ot.isEngine("Safari")?new Xk:Ot.isEngine("Firefox")?new eO:Ap()?new tO:Ot.isEngine("Chromium")?new iO:new Yk,this.sessionCount=0,this._consoleOverrides={},this.uaConfig=new Vp(this),this.mediaConfiguration={},this.configReceivedDefer=new Kt,this.logger.info(`initializing configProvider ${this.constructor.name} from BrowserInfo: ${Ot.toString()}`),this.initialSettings=(0,av.mergeWith)({},(0,av.cloneDeep)(this.platformConfig.getInitialSettings()),(0,av.cloneDeep)(i),this.platformConfig.getEnforcedSettings(),xm),this.settings=this.initialSettings,this.settingsWithoutOverrides=this.initialSettings,this.stackSettings=(0,av.cloneDeep)(i),this.mediaSettings=new nO(this.settings),this.platformCallConstraintsProvider.changed((()=>{this.updateSettings();const e=this.platformCallConstraintsProvider.constraints,t=this.logger.createChild("SettingsToCallConstraintsConverter"),i=Am(t,this.settings,e);this.platformCallConstraintsProvider.addCallConstraintsTelemetryEvent(i,"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(e){return this.platformCallConstraintsProvider.setConstraints(e),e}getCallConstraintsTelemetry(){return this.logger.error("Not supported globally, returning empty array"),[]}addCallConstraintsTelemetryEvent(e,t){this.logger.error("Not supported globally")}overrideMaxSessionBandwidth(e){return this.logger.error("Not supported globally"),!1}getIceTransportPolicy(){return this.logger.warn(`Not supported globally, returning default ${Gi.ICE_TRANSPORT_POLICY.all}`),Gi.ICE_TRANSPORT_POLICY.all}setIceTransportPolicy(e){this.logger.error("Not supported globally")}getConfigReceivedOrTimeout(){return this.configReceivedDefer.promise}getConfigView(e,t){const i=e?"Multiparty":"1on1",n=Object.entries((0,av.cloneDeep)(this.settings)).reduce(((e,[t,n])=>(e[t]=n,t.endsWith(i)&&(e[t.replace(i,"")]=n),e)),{}),r=new nO(n);return r.setMediaConfiguration(this.mediaConfiguration,t?.mediaConfig),new Um(this.logger.createChild("ConfigProviderView"),n,r,this.userAgentConfig,this.countryCode,this.platformCallConstraintsProvider,t?.getCallConstraints())}updateConfig(e,t,i,n){this.etag=t||this.etag,this.configIds=i||this.configIds,this.country=n||this.country,this.event("newConfigReceived").raise(e,t,i),this.settingsWithoutOverrides=(0,av.mergeWith)({},this.settingsWithoutOverrides,e,xm),this.updateSettings(),this.configReceivedTimeout&&(window.clearTimeout(this.configReceivedTimeout),this.configReceivedTimeout=void 0),this.configReceivedDefer.resolve()}updateSessionCount(e){this.sessionCount=e,0===e&&this.pendingSettings&&(this.logSettings("Applying pending configuration",this.pendingSettings),this.updateSettings(this.pendingSettings),this.pendingSettings=null),e>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(e){this.mediaConfiguration=e,this.mediaSettings.setMediaConfiguration(e)}get mediaConfig(){return this.mediaSettings}get ETag(){return this.etag}get ecsConfigIds(){return this.configIds}setConsoleOverrides(e){this._consoleOverrides=(0,av.mergeWith)({},this._consoleOverrides,e,xm),this.updateSettings()}setConsoleOverride(e,t){this._consoleOverrides[e]=t,this.updateSettings()}clearConsoleOverride(e){delete this._consoleOverrides[e],this.updateSettings()}clearAllConsoleOverrides(){this._consoleOverrides={},this.updateSettings()}updateSettings(e=this.settingsWithoutOverrides){if(this.sessionCount>0)return this.pendingSettings=e,void this.logSettings("pendingSettings updated",e);this.settings=this.mergeSettings(e),this.event("configUpdated").raise(),this.logSettings("Settings updated",this.settings)}logSettings(e,t){const i=Object.entries(t).reduce(((e,[t,i])=>(i!==this.initialSettings[t]&&(e[t]=i),e)),{});this.logger.safe.info(`${e}: ${JSON.stringify(i)}`)}mergeSettings(e){if(!e.enablePlatformCallConstraints&&!this._consoleOverrides.enablePlatformCallConstraints)return this.mergeSettingsWithConsoleOverrides(e);let t=e;const{setConsoleOverridesBeforeCallConstraints:i}=this._consoleOverrides;return i&&(t=this.mergeSettingsWithConsoleOverrides(t)),t=this.mergeSettingsWithPlatformConstraints(t),i||(t=this.mergeSettingsWithConsoleOverrides(t)),t}mergeSettingsWithConsoleOverrides(e){return this.logger.safe.info(`Merging settings with console overrides: ${tt(this._consoleOverrides)}`),(0,av.mergeWith)({},e,this._consoleOverrides,xm)}mergeSettingsWithPlatformConstraints(e){const t=this.platformCallConstraintsProvider.getSettings(e);return this.logger.safe.info(`Merging settings with platform call constraints: ${tt(t)}`),(0,av.assign)({},e,t,xm)}},sO=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(e){this.data.activeStrategy=e}resetState(){return this.data.lastMsgOrigin=void 0,this}recordHistoryEvent(e,t){var i,n;this.data.changedCountDSH++,(i=this.data)[n=t+"DSH"]??(i[n]={count:0,duplicateCount:0}),this.data.lastMsgOrigin=t;const r=this.data[t+"DSH"];r.count++,r.firstMsgTime??(r.firstMsgTime=Date.now()),an(this.data.lastHistory,e)&&r.duplicateCount++,this.data.lastHistory=e,this.data.lastMsgDate=Date.now()}getObjectRef(){return this.data}},aO=class{constructor(e,t,i,n,r,s,a,o){this.mediaStream=e,this.receiver=t,this.modality=i,this.sourceStreamId=n,this.controller=r,this.videoCapabilities=s,this.getMaxAllowedVideoFS=a,this.substreamIndex=o,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(e){this.msi=e;const t=this.operations.then((()=>{let t;return this.videoCapabilities&&(this.videoCapabilities.resetToInitial(),this.getMaxAllowedVideoFS&&this.videoCapabilities.setMaxFS(Math.min(this.getMaxAllowedVideoFS(),this.videoCapabilities.getMaxFS())),t=this.videoCapabilities.buildFmtp(),this.videoCapabilities.resetToInitial()),this.controller.requestSource(this.mediaStream.id,e,t)}));return this.operations=t.catch((()=>{})),t}},oO=class{constructor(e){this.subscription=e}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(e){this.checkDisposed(),this.mediaStreamChanged=e,this.subscription.isStreamReady&&this.notifyMediaStreamChanged()}setOnErrorHandler(e){this.checkDisposed(),this.error=e}dispose(){this.subscription&&(this.subscription.dispose(be(),this),this.subscription=null)}unsubscribe(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null)}notifyMediaStreamChanged(){if(this.mediaStreamChanged){const e=this.subscription.stream,t=this.subscription.isStreamReady;this.mediaStreamChanged(e&&t?e.getMediaStream():null)}}notifyError(e){this.error&&this.error(e)}checkDisposed(){if(!this.subscription)throw new Error("subscription disposed")}},lO=class extends Vi{constructor(e,t,i){super(),this.modality=e,this.msi=t,this.disposeDelay=i,this.clients=[],this.streamReady=!1}createClient(){const e=new oO(this);return this.clients.push(e),e}get isStreamReady(){return this.streamReady}get localMsi(){return this.subStream?.getSourceStreamId()}get isInactive(){return!this.clients.length}get stream(){return this.subStream}set stream(e){try{if(e===this.subStream)return;this.subStream&&(this.unsubscribe(!1),this.notifyStreamChanged()),this.subStream=e,e&&(this.streamReady=!1,e.requestSource(this.msi).then((()=>{this.streamReady=!0,this.notifyStreamChanged()})).catch((e=>{this.notifyError(e)})))}catch(e){this.event("onFailed").raise(this,e)}}notifyError(e){this.clients.forEach((t=>{t.notifyError(e)})),this.event("onFailed").raise(this,e)}dispose(e,t){t?(Qi(this.clients,(e=>e===t)),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(e=!0){this.subStream&&(this.subStream.requestSource(-1).catch((()=>{})),this.streamReady=!1,this.subStream=null),e&&this.event("onDisposed").raise(this)}notifyStreamChanged(){this.clients.forEach((e=>e.notifyMediaStreamChanged())),this.event("onStreamChanged").raise()}},cO=class extends Vi{constructor(e,t,i,n){super(e),this.configProvider=t,this.diagnostics=n,this.videoSubscriptions=[],this.isMcpSrAvailable=!1,this.subscriptionEvents=new Map,this.setLogger(e),this.diagnostics??(this.diagnostics=new dO(this.configProvider,(()=>{}))),this.setStreamProvider(i),this.logger.safe.info("created")}getSubscriptionsCount(){return this.videoSubscriptions.filter((e=>e.isStreamReady)).length}setStreamProvider(e){this.streamProvider=e,this.streamProvider.setOnStreamsChangedHandler((()=>this.streamsChanged()))}setLogger(e){this.logger=e}subscribeVideo(e,t=-2){let i=this.videoSubscriptions.find((i=>i.msi===t&&i.modality===e)),n=this.getAvailableStream(e);if(i)!i.stream&&n?this.assignStream(i,n):this.logger.safe.info(`subscription #${t} for modality ${e} already exists, stream assigned: ${!!i.stream}`);else{const r=Date.now();this.disposeInactiveSubscriptionIfNeeded(e),n=this.getAvailableStream(e);const s=n?.getSourceStreamId();this.logger.safe.info(`creating new subscription #${t} for modality ${e}`),this.event("onSubscriptionChanged").raise(1,e,t,s,null),this.diagnostics.addSubscribe(e,t,s),i=new lO(e,t,this.configProvider.config.webrtcVideoSubscriptionDisposeTimeout);const a=[];a.push(i.on("onDisposed",(e=>this.onSubscriptionDisposed(e)))),a.push(i.on("onStreamChanged",(()=>{const n=i.stream?.getId(),s=i.localMsi;if(this.updateTrackIds(),i.isStreamReady){const i=Date.now();this.event("onSubscriptionChanged").raise(2,e,t,s,i-r,n),this.diagnostics.addSubscribed(e,t,s,i-r)}}))),a.push(i.on("onFailed",((e,t)=>this.onSubscriptionFailed(e,t)))),this.subscriptionEvents.set(i,a),this.videoSubscriptions.push(i),n?this.assignStream(i,n):this.logger.safe.info(`waiting for available stream for subscription #${t}`)}return i.createClient()}dispose(){const e=be();this.videoSubscriptions.concat().forEach((t=>t.dispose(e))),this.streamProvider.setOnStreamsChangedHandler(null),super.dispose(),this.logger.safe.info("disposed")}reriseSubscribeEvents(){this.logger.safe.info(`rerising subscription events: ${this.videoSubscriptions.length}`);const e=[];this.videoSubscriptions.forEach((t=>{const i=t.modality,n=t.msi,r=t.localMsi;this.event("onSubscriptionChanged").raise(1,i,n,r),this.diagnostics.addSubscribe(i,n,r),e.push(...this.getSubscriptionVideoTrackIds(t))})),this.diagnostics.subscribedTrackIds=e}setDiagnostics(e){this.diagnostics=e??new dO(this.configProvider,(e=>{this.logger.safe.warn(`Unhandled stats error from inactive subscription manager: ${e}`)}))}streamChangedByMsi(e){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`);const t=this.videoSubscriptions.find((t=>t.msi===e));t?this.assignSubscriptionToStream(t):this.logger.safe.error(`Subscription for msi ${e} not found`)}mcpSourceRequestsAvailable(){this.isMcpSrAvailable=!0}streamsChanged(){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`),this.videoSubscriptions.forEach((e=>{this.assignSubscriptionToStream(e)}))}assignSubscriptionToStream(e){const t=!e.stream||this.isStreamRemoved(e.stream);if(this.logger.safe.info(`Subscription for ${e.modality} #${e.msi} needs new stream: ${t}`),!t)return;const i=this.getAvailableStream(e.modality);i?this.assignStream(e,i):this.resignStream(e)}getAvailableStream(e){let t=this.streamProvider.getStreams();return"video"===e&&!this.isMcpSrAvailable&&this.configProvider.config.multiStreamSupported&&(t=t.filter((e=>void 0===e.getSubstreamIndex()))),t.find((t=>e===t.getModality()&&-1===t.getMsi()))}isStreamRemoved(e){return!this.streamProvider.getStreams().some((t=>t===e))}assignStream(e,t){this.logger.safe.info(`assigning stream #${t.getId()} to subscription #${e.msi}`),e.stream=t}resignStream(e){if(e.stream)this.logger.safe.info(`removing stream from subscription #${e.msi}`),e.stream=null;else{const t=this.streamProvider.getStreams().filter((t=>e.modality===t.getModality()&&-1!==t.getMsi())).length;this.logger.safe.warn(`no stream available for ${e.modality} #${e.msi}, ${e.modality} used stream count: ${t}`)}}disposeInactiveSubscriptionIfNeeded(e){this.getAvailableStream(e)||this.videoSubscriptions.find((t=>t.modality===e&&t.isInactive))?.unsubscribeIfInactive()}onSubscriptionDisposed(e){const t=be(),i=e.modality,n=e.msi,r=e.localMsi;this.event("onSubscriptionChanged").raise(3,i,n,r),this.diagnostics.addUnsubscribe(i,n,r),this.logger.safe.info(`disposing subscription for ${i} #${n}`),Qi(this.videoSubscriptions,(t=>t===e)),this.streamsChanged(),this.updateTrackIds(),this.subscriptionEvents.has(e)&&(this.subscriptionEvents.get(e).forEach((e=>e.dispose(t))),this.subscriptionEvents.delete(e))}updateTrackIds(){const e=[],t=[];this.videoSubscriptions.forEach((i=>{if(!i.isStreamReady)return;const n=i.stream?.getId().split("-")[1];t.push(n),e.push(...this.getSubscriptionVideoTrackIds(i))})),this.event("onTrackIdsChanged").raise(e),this.diagnostics.subscribedTrackIds=e,this.configProvider.config.subscribeToSsrcForVideo&&this.event("onTrackSsrcChanged").raise(t)}getSubscriptionVideoTrackIds(e){return e?.stream?.getMediaStream()?.getVideoTracks().map((e=>e.id))??[]}onSubscriptionFailed(e,t){this.event("onSubscriptionFailed").raise(-1,e.modality,e.msi,e.localMsi,t),this.diagnostics.addFailed(e.modality,e.msi,e.localMsi,tt(t))}},dO=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,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(e){this.data.subscribedTrackIds=e}addSubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:1,msi:t,localMsi:i,ts:Date.now()};Sn(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.attempted++}}addSubscribed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:2,msi:t,localMsi:i,ts:Date.now(),duration:n};Sn(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.subscribed++}}addUnsubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:3,msi:t,localMsi:i,ts:Date.now()};Sn(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.unsubscribed++}}addFailed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:-1,msi:t,localMsi:i,ts:Date.now(),error:n};Sn(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.failed++}}getObjectRef(){return this.data}getModalityData(e){switch(e){case Gi.MEDIA_TYPE.video:return this.data.video;case Gi.MEDIA_TYPE.sharing:return this.data.sharing;default:return void this.addStatsError(`Unsupported modality ${e}`)}}},uO=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,this.data={videoMaxCapabilitiesEvents:[],videoMaxCapabilitiesErrors:[],sharingMaxCapabilitiesEvents:[],sharingMaxCapabilitiesErrors:[],currentVideoSsrcRequestedCapabilities:{},currentVideoSsrcAppliedCapabilities:{},currentSharingSsrcRequestedCapabilities:{},currentSharingSsrcAppliedCapabilities:{},numVideoControlMessages:0,numOutOfOrderVideoControlMessages:0,numWebcamFreezeIntervals:0,numProcessedStreamFreezeIntervals:0}}onMaxCapabilitiesRequested(e){const t={causeId:e.causeId,events:[{eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled}]};try{if(e.modality===Gi.MODALITY.video){Sn(this.data.videoMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentVideoSsrcRequestedCapabilities={};for(const t of e.capabilities)this.data.currentVideoSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}else if(e.modality===Gi.MODALITY.sharing){Sn(this.data.sharingMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentSharingSsrcRequestedCapabilities={};for(const t of e.capabilities)this.data.currentSharingSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}}catch(e){this.addStatsError?.("onMaxCapabilitiesRequested",tt(e))}}onMaxCapabilitiesApplied(e){try{const t=this.getEventForCause(e.modality,e.causeId),i={eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:`${e.error}`||"none"};if(t&&(Sn(t.events,i,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1),e.error&&(e.modality===Gi.MODALITY.video?Sn(this.data.videoMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1):e.modality===Gi.MODALITY.sharing&&Sn(this.data.sharingMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1))),e.modality===Gi.MODALITY.video){this.data.currentVideoSsrcAppliedCapabilities={};for(const t of e.capabilities)this.data.currentVideoSsrcAppliedCapabilities[`${t.ssrc??0}`]=t}else if(e.modality===Gi.MODALITY.sharing){this.data.currentSharingSsrcAppliedCapabilities={};for(const t of e.capabilities)this.data.currentSharingSsrcAppliedCapabilities[`${t.ssrc??0}`]=t}}catch(e){this.addStatsError?.("onMaxCapabilitiesApplied",tt(e))}}addVideoControlMessage(e=!1){this.data.numVideoControlMessages++,e&&this.data.numOutOfOrderVideoControlMessages++}getObjectRef(){return this.data}registerWebcamFreeze(){this.data.numWebcamFreezeIntervals++}registerProcessedStreamFreeze(){this.data.numProcessedStreamFreezeIntervals++}getEventForCause(e,t){return(e===Gi.MODALITY.video?this.data.videoMaxCapabilitiesEvents:this.data.sharingMaxCapabilitiesEvents).find((e=>e.causeId===t))}},hO=class{constructor(e){this.configProvider=e,this.data={renderers:[],firstTimeToFirstFrameVideo:-1,firstTimeToFirstFrameSharing:-1,timeToFirstFrameSinceSubscriptionStartVideo:-1,timeToFirstFrameSinceSubscriptionStartSharing:-1,isRenderingEvents:{video:[],sharing:[]},preferredResolution:{video:void 0,sharing:void 0}}}setTimeToFirstFrame(e,t){-1!==e&&(t===Gi.MODALITY.video&&-1===this.data.firstTimeToFirstFrameVideo?this.data.firstTimeToFirstFrameVideo=e:t===Gi.MODALITY.sharing&&-1===this.data.firstTimeToFirstFrameSharing&&(this.data.firstTimeToFirstFrameSharing=e))}setTimeToFirstFrameSinceSubscriptionStart(e,t){-1!==e&&(t===Gi.MODALITY.video&&-1===this.data.timeToFirstFrameSinceSubscriptionStartVideo?this.data.timeToFirstFrameSinceSubscriptionStartVideo=e:t===Gi.MODALITY.sharing&&-1===this.data.timeToFirstFrameSinceSubscriptionStartSharing&&(this.data.timeToFirstFrameSinceSubscriptionStartSharing=e))}setIsRendering(e,t){this.data.isRenderingEvents[t]&&Sn(this.data.isRenderingEvents[t],{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents)}setPreferredResolution(e,t){(e.width||e.height)&&(this.data.preferredResolution[t]=e)}newRendererDiagnostics(){const e=new gO(this,this.configProvider),t=e.on("onDisposed",(()=>{this.removeDeadRenderers(),t.dispose()}));return this.data.renderers.push(e.getObjectRef()),e}getObjectRef(){return this.data}removeDeadRenderers(){this.data.renderers=this.data.renderers.filter((e=>e.alive))}},gO=class extends Vi{constructor(e,t){super(),this.managerDiagnostics=e,this.configProvider=t,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(e){this.data.trackId=e}set rendererSize(e){this.data.rendererSize=e,e.toString=()=>`${e.width}x${e.height}`,this.managerDiagnostics.setPreferredResolution(e,this.data.modality)}set msi(e){this.data.msi=e}set modality(e){this.data.modality=e}set isRendering(e){this.data.isRendering=e,this.managerDiagnostics.setIsRendering(e,this.data.modality)}set timeToFirstFrame(e){this.data.timeToFirstFrame=e,this.managerDiagnostics.setTimeToFirstFrame(e,this.data.modality)}set timeToFirstFrameSinceSubscriptionStart(e){this.data.timeToFirstFrameSinceSubscriptionStart=e,this.managerDiagnostics.setTimeToFirstFrameSinceSubscriptionStart(e,this.data.modality)}addFreezeDuration(e){this.data.totalFreezeDuration+=e}addStateChange(e){Sn(this.data.rendererStates,e,this.configProvider.config.diagnostics.telemetryLimits.numRendererStateChangedEvents)}dispose(){this.isAlive=!1,this.event("onDisposed").raise()}getObjectRef(){return this.data}},pO=Z,mO=p(ye()),fO=Z;function vO(e){let t="";return qi(e,((e,i)=>{t+=(t?";":"")+i,void 0!==e&&(t+=`=${e}`)})),t}var SO=class{constructor(e){this.parameters={},e&&e.split(";").forEach((e=>{const t=e.split("=");this.parameters[t[0]]=t[1]}))}setIfMissing(e,t){this.contains(e)||(this.parameters[e]=t)}removeIfPresent(e){this.contains(e)&&delete this.parameters[e]}get(e){return this.parameters[e]}names(){return Object.keys(this.parameters)}contains(e){return this.parameters.hasOwnProperty(e)}toString(){return vO(this.parameters)}};function yO(e,t,i){if(!e.rtp)return;const n=e.rtp.filter((e=>e.payload===t))[0];n&&TO(e,{codec:n.codec,rate:n.rate,payload:n.payload,encoding:n.encoding},(e=>(e.rtp.payload=i,e)))}function CO(e){const t=new Set;for(const i of e.media)for(const e of i.rtp??[])t.add(e.payload);const i=[96,127];for(let e=i[0];e<=i[1];e++)if(!t.has(e))return e;const n=[35,64];for(let e=n[0];e<=n[1];e++)if(!t.has(e))return e;return-1}function TO(e,t,i,n){bO(e,t,!0,n,i)}function EO(e,t,i,n){bO(e,t,!1,n,i)}function bO(e,t,i,n=!0,r){if(e.rtp){for(let s=0;s<e.rtp.length;s++){const a=e.rtp[s],o=a.payload;if(t.codec.toLowerCase()!==a.codec.toLowerCase()||t.rate!==a.rate||t.encoding!==a.encoding||t.payload&&t.payload!==a.payload)continue;const l={rtp:a};e.fmtp||(e.fmtp=[]);const c=e.fmtp.find((e=>a.payload===e.payload));l.fmtp=c,e.rtcpFb||(e.rtcpFb=[]),l.rtcpFb=e.rtcpFb.filter((e=>e.payload===a.payload));const d=l.rtcpFb.length>0;if(null===r(l))e.payloads=e.payloads.toString().split(" ").filter((e=>a.payload!==+e)).join(" "),e.fmtp=e.fmtp.filter((e=>a.payload!==e.payload)),e.rtcpFb=e.rtcpFb.filter((e=>a.payload!==e.payload)),e.rtp[s]=null;else{if(l.rtp.payload!==o){const t=l.rtp.payload;e.payloads=e.payloads.toString().split(" ").map((e=>+e===o?t:+e)).join(" "),l.fmtp&&(l.fmtp.payload=t),l.rtcpFb&&l.rtcpFb.forEach((e=>e.payload=t)),n&&e.fmtp.filter((e=>e.config&&e.config.indexOf(`apt=${o}`)>-1)).forEach((e=>e.config=e.config.replace(`apt=${o}`,`apt=${t}`)))}!c&&l.fmtp&&e.fmtp.push(l.fmtp),!d&&l.rtcpFb&&l.rtcpFb.forEach((t=>e.rtcpFb.push(t)))}if(i)break}e.rtp=e.rtp.filter((e=>!!e))}}function _O(e,t){if(!e.rtp)return;let i=-1;if(e.rtp.forEach((function(e,n){t.codec.toLowerCase()!==e.codec.toLowerCase()||t.rate!==e.rate||t.encoding!==e.encoding||t.payload&&t.payload!==e.payload||(i=n)})),i>=0&&e.rtp.length>1){const t=e.rtp[i].payload;e.rtp.splice(i,1),e.payloads=e.payloads.split(" ").filter((e=>t!==+e)).join(" "),e.fmtp=e.fmtp?.filter((e=>t!==e.payload))}}function IO(e,t){e.rtp.unshift({payload:t.payload,codec:t.codec,rate:t.rate,encoding:t.encoding}),e.payloads=`${t.payload} ${e.payloads}`}function wO(e,t,i){if(!(0,fO.isUndefined)(e.rate)&&e.rate!==t.rate)return!1;if(!(0,fO.isUndefined)(e.codec)&&e.codec.toLowerCase()!==t.codec.toLowerCase())return!1;if(!(0,fO.isUndefined)(e.encoding)){if(!(0,fO.isUndefined)(t.encoding)&&e.encoding!==t.encoding)return!1;if((0,fO.isUndefined)(t.encoding)&&1!==e.encoding)return!1}if(!(0,fO.isUndefined)(e.fmtpLine)){const n=i?.find((i=>i.payload===t.payload&&-1!==i.config.toLowerCase().indexOf(e.fmtpLine.toLowerCase())));return!!n}return!0}function AO(e,t){return t===e||"*"===t}function PO(e,t,i,n){if(!e.rtp?.length)return;let r=e.rtp.filter((i=>t.some((t=>wO(t,i,e.fmtp)))));e.type===Gi.MEDIA_TYPE.video&&(r=r.filter((t=>{const i=e.fmtp?.find((e=>e.payload===t.payload&&e.config.startsWith("apt=")));if(i){const e=+i.config.split(";")[0].split("=")[1];return r.some((t=>t.payload===e))}return!0}))),r.length?(e.rtp=r,i&&(e.rtp=(0,fO.flatten)(t.map((t=>e.rtp.filter((i=>wO(t,i,e.fmtp))))))),e.payloads=e.rtp.map((e=>e.payload)).join(" "),e.fmtp=e.fmtp?.filter((t=>e.rtp.some((e=>AO(e.payload,t.payload))))),e.rtcpFb=e.rtcpFb?.filter((t=>e.rtp.some((e=>AO(e.payload,t.payload)))))):n&&n.warn("Empty rtp list after filtering")}function RO(e){if(e.label)switch(e.label){case Gi.MEDIA_LABEL.audio:return"Audio";case Gi.MEDIA_LABEL.video:return"Video";case Gi.MEDIA_LABEL.sharing:return"ScreenShare";case Gi.MEDIA_LABEL.data:return"Data"}else switch(e.type){case Gi.MEDIA_TYPE.audio:return"Audio";case Gi.MEDIA_TYPE.video:return"Video";case Gi.MEDIA_TYPE.data:case Gi.MEDIA_TYPE.dataChannel:return"Data"}return null}function MO(e){if(e.label)switch(e.label){case Gi.MEDIA_LABEL.audio:return Gi.MODALITY.audio;case Gi.MEDIA_LABEL.video:return Gi.MODALITY.video;case Gi.MEDIA_LABEL.sharing:return Gi.MODALITY.sharing;case Gi.MEDIA_LABEL.data:return Gi.MODALITY.data}else switch(e.type){case Gi.MEDIA_TYPE.audio:return Gi.MODALITY.audio;case Gi.MEDIA_TYPE.video:return Gi.MODALITY.video;case Gi.MEDIA_TYPE.data:case Gi.MEDIA_TYPE.dataChannel:return Gi.MODALITY.data}return null}function DO(e){switch(e){case Gi.MODALITY.audio:return Gi.MEDIA_LABEL.audio;case Gi.MODALITY.video:return Gi.MEDIA_LABEL.video;case Gi.MODALITY.sharing:return Gi.MEDIA_LABEL.sharing;case Gi.MODALITY.data:return Gi.MEDIA_LABEL.data;default:return null}}function kO(e){return e.media.reduce(((e,t)=>{if(0!==t.port){const i=MO(t);if(!(i in e)){const n=t.direction?t.direction.toLowerCase():Gi.MEDIA_STATE.sendReceive;e[i]=n}}return e}),{})}function OO(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));if(t){const i=t.mids?.toString().split(" ")[0];return e.media.find((e=>{const t="number"==typeof e.mid?e.mid.toString():e.mid;return i===t}))||null}return null}function NO(e){return 0===e.port}function LO(e){let t;return e&&TO(e,{codec:"h264",rate:9e4},(e=>{e.fmtp?.config&&(t=function(e){const t=new SO(e);return{maxFs:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Gi.VIDEO_CAPABILITIES.MAX_BR_PATH)}}(e.fmtp.config))})),t}function xO(e){const t=e.media.map((e=>parseFloat(e.mid||"0")));for(let e=1;e<=Math.max(...t)+1;e++)if(!t.includes(e))return e.toString();return"-1"}var FO=Z;function UO(){const e=[{jsep:"active",msSdp:"tcp-act"},{jsep:"passive",msSdp:"tcp-pass"},{jsep:"so",msSdp:"tcp-so"}];function t(e,t){delete e.generation,delete e["network-id"],delete e["network-cost"],e.transport.match(/tcp/i)&&i(e,t)}function i(t,i){e.some((function(e){if(i){if(e.msSdp===t.transport.toLowerCase())return t.transport="tcp",t.tcptype=e.jsep,!0}else if(t.tcptype&&e.jsep===t.tcptype.toLowerCase())return t.transport=e.msSdp,delete t.tcptype,!0;return!1}))}function n(e,t,i){const n=t.connection||i.connection,r=function(e,t,i){return e.port===i&&e.ip===t};return!!n&&(1===e.component?r(e,n.ip,t.port):!!t.rtcp&&r(e,t.rtcp.ip||n.ip,t.rtcp.port))}this.fromMsSdp=function(e){e.candidates=e.candidates||[],e.xCandidatesIpv6&&(e.xCandidatesIpv6.forEach((function(t){e.candidates.push(t)})),delete e.xCandidatesIpv6),e.candidates.forEach((function(e){t(e,!0)}))},this.toMsSdp=function(e,i){e.candidates=e.candidates||[],e.candidates.sort((function(t,r){return t.foundation!==r.foundation?t.foundation-r.foundation:t.component!==r.component?t.component-r.component:+n(r,e,i)-+n(t,e,i)})),e.candidates=e.candidates.filter((function(i,n){t(i,!1);const r=e.candidates[n-1];return!r||r.component!==i.component||r.foundation!==i.foundation})),function(e,t){if(e.port&&!e.candidates.length){const i=OO(t);i&&(e.port=i.port,e.connection=i.connection)}}(e,i)}}var BO=class{toMsSdp(e,t){"offer"===t?e.rtcp&&(e.rtcp={port:e.port}):delete e.rtcp}},VO={STREAM_ID:{audio:"mainAudio",video:"mainVideo",sharing:"applicationsharingVideo"},STREAM_ID_DELIMITER:"-"},HO=[{label:Gi.MEDIA_LABEL.audio,id:VO.STREAM_ID.audio},{label:Gi.MEDIA_LABEL.video,id:VO.STREAM_ID.video},{label:Gi.MEDIA_LABEL.sharing,id:VO.STREAM_ID.sharing}].reduce(((e,t)=>(e[t.label]=t.id,e)),{}),$O=sn(),jO=class{constructor(e){this.configuration=e}fromMsSdp(e){if(0!==e.port){if(!this.isRecvOnly(e)||this.configuration.unifiedPlanEnabled){if(e.msid){e.ssrcs&&1===e.ssrcs.length&&(this.addStream(e,e.ssrcs[0].id,e.ssrcs[0].value,e.msid),e.ssrcs.shift());const t=e.msid.split(" ");(this.configuration.addPrefixForMsid||"-"===t[0])&&(e.msid=this.getMsidValue(t[0],t[1]||t[0],e.label))}if(e.ssrcs)this.updateMsids(e.ssrcs,((t,i)=>this.configuration.addPrefixForMsid||"-"===t?this.getMsidValue(t,i,e.label):`${t} ${i}`));else{const t=this.getFlowSsrcs(e);t.length>0?t.forEach((i=>{this.addStream(e,i,$O,this.getMsidValue(t[0],t[0],e.label))})):e.xSsrcRange&&this.addStream(e,e.xSsrcRange.ssrcMin,$O,this.getMsidValue(e.xSsrcRange.ssrcMin,e.xSsrcRange.ssrcMin,e.label))}}delete e.xSsrcRange}}toMsSdp(e,t){if(0===e.port)return;let i;e.ssrcs?.[0]&&(i=e.ssrcs[0].id),void 0!==i&&(e.xMultiStream||(e.xSsrcRange={ssrcMin:i,ssrcMax:i+t}))}getFlowSsrcs(e){if(e.ssrcGroups&&e.type===Gi.MEDIA_TYPE.video){let t;if(e.ssrcGroups.some((e=>"FID"===e.semantics&&(t=e,!0))),t)return t.ssrcs.split(" ").map((e=>+e))}return[]}addStream(e,t,i,n){e.ssrcs=e.ssrcs||[],e.ssrcs.push({attribute:"cname",id:t,value:i}),e.ssrcs.push({attribute:"msid",id:t,value:n})}updateMsids(e,t){e.filter((e=>"msid"===e.attribute)).forEach((e=>{const i=e.value.split(" ");e.value=t(i[0],i[1]||i[0])}))}getMsidValue(e,t,i){const n=this.getMsidPrefix(i);return n+e+" "+n+t}getMsidPrefix(e){return HO[e]?HO[e]+VO.STREAM_ID_DELIMITER:""}isRecvOnly(e){return"recvonly"===e.direction}},GO={audio:"main-audio",video:"main-video"},qO=class{constructor(e,t){this.context=e,this.mediaManager=t,this.logger=this.context.logger,this.candidateTransform=new UO,this.streamTransform=new jO(this.context.configuration),this.rtcpTransform=new BO}toMsSdp(e,t){return e.msidSemantic={semantic:"WMS",token:"*"},e.media.forEach(((i,n)=>{if(i.protocol=Gi.PROFILES.rtpSavp,i.label=i.label||this.getLabel(i.type),NO(i)){for(const e in i)i.hasOwnProperty(e)&&["type","port","protocol","payloads"].indexOf(e)<0&&delete i[e];i.payloads="34"}const r=this.getSsrcRangeForIndex(i.direction,n);this.streamTransform.toMsSdp(i,r),i.crypto&&i.crypto.forEach((function(e){e.config+="|2^31"})),0!==i.port&&e.fingerprint&&(i.fingerprint=e.fingerprint),this.candidateTransform.toMsSdp(i,e),this.rtcpTransform.toMsSdp(i,t),i.invalid&&(this.logger.unsafe.error(`Unknown SDP attributes! ${JSON.stringify(i.invalid)}`),delete i.invalid),this.transformExtensions(i,!1),0!==i.port&&(i.type===Gi.MEDIA_TYPE.audio&&this.context.configProvider.config.webrtcAudioChannelSignalingFeedback?i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcAudioChannelSignalingFeedback}:i.type===Gi.MEDIA_TYPE.video&&this.context.configProvider.config.webrtcVideoChannelSignalingFeedback&&(i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcVideoChannelSignalingFeedback}))})),delete e.fingerprint,e}fromMsSdp(e,t){for(let i=e.media.length-1;i>=0;--i){const n=e.media[i];if((n.ssrcs?.[0]||n.xSsrcRange)&&(e.msidSemantic={semantic:"WMS",token:"*"}),NO(n))n.direction||(n.direction="inactive");else{if(this.streamTransform.fromMsSdp(n),delete n.cryptoscale,n.fingerprint&&(!this.isOffer(t)||this.context.configProvider.config.disableIncomingDtlsRoleOverride&&n.setup||(n.setup="actpass")),n.crypto)for(let e=n.crypto.length-1;e>=0;--e){const t=n.crypto[e];t.config.match(/.*\|\d+:\d+/)?n.crypto.splice(e,1):t.config=t.config.replace(/(.*)\|2\^\d+/,"$1")}n.remoteCandidates&&(delete n.candidates,delete n.xCandidatesIpv6,delete n.remoteCandidates),this.candidateTransform.fromMsSdp(n),n.rtcpFbXMessage&&delete n.rtcpFbXMessage,n.invalid&&this.logger.unsafe.info(`Unknown SDP attributes! ${JSON.stringify(n.invalid)}`),this.transformExtensions(n,!0)}}return e}transformExtensions(e,t){const i=[{name:Gi.ABS_SEND_TIME.EXT_URI,encoded:Gi.ABS_SEND_TIME.MSSDP_ENCODED_URI},{name:Gi.TRANSPORT_CC.EXT_URI,encoded:Gi.TRANSPORT_CC.MSSDP_ENCODED_URI}];e.ext&&e.ext.forEach((function(e){i.some((function(i){const n=t?i.encoded:i.name,r=t?i.name:i.encoded;return n===e.uri&&(e.uri=r,!0)}))}))}isOffer(e){return"offer"===e}getLabel(e){return GO.hasOwnProperty(e)&&GO[e]||"undefined"}getSsrcRangeForIndex(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();return Wp(e)&&n?n.getSsrcRange():0}},zO=4294967040,WO=class{constructor(){this.ssrc=Math.floor(Math.random()*(zO-1))+1}nextAudioStreamSsrc(){return this.nextSsrc(0)}nextVideoStreamSsrc(){return this.nextSsrc(99)}nextSsrc(e){let t=this.ssrc;do{t=this.ssrc,this.ssrc=(this.ssrc+e+1)%zO,0===this.ssrc&&(this.ssrc=1)}while(t+e>zO);return{min:t,max:t+e}}},KO=Z,JO=class{constructor(e,t,i){this.mediaEntity=e,this.logger=t,this.configProvider=i,this.activeRids=[],this.isLocalDescSet=!1,this.enabledLocally=!1,this.enabledRemotely=!1;const n=sm(this.mediaEntity.getModality());this.config=function(e,t){return"Video"===e?t.config.specCompliantSimulcast?.video:"ScreenShare"===e?t.config.specCompliantSimulcast?.sharing:null}(n,this.configProvider),this.config?this.logger.safe.debug(`Adding simulcast info to ${e.getModality()} with mid: ${e.getMid()}, config: ${JSON.stringify(this.config)}`):this.logger.safe.debug(`Simulcast is disabled for ${e.getModality()}`)}get ridList(){return this.config?(0,KO.times)(this.config.layerScaleFactors.length,(e=>e+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 e=this.mediaEntity.getRtpHeaderExtensions();return e?.some((e=>"mid"===e.headerType||"rid"===e.headerType||"rrid"===e.headerType))}},YO=Z,QO=[2812,4218,8437,16875,33750,67500,108e3,135e3,198e3,244800,27e4,352500,52e4],ZO=class{constructor(e,t,i,n){this.initialMaxFS=e,this.initialMaxFPS=t,this.isAv1Allowed=i,this.h264SubscribeProfile=n,this.maxFS=e,this.maxFPS=t}setMaxFS(e,t){return!(this.maxFS===e||(this.maxFS=e,!t)||(t(this),0))}getMaxFS(){return this.maxFS}getMaxFPS(){return this.maxFPS}getMaxMBPS(){return this.calculateMbps(this.maxFS,this.maxFPS)}calculateMbps(e,t){return cn(QO,e*t/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 e=[];let t=this.fmtpParams();return this.h264SubscribeProfile&&(t["profile-level-id"]=this.h264SubscribeProfile),e.push(t),this.isAv1Allowed&&(t=this.fmtpParams(),t.codec="AV1",e.push(t)),e}},XO=class e{constructor(e,t){this.entity=e,this.configProvider=t,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(e,t,i){if(e!==Gi.MEDIA_TYPE.video)return null;let n,r;t===Gi.MODALITY.sharing?(n=i.config.webrtcScreensharingCapabilityMaxFS,r=i.config.webrtcScreensharingCapabilityMaxFPS):(n=i.config.webrtcVideoCapabilityMaxFS,r=i.config.webrtcVideoCapabilityMaxFPS,i.config.useMultiviewLimitsOnInitialRequest&&i.config.multiviewResolutionLimits[1]&&(n=Hn.Send.getMaxFsForHeight(i.config.multiviewResolutionLimits[1])));const s=i.config.isAv1Allowed&&t===Gi.MODALITY.sharing;return new ZO(n,r,s,i.config.h264SubscribeProfile)}static create(t,i,n){const r=function(e){switch(e){case Gi.MODALITY.audio:return Gi.MEDIA_TYPE.audio;case Gi.MODALITY.video:case Gi.MODALITY.sharing:return Gi.MEDIA_TYPE.video;case Gi.MODALITY.data:return Gi.MEDIA_TYPE.data;default:return null}}(i),s=new e({modality:i,mid:n,mtype:r,extensions:{}},t);return s.localRecvCapabilities=e.getVideoCababilities(r,i,t),s}clone(){const t=new e((0,YO.cloneDeep)(this.entity),this.configProvider);return t.setSimulcastContext(this.simulcastContext),t.localRecvCapabilities=this.localRecvCapabilities,t.remoteRecvCapabilities=this.remoteRecvCapabilities,t.supportedSendProfiles=this.supportedSendProfiles,t}getModality(){return this.entity.modality}getType(){return this.entity.mtype}getMid(){return this.entity.mid}disable(){this.entity.mid=null}update(t,i){this.entity.modality!==t&&(this.localRecvCapabilities=e.getVideoCababilities(this.entity.mtype,t,this.configProvider)),this.entity.modality=t,this.entity.mid=i,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(e){this.remoteRecvCapabilities=e}getRemoteStreamId(){return this.entity.remoteStreamId}setRemoteStreamId(e){this.entity.remoteStreamId=e}setRemoteSsrc(e){this.entity.remoteSsrc=e}getRemoteSsrc(){return this.entity.remoteSsrc}setLocalSsrc(e){this.entity.localSsrc=e}getLocalSsrc(){return this.entity.localSsrc}getRemoteTrackId(){return this.entity.remoteTrackId}setRemoteTrackId(e){this.entity.remoteTrackId=e}getXSourceStreamId(){return this.entity.xSourceStreamId}setXSourceStreamId(e){this.entity.xSourceStreamId=e}setLocalTrackId(e){this.entity.localTrackId=e}getLocalTrackId(){return this.entity.localTrackId}setSubStreamIndex(e){this.entity.subStreamIndex=e}getSubstreamIndex(){return this.entity.subStreamIndex}getExtension(e){return this.entity.extensions[e]}setExtension(e,t){this.entity.extensions[e]=t}getRtpHeaderExtensions(){return this.entity.rtpExt}setRtpHeaderExtensions(e){this.entity.rtpExt=e}setSimulcastContext(e){this.simulcastContext=e}getSimulcastContext(){return this.simulcastContext}addSupportedSendProfile(e,t){void 0===this.supportedSendProfiles[e]&&(this.supportedSendProfiles[e]=new Set),this.supportedSendProfiles[e].add(t)}isSendProfileSupported(e,t){const i=this.supportedSendProfiles[e];if(void 0!==i){const e=t.slice(0,2);for(const t of i)if(t.startsWith(e))return!0}return!1}serialize(){return nn(this.entity)}},eN={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"},tN=class{constructor(e){this.context=e,this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.ssrcGenerator=new WO,this.rollbackHandlers=[],this.logger=e.logger.createChild("MM2"),this.configProvider=e.configProvider}fromOffer(e,t,i=!1){this.logger.safe.debug(`fromOffer, modalities: ${JSON.stringify(t)} disableOnly: ${i}`),this.updateMediaEntitiesFromModel(e,i),this.updateSharingEntity(!!t.sharing),e.media.forEach((e=>{this.logger.safe.debug(`Media entity for mid: ${e.mid}, ${this.getMediaEntityByMid(e.mid)}`);const t=this.getMediaEntityByMid(e.mid);t&&this.saveLocalSsrc(t,e)}))}fromRemote(e,t){const i=0===this.mediaEntities.length;this.updateMediaEntitiesFromModel(e,!1,t),e.media.forEach(((e,t)=>{const i=this.getMediaEntityByMid(e.mid);i&&(this.saveRemoteMsid(i,e),this.saveRemoteSsrc(i,e),this.saveRtpHeaderExtensions(i,e),i.setXSourceStreamId(e.xSourceStreamId||this.generateSourceStreamId(t)),i.setRemoteRecvCapabilities(LO(e)),i.setSubStreamIndex(e.subStreamIndex)),this.logger.safe.debug(`Media entity for mid: ${e.mid}, ${i}`)})),i&&this.updateReinvitelessState(e)}isEmpty(){return 0===this.mediaEntities.length}createMediaEntity(e,t){const i=XO.create(this.configProvider,e,t);return this.logger.safe.debug(`Creating media entity for modality: ${e}, mid: ${t}`),this.context.useSimulcast&&!this.mediaEntities.find((t=>t.getModality()===e))&&this.setSimulcastContext(i),i.setExtension("reinviteless",!1),this.mediaEntities.push(i),i}getMediaEntities(){return this.mediaEntities}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntitiesByMediaType(e){const t=sm(e);return this.getMediaEntitiesByModality(t)}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[],this.rollbackHandlers=[]}syncModalities(e,t,i=!1){this.logger.safe.debug(`syncModalities, modalities: ${JSON.stringify(t)}, disableOnly: ${i},`),this.fromOffer(e,t,i)}setLocalTracksInfo(e){this.mediaTracks=e}getLocalTracksInfo(){return this.mediaTracks}backup(){this.logger.safe.debug("backup"),this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{e.setExtension("unnegotiatedModality",!1)}))}rollback(){this.logger.safe.debug(`rollback, if backup exists: ${!!this.mediaEntitiesBackup.length}`),this.mediaEntitiesBackup.length&&(this.rollbackHandlers.forEach((e=>e(this.mediaEntities,this.mediaEntitiesBackup))),this.mediaEntities.forEach(((e,t)=>{this.mediaEntitiesBackup[t]?this.mediaEntities[t]=this.mediaEntitiesBackup[t]:(e.disable(),e.setExtension("rollback",!0))})))}updateMediaEntitiesWithLocalTracks(){this.mediaTracks?(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?(this.logger.safe.debug(`Setting local track id ${e.trackId} for modality ${e.modality}`),t.setLocalTrackId(e.trackId)):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)}))):this.logger.safe.debug("No mediaTracks, not updating local tracks for media entities")}updateMediaEntitiesWithActivityState(e,t){this.logger.safe.debug(`Updating activity indexes for ${e} to ${JSON.stringify(t)}`);const i=am(e),n=this.getMediaEntitiesByModality(i)[0];if(!n)return void this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(i)}`);const r=n.getSimulcastContext();r&&(r.activeRids=t)}setRollbackUpdateHandler(e){this.rollbackHandlers.push(e)}saveRtpHeaderExtensions(e,t){if(e.isDisabled())return void e.setRtpHeaderExtensions(void 0);const i=t.ext?.map((e=>this.getHeaderExtension(e)));this.logger.safe.debug(`RTP header ext for mid=${t.mid}, modality=${e.getModality()}: ${JSON.stringify(i)}`),e.setRtpHeaderExtensions(i)}getHeaderExtension(e){let t="unknown";for(const[i,n]of Object.entries(eN))if(e.uri.endsWith(i)){t=n;break}return{headerType:t,value:e.value}}saveRemoteMsid(e,t){if(NO(t))e.setRemoteStreamId(null);else if(t.msid)e.setRemoteStreamId(t.msid.split(" ")[0]);else if(t.ssrcs){const i=t.ssrcs.find((e=>"msid"===e.attribute));i?e.setRemoteStreamId(i.value.split(" ")[0]):this.logger.safe.warn(`No ssrc msid for media of type ${t.type} with mid ${t.mid}`)}}saveRemoteSsrc(e,t){if(t.ssrcs?.length){const i=t.ssrcs[0];e.setRemoteSsrc(+i.id)}}saveLocalSsrc(e,t){const i=t.ssrcs?.[0]?.id;if(!Wp(t.direction))return this.logger.safe.debug(`set local SSRC to ${i}`),void e.setLocalSsrc(+i);this.logger.safe.debug("has no send direction");const n=i||e.getLocalSsrc()||this.ssrcGenerator.nextVideoStreamSsrc().min;e.setLocalSsrc(+n)}updateMediaEntitiesFromModel(e,t,i){e.media.forEach(((e,n)=>{if(this.mediaEntities[n])if(NO(e))this.logger.safe.debug(`Disabling media entity for mid: ${e.mid}`),this.mediaEntities[n].disable();else{const t=e.mid||this.mediaEntities[n].getMid(),i=this.mediaEntities[n].getModality();this.logger.safe.debug(`Updating media entity for mid: ${t}, modality: ${i}`),this.mediaEntities[n].update(i,t),this.logger.safe.debug(`updated entity: ${this.mediaEntities[n]}`)}else t||this.createMediaEntity(MO(e),e.mid||n.toString());this.mediaEntities[n]&&i&&!(this.mediaEntities[n].getModality()in i)&&(this.logger.safe.debug(`Disabling media entity for mid: ${e.mid} as it is not found in modalities ${JSON.stringify(i)}`),this.mediaEntities[n].disable())}))}updateSharingEntity(e){if(e&&!this.getMediaEntitiesByModality(Gi.MODALITY.sharing).length){const e=this.getMediaEntitiesByModality(Gi.MODALITY.video).pop();e.update(Gi.MODALITY.sharing,e.getMid())}}setSimulcastContext(e){if(!e||e.getSimulcastContext())return;const t=new JO(e,this.logger.createChild(`SimContext:${e.getModality()}`),this.configProvider);e.setSimulcastContext(t)}generateSourceStreamId(e){return e+10}updateReinvitelessState(e){const t={[Gi.MODALITY.audio]:0,[Gi.MODALITY.video]:0,[Gi.MODALITY.sharing]:0};for(const i of e.media){const e=MO(i);void 0!==t[e]&&t[e]++;const n=this.getMediaEntityByMid(i.mid);if(n){const r=this.context.reinviteltessContext?.maxStreamsForModality[e]>=t?.[e]&&(!i.direction||"sendrecv"===i.direction);n.setExtension("reinviteless",r)}}}},iN=class{constructor(e){this.modifierList=e}modify(e){for(const t of this.modifierList)t.modify(e)}},nN=class{constructor(e,t,i,n){this.context=e,this.mediaManager=t,this.modalities=i,this.cname=n}build(e){switch(e.sdpSource){case 0:return new iN([new JN(this.context.configProvider),new AN(this.context.configProvider),new aL(this.mediaManager,this.context.configProvider),new sL(this.mediaManager),new FN(this.context.configProvider),new ON(this.context.configProvider),new KN(this.context.configProvider,this.mediaManager,e.sdpType,!1,this.context.getLogger().createChild("OverrideH264SendProfile")),new MN(this.mediaManager,this.context.configProvider,e.sdpType),new RN(this.mediaManager,this.context.configProvider,this.context.config.isConference,!1),new fL(this.context.configProvider,e.sdpType),new GN(this.context.configProvider)]);case 2:return new iN([new cN(this.mediaManager,this.modalities),new PN,new dN(this.mediaManager,!0),new XN(this.context.configProvider,this.mediaManager),new vN(this.modalities,this.mediaManager),new VN,new xN,new UN,new BN(this.context.configProvider),new LN(this.context.configProvider),new WN(this.context.configProvider),new KN(this.context.configProvider,this.mediaManager,e.sdpType,!0,this.context.getLogger().createChild("OverrideH264SendProfile")),new yN,new aN(this.context),new nL(this.mediaManager,this.context.configProvider),new wN(this.context.configProvider),new uL,new dL(this.context.configProvider),new oL(this.context.configProvider),new EN(this.mediaManager,this.modalities,this.context.configProvider),new fN(this.context),new hL(this.context.configProvider),new pN(this.context.configProvider),new MN(this.mediaManager,this.context.configProvider,e.sdpType),new DN(this.mediaManager,this.context.configProvider,e.sdpType),new RN(this.mediaManager,this.context.configProvider,this.context.config.isConference,!0),new $N(this.context.configProvider,this.context.getLogger()),new TN,new pL(this.context.configProvider),new GN(this.context.configProvider),new vL(e,this.context),new tL(this.context.configProvider),new QN(this.context.configProvider)]);case 1:return new iN([new hN(this.context,this.modalities.data),new dN(this.mediaManager,!1),new bN(this.context.configProvider),new cN(this.mediaManager,this.modalities),new CN(this.mediaManager),new xN,new NN(this.context.configProvider),new oN(this.mediaManager,"offer"===e.sdpType,this.context.configProvider),new rL(this.mediaManager,this.context.getLogger()),new cL(this.context.configProvider,this.mediaManager),new SN(this.context.config.isConference,this.cname),new _N(this.mediaManager),new IN,new YN(this.context.configProvider),new mN(this.context.configProvider),new gL(this.context.configProvider),new mL(this.context.configProvider),new DN(this.mediaManager,this.context.configProvider,e.sdpType),new zN(this.mediaManager,this.context.configProvider,e.sdpType),new QN(this.context.configProvider)])}}},rN=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new qO(this.context,this.mediaManager)}modify(e){this.msSdpT.toMsSdp(e,this.sessionType)}},sN=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new qO(this.context,this.mediaManager)}modify(e){this.msSdpT.fromMsSdp(e,this.sessionType)}},aN=class{constructor(e){this.context=e}modify(e){const t=gm(this.context.configProvider,this.context.config.isPstnCall),i=im(e),n=e.media.find((e=>!!e.crypto));e.media.forEach((e=>{e.type!==Gi.MEDIA_TYPE.dataChannel&&(!t&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!i.dtls||i.sdes&&t?Gi.PROFILES.rtpSavpf:Gi.PROFILES.udpTlsRtpSavpf,NO(e)&&e.protocol===Gi.PROFILES.rtpSavpf&&n&&(e.crypto=n.crypto))}))}},oN=class{constructor(e,t,i){this.mediaManager=e,this.isOffer=t,this.configProvider=i}modify(e){e.media.forEach(((e,t)=>{const i=e.setup,n=this.mediaManager.getMediaEntities()[t],r=n.getExtension("setup");i&&n.isEnabled()&&("actpass"!==i?n.setExtension("setup",i):this.isOffer&&void 0!==r&&"actpass"!==r&&!this.configProvider.config.disableOutgoingDtlsRoleOverride&&(e.setup=r))}))}},lN=class{modify(e){e.media.forEach((e=>{e.direction===Gi.MEDIA_STATE.sendReceive&&(e.direction=Gi.MEDIA_STATE.receive),e.direction===Gi.MEDIA_STATE.send&&(e.direction=Gi.MEDIA_STATE.inactive)}))}},cN=class{constructor(e,t){this.mediaManager=e,this.modalities=t}modify(e){let t=0;e.media.forEach(((e,i)=>{const n=parseInt(e.mid,10);!isNaN(n)&&n>=t&&(t=n+1)})),e.media.forEach(((i,n)=>{const r=this.mediaManager.getMediaEntities()[n];if(NO(i)||r.isDisabled()||!(r.getModality()in this.modalities)){const s=r.getExtension("midApplied")?void 0:i.mid||""+t++;0===n?i.direction=Gi.MEDIA_STATE.inactive:e.media[n]=SL(i.type,void 0,i.protocol,s)}}))}},dN=class{constructor(e,t){this.mediaManager=e,this.remote=t}modify(e){const t=this.mediaManager.getMediaEntities();for(let i=0;i<t.length;i++){const n=t[i],r=e.media[i];if(n.getExtension("rollback"))if(r&&!this.remote)e.media[i]=null;else if(!r&&this.remote){const t=n.getType()===Gi.MEDIA_TYPE.data?Gi.MEDIA_TYPE.dataChannel:n.getType(),i=t===Gi.MEDIA_TYPE.dataChannel?Gi.PROFILES.udpDtlsSctp:Gi.PROFILES.udpTlsRtpSavpf;e.media.push(SL(t,void 0,i,void 0))}}e.media=e.media.filter((e=>e))}},uN=class{constructor(e){this.mediaManager=e}modify(e){this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];t.getModality()!==Gi.MODALITY.data||n&&n.type===Gi.MEDIA_TYPE.dataChannel||e.media.splice(i,0,SL(Gi.MEDIA_TYPE.data,Gi.MEDIA_LABEL.data,Gi.PROFILES.rtpSavp,void 0))}))}},hN=class{constructor(e,t){this.context=e,this.direction=t}modify(e){e.media.forEach((e=>{e.type===Gi.MEDIA_TYPE.dataChannel&&(e.type=Gi.MEDIA_TYPE.data,e.payloads=Gi.PAYLOAD_TYPE.X_DATA)})),mm(this.context)&&yL(e,Gi.MEDIA_TYPE.data).forEach((t=>{t.rtp=t.rtp||[],t.fmtp=t.fmtp||[],t.rtp.push({codec:"x-data",payload:127,rate:9e4}),t.rtp.push({codec:"rtx",payload:126,rate:9e4}),t.fmtp.push({payload:126,config:"apt=127"});const i=this.getNonOverlappingSsrc(e);t.xSsrcRange={ssrcMin:i,ssrcMax:i},t.rtcpMux="rtcp-mux",t.xDataProtocol="sctp",t.direction=this.direction}))}getNonOverlappingSsrc(e){let t,i=!0;do{t=Math.floor(4294967293*Math.random())+2,yL(e).forEach((e=>{e?.ssrcs?.[0]?.id===t&&(i=!1)}))}while(!i);return t}},gN=class{constructor(e){this.configProvider=e,this.uri="urn:3gpp:video-orientation",this.value=13}modify(e){if(this.configProvider.config.enableVideoOrientationExtension)for(const t of yL(e,Gi.MEDIA_TYPE.video))this.modifyMedia(t)}},pN=class extends gN{modifyMedia(e){e.ext??(e.ext=[]),e.ext.some((e=>e.uri===this.uri))||e.ext.push({value:this.getAvailableValue(e.ext),uri:this.uri})}getAvailableValue(e){const t=e.map((e=>e.value));return t.includes(this.value)?Math.max(...t)+1:this.value}},mN=class extends gN{modifyMedia(e){e.ext=e.ext?.filter((e=>e.uri!==this.uri))}},fN=class{constructor(e){this.context=e}modify(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));for(let i=e.media.length-1;i>=0;i--){const n=e.media[i];if(n.type===Gi.MEDIA_TYPE.data){const r=this.context.configProvider.config.rejectUnbundledDataModality&&!this.context.configProvider.mediaConfig.isTransportUnbundled&&!t?.mids?.toString().includes(n.mid),s=mm(this.context);s||this.context.configProvider.config.acceptDisabledDataModality?(n.port=s&&!r?n.port:0,n.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL,n.type=Gi.MEDIA_TYPE.dataChannel,n.protocol=Gi.PROFILES.udpDtlsSctp,n.sctpPort??(n.sctpPort=this.context.configProvider.config.sctpPort),delete n.xDataProtocol,delete n.rtp,delete n.fmtp,delete n.rtcp,delete n.rtcpMux,delete n.ext,delete n.ssrcs,delete n.ssrcGroups,delete n.xSsrcRange):e.media.splice(i,1)}}}},vN=class{constructor(e,t){this.modalities=e,this.mediaManager=t}modify(e){yL(e).forEach((e=>{const t=MO(e),i=this.mediaManager.getMediaEntityByMid(e.mid);!(this.modalities[t]!==Gi.MEDIA_STATE.send||i.getExtension("reinviteless")||e.direction&&e.direction.toLowerCase()===Gi.MEDIA_STATE.receive)&&(e.direction=Gi.MEDIA_STATE.receive)}))}},SN=class{constructor(e,t){this.isMultiparty=e,this.cname=t}modify(e){this.isMultiparty&&yL(e).forEach((e=>{const t=e.direction;t!==Gi.MEDIA_STATE.receive&&t!==Gi.MEDIA_STATE.inactive||(e.ssrcs?.[0]?e.ssrcs=[{id:e.ssrcs[0].id,attribute:"cname",value:this.cname}]:e.type===Gi.MEDIA_TYPE.audio?e.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:e.type===Gi.MEDIA_TYPE.video&&(e.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}))}},yN=class{modify(e){const t=new Set;yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{e.ssrcs&&e.ssrcs.length>1&&t.add(+e.ssrcs[0].id)}));const i=yL(e,Gi.MEDIA_TYPE.video).find((e=>e.direction===Gi.MEDIA_STATE.sendReceive||e.direction===Gi.MEDIA_STATE.send));yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{const n=e.direction;if((n===Gi.MEDIA_STATE.receive||n===Gi.MEDIA_STATE.inactive)&&e.ssrcs&&1===e.ssrcs.length){const n=e.ssrcs[0].id;(1===n||i&&i.ssrcs[0].id===n||!i&&t.has(n))&&(delete e.ssrcs,delete e.ssrcGroups)}}))}},CN=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t];e.label=DO(i.getModality())}))}},TN=class{modify(e){e.media.forEach((e=>{delete e.label}))}},EN=class{constructor(e,t,i){this.mediaManager=e,this.modalities=t,this.configProvider=i}modify(e){let t=this.configProvider.mediaConfig.maxBandwidthInKbps;const i=e.bandwidth?.find((e=>"CT"===e.type));i&&(!t||t>+i.limit)&&(t=+i.limit);const n=this.configProvider.config.audioBandwidthInKbps||0,r=Math.max(t-n,0),s=this.configProvider.config.videoBandwidthAllocation&&Wp(this.modalities.video)&&Wp(this.modalities.sharing);yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{if(delete e.bandwidth,r){let t=r;if(s){const i=this.mediaManager.getMediaEntityByMid(e.mid).getModality()===Gi.MODALITY.video?this.configProvider.config.videoBandwidthAllocation:1-this.configProvider.config.videoBandwidthAllocation;t=Math.round(r*i)}e.bandwidth=[{limit:t,type:"AS"}]}}))}},bN=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.mediaConfig.maxBandwidthInKbps;t&&(e.bandwidth=[{limit:t,type:"CT"}])}},_N=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i.getExtension("iceUfrag");i.setExtension("iceRestart",!!e.iceUfrag&&!!n&&n!==e.iceUfrag),i.setExtension("iceUfrag",e.iceUfrag)}))}},IN=class{modify(e){const t=new Set(["urn:ietf:params:rtp-hdrext:csrc-audio-level","http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]);yL(e).forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}))}},wN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed&&(e.extmapAllowMixed="extmap-allow-mixed")}},AN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed||delete e.extmapAllowMixed}},PN=class{modify(e){yL(e).forEach((e=>{delete e.signalingFbXMessage}))}},RN=class{constructor(e,t,i,n){this.mediaManager=e,this.configProvider=t,this.isConference=i,this.remote=n}modify(e){if(this.configProvider.config.isAv1Allowed&&this.isConference){const t=function(e,t){const i=new Set,n=[];for(const t of e.media)for(const e of t.rtp??[])i.add(e.payload);for(let e=t[0];e<=t[1];e++)i.has(e)||n.push(e);return n}(e,[96,127]);this.mediaManager.getMediaEntities().forEach(((i,n)=>{let r=0;const s=e.media[n];if(i.getModality()!==Gi.MODALITY.audio){if(!this.remote){const e=bL(s,{codec:"AV1",rate:9e4},t,!0,r);r=t.length-1,e.forEach((e=>{bL(s,{codec:"rtx",rate:9e4,payload:e+1},t,!1,r),r--}))}this.remote&&this.configProvider.config.av1LevelIndex&&EO(s,{codec:"AV1",rate:9e4},(e=>{e.fmtp.config=((e,t)=>e.replace(/level-idx=\d+((\.\d+)+)?/g,`level-idx=${t}`))(e.fmtp.config,this.configProvider.config.av1LevelIndex)}))}}))}}},MN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new kN(this.mediaManager,this.configProvider,this.sdpType,!1)}modify(e){this.configProvider.config.filterCodecsInSdpV2||this.baseModifier.modify(e)}},DN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new kN(this.mediaManager,this.configProvider,this.sdpType,!0)}modify(e){this.configProvider.config.filterCodecsInSdpV2&&this.baseModifier.modify(e)}},kN=class{constructor(e,t,i,n=!1){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.alwaysReorder=n}modify(e){this.configProvider.config.filterCodecsInSdp&&"offer"===this.sdpType&&this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];if(!n)return;const r=fm(this.configProvider,n.type);r.length&&PO(n,vm(r),!!t.getExtension("unnegotiatedModality")||this.alwaysReorder,null)}))}},ON=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally)return this.removeSubstitutionCodec(t,"SatinFB"),void this.removeSubstitutionCodec(t,"MUCHv2");i.codec!==i.lastUsedCodec&&"None"!==i.lastUsedCodec&&this.removeSubstitutionCodec(t,i.lastUsedCodec),i.enabledLocally&&!i.disabledRemotely&&this.addSubstitutionCodecIfNeeded(t,i.codec,e)}addSubstitutionCodecIfNeeded(e,t,i){if(this.isSubstitutionCodecAdded(e,t))return;const n=CO(i);if(-1===n)return;const r=TL(t,"SUBSTITUTION");EL(i,r.payload,n),IO(e,r)}removeSubstitutionCodec(e,t){_O(e,TL(t,"SUBSTITUTION"))}isSubstitutionCodecAdded(e,t){let i=!1;return TO(e,TL(t,"SUBSTITUTION"),(()=>{i=!0})),i}},NN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally||i.disabledRemotely)return this.removeSubstitutionCodec(t,"SatinFB"),void this.removeSubstitutionCodec(t,"MUCHv2");const n=TL(i.codec,"SUBSTITUTION"),r=TL(i.codec,"CODEC");TO(t,n,(e=>{e.rtp.codec=r.codec,e.rtp.rate=r.rate,e.rtp.encoding=r.encoding,"SatinFB"===i.codec&&(e.fmtp={payload:r.payload,config:"decoderversion=1"})}))}removeSubstitutionCodec(e,t){_O(e,TL(t,"SUBSTITUTION"))}},LN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally)return this.removeCodec(t,"SatinFB"),void this.removeCodec(t,"MUCHv2");const n=TL(i.codec,"CODEC"),r=TL(i.codec,"SUBSTITUTION");let s=!1;TO(t,n,(e=>{i.enabledForSend&&(e.rtp.codec=r.codec,e.rtp.rate=r.rate,e.rtp.encoding=r.encoding,e.fmtp={payload:n.payload,config:"ptime=20"}),s=!0})),i.disabledRemotely=!s}removeCodec(e,t){_O(e,TL(t,"CODEC")),_O(e,TL(t,"SUBSTITUTION"))}},xN=class{modify(e){_O(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"CN",rate:16e3})}},FN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;if(this.configProvider.config.fixOpusComfortNoise){if(!t||i&&(!i.enabledLocally||i.disabledRemotely))return}else if(!t||!i?.enabledLocally||i.disabledRemotely)return;let n=!1;const r={codec:"CN",rate:48e3};if(TO(t,r,(()=>{n=!0})),n)return;const s=CO(e);-1!==s&&(this.configProvider.config.fixOpusComfortNoise?r.payload=s:(EL(e,Gi.PAYLOAD_TYPE.MSRTC_CNFB,s),r.payload=Gi.PAYLOAD_TYPE.MSRTC_CNFB),IO(t,r))}},UN=class{modify(e){_O(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"g722",rate:8e3,encoding:2})}},BN=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.config.enforceOpusFmtp;t&&TO(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"opus",rate:48e3,encoding:2},(e=>{e.fmtp||(e.fmtp={payload:e.rtp.payload});const i=new SO(e.fmtp.config);Object.keys(t).forEach((e=>{i.removeIfPresent(e),i.setIfMissing(e,`${t[e]}`)})),e.fmtp.config=i.toString()}))}},VN=class{modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(t&&NO(t)){const i=e.media.find((e=>!!e.iceUfrag));i&&(t.port=9,t.direction="inactive",t.iceUfrag=i.iceUfrag,t.icePwd=i.icePwd,t.rtcpMux="rtcp-mux",i.crypto&&(t.crypto=i.crypto),i.fingerprint&&(t.fingerprint=i.fingerprint,t.setup=i.setup),t.rtp=[{payload:0,codec:"PCMU",rate:8e3}],t.payloads="0")}}},HN=class{constructor(e){this.otherPartyCodecs=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=["cn","telephone-event"],n=t.rtp.filter((e=>-1!==this.otherPartyCodecs.indexOf(e.codec.toLowerCase())&&-1===i.indexOf(e.codec.toLowerCase())));if(0===n.length)throw new Error("there is no matching primary audio codec");t.rtp.filter((e=>e!==n[0]&&-1===i.indexOf(e.codec.toLowerCase()))).forEach((e=>{_O(t,e)}))}},$N=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){this.configProvider.config.webrtcInjectTransportCCAudio&&yL(e,Gi.MEDIA_TYPE.audio).forEach((e=>{const t=e.ext?.find((e=>e.uri===Gi.TRANSPORT_CC.EXT_URI));if(!t)return void this.logger.safe.info("transport-cc ext not present in sdp, skipping injecting transport-cc attribute for audio");const i=e.rtp?.find((e=>"opus"===e.codec.toLowerCase()));if(!i)return void this.logger.safe.info("opus codec not found, skipping injecting transport-cc attribute for audio");const n=i.payload,r=e.rtcpFb?.find((e=>e.type===Gi.TRANSPORT_CC.ATTRIBUTE&&e.payload===n));r?this.logger.safe.info("opus codec already has transport-cc attribute"):(e.rtcpFb=e.rtcpFb||[],e.rtcpFb.push({payload:n,type:Gi.TRANSPORT_CC.ATTRIBUTE}),this.logger.safe.info("injected transport-cc attribute"))}))}},jN=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){e.media.forEach(((e,t)=>{if(NO(e)||e.type!==Gi.MEDIA_TYPE.video)return;const i=this.mediaManager.getMediaEntities()[t];TO(e,{codec:"h264",rate:9e4},(e=>{const t=i.getLocalRecvCapabilities();if(!t)return;e.fmtp||(e.fmtp={payload:e.rtp.payload});const n=new SO(e.fmtp.config);this.configProvider.config.h264SdpProfile?(n.removeIfPresent("profile-level-id"),n.setIfMissing("profile-level-id",this.configProvider.config.h264SdpProfile)):n.setIfMissing("profile-level-id","42C02A"),n.setIfMissing("max-fs",t.getMaxFS().toString()),n.setIfMissing("max-mbps",t.getMaxMBPS().toString()),n.setIfMissing("max-fps",t.getMaxFPS().toString()),e.fmtp.config=n.toString()}))}))}},GN=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.removeRtcpRsizeFromLocalSdp)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));t?.rtcpRsize&&delete t.rtcpRsize}},qN=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<this.configProvider.config.nonMultiStreamChannels)return;let t=0;for(let i=0;i<e.media.length;i++)if("Video"===RO(e.media[i])){if(e.media[i].xMultiStream)break;t++}const i=e.media.findIndex((e=>e.xMultiStream)),n=e.media[i];if(!n)return;const r=n.xMultiStream.startSsrc,s=n.xMultiStream.ssrcGroupRange,a=n.xMultiStream.ssrcRange;delete n.xMultiStream;const o=this.configProvider.config.numVideoChannelsGvc-t-1;n.subStreamIndex=o;const l=[];for(let t=0;t<o;t++){const o=(0,FO.cloneDeep)(n);o.mid=xO(e),o.xSourceStreamId=n.xSourceStreamId,o.subStreamIndex=t,l.push(o.mid);const c=r+t*a;o.ssrcGroups=[{ssrcs:`${c} ${c+s}`,semantics:"FID"}],o.xSsrcRange={ssrcMin:c,ssrcMax:c+a-1},e.media.splice(i+t,0,o)}const c=r+o*a;n.ssrcGroups=[{ssrcs:`${c} ${c+s}`,semantics:"FID"}],n.xSsrcRange={ssrcMin:c,ssrcMax:c+a-1};const d=e.groups.find((e=>e.mids.includes(n.mid)));d.mids=`${d.mids} ${l.join(" ")}`}},zN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.type=i}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<=this.configProvider.config.nonMultiStreamChannels+1)return;const t=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.video);let i=-1,n=-1;if(t.forEach(((t,r)=>{const s=e.media.findIndex((e=>e.mid===t.getMid()));r===this.configProvider.config.nonMultiStreamChannels-1&&(n=s),i=s})),-1===i||-1===n)return;const r=e.media[i];e.media.splice(n+1,i-n-1);const s=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;r.xMultiStream={numberOfStreams:s,startSsrc:1,ssrcRange:1,ssrcGroupRange:1},"answer"===this.type&&(r.xMultiStream.numberOfStreams=Math.min(s,this.configProvider.mediaConfig.multiStreamChannelsOffered),r.ssrcGroups&&delete r.ssrcGroups,r.xSsrcRange&&delete r.xSsrcRange)}},WN=class{constructor(e){this.configProvider=e}modify(e){yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{TO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO,i=new SO(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((e=>{if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n=this.configProvider.config.h264SendProfileOverride||n),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}))}},KN=class{constructor(e,t,i,n,r){this.configProvider=e,this.mediaManager=t,this.sdpType=i,this.remote=n,this.log=r}process(e,t,i){yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{RO(e)===t&&TO(e,{codec:"h264",rate:9e4},(t=>{if(t.fmtp){const n=new SO(t.fmtp.config),r=new SO;let s=!1;for(const t of n.names()){let a=n.get(t);if("profile-level-id"===t){const t=this.mediaManager.getMediaEntities().filter((t=>t.getModality()===MO(e))).filter((e=>e.isEnabled())),n=i(t,a);typeof n==typeof a&&n!==a&&(a=n,s=!0)}r.setIfMissing(t,a)}s&&(t.fmtp.config=r.toString())}}))}))}modify(e){const t=this.configProvider.config.preferredH264SendProfileFallback,i=this.configProvider.config.preferredH264SharingSendProfile,n=this.configProvider.config.preferredH264VideoSendProfile;if(this.remote){const r=e=>(i,n)=>i.some((t=>t.isSendProfileSupported("H264",e)))?(this.log.safe.info(`Overriding H264 send profile: ${n} => ${e}`),e):(this.log.safe.info(`Applying fallback H264 profile: ${n} => ${t}`),t);n&&this.process(e,"Video",r(n)),i&&this.process(e,"ScreenShare",r(i))}else"answer"===this.sdpType&&(n||i)&&this.configProvider.config.enableFallbackH264SendProfileForLocalAnswer&&this.process(e,"Video",((e,r)=>r===n||r===i?(this.log.safe.info(`Restoring fallback profile in local answer: ${r} => ${t}`),t):r))}},JN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{EO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO(e.fmtp.config);t.setIfMissing("sps-pps-idr-in-keyframe","1"),e.fmtp.config=t.toString()}}))}))}},YN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{EO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO(e.fmtp.config);t.removeIfPresent("sps-pps-idr-in-keyframe"),e.fmtp.config=t.toString()}}))}))}},QN=class{constructor(e){this.configProvider=e}modify(e){const t=(e.groups||[]).findIndex((e=>"BUNDLE"===e.type)),i=e.groups?e.groups[t]:void 0;i&&(this.configProvider.mediaConfig.isTransportUnbundled?(i.mids=this.createBundleFromMedia(yL(e,Gi.MEDIA_TYPE.video)),i.mids||e.groups.splice(t,1)):i.mids=this.createBundleFromMedia(yL(e)))}createBundleFromMedia(e){return e.map((e=>e.mid?.toString())).filter((e=>e)).join(" ")}},ZN=class{modify(e){e.media.forEach((e=>{NO(e)&&e.bundleOnly&&(e.port=9,delete e.invalid)}))}},XN=class{constructor(e,t){this.configProvider=e,this.mediaManager=t}modify(e){if(!this.configProvider.mediaConfig.isTransportUnbundled&&!e.groups?.find((e=>"BUNDLE"===e.type))){let t=!1;if(e.media.forEach(((e,i)=>{const n=this.mediaManager.getMediaEntities()[i];!t&&n.isEnabled()?(e.mid=n.getMid(),t=!0):(n.disable(),e.port=0)})),t){e.groups||(e.groups=[]);const t={type:"BUNDLE"};e.groups.push(t)}}}},eL=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){e.media.forEach((e=>{const t=!!e.candidates;if(e.candidates&&(e.candidates=e.candidates.filter((e=>{let t=!0,i=!0,n=!0;return this.configProvider.config.iceCandidateType&&(t=!!e.type.match(new RegExp(this.configProvider.config.iceCandidateType,"i"))),this.configProvider.config.iceCandidateTransport&&(i=!!e.transport.match(new RegExp(this.configProvider.config.iceCandidateTransport,"i"))),this.configProvider.config.iceCandidateFilterMDns&&(n=!this.isMdns(e.ip),n||this.logger.safe.info(`Filtering out mDNS candidate ${De(e.ip)}:${De(e.port)}`)),t&&i&&n}))),t&&e.connection&&this.configProvider.config.iceCandidateFilterMDns&&(e.candidates&&0!==e.candidates.length||(e.candidates=[CL(e.port)]),this.isMdns(e.connection.ip)||!this.hasMatchingCandidate(e))){const t=this.getDefaultCandidate(e);e.connection.ip=t.ip,e.port=t.port}}))}hasMatchingCandidate(e){const t=e.connection;return t&&!!e.candidates.find(this.createIpAndPortMatcher(t.ip,e.port))}getDefaultCandidate(e){return e.candidates.slice().sort(((e,t)=>e.type===t.type?0:"host"===e.type||"relay"===t.type?1:"relay"===e.type||"host"===t.type?-1:0))[0]}isMdns(e){return e.indexOf(".local")>-1||e.indexOf(".encrypted")>-1}createIpAndPortMatcher(e,t){return i=>i.ip===e&&i.port===t}},tL=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.useOneRelayCandidateForRemoteSDP&&e.media.forEach((e=>{if(e.candidates){const t=e.candidates.filter((e=>!!e.type.match(new RegExp("relay","i"))));t.length>0&&(e.candidates=t.slice(0,1))}}))}},iL=class{modify(e){const t=yL(e)[0];t&&(t.candidates=[CL()])}},nL=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){e.media.forEach(((e,t)=>{this.fromMsSdp(e,t)}))}fromMsSdp(e,t){if(NO(e)||e.rids&&e.simulcast)return;const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n?.shouldBeEnabledInRemoteDesc()&&(n.enableInRemoteDesc(),e.simulcast={dir1:"recv",list1:this.configProvider.config.specCompliantSimulcast?.disableTilde?n.ridList.map((e=>`${e}`)).join(";"):n.ridList.map((e=>`${n.activeRids.includes(e)?"":"~"}${e}`)).join(";")},e.rids=n.ridList.map((e=>({id:e,direction:"recv"}))))}},rL=class{constructor(e,t){this.mediaManager=e,this.logger=t}modify(e){e.media.forEach(((e,t)=>{this.toMsSdp(e,t)}))}toMsSdp(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n&&(n.localDescriptionIsApplied(),n.shouldBeEnabledInLocalDesc()&&(n.enableInLocalDesc(),this.removeSimulcastEnvelope(e),this.addStreamSsrc(e,i.getLocalSsrc())))}removeSimulcastEnvelope(e){e.rids&&delete e.rids,e.simulcast&&delete e.simulcast}addStreamSsrc(e,t){if(!t)return;if(e.ssrcs)return void this.logger.safe.debug(`Media mid: ${e.mid} already contains ssrc: ${JSON.stringify(e.ssrcs)}`);const i=t;this.setSsrc(e,i)}setSsrc(e,t){e.ssrcs=[{id:t,attribute:"fake_attribute",value:"fake_value"}]}},sL=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i?.getLocalTrackId();(!e.msid&&i?.getSimulcastContext()?.shouldUseSimulcast()&&n||i?.getExtension("reinviteless"))&&(e.msid=`- ${n??t}`)}))}},aL=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){const t=this.mediaManager.getMediaEntities(),i=(0,FO.flatMap)(t,(e=>e.getRtpHeaderExtensions())),n=i.find((e=>"vla"===e?.headerType))?.value,r=i.find((e=>"non-adv-vla"===e?.headerType))?.value,s=n??r??(0,FO.flatMap)(e.media,(e=>e.ext||[])).find((e=>e.uri===Gi.VLA.EXT_URI))?.value,a=function(e,t,i,n=!1){const r=(0,FO.flatMap)(e.media,(e=>e.ext||[])).map((e=>e.value));if(0===r.length)return i;if(n&&!r.includes(i))return i;let s;for(let e=2;e<=14;e++)if(!r.includes(e)){s=e;break}return!s&&t&&(s=Math.max(...r)+1),s}(e,this.configProvider.config.extmapAllowMixed,Gi.VLA.DEFAULT_VALUE);e.media.forEach(((e,i)=>{const n=RO(e);if(!this.configProvider.config.enableVla||"Video"!==n&&"ScreenShare"!==n)return;if(e.ext?.find((e=>e.uri===Gi.VLA.EXT_URI)))return;const r=t[i]?.getRtpHeaderExtensions(),o=r?r.find((e=>"vla"===e.headerType))?.value??r.find((e=>"non-adv-vla"===e.headerType))?.value:s??a;o&&(e.ext=e.ext||[],e.ext.push({value:o,uri:Gi.VLA.EXT_URI}))}))}},oL=class{constructor(e){this.configProvider=e}modify(e){e.media.forEach((e=>{const t=RO(e);if(this.configProvider.config.allowRemoteVla&&("Video"===t||"ScreenShare"===t))return;const i=e.ext?.findIndex((e=>e.uri===Gi.VLA.EXT_URI));i>-1&&e.ext.splice(i,1)}))}},lL=class{constructor(e){this.configProvider=e}modify(e,t,i){e.media.forEach((e=>{const n=RO(e);if(!this.configProvider.config.enableNonAdvVla||"Video"!==n&&"ScreenShare"!==n||e.ext?.find((e=>e.uri===i)))return;const r=e.ext?.find((e=>e.uri===t));r&&(r.uri=i)}))}},cL=class extends lL{constructor(e,t){super(e),this.mediaManager=t}modify(e){const t=this.mediaManager.getMediaEntities();(0,FO.flatMap)(t,(e=>e.getRtpHeaderExtensions())).some((e=>"vla"===e?.headerType))||super.modify(e,Gi.VLA.EXT_URI,Gi.VLA.EXT_URI_NON_ADV)}},dL=class extends lL{constructor(e){super(e)}modify(e){super.modify(e,Gi.VLA.EXT_URI_NON_ADV,Gi.VLA.EXT_URI)}},uL=class{modify(e){e.media.forEach((e=>{e.ext?.forEach((e=>e.uri=this.normalizeSlashesInUri(e.uri)))}))}normalizeSlashesInUri(e){return e.replace(/\\/g,"/")}},hL=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.fixSdpForPartialIceRestart){const[{iceUfrag:t,icePwd:i}={}]=e.media;void 0!==t&&void 0!==i&&e.media.forEach((e=>{e.iceUfrag=t,e.icePwd=i}))}}},gL=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.reduceRtcpFbInSdp?.length)for(const t of yL(e,Gi.MEDIA_TYPE.video))t.rtcpFb=t.rtcpFb&&this.getFbList(t.rtcpFb)}getFbList(e){const t=[],i=[];for(const n of e){const e=n.subtype?`${n.type}/${n.subtype}`:`${n.type}`;t.includes(e)||(this.configProvider.config.reduceRtcpFbInSdp.includes(e)?(t.push(e),i.push({...n,payload:"*"})):i.push(n))}return i}},pL=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.redReceiveEnabled)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));let i=0;TO(t,{codec:"opus",rate:48e3,encoding:2},(e=>{i=e.rtp.payload}));const n={codec:"RED",rate:8e3};TO(t,n,(e=>{e.rtp.rate=48e3,e.rtp.encoding=2,i&&(e.fmtp={payload:e.rtp.payload,config:`${i}/${i}`})})),_O(t,n)}},mL=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.redReceiveEnabled&&TO(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"red",rate:48e3,encoding:2},(e=>{e.rtp.codec="RED",e.rtp.rate=8e3,delete e.rtp.encoding}))}},fL=class{constructor(e,t){this.configProvider=e,this.sdpType=t}modify(e){if(!this.configProvider.config.redReceiveEnabled||"offer"!==this.sdpType)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i={codec:"red",rate:48e3,encoding:2};let n=0;if(TO(t,i,(e=>{n=e.rtp.payload})),n===Gi.PAYLOAD_TYPE.MSRTC_RED)return;const r=CO(e);-1!==r&&(EL(e,Gi.PAYLOAD_TYPE.MSRTC_RED,r),TO(t,i,(e=>{e.rtp.payload=Gi.PAYLOAD_TYPE.MSRTC_RED})))}},vL=class{constructor(e,t){this.modification=e,this.context=t,this.logger=t.getLogger().createChild("IncomingDtlsRoleModifier")}modify(e){if("answer"!==this.modification.sdpType)if("offer"===this.modification.sdpType&&2===this.modification.sdpSource){if(this.modification.isOrWasProvisional){const t=this.context.config.isPstnCall?this.context.configProvider.config.createProvisionalAnswer.dtlsRolePstn:this.context.configProvider.config.createProvisionalAnswer.dtlsRole;if(!t)return;this.logger.debug(`Configured DTLS role override: ${t}`),e.media.forEach(((e,i)=>{const n=e.setup;"inactive"!==e.direction&&(n&&"actpass"!==n?this.logger.warn(`Remote DTLS role is ${n}, cannot change`):(e.setup=t,this.logger.debug(`Remote DTLS role changed from ${n} to ${e.setup} for mid=${e.mid}`)))}))}}else this.logger.error(`Tried to apply invalid change to DTLS role: ${this.modification.sdpType} ${this.modification.sdpSource}`)}};function SL(e,t,i,n){const r={type:e,port:0,label:t,payloads:e===Gi.MEDIA_TYPE.dataChannel||e===Gi.MEDIA_TYPE.data?Gi.PAYLOAD_TYPE.DATA_CHANNEL:"36",protocol:i,connection:{ip:"10.10.10.10",version:4}};return n&&(r.mid=n),r}function yL(e,t=null){return e.media.filter((e=>!(NO(e)||t&&e.type!==t)))}function CL(e=1234){return{component:1,ip:"10.10.10.10",foundation:"1755259772",priority:2122197247,port:9!==e?e:1234,transport:"UDP",type:"host"}}function TL(e,t){if(!tf[e]?.[t])throw`unsupported codec ${e} or type ${t}`;const i=tf[e][t];return{codec:i.NAME,rate:i.RATE,encoding:i.ENCODING,payload:tf[e].PT}}function EL(e,t,i){for(const n of e.media)yO(n,t,i)}function bL(e,t,i,n,r){const s=new Set;return EO(e,t,(e=>{e.rtp.payload<96&&(s.add(e.rtp.payload),e.rtp.payload=i[r]??e.rtp.payload,r++)}),n),s}var _L=class e{constructor(e,t,i,n){this.context=e,this.sessionType=t,this.sdp=i,this.remote=n,this.mediaManager=this.context.mediaManager,this.sdpTransform=this.context.sdpTransform,this.logger=this.context.logger.createChild("SessionDescr"),this.sdpModel=mO.parse(this.sdp),n&&new qN(this.context.configProvider).modify(this.sdpModel),this.sdpModel.media.forEach((e=>{(0,pO.isUndefined)(e.mid)||(e.mid=e.mid.toString())})),this.remote&&!this.context.configProvider.config.disableMsSdp&&new sN(e,this.mediaManager,t).modify(this.sdpModel)}getSdp(){return mO.write(this.sdpModel)}clone(){return new e(this.context,this.sessionType,this.sdp,this.remote)}getModalities(){return this.modalities||kO(this.sdpModel)}updateModalities(e){this.logger.debug("updateModalities",e),this.modalities=e}getSrtpInfo(){return im(this.sdpModel)}getVideoCodecs(){const e={};return this.sdpModel.media.forEach((t=>{"video"===t.type&&t.rtp.map((e=>e.codec.toLowerCase())).forEach((t=>e[t]=!0))})),Object.keys(e)}usePrimaryAudioCodecOnly(e){new HN(e).modify(this.sdpModel)}isCodecSwitchSupported(){return!this.sdpModel.media.some((e=>e.type===Gi.MEDIA_TYPE.audio&&e.xMediaSettings&&this.containsMediaSetting(e.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 e="offer"===this.sessionType;return new eL(this.context.configProvider,this.logger).modify(this.sdpModel),(new ZN).modify(this.sdpModel),e&&this.mediaManager.isEmpty()&&this.mediaManager.fromOffer(this.sdpModel,this.modalities),this.mediaManager.syncModalities(this.sdpModel,this.modalities,!e),this.sdpModel=e?this.sdpTransform.toOffer(this.sdpModel,this.mediaManager,this.modalities):this.sdpTransform.toAnswer(this.sdpModel,this.mediaManager,this.modalities),this.context.configProvider.config.disableMsSdp||new rN(this.context,this.mediaManager,this.sessionType).modify(this.sdpModel),new jN(this.mediaManager,this.context.configProvider).modify(this.sdpModel),this.modalities=kO(this.sdpModel),this.getSdp()}setModalities(e){this.modalities=e,this.mediaManager.fromRemote(this.sdpModel,this.modalities)}toRemote(e=!1){return this.sdpModel=this.sdpTransform.toRemote(this.sdpModel,this.mediaManager,this.modalities,this.sessionType,e),this.getSdp()}getVideoRecvCapabilities(){return LO(this.getMediaByLabel(Gi.MEDIA_LABEL.video))}getSharingRecvCapabilities(){return LO(this.getMediaByLabel(Gi.MEDIA_LABEL.sharing))}getMediaByType(e){return this.sdpModel.media.find((t=>t.type===e))}isUnbundled(){const e=this.sdpModel.groups?.find((e=>"BUNDLE"===e.type)),t=this.sdpModel.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=this.sdpModel.media.find((e=>e.type===Gi.MEDIA_TYPE.video));return e?!e.mids.toString().split(" ").find((e=>e===t.mid)):!!i}couldBeUnbundled(){return!this.sdpModel.groups?.find((e=>"BUNDLE"===e.type))||this.hasUnbundledIceCandidates()}containsMediaSetting(e,t){return e.some((e=>-1!==e.settings.indexOf(t)))}getMediaByLabel(e){return this.sdpModel.media.find((t=>t.label===e))}hasIceCandidatesForMediaType(e,t=""){const i=this.sdpModel.media?this.sdpModel.media.filter((t=>t.type===e&&!!t.candidates&&0!==t.candidates.length)):[];return t?i.some((e=>!!e.candidates&&e.candidates.some((e=>e.type===t)))):!!i.length}hasIceCandidates(){return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio)||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video)}hasRelayIceCandidates(){return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio,"relay")||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video,"relay")}hasUnbundledIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Gi.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio)&&(!e.length||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video))}hasUnbundledRelayIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Gi.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio,"relay")&&(!e.length||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video,"relay"))}isIceRestart(){return this.mediaManager.getMediaEntities().some((e=>e.getExtension("iceRestart")))}isMSRTC(){return!!this.sdpModel.xMediaBw}insertFakeCandidateIfNeeded(){return!this.hasIceCandidates()&&((new iL).modify(this.sdpModel),!0)}forceRecvonly(){(new lN).modify(this.sdpModel)}getBweType(){const e=this.sdpModel.media.find((e=>0!==e.port&&e.type===Gi.MEDIA_TYPE.video));if(!e)return"Unknown";const t=e.ext?.find((e=>e.uri===Gi.TRANSPORT_CC.EXT_URI||e.uri===Gi.TRANSPORT_CC.MSSDP_ENCODED_URI));return t?"SSBWE":"REMB"}fixDataModality(){new uN(this.mediaManager).modify(this.sdpModel)}getPayloadsForMedia(e){const t=this.sdpModel.media.find((t=>t.type===e&&0!==t.port));return t?.rtp??[]}},IL=class{constructor(e){this.context=e}createLocalOffer(e){return new _L(this.context,"offer",e)}createRemoteOffer(e){return new _L(this.context,"offer",e,!0)}createLocalAnswer(e){return new _L(this.context,"answer",e)}createRemoteAnswer(e){return new _L(this.context,"answer",e,!0)}},wL=class{static build(e){return new IL(e=e||{})}};function AL(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var PL=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(e){"host"===e.type&&"udp"===e.protocol?this.setIPAddressInfo(e.ip):"srflx"===e.type&&this.setReflexiveLocalIP(e.ip)}setOfferedModalities(e){this.offeredModalities=e,this.activeModalities=e}setNegotiatedModalities(e){this.negotiatedModalities=e,this.activeModalities=e}setNegotiatedSrtpInfo(e){this.info.NegotiatedSrtp=AL(e)}setOfferedSrtpInfo(e){this.info.OfferedSrtp=AL(e)}setIceConnectionState(e){this.info.IceConnectionStatePrevious=this.info.IceConnectionState,this.info.IceConnectionState=e}setSignalingConnectionState(e){this.info.SignalingStatePrevious=this.info.SignalingState,this.info.SignalingState=e}setRelayCandidateInfo(e){this.info.RelayCandidate=JSON.stringify(e)}fillExtensionInfo(e){!function(e,t){for(const i in t)t.hasOwnProperty(i)&&(e[i]=t[i])}(e,this.info)}setIceTransportPolicy(e){this.info.IceTransportPolicy=e}setIceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.info.IceServers=JSON.stringify(t)}setFakeIceCandidate(e){this.info.FakeIceCandidate=e}setBweType(e){"Unknown"!==e&&(this.info.BweType=e)}setSdpSemantics(e){this.info.SdpSemantics=e}setBundlePolicy(e){this.info.BundlePolicy=e}setEncodedStreamWorkerLoaded(e){this.info.EncodedStreamWorker=e}setAudioCodecEvents(e){this.info.AudioCodecEvents=JSON.stringify(e)}setIPAddressInfo(e){this.info.NumberOfInterfaces+=1,"none"===this.info.IPAddress&&(this.info.IPAddress=e)}setReflexiveLocalIP(e){"none"===this.info.ReflexiveLocalIP&&(this.info.ReflexiveLocalIP=e)}},RL=class{constructor(){this.presentationAPIUserDuration=0,this.presentationAudioDuration=0,this.isActiveScreenSharing=!1}handleInputLevel(e,t){this.isActiveScreenSharing&&("ScreenShare"===e&&t>0&&(this.presentationAPIUserDuration+=Gi.TIME_INTERVAL.SEC_1),"Audio"===e&&t>0&&(this.presentationAudioDuration+=Gi.TIME_INTERVAL.SEC_1))}updateScreenSharingStream(e,t){"ScreenShare"===t&&(this.isActiveScreenSharing=!!e)}getPresentationAudioDuration(){return this.presentationAudioDuration}getPresentationAudioAPIUserDuration(){return this.presentationAPIUserDuration}},ML=class e{constructor(e){this.name=e,this.sharedState={mark:new Map,measure:[]}}mark(e,t){const i=_n();this.sharedState.mark.set(e,{name:e,ts:i,startTime:mn(In+i),details:t})}measure(e,t){const i=this.sharedState.mark.get(t.start),n=this.sharedState.mark.get(t.end);if(i&&n){const r={...t,parentName:this.name===e?"":this.name};this.sharedState.measure.push({name:e,details:r,duration:mn(n.ts-i.ts),startTime:i.startTime})}}markAndMeasure(e,t,i,n){!1===this.sharedState.mark.has(t)&&this.mark(t,i);const r=this.sharedState.mark.get(e),s=this.sharedState.mark.get(t);if(r&&s){const e={...n,parentName:this.name===t?"":this.name};this.sharedState.measure.push({name:t,details:e,duration:mn(s.ts-r.ts),startTime:r.startTime})}}clone(t){const i=new e(`${this.name}|${t}`);return i.setSharedState(this.sharedState),i}setSharedState(e){this.sharedState=e}getReport(){return this.sharedState.measure.map((e=>({name:e.name,duration:e.duration,ts:e.startTime,parentName:e.details.parentName})))}},DL=class e{mark(){}measure(){}markAndMeasure(){}clone(){return new e}getReport(){return[]}},kL=class{constructor(e){this.enableTimerTracker=e,this.timerTrackers={},this.timerTrackerOptions={}}getTimerTracker(e,t){if(!this.enableTimerTracker)return new DL;const i=new ML(e);if(this.timerTrackers[e]){const t=this.timerTrackerOptions[e];if(t?.first)return new DL;t?.last&&(this.timerTrackers[e]=[i]),t?.all&&this.timerTrackers[e].push(i)}else this.timerTrackers[e]=[i],this.timerTrackerOptions[e]=t;return i}getReport(){if(this.enableTimerTracker)return Object.keys(this.timerTrackers).reduce(((e,t)=>{const i=this.timerTrackerOptions[t];return(i.first||i.last)&&(e[t]=[this.timerTrackers[t][0]?.getReport()]),i.all&&(e[t]=Object.values(this.timerTrackers[t]).map((e=>e?.getReport()))),e}),{})}},OL=class{constructor(e,t){this.configProvider=e,this.sessionInfo=t,this.data={fakeCandidate:!1,bweType:"Unknown",offeredSrtp:"unknown",negotiatedSrtp:"unknown",callSetupTimeReport:{}},this.timerTrackerManager=new kL(this.configProvider.config.enableTimerTracker),yn(this.data,{callSetupTimeReport:()=>this.timerTrackerManager.getReport()})}getTimerTracker(e,t){return this.timerTrackerManager.getTimerTracker(e,t)}set offeredModalities(e){this.data.offeredModalities=e,this.data.activeModalities=e,this.sessionInfo.setOfferedModalities(e)}set negotiatedModalities(e){this.data.negotiatedModalities=e,this.data.activeModalities=e,this.sessionInfo.setNegotiatedModalities(e)}set fakeCandidate(e){var t;(t=this.data).fakeCandidate||(t.fakeCandidate=e),this.sessionInfo.setFakeIceCandidate(e)}set bweType(e){this.data.bweType=e,this.sessionInfo.setBweType(e)}set negotiatedSrtp(e){this.data.negotiatedSrtp=NL(e),this.sessionInfo.setNegotiatedSrtpInfo(e)}set offeredSrtp(e){this.data.offeredSrtp=NL(e),this.sessionInfo.setOfferedSrtpInfo(e)}set meetingScenario(e){this.data.meetingScenario=e}set isTownHall(e){this.data.isTownHall=e}getObjectRef(){return this.data}};function NL(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var LL=class{constructor(e){this.data=e,this.reopenRequestDeviceIds=new Set}registerReopenRequest(e){this.reopenRequestDeviceIds.has(e)||(this.data.sinkNumOfReopenRequests++,this.reopenRequestDeviceIds.add(e))}registerSuccessfullReopen(e){this.reopenRequestDeviceIds.has(e)&&(this.data.sinkNumOfSuccessfulReopens++,this.reopenRequestDeviceIds.delete(e))}getObjectRef(){return this.data}},xL=class{constructor(e){this.configProvider=e,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={},yn(this.data,{scheduledCallbacks:()=>this.scheduledCallbacks.values(),timers:()=>{const e={};for(const t of Object.keys(this.stateTrackers))e[t]=this.stateTrackers[t].durations;return e}})}dispose(){for(const e of Object.values(this.stateTrackers))e.dispose()}set hasConnectionState(e){this.data.hasConnectionState=e}set transportState(e){this.data.transportStatePrevious=this.data.transportState,this.data.transportState=e,this.addStateEvent("transport",this.data.transportStatePrevious,this.data.transportState)}set signalingState(e){this.data.signalingStatePrevious=this.data.signalingState,this.data.signalingState=e,this.addStateEvent("signaling",this.data.signalingStatePrevious,this.data.signalingState)}set iceConnectionState(e){this.data.iceConnectionStatePrevious=this.data.iceConnectionState,this.data.iceConnectionState=e,this.addStateEvent("ice",this.data.iceConnectionStatePrevious,this.data.iceConnectionState)}set connectionState(e){this.data.connectionStatePrevious=this.data.connectionState,this.data.connectionState=e,this.addStateEvent("connection",this.data.connectionStatePrevious,this.data.connectionState)}set dtlsTransportState(e){this.data.dtlsTtransportStatePrevious=this.data.dtlsTransportState,this.data.dtlsTransportState=e,this.addStateEvent("dtlsTransport",this.data.dtlsTtransportStatePrevious,this.data.dtlsTransportState)}set provisional(e){this.addStateEvent("provisional",`${this.data.isProvisional}`,`${e}`),this.data.isProvisional=e}scheduleDoOnConnected(e,t,i,n){this.scheduledCallbacks.set(e,`${t}: ${i?"p":""}${n?"n":""}`),this.addCallbackEvent(t,i,n),this.data.numCallbacksScheduled++}runDoOnConnected(e,t=!1){this.scheduledCallbacks.get(e)&&this.scheduledCallbacks.delete(e),this.data.numCallbacksExecuted++,t&&this.data.numCallbacksExecutedImmediately++}getObjectRef(){return this.data}addCallbackEvent(e,t,i){rt(this.data.events,{evType:"callback",timestamp:Date.now(),logName:e,allowProvisional:t,mayRunImmediately:i},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents)}addStateEvent(e,t,i){rt(this.data.events,{evType:"stateChanged",timestamp:Date.now(),changedState:e,previous:t,current:i},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents);const n=this.stateTrackers[e]??new FL;n.state=i,this.stateTrackers[e]=n}},FL=class{constructor(){this.stopwatches={}}set state(e){if(this.stateInternal===e)return;this.running?.stop();const t=this.stopwatches[e]??new GL;this.stopwatches[e]=t,t.start(),this.running=t,this.stateInternal=e}get durations(){const e={};for(const t in this.stopwatches){const i=this.stopwatches[t];e[t]=i.elapsed}return e}dispose(){this.running?.stop(),this.running=void 0}},UL=/profile-level-id=(.{6})/,BL=class{constructor(e,t,i=()=>{},n=()=>this,r=()=>{},s=new sO,a){this.configProvider=e,this.dmDiagnostics=t,this.addSessionStatsError=i,this.newNativeSession=n,this.commitNativeSession=r,this.dshDiagnostics=s,this.getSessionRef=a,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 RL,yn(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(e){this.bandwidthStatsRef=e}get callIsMuted(){return this.getSessionRef?.().callIsMuted}get sharingAudioLevel(){return this.analyzerSharing?.getInputLevelNormalized()}set relayCandidateInfo(e){this.data.relayCandidate=JSON.stringify(e)}set iceTransportPolicy(e){this.data.iceTransportPolicy=e}set reinvitelessContext(e){this.data.reinvitelessContext=e}set iceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.data.iceServers=JSON.stringify(t)}set sdpSemantics(e){this.data.sdpSemantics=e}set isCodecsSupported(e){this.data.codecSupport=e}set bundlePolicy(e){this.data.bundlePolicy=e}set latestRawReport(e){this.data.latestRawReport=e}set recvVideoStreamsCount(e){this.data.recvVideoStreamCount=e}set aggregatedStatsRef(e){this.data.aggregatedModalityStats=e}set multiViewStats(e){this.data.multiViewStats=e}set videoCapabilities(e){if(!e?.codecs)return;const t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=UL.exec(e.sdpFmtpLine)?.[1];i&&t.push(i)}})),this.data.H264Profiles=[...new Set(this.data.H264Profiles.concat(t))]}setSupportedH264Profiles(e,t){if(!e?.codecs&&!t?.codecs)return;const i=e=>{const t=[];return e.codecs?.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=UL.exec(e.sdpFmtpLine)?.[1];i&&!t.includes(i)&&t.push(i)}})),t};this.data.h264CodecCapabilities.sendProfiles=i(e),this.data.h264CodecCapabilities.receiveProfiles=i(t)}set sentBWSeed(e){var t;(t=this.data).initialBWSeed??(t.initialBWSeed=e),this.data.sentBWSeed=e}reportedSendBandwidthLayouts(e){rt(this.data.reportedSendBandwidthLayouts,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}set maxSessionBandwidth(e){this.data.maxSessionBandwidth=e}set bwStabilizationTime(e){this.data.bwStabilizationTime=e}set bwDownlinkStabilizationTime(e){this.data.bwDownlinkStabilizationTime=e}set statsOnSubscribed(e){this.data.statsOnSubscribed=e}set loopIntervalMax(e){this.data.loopIntervalMax=e}set loopIntervalMedian(e){this.data.loopIntervalMedian=e}set fetchTimeMax(e){this.data.fetchTimeMax=e}set fetchTimeMedian(e){this.data.fetchTimeMedian=e}set simulcastReport(e){this.data.simulcast=e}setTotalVideoRecvMblocksRates(e){this.data.totalVideoRecvMblocksRates=e}set dataChannelSessionState(e){this.data.dataChannelSessionState=e}set createChannelFailReason(e){this.data.dataChannelCreationError=e}setCandidateDetails(e){"host"===e.type&&"udp"===e.protocol?(this.data.numInterfaces++,this.data.IPAddress||(this.data.IPAddress=e.ip)):"srflx"!==e.type||this.data.reflexiveLocalIP||(this.data.reflexiveLocalIP=e.ip)}setAudioSendStream(e,t){if(this.configProvider.config.useAudioAnalyzer){const i=new zk(e.rawStream);"ScreenShare"===t&&e.hasAudio()?(this.analyzerSharing?.dispose(),this.analyzerSharing=i):"Audio"===t&&(this.analyzer?.dispose(),this.analyzer=i)}}addNetworkInfo(e){rt(this.data.networkInfo,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addIceCandidateError(e){this.data.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.data.iceCandidateErrors=[]}registerEarlyMediaPoll(){this.data.earlyMediaNumStatsPolls++}addReportedReceiveBandwidth(e){rt(this.data.reportedReceiveBandwidth,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addOvcSubscriptionReport(e,t,i){const n=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];n?.ovc.count!==e&&rt(this.data.ovcToSubscriptionEvents,{ovc:{ts:Date.now(),count:e,subsCount:t,...i},subs:[]},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addSubscriptionToOvcEvent(e){const t=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];t&&rt(t.subs,{ts:Date.now(),count:e},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addStatsReport(e){rt(this.data.statsReports,e,this.configProvider.config.diagnostics.collectionLimits.numStatsReports)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));i?i.count++:rt(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors),this.addSessionStatsError(`nativeSession:${e}`,t)}setPresentationAudioOnScreenSharing(e,t){this.presentationAudioTelemetry.updateScreenSharingStream(e,t)}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 e=new uO(this.configProvider,((e,t)=>this.addStatsError(`qualityManagerDiagnostics:${e}`,t)));return this.data.qualityManager=e.getObjectRef(),e}newRemoteVideoManagerDiagnostics(){const e=new hO(this.configProvider);return this.data.remoteVideoManager=e.getObjectRef(),e}newNegotiationDiagnostics(e){const t=new OL(this.configProvider,e);return this.data.negotiation=t.getObjectRef(),t}newSubscriptionManagerDiagnostics(){const e=new dO(this.configProvider,(e=>this.addStatsError("subscriptionManagerDiagnostics",e)));return this.data.subscriptionManager=e.getObjectRef(),e}newDataChannelDiagnostics(e){const t=new Jg(e);return this.data.dataChannel=t.getObjectRef(),t}newTransportStateDiagnostics(){const e=new xL(this.configProvider);return this.data.transportState=e.getObjectRef(),e}set encodedStreamWorker(e){this.data.encodedStreamWorker=e}set audioCodecEvents(e){this.data.audioCodecEvents=e}getObjectRef(){return this.data}registerVideoPerformanceEvent(e,t,i){const n={type:t,perfEvent:e,resRequestEvent:null,resChangedEvent:[],perfConstrainedOvc:i};rt(this.data.videoPerformanceEvent,n,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}registerLocalVideoPerformanceEvent(e){rt(this.data.localVideoPerformanceEvents,{timestamp:Date.now(),description:e.description,activeModalities:e.activeModalities,isTransient:e.isTransient},this.configProvider.config.diagnostics.collectionLimits.numPerformanceEvents)}registerResolutionChangeRequest(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];t&&(t.resRequestEvent=e)}registerResolutionChangeEvent(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];e.ts-t?.resRequestEvent?.ts<this.configProvider.config.diagnostics.performanceMonitoring.telemetryResolutionRequestSpanMs&&t.resChangedEvent.push(e)}set contributingSourcesError(e){this.data.contributingSourcesError=e}newAudioRendererDiagnostics(){return this.data.audioRenderer=this.getSessionRef?.().audioRenderer,this.data.audioRenderer?new LL(this.data.audioRenderer):null}},VL=Symbol("sessionDiagnosticsRef"),HL=class{constructor(e,t,i,n,r,s,a){this.logger=e,this.configProvider=t,this.diagnosticsReport=i,this.dmDiagnostics=n,this.ufdDiagnostics=r,this.dshDiagnostics=new sO,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:[],remoteUfdsCount:{},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,ufdManager:void 0,relayTimers:void 0,authTokenFetcherStats:void 0,dominantSpeaker:this.dshDiagnostics.getObjectRef(),[VL]:this,callConstraints:[],audioRenderer:{sinkNumOfReopenRequests:0,sinkNumOfSuccessfulReopens:0},elevation:[],batteryLevel:void 0},this.transportDisconnected=!1,this.commonMuteTracker=new GL,this.swMuteTracker=new GL,this.osMuteTracker=new GL,this.speakerMuteTracker=new GL,this.hwSilentTracker=new GL,this.isSpeakingTracker=new GL,this.networkRecvTracker=new qL,this.networkSendTracker=new qL,this.zeroCaptureTracker=new qL,this.zeroRenderTracker=new qL,this.deviceRenderTracker=new qL,this.deviceCaptureTracker=new qL,this.rawMediaTimers={audio:{send:new GL,recv:new GL}},this.dmFragmenter=new jL(this.dmDiagnostics),this.ufdFragmenter=new $L(this.ufdDiagnostics),this.durationTimer=new GL,this.data.callNumber=s,this.data.sessionId=a,this.durationTimer.start(),yn(this.data,{isOngoing:()=>void 0===this.data.terminationTime,duration:()=>this.durationTimer.elapsed,callMutedRatio:()=>zL(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(),ufdManager:()=>this.ufdFragmenter.getFragment(this.ufdDiagnostics)}),yn(this.data.rawMedia.audio.recv,{durationRatio:()=>zL(this.rawMediaTimers.audio.recv.elapsed,this.data.duration)}),yn(this.data.rawMedia.audio.send,{durationRatio:()=>zL(this.rawMediaTimers.audio.send.elapsed,this.data.duration)})}get telemetryReport(){const e={type:"WebRtcMediaStats",data:this.diagnosticsReport.getSessionTelemetry(this.data.sessionId)},t={};return zi(e.data,((e,i,n)=>{let r=0;Hp.test(e)?(r=13,t[i]="IPv4"):$p.test(e)&&(r=4,t[i]="IPv6"),n[i]={type:r,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(t),__VALUE__:!0},e}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(e){this._relayManager=e}set isMultiParty(e){this.data.isMultiParty=e}set mediaLegId(e){this.data.mediaLegId=e.process()}set ETag(e){this.data.ETag=e}set configIds(e){this.data.configIds=e}set reconnect(e){this.data.reconnect=e}set relay(e){this.data.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}set sessionError(e){this.data.error=e}set dtmfResult(e){e?this.data.dtmfSuccessCount++:this.data.dtmfFailureCount++}set swMute(e){e?this.swMuteTracker.start():this.swMuteTracker.stop(),this.updateCommonMute()}set speakerMute(e){e?this.speakerMuteTracker.start():this.speakerMuteTracker.stop()}set hwSilent(e){e?this.hwSilentTracker.start():this.hwSilentTracker.stop()}set isSpeaking(e){e?this.isSpeakingTracker.start():this.isSpeakingTracker.stop()}set iceInitTime(e){this.data.iceInitTime||(this.data.iceInitTime=e)}set finalAnswerTime(e){this.data.finalAnswerTime||(this.data.finalAnswerTime=e)}set iceConnectedStateTimestamp(e){this.data.iceConnectedStateTime||(this.data.iceConnectedStateTime=e)}set allowedModalities(e){this.data.allowedAudioSend=e.audio.some((e=>Wp(e))),this.data.allowedVideoSend=e.video.some((e=>Wp(e))),this.data.allowedScreensharingSend=e.sharing.some((e=>Wp(e)))}negotiationStart(e){var t;(t=this.data).initialNegotiationType??(t.initialNegotiationType=e),this.data.negotiationCount++}negotiationCompleted(e){this.data.initialNegotiationCompleted=!0,this.data.activeModalities=e,this.data.error=void 0}negotiationRejected(){this.data.rejectedNegotiationCount++}registerRollbackEvent(e){this.data.rollbackNegotiation.push({type:e.type,attempt:this.data.rollbackNegotiation.length+1,error:e.error})}registerRawMediaAccess(e,t,i){const n=this.data.rawMedia[e]?.[t];if(n){n.numAttempts++;const r=this.rawMediaTimers[e]?.[t];i?r?.start():r?.stop()}}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.data.noIceCandidatesEventCount.good++:this.data.noIceCandidatesEventCount.bad++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.data.noRelayIceCandidatesEventCount.good++:this.data.noRelayIceCandidatesEventCount.bad++;break;case"DeviceCaptureNotFunctioning":this.deviceCaptureTracker.updateLevel(e.value),"Good"===e.value?this.data.microphoneInUseEventCount.good++:this.data.microphoneInUseEventCount.bad++;break;case"DeviceRenderNotFunctioning":this.deviceRenderTracker.updateLevel(e.value);break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.data.cameraInUseEventCount.good++:this.data.cameraInUseEventCount.bad++;break;case"DeviceCaptureMute":"Bad"===e.value?this.osMuteTracker.start():this.osMuteTracker.stop(),this.updateCommonMute();break;case"NetworkRecvQuality":this.networkRecvTracker.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSendTracker.updateLevel(e.value);break;case"ZeroCaptureDevicesEnumerated":this.zeroCaptureTracker.updateLevel(e.value);break;case"ZeroRenderDevicesEnumerated":this.zeroRenderTracker.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.data.cameraFreezeEventCount.end++:this.data.cameraFreezeEventCount.start++}"DeviceSpeakWhileMuted"!==e.type&&Sn(this.data.ufds,{...e,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRemoteQualityStateChangedEvent(e,t){e.forEach((e=>{var i,n,r;(i=this.data.remoteUfdsCount)[n=Rf(e)]??(i[n]={});const s=this.data.remoteUfdsCount[Rf(e)];s[r=e.value.toLowerCase()]??(s[r]=0),s[e.value.toLowerCase()]++,rt(this.data.remoteUfds,{...e,participantId:t,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(e){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=nn(e),this.data.terminationTime=Date.now(),this.durationTimer.stop(),this.dmFragmenter.terminated(this.dmDiagnostics),this.ufdFragmenter.terminated(this.ufdDiagnostics)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));this.logger.safe.error(`Stats error from '${e}': ${t} (${i?.count??1})`),i?i.count++:Sn(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}newNativeSessionDiag(e=!0){let t;return t=new BL(this.configProvider,this.dmDiagnostics,((e,t)=>this.addStatsError(e,t)),(e=>this.newNativeSessionDiag(e)),(()=>this.pushNativeSessionDiag(t.getObjectRef())),this.dshDiagnostics.resetState(),(()=>this.getObjectRef())),e&&Sn(this.data.webrtcSessions,t.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numNativeSessions),t}pushNativeSessionDiag(e){Sn(this.data.webrtcSessions,e,this.configProvider.config.diagnostics.collectionLimits.numNativeSessions)}getObjectRef(){return this.data}setBatteryLevel(e){this.data.batteryLevel=e}updateCommonMute(){this.swMuteTracker.isRunning||this.osMuteTracker.isRunning?this.commonMuteTracker.start():this.swMuteTracker.isRunning||this.osMuteTracker.isRunning||this.commonMuteTracker.stop()}registerElevation(e){rt(this.data.elevation,{event:e,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numElevation)}},$L=class{constructor(e){this.fragmentBase=nn(e)}getFragment(e){const t=this.fragmentTerminated??e,i={};for(const[e,n]of Object.entries(t.count))for(const[t,r]of Object.entries(n)){const n=this.fragmentBase.count[e]?this.fragmentBase.count[e][t]:void 0,s=n?r-n:r;s&&(i[e]??(i[e]={}),i[e][t]=s)}return{count:i}}terminated(e){this.fragmentTerminated=nn(e)}},jL=class{constructor(e){this.initTimestamp=Number.MIN_SAFE_INTEGER,this.terminatedTimestamp=Number.MAX_SAFE_INTEGER,this.fragmentBase=this.sanitizeDiagnostics(e),this.initTimestamp=Date.now()}getFragment(e){const t=this.fragmentTerminated??e;return{devicesChangeCount:t.devicesChangeCount-this.fragmentBase.devicesChangeCount,deviceSelectionChangeCount:t.deviceSelectionChangeCount-this.fragmentBase.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:t.deviceSelectionChangeCountFromInterface-this.fragmentBase.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:t.devicesPollChangeCount-this.fragmentBase.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:t.audioSourceNumOfSuccessfulReopens-this.fragmentBase.audioSourceNumOfSuccessfulReopens||void 0,audioSourceNumOfReopenRequests:t.audioSourceNumOfReopenRequests-this.fragmentBase.audioSourceNumOfReopenRequests||void 0,audioCaptureDeviceErrorFlag:e.audioCaptureDeviceErrorFlags.filter((e=>e.timestamp>this.initTimestamp&&e.timestamp<this.terminatedTimestamp)).reduce(((e,t)=>Number(BigInt(e)|BigInt(t.audioDeviceErrorFlag))),0),audioRenderDeviceErrorFlag:e.audioRenderDeviceErrorFlags.filter((e=>e.timestamp>this.initTimestamp&&e.timestamp<this.terminatedTimestamp)).reduce(((e,t)=>Number(BigInt(e)|BigInt(t.audioDeviceErrorFlag))),0)}}terminated(e){this.fragmentTerminated=this.sanitizeDiagnostics(e),this.terminatedTimestamp=Date.now()}sanitizeDiagnostics(e){return{devicesChangeCount:e.devicesChangeCount,deviceSelectionChangeCount:e.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:e.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:e.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:e.audioSourceNumOfSuccessfulReopens,audioSourceNumOfReopenRequests:e.audioSourceNumOfReopenRequests,audioCaptureDeviceErrorFlag:0,audioRenderDeviceErrorFlag:0}}},GL=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+_n()-this.startTime:this.elapsedInternal)}get count(){return this.countInternal}start(){this.startTime||(this.startTime=_n(),this.countInternal++)}stop(){this.startTime&&(this.elapsedInternal+=_n()-this.startTime,this.startTime=0)}},qL=class{constructor(){this.currentLevel="Good",this.stopWatches={},this.startTime=_n(),this.getStopWatch(this.currentLevel).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getRatio(e){return zL(this.getStopWatch(e).elapsed,Math.round((this.endTime||_n())-this.startTime))}dispose(e){this.getStopWatch(this.currentLevel).stop(),this.endTime=_n()}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new GL,this.stopWatches[e]=t),t}};function zL(e,t){return e/(t||1)}function WL(e,t,i){return rn({recv:rn({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytesReceived:Pn(e.audio?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Pn(e.audio?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Pn(e.audio?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:t?.codec?.mimeType.split("/").pop(),googTrackId:t?.track?.trackIdentifier,transport_id:t?.transport?.id,transportId:t?.inboundRTP.transportId,transport_selectedCandidatePairId:t?.transport?.selectedCandidatePairId,transport_dtlsCipher:t?.transport?.dtlsCipher,transport_srtpCipher:t?.transport?.srtpCipher,pair_id:t?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:t?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:t?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:t?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:t?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(e.audio?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:t?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:t?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:t?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:t?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:t?.transport?.selectedCandidatePair?.localCandidate?.ip??t?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:t?.transport?.selectedCandidatePair?.remoteCandidate?.ip??t?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:t?.transport?.selectedCandidatePair?.nominated}),send:rn({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytesSent:Pn(e.audio?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Pn(e.audio?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Pn(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:i?.codec?.mimeType.split("/").pop(),googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.outboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(e.audio?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated})})}function KL(e,t,i,n){return rn({recv:rn({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytesReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Pn(t[e]?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:i?.codec?.mimeType.split("/").pop(),codecImplementationName:i?.inboundRTP.decoderImplementation,googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.inboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(t[e]?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated,framesDecoded:Pn(t[e]?.recv,(e=>e.inboundRTP.framesDecoded)),googFrameHeightReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.frameHeight)),googFrameWidthReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.frameWidth)),googFrameRateReceived:Pn(t[e]?.recv,(e=>e.extensions?.frameRateReceived||0)),googNacksSent:Pn(t[e]?.recv,(e=>e.inboundRTP.nackCount)),googPlisSent:Pn(t[e]?.recv,(e=>e.inboundRTP.pliCount)),keyFramesDecoded:Pn(t[e]?.recv,(e=>e.inboundRTP.keyFramesDecoded)),googFirsSent:Pn(t[e]?.recv,(e=>e.inboundRTP.firCount)),googJitterBufferMs:Pn(t[e]?.recv,(e=>e.extensions?.jitterBufferMs)),googFrameRateDecoded:Pn(t[e]?.recv,(e=>e.extensions?.frameRateDecoded||0)),googFrameRateOutput:i?.extensions?.trackRecvFps,jitter:i?.inboundRTP.jitter}),send:rn({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytesSent:Pn(t[e]?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Pn(t[e]?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Pn(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:n?.codec?.mimeType.split("/").pop(),codecImplementationName:n?.outboundRTP.encoderImplementation,googTrackId:n?.track?.trackIdentifier,transport_id:n?.transport?.id,transportId:n?.outboundRTP.transportId,transport_selectedCandidatePairId:n?.transport?.selectedCandidatePairId,transport_dtlsCipher:n?.transport?.dtlsCipher,transport_srtpCipher:n?.transport?.srtpCipher,pair_id:n?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:n?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:n?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:n?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:n?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(t[e]?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:n?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:n?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:n?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:n?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:n?.transport?.selectedCandidatePair?.localCandidate?.ip??n?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:n?.transport?.selectedCandidatePair?.remoteCandidate?.ip??n?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:n?.transport?.selectedCandidatePair?.nominated,framesEncoded:Pn(t[e]?.send,(e=>e.outboundRTP.framesEncoded)),googNacksReceived:Pn(t[e]?.send,(e=>e.outboundRTP.nackCount)),googPlisReceived:Pn(t[e]?.send,(e=>e.outboundRTP.pliCount)),googFirsReceived:Pn(t[e]?.send,(e=>e.outboundRTP.firCount)),keyFramesEncoded:Pn(t[e]?.send,(e=>e.outboundRTP.keyFramesEncoded)),googFrameHeightInput:n?.mediaSource?.height,googFrameWidthInput:n?.mediaSource?.width,googFrameRateInput:Pn(t[e]?.send,(e=>e.mediaSource?.framesPerSecond)),googFrameHeightSent:Pn(t[e]?.send,(e=>e.outboundRTP.frameHeight)),googFrameWidthSent:Pn(t[e]?.send,(e=>e.outboundRTP.frameWidth)),googFrameRateSent:Pn(t[e]?.send,(e=>e.extensions?.frameRateSent)),googRtt:Pn(t[e]?.send,(e=>1e3*(e.remoteInboundRTP?.roundTripTime??0)),!0),hugeFramesSent:n?.outboundRTP.hugeFramesSent,qpSum:Pn(t[e]?.send,(e=>e.outboundRTP.qpSum)),qualityLimitationDurations:n?JSON.stringify(n?.outboundRTP.qualityLimitationDurations):void 0,qualityLimitationReason:n?.outboundRTP.qualityLimitationReason,qualityLimitationResolutionChanges:n?.outboundRTP.qualityLimitationResolutionChanges,jitter:n?.remoteInboundRTP?.jitter,retransmittedPacketsSent:Pn(t[e]?.send,(e=>e.outboundRTP.retransmittedPacketsSent))})})}var JL=e=>rn({id:e.outboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,rtt:e.remoteInboundRTP?.roundTripTime,frameRateInput:e.mediaSource?.framesPerSecond,frameWidthInput:e.mediaSource?.width,frameHeightInput:e.mediaSource?.height,framesEncoded:e.outboundRTP.framesEncoded,frameRateEncoded:e.extensions?.frameRateEncoded,framesSent:e.outboundRTP.framesSent,frameRateSent:e.extensions?.frameRateSent,frameWidthSent:e.outboundRTP.frameWidth,frameHeightSent:e.outboundRTP.frameHeight,keyFramesEncoded:e.outboundRTP.keyFramesEncoded,nackCount:e.outboundRTP.nackCount,firCount:e.outboundRTP.firCount,pliCount:e.outboundRTP.pliCount,transportId:e.outboundRTP.transportId,isFsOvershooting:e.extensions?.isFsOvershooting,isFpsOvershooting:e.extensions?.isFpsOvershooting,isBrOvershooting:e.extensions?.isBrOvershooting,totalFsOvershootDuration:e.extensions?.totalFsOvershootDuration,totalFpsOvershootDuration:e.extensions?.totalFpsOvershootDuration,totalBrOvershootDuration:e.extensions?.totalBrOvershootDuration,altLayouts:e.altLayouts?.map(JL)}),YL=e=>rn({id:e.inboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,msi:e.renderer?.msi,jitterBufferMs:e.extensions?.jitterBufferMs,frameRateOutput:e.extensions?.frameRateDecoded,frameRateDecoded:e.extensions?.frameRateDecoded,frameRateReceived:e.extensions?.frameRateReceived,frameWidthReceived:e.inboundRTP.frameWidth,frameHeightReceived:e.inboundRTP.frameHeight,longestFreezeDuration:e.extensions?.longestFreeze,totalFreezeDuration:e.extensions?.totalFreezeDuration,framesReceived:e.inboundRTP.framesReceived,framesDropped:e.inboundRTP.framesDropped,framesDecoded:e.inboundRTP.framesDecoded,keyFramesDecoded:e.inboundRTP.keyFramesDecoded,nackCount:e.inboundRTP.nackCount,firCount:e.inboundRTP.firCount,pliCount:e.inboundRTP.pliCount,transportId:e.inboundRTP.transportId}),QL=e=>rn({id:e.outboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.remoteInboundRTP?.packetsDiscarded,rtt:e.remoteInboundRTP?.roundTripTime,audioLevel:e.mediaSource?.audioLevel,transportId:e.outboundRTP.transportId}),ZL=e=>rn({id:e.inboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,jitterBufferMs:e.extensions?.jitterBufferMs,audioLevel:e.inboundRTP.audioLevel,healedRatio:e.extensions?.healedRatio,transportId:e.inboundRTP.transportId}),XL=e=>rn({id:e.id,state:e.state,dataChannelIdentifier:e.dataChannelIdentifier,messagesSent:e.messagesSent,bytesSent:e.bytesSent,messagesReceived:e.messagesReceived,bytesReceived:e.bytesReceived,sendBitrate:e.extensions?.sendBitrate,recvBitrate:e.extensions?.recvBitrate,messagesSentPerSecond:e.extensions?.sendMessageRate,messagesReceivedPerSecond:e.extensions?.recvMessageRate}),ex=e=>rn({id:e.id,rtt:e.selectedCandidatePair?.currentRoundTripTime,availableIncomingBitrate:e.selectedCandidatePair?.availableIncomingBitrate,availableOutgoingBitrate:e.selectedCandidatePair?.availableOutgoingBitrate,relayProtocol:e.selectedCandidatePair?.localCandidate?.relayProtocol,candidateType:`${e.selectedCandidatePair?.localCandidate?.candidateType??""}:${e.selectedCandidatePair?.remoteCandidate?.candidateType??""}`});function tx(e){return(e.audio?.send??[]).map(QL)}function ix(e){return(e.audio?.recv??[]).map(ZL)}function nx(e){return e.video?.send?.length?e.video.send.map(JL):[]}function rx(e){return(e.video?.recv??[]).map(YL)}function sx(e){return e.sharing?.send?.length?e.sharing.send.map(JL):[]}function ax(e){return(e.sharing?.recv??[]).map(YL)}function ox(e){return(e.data??[]).map(XL)}function lx(e){return Object.values(e.transports??{}).map(ex)}function cx(e){return 1e4*e}function dx(e,t=Number(new Date)){if(!e)return;const i=nn(e);return e.lastMsgDate&&(e.timeSinceLastMsg=e.lastMsgDate-t),delete i.lastMsgDate,delete i.lastHistory,rn(i)}function ux(e,t,i=0){const n=t.filter((e=>void 0!==e));let r;switch(e){case"Difference":r=n[n.length-1]-n[0];break;case"Average":r=n.reduce(((e,t)=>e+t),0)/n.length;break;case"LastValue":r=n[n.length-1]}return r||0===r?`${"number"==typeof r?+r.toFixed(i):r}`:void 0}function hx(e,t,i){return(i?e.map((e=>e?.[t]?.[i])):e.map((e=>e?.[t]))).filter((e=>void 0!==e)).reduce(((e,t)=>e.concat(t)),[])}function gx(e){const t=e[e.length-1]?.extensions?.powerEfficient;return void 0===t?"":t?"hw":"sw"}function px(e,t){return e&t?"Bidirectional":e?"ReceiveFromPeer":t?"SendToPeer":"Inactive"}function mx(e){const t=e[e.length-1]?.extensions?.callIsMuted,i=e[e.length-1]?.extensions?.rawInputVolume;return t?"0":!t&&i>0?"2":t||0!==i?void 0:"1"}function fx(e,t){const i=ux("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/").pop(),n=i?i+` ${gx(e)}`:void 0;return{"Rtp Packet Sent":ux("Difference",e.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":ux("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Current Bitrate":ux("Average",e.map((e=>e?.extensions?.bitrate))),"Allocated Send Bandwidth Average":ux("LastValue",e.map((e=>e?.extensions?.bitrateAvg))),"Send Actual Height":ux("LastValue",e.map((e=>e?.outboundRTP.frameHeight))),"Send Actual Width":ux("LastValue",e.map((e=>e?.outboundRTP.frameWidth))),"Send Current Frame Rate":ux("Average",e.map((e=>e?.extensions?.frameRateSent))),"Send RTT (Avg)":ux("LastValue",e.map((e=>e?.extensions?.rttAvg))),"Sent Codec Name":n,"Webcam Freeze Intervals":ux("LastValue",e.map((e=>e?.extensions?.captureFreezeIntervalsCount))),"Current Capture Device Name":t?.camera,"Number of Sync Frame Request per Minute":ux("LastValue",e.map((e=>e?.extensions?.pliRate)))}}function vx(e){const t=ux("LastValue",e.map((e=>e?.mediaEntity?.xSourceStreamId))),i=ux("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/").pop(),n=i?i+` ${gx(e)}`:void 0;return{"Recv Loss Rate (Avg)":ux("LastValue",e.map((e=>e?.extensions?.lossRate)),3),"Received BW estimate":ux("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Receive Current Bitrate":ux("Average",e.map((e=>e?.extensions?.bitrate))),"Rtp Packets Received":ux("Difference",e.map((e=>e?.inboundRTP.packetsReceived))),"Receive Actual Height":ux("LastValue",e.map((e=>e?.inboundRTP.frameHeight))),"Receive Actual Width":ux("LastValue",e.map((e=>e?.inboundRTP.frameWidth))),"Receive Current Frame Rate":ux("Average",e.map((e=>e?.extensions?.frameRateReceived))),"Received Codec Name":n,"Received Total Freeze Fraction (ms per min)":ux("LastValue",e.map((e=>e?.extensions?.totalFreezeFraction))),videoSourceId:t?parseInt(t):void 0,"Received Fps Time Weighted Harmonic Average":ux("LastValue",e.map((e=>e?.extensions?.fpsHarmonicAverage)))}}function Sx(e,t,i){const n=function(e,t){const i=hx(e,"audio","send"),n=hx(e,"audio","recv"),r=function(e){const t=e.find((e=>e?.transports));return t?t.transports[Object.keys(t.transports)[0]]:void 0}(e);if(i.length||n.length)return rn({mediaType:"Audio",mediaDirection:px(n.length,i.length),"Received BW estimate":ux("Average",n.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Recv Loss Rate (Avg)":ux("LastValue",n.map((e=>e?.extensions?.lossRate/100)),3),"Rtp Packets Received":ux("Difference",n.map((e=>e?.inboundRTP.packetsReceived))),"Rtp Packet Sent":ux("Difference",i.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":ux("Average",i.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Audio Codec":ux("LastValue",i.map((e=>e?.codec?.mimeType)))?.split("/").pop(),"Send RTT (Avg)":ux("LastValue",i.map((e=>e?.extensions?.rttAvg))),"Audio NW jitter avg":ux("LastValue",n.map((e=>e?.extensions?.jitterAvg)),3),"Audio send bps":ux("Average",i.map((e=>e?.extensions?.bitrate))),"JB delay (ms)":ux("LastValue",n.map((e=>e?.extensions?.jitterBufferDelayMs))),"Recv Audio Codec":ux("LastValue",n.map((e=>e?.codec?.mimeType)))?.split("/").pop(),"Current Render Device Name":t?.speaker,"Current Capture Device Name":t?.microphone,"Latest Network Type":r?.selectedCandidatePair?.localCandidate?.networkType,"Latest Transport Protocol":r?.selectedCandidatePair?.localCandidate?.protocol,"Latest Reflexive Address":ym(r?.extensions?.reflexiveLocalIP),"Local Address":ym(r?.selectedCandidatePair?.localCandidate?.ip),"Local short-term Healed Data Ratio":ux("LastValue",n.map((e=>e?.extensions?.healedRatio))),"Send activity (0=muted; 1=inactive; 2=active)":mx(i)})}(e,t);n&&i.channels.push(n);const r=function(e,t){const i=[],n=function(e){const t={},i=i=>{e.map((e=>e?.video?.[i])).forEach((e=>{e?.forEach((e=>{var n;const r=e?.mediaEntity?.remoteSsrc;t[r]??(t[r]={}),(n=t[r])[i]??(n[i]=[]),t[r][i].push(e)}))}))};return i("recv"),i("send"),t}(e);for(const{send:e,recv:r}of Object.values(n)){let n={mediaType:"Camera",mediaDirection:px(r?.length,e?.length)};r&&(n={...n,...vx(r)}),e&&(n={...n,...fx(e,t)}),i.push(rn(n))}return i}(e,t);r.length&&i.channels.push(...r);const s=function(e){const t=hx(e,"sharing","send"),i=hx(e,"sharing","recv");if(!i.length&&!t.length)return;let n={mediaType:"AppSharing",mediaDirection:"Bidirectional","Render Device Name":""};return i.length&&(n={...n,...vx(i)}),t.length&&(n={...n,...fx(t,{microphone:void 0,camera:"Screen sharing",speaker:void 0})}),rn(n)}(e);s&&i.channels.push(s)}function yx(e,t,i,n,r){return rn({recv:rn({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytes:Rn(t[e]?.recv,(e=>e.inboundRTP.bytesReceived),r),packets:Rn(t[e]?.recv,(e=>e.inboundRTP.packetsReceived),r),packetsLost:Rn(t[e]?.recv,(e=>e.inboundRTP.packetsLost),r),codec:i?.codec?.mimeType.split("/").pop(),codecReport:i?.aggregated?.codecReport,framesDecoded:Rn(t[e]?.recv,(e=>e.inboundRTP.framesDecoded),r),height:Rn(t[e]?.recv,(e=>e.inboundRTP.frameHeight),r),width:Rn(t[e]?.recv,(e=>e.inboundRTP.frameWidth),r),frameRate:Rn(t[e]?.recv,(e=>e.extensions?.frameRateReceived),r)}),send:rn({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytes:Rn(t[e]?.send,(e=>e.outboundRTP.bytesSent),r),packets:Rn(t[e]?.send,(e=>e.outboundRTP.packetsSent),r),packetsLost:Rn(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost),r),codec:n?.codec?.mimeType.split("/").pop(),framesEncoded:Rn(t[e]?.send,(e=>e.outboundRTP.framesEncoded),r),heightInput:n?.mediaSource?.height,widthInput:n?.mediaSource?.width,height:Rn(t[e]?.send,(e=>e.outboundRTP.frameHeight),r),width:Rn(t[e]?.send,(e=>e.outboundRTP.frameWidth),r),frameRate:Rn(t[e]?.send,(e=>e.extensions?.frameRateSent),r)})})}function Cx(e,t,i,n){return rn({recv:rn({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytes:Rn(e.audio?.recv,(e=>e.inboundRTP.bytesReceived),n),packets:Rn(e.audio?.recv,(e=>e.inboundRTP.packetsReceived),n),packetsLost:Rn(e.audio?.recv,(e=>e.inboundRTP.packetsLost),n),codec:t?.codec?.mimeType.split("/").pop(),audioLevel:Rn(e.audio?.recv,(e=>Math.floor(65535*e.inboundRTP.audioLevel)),n)}),send:rn({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytes:Rn(e.audio?.send,(e=>e.outboundRTP.bytesSent),n),packets:Rn(e.audio?.send,(e=>e.outboundRTP.packetsSent),n),packetsLost:Rn(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost),n),codec:i?.codec?.mimeType.split("/").pop(),audioLevel:Rn(e.audio?.send,(e=>Math.floor(65535*e.aggregated.audioLevel)),n)})})}function Tx(e){return rn({negotiationCount:e.negotiationCount,rejectedNegotiationCount:e.rejectedNegotiationCount})}var Ex=class{constructor(e,t){this.rootRef=e,this.configProvider=t}get rawRootRef(){return this.rootRef}getSessionTelemetry(e){const t=this.getLatestSession(e);if(!t)return;const i={metrics:{},Extensions:{}},n=_n();try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,n=e?.terminationTime??0,r=t.webrtcSessions[t.webrtcSessions.length-1];i.metrics=function(e,t,i,n){const r=n.config.diagnostics.telemetryLimits,s=e.webrtcSessions[e.webrtcSessions.length-1];return rn({MediaLegId:e.mediaLegId,CreationTime:cx(e.creationTime),CallNumber:e.callNumber,SessionId:e.sessionId,MultiParty:e.isMultiParty,ErrorType:e.error?.type??"none",ErrorDetail:e.error?.detail??"none",IncompatibleOffer:e.error?.type===Gi.MEDIA_ERROR.incompatibleOffer,TerminationTime:cx(e.terminationTime),TerminationReason_code:e.terminationReason?.code,TerminationReason_subCode:e.terminationReason?.subCode,TerminationReason_phrase:e.terminationReason?.phrase,TerminationReason_remoteTerminated:e.terminationReason?.remoteTerminated,TerminationReason_clientReasonPhrase:e.terminationReason?.clientReasonPhrase,TerminationReason_clientReasonSubCode:e.terminationReason?.clientReasonSubCode,TerminationReason_resultCategories:e.terminationReason?.resultCategories,CallDuration:cx(e.duration),IceInitTime:cx(e.iceInitTime),IceConnectedStateTime:cx(e.iceConnectedStateTime),NegotiationCount:e.negotiationCount,RejectedNegotiationCount:e.rejectedNegotiationCount,InitialNegotiationCompleted:e.initialNegotiationCompleted,InitialNegotiationType:e.initialNegotiationType,FinalAnswerTime:cx(e.finalAnswerTime),TransportReconnectedCount:e.transportReconnectedCount,RollbackNegotiation:JSON.stringify(e.rollbackNegotiation),Relay:e.relay?JSON.stringify(e.relay):void 0,ActiveModalities:JSON.stringify(e.activeModalities),AllowedAudioSend:e.allowedAudioSend,AllowedVideoSend:e.allowedVideoSend,AllowedScreensharingSend:e.allowedScreensharingSend,RelayManager:JSON.stringify(e.relayTimers),AuthTokenStats:JSON.stringify(e.authTokenFetcherStats),CallMutedRatio:e.callMutedRatio,CallOsMuted:cx(e.callOsMuted),CallHwSilent:cx(e.callHwSilent),CallSwMuted:cx(e.callSwMuted),CallSpeakerMuted:cx(e.callSpeakerMuted),CallIsSpeaking:cx(e.callIsSpeaking),DtmfSuccess:e.dtmfSuccessCount,DtmfFailure:e.dtmfFailureCount,ContributingSourcesError:s.contributingSourcesError,ReconnectInProgress:e.reconnect?.isReconnecting,RetargetIncomingCount:e.reconnect?.retargetCount.incoming,RetargetOutgoingCount:e.reconnect?.retargetCount.outgoing,RetargetCompletedCount:e.reconnect?.retargetCount.completed,RetargetRejectedCount:e.reconnect?.retargetCount.rejected,EscalationAttemptedCount:e.reconnect?.escalationCount.attempted,EscalationCompletedCount:e.reconnect?.escalationCount.completed,EscalationRejectedCount:e.reconnect?.escalationCount.rejected,Elevation:JSON.stringify(e.elevation),ReconnectAttemptedCount:e.reconnect?.reconnectCount.attempted,ReconnectConnectedCount:e.reconnect?.reconnectCount.connected,ReconnectAttempts:xn(e.reconnect?.records,r.numReconnects,"startTime",e.creationTime),NetworkEvents:xn(e.reconnect?.tmpRecords,r.numNetworkEvents,"startTime",e.creationTime),NoIceCandidatesGoodEventCount:e.noIceCandidatesEventCount.good,NoIceCandidatesBadEventCount:e.noIceCandidatesEventCount.bad,NoRelayIceCandidatesGoodEventCount:e.noRelayIceCandidatesEventCount.good,NoRelayIceCandidatesBadEventCount:e.noRelayIceCandidatesEventCount.bad,MicrophoneInUseGoodEventCount:e.microphoneInUseEventCount.good,MicrophoneInUseBadEventCount:e.microphoneInUseEventCount.bad,CameraInUseGoodEventCount:e.cameraInUseEventCount.good,CameraInUseBadEventCount:e.cameraInUseEventCount.bad,CameraFreezeStartEventCount:e.cameraFreezeEventCount.start,CameraFreezeEndEventCount:e.cameraFreezeEventCount.end,NetworkRecvGood:e.networkRecvUFD.good,NetworkRecvGoodRatio:e.networkRecvUFD.goodRatio,NetworkRecvPoor:e.networkRecvUFD.poor,NetworkRecvPoorRatio:e.networkRecvUFD.poorRatio,NetworkRecvBad:e.networkRecvUFD.bad,NetworkRecvBadRatio:e.networkRecvUFD.badRatio,NetworkSendGood:e.networkSendUFD.good,NetworkSendGoodRatio:e.networkSendUFD.goodRatio,NetworkSendPoor:e.networkSendUFD.poor,NetworkSendPoorRatio:e.networkSendUFD.poorRatio,NetworkSendBad:e.networkSendUFD.bad,NetworkSendBadRatio:e.networkSendUFD.badRatio,Connection_Downlink:Pn(s.networkInfo,(e=>e.downlink)),Connection_EffectiveType:s.networkInfo.map((e=>e.effectiveType)).filter((e=>e)).join(","),Connection_Rtt:Pn(s.networkInfo,(e=>e.rtt)),Connection_SaveData:Cn(s.networkInfo)?.saveData,RawOutputAudioAccessAttempted:e.rawMedia.audio.recv.numAttempts,RawOutputAudioAccessDurationRatio:e.rawMedia.audio.recv.durationRatio,RawInputAudioOverrideAttempted:e.rawMedia.audio.send.numAttempts,RawInputAudioOverrideDurationRatio:e.rawMedia.audio.send.durationRatio,ZeroCaptureDevicesEnumeratedEventRatio:mn(e.zeroCaptureDevicesRatio,Gi.NATIVE_RATIO_PRECISION),ZeroRenderDevicesEnumeratedEventRatio:mn(e.zeroRenderDevicesRatio,Gi.NATIVE_RATIO_PRECISION),DeviceCaptureNotFunctioningEventRatio:mn(e.deviceCaptureFailuresRatio,Gi.NATIVE_RATIO_PRECISION),DeviceRenderNotFunctioningEventRatio:mn(e.deviceRenderFailuresRatio,Gi.NATIVE_RATIO_PRECISION),UFDs:xn(e.ufds,r.numUFDs,"timestamp",e.creationTime),remoteUFDs:xn(e.remoteUfds,r.numUFDs,"timestamp",e.creationTime),UFDs_count:JSON.stringify(e.ufdManager.count),remoteUFDs_count:JSON.stringify(e.remoteUfdsCount),MediaQosEnabled:i.configuration.mediaConfig?.enableMediaQoS??!1,PortRangeConfigured:!!i.configuration.mediaConfig?.mediaPortRanges,hardwareConcurrency:i.configuration.userAgentConfig.hardwareConcurrency,ETag:e.ETag,ConfigIds:e.configIds,GPUName:i.configuration.userAgentConfig.unmaskedGlRenderer,PermissionStates:JSON.stringify(i.deviceManager.permissionStates),DeviceList:JSON.stringify(i.deviceManager.deviceList),DeviceListDebug:JSON.stringify(i.deviceManager.deviceDebugStrings),DevicesChangeCount:e.deviceManager.devicesChangeCount,DevicesPollChangeCount:e.deviceManager.devicesPollChangeCount,DeviceSelectionChangeCount:e.deviceManager.deviceSelectionChangeCount,DeviceSelectionChangeFromInterfaceCount:e.deviceManager.deviceSelectionChangeCountFromInterface,DevicesCount:JSON.stringify(i.deviceManager.devicesCount),UsedMicrophone:i.deviceManager.usedDevices?.microphone,UsedSpeaker:i.deviceManager.usedDevices?.speaker,UsedCamera:i.deviceManager.usedDevices?.camera,DeviceEvents:xn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),r.numDeviceEvents,"timestamp",e.creationTime),VideoEffects:xn(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>t)),r.numVideoEffectsEvents,"timestamp",e.creationTime),AudioEffects:xn(i.deviceManager.audioEffectsEvents.filter((e=>e.timestamp>t)),r.numAudioEffectsEvents,"timestamp",e.creationTime),WorkerEvents:xn(i.deviceManager.workerEvents.filter((e=>e.timestamp>t)),r.numWorkerEvents,"timestamp",e.creationTime),MediaByPassEnabled:!!i.configuration.mediaConfig.enableMediaBypass,CallConstraints:JSON.stringify(e.callConstraints),DominantSpeaker:JSON.stringify(dx(e.dominantSpeaker,e.terminationTime)),AudioSourceNumOfReopenRequests:e.deviceManager.audioSourceNumOfReopenRequests||void 0,AudioSourceNumOfSuccessfulReopens:e.deviceManager.audioSourceNumOfSuccessfulReopens||void 0,AudioCaptureErrorCodeFlagsInit:e.deviceManager.audioCaptureDeviceErrorFlag,AudioRenderErrorCodeFlagsInit:e.deviceManager.audioRenderDeviceErrorFlag,AudioSinkNumOfReopenRequests:e.audioRenderer.sinkNumOfReopenRequests,AudioSinkNumOfSuccessfulReopens:e.audioRenderer.sinkNumOfSuccessfulReopens,CallSetupTimeTracker:JSON.stringify(e.webrtcSessions[0].negotiation.callSetupTimeReport),LastSessionSetupTimeTracker:e.webrtcSessions.length>1?JSON.stringify(s.negotiation.callSetupTimeReport):void 0,BatteryLevel:e.batteryLevel})}(t,n,this.rootRef,this.configProvider),i.Extensions=function(e,t,i){const n=t.config.diagnostics.telemetryLimits,r=e.aggregatedModalityStats,s=Cn(r.audio?.recv),a=Cn(r.audio?.send),o=Cn(r.video?.recv),l=Cn(r.video?.send),c=Cn(r.sharing?.recv),d=Cn(r.sharing?.send),u=i=>i&&vn(nn(i).map((t=>wn(vn(t.events,n.numCapabilitiesApplied,1),"timestamp",e.startTime))),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),h=u(e.qualityManager?.videoMaxCapabilitiesEvents),g=u(e.qualityManager?.videoMaxCapabilitiesErrors),p=u(e.qualityManager?.sharingMaxCapabilitiesEvents),m=u(e.qualityManager?.sharingMaxCapabilitiesErrors),f="REMB"!==e.negotiation.bweType?e.bandwidthReport:void 0,v="REMB"===e.negotiation.bweType?e.bandwidthReport:void 0;return rn({BundlePolicy:e.bundlePolicy,FakeIceCandidate:e.negotiation.fakeCandidate,h264AvailableProfiles:JSON.stringify(e.H264Profiles),h264CodecCapabilities:JSON.stringify(e.h264CodecCapabilities),IceConnectionState:e.transportState?.iceConnectionState,IceConnectionStatePrevious:e.transportState?.iceConnectionStatePrevious,IceServers:e.iceServers,IceTransportPolicy:e.iceTransportPolicy,NegotiatedSrtp:JSON.stringify(e.negotiation.negotiatedSrtp),OfferedSrtp:JSON.stringify(e.negotiation.offeredSrtp),RelayCandidate:e.relayCandidate,SdpSemantics:e.sdpSemantics,iceCandidateErrors:JSON.stringify(e.iceCandidateErrors),SignalingState:e.transportState?.signalingState,SignalingStatePrevious:e.transportState?.signalingStatePrevious,WebRTCStats_statsErrors:JSON.stringify(i),MaxSessionBandwidth:e.maxSessionBandwidth,Bandwidth_uplinkStabilizationTime:JSON.stringify(e.bwStabilizationTime),Bandwidth_downlinkStabilizationTime:JSON.stringify(e.bwDownlinkStabilizationTime),totalVideoControlMessages:e.qualityManager?.numVideoControlMessages,outOfOrderVideoControlMessages:e.qualityManager?.numOutOfOrderVideoControlMessages,webcamFreezeIntervals:e.qualityManager?.numWebcamFreezeIntervals,processedStreamFreezeIntervals:e.qualityManager?.numProcessedStreamFreezeIntervals,IPAddress:e.IPAddress??"none",ReflexiveLocalIP:e.reflexiveLocalIP??"none",NumberOfInterfaces:e.numInterfaces,StartTime:e.startTime,EndTime:e.endTime,AudioTransportRecvBitrate:s?.transport?.extensions?.recvBWAvg,AudioTransportSendBitrate:s?.transport?.extensions?.sendBWAvg,AudioPayloadRecvBitrate:s?.aggregated?.bitrateAvg,AudioPayloadSendBitrate:a?.aggregated?.bitrateAvg,VideoPayloadRecvBitrate:o?.aggregated?.bitrateAvg,VideoPayloadSendBitrate:l?.aggregated?.bitrateAvg,WebRTCStats_bweStat_googAvailableReceiveBandwidth:Pn(r.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate))??Pn(r.video?.send,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate)),WebRTCStats_bweStat_googAvailableSendBandwidth:Pn(r.video?.send,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate))??Pn(r.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate)),Bandwidth_jumpsHistogram:JSON.stringify(l?.transport?.extensions?.bwJumpsHistogram),StartCallBWESendSide:JSON.stringify(f?.startOfTheCall),EndCallBWESendSide:JSON.stringify(f?.endOfTheCall),BWEStdSendSide:JSON.stringify(f?.std),BwPercentilesSendSide:JSON.stringify(f?.bwPercentiles),AvgBwSendSide:JSON.stringify(f?.avgBwe),StartCallBWE:JSON.stringify(v?.startOfTheCall),EndCallBWE:JSON.stringify(v?.endOfTheCall),BWEStd:JSON.stringify(v?.std),BwPercentiles:JSON.stringify(v?.bwPercentiles),AvgBw:JSON.stringify(v?.avgBwe),WebRTCStats_ssrc:rn({audio:WL(r,s,a),video:KL("video",r,o,l),sharing:KL("sharing",r,c,d)}),Audio_recv_jitterBufferAvgSize:s?.aggregated?.avgJitterBufferSize,Audio_recv_packetsLostRateMax:mn(s?.aggregated?.lossRateMax,6),Audio_recv_jitterAvg:s?.aggregated?.jitterAvg,Audio_recv_jitterMax:s?.aggregated?.jitterMax,Audio_recv_networkAvgLossRate:mn(s?.aggregated?.networkAvgLossRate,6),Audio_recv_packetsLostAvg:s?.aggregated?.packetsLostAvg,Audio_recv_healedRatioAvg:s?.aggregated?.healedRatioAvg,Audio_recv_healedRatioMax:s?.aggregated?.healedRatioMax,Audio_send_rttAvg:a?.aggregated?.rttAvg&&mn(1e3*a.aggregated.rttAvg),Audio_send_rttMax:a?.aggregated?.rttMax&&mn(1e3*a.aggregated.rttMax),Audio_send_RawInputVolume:Pn(r.audio?.send,(e=>e.aggregated?.rawInputVolume)),Audio_send_packetsLostRateMax:mn(a?.aggregated?.lossRateMax,6),Audio_send_presentationAPIUserDuration:e.presentationAPIUserDuration,Audio_send_presentationDuration:e.presentationAudioDuration,Video_recv_DurationSeconds:o?.aggregated?.duration,Video_recv_FreezeHistogram:JSON.stringify(o?.aggregated?.freezeCountHistogram),Video_recv_FreezeTimestamps:JSON.stringify(An(o?.aggregated?.freezeTimestampsHistogram,e.startTime,n.numOfHistogramSamples)),Video_recv_LongestFreezeDuration:o?.aggregated?.longestFreeze,Video_recv_OngoingFreeze:o?.extensions?.isFrozen,Video_recv_OngoingFreezeDuration:o?.aggregated?.ongoingFreezeDuration,Video_recv_TotalFreezeDuration:o?.aggregated?.totalFreezeDuration,Video_recv_RecvAvgFreezeDuration:o?.aggregated?.avgFreezeDuration,Video_recv_NumResolutionSwitches:o?.aggregated?.numResolutionSwitches,Video_recv_ResolutionDurations:JSON.stringify(o?.aggregated?.resolutionDurations),Video_recv_StreamsMax:e.recvVideoStreamCount.max,Video_recv_StreamsMin:e.recvVideoStreamCount.min,Video_recv_StreamsMode:e.recvVideoStreamCount.mode,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_bitrateAvg:o?.aggregated?.bitrateAvg,Video_recv_bitrateMax:o?.aggregated?.bitrateMax,Video_recv_frameRateAvg:o?.aggregated?.avgFrameRate,Video_recv_jitterBufferAvgSize:o?.aggregated?.avgJitterBufferSize,Video_recv_packetsLostRateMax:mn(o?.aggregated?.lossRateMax,6),Video_recv_isRenderingEvents:JSON.stringify(vn(e.remoteVideoManager?.isRenderingEvents.video,n.numIsRenderingEvents)),Video_recv_FpsHarmonicAverage:o?.aggregated?.fpsHarmonicAverage,Video_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.video?.toString(),Video_recv_statsOnSubscribed:JSON.stringify(e.statsOnSubscribed.video),Video_SubscriptionEvents:JSON.stringify(wn(e.subscriptionManager?.video.events,"ts",e.startTime)),Video_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.video.counters),Video_send_CaptureFramerateAvg:l?.aggregated?.captureFramerateAvg,Video_send_DurationSeconds:l?.aggregated?.duration,Video_send_FreezeIntervals:l?.extensions?.captureFreezeIntervalsCount,Video_send_MaxCapabilities:JSON.stringify(h),Video_send_MaxCapabilitiesErrors:JSON.stringify(g),Video_send_OvershootDurations:JSON.stringify({fs:l?.aggregated?.totalFsOvershootDuration,fps:l?.aggregated?.totalFpsOvershootDuration,br:l?.aggregated?.totalBrOvershootDuration}),Video_send_OvershootEvents:xn(l?.aggregated?.overshootEvents,n.numOvershootEvents,"timestamp",e.startTime),Video_send_QpAvg:l?.aggregated?.qpAvg,Video_send_bitrateAvg:l?.aggregated?.bitrateAvg,Video_send_bitrateMax:l?.aggregated?.bitrateMax,Video_send_frameRateAvg:l?.aggregated?.frameRateAvg,Video_send_AllocateBWAvg:l?.aggregated?.bweAvg,Video_send_CameraOpenWidth:l?.extensions?.cameraOpenResolution?.width,Video_send_CameraOpenHeight:l?.extensions?.cameraOpenResolution?.height,Video_send_packetsLostRateMax:mn(l?.aggregated?.lossRateMax,6),Video_send_resolutionSwitches:JSON.stringify(l?.aggregated?.resolutionSwitches),Video_send_performanceEvents:xn(e.localVideoPerformanceEvents,n.numPerformanceEvents,"timestamp",e.startTime),Video_send_Simulcast:JSON.stringify(e.simulcast?.video),Video_send_powerEfficientEncoderEvents:xn(l?.extensions?.powerEfficientEncoderEvents,n.numPowerEfficientEncoderEvents,"timestamp",e.startTime),Video_send_powerEfficientEncoderEventOnCount:l?.extensions?.powerEfficientEncoderEventOnCount,Video_send_powerEfficientEncoderEventOffCount:l?.extensions?.powerEfficientEncoderEventOffCount,Sharing_recv_DurationSeconds:c?.aggregated?.duration,Sharing_recv_FreezeHistogram:JSON.stringify(c?.aggregated?.freezeCountHistogram),Sharing_recv_FreezeTimestamps:JSON.stringify(An(c?.aggregated?.freezeTimestampsHistogram,e.startTime,n.numOfHistogramSamples)),Sharing_recv_LongestFreezeDuration:c?.aggregated?.longestFreeze,Sharing_recv_OngoingFreeze:c?.extensions?.isFrozen,Sharing_recv_TotalFreezeDuration:c?.aggregated?.totalFreezeDuration,Sharing_recv_RecvAvgFreezeDuration:c?.aggregated?.avgFreezeDuration,Sharing_recv_NumResolutionSwitches:c?.aggregated?.numResolutionSwitches,Sharing_recv_ResolutionDurations:JSON.stringify(c?.aggregated?.resolutionDurations),Sharing_recv_StreamsMax:e.recvVideoStreamCount.max,Sharing_recv_StreamsMin:e.recvVideoStreamCount.min,Sharing_recv_StreamsMode:e.recvVideoStreamCount.mode,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_bitrateAvg:c?.aggregated?.bitrateAvg,Sharing_recv_bitrateMax:c?.aggregated?.bitrateMax,Sharing_recv_frameRateAvg:c?.aggregated?.avgFrameRate,Sharing_recv_jitterBufferAvgSize:c?.aggregated?.avgJitterBufferSize,Sharing_recv_packetsLostRateMax:mn(c?.aggregated?.lossRateMax,6),Sharing_recv_FpsHarmonicAverage:c?.aggregated?.fpsHarmonicAverage,Sharing_recv_isRenderingEvents:JSON.stringify(vn(e.remoteVideoManager?.isRenderingEvents.sharing,n.numIsRenderingEvents)),Sharing_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.sharing?.toString(),Sharing_recv_statsOnSubscribed:JSON.stringify(e.statsOnSubscribed.sharing),Sharing_SubscriptionEvents:JSON.stringify(wn(e.subscriptionManager?.sharing.events,"ts",e.startTime)),Sharing_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.sharing.counters),Sharing_send_CaptureFramerateAvg:d?.aggregated?.captureFramerateAvg,Sharing_send_DurationSeconds:d?.aggregated?.duration,Sharing_send_MaxCapabilities:JSON.stringify(p),Sharing_send_MaxCapabilitiesErrors:JSON.stringify(m),Sharing_send_OvershootDurations:JSON.stringify({fs:d?.aggregated?.totalFsOvershootDuration,fps:d?.aggregated?.totalFpsOvershootDuration,br:d?.aggregated?.totalBrOvershootDuration}),Sharing_send_resolutionSwitches:d?.aggregated?.resolutionSwitches,Sharing_send_OvershootEvents:xn(d?.aggregated?.overshootEvents,n.numOvershootEvents,"timestamp",e.startTime),Sharing_send_QpAvg:d?.aggregated?.qpAvg,Sharing_send_bitrateAvg:d?.aggregated?.bitrateAvg,Sharing_send_bitrateMax:d?.aggregated?.bitrateMax,Sharing_send_frameRateAvg:d?.aggregated?.frameRateAvg,Sharing_send_AllocateBWAvg:d?.aggregated?.bweAvg,Sharing_send_packetsLostRateMax:mn(d?.aggregated?.lossRateMax,6),Sharing_send_Simulcast:JSON.stringify(e.simulcast?.sharing),Data_ProtocolCounters:JSON.stringify(e.dataChannel?.protocolCounters),Data_Error:e.dataChannel?.error,Data_SessionState:e.dataChannelSessionState?.toString(),Data_CreateChannelError:e.dataChannelCreationError,multipleVideoStreams:JSON.stringify(wn(e.multiViewStats,"startTime",e.startTime)),ReportedReceiveBandwidth:JSON.stringify(e.reportedReceiveBandwidth),ReportedSendBandwidth:JSON.stringify(e.reportedSendBandwidthLayouts),OvcToSubscriptions:JSON.stringify(e.ovcToSubscriptionEvents),EncodedStreamWorker:e.encodedStreamWorker,AudioCodecEvents:JSON.stringify(e.audioCodecEvents),HevcCodecSupport:JSON.stringify(e.codecSupport),MeetingScenario:JSON.stringify(e.negotiation.meetingScenario),IsTownHall:e.negotiation.isTownHall,InitialBWSeed:e.initialBWSeed,SentBWSeed:e.sentBWSeed,videoPerformanceEvent:JSON.stringify(e.videoPerformanceEvent),EarlyMedia_NumStatsPolls:e.earlyMediaNumStatsPolls})}(r,this.configProvider,t.statsErrors)}catch(e){t[VL].addStatsError("DiagnosticsReport:getSessionTelemetry",tt(e)),i.Extensions.WebRTCStats_statsErrors=JSON.stringify(t.statsErrors)}return i.metrics.ReportGenerationTimeMs=mn(_n()-n),i}getTeamsRealtimeTelemetry(e){const t=this.getLatestSession(e);if(t)try{const e=t.webrtcSessions[t.webrtcSessions.length-1],i=this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval;return function(e,t){const i=hx(e,"inactiveTracks"),n={channels:[]};return Sx(e,t,n),i.length&&Sx(i,void 0,n),n}(e.statsReports.slice(e.statsReports.length-i),this.rootRef.deviceManager.rawUsedDevices)}catch(e){throw t[VL].addStatsError("DiagnosticsReport:getRealTimeTelemetry",tt(e)),e}}getMediaSessionStats(e){const t=this.getLatestSession(e);if(t)try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,i=e?.terminationTime??0,n=t.webrtcSessions[t.webrtcSessions.length-1],r=n?.statsReports.length?n.statsReports[n.statsReports.length-1]:void 0,s=r?function(e){return{audio:{send:tx(e),recv:ix(e)},video:{send:nx(e),recv:rx(e)},screenShare:{send:sx(e),recv:ax(e)},data:ox(e),transports:lx(e)}}(r):void 0;return s&&(s.extensions=function(e,t){const i=e.qualityManager&&vn(nn(e.qualityManager.videoMaxCapabilitiesEvents),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),n=e.qualityManager&&vn(nn(e.qualityManager.sharingMaxCapabilitiesEvents),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested);return rn({Video_SubscriptionEvents:JSON.stringify(e.subscriptionManager?.video.events),Sharing_SubscriptionEvents:JSON.stringify(e.subscriptionManager?.sharing.events),Video_send_MaxCapabilities:JSON.stringify(i),Sharing_send_MaxCapabilities:JSON.stringify(n),RelayCandidate:e.relayCandidate,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartVideo,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartSharing,IceServers:e.iceServers})}(n,this.configProvider),s.metrics=function(e,t,i){return rn({DeviceEvents:JSON.stringify(wn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),IceConnectedStateTime:1e4*e.iceConnectedStateTime})}(t,i,this.rootRef)),s}catch(e){throw t[VL].addStatsError("DiagnosticsReport:getMediaSessionStats",tt(e)),e}}getDiagnosticsForE2eTests(e){const t=this.getLatestSession(e);let i={statsErrors:[]};if(t){try{const e=t.webrtcSessions[t.webrtcSessions.length-1],n=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,r=n?.terminationTime??0;i=function(e,t,i,n,r){const s=e.aggregatedModalityStats,a=Cn(s.audio?.recv),o=Cn(s.audio?.send),l=Cn(s.video?.recv),c=Cn(s.video?.send),d=Cn(s.sharing?.recv),u=Cn(s.sharing?.send),h=[],g=[];return e.statsOnSubscribed.video?.forEach((e=>h.push(e))),e.statsOnSubscribed.sharing?.forEach((e=>g.push(e))),rn({multipleVideoStreams:e.multiViewStats,WebRTCStats_ssrc:rn({audio:Cx(s,a,o,r),video:yx("video",s,l,c,r),sharing:yx("sharing",s,d,u,r),negotiationStats:Tx(t)}),CallSwMuted:1e3*t.callSwMuted,DeviceEvents:wn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),VideoEffects:wn(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),AudioEffects:wn(i.deviceManager.audioEffectsEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),statsErrors:t.statsErrors,WorkerEvents:wn(i.deviceManager.workerEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),transportState:e.transportState})}(e,t,this.rootRef,r,this.configProvider.config.diagnostics.collectionLimits.numSamplesForE2E)}catch(e){const n="DiagnosticsReport:getDiagnosticsForE2eTests",r=tt(e);t[VL].addStatsError(n,r),Sn(i.statsErrors,{origin:n,error:r,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}return i}}getLatestSession(e){return this.rootRef.sessions.filter((t=>t.sessionId===e)).sort(((e,t)=>e.callNumber-t.callNumber)).pop()}},bx=class{constructor(e,t,i){this.configProvider=e,this.deviceManagerDiagnostics=t,this.ufdManagerDiagnostics=i,this.root={creationTime:Date.now(),numTotalSessions:0,deviceManager:this.deviceManagerDiagnostics.getObjectRef(),ufdManager:this.ufdManagerDiagnostics.getObjectRef(),configuration:{stackConfig:this.configProvider.stackConfig,defaultConfig:this.configProvider.defaultConfig,mediaConfig:{},userAgentConfig:{isAudioOutputSelectionSupported:this.configProvider.userAgentConfig.isAudioOutputSelectionSupported,isBrowserRollbackSupported:this.configProvider.userAgentConfig.isBrowserRollbackSupported,hardwareConcurrency:Vp.hardwareConcurrency,unmaskedGlRenderer:Vp.unmaskedGlRenderer,hasMediaApi:Vp.hasMediaApi(),hasCapabilitiesApi:Vp.hasCapabilitiesApi(),hasUnifiedPlanSupport:void 0},consoleOverrides:this.configProvider.consoleOverrides,fullConfig:nn(this.configProvider.config),ecsConfigUpdates:[]},browserInfo:Ot.getBrowserInfo(),sessions:[]},this.diagnosticsReport=new Ex(this.root,this.configProvider),this.configProvider.on("newConfigReceived",((e,t,i)=>{this.root.configuration.ecsConfigUpdates.push({timestamp:Date.now(),etag:t,configIds:i,config:e})})),this.configProvider.on("configUpdated",(()=>{this.root.configuration.consoleOverrides=this.configProvider.consoleOverrides,this.root.configuration.fullConfig=nn(this.configProvider.config)}))}get reportGenerator(){return this.diagnosticsReport}get rootRef(){return this.root}set mediaConfig(e){this.root.configuration.mediaConfig=e}newSession(e,t,i){this.root.configuration.userAgentConfig.hasUnifiedPlanSupport=this.configProvider.mediaConfig.simulcastSessionEnabled;const n=new HL(i,e,this.diagnosticsReport,this.root.deviceManager,this.root.ufdManager,++this.root.numTotalSessions,t);return Sn(this.root.sessions,n.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numSessions),n}},_x=class e{constructor(e,t){this.safe=e,this.unsafe=t,this.safe||(this.safe=this.unsafe)}warn(...e){this.unsafe.warn(...e)}error(...e){this.unsafe.error(...e)}debug(...e){this.unsafe.debug(...e)}info(...e){this.unsafe.info(...e)}createChild(t){return new e(this.safe.createChild(t),this.unsafe.createChild(t))}},Ix=Z,wx=class{constructor(e){this.logger=e,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(e){this.isExtensionAvailable&&(0===this.connectionCount&&1===e?("stopped"===this.loggingState&&await this.discardLogs(),await this.initialStartLogging()):0===e&&await this.stopLogging(),this.connectionCount=e)}async collect(){return this.isExtensionAvailable?this.collectPromise?this.collectPromise:this.collectPromise=new Promise((async e=>{try{this.connectionCount>0&&(this.logger.safe.info(`Stopping logger for gathering, open connections: ${this.connectionCount}`),await this.stopLogging()),await this.storeLogs();const t=await this.gatherFromStorage();this.connectionCount>0&&await this.continueLogging(),e(t.length>0?t.join("\r\n"):"")}catch(t){this.logger.safe.error("Error while collecting logs",t),e(JSON.stringify(t))}this.collectPromise=void 0})):""}async initialStartLogging(){try{await this.startLogging()}catch(e){if(e?.includes("A log is already open"))try{const t=e.match(/State=(\w+)/);await this.cleanState(t?.[1]),await this.startLogging()}catch(e){this.logger.safe.error("Error while starting logging at cleanup phase",e),this.loggingState="unknown"}else this.logger.safe.error("Error while starting logging",e),this.loggingState="unavailable"}}async continueLogging(){try{await this.startLogging()}catch(e){this.logger.safe.error("Error while continuing logging",e),this.loggingState="stopped"}}async startLogging(){await this.sendMessage(this.extensionId,{method:"logging.start"}),this.logger.safe.info("Logging started"),this.loggingState="started"}async cleanState(e){try{if("started"===e)await this.stopLogging(),await this.discardLogs();else{if("stopped"!==e)throw new Error(`Unexpected logging state: ${e}`);await this.discardLogs()}}catch(e){this.logger.safe.error("Error while cleaning state",e)}}async stopLogging(){try{await this.sendMessage(this.extensionId,{method:"logging.stop"}),this.logger.safe.info("Logging stopped"),this.loggingState="stopped"}catch(e){this.logger.safe.error("Error while stopping logging",e)}}async discardLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.discard"}),this.logger.safe.info("Logs discarded"),this.loggingState="closed"}catch(e){this.logger.safe.error("Error while discarding logs",e)}}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(e){this.logger.safe.error("Error while storing logs",e)}}async gatherFromStorage(){const e=[];let t={offset:0};do{t=await this.sendMessage(this.editorExtensionId,{api:"getWebRtcLog",logId:this.logId,offset:t.offset}),e.push(t.data),this.logger.safe.info(`Batch gathered with offset: ${t.offset}, moreData: ${t.moreData}`)}while(t.moreData);return this.logger.safe.info("Finished gathering"),e}sendMessage(e,t){return new Promise(((i,n)=>{const r=chrome.runtime;r.sendMessage(e,t,(e=>{if(!e||e?.error){const i=e?JSON.stringify(e.error):r.lastError;n(`sendMessage ${JSON.stringify(t)} failed with error: ${i}`)}i(e)}))}))}},Ax=(()=>{let e;return{getInstance:function(t,i){return i.config.enableWebRtcInternalsLogs&&Ot.isBrowser("EdgeAnaheim")&&chrome?.runtime?(e||(e=new wx(t)),e):(t.safe.info("WebRTC internal logging is disabled"),{collect:()=>Promise.resolve(""),updateSessionCount:()=>Promise.resolve()})}}})(),Px=class{getId(){return 0}getDeviceId(){return Gi.EMPTY_DEVICE_ID}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return"display"}getType(){return 1}getIcon(e,t){return Promise.resolve(null)}},Rx=class{constructor(e){this.descr=e}getId(){return 0}getDeviceId(){return this.descr.browserId}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return this.descr.label}getType(){return 3}getIcon(e,t){return Promise.resolve(null)}},Mx=class{constructor(e){this.deviceManager=e,this.sharingSource=new Px}onScreensChanged(e){return{dispose:()=>{}}}enumerateScreensAsync(){return Promise.resolve([this.sharingSource])}enumerateWindowsAsync(){return Promise.resolve([])}async enumerateCamerasAsync(){return(await this.deviceManager.enumerateDevicesAsync()).filter((e=>"camera"===e.kind)).map((e=>new Rx(e)))}},Dx=class{constructor(e){this.configProvider=e,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(e){const t="connected"===e?this.activeTmpRecord:this.getTmpRecord();t&&t.events[t.events.length-1]?.type!==e&&(t.events.push({type:e,time:Date.now()-t.startTime}),"networkOnline"===e?this.data.networkRecoveredCount++:"connected"===e&&this.data.disconnectedRecoveredCount++,"reconnect"!==e&&"connected"!==e||(t.endTime=Date.now()-t.startTime,this.activeTmpRecord=null))}registerReconnectAttempt(e){this.activeRecord&&(this.activeAttempt={direction:e,startTime:Date.now()-this.activeRecord.startTime,status:!1},this.data.isReconnecting=!0,rt(this.activeRecord.attempts,this.activeAttempt,this.configProvider.config.diagnostics.collectionLimits.numReconnectRecords))}registerReconnectAttemptStatus(e){"completed"===e&&(this.data.isReconnecting=!1),this.activeAttempt&&this.activeRecord&&(this.activeAttempt.endTime=Date.now()-this.activeRecord.startTime,this.activeAttempt.status="completed"===e)}registerReconnect(e){if(this.data.reconnectCount[e]++,this.data.isReconnecting="attempted"===e,"attempted"===e){if(this.activeRecord)return;this.activeRecord={startTime:Date.now(),attempts:[]},rt(this.data.records,this.activeRecord,this.configProvider.config.diagnostics.collectionLimits.numReconnects)}else if("connected"===e){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(e){this.data.retargetCount[e]++}registerEscalation(e){this.data.escalationCount[e]++}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}},kx=class{constructor(){}process(e){return this.mediaLegId=e||this.mediaLegId||sn().toUpperCase(),this.mediaLegId}},Ox=class{constructor(e,t){this.relayManager=e,this.diagnostics=t}initialize(){}setRelayOverride(){}async queryRelaysAsync(e){const t=await this.relayManager.queryRelaysAsync(e);return t.length>0&&(this.diagnostics.relay=t[0]),t}getStats(){return this.relayManager.getStats?.()??{stats:{unavailable:"1"}}}getAuthTokenStats(){return this.relayManager.getAuthTokenStats()}},Nx=class{constructor(e,t,i){this.stats=e,this.diag=t,i&&t&&(i.reconnect=t.getObject())}registerState(e){this.diag?.registerState(e)}registerReconnectAttempt(e){this.stats.registerReconnectAttempt(e),this.diag?.registerReconnectAttempt(e)}registerReconnectAttemptStatus(e){switch(e){case"completed":this.stats.registerReconnectAttemptCompleted();break;case"rejected":this.stats.registerReconnectAttemptRejected()}this.diag?.registerReconnectAttemptStatus(e)}registerReconnect(e){switch(e){case"attempted":this.stats.registerReconnectAttempted();break;case"connected":this.stats.registerReconnectConnected()}this.diag?.registerReconnect(e)}registerRetarget(e){switch(e){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(e)}registerEscalation(e){switch(e){case"attempted":this.stats.registerEscalationStart();break;case"completed":this.stats.registerEscalationCompleted();break;case"rejected":this.stats.registerEscalationRejected()}this.diag?.registerEscalation(e)}},Lx=class{constructor(e){this.initialCallbacks=e,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((e=>{e.method.apply(null,e.args)})),this.clear()}clear(){this.queue=[]}genCallback(e){return(...t)=>this.queue.push({method:e,args:t})}},xx=class{constructor(e,t){this.relayConfig=e,this.logger=t}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 e=0;this.probeDeferred=new Kt;const t=async()=>{await this.performCheck()&&this.finalize()},i=()=>{t(),e<3e3&&(e+=1e3),this.probeTimer=setTimeout(i,e)};return i(),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 e=this.tryCreatePc();if(!e)return!1;e.createDataChannel("probe");const t=new Kt;function i(i){e.onicecandidate=void 0,e.close(),t.resolve(i)}let n=!1;return e.onicecandidate=e=>{const t=e.candidate;if(!t)return n||this.logger.safe.info("still offline"),void i(n);const r=t.type??rm(t.candidate).type;"srflx"!==r&&"relay"!==r||(this.logger.safe.info(`Back online through ${r} candidate`),n=!0,"srflx"===r&&(this.ipFromRelay=t.address,i(!0)))},await e.setLocalDescription(await e.createOffer()),t.promise}tryCreatePc(){try{return new Mp.window.RTCPeerConnection({iceServers:this.relayConfig})}catch(e){return this.logger.safe.info(`Failed to create PC, errCode=${e.code}`),null}}},Fx=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],s=i.fqdns&&i.fqdns.length>0,a=t.iceUdpAddressType,o=t.iceTcpAddressType,l=t.iceServerTransport;if(!r&&!s)return e;if(l.includes("udp")&&i.udpPort){const e=!s||"fqdn"!==a&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.udpPort}?transport=udp`)}if(l.includes("tcp")&&i.tcpPort){const e=!s||"fqdn"!==o&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.tcpPort}?transport=tcp`)}return l.includes("tls")&&i.tlsPort&&s&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),Ux=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],s=i.fqdns&&i.fqdns.length>0,a=t.iceUdpAddressType,o=t.iceServerTransport;if(!r&&!s)return e;if(o.includes("udp")&&i.udpPort){const e=!s||"fqdn"!==a&&r?r:i.fqdns[0];n.push(`stun:${e}:${i.udpPort}`)}return o.includes("tls")&&i.tlsPort&&s&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),Bx=class{constructor(e,t,i,n,r,s,a,o){this.session=e,this.context=t,this.diagnostics=i,this.sessionOperationQueue=n,this.callback=r,this.sessionCallbacks=s,this.configProvider=a,this.relayManager=o,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 Kt},this.logger=t.getLogger().createChild("ReconnectManagerV2"),this.ufdManager=t.getUfdManager(),this.session.callbacks=s,this.reconnectManagerMessageQueue=new Lx(s),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)}get isOnline(){return!this.isOnlineDeferred}async createRelayProber(){if(!this._relayProber){const e=Date.now(),t=Ux(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config),i=Date.now()-e;this.logger.safe.info(`RelayProber configuration fetched in ${i} ms`),i>5e3&&this.diagnostics.registerState("relayConfigFetched"),this._relayProber=new xx(t,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(e){if(this.wasConnected)this.raiseReconnectEvent("Bad",e);else if(!this.settings.reconnectWithNoRelays&&!this.session.hasRelayCandidates())return void this.onReconnectFailed("no relays",e);if(this.isDisconnected=!0,!this.isReconnecting()&&!this.isWaitingForNetwork)return this.logger.safe.info(`[${e}] reconnect attempt after iceDisconnect error`),this.session.transportStateProvider?.isFailed&&this.diagnostics.registerState("failed"),this.diagnostics.registerReconnect("attempted"),this.reconnectAsync(e)}onTransportDisconnect(e){this.isDisconnected=!0,this.wasConnected&&(this.diagnostics.registerState("disconnected"),this.handleTmpConnectivityLoss(e))}onConnected(e){this.isDisconnected=!1,this.logger.safe.info(`[${e}] set allow UFD`),this.diagnostics.registerState("connected"),this.raiseReconnectEvent("Good",e),this.wasConnected=!0,this._relayProber?.finalize()}onNegotiationCompletedAsync(e){return this.logger.safe.info(`[${e}] handle negotiation completed`),this.setSignalingState(!0),this.isReconnecting()&&(this.diagnostics.registerRetarget("completed"),2===this.escalationType&&this.blockCurrentSession(e)),Promise.resolve()}async onSessionErrorOccurred(e,t){this.logger.safe.info(`[${t}] handle session error`,tt(e)),await this.rejectReconnect(t),this.isReconnectAllowed()?await this.scheduleReconnectRetry(t,!1,!1):this.callback.onSessionErrorOccurred(e,t,this.wasConnected)}onNegotiationRejection(e,t){this.logger.safe.info(`[${t}] handle negotiation rejection`),this.diagnostics.registerRetarget("rejected");const i=1===this.escalationType;return this.rejectReconnect(t).then((()=>{const n=e.type===Gi.RENEGOTIATION_ERROR.glare&&i;(e.type!==Gi.RENEGOTIATION_ERROR.glare||i)&&(this.isRecoverableError(e.type)||n?this.scheduleReconnectRetry(t,n,i):this.onReconnectFailed(tt(e),t))}))}async ensureNetwork(e){const t=this.isOnline;if(!this.isOnline){this.logger.safe.info(`[${e}] waiting for network...`);try{await this.isOnlineDeferred.promise}catch(t){return void this.logger.safe.info(`${e} call disposed while waiting for network`)}this.logger.safe.info(`[${e}] network seems up`)}if(this.isDisconnected){const i=await this.createRelayProber(),n=await i.ensureOnline();this.logger.safe.info(`[${e}] probing complete in ${n} ms`),this.diagnostics.registerState("relaysUp"),t&&n<1e3&&this.logger.safe.info(`[${e}] looks like network failed on remote side, recovery was quick`)}}oldSessionIsOnline(e){return!!this.session?.transportStateProvider?.isConnected&&(this.logger.safe.info(`[${e}] old session recovered`),this.isReconnecting()||this.diagnostics.registerReconnect("connected"),!0)}async waitForNetworkAndTryLightweightRecovery(e){const t=this.oldSessionIsOnline(e);if(t||!this.settings.reconnectWithProbes)return t;this.setReconnectTimer(),this.isWaitingForNetwork=!0;const i=this.getMaxNetworkWaitTime();return this.logger.safe.info(`[${e}] can wait up to ${i} ms`),await Promise.race([this.ensureNetwork(e),Yt(i)]),this.isWaitingForNetwork=!1,this.session&&(this.session.transportStateProvider?.isConnected||this.session.transportStateProvider?.isFailed||(this.logger.safe.info(`[${e}] giving session a moment to recover`),await Yt(this.settings.reconnectWaitTimeAfterProbe)),this.oldSessionIsOnline(e))?(this.resetReconnectTimer(),!0):this.checkIfTimerFailed(e)?(this.logger.safe.info(`[${e}] session reconnect timer reached during network checks`),!0):!!this.isDisposing&&(this.logger.safe.info(`[${e}] session is disposed`),!0)}reconnectAsync(e,t=!1,i=!1,n){return this.logger.safe.info(`[${e}] queueing reconnect, force=${t}, escalation=${i}`),this.diagnostics.registerReconnectAttempt(i?"local escalation":"out"),this.context.getSmallCallTelemetry()?.setEventType("reconnect"),this._isReconnectScheduled=!0,i&&(this.escalationType=1,this.onReconnectCompleted=n),this.sessionOperationQueue.queueOperation((async()=>{if(this._isReconnectScheduled=!1,t||!await this.waitForNetworkAndTryLightweightRecovery(e))return this.isReconnecting()?(this.logger.safe.info(`[${e}] ongoing reconnect is in progress`),void this.sessionOperationQueue.completeCurrentOperation()):(this.diagnostics.registerState("reconnect"),await this.initReconnect(e),await this.reconnectSession.configureModalitiesAsync(this.getConfiguredModalities(),e),void this.sessionOperationQueue.completeCurrentOperation());this.sessionOperationQueue.completeCurrentOperation()}),e)}async acceptReconnectStartAsync(e,t){return this.logger.safe.info(`[${t}] accepting reconnect`),this.diagnostics.registerRetarget("incoming"),e?(this.escalationType=2,this.diagnostics.registerEscalation("attempted")):(!this.isReconnecting()&&this.isDisconnected?this.diagnostics.registerReconnect("attempted"):this.isReconnecting()&&await this.rejectReconnect(t),this.diagnostics.registerState("reconnect"),this.diagnostics.registerReconnectAttempt("in")),this.initReconnect(t)}acceptReconnectFinish(e){const t=this.getConfiguredModalities();return this.reconnectSession.configureModalitiesAsync(t,e).then((()=>t))}isReconnecting(){return!!this.reconnectSession}isReconnectScheduled(){return this._isReconnectScheduled}cleanUp(){this.sessionCallbacks=null,this.reconnectSession=null}async terminateAsync(e){try{await(this.session?.terminate(e,{}))}catch{}try{await this.terminateReconnectSessionAsync(e,!0)}catch{}this.cleanUp()}completeReconnect(e){return this.logger.safe.info(`[${e}] completing reconnect`),2===this.escalationType&&(this.unblockCurrentSession(e),this.diagnostics.registerEscalation("completed")),this.escalationType=0,this.reconnectSession&&(this.context.config.isConference=this.isReconnectConference,this.disposeActiveSession(e),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(e){this.logger.safe.info(`[${e}] rejecting reconnect`),this.setSignalingState(!1),2===this.escalationType&&this.diagnostics.registerEscalation("rejected"),this.escalationType=0,this.reconnectSession&&(await this.terminateReconnectSessionAsync(e,!1),this.diagnostics.registerReconnectAttemptStatus("rejected")),this.session&&(this.reconnectManagerMessageQueue.flush(),this.session.callbacks=this.sessionCallbacks,this.unblockCurrentSession(e))}configureModalitiesAsync(e,t,i){this.lastKnownConfiguredModalities=e;const n=[];return this.session&&n.push(this.session.configureModalitiesAsync(e,t,i)),this.reconnectSession&&n.push(this.reconnectSession.configureModalitiesAsync(e,t,i)),Promise.all(n).then((()=>Promise.resolve()))}canSendDtmf(){return this.getMainSession().canSendDtmf()}muteHold(e,t){this.getMainSession().muteHold(e,t)}muteInputAsync(e){return this.getMainSession().muteInputAsync(e)}unmuteInputAsync(e){return this.getMainSession().unmuteInputAsync(e)}muteOutputAsync(e){return this.getMainSession().muteOutputAsync(e)}unmuteOutputAsync(e){return this.getMainSession().unmuteOutputAsync(e)}async getSpeakerVolume(e){return this.getMainSession().getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.getMainSession().setSpeakerVolume(e,t)}_deviceSelectionChanged(){this.session&&this.session.deviceSelectionChanged(),this.reconnectSession&&this.reconnectSession.deviceSelectionChanged()}disposeActiveSession(e){if(this.session&&this.isReconnecting()){this.logger.safe.info(`[${e}] About to dispose current session...`);const t=this.session;return this.lastKnownConfiguredModalities=this.session.getConfiguredModalities(),t.callbacks=this.reconnectManagerMessageQueue.queueCallbacks,t.move(this.reconnectSession,e),this.session=null,t.terminate(e,{},!1)}return Promise.resolve()}registerRetargetOutgoing(){this.diagnostics.registerRetarget("outgoing")}isSignalingStable(){return this._isSignalingStable}getConfiguredModalities(){return this.getMainSession().getConfiguredModalities()||this.lastKnownConfiguredModalities}checkIfTimerFailed(e){return!(this.isReconnectAllowed()||this.session&&!this.session.transportStateProvider?.isFailed||(this.onReconnectFailed("the time limit was reached",e),0))}async scheduleReconnectRetry(e,t,i){const n=this.getReconnectDelayTime();if(this.logger.safe.info(`[${e}] scheduling reconnect retry attempt in ${n}`),await Yt(n),t||!this.checkIfTimerFailed(e))return this.reconnectAsync(e,i,i,this.onReconnectCompleted)}isRecoverableError(e){return Gi.RENEGOTIATION_ERROR.media===e||Gi.RENEGOTIATION_ERROR.signaling===e}async resetReconnectSession(e){this.logger.safe.info(`[${e}] Resetting reconnect session. Session exists: old: ${!!this.session}, new: ${!!this.reconnectSession}`),this.isReconnectConference=0!==this.escalationType||this.context.config.isConference;const t=0!==this.escalationType||this.context.config.isConference&&this.wasConnected&&!this.isDisconnected,i=this.getMainSession(),n=this.configProvider.getConfigView(this.isReconnectConference,i.getSessionConfig()),r=i.clone(t,n);r.callbacks={...this.sessionCallbacks,onTransportConnected:e=>{2!==this.escalationType&&this.completeReconnect(e),this.onReconnectCompleted?.(),this.raiseReconnectEvent("Good",e),this.sessionCallbacks.onTransportConnected(e)}},this.session&&(this.session.callbacks={...this.reconnectManagerMessageQueue.queueCallbacks,onSessionErrorOccurred:(e,t)=>(e.type!==Gi.MEDIA_ERROR.iceConnectionError&&this.reconnectManagerMessageQueue.queueCallbacks.onSessionErrorOccurred(e,t),Promise.resolve())}),this.reconnectSession&&(this.reconnectSession.move(r,e),this.logger.safe.info(`[${e}] reconnect session still exists during reconnect clone operation`),await this.terminateReconnectSessionAsync(e,!1)),this.logger.safe.info(`[${e}] New session reset.`),this.reconnectSession=r}async initReconnect(e){this.logger.safe.info(`[${e}] initiate reconnect`),this.setReconnectTimer(),await this.resetReconnectSession(e),this.setSignalingState(!1),this.session&&(this.blockCurrentSession(e),await Promise.all([this.reconnectSession.muteInputAsync(e),this.reconnectSession.muteOutputAsync(e)]))}blockCurrentSession(e){this.logger.safe.debug(`[${e}] blocking current session negotiations`),this.negotiationPausePromise=this.session.pauseNegotiations(e)}unblockCurrentSession(e){this.negotiationPausePromise&&(this.logger.safe.debug(`[${e}] unblocking current session negotiations`),this.negotiationPausePromise.resolve(),this.negotiationPausePromise=null)}raiseReconnectEvent(e,t){this.ufdManager.signalEvent("NetworkReconnect",e,"Audio",!0,t)}async terminateReconnectSessionAsync(e,t){if(this.reconnectSession){const i=new Lx(this.sessionCallbacks);this.reconnectSession.callbacks={...i.queueCallbacks,onTerminated:t?this.sessionCallbacks.onTerminated:i.queueCallbacks.onTerminated},await this.reconnectSession.terminate(e,{},!1),i.clear(),this.reconnectSession=null}}setReconnectTimer(){const e=this.wasConnected?this.settings.reconnectTimeLimit:this.settings.initialReconnectTimeLimit;e>0&&!this.reconnectTimer&&(this.reconnectTimerStart=Date.now(),this.reconnectTimer=window.setTimeout((()=>this.resetReconnectTimer()),e))}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 e=this.reconnectTimerStart>0?Date.now()-this.reconnectTimerStart:0;return Math.max(this.settings.reconnectTimeLimit-e,0)}onReconnectFailed(e,t){this.callback.onSessionErrorOccurred({type:Gi.MEDIA_ERROR.iceConnectionError,detail:`Reconnect failed, error - ${tt(e)}`},t,this.wasConnected)}setSignalingState(e){this._isSignalingStable=e}async handleTmpConnectivityLoss(e){this.logger.safe.info(`[${e}] Session went into disconnected state, giving it ${this.settings.losingConnectivityTimeoutMs}ms to recover`),-1!==this.settings.losingConnectivityTimeoutMs&&(await Yt(this.settings.losingConnectivityTimeoutMs),this.isDisconnected&&this.raiseReconnectEvent("Poor",e)),this.isDisconnected&&this.settings.reconnectOnDisconnect&&(this.logger.safe.info(`[${e}] Session is still down, triggering reconnect`),this.onIceDisconnect(e))}},Vx=class{constructor(e,t){this.stats=e,this.diagnostics=t}set mediaLegId(e){this.stats.setMediaLegId(e.process()),this.diagnostics&&(this.diagnostics.mediaLegId=e)}set isMultiParty(e){e&&this.stats.setMultiParty(),this.diagnostics&&(this.diagnostics.isMultiParty=e)}set allowedModalities(e){this.stats.setSendModalities(e),this.diagnostics&&(this.diagnostics.allowedModalities=e)}set sessionError(e){this.stats.setError(e),this.diagnostics&&(this.diagnostics.sessionError=e)}set finalAnswerTime(e){this.stats.setFinalAnswerTimestamp(e),this.diagnostics&&(this.diagnostics.finalAnswerTime=e)}set dtmfResult(e){this.stats.dtmfResult(e),this.diagnostics&&(this.diagnostics.dtmfResult=e)}set swMute(e){this.stats.setSwMute(e),this.diagnostics&&(this.diagnostics.swMute=e)}set speakerMute(e){this.stats.setSpeakerMute(e),this.diagnostics&&(this.diagnostics.speakerMute=e)}set hwSilent(e){this.stats.setHwSilent(e),this.diagnostics&&(this.diagnostics.hwSilent=e)}set isSpeaking(e){this.stats.setSpeakingState(e),this.diagnostics&&(this.diagnostics.isSpeaking=e)}set iceConnectedStateTimestamp(e){this.stats.setIceConnectedStateTimestamp(e),this.diagnostics&&(this.diagnostics.iceConnectedStateTimestamp=e)}set iceInitTime(e){this.stats.setIceInitTimestamp(e),this.diagnostics&&(this.diagnostics.iceInitTime=e)}set ETag(e){this.stats.setETag(e),this.diagnostics&&(this.diagnostics.ETag=e)}set configIds(e){this.stats.setConfigIds(e),this.diagnostics&&(this.diagnostics.configIds=e)}set relay(e){this.stats.setRelay(e),this.diagnostics&&(this.diagnostics.relay=e)}negotiationStart(e){switch(this.diagnostics?.negotiationStart(e),e){case"Offering":this.stats.negotiation.offering.started();break;case"Answering":this.stats.negotiation.answering.started()}}negotiationCompleted(e){this.stats.negotiation.current.completed(e),this.diagnostics?.negotiationCompleted(e)}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(e){this.stats.registerRollbackEvent(e),this.diagnostics?.registerRollbackEvent(e)}registerRawMediaAccess(e,t,i){"send"===t?this.stats.registerSetInputRawMedia(i):this.stats.registerOutputRawMediaAccess(),this.diagnostics?.registerRawMediaAccess(e,t,i)}registerQualityStateChangedEvent(e){this.stats.registerQualityStateChangedEvent(e),this.diagnostics?.registerQualityStateChangedEvent(e)}terminated(e){this.stats.terminated(e),this.diagnostics?.terminated(e)}registerRemoteQualityStateChangedEvent(e,t){this.stats.registerRemoteQualityStateChangedEvent(e,t),this.diagnostics?.registerRemoteQualityStateChangedEvent(e,t)}},Hx=class{constructor(e){this.logger=e,this.operationQueue=null,this.currentOperationDeferred=null,this.operationQueue=new tk(this.logger)}queueOperation(e,t=be()){this.logger.safe.info(`[${t}] queueing operation`);const i=new Kt,n=this.operationQueue.add((()=>(this.currentOperationDeferred=i,e())),t);return this.operationQueue.add(i,t),n}completeCurrentOperation(){this.currentOperationDeferred&&(this.logger.safe.info("completing operation"),this.currentOperationDeferred.resolve())}},$x=class extends Vi{constructor(e,t,i,n,r,s,a,o=i.getLogger().createChild("SessionV2",t)){super(o),this.context=i,this.callback=n,this.statistics=r,this.configProvider=s,this.diagnostics=a,this.logger=o,this.audioStreamStates={[Gi.STREAMING_STATE.inactive]:[Gi.STREAMING_STATE.started,Gi.STREAMING_STATE.active,Gi.STREAMING_STATE.failed],[Gi.STREAMING_STATE.started]:[Gi.STREAMING_STATE.active,Gi.STREAMING_STATE.removed,Gi.STREAMING_STATE.stopped,Gi.STREAMING_STATE.failed],[Gi.STREAMING_STATE.active]:[Gi.STREAMING_STATE.removed,Gi.STREAMING_STATE.stopped,Gi.STREAMING_STATE.failed]},this.mediaLegId=new kx,this.rejectedNegotiations=0,this.negotiationState=null,this.audioStreamState=Gi.STREAMING_STATE.inactive,this.deviceManagerDisposables=[],this.visibilityChangedHandler=()=>{if(this.logger.safe.debug(`document.visibilityState changed: ${document.visibilityState}`),"visible"===document.visibilityState&&this.pcClosedInfo){const e=this.pcClosedInfo;this.pcClosedInfo=null,Date.now()<e.timestamp+this.configProvider.config.reconnectWakeupTimeLimit?(this.logger.safe.info(`[${e.causeId}] start reconnect after wakeup`),this.startReconnect(e.causeId)):(this.logger.safe.info(`[${e.causeId}] terminate a call after wakeup because allowed time limit for reconnect exceeded`),this.endCallOnFailure(e.mediaError,e.causeId))}"hidden"===document.visibilityState&&this.context.getSmallCallTelemetry()?.setEventType("visibilityHidden")},this.ufdManager=i.getUfdManager(),this.ufdManagerDisposable=this.ufdManager.on("onQualityChanged",(e=>this.qualityChanged(e))),this.sessionOperationQueue=new Hx(this.logger),this.mediaLegId=new kx,this.diagnosticsWrapper=new Vx(this.statistics,this.diagnostics),this.statistics.setId(t),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.diagnosticsWrapper.ETag=this.configProvider.ETag,this.diagnosticsWrapper.configIds=this.configProvider.ecsConfigIds,this.diagnosticsWrapper.isMultiParty=!!i.config.isConference,this.recoverableErrors=this.configProvider.config.recoverableMediaErrors.split(","),this.forceReconnectErrors=this.configProvider.config.forceReconnectErrors.split(",");const l=this.getSessionCallbacks();e.callbacks=l,e.relayManagerProvider=this,this.reconnectManager=new Bx(e,i,new Nx(this.statistics,this.diagnostics?new Dx(this.configProvider):void 0,this.diagnostics),this.sessionOperationQueue,this.getReconnectManagerCallbacks(),l,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",((e,t)=>this.deviceListChanged(t)))),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount()),this.diagnostics&&(this.diagnostics.relayManager=this.getRelayManager()),this.ufdManager.applyCurrentState((e=>this.qualityChanged(e))),document.addEventListener("visibilitychange",this.visibilityChangedHandler),this.requestWakeLock()}async requestWakeLock(){if(Vp.isWakeLockSupported()&&this.configProvider.config.useWakeLockApi)try{this.wakeLock=await window.navigator.wakeLock.request("screen")}catch(e){this.logger.safe.info(`Wakelock request failed - ${e.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(e,t){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Offering");try{const i=await this.getCurrentSession().createOfferAsync(e,t);return this.updateSelectedDevices(),i.mediaLegId=this.mediaLegId.process(i.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.reconnectManager.isReconnecting()&&!this.reconnectManager.isSignalingStable()&&(this.reconnectManager.registerRetargetOutgoing(),i.newOffer=!0),i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),e)}registerRemoteQualityStateChangedEvent(e,t){this.diagnosticsWrapper.registerRemoteQualityStateChangedEvent(e,t)}setCallConstraints(e,t){return this.getCurrentSession().setCallConstraints(e,t)}processOfferAsync(e,t){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Answering"),e.mediaLegId=this.mediaLegId.process(e.mediaLegId);try{e.newOffer&&await this.reconnectManager.acceptReconnectStartAsync(e.escalationOccurring,t);const i=await this.getCurrentSession().processOfferAsync(e,t);if(e.newOffer){const e=await this.reconnectManager.acceptReconnectFinish(t);return i.sharing===Gi.MEDIA_STATE.sendReceive&&(i.sharing=e.sharing===Gi.MEDIA_STATE.send?Gi.MEDIA_STATE.send:Gi.MEDIA_STATE.receive),i}return i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),t)}async processAnswerAsync(e,t,i,n){try{return this.configProvider.config.muteDuringRemotePranswer&&(i&&!this.callMuteState&&(this.logger.safe.info(`[${t}] Muting input before processing full answer`),await this.muteInputAsync(t),this.lastMuteFromPranswer=!0),!i&&this.lastMuteFromPranswer&&(this.logger.safe.info(`[${t}] Unmuting input before processing full answer`),await this.unmuteInputAsync(t),this.lastMuteFromPranswer=!1)),await this.getCurrentSession().processAnswerAsync(e,t,i,n)}catch(e){throw this.lastMuteFromPranswer=!1,this.diagnosticsWrapper.sessionError=e,e}}async completeNegotiationAsync(e){this.rejectedNegotiations=0;try{const t=await this.getCurrentSession().completeNegotiationAsync(e);return this.negotiationState=t,this.diagnosticsWrapper.finalAnswerTime=Date.now(),this.diagnosticsWrapper.negotiationCompleted?.(t.activeModalities),await this.reconnectManager.onNegotiationCompletedAsync(e),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}ignoreNotReconnectError(e){return e.detail?.type!==Gi.MEDIA_ERROR.incompatibleOriginator}async rejectNegotiationAsync(e,t){this.logger.safe.info(`[${t}] rejectNegotiationAsync`,e);try{if(this.reconnectManager.isReconnecting()&&this.ignoreNotReconnectError(e))return await this.reconnectManager.onNegotiationRejection(e,t),this.registerNegotiationRejection(this.negotiationState),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState;{const i=await this.getCurrentSession().rejectNegotiationAsync(e,t,this.isRenegotiationAllowed(e.type));return this.sessionOperationQueue.completeCurrentOperation(),this.registerNegotiationRejection(i),i}}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}completeEscalationAsync(e){return this.reconnectManager.completeReconnect(e)}rejectEscalationAsync(e){return this.reconnectManager.rejectReconnect(e)}async terminate(e,t){this.logger.safe.info(`terminate reject reason: ${JSON.stringify(t||"")}`),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(t);const i=()=>this.cleanUp();return this.reconnectManager.terminateAsync(e).then(i,i)}async getStatsAsync(e){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.getMainSession().getStatsAsync(e).then((e=>this.prepareStats(e)))}getLastKnownStats(e=!1){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.prepareStats(this.getMainSession().getLastKnownStats(e),e)}getCallTechnicalInfo(){return this.diagnostics?.realtimeTelemetryReport}async createAnswerAsync(e,t){try{const i=await this.getCurrentSession().createAnswerAsync(e,t);return this.updateSelectedDevices(),i.mediaLegId=this.mediaLegId.process(i.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}configureModalitiesAsync(e,t,i){return qi(e,((t,i)=>{t||delete e[i]})),this.reconnectManager.configureModalitiesAsync(e,t,i)}getAllowedModalities(){return this.deviceManager.getAllowedModalities()}createRemoteRenderer(e){return this.getMainSession().createRemoteRenderer(e)}async sendDtmf(e){try{const t=await this.getMainSession().sendDtmf(e);return this.diagnosticsWrapper.dtmfResult=!0,t}catch(e){throw this.diagnosticsWrapper.dtmfResult=!1,e}}canSendDtmf(){return this.reconnectManager.canSendDtmf()}muteHold(e,t){this.reconnectManager.muteHold(e,t)}muteInputAsync(e){return this.callMuteState=!0,this.diagnosticsWrapper.swMute=!0,this.lastMuteFromPranswer=!1,this.reconnectManager.muteInputAsync(e)}unmuteInputAsync(e){return this.callMuteState=!1,this.diagnosticsWrapper.swMute=!1,this.lastMuteFromPranswer=!1,this.reconnectManager.unmuteInputAsync(e)}muteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!0,this.reconnectManager.muteOutputAsync(e)}unmuteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!1,this.reconnectManager.unmuteOutputAsync(e)}async getSpeakerVolume(e){return this.reconnectManager.getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.reconnectManager.setSpeakerVolume(e,t)}getAcceptedTypes(){return this.reconnectManager.getCurrentSession().getAcceptedTypes()}useNullAudioStreamClient(){this.getCurrentSession().useNullAudioStreamClient()}createAudioElement(e){this.getCurrentSession().createAudioElement(e)}getIncomingRawAudioStream(e){return this.diagnosticsWrapper.registerRawMediaAccess("audio","recv",!0),this.getCurrentSession().getIncomingRawAudioStream(e)}getUnmixedAudioProvider(){return this.getCurrentSession().getUnmixedAudioProvider()}deviceSelectionChanged(){this.updateSelectedDevices(),this.reconnectManager._deviceSelectionChanged()}registerDeviceTelemetryEvent(e){this.getCurrentSession().onDeviceEvent(e),this.statistics.registerDeviceTelemetryEvent(e)}registerVideoEffectsTelemetryEvent(e){this.statistics.registerVideoEffectsTelemetryEvent(e)}registerAudioEffectsTelemetryEvent(e){this.statistics.registerAudioEffectsTelemetryEvent(e)}reconnectAsync(e,t=!1,i){return this.reconnectManager.reconnectAsync(e,!0,t,i)}isReconnecting(){return this.reconnectManager.isReconnecting()}getRelayManager(){return this.relayManager??(this.relayManager=new Ox(this.context.maContext.getRelayManager(),this.diagnosticsWrapper))}getSessionConfig(){return this.reconnectManager.getCurrentSession().getSessionConfig()}getDiagnostics(){return this.diagnostics}async getAudioSenderStats(){return this.getCurrentSession().getAudioSenderStats()}getLocalMediaTrackId(e){return this.reconnectManager.getMainSession().getLocalMediaTrackId(e)}getSubscriptionManager(){return this.getCurrentSession().getSubscriptionManager()}getDisabledModalities(){return this.getCurrentSession().getDisabledModalities()}configureSpatialAudio(e,t){this.getCurrentSession().configureSpatialAudio(e,t)}setParticipantSpatialAudioPositions(e,t){this.getCurrentSession().setParticipantSpatialAudioPositions(e,t)}startMediaDescriptionsUpdateAsync(e,t){return this.getCurrentSession().startMediaDescriptionsUpdateAsync(e,t)}completeMediaDescriptionsUpdateAsync(e){return this.getCurrentSession().completeMediaDescriptionsUpdateAsync(e)}rejectMediaDescriptionsUpdateAsync(e,t){return this.getCurrentSession().rejectMediaDescriptionsUpdateAsync(e,t)}processNotification(e,t){this.getCurrentSession().processNotification(e,t)}getMediaControlPlaneInstance(){return this.getCurrentSession().getMediaControlPlaneInstance()}async cleanUp(){this.callback=null,this.deviceManagerDisposables.forEach((e=>e.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 e=this.deviceManager.getSelectedDevices(),t=e=>e?this.deviceManager.getDeviceNameAsync(e).then((e=>fn(e,this.configProvider.config.devices.piiSafeWords))):Promise.resolve("none");Promise.all([t(e.microphone),t(e.speaker),t(e.camera)]).then((([e,t,i])=>{this.statistics.setUsedDevices({microphone:e,speaker:t,camera:i})}))}getCurrentSession(){return this.reconnectManager.getCurrentSession()}getMainSession(){return this.reconnectManager.getMainSession()}setAudioStreamState(e,t,i){this.isAudioStateValid(e)?this.raiseAudioStateChanged(e,t,i):this.logger.safe.error(`[${t}] audio state transition is invalid: ${this.audioStreamState} -> ${e}`)}isAudioStateValid(e){return this.audioStreamStates[this.audioStreamState].indexOf(e)>=-1}raiseAudioStateChanged(e,t,i){if(this.logger.safe.info(`[${t}] audio state changed to ${e}`),this.callback.onAudioStateChanged){const t={content:"audio",direction:"receive",stream:e};this.callback.onAudioStateChanged(t,i)}}getReconnectManagerCallbacks(){return{onSessionErrorOccurred:(e,t,i)=>{this.isNetworkMediaError(e)&&!i&&this.ufdManager.raisePendingWhitelistingUFD(),this.endCallOnFailure(e,t)}}}isNetworkMediaError(e){return e.type===Gi.MEDIA_ERROR.iceConnectionError||e.type===Gi.MEDIA_ERROR.noNetworkError}isRecoverableMediaError(e){return this.recoverableErrors.includes(e.type)}startReconnect(e=be()){return this.reconnectManager.onIceDisconnect(e)}shouldForceReconnect(e){return this.forceReconnectErrors.includes(e.type)}isUnexpectedPcClose(e){return e.type===Gi.MEDIA_ERROR.unexpectedClose}getSessionCallbacks(){return this.sessionCallbacks||(this.sessionCallbacks={onTerminated:()=>{this.logger.safe.warn("call onTerminated"),this.event("onTerminated").raise(this)},onSessionErrorOccurred:(e,t=be())=>this.isUnexpectedPcClose(e)?this.handlePcClosed(e,t):this.shouldForceReconnect(e)?this.reconnectManager.reconnectAsync(t,!0):this.isRecoverableMediaError(e)?this.reconnectManager.isReconnecting()?this.reconnectManager.onSessionErrorOccurred(e,t):this.startReconnect(t):(this.endCallOnFailure(e,t),Promise.resolve()),onNegotiationRequired:(e,t)=>this.callback.onNegotiationRequired(e,t),onAudioHwSilentChanged:e=>{this.diagnosticsWrapper.hwSilent=e},onAudioStateChanged:(e,t)=>{this.setAudioStreamState(e,t)},onTransportConnected:(e=be())=>{this.logger.safe.info(`[${e}] Transport connectivity established`),this.ufdManager.cancelPendingWhitelistingUFD(),this.reconnectManager.onConnected(e),this.diagnosticsWrapper.registerTransportConnected(),this.diagnosticsWrapper.iceConnectedStateTimestamp=Date.now(),this.callback?.onTransportConnected(e)},onTransportDisconnected:(e=be())=>{this.logger.safe.warn(`[${e}] Transport connectivity lost`),this.reconnectManager.onTransportDisconnect(e),this.diagnosticsWrapper.registerTransportDisconnected(),this.callback?.onTransportDisconnected?.(e)},onTransportFailed:()=>{this.diagnosticsWrapper.registerTransportFailed(),this.callback?.onTransportFailed?.()},onTransportInitialized:()=>{this.diagnosticsWrapper.iceInitTime=Date.now()},onUpdateMediaDescriptionsRequired:(e,t)=>this.callback.onUpdateMediaDescriptionsRequired(e,t),onTeamsRealtimeTelemetryReport:()=>this.callback.onRealtimeTelemetryReport()}),this.sessionCallbacks}registerNegotiationRejection(e){this.rejectedNegotiations++,this.diagnosticsWrapper.negotiationRejected?.(),e.rollback&&this.diagnosticsWrapper.registerRollbackEvent(e.rollback)}isRenegotiationAllowed(e){return this.rejectedNegotiations<this.context.configProvider.config.renegotiationAttempts&&!this.reconnectManager.isReconnectScheduled&&(Gi.RENEGOTIATION_ERROR.signaling===e||Gi.RENEGOTIATION_ERROR.media===e)}prepareStats(e,t=!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 i=this.statistics.generateStatistics(e,this.mediaLegId,t);return this.configProvider.config.diagnostics.features.useNewerStatisticsMetrics&&(i.data.metrics=this.diagnostics?.telemetryReport?.data.metrics),!e.data.Extensions?.StartTime&&this.configProvider.config.diagnostics.features.useFallbackToNewExtensions&&(i.data.Extensions=this.diagnostics?.telemetryReport?.data.Extensions),i}deviceListChanged(e){e&&this.statistics.deviceChangedByPoll(),this.statistics.devicesChanged(),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount())}qualityChanged(e){const t=e.deviceManagerId;!t||this.context.callDeviceManager.hasDevice(t)?(this.context.getSmallCallTelemetry()?.setEventType(e.type),this.callback?.onQualityChanged&&(this.diagnosticsWrapper.registerQualityStateChangedEvent(e),"DeviceSpeakWhileMuted"===e.type&&(this.diagnosticsWrapper.isSpeaking="Good"!==e.value),this.callback.onQualityChanged(e))):this.logger.info(`${t} - is not added to Call, skipping UFD.`)}endCallOnFailure(e,t,i){this.callback&&(this.callback.onSessionErrorOccurred&&this.callback.onSessionErrorOccurred(e,t),this.diagnosticsWrapper.sessionError=e,this.setAudioStreamState(Gi.STREAMING_STATE.failed,t,i))}async handlePcClosed(e,t){const i=this.configProvider.config.reconnectWakeupTimeLimit;return this.logger.safe.info(`[${t}] handle unexpected PC closed event`,`visibilityState=${document.visibilityState}, wakeupLimit=${this.configProvider.config.reconnectWakeupTimeLimit}`),"visible"===document.visibilityState?this.startReconnect(t):i?void(this.pcClosedInfo={timestamp:Date.now(),causeId:t,mediaError:e}):this.endCallOnFailure(e,t,"suspended")}},jx=class{constructor(e){this.creationTime=e,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(e){if(!this.activeRecord)return null;this.activeAttempt={direction:e,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(e){this.activeAttempt&&this.activeRecord&&(this.activeAttempt.status=e,this.activeAttempt.endTime=this.getTimestamp())}getTimestamp(){return Date.now()-this.creationTime-this.activeRecord.startTime}},Gx=window.navigator,qx=class{constructor(e="Good"){this.stopWatches=[],this.currentLevel=e,this.getStopWatch(e).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getElapsed(e){const t=this.stopWatches[e];return t?t.elapsed:0}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new GL,this.stopWatches[e]=t),t}},zx=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})?$/),Wx=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})?$/),Kx=class{constructor(e,t,i){this.configProvider=e,this.callNumber=t,this.sessionDiagnostics=i,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 qx,this.networkSend=new qx,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 GL,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 GL,this.osMute=new GL,this.hwSilent=new GL,this.isSpeaking=new GL,this.swMute=new GL,this.speakerMute=new GL,this.deviceTelemetryEvents=[],this.videoEffectsTelemetryEvents=new $M(this.configProvider.config.effectsTelemetryBufferSize),this.audioEffectsTelemetryEvents=new $M(this.configProvider.config.effectsTelemetryBufferSize),this.devicesCount=null,this.reconnectStats=new jx(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 GL},this.rawInputAudioOverride={attempt:0,timer:new GL},this.connectionEffectiveTypeSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionRttSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionDownlinkSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.navigatorConnectionInterval=setInterval((()=>{const e=Gx?.connection;e&&("number"==typeof e.downlink&&this.connectionDownlinkSeries.add(e.downlink),"number"==typeof e.rtt&&this.connectionRttSeries.add(e.rtt),"number"==typeof e.effectiveType&&this.connectionEffectiveTypeSeries.add(e.effectiveType))}),this.configProvider.config.navConnectionPollingInterval),this.durationTimer.start()}terminated(e){this.terminationReason=nn(e),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(e,t){this.deviceList=e.map((e=>({label:fn(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.kind}))),t&&(this.deviceDebugStrings=nn(t))}setPermissionStates(e){this.permissionStates=e}setSwMute(e){e?this.swMute.start():this.swMute.stop(),this.updateCommonMute()}setSpeakerMute(e){e?this.speakerMute.start():this.speakerMute.stop()}setHwSilent(e){e?this.hwSilent.start():this.hwSilent.stop()}setSpeakingState(e){e?this.isSpeaking.start():this.isSpeaking.stop()}setETag(e){this.ETag=e}setConfigIds(e){this.configIds=e}setVideoEffectStats(e){e&&this.videoEffectsTelemetryEvents.add(e)}setAudioEffectStats(e){e&&this.audioEffectsTelemetryEvents.add(e)}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.noIceCandidatesGoodEventCount++:this.noIceCandidatesBadEventCount++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.noRelayIceCandidatesGoodEventCount++:this.noRelayIceCandidatesBadEventCount++;break;case"DeviceCaptureNotFunctioning":"Good"===e.value?this.microphoneInUseGoodEventCount++:this.microphoneInUseBadEventCount++;break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.cameraInUseGoodEventCount++:this.cameraInUseBadEventCount++;break;case"DeviceCaptureMute":"Audio"===e.mediaType&&("Bad"===e.value?this.osMute.start():this.osMute.stop(),this.updateCommonMute());break;case"NetworkRecvQuality":this.networkRecv.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.cameraFreezeEndEventCount++:this.cameraFreezeStartEventCount++}"DeviceSpeakWhileMuted"!==e.type&&this.ufds.push({...e,timestamp:Date.now()-this.creationTime}),this.ufds.length>this.configProvider.config.maxStoredUFDCount&&this.ufds.shift()}registerRemoteQualityStateChangedEvent(e,t){e.forEach((e=>{rt(this.remoteUfds,{...e,participantId:t,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(e){e&&this.rollbackNegotiation.push({type:e.type,attempt:this.rollbackNegotiation.length+1,error:e.error?e.error:""})}registerReconnectAttempted(){this.reconnectAttemptedCount++,this.reconnectStats.onReconnectStart()}registerReconnectConnected(){this.reconnectConnectedCount++,this.reconnectStats.onReconnectConnected()}registerDeviceTelemetryEvent(e){e.timestamp=e.timestamp-this.creationTime,this.deviceTelemetryEvents.push(e)}registerVideoEffectsTelemetryEvent(e){e&&(e.timestamp=e.timestamp-this.creationTime,this.videoEffectsTelemetryEvents.add(e))}registerAudioEffectsTelemetryEvent(e){if(e){e.timestamp=e.timestamp-this.creationTime;const t=this.audioEffectsTelemetryEvents.items.pop();t&&this.audioEffectsChanged(t,e)&&this.audioEffectsTelemetryEvents.add(t),this.audioEffectsTelemetryEvents.add(e)}}audioEffectsChanged(e,t){return e.payload.fallback!==t.payload.fallback||void 0!==t.payload.userNoiseSuppressionMethod&&e.payload.userNoiseSuppressionMethod!==t.payload.userNoiseSuppressionMethod||void 0!==t.payload.userAudioEffect&&e.payload.userAudioEffect!==t.payload.userAudioEffect}registerReconnectAttempt(e){this.reconnectStats.onReconnectAttempt(e)}registerReconnectAttemptCompleted(){this.reconnectStats.onReconnectCompleted()}registerReconnectAttemptRejected(){this.reconnectStats.onReconnectRejected()}setMediaLegId(e){this.mediaLegId=e}setId(e){this.sessionId=e}setError(e){e.type===Gi.MEDIA_ERROR.incompatibleOffer&&(this.incompatibleOffer=!0),this.mediaError.type=e.type||Gi.MEDIA_ERROR.internalError,this.mediaError.detail=e.detail||e.toString()}setRelay(e){this.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}setRelayManagerTimers(e){this.relayManagerTimers=e}setSendModalities(e){this.allowedAudioSend=e.audio.some((e=>Wp(e))),this.allowedVideoSend=e.video.some((e=>Wp(e))),this.allowedScreensharingSend=e.sharing.some((e=>Wp(e)))}setIceInitTimestamp(e){this.iceInitTime||(this.iceInitTime=e)}setFinalAnswerTimestamp(e){this.finalAnswerTime||(this.finalAnswerTime=e)}setIceConnectedStateTimestamp(e){this.iceConnectedStateTime||(this.iceConnectedStateTime=e)}dtmfResult(e){e?++this.dtmfSuccess:++this.dtmfFailure}setUsedDevices(e){this.usedDevices&&JSON.stringify(e)!==JSON.stringify(this.usedDevices)&&this.deviceSelectionChangeCount++,this.usedDevices=e}setDevicesCount(e){this.devicesCount=e}setMediaQosEnabled(e){this.mediaQosEnabled=e}setPortRangeConfigured(e){this.portRangeConfigured=e}devicesChanged(){this.devicesChangeCount++}deviceChangedByPoll(){this.devicesPollChangeCount++}registerOutputRawMediaAccess(){this.rawOutputAudioAccess.attempt++,this.rawOutputAudioAccess.timer.start()}registerSetInputRawMedia(e){this.rawInputAudioOverride.attempt++,e?this.rawInputAudioOverride.timer.start():this.rawInputAudioOverride.timer.stop()}getReport(){const e=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:e.microphone,UsedSpeaker:e.speaker,UsedCamera:e.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(wn(vn(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),remoteUfdsCount:this.sessionDiagnostics?.getObjectRef().remoteUfdsCount,MediaQosEnabled:this.mediaQosEnabled,PortRangeConfigured:this.portRangeConfigured,RollbackNegotiation:JSON.stringify(this.rollbackNegotiation),hardwareConcurrency:Vp.hardwareConcurrency,GPUName:Vp.unmaskedGlRenderer,Connection_Downlink:Pn(this.connectionDownlinkSeries.items,(e=>e)),Connection_EffectiveType:this.connectionEffectiveTypeSeries.items.filter((e=>e)).join(","),Connection_Rtt:Pn(this.connectionRttSeries.items,(e=>e)),Connection_SaveData:Gx?.connection?.saveData,MediaByPassEnabled:!!this.configProvider.mediaConfig.mediaBypassEnabled,CallConstraints:JSON.stringify(this.configProvider.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(dx(this.sessionDiagnostics?.getObjectRef().dominantSpeaker,this.terminationTime))}}generateStatistics(e,t,i=!1){if(this.setMediaLegId(t.process()),"WebRtcMediaStats"!==e.type)throw new Error(`Unknown stats type - ${e.type}`);if(i){const e=this.deviceTelemetryEvents.length;this.deviceTelemetryEvents.splice(0,e-1),this.deviceDebugStrings=Pk,this.audioEffectsTelemetryEvents.clear()}e.data.metrics=this.getReport();const n=this.sessionDiagnostics?.getObjectRef().statsErrors;if(n?.length)if(e.data.Extensions?.WebRTCStats?.statsErrors){const t=JSON.parse(e.data.Extensions.WebRTCStats.statsErrors);t.push(...n),e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(t)}else e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(n);const r={};return zi(e.data,((e,t,i)=>{let n=0;zx.test(e)?(n=13,r[t]="IPv4"):Wx.test(e)&&(n=4,r[t]="IPv6"),i[t]={type:n,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(r),__VALUE__:!0},e}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:e=>{this.initialNegotiationCompleted=!0,this.activeModalities=e,this.resetError()},rejected:()=>{++this.rejectedNegotiationCount}}}getDurationRatio(e){const t=this.getCurrentDuration();return e/(0!==t?t:1)}getCurrentDuration(){return this.durationTimer.elapsed}getHpTimeFromMillis(e){return 1e4*e}},Jx=class{constructor(e,t,i,n){this.onActiveSpeakersChanged=e,this.onDominantSpeakersChanged=t,this.logger=i,this.diagnostics=n}setStrategy(e){this.disposeStrategy(),this.dshStrategy=e,this.dshStrategy?.setOnDominantSpeakerChanged(this.onDominantSpeakerHistoryChanged.bind(this)),this.diagnostics?.setCurrentActiveStrategy("client")}onContributingSourcesChanged(e){this.onActiveSpeakersChanged(e),this.diagnostics?.contributingSourcesChanged(),this.dshStrategy?.setSources(e)}onDominantSpeakerHistoryChanged(e,t){this.onDominantSpeakersChanged(e),this.diagnostics?.recordHistoryEvent(e,t),"client"!==t&&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}},Yx=class{constructor(e){this.listener=e,this.streams=[]}add(e){this.streams.some((t=>t.getId()===e.getId()))||(this.streams.push(e),this.listener.streamAdded(e))}remove(e){let t;Qi(this.streams,(i=>i.getId()===e&&(t=i,!0)))&&this.listener.streamRemoved(t)}getStreams(){return this.streams}clear(){this.streams.forEach((e=>e.dispose())),this.streams=[]}},Qx=p(ye()),Zx=class{constructor(e,t,i){this.logger=e,this.qualityManager=t,this.configProvider=i}getControlItem(){return this.controlItem}setControlItem(e){this.controlItem=e}dispose(){this.controlItem=null}setVideoControlMessage(e){this.controlItem=this.messageToControlItem(e),this.logger.safe.info(`BW limit requested to ${this.controlItem.bandwidth}`)}modifyDescriptor(e){if(!this.controlItem)return e;const t=Qx.parse(e.sdp);if(!t.media[1])return this.logger.unsafe.warn("video modality is disabled, skipping sdp modification, ",e),e;const i=this.getCurrentResolutionBitrate();this.logger.safe.info(`Select the BW limit as min of requested ${this.controlItem.bandwidth} and Current Resolution Max BR ${i}`);const n=this.getSessionBitrate(t),r=Math.min(i,this.controlItem.bandwidth,n);if(t.media[1].bandwidth)t.media[1].bandwidth[0].limit=r;else{const e={limit:r,type:"AS"};t.media[1].bandwidth=[e]}return e.sdp=Qx.write(t),e}messageToControlItem(e){const t=new SO(e.controlVideoStreaming.controlInfo[0].fmtParams),i="max-br";if(!t.contains(i))return null;const n=Math.round(1.2*+t.get(i));return{sourceId:e.controlVideoStreaming.controlInfo[0].sourceId,streamMsid:e.controlVideoStreaming.controlInfo[0].streamMsid,bandwidth:n}}getCurrentResolutionBitrate(){const e=this.qualityManager.getCurrentResolution(),t=Hn.Send.getResolutionByFs(e);return e&&t?Math.floor(Hn.Send.getBitrateForResolution(t.width,t.height).maxBitrate/1e3):Number.MAX_VALUE}getSessionBitrate(e){let t=Number.MAX_SAFE_INTEGER;return this.configProvider.mediaConfig.maxBandwidthInKbps&&(t=this.configProvider.mediaConfig.maxBandwidthInKbps),e.bandwidth&&(t=Math.min(+e.bandwidth[0].limit,t)),t-(this.configProvider.config.audioBandwidthInKbps||0)}},Xx=class{constructor(e,t,i){this.pc=e,this.configProvider=t,this.logger=i.createChild("MediaRollbackModifier")}modifyDescriptor(e){const t=Qx.parse(e.sdp);return Qx.parse(this.pc.localDescription.sdp).media.forEach(((e,i)=>{const n=t.media[i];(NO(e)&&!e.bundleOnly||!n||NO(n))&&(this.logger.safe.info(`Adding disabled media ${e.type}, position ${i}`),t.media[i]=SL(e.type,void 0,e.protocol,void 0))})),new QN(this.configProvider).modify(t),e.sdp=Qx.write(t),e}},eF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send){this.diagnostics.handlePresentationAudioInputLevel();for(const i of e.send)try{t.add(i.outboundRTP.id);let e=this.sendExtenders.get(i.outboundRTP.id)??new nF(this.diagnostics,this.configProvider);i.outboundRTP.bytesSent<e.lastBytes&&(e=new nF(this.diagnostics,this.configProvider)),this.sendExtenders.set(i.outboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:send",tt(e))}}if(Mn(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new tF(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new tF(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:recv",tt(e))}Mn(this.recvExtenders,t)}},tF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.totalSamplesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.concealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.silentConcealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.concealedRatioAverager=new qM,this.stretchedRatioAverager=new qM,this.codecSwitchesTracker=new QM,this.packetDurationTracker=new QM,this.jitterAverager=new qM,this.jitterBufferDelayAverager=new qM,this.lastBytes=0}processSample(e){let t,i,n,r,s;const a=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDiff.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp),this.totalSamplesReceivedDiff.captureSample(e.inboundRTP.totalSamplesReceived,e.inboundRTP.timestamp),this.concealedSamplesDiff.captureSample(e.inboundRTP.concealedSamples,e.inboundRTP.timestamp),this.silentConcealedSamplesDiff.captureSample(e.inboundRTP.silentConcealedSamples,e.inboundRTP.timestamp);const o=this.bytesReceivedDiff.delta&&8*this.bytesReceivedDiff.delta;this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const l=e.inboundRTP.jitterBufferDelay&&e.inboundRTP.jitterBufferEmittedCount&&mn(e.inboundRTP.jitterBufferDelay/e.inboundRTP.jitterBufferEmittedCount*1e3,0);if(this.jitterAverager.captureSample(1e3*e.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(e.inboundRTP.jitterBufferDelay),t=this.totalSamplesReceivedDiff.delta&&this.concealedSamplesDiff.delta&&this.silentConcealedSamplesDiff.delta&&mn((this.concealedSamplesDiff.delta-this.silentConcealedSamplesDiff.delta)/this.totalSamplesReceivedDiff.delta),e.customHealerStats){e.customHealerStats.numSamplesPerFrame&&(r=e.customHealerStats.decodedSamples/e.customHealerStats.numSamplesPerFrame,s=e.customHealerStats.cngSamples/e.customHealerStats.numSamplesPerFrame),t=e.customHealerStats.healedSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),n=e.customHealerStats.concealSamples&&e.customHealerStats.concealSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),i=e.customHealerStats.stretchSamples&&e.customHealerStats.stretchSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples);const a=e.customHealerStats.packetDurationInMs&&e.customHealerStats.packetDurationInMs>100?100:e.customHealerStats.packetDurationInMs;this.concealedRatioAverager.captureSample(n),this.stretchedRatioAverager.captureSample(i),this.codecSwitchesTracker.captureSample(`${e.customHealerStats.pullAdspPayloadType}`),this.packetDurationTracker.captureSample(`${a}`)}e.extensions={lossRate:a,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,healedRatio:t,jitterBufferMs:l,bitrate:o||0,customHealerStats:e.customHealerStats&&{concealedDataRatio:n,concealedDataRatioMax:this.concealedRatioAverager.maxSample,stretchedDataRatio:i,stretchedDataRatioMax:this.stretchedRatioAverager.maxSample,numberOfDecodedFrames:r,usageMetricsCodecId:this.codecSwitchesTracker.sortedDurations,percentageOfPtime:this.packetDurationTracker.durationRatios,pushPacketProcessingTimes:e.customHealerStats.pushProcessingTimes,pullPacketProcessingTimes:e.customHealerStats.pullProcessingTimes,pullProcessingTimePerStreamNumber:e.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:e.customHealerStats.pullTimings,cnpPushCount:e.customHealerStats.cnpPushCount,cnpPullCount:e.customHealerStats.cnpPullCount,numberOfCNFrames:s,redPacketsCount:e.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:e.customHealerStats.pullNumOfStreamsCounter},jitterAvg:mn(this.jitterAverager.avg),jitterBufferDelayMs:mn(this.jitterBufferDelayAverager.avg)},this.duration++}},iF=class{constructor(){this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.jitterBufferAverager=new qM,this.jitterAverager=new qM,this.jitterBufferDelayAverager=new qM,this.healedRatioAverager=new qM}processSample(e,t,i){const n=e[0],r={inboundRTP:n.inboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.healedRatioAverager.captureSample(n.extensions.healedRatio),this.jitterBufferAverager.captureSample(n.extensions.jitterBufferMs),this.jitterAverager.captureSample(1e3*n.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(n.inboundRTP.jitterBufferDelay);const e=n.inboundRTP.packetsReceived+n.inboundRTP.packetsLost;r.aggregated={lossRateMax:this.lossRateAverager.maxSample,lossRateAvg:this.lossRateAverager.avg,networkAvgLossRate:e>0?n.inboundRTP.packetsLost/e:0,packetsLostAvg:this.duration>0?n.inboundRTP.packetsLost/this.duration:0,duration:this.duration,bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(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:n.extensions.customHealerStats&&{concealedDataRatio:n.extensions.customHealerStats.concealedDataRatio,concealedDataRatioMax:n.extensions.customHealerStats.concealedDataRatioMax,stretchedDataRatio:n.extensions.customHealerStats.stretchedDataRatio,stretchedDataRatioMax:n.extensions.customHealerStats.stretchedDataRatioMax,numberOfDecodedFrames:n.extensions.customHealerStats.numberOfDecodedFrames,usageMetricsCodecId:n.extensions.customHealerStats.usageMetricsCodecId,percentageOfPtime:n.extensions.customHealerStats.percentageOfPtime,pushPacketProcessingTimes:n.extensions.customHealerStats.pushPacketProcessingTimes,pullPacketProcessingTimes:n.extensions.customHealerStats.pullPacketProcessingTimes,pullProcessingTimePerStreamNumber:n.extensions.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:n.extensions.customHealerStats.pullTimings,cnpPushCount:n.extensions.customHealerStats.cnpPushCount,cnpPullCount:n.extensions.customHealerStats.cnpPullCount,numberOfCNFrames:n.extensions.customHealerStats.numberOfCNFrames,redPacketsCount:n.extensions.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:n.extensions.customHealerStats.pullNumOfStreamsCounter}},this.duration++}Sn(t,r,i)}},nF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.bytesSendDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.rttAverager=new qM,this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost)??0;this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDiff.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDiff.delta;this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,bitrate:i?8*i:0,rttAvg:mn(this.rttAverager.avg),callIsMuted:this.diagnostics.callIsMuted,rawInputVolume:this.diagnostics.audioLevel},this.duration++}},rF=class{constructor(e){this.diagnostics=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.rttAverager=new qM}processSample(e,t,i){const n=e[0],r={outboundRTP:n.outboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),r.aggregated={duration:this.duration,lossRateMax:this.lossRateAverager.maxSample,bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),rttAvg:mn(this.rttAverager.avg),rttMax:mn(this.rttAverager.maxSample),rawInputVolume:this.diagnostics.audioLevel,audioLevel:n.track?.audioLevel??n.mediaSource?.audioLevel},this.duration++),Sn(t,r,i)}},sF=Z,aF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send&&(0,sF.flatMap)(e.send,(e=>[e,...e.altLayouts??[]])).forEach((e=>{try{t.add(e.outboundRTP.id);let i=this.sendExtenders.get(e.outboundRTP.id)??new cF(this.diagnostics,this.configProvider);e.outboundRTP.bytesSent<i.lastBytes&&(i=new cF(this.diagnostics,this.configProvider)),this.sendExtenders.set(e.outboundRTP.id,i),i.processSample(e)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:send",tt(e))}})),Mn(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new oF(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new oF(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:recv",tt(e))}Mn(this.recvExtenders,t)}},oF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.framesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.framesDecodedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.trackFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.decodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new KM(2):new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.prevTimeToFirstFrame=-1,this.hasPrevFramerate=!1,this.lastBytes=0,this.macroblockStatsTracker=new lD}processSample(e){const t=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.framesReceivedDelta.captureSample(e.inboundRTP.framesReceived,e.inboundRTP.timestamp),this.framesDecodedDelta.captureSample(e.inboundRTP.framesDecoded,e.inboundRTP.timestamp),this.trackFramesDelta.captureSample(e.inboundRTP.framesReceived??e.track?.framesReceived,e.inboundRTP.timestamp),this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const i=this.framesReceivedDelta.delta,n=this.framesDecodedDelta.delta;this.harmonicDecodedFps.captureSample(n),this.decodeTimeDelta.captureSample(e.inboundRTP.totalDecodeTime,e.inboundRTP.timestamp);const r=this.decodeTimeDelta.delta&&n&&mn(this.decodeTimeDelta.delta/n*1e3,2),s=n>0&&i>0,a=e.renderer?.timeToFirstFrame??(s?0:-1);this.freezeHistogram.active=-1!==a&&-1!==this.prevTimeToFirstFrame&&!s,"sharing"===e.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.prevTimeToFirstFrame=a,this.hasPrevFramerate=s,this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDelta.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp);const o=this.bytesReceivedDelta.delta,l=e.inboundRTP.jitterBufferEmittedCount&&mn((e.inboundRTP.jitterBufferDelay??0)/e.inboundRTP.jitterBufferEmittedCount*1e3),c=oD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,i||0),d=oD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,n||0);this.macroblockStatsTracker.captureSample(c,d),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,frameRateReceived:i,frameRateDecoded:n,trackRecvFps:this.trackFramesDelta.delta,decodeTime:r||0,jitterBufferMs:l,bitrate:o?8*o:0,isFrozen:this.freezeHistogram.active,macroblockRateReceived:c,macroblockRateDecoded:d,macroblockRateStats:this.macroblockStatsTracker.getReport(),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,powerEfficient:void 0!==e.inboundRTP.powerEfficientDecoder?e.inboundRTP.powerEfficientDecoder:rD(e.inboundRTP.decoderImplementation),totalFreezeFraction:this.duration?this.freezeHistogram.totalDuration/this.duration:0,fpsHarmonicAverage:mn(this.harmonicDecodedFps.harmonicMean)},this.duration++}},lF=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.jitterAverager=new qM,this.frameRateAverager=new qM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.resolutionDurations=new QM,this.codecCalculator=new cD}processSample(e,t,i){const n=e.sort(((e,t)=>t.inboundRTP.frameHeight*t.inboundRTP.frameWidth-e.inboundRTP.frameHeight*e.inboundRTP.frameWidth))[0],r={inboundRTP:n.inboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec,this.configProvider.config.isAv1Allowed&&"sharing"===n.mediaEntity?.modality&&this.codecCalculator.captureSample(n.codec.mimeType,n.renderer?.msi)),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions&&(this.harmonicDecodedFps.captureSample(n.extensions.frameRateDecoded),this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.jitterAverager.captureSample(1e3*(n.inboundRTP.jitter??0)),this.frameRateAverager.captureSample(n.extensions.frameRateReceived??n.extensions.frameRateDecoded),this.freezeHistogram.active=n.extensions.isFrozen,n.inboundRTP.frameWidth&&n.inboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.inboundRTP.frameWidth}x${n.inboundRTP.frameHeight}`),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,avgFrameRate:mn(this.frameRateAverager.avg),fpsHarmonicAverage:mn(this.harmonicDecodedFps.harmonicMean),avgJitterBufferSize:mn(this.jitterAverager.avg),bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),bitrateMinNonZero:mn(this.bitrateAverager.minNonZeroSample,0),ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,numFreezes:this.freezeHistogram.numEvents,avgFreezeDuration:mn(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:n.extensions.macroblockRateStats,codecReport:this.codecCalculator?.report},this.duration++),rt(t,r,i)}},cF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.lossRateAverager=new qM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.hasPrevFramerate=!1,this.captureFreezeIntervalsCount=0,this.bytesSendDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.encodedFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sentFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.harmonicEncodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.encodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new KM(2):new WM,this.qpDelta=this.useLastSampleDeltaPerSecondConverter?new KM(3):new WM,this.fsOvershoot=new tD("fs"),this.fpsOvershoot=new tD("fps",1),this.brOvershoot=new tD("br"),this.plisDelta=new WM,this.pliRate=new sD(60),this.resolutionSwitcherTracker=new aD(this.configProvider.config.diagnostics.collectionLimits.numResolutionSwitches),this.bitrateAverager=new qM,this.rttAverager=new qM,this.powerEfficientEncoderChangeTracker=new dD(this.configProvider.config.diagnostics.collectionLimits.numPowerEfficientEncoderEvents),this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost);this.lossRateAverager.captureSample(t),this.plisDelta.captureSample(e.outboundRTP.pliCount),this.pliRate.captureSample(this.plisDelta.delta),this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDelta.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDelta.delta,n=i?8*i:void 0;this.bitrateAverager.captureSample(n),this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),this.encodedFramesDelta.captureSample(e.outboundRTP.framesEncoded,e.outboundRTP.timestamp);const r=this.encodedFramesDelta.delta;this.sentFramesDelta.captureSample(e.outboundRTP.framesSent,e.outboundRTP.timestamp);const s=this.sentFramesDelta.delta||0;this.harmonicEncodedFps.captureSample(r);const a=e.mediaSource?.framesPerSecond;0===a&&void 0!==this.lastCaptureFramerate&&this.lastCaptureFramerate>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFramerate=a;const o=r>0&&s>0;this.freezeHistogram.active=!o,"sharing"===e.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.hasPrevFramerate=o,this.encodeTimeDelta.captureSample(e.outboundRTP.totalEncodeTime,e.outboundRTP.timestamp);const l=this.encodeTimeDelta.delta&&r&&mn(this.encodeTimeDelta.delta/r*1e3,2);this.qpDelta.captureSample(e.outboundRTP.qpSum,e.outboundRTP.timestamp);const c=this.qpDelta.delta&&r&&mn(this.qpDelta.delta/r,2);e.outboundRTP.frameWidth&&e.outboundRTP.frameHeight&&this.resolutionSwitcherTracker.captureSample(e.outboundRTP.frameWidth,e.outboundRTP.frameHeight);const d=this.diagnostics.deviceManager?.latestCameraOpenResolution,u=e.appliedCapabilities??e.requestedCapabilities;u&&(void 0!==e.outboundRTP.frameHeight&&void 0!==e.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(e.outboundRTP.frameHeight/16*(e.outboundRTP.frameWidth/16),u.maxFs),this.fpsOvershoot.captureSample(s,u.maxFps),u.maxBr&&this.brOvershoot.captureSample(n,u.maxBr));const h=[...this.fsOvershoot.events,...this.brOvershoot.events,...this.fpsOvershoot.events];if(h.sort(((e,t)=>e.timestamp-t.timestamp)),e.outboundRTP.frameHeight&&(e.outboundRTP.powerEfficientEncoder||e.outboundRTP.encoderImplementation)){const t=void 0!==e.outboundRTP.powerEfficientEncoder?e.outboundRTP.powerEfficientEncoder:rD(e.outboundRTP.encoderImplementation);this.powerEfficientEncoderChangeTracker.captureSample(t,e.outboundRTP.frameHeight)}e.extensions={cameraOpenResolution:d,lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,pliRate:this.pliRate.getRate(),frameRateEncoded:this.encodedFramesDelta.delta,frameRateSent:s,bitrate:n||0,encodeTime:l||0,qp:c||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:h,powerEfficient:this.powerEfficientEncoderChangeTracker.curPowerEfficientEncoderState,powerEfficientEncoderEvents:this.powerEfficientEncoderChangeTracker.events,powerEfficientEncoderEventOnCount:this.powerEfficientEncoderChangeTracker.eventOnCount,powerEfficientEncoderEventOffCount:this.powerEfficientEncoderChangeTracker.eventOffCount,bitrateAvg:mn(this.bitrateAverager.avg,0),rttAvg:mn(this.rttAverager.avg)},this.duration++}},dF=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.sendBWEAverager=new qM,this.rttAverager=new qM,this.framerateAverager=new qM,this.captureFpsAverager=new qM,this.captureFreezeIntervalsCount=0,this.lastCaptureFps=void 0,this.resolutionDurations=new QM,this.fsOvershoot=new tD("fs"),this.fpsOvershoot=new tD("fps",1),this.brOvershoot=new tD("br"),this.harmonicEncodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax)}processSample(e,t,i){e.length>1&&e.sort(((e,t)=>{const i=e.appliedCapabilities??e.requestedCapabilities,n=t.appliedCapabilities??t.requestedCapabilities;return i?.maxMbps&&n?.maxMbps?n.maxMbps-i.maxMbps:0}));const n=e[0],r={outboundRTP:n.outboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.sendBWEAverager.captureSample(n.transport?.selectedCandidatePair?.availableOutgoingBitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),this.framerateAverager.captureSample(n.extensions.frameRateSent);const e=n.mediaSource?.framesPerSecond;this.captureFpsAverager.captureSample(e),0===e&&void 0!==this.lastCaptureFps&&this.lastCaptureFps>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFps=e,n.outboundRTP.frameWidth&&n.outboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.outboundRTP.frameWidth}x${n.outboundRTP.frameHeight}`);const t=n.appliedCapabilities??n.requestedCapabilities;t&&(void 0!==n.outboundRTP.frameHeight&&void 0!==n.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(n.outboundRTP.frameHeight/16*(n.outboundRTP.frameWidth/16),t.maxFs),this.fpsOvershoot.captureSample(n.extensions.frameRateSent,t.maxFps),t.maxBr&&this.brOvershoot.captureSample(n.extensions?.bitrate,t.maxBr)),this.harmonicEncodedFps.captureSample(n.extensions.frameRateEncoded);const i=[...this.fsOvershoot.events,...this.fpsOvershoot.events,...this.brOvershoot.events];i.sort(((e,t)=>e.timestamp-t.timestamp)),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,frameRateAvg:mn(this.framerateAverager.avg),captureFramerateAvg:mn(this.captureFpsAverager.avg),fpsHarmonicAverage:mn(this.harmonicEncodedFps.harmonicMean),qpAvg:mn(n.outboundRTP.qpSum/n.outboundRTP.framesSent),rttAvg:mn(this.rttAverager.avg),bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),bitrateMinNonZero:mn(this.bitrateAverager.minNonZeroSample,0),bweAvg:mn(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:i},this.duration++}rt(t,r,i)}},uF=class{constructor(e){this.configProvider=e,this.samplesCountPerSubscription=0,this.data=new $M(this.configProvider.config.diagnostics.collectionLimits.numVideoSubscriptionStats)}prepareCollectingStatsOnSubscribed(e){this.samplesCountPerSubscription=0,this.data.add({timestamp:Date.now(),framesDecoded:[],bytesReceived:[],height:[],msi:e})}captureStatsOnSubscribed(e,t,i){if(this.samplesCountPerSubscription>=this.configProvider.config.diagnostics.collectionLimits.numVideoStatsAfterSubscription)return;const n=Cn(this.data.items);n&&(e&&n.framesDecoded.push(e),t&&n.bytesReceived.push(t),i&&n.height.push(i)),this.samplesCountPerSubscription++}get videoStatsOnSubscribed(){return this.data.items}},hF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){const t=new Set;for(const i in e)try{t.add(i);const n=e[i],r=this.extenders.get(n.id)??new gF(this.configProvider,this.diagnostics);this.extenders.set(n.id,r),r.processSample(n)}catch(e){this.diagnostics.addStatsError("TransportStatsProcessor",tt(e))}Mn(this.extenders,t)}},gF=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.bwJumpsHistogramCollector=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.sendBWEAverager=new qM,this.recvBWEAverager=new qM,this.sendBW=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvBW=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sendBWAverager=new qM,this.recvBWAverager=new qM}processSample(e){this.sendBWEAverager.captureSample(e.selectedCandidatePair?.availableOutgoingBitrate),this.recvBWEAverager.captureSample(e.selectedCandidatePair?.availableIncomingBitrate),this.sendBW.captureSample(e.selectedCandidatePair?.bytesSent,e.selectedCandidatePair?.timestamp),this.recvBW.captureSample(e.selectedCandidatePair?.bytesReceived,e.selectedCandidatePair?.timestamp);const t=this.sendBW.delta,i=this.recvBW.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendBWAverager.captureSample(n),this.recvBWAverager.captureSample(r);const s=e.selectedCandidatePair?.availableOutgoingBitrate;s&&(this.bwJumpsHistogramCollector.active=this.bwJumpsHistogramCollector.active&&s<this.configProvider.config.webrtcBWJumpUpperLimit||s<this.configProvider.config.webrtcBWJumpLowerLimit),e.extensions={sendBWEAvg:mn(this.sendBWEAverager.avg,0),sendBWEMax:mn(this.sendBWEAverager.maxSample,0),recvBWEAvg:mn(this.recvBWEAverager.avg,0),recvBWEMax:mn(this.recvBWEAverager.maxSample,0),sendBitrate:n,recvBitrate:r,sendBWAvg:mn(this.sendBWAverager.avg,0),sendBWMax:mn(this.sendBWAverager.maxSample,0),recvBWAvg:mn(this.recvBWAverager.avg,0),recvBWMax:mn(this.recvBWAverager.maxSample,0),bwJumpsHistogram:this.bwJumpsHistogramCollector.counts,reflexiveLocalIP:this.diagnostics.reflexiveLocalIP}}},pF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){if(!e)return;const t=new Set;for(const i of e)try{t.add(i.id);const e=this.extenders.get(i.id)??new mF(this.configProvider);this.extenders.set(i.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("DataChannelStatsProcessor",tt(e))}Mn(this.extenders,t)}},mF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.sendBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sendMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM}processSample(e){this.sendBytesDeltaCalculator.captureSample(e.bytesSent,e.timestamp),this.recvBytesDeltaCalculator.captureSample(e.bytesReceived,e.timestamp);const t=this.sendBytesDeltaCalculator.delta,i=this.recvBytesDeltaCalculator.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendMessagesDeltaCalculator.captureSample(e.messagesSent,e.timestamp),this.recvMessagesDeltaCalculator.captureSample(e.messagesReceived,e.timestamp);const s=this.sendMessagesDeltaCalculator.delta,a=this.recvMessagesDeltaCalculator.delta;e.extensions={sendBitrate:n,recvBitrate:r,sendMessageRate:s,recvMessageRate:a}}},fF=class{constructor(e,t,i,n){this.slidingWindowSize=e,this.maxDeviation=t,this.minBandwidth=i,this.directionalityCheck=n,this.slidingWindow=new $M(this.slidingWindowSize),this.currentModality=null,this.previousModality=null,this.inProcess=!1}processBandwidth(e,t,i){this.currentModality?this.handleStopEvent(t,i):this.handleStartEvent(t,i),this.inProcess&&(this.stabilizationTime++,this.slidingWindow.add(e),this.inProcess=!this.slidingWindow.isFull||!this.isBandwidthStable())}getReport(e=!1){if(void 0!==this.stabilizationTime)return{time:this.inProcess?this.stabilizationTime:Math.max(this.stabilizationTime-this.slidingWindowSize,0),bandwidth:e?mn(this.averageBandwidth,2):this.averageBandwidth,finished:!this.inProcess,modality:this.previousModality}}handleStartEvent(e,t){this.currentModality=this.GetModalityString(e),t&&this.currentModality&&!this.previousModality&&(this.previousModality=this.currentModality,this.stabilizationTime=0,this.slidingWindow.clear(),this.inProcess=!0)}handleStopEvent(e,t){t&&(this.directionalityCheck(e.audio)||this.directionalityCheck(e.video)||this.directionalityCheck(e.sharing))||(this.currentModality=null,this.inProcess=!1)}GetModalityString(e){return[this.directionalityCheck(e.audio)?Gi.MODALITY.audio:null,this.directionalityCheck(e.video)?Gi.MODALITY.video:null,this.directionalityCheck(e.sharing)?Gi.MODALITY.sharing:null].filter(Boolean).join(", ")}isBandwidthStable(){if(this.averageBandwidth=Yi(this.slidingWindow.items),this.averageBandwidth<this.minBandwidth)return!1;{const e=this.averageBandwidth*this.maxDeviation,t=this.averageBandwidth-e,i=this.averageBandwidth+e;return this.slidingWindow.items.every((e=>dn(e,t,i)))}}},vF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.uplinkStabilizationTelemetry=new fF(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wp),this.downlinkStabilizationTelemetry=new fF(this.configProvider.config.downlinkBWStabilizationSlidingWindowSize,this.configProvider.config.downlinkBWStabilizationMaxDeviation,this.configProvider.config.downlinkBWStabilizationMinBandwidth,Kp),this.bandwidthCalculator=new nD,this.bandwidthAvg=new qM}processStats(e){const t=this.diagnostics.getObjectRef(),i=t?.negotiation.activeModalities;if(!i||!e.transports)return;const n=e.transports[Object.keys(e.transports)[0]],r=t?.reportedReceiveBandwidth?.[t.reportedReceiveBandwidth.length-1],s=n?.selectedCandidatePair?.availableOutgoingBitrate,a=e.audio?.send?.length>0||e.video?.send?.length>0||e.sharing?.send?.length>0,o=e.audio?.recv?.length>0||e.video?.recv?.length>0||e.sharing?.recv?.length>0;this.bweType!==t?.negotiation.bweType&&(this.bandwidthCalculator=new nD,this.bandwidthAvg=new qM,this.bweType=t?.negotiation.bweType);const l="REMB"===t?.negotiation.bweType?"availableIncomingBitrate":"availableOutgoingBitrate",c=n?.selectedCandidatePair?.[l];this.bandwidthCalculator.captureSample(c),this.bandwidthAvg.captureSample(c);try{this.uplinkStabilizationTelemetry.processBandwidth(s,i,a),this.downlinkStabilizationTelemetry.processBandwidth(r,i,o)}catch(e){this.diagnostics.addStatsError("BandwidthStatsProcessor",tt(e))}}getStabilizedReport(e=!1){return this.uplinkStabilizationTelemetry.getReport(e)}getDownlinkStabilizedReport(e=!1){return this.downlinkStabilizationTelemetry.getReport(e)}calculateBwPercentiles(){if(!this.bandwidthCalculator.getFirst())return;const e=this.configProvider.config.bwPercentiles,t={};return e.forEach((e=>{Object.defineProperty(t,e,{value:this.bandwidthCalculator.calculatePercentile(e/100),enumerable:!0})})),t}getBandwidthReport(){return{startOfTheCall:this.bandwidthCalculator.getFirst(),endOfTheCall:this.bandwidthCalculator.getLast(),std:this.bandwidthCalculator.calculateStd(),bwPercentiles:this.calculateBwPercentiles(),avgBwe:mn(this.bandwidthAvg.avg,2)}}},SF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.videoSimulcastStreamsData={},this.videoLayoutProcessor=new yF(this.diagnostics,Gi.MODALITY.video),this.sharingSimulcastStreamsData={},this.sharingLayoutProcessor=new yF(this.diagnostics,Gi.MODALITY.sharing)}processStats(e){if(e.video?.send?.length){const t=e.video.send[0],i=[t,...t.altLayouts??[]];this.processSimulcastStream(i,this.videoSimulcastStreamsData),this.videoLayoutProcessor.processLayout(i)}if(e.sharing?.send?.length){const t=e.sharing.send[0],i=[t,...t.altLayouts??[]];this.processSimulcastStream(i,this.sharingSimulcastStreamsData),this.sharingLayoutProcessor.processLayout(i)}this.diagnostics.simulcastReport=this.getSimulcastDiagnostics()}processSimulcastStream(e,t){const{numAggregatedSamples:i}=this.configProvider.config.diagnostics.telemetryLimits;for(const n of e){const e=n.outboundRTP.rid;if(!e)continue;t[e]??(t[e]={sentLayerProcessor:new TF,appliedLayerProcessor:new TF,requestedLayerProcessor:new TF,encoderProcessor:new CF,debugResolutionTracker:new QM,outboundStats:[],report:{ssrc:n.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 r=t[e],{sentLayer:s,requestedLayer:a,appliedLayer:o}=this.getLayers(n);r.sentLayerProcessor.processLayer(s),r.appliedLayerProcessor.processLayer(o),r.requestedLayerProcessor.processLayer(a),r.encoderProcessor.processVideo(n),o&&s&&r.debugResolutionTracker.captureSample(`${o.width}x${o.height}:${s.width}x${s.height}`),rt(r.outboundStats,n.outboundRTP,i),r.report.time.sent=r.sentLayerProcessor.getTime(),r.report.time.applied=r.appliedLayerProcessor.getTime(),r.report.time.requested=r.requestedLayerProcessor.getTime(),r.report.duration.sent=r.sentLayerProcessor.getDuration(),r.report.duration.applied=r.appliedLayerProcessor.getDuration(),r.report.duration.requested=r.requestedLayerProcessor.getDuration(),r.report.restarts.sent=r.sentLayerProcessor.getRestarts(),r.report.restarts.applied=r.appliedLayerProcessor.getRestarts(),r.report.restarts.requested=r.requestedLayerProcessor.getRestarts(),r.report.resolution.sent=r.sentLayerProcessor.getResolutionDurations(),r.report.resolution.applied=r.appliedLayerProcessor.getResolutionDurations(),r.report.resolution.requested=r.requestedLayerProcessor.getResolutionDurations(),r.report.resolution.debug=r.debugResolutionTracker.durations,r.report.framerate.sent=r.sentLayerProcessor.getFpsDurations(),r.report.framerate.applied=r.appliedLayerProcessor.getFpsDurations(),r.report.framerate.requested=r.requestedLayerProcessor.getFpsDurations(),r.report.bitrate.sent=r.sentLayerProcessor.getBitrateDurations(),r.report.bitrate.applied=r.appliedLayerProcessor.getBitrateDurations(),r.report.bitrate.requested=r.requestedLayerProcessor.getBitrateDurations(),r.report.encoder=r.encoderProcessor.getEncoderReport(),r.report.stats.fir=Pn(r.outboundStats,(e=>e.firCount)),r.report.stats.nack=Pn(r.outboundStats,(e=>e.nackCount)),r.report.stats.pli=Pn(r.outboundStats,(e=>e.pliCount)),r.report.stats.packetsSent=Pn(r.outboundStats,(e=>e.packetsSent)),r.report.overshootEvents=n.extensions?.overshootEvents,r.report.totalBrOvershootDuration=n.extensions?.totalBrOvershootDuration,r.report.totalFpsOvershootDuration=n.extensions?.totalFpsOvershootDuration,r.report.totalFsOvershootDuration=n.extensions?.totalFsOvershootDuration,r.report.totalFreezeDuration=n.extensions?.totalFreezeDuration,r.report.ongoingFreezeDuration=n.extensions?.ongoingFreezeDuration,r.report.freezeHistogram=n.extensions?.freezeCountHistogram}}getSimulcastDiagnostics(){if(!Xi(this.videoSimulcastStreamsData)||!Xi(this.sharingSimulcastStreamsData))return{video:{streams:Object.fromEntries(Object.entries(this.videoSimulcastStreamsData).map((([e,{report:t}])=>[e,t]))),layouts:this.videoLayoutProcessor.getLayoutReport()},sharing:{streams:Object.fromEntries(Object.entries(this.sharingSimulcastStreamsData).map((([e,{report:t}])=>[e,t]))),layouts:this.sharingLayoutProcessor.getLayoutReport()}}}getLayers(e){const t=e.outboundRTP.rid,i=this.diagnostics.getObjectRef().qualityManager,n=e=>Object.values(e).find((e=>e.rid===t)),r="sharing"===e.mediaEntity?.modality?n(i.currentSharingSsrcAppliedCapabilities):n(i.currentVideoSsrcAppliedCapabilities),s="sharing"===e.mediaEntity?.modality?n(i.currentSharingSsrcRequestedCapabilities):n(i.currentVideoSsrcRequestedCapabilities);return{sentLayer:e.outboundRTP.frameHeight&&{height:e.outboundRTP.frameHeight,width:e.outboundRTP.frameWidth,framerate:e.extensions?.frameRateSent,bitrate:e.extensions?.bitrate},appliedLayer:r&&EF(r),requestedLayer:s&&EF(s)}}},yF=class{constructor(e,t){this.diagnostics=e,this.modality=t,this.sentResolutionTracker=new QM,this.requestedResolutionTracker=new QM,this.appliedResolutionTracker=new QM,this.debugResolutionTracker=new QM}processLayout(e){const t=e=>e.filter((e=>e.width&&e.height)).sort(((e,t)=>e.height-t.height)).map((e=>`${e.width}x${e.height}`)).join(":"),i=e=>Object.values(e).map(EF),n=t(e.map((e=>({height:e.outboundRTP.frameHeight,width:e.outboundRTP.frameWidth,framerate:e.extensions?.frameRateSent,bitrate:e.extensions?.bitrate})))),r=this.diagnostics.getObjectRef().qualityManager,s="sharing"===this.modality?r.currentSharingSsrcAppliedCapabilities:r.currentVideoSsrcAppliedCapabilities,a="sharing"===this.modality?r.currentSharingSsrcRequestedCapabilities:r.currentVideoSsrcRequestedCapabilities,o=t(i(s)),l=t(i(a));n&&this.sentResolutionTracker.captureSample(n),l&&this.requestedResolutionTracker.captureSample(l),o&&this.appliedResolutionTracker.captureSample(o),o&&n&&this.debugResolutionTracker.captureSample(`${o}->${n}`)}getLayoutReport(){return{requested:this.requestedResolutionTracker.durations,sent:this.sentResolutionTracker.durations,applied:this.appliedResolutionTracker.durations,debug:this.debugResolutionTracker.durations}}},CF=class{constructor(){this.report={}}processVideo(e){var t,i;const{encoderImplementation:n,frameWidth:r,frameHeight:s,rid:a}=e.outboundRTP,{encodeTime:o}=e.extensions;if(!n||!s)return;const l=function(e,t){if(e.startsWith("SimulcastEncoderAdapter")){const i=e.indexOf("(")+1,n={},r=e.indexOf(")");e.substring(i,r).split(",").forEach(((e,t)=>{n[`${t+1}`]=e.trim()})),e=n[t]??"Unknown"}switch(e){case"OpenH264":return"H264:SW";case"ExternalEncoder":case"MediaFoundationVideoEncodeAccelerator":case"VideoToolbox":case"WMFVideoEncoder":case"VTVideoEncoder":case"VaapiVideoEncodeAccelerator":return"H264:HW";default:return"H264:Other"}}(n,a),c=`${r}x${s}`;(t=this.report)[l]??(t[l]={resolutionTracker:new QM,encodingHistograms:{},report:{resolution:{},encodeTime:{},restarts:0}});const d=this.report[l];d.resolutionTracker.captureSample(c),(i=d.encodingHistograms)[c]??(i[c]=new QM),d.encodingHistograms[c].captureSample(function(e){return bF(e,[{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"}])}(o)),d.report.resolution=d.resolutionTracker.durations,d.report.encodeTime[c]=d.encodingHistograms[c].durations,this.prevEncoder&&this.prevEncoder!==l&&d.report.restarts++,this.prevEncoder=l}getEncoderReport(){return Object.fromEntries(Object.entries(this.report).map((([e,{report:t}])=>[e,t])))}},TF=class{constructor(){this.resolutionTracker=new QM,this.fpsTracker=new QM,this.bitrateTracker=new QM,this.durationTracker=new GL,this.startedAt=0}processLayer(e){e?(this.startedAt||(this.startedAt=_n()),this.durationTracker.start(),this.resolutionTracker.captureSample(`${e.width}x${e.height}`),this.fpsTracker.captureSample(function(e){return bF(e,[{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"}])}(e.framerate)),this.bitrateTracker.captureSample(function(e){return bF(e,[{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"}])}(e.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 EF(e){const t={...Hn.Send.getResolutionByFs(e.maxFs)};return 405===e.maxFs&&(t.width=426,t.height=240),{width:t.width,height:t.height,framerate:e.maxFps,bitrate:e.maxBr}}function bF(e,t){for(const{limit:i,label:n}of t)if(e>i)return n;return`${e}`}var _F=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.dataChannelStatsProcessor=new pF(this.diagnostics,this.configProvider),this.transportStatsProcessor=new hF(this.diagnostics,this.configProvider),this.audioStatsProcessor=new eF(this.diagnostics,this.configProvider),this.videoStatsProcessor=new aF(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new aF(this.diagnostics,this.configProvider),this.bandwidthStatsProcessor=new vF(this.diagnostics,this.configProvider),this.simulcastStatsProcessor=new SF(this.diagnostics,this.configProvider),this.macroblockStatsTracker=new lD,this.statsAggregators={audio:{recv:new iF,send:new rF(this.diagnostics)},video:{recv:new lF(this.configProvider),send:new dF(this.configProvider)},sharing:{recv:new lF(this.configProvider),send:new dF(this.configProvider)}},this.aggregatedModalityStats={},this.recvVideoStreamsCounter=new zM,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(e){const t=this.configProvider.config.diagnostics.enabledStatsProcessors;this.execute((()=>this.dataChannelStatsProcessor.processStats(e.data)),"dataChannelStatsProcessor",t.dataChannel),this.execute((()=>this.transportStatsProcessor.processStats(e.transports)),"transportStatsProcessor",t.transport),this.execute((()=>this.audioStatsProcessor.processStats(e.audio)),"audioStatsProcessor",t.audio),this.execute((()=>this.videoStatsProcessor.processStats(e.video)),"videoStatsProcessor",t.video),this.execute((()=>this.sharingStatsProcessor.processStats(e.sharing)),"sharingStatsProcessor",t.sharing),this.execute((()=>{this.bandwidthStatsProcessor.processStats(e),this.diagnostics.bwStabilizationTime=this.bandwidthStatsProcessor.getStabilizedReport(!0),this.diagnostics.bwDownlinkStabilizationTime=this.bandwidthStatsProcessor.getDownlinkStabilizedReport(!0)}),"bandwidthStatsProcessor",t.bandwidth),this.execute((()=>{this.recvVideoStreamsCounter.captureSample(e.video?.recv?.length),this.diagnostics.recvVideoStreamsCount={min:this.recvVideoStreamsCounter.min,max:this.recvVideoStreamsCounter.max,mode:this.recvVideoStreamsCounter.mode}}),"recvVideoStreamsCounter",t.recvVideoStreamsCounter),this.execute((()=>this.processAggregated(e)),"processAggregated",t.aggregated),this.execute((()=>this.processMultiview(e.video?.recv??[])),"processMultiview",t.multiview),this.execute((()=>this.simulcastStatsProcessor.processStats(e)),"processSimulcastStats",t.simulcast),this.execute((()=>this.processNetworkInfoStats()),"processNetworkInfoStats",t.networkInfo),this.execute((()=>this.processMacroblockRateStats(e.video?.recv)),"processMacroblockRateStats",t.macroblockRate)}signalNoConnection(){this.transportStatsProcessor=new hF(this.diagnostics,this.configProvider),this.audioStatsProcessor=new eF(this.diagnostics,this.configProvider),this.videoStatsProcessor=new aF(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new aF(this.diagnostics,this.configProvider)}processNetworkInfoStats(){const e=navigator?.connection;e&&this.diagnostics.addNetworkInfo({downlink:e.downlink,rtt:e.rtt,effectiveType:e.effectiveType,saveData:e.saveData})}processMultiview(e){const t=new Set;for(const i of e){const e=i.inboundRTP.id;t.add(e);let n=this.multiviewData[e];n&&this.multiviewKeySet.has(e)?n.stats.duration++:(n={bitrateAverager:new qM,jitterAverager:new qM,frameRateAverager:new qM,freezeHistogram:new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),resolutionDurations:new QM,isRenderingEvents:[],statsOnSubscribed:new uF(this.configProvider),stats:{ssrc:i.inboundRTP.ssrc,startTime:Date.now(),duration:0,framesDecoded:[],bytesReceived:[],height:[],width:[]}},n.statsOnSubscribed.prepareCollectingStatsOnSubscribed(i.renderer?.msi),this.multiviewData[e]=n),n.statsOnSubscribed.captureStatsOnSubscribed(i.inboundRTP.framesDecoded,i.inboundRTP.bytesReceived,i.inboundRTP.frameHeight),n.bitrateAverager.captureSample(i.extensions?.bitrate),n.jitterAverager.captureSample(1e3*(i.inboundRTP.jitter??0)),n.frameRateAverager.captureSample(i.extensions.frameRateReceived),n.freezeHistogram.active=i.extensions?.isFrozen,i.inboundRTP.frameWidth&&i.inboundRTP.frameHeight&&n.resolutionDurations.captureSample(`${i.inboundRTP.frameWidth}x${i.inboundRTP.frameHeight}`);const r=i.renderer?.isRendering??!1;(!n.isRenderingEvents.length&&r||n.isRenderingEvents.length&&Cn(n.isRenderingEvents).isRendering!==r)&&Sn(n.isRenderingEvents,{isRendering:r,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents),n.stats.frameRateAvg=mn(n.frameRateAverager.avg),n.stats.bitrateAvg=mn(n.bitrateAverager.avg,0),n.stats.bitrateMax=mn(n.bitrateAverager.maxSample,0),n.stats.bitrateMinNonZero=mn(n.bitrateAverager.minNonZeroSample),n.stats.freezeHistogram=n.freezeHistogram.counts,n.stats.freezeTimestamps=n.freezeHistogram.timestamps,n.stats.avgFreezeDuration=mn(n.freezeHistogram.avgDuration),n.stats.totalFreezeDuration=n.freezeHistogram.totalDuration,n.stats.ongoingFreeze=n.freezeHistogram.active,n.stats.ongoingFreezeDuration=n.freezeHistogram.ongoingDuration,n.stats.numResolutionSwitches=n.resolutionDurations.changeCount,n.stats.rendererSize=`${i.renderer?.rendererSize?.width}x${i.renderer?.rendererSize?.height}`,n.stats.resolutionDurations=n.resolutionDurations.durations,n.stats.timeToFirstFrame=i.renderer?.timeToFirstFrame,n.stats.timeToFirstFrameSinceSubscriptionStart=i.renderer?.timeToFirstFrameSinceSubscriptionStart,n.stats.isRenderingEvents=n.isRenderingEvents,n.stats.statsOnSubscribed=n.statsOnSubscribed.videoStatsOnSubscribed,n.stats.msi=i.renderer?.msi,n.stats.rendererStates=i.renderer?.rendererStates,Sn(n.stats.framesDecoded,i.inboundRTP.framesDecoded,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.bytesReceived,i.inboundRTP.bytesReceived,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.height,i.inboundRTP.frameHeight,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.width,i.inboundRTP.frameWidth,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples);const s=i.extensions?.macroblockRateStats??{};for(const e in s)n.stats[e]=mn(s[e],0)}this.diagnostics.multiViewStats=Object.values(this.multiviewData).map((e=>e.stats)),this.multiviewKeySet=t}processAggregated(e){for(const t of["audio","video","sharing"])if(e[t])for(const i in e[t])this.processAggregatedModality(e,t,i)}processAggregatedModality(e,t,i){var n,r;const s=e[t]?.[i]?.length??0;s>0&&((n=this.aggregatedModalityStats)[t]??(n[t]={}),(r=this.aggregatedModalityStats[t])[i]??(r[i]=[]),s>1&&("audio"===t||"sharing"===t)&&this.diagnostics.addStatsError("webrtcStatistics:processAggregatedModality",`Multiple ${t} ${i} streams: ${s}`),this.statsAggregators[t][i].processSample(e[t][i],this.aggregatedModalityStats[t][i],this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),"sharing"!==t&&"video"!==t||"recv"!==i||this.processStatsOnSubscribed(e[t][i],t))}processStatsOnSubscribed(e,t){const i=new Set;for(const n of e)if(n.inboundRTP){const e=`${n.inboundRTP.id}x${n.renderer?.msi}`;let r=this.statsOnSubscribedData[t]?.[e];i.add(e),r||(r=new uF(this.configProvider),r.prepareCollectingStatsOnSubscribed(n.renderer?.msi),this.statsOnSubscribedData[t][e]=r,this.statsOnSubscribed[t].push(...r.videoStatsOnSubscribed)),r.captureStatsOnSubscribed(n.inboundRTP.framesDecoded,n.inboundRTP.bytesReceived)}!function(e,t){const i=[];for(const n of Object.keys(e))t.has(n)||i.push(n);for(const t of i)delete e[t]}(this.statsOnSubscribedData[t],i)}processMacroblockRateStats(e){if(!e?.length)return;let t=0,i=0;for(const n of e)t+=n.extensions?.macroblockRateReceived,i+=n.extensions?.macroblockRateDecoded;this.macroblockStatsTracker.captureSample(t,i),this.diagnostics.setTotalVideoRecvMblocksRates(this.macroblockStatsTracker.getReport())}execute(e,t,i){try{i&&e()}catch(e){this.diagnostics.addStatsError(`webrtcStatistics:${t}`,tt(e))}}},IF=Z,wF=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.webrtcStats=new _F(this.configProvider,this.diagnostics),this.ssrcToRecvTrackMap=new Map,this.activeChannels={}}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}setAudioEncoderCodecName(e){this.audioEncoderCodecName=e}signalNoConnection(){this.webrtcStats.signalNoConnection()}processRawReport(e){this.diagnostics.latestRawReport=e;const t={loopTime:-1,fetchTime:-1,convertTime:-1,processingTime:-1,legacyProcessingTime:-1};try{let i=_n(),n=i;const r=this.convertStatsReport(e);return r.perfCounters=t,i=_n(),t.convertTime=i-n,n=i,this.webrtcStats.processStats(r),this.diagnostics.addStatsReport(r),i=_n(),t.processingTime=i-n,r}catch(e){const t=tt(e);return this.logger.safe.error(`Error processing raw stats: ${t}`),void this.diagnostics.addStatsError("StatisticsGatherer:processRawReport",t)}}setSsrcTrackPair(e,t){null===t?this.ssrcToRecvTrackMap.delete(e):this.ssrcToRecvTrackMap.set(e,t)}convertStatsReport(e){const t={transports:this.processTransportStats(e)};return this.appendPcStats(e,t),this.appendSendMediaStats(e,t),this.appendRecvMediaStats(e,t),e["data-channel"]&&(t.data=Object.values(e["data-channel"])),t}processTransportStats(e){if(e.transport){const t={};for(const i in e.transport){const n=e.transport[i];if(t[i]=tn(n),n.selectedCandidatePairId){const r=tn(e["candidate-pair"][n.selectedCandidatePairId]);r.localCandidate=e["local-candidate"][r.localCandidateId],r.remoteCandidate=e["remote-candidate"][r.remoteCandidateId],t[i].selectedCandidatePair=r}n.localCertificateId&&e.certificate&&(t[i].localCertificate=e.certificate[n.localCertificateId]),n.remoteCertificateId&&e.certificate&&(t[i].remoteCertificate=e.certificate[n.remoteCertificateId])}return t}if(e["candidate-pair"]){const t={};for(const i in e["candidate-pair"]){const n=tn(e["candidate-pair"][i]);n.selected&&(n.localCandidate=e["local-candidate"][n.localCandidateId],n.remoteCandidate=e["remote-candidate"][n.remoteCandidateId],t.faketransport={id:"faketransport",timestamp:n.timestamp,type:"transport",selectedCandidatePair:n,selectedCandidatePairId:n.id})}return t}}appendPcStats(e,t){let i="";e["peer-connection"]&&(Object.keys(e["peer-connection"]).forEach((e=>{""===i?i=e:(this.logger.safe.error(`Unexpected second peer connection stats id ${e}, also found ${i}`),this.diagnostics.addStatsError("StatisticsGatherer","Unexpected second peer connection stats"))})),t.peerConnection=e["peer-connection"][i])}appendSendMediaStats(e,t){var i,n,r,s;for(const a in e["outbound-rtp"]){const o=e["outbound-rtp"][a],l={outboundRTP:o};o.codecId&&e.codec&&(l.codec=e.codec[o.codecId]),Object.defineProperty(l,"transport",{value:t.transports[o.transportId??"faketransport"],configurable:!1,enumerable:!1}),o.remoteId&&e["remote-inbound-rtp"]&&(l.remoteInboundRTP=e["remote-inbound-rtp"][o.remoteId]),o.mediaSourceId&&e["media-source"]&&(l.mediaSource=e["media-source"][o.mediaSourceId]),o.trackId&&e.track&&(l.track=e.track[o.trackId]);const c=DF(this.mediaManager,l.track?.trackIdentifier??l.mediaSource?.trackIdentifier,o.rid)??MF(this.mediaManager,o.ssrc,o.rid)??LF(this.mediaManager,l.outboundRTP.mid,o.rid);if(!c?.getLocalTrackId())continue;l.mediaEntity=c.serialize(),!l.mediaSource&&l.mediaEntity&&e["media-source"]&&(l.mediaSource=Object.values(e["media-source"]).find((e=>e.trackIdentifier===l.mediaEntity.localTrackId)));const d="video"===o.kind?"sharing"===c?.getModality()?"sharing":"video":o.kind;if((i=this.activeChannels)[d]??(i[d]={}),(n=this.activeChannels[d]).send??(n.send={}),Wp(this.diagnostics.getObjectRef().negotiation.activeModalities?.[d])){if(t[d]||(t[d]={}),t[d].send||(t[d].send=[]),"video"===o.kind){const e=kF(this.diagnostics,d,o.ssrc)??kF(this.diagnostics,d,0);e&&(l.requestedCapabilities=e);const i=OF(this.diagnostics,d,o.ssrc)??OF(this.diagnostics,d,0);i&&(l.appliedCapabilities=i);const n=t[d].send.find((e=>e.outboundRTP.trackId===l.outboundRTP.trackId));if(n){const e=parseInt(n.outboundRTP.rid,10)>parseInt(l.outboundRTP.rid,10);if(!n.altLayouts&&e&&(n.altLayouts=[]),e)n.altLayouts.push(l);else{l.altLayouts=[],l.altLayouts.push(n);const e=t[d].send.indexOf(n);t[d].send[e]=l}continue}}"audio"===o.kind&&l.codec&&this.audioEncoderCodecName&&"None"!==this.audioEncoderCodecName&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing send audio codec with custom audio encoder codec"),l.codec.mimeType=this.audioEncoderCodecName),this.activeChannels[d].send[o.id]=l,t[d].send.push(l)}else this.activeChannels[d].send[o.id]&&"sharing"!==d&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[d]??(r[d]={}),(s=t.inactiveTracks[d]).send??(s.send=[]),t.inactiveTracks[d].send.push(this.activeChannels[d].send[o.id]))}}appendRecvMediaStats(e,t){var i,n,r,s;const a=this.diagnostics.getObjectRef().subscriptionManager?.subscribedTrackIds;for(const o in e["inbound-rtp"]){const l=e["inbound-rtp"][o],c={inboundRTP:l};l.codecId&&e.codec&&(c.codec=e.codec[l.codecId]),"audio"===l.kind&&c.inboundRTP.ssrc===this.audioDecoderStatsProvider?.ssrc&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing recv audio stats with custom audio decoder stats"),c.codec||(c.codec={transportId:l.transportId??"faketransport",id:"fakeCodec",payloadType:999,timestamp:l.timestamp,type:"codec",mimeType:"unk"}),c.codec.mimeType=this.audioDecoderStatsProvider.codecName,c.inboundRTP=(0,IF.merge)(c.inboundRTP,this.audioDecoderStatsProvider.getWebRtcCompatibleStats()),c.customHealerStats=this.audioDecoderStatsProvider.getWasmStats()),t.transports[l.transportId??"faketransport"]&&Object.defineProperty(c,"transport",{value:t.transports[l.transportId??"faketransport"],configurable:!1,enumerable:!1}),l.remoteId&&e["remote-outbound-rtp"]&&(c.remoteOutboundRTP=e["remote-outbound-rtp"][l.remoteId]);const d=c.inboundRTP.trackIdentifier??this.ssrcToRecvTrackMap.get(l.ssrc);if(l.trackId||d){l.trackId&&e.track?c.track=e.track[l.trackId]:d&&(c.track={id:"ssrcToTrackId",kind:l.kind,timestamp:l.timestamp,type:"track",trackIdentifier:d});const t=NF(this.diagnostics,c.track?.trackIdentifier);t&&(c.renderer=t)}const u=RF(this.mediaManager,c.track?.trackIdentifier)??PF(this.mediaManager,l.ssrc);if(!u)continue;c.mediaEntity=u.serialize();const h="video"===l.kind&&c.track?"sharing"===u?.getModality()?"sharing":"video":l.kind;(i=this.activeChannels)[h]??(i[h]={}),(n=this.activeChannels[h]).recv??(n.recv={}),"video"!==l.kind||a.some((e=>e&&e===c.track?.trackIdentifier))?Kp(this.diagnostics.getObjectRef().negotiation.activeModalities?.[h])&&(t[h]||(t[h]={}),t[h].recv||(t[h].recv=[]),this.activeChannels[h].recv[l.id]=c,t[h].recv.push(c)):this.activeChannels[h].recv[l.id]&&"sharing"!==h&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[h]??(r[h]={}),(s=t.inactiveTracks[h]).recv??(s.recv=[]),t.inactiveTracks[h].recv.push(this.activeChannels[h].recv[l.id]))}}};function AF(e,t){return!t||e.getSimulcastContext()?.activeRids.map(String).some((e=>e===t))}function PF(e,t){return e.getMediaEntities().find((e=>e.getRemoteSsrc()===t))}function RF(e,t){const i=e.getMediaEntities();return void 0!==t?i.find((e=>e.getRemoteTrackId()===t)):void 0}function MF(e,t,i){return e.getMediaEntities().find((e=>e.getLocalSsrc()===t&&AF(e,i)))}function DF(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getLocalTrackId()===t&&AF(e,i))):void 0}function kF(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcRequestedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcRequestedCapabilities[`${i}`]:void 0}function OF(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcAppliedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcAppliedCapabilities[`${i}`]:void 0}function NF(e,t){return e.getObjectRef().remoteVideoManager?.renderers.find((e=>e.trackId===t))}function LF(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getMid()===t&&AF(e,i))):void 0}var xF=class{constructor(){this.googCandidatePair={},this.ssrc={},this.googComponent={},this.VideoBwe={bweforvideo:{}}}},FF=class{constructor(){this.statistics=new xF,this.statsDiffMap=new Map,this.ssrcTrackMap=new Map}build(e){return this.statistics=new xF,this.constructGoogCandidatePair(e),this.constructGoogSsrc(e),this.constructGoogComponent(e),this.constructDataChannel(e),this.constructBwe(e),this.statistics}setSsrcTrackPair(e,t){null===t?this.ssrcTrackMap.delete(e):this.ssrcTrackMap.set(e,t)}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}setAudioEncoderCodecName(e){this.audioEncoderCodecName=e}constructGoogSsrc(e){const t={};if(e.hasOwnProperty("outbound-rtp")){const i=e["outbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_send`,s=this.constructSendSsrc(e,i[n]);t[r]=s}))}if(e.hasOwnProperty("inbound-rtp")){const i=e["inbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_recv`,s=this.constructRecvSsrc(e,i[n]);t[r]=s}))}this.statistics.ssrc=t}constructSendSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=t.mediaSourceId?e["media-source"][t.mediaSourceId]:null,r=e["remote-inbound-rtp"]?.[t.remoteId],s=`ssrc_${t.ssrc}_send`,a=n?.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let o={id:s,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesSent:t.bytesSent,bytesSentDiff:this.calculateDiff(s,t.bytesSent,4),packetsSent:t.packetsSent,packetsLost:r?.packetsLost,jitter:r?.jitter,googRtt:this.getRtt(r),googCodecName:this.getCodec(e,t.codecId),transportId:t.transportId,googTrackId:a};return"audio"===o.mediaType&&(o={...o,...this.constructAudioSendSsrc(t,n)}),"video"===o.mediaType&&(o={...o,...this.constructVideoSendSsrc(t,n,s,i)}),rn(o)}constructAudioSendSsrc(e,t){const i={audioInputLevel:t?.audioLevel,totalAudioEnergy:t?.totalAudioEnergy,fecPacketsSent:e.fecPacketsSent};return this.audioEncoderCodecName&&"None"!==this.audioEncoderCodecName&&(i.googCodecName=this.audioEncoderCodecName),i}constructVideoSendSsrc(e,t,i,n){return{framesEncoded:e.framesEncoded,googFrameRateEncoded:this.calculateDiff(i,e.framesEncoded,2),googFrameRateSent:this.calculateDiff(i,e.framesSent??n?.framesSent,1),googFrameRateInput:t?.framesPerSecond,googFrameHeightSent:e.frameHeight??n?.frameHeight,googFrameWidthSent:e.frameWidth??n?.frameWidth,googFrameHeightInput:t?.height,googFrameWidthInput:t?.width,hugeFramesSent:e.hugeFramesSent??n?.hugeFramesSent,keyFramesEncoded:e.keyFramesEncoded,qpSum:e.qpSum,qp:this.calculateDiff(i,e.qpSum,8),googPlisReceived:e.pliCount,googFirsReceived:e.firCount,googNacksReceived:e.nackCount,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,codecImplementationName:e.encoderImplementation,rid:e.rid,encodeTime:e.totalEncodeTime&&Math.round(1e3*this.calculateDiff(i,e.totalEncodeTime,6))}}constructRecvSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=`ssrc_${t.ssrc}_recv`,r=t.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let s={id:n,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesReceived:t.bytesReceived,bytesReceivedDiff:this.calculateDiff(n,t.bytesReceived,5),packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,jitter:t.jitter,googJitterBufferMs:t.jitterBufferEmittedCount&&Math.round(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3),googCodecName:this.getCodec(e,t.codecId),googTrackId:r,transportId:t.transportId};return"audio"===s.mediaType&&(s={...s,...this.constructAudioRecvSsrc(t,i)}),"video"===s.mediaType&&(s={...s,...this.constructVideoRecvSsrc(t,n,i)}),rn(s)}constructAudioRecvSsrc(e,t){const i=this.audioDecoderStatsProvider?.ssrc===e.ssrc?this.audioDecoderStatsProvider?.getWebRtcCompatibleStats():e,n={audioOutputLevel:i.audioLevel??t?.audioLevel,totalAudioEnergy:i.totalAudioEnergy??t?.totalAudioEnergy,concealedSamples:i.concealedSamples,silentConcealedSamples:i.silentConcealedSamples,totalSamplesReceived:i.totalSamplesReceived,healedRatio:i.totalSamplesReceived&&(i.concealedSamples-i.silentConcealedSamples)/i.totalSamplesReceived,fecPacketsReceived:i.fecPacketsReceived,fecPacketsDiscarded:i.fecPacketsDiscarded,packetsDiscarded:i.packetsDiscarded};if(this.audioDecoderStatsProvider?.ssrc===e.ssrc){n.googJitterBufferMs=i.jitterBufferEmittedCount&&Math.round(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3),n.googCodecName=this.audioDecoderStatsProvider.codecName;const e=this.audioDecoderStatsProvider.getDecoderStats();n.pushCount=e.pushCount,n.pushErrCount=e.pushErrCount,n.pullCount=e.pullCount,n.pullErrCount=e.pullErrCount}return n}constructVideoRecvSsrc(e,t,i){return{framesDecoded:e.framesDecoded,googFrameRateDecoded:this.calculateDiff(t,e.framesDecoded,3),googFrameRateReceived:this.calculateDiff(t,e.framesReceived??i?.framesReceived,0),googFrameHeightReceived:e.frameHeight??i?.frameHeight,googFrameWidthReceived:e.frameWidth??i?.frameWidth,keyFramesDecoded:e.keyFramesDecoded,googPlisSent:e.pliCount,googFirsSent:e.firCount,googNacksSent:e.nackCount,codecImplementationName:e.decoderImplementation,decodeTime:e.totalDecodeTime&&Math.round(1e3*this.calculateDiff(t,e.totalDecodeTime,7))}}constructGoogCandidatePair(e){const t=e["candidate-pair"];t&&Object.keys(t).forEach((i=>{const n=this.constructPair(e,t[i]);this.statistics.googCandidatePair[n.id]=n}))}constructPair(e,t){const i=e["local-candidate"][t.localCandidateId],n=e["remote-candidate"][t.remoteCandidateId];return rn({bytesReceived:t.bytesReceived,bytesSent:t.bytesSent,googTransportType:i.protocol,googRtt:t.currentRoundTripTime?Math.round(1e3*t.currentRoundTripTime):void 0,googLocalAddress:`${i.ip?i.ip:i.address}:${i.port}`,googLocalCandidateType:i.candidateType,localRelayProtocol:i.relayProtocol,localNetworkType:i.networkType,googRemoteAddress:`${n.ip?n.ip:n.address}:${n.port}`,googRemoteCandidateType:n.candidateType,googActiveConnection:t.nominated,requestsReceived:t.requestsReceived,requestsSent:t.requestsSent,responsesReceived:t.responsesReceived,responsesSent:t.responsesSent,consentRequestsSent:t.consentRequestsSent,id:t.id,remoteCandidateId:t.remoteCandidateId,localCandidateId:t.localCandidateId,googWritable:t.writable,selected:t.selected,packetsDiscardedOnSend:t.packetsDiscardedOnSend})}constructGoogComponent(e){e.transport&&Object.keys(e.transport).forEach((t=>{this.statistics.googComponent[t]={id:t,selectedCandidatePairId:e.transport[t].selectedCandidatePairId}}))}constructDataChannel(e){if(!e.hasOwnProperty("data-channel"))return;const t=e["data-channel"];this.statistics.data=Object.keys(t).map((e=>{const i=t[e];return{bytesReceived:i.bytesReceived,bytesSent:i.bytesSent,dataChannelIdentifier:i.dataChannelIdentifier,label:i.label,messagesReceived:i.messagesReceived,messagesSent:i.messagesSent,protocol:i.protocol,state:i.state,timestamp:i.timestamp,type:i.type}}))}constructBwe(e){const t=Object.values(e["outbound-rtp"]??{})?.find((e=>{const t=e.mediaType??e.kind;return"audio"===t||"video"===t}));if(!t)return;const i=e.transport?.[t.transportId];if(!i)return;const n=e["candidate-pair"]?.[i.selectedCandidatePairId];if(!n)return;const r={googAvailableSendBandwidth:n.availableOutgoingBitrate,googAvailableReceiveBandwidth:n.availableIncomingBitrate};this.statistics.VideoBwe.bweforvideo=rn(r)}getRtt(e){const t=e?.roundTripTime;return t?Math.round(1e3*t):void 0}getCodec(e,t){if(t&&e.codec&&e.codec[t])return e.codec[t].mimeType.split("/").pop()}calculateDiff(e,t,i){if(void 0===t)return;let n=t;const r=this.statsDiffMap.has(e)?this.statsDiffMap.get(e):new Map;if(r.has(i)){const e=r.get(i);e<=t&&(n=t-e)}return r.set(i,t),this.statsDiffMap.set(e,r),isNaN(n)?void 0:n}},UF=Z,BF=Z,VF=class{constructor(e){this.healedRatio=0,this.healedRatioMax=0,this.healedRatioDuration=0,this.healedRatioTotal=0,this.totalSamplesReceivedDiff=0;const t=e.config;this.networkDetectionDuration=t.webrtcStatNetworkDetectionDuration,this.networkRecvQualityDiagnostics=t.networkRecvQualityDiagnostics,this.networkRecvQualityDiagnostics&&(this.healedRatioAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize))}captureHealedRatioSamples(e,t,i){!e||!t||!i||e.length<=this.networkDetectionDuration||t.length<=this.networkDetectionDuration||i.length<=this.networkDetectionDuration||this.setHealedRatioPerDuration(e,t,i)}getHealedRatioMax(){return this.healedRatioMax}getHealedRatioAvg(){return this.healedRatioDuration?this.healedRatioTotal/this.healedRatioDuration:0}getHealedRatio(){return this.healedRatio}getTotalSamplesReceivedDiff(){return this.totalSamplesReceivedDiff}setHealedRatioPerDuration(e,t,i){const n=-1-this.networkDetectionDuration,r=Math.max((0,BF.last)(e)-(0,BF.nth)(e,n),0),s=Math.max((0,BF.last)(t)-(0,BF.nth)(t,n),0);this.totalSamplesReceivedDiff=Math.max((0,BF.last)(i)-(0,BF.nth)(i,n),0),0!==this.totalSamplesReceivedDiff&&(this.healedRatio=(r-s)/this.totalSamplesReceivedDiff,this.healedRatioDuration++,this.healedRatioTotal+=this.healedRatio,this.healedRatioMax=Math.max(this.healedRatioMax,this.healedRatio),this.networkRecvQualityDiagnostics&&(this.concealedSamplesAccumulator.add((0,BF.last)(e)),this.silentConcealedSamplesAccumulator.add((0,BF.last)(t)),this.totalSamplesReceivedAccumulator.add((0,BF.last)(i)),this.concealedSamplesDiffAccumulator.add(r),this.silentConcealedSamplesDiffAccumulator.add(s),this.totalSamplesReceivedDiffAccumulator.add(this.totalSamplesReceivedDiff),this.healedRatioAccumulator.add(this.healedRatio)))}getDiagnostics(e){return{quality:(0,BF.last)(e),qualityLevels:e,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((e=>mn(e)))}}},HF=class{constructor(e){this.configProvider=e,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(e){this.jitterBufferDuration+=Gi.TIME_INTERVAL.SEC_1,this.jitterBufferTotal+=e}captureJitter(e){const t=1e3*e;this.jitterTotal+=t,this.jitterMax=Math.max(t,this.jitterMax),this.jitterDuration+=Gi.TIME_INTERVAL.SEC_1}getJitterAvg(){return this.jitterDuration?mn(this.jitterTotal/this.jitterDuration):0}getAvgJitterBuffer(){return this.jitterBufferDuration?Math.round(this.jitterBufferTotal/this.jitterBufferDuration):0}captureRtt(e){if(null!==e){const t=parseInt(e);this.rttDuration+=Gi.TIME_INTERVAL.SEC_1,this.rttTotal+=t,this.rttMax=Math.max(this.rttMax,t)}}getAvgRtt(){return this.rttDuration?mn(this.rttTotal/this.rttDuration):0}getMaxRtt(){return this.rttMax}getJitterMax(){return this.jitterMax}updateSendStream(e,t){if(!this.configProvider.config.useAudioAnalyzer)return;const i=this.audioAnalyzers.get(t);i&&(i.dispose(),this.audioAnalyzers.delete(t)),e?.rawStream?.getAudioTracks().length&&this.audioAnalyzers.set(t,new zk(e.rawStream))}getInputLevel(e){const t=this.audioAnalyzers.get(e);return t?.getInputLevelNormalized()}},$F=class{constructor(e,t){this.dropBadBandwidth=e,this.dropGoodBandwidth=t,this.dropDurationCounts={},Object.keys(Gi.HISTOGRAM_BATCH).forEach((e=>{this.dropDurationCounts[e]=0}))}recordSendBandwidth(e){this.currentDropDuration&&e<this.dropGoodBandwidth||e<this.dropBadBandwidth?this.initiateDrop():this.currentDropDuration&&e>this.dropGoodBandwidth&&this.recoverDrop()}getReport(){const e=tn(this.dropDurationCounts);return this.currentDropDuration&&(e.ongoingDuration=this.currentDropDuration),e}initiateDrop(){this.currentDropDuration?this.currentDropDuration++:this.currentDropDuration=1}recoverDrop(){for(const e of Object.keys(Gi.HISTOGRAM_BATCH))if(this.currentDropDuration<=Gi.HISTOGRAM_BATCH[e]){this.dropDurationCounts[e]+=1,this.currentDropDuration=0;break}}},jF=Z,GF=class{constructor(e,t,i,n){this.lowThreshold=e,this.highThreshold=t,this.isLowerBetter=i,this.curInLowerRange=i,this.stateTracker=new qF(n)}onSample(e,t){let i=this.curInLowerRange;this.curInLowerRange?e>this.highThreshold&&(i=!1):e<this.lowThreshold&&(i=!0);const n=this.stateTracker.onNewState(this.getQuality(i),t);return n!==this.getQuality(this.curInLowerRange)&&(this.curInLowerRange=i),n}getQuality(e){return e===this.isLowerBetter?"Good":"Bad"}},qF=class{constructor(e){this.stickinessTime=e}onNewState(e,t){return"Good"!==e&&"Bad"!==e?this.curState:0===this.stickinessTime?e:e===this.curState?(this.stickTimerStarted=0,this.curState):("Bad"===this.curState?0===this.stickTimerStarted?this.stickTimerStarted=t:t-this.stickTimerStarted>this.stickinessTime&&(this.curState=e,this.stickTimerStarted=0):(this.curState=e,this.stickTimerStarted=0),this.curState)}},zF=class{constructor(e,t,i,n){this.stateProcessor=e,this.windowSize=t,this.extendedWindowSize=i,this.addDiagnosticData=n,this.dataAccumulator=new $M(i),this.avgAccumulator=new $M(i)}getLatestSendQuality(e,t,i){if(this.dataAccumulator.add(e),this.dataAccumulator.items.length>=this.windowSize){const e=this.dataAccumulator.items.slice(-this.windowSize),i=(0,jF.mean)(e);return this.addDiagnosticData&&this.avgAccumulator.add(i),this.stateProcessor.onSample(i,t)}return i}getData(){return this.dataAccumulator.items.map((e=>mn(e)))}getAggregatedData(){return this.avgAccumulator.items.map((e=>mn(e)))}},WF=class{constructor(e,t,i){this.configProvider=e,this.newStatsApi=t,this.webrtcHealedRatio=i,this.sendAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiffAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostDiffAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.totalAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendQualityAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiagnosticsEnabled=this.configProvider.config.networkSendQualityDiagnostics,this.recvDiagnosticsEnabled=this.configProvider.config.networkRecvQualityDiagnostics,this.recvQualityAccumulator=new $M(this.configProvider.config.webrtcHealedRatioExtendedWindowSize);const n=Number(this.configProvider.config.webrtcStatNetworkDetectionHysteresis);this.networkDetectionBadLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionBadLevel)+n/2,this.networkDetectionBadLevelLow=this.networkDetectionBadLevelHigh-n,this.networkDetectionGoodLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionGoodLevel)+n/2,this.networkDetectionGoodLevelLow=this.networkDetectionGoodLevelHigh-n;const r=new GF(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),s=new GF(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime);this.jitterCalculator=new zF(r,e.config.webrtcJitterWindowSize,e.config.webrtcJitterExtendedWindowSize,this.sendDiagnosticsEnabled),this.lossRateCalculator=new zF(s,e.config.webrtcLossRateWindowSize,e.config.webrtcLossRateExtendedWindowSize,this.sendDiagnosticsEnabled)}calculateNetworkSendQualityLevel(e,t,i,n){if(!e||!t)return{quality:n};if(e.length<2||t.length<2||(0,jF.last)(e)<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return{quality:n};const r=Date.now(),s=(0,jF.last)(i),a=this.jitterCalculator.getLatestSendQuality(s,r,n),[o,l]=e.slice(-2),[c,d]=t.slice(-2),u=this.getLossRate(l,o,d,c),h=this.lossRateCalculator.getLatestSendQuality(u,r,n),g="Good"===a&&"Good"===h?"Good":"Bad";return this.sendDiagnosticsEnabled&&(this.sendAccumulator.add(l),this.lostAccumulator.add(d),this.sendQualityAccumulator.add(g)),this.sendDiagnosticsEnabled?{quality:g,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:g}}calculateNetworkRecvQualityLevel(e){if(this.newStatsApi){const t=e;return this.calculateNetworkRecvQualityLevelNewStatsApi(t.concealedSamples,t.silentConcealedSamples,t.totalSamplesReceived,t.oldNetworkLevel)}{const t=e;return this.calculateNetworkRecvQualityLevelLegacyStatsApi(t.googDecodingCTN,t.googDecodingPLC,t.oldNetworkLevel)}}calculateNetworkRecvQualityLevelLegacyStatsApi(e,t,i){const n=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||!t||e.length<2*n)return{quality:i};let r=e.length-1-n;const s=e[e.length-1];for(;r>=0&&s-e[r]<100*n;)r--;if(r<0)return{quality:i};const a=s-e[r],o=t[t.length-1]-t[r];if(a<=0)return{quality:i};const l=o/a;return{quality:this.getRecvQuality(l,i)}}calculateNetworkRecvQualityLevelNewStatsApi(e,t,i,n){const r=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||e.length<=r||!t||t.length<=r||!i||i.length<=r)return{quality:n};if((0,jF.last)(i)<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality)return{quality:n};if(0===this.webrtcHealedRatio.getTotalSamplesReceivedDiff())return{quality:n};const s=this.webrtcHealedRatio.getHealedRatio(),a=this.getRecvQuality(s,n);return this.recvDiagnosticsEnabled?(this.recvQualityAccumulator.add(a),this.webrtcHealedRatio.getDiagnostics(this.recvQualityAccumulator.items)):{quality:a}}getRecvQuality(e,t){return e<this.networkDetectionGoodLevelLow?"Good":e<this.networkDetectionGoodLevelHigh?"Good"===t?"Good":"Poor":e<this.networkDetectionBadLevelLow?"Poor":e<this.networkDetectionBadLevelHigh?"Bad"===t?"Bad":"Poor":"Bad"}getLossRate(e,t,i,n){const r=e-t,s=i-n,a=r+s;return this.sendDiagnosticsEnabled&&(this.sendDiffAccumulator.add(r),this.lostDiffAccumulator.add(s),this.totalAccumulator.add(a)),a>0?s/a:0}},KF=class{constructor(e){this.configProvider=e,this.qualityLimitationReasonEvents=[]}setQualityLimitationReason(e){this.lastQualityLimitationReason!==e&&this.qualityLimitationReasonEvents.push({event:e,startTime:Date.now(),endTime:Date.now()}),this.qualityLimitationReasonEvents.length>this.configProvider.config.maxStoredQualityLimitationReasonEvents&&this.qualityLimitationReasonEvents.shift(),this.lastQualityLimitationReason=e}getQualityLimitationReasonEvents(){return this.qualityLimitationReasonEvents.reduce(((e,t,i)=>"none"===t.event?e:[...e,{...t,endTime:this.qualityLimitationReasonEvents[i+1]?.startTime??Date.now()}]),[])}},JF=class{constructor(){this.bitrateData={[Gi.MEDIA_DIRECTION.SEND]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0,allocateBW:0,allocateBWSamples:0},[Gi.MEDIA_DIRECTION.RECV]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0}}}captureSample(e,t){const i=Date.now()/1e3;if(0!==this.bitrateData[e].lastTimestamp&&t>this.bitrateData[e].lastBytes){const n=i-this.bitrateData[e].lastTimestamp,r=8*(t-this.bitrateData[e].lastBytes)/n;this.onBitrateSample(e,r)}this.bitrateData[e].lastTimestamp=i,this.bitrateData[e].lastBytes=t}getMax(e){return Math.round(this.bitrateData[e].maxSample)}getAvg(e){return 0===this.bitrateData[e].nSamples?0:Math.round(this.bitrateData[e].bitrateTotal/this.bitrateData[e].nSamples)}stopCapture(e){this.bitrateData[e].lastBytes=0,this.bitrateData[e].lastTimestamp=0}onBitrateSample(e,t){t>this.bitrateData[e].maxSample&&(this.bitrateData[e].maxSample=t),this.bitrateData[e].bitrateTotal+=t,this.bitrateData[e].nSamples++}captureAllocateBandwidth(e){if(e){const t=parseInt(e[e.length-1]);this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBW+=t,this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBWSamples+=1}}getAllocateBandwidthAvg(){const e=this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBW,t=this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBWSamples;if(e>0&&t>0)return Math.floor(e/t)}},YF=class{constructor(e,t){this.maxAppliedCapabilitiesCount=t,this.events=[],this.events.push({eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled})}setMaxCapabilitiesApplied(e){this.events.push({eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:e.error?`${e.error}`:"none"}),this.maxAppliedCapabilitiesCount&&this.events.length>this.maxAppliedCapabilitiesCount+1&&this.events.splice(1,1)}getEvents(){return this.events}},QF=class{constructor(e,t){this.configProvider=e,this.logger=t,this.resolutionChangeRequestRecords={},this.currentResolutionsByRid={},this.resolutionChangeCounterByRid={},this.events=[],this.errors=[]}setMaxCapabilitesRequested(e){const t=new YF(e,this.configProvider.config.webrtcLastAppliedVideoCapabilitiesCount);this.events.push({causeId:e.causeId,seq:t}),this.recordResolutionChange(e),this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.length>this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.shift()}setMaxCapabilitesApplied(e){const t=this.events.find((t=>t.causeId===e.causeId));t?(t.seq.setMaxCapabilitiesApplied(e),e.error&&this.errors.push(t)):this.logger.safe.warn(`Requested capabilities with id ${e.causeId} not found`)}getEvents(){return this.events.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getErrors(){return this.errors.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getResolutionRecords(){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo)return{req:this.resolutionChangeRequestRecords,count:this.resolutionChangeCounterByRid}}recordResolutionChange(e){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo){const t=Object.keys(this.currentResolutionsByRid),i=e=>e.rid||"default";[...t,...e.capabilities.map((e=>i(e)))].forEach((t=>{const n=e.capabilities.find((e=>i(e)===t)),r=this.currentResolutionsByRid[t]||0,s=n?.maxFs||0;if(r===s)return;this.resolutionChangeRequestRecords[t]||(this.resolutionChangeRequestRecords[t]=[],this.resolutionChangeCounterByRid[t]=0);const a=this.resolutionChangeRequestRecords[t].find((e=>e.from===r&&e.to===s));a?a.counter++:this.resolutionChangeRequestRecords[t].push({from:r,to:s,counter:1}),this.currentResolutionsByRid[t]=s,this.resolutionChangeCounterByRid[t]++}))}}},ZF=class{constructor(){this.delayCur=[],this.delayTotal=0,this.delayEventCount=0}analyzeDelay(e,t){if(t&&""!==t){this.delayCur.length===e&&this.delayCur.shift();const i=parseInt(t);this.delayCur.push(i),this.delayTotal+=i,this.delayEventCount+=Gi.TIME_INTERVAL.SEC_1}}getDelayCur(){if(this.delayCur.length>0){const e=this.delayCur.reduce(((e,t)=>e+t))/this.delayCur.length;return e<0?0:e}}getDelayAvg(){if(this.delayEventCount>0&&this.delayTotal>0){const e=this.delayTotal/this.delayEventCount;return e<0?0:e}}},XF=class{constructor(e,t){this.configProvider=e,this.startTime=t,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(Gi.HISTOGRAM_BATCH).forEach((e=>{this.receiveFreezeDurationCounts[e]=0,this.receiveFreezeDurationTimestamps[e]=[]}))}gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:n}){if(e){const r=parseInt(e[e.length-1],10),s=t?.length>0?parseInt(t[t.length-1],10):void 0;void 0!==i&&"ScreenShare"!==n&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&!this.configProvider.config.isRenderingBasedOnRawStatistics&&this.calculateBitrate(i,r),-1===this.recvTotalFreezeDuration&&(this.recvTotalFreezeDuration=0),r>0&&(this.mediaStarted=!0),0!==r&&0!==s||!this.mediaStarted?r>0&&(void 0===s||s>0)&&this.recvFreezeIsOngoing&&this.stopRecvDataGathering(!1):(this.recvFreezeIsOngoing||(this.recvCurrentFreezeStartTimestamp=Date.now()-this.startTime),this.recvFreezeIsOngoing=!0,this.recvCurrentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1,this.recvTotalFreezeDuration+=Gi.TIME_INTERVAL.SEC_1)}}getIsRendering(e){return this.recvCurrentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted}detectCaptureFreeze(e){if(e){const t=parseInt(e[e.length-1],10);this.previousInputFrame>0&&0===t&&(this.sendCameraFreezeIntervalsCount+=1),this.previousInputFrame=t}}getSendCameraFreezeIntervals(){return this.sendCameraFreezeIntervalsCount>0?this.sendCameraFreezeIntervalsCount:void 0}stopRecvDataGathering(e=!0){this.finalFreezeIsOngoing=this.recvFreezeIsOngoing,this.recvFreezeIsOngoing=!1,e&&(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(e){if(0===this.recvFreezeCount)return;const t={};return Object.keys(this.receiveFreezeDurationTimestamps).forEach((i=>{const n=this.receiveFreezeDurationTimestamps[i].length;t[i]=n>e?this.receiveFreezeDurationTimestamps[i].slice(n-e):this.receiveFreezeDurationTimestamps[i]})),JSON.stringify(t)}getRecvFreezeIsOngoing(e){return this.finalRecvCurrentFreezeDuration>=e&&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 e of Object.keys(Gi.HISTOGRAM_BATCH))if(this.recvCurrentFreezeDuration<=Gi.HISTOGRAM_BATCH[e]){this.receiveFreezeDurationCounts[e]+=1,this.receiveFreezeDurationTimestamps[e].push(this.recvCurrentFreezeStartTimestamp);break}this.recvCurrentFreezeStartTimestamp=0}populateLongestRecvFreezeDuration(){this.recvCurrentFreezeDuration>this.longestRecvFreezeDuration&&(this.longestRecvFreezeDuration=this.recvCurrentFreezeDuration)}calculateBitrate(e,t){const i=(e-this.lastBytesRecv)/125;this.lastBytesRecv=e,i<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}},eU=class{constructor(){this.mediaData={[Gi.MEDIA_DIRECTION.SEND]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0},[Gi.MEDIA_DIRECTION.RECV]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0}},this.gatheringSendData=!1}captureMediaData(e,t,i){const n=this.mediaData[e];if(e===Gi.MEDIA_DIRECTION.SEND&&(this.gatheringSendData=!0),t){const e=parseInt(t[t.length-1],10);n.totalFrameCount+=e}if(i){-1===n.totalMediaDuration&&(n.totalMediaDuration=0);const e=parseInt(i[i.length-1],10);n.mediaStarted||e>0&&(n.mediaStarted=!0,n.mediaStartTimestamp=new Date)}n.mediaStarted&&(n.totalMediaDuration+=Gi.TIME_INTERVAL.SEC_1)}captureFrameRate(e){const t=this.mediaData[Gi.MEDIA_DIRECTION.SEND];if(e){const i=parseInt(e[e.length-1],10);t.cameraFrameRate+=i}}stopRecvDataGathering(){const e=this.mediaData[Gi.MEDIA_DIRECTION.RECV],t=(new Date).getTime();e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t-e.mediaStartTimestamp.getTime())/1e3):0,e.mediaStarted=!1}isGatheringSendData(){return this.gatheringSendData}stopSendDataGathering(){const e=this.mediaData[Gi.MEDIA_DIRECTION.SEND],t=new Date;e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t.getTime()-e.mediaStartTimestamp.getTime())/1e3):0,this.gatheringSendData=!1,e.mediaStarted=!1}getAvgFrameRate(e){const t=this.mediaData[e];if(t.totalMediaDuration>0&&t.totalFrameCount>0)return t.totalFrameCount/t.totalMediaDuration}getTotalDuration(e){const t=this.mediaData[e];return t.totalMediaDuration>=0?t.totalMediaDuration:void 0}getTimeSinceLastDecode(e){const t=this.mediaData[e];return t.timeSinceLastDecode>0?t.timeSinceLastDecode:void 0}getSendCameraFramerate(){const e=this.mediaData[Gi.MEDIA_DIRECTION.SEND];if(e.totalMediaDuration>0)return e.cameraFrameRate/e.totalMediaDuration}},tU={fs:0,fps:1},iU=class{constructor(e){this.logger=e,this.allowed=new Map,this.lastParams=new Map,this.currentEvents=new Map,this.finishedEvents=[]}setMaxCapabilities(e){e.forEach((e=>{if(e.ssrc||0===e.ssrc){this.finishIfActive(e.ssrc),this.allowed.set(e.ssrc,{fs:e.maxFs+tU.fs,fps:e.maxFps+tU.fps});const t=this.lastParams.get(e.ssrc);t&&this.setCurrentParams(e.ssrc,t.fs,t.fps)}}))}setCurrentParams(e,t,i){this.lastParams.set(e,{fs:t,fps:i});const n=this.getAllowedParams(e);n&&(t>n.fs||i>n.fps)?(this.captureOvershoot(e,i,n.fps,"fps"),this.captureOvershoot(e,t,n.fs,"fs")):n&&this.finishIfActive(e)}flush(){this.currentEvents.forEach(((e,t)=>this.finishIfActive(t)))}getEvents(){const e=[...nn(this.finishedEvents)],t=Date.now();return this.currentEvents.forEach((i=>i.forEach((i=>e.push({ssrc:i.ssrc,timestamp:i.timestamp,duration:t-i.timestamp,overshootType:i.overshootType,amount:i.amount}))))),e}captureOvershoot(e,t,i,n){const r=this.currentEvents.get(e)||[],s=r.findIndex((e=>e.overshootType===n)),a=r[s],o=t-i,l=tU[n];o<=l&&a?(a.duration=Date.now()-a.timestamp,this.finishedEvents.push(a),this.logger.debug(`stopped overshooting ${n} by ${a.amount}`),r.splice(s,1)):o>l&&!a?(this.logger.safe.info(`overshooting ${n} by ${t-i}`),r.push({ssrc:e,timestamp:Date.now(),duration:-1,overshootType:n,amount:{min:o,max:o}})):o>l&&a&&(a.amount={min:Math.min(a.amount.min,o),max:Math.max(a.amount.max,o)}),r.length?this.currentEvents.set(e,r):this.currentEvents.has(e)&&this.currentEvents.delete(e)}getAllowedParams(e){return this.allowed.get(e)||this.allowed.get(0)}finishIfActive(e){const t=this.currentEvents.get(e);if(t){const i=Date.now();t.forEach((t=>{t.duration=i-t.timestamp,this.finishedEvents.push(t),this.logger.debug(`finished overshooting ${t.overshootType} by min:${t.amount.min} max:${t.amount.max} for ${t.duration}ms for ssrc ${e}`)})),this.currentEvents.delete(e)}}},nU=class{constructor(){this.qpData={[Gi.MEDIA_DIRECTION.SEND]:{frames:0,qpSum:0},[Gi.MEDIA_DIRECTION.RECV]:{frames:0,qpSum:0}}}captureQpData(e,t,i){const n=this.qpData[e];if(i&&i.length>0){const e=parseInt(i[i.length-1],10);e>0&&(n.frames=e)}if(t){const e=parseInt(t,10);e>0&&(n.qpSum=e)}}getQpAverage(e){const t=this.qpData[e];if(t.qpSum>0&&t.frames>0)return t.qpSum/t.frames}},rU=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(e){e&&e.width&&e.height&&(this.isResolutionChanged(this.lastResolution,e)&&this.resolutionChanged(e),this.updateResolutionDuration(this.getResolutionKey(e),this.resDurations)),this.lastPreferredResolution&&this.updatePreferredResolutionDurations()}capturePreferredResolution(e,t){const i=this.getResolutionKey(e);this.preferredResolution.includes(i)||(this.preferredResolutions.length>=t&&this.preferredResolutions.shift(),this.preferredResolutions.push(i)),this.isResolutionChanged(this.lastPreferredResolution,e)&&(this.preferredResolutionChanged(e),this.updatePreferredResolutionDurations())}getResolutionKey(e){return`${e.width}x${e.height}`}isResolutionChanged(e,t){return!e||e.width!==t.width||e.height!==t.height}countResolutionDurationRatio(e){const t={};let i=0;for(const t in e)i+=e[t];for(const n in e)t[n]=mn(e[n]/i*100,2);return t}updatePreferredResolutionDurations(){this.updateResolutionDuration(this.getResolutionKey(this.lastPreferredResolution),this.preferredResolutionDurations)}updateResolutionDuration(e,t){t[e]||(t[e]=0),t[e]++}preferredResolutionChanged(e){this.lastPreferredResolution=e}resolutionChanged(e){this.lastResolution=e,this.resolutionChangedCount++}},sU=class{constructor(){this.streamsTimers={}}countRecvStreams(e){const t=`${e}`;this.streamsTimers.hasOwnProperty(t)||(this.streamsTimers[t]=0),this.streamsTimers[t]++}getStreamCounts(){const e={min:void 0,max:void 0,mode:void 0},t=Object.keys(this.streamsTimers).map(Number);return 0===t.length||1===t.length&&0===t[0]||(e.min=Math.min(...t.filter((e=>e>0))),e.max=Math.max(...t),e.mode=t.reduce(((e,t)=>this.streamsTimers[t]>this.streamsTimers[e]?t:e),t[0])),e}},aU=class{constructor(e){this.configProvider=e,this.subscriptionEvents=[],this.subscriptionCounters={attempted:0,subscribed:0,unsubscribed:0,failed:0}}addSubscriptionEvent(e){switch(this.subscriptionEvents.length>this.configProvider.config.webrtcSubscriptionEventLimit&&this.subscriptionEvents.shift(),this.subscriptionEvents.push(e),e.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}},oU=class{constructor(e,t,i,n="Video"){this.startTime=e,this.configProvider=t,this.logger=i,this.mediaType=n,this.subscriptionCounter=0,this.videoFreezeTelemetry=new XF(this.configProvider,this.startTime),this.videoDelayTelemetry=new ZF,this.videoSubscriptionEvents=new aU(this.configProvider),this.videoQPEvents=new nU,this.videoResolutionTelemetry=new rU,this.videoGeneralTelemetry=new eU,this.videoStreamsCounters=new sU,this.videoBitrate=new JF,this.videoMaxCapabilities=new QF(this.configProvider,this.logger),this.videoOvershoot=new iU(this.logger),this.videoQualityLimitations=new KF(this.configProvider),this.videoStatsOnSubscribed=new uF(this.configProvider),this.videoResolutionSwitchTracker=new aD(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(e){this.currentTrackId=e}get isRecvDataGatheringEnabled(){return this.subscriptionCounter>0}startStopRecvDataGathering(e){this.logger.safe.info("Receive data gathering is "+(e?"enabled":"disabled")),e?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(Gi.MEDIA_DIRECTION.RECV)}isSendGathering(){return this.videoGeneralTelemetry.isGatheringSendData()}stopSendGathering(){this.videoGeneralTelemetry.stopSendDataGathering(),this.videoBitrate.stopCapture(Gi.MEDIA_DIRECTION.SEND),this.videoOvershoot.flush()}gatherRecvFreezeData(e,t,i){this.videoFreezeTelemetry.gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:this.mediaType})}detectCaptureFreeze(e){this.videoFreezeTelemetry.detectCaptureFreeze(e)}getRecvFreezeDurationCounts(){return this.videoFreezeTelemetry.getRecvFreezeDurationCounts()}getRecvFreezeDurationTimestamps(){return this.videoFreezeTelemetry.getRecvFreezeDurationTimestamps(this.configProvider.config.maxVideoFreezeTimestampsInBucket)}getRecvTotalFreezeDuration(){return this.videoFreezeTelemetry.getRecvTotalFreezeDuration()}setRecvTotalFreezeDurationMs(e){this.recvTotalFreezeDurationMs=void 0!==e?this.recvTotalFreezeDurationMs+=e:void 0}analyzeDelay(e,t){this.videoDelayTelemetry.analyzeDelay(e,t)}getDelayCur(){return this.videoDelayTelemetry.getDelayCur()}getDelayAvg(){return this.videoDelayTelemetry.getDelayAvg()}addSubscriptionEvent(e){this.videoSubscriptionEvents.addSubscriptionEvent(e)}getSubscriptionEvents(){return this.videoSubscriptionEvents.getSubscriptionEvents()}getSubscriptionCounters(){return this.videoSubscriptionEvents.getSubscriptionCounters()}captureQpData(e,t,i){this.videoQPEvents.captureQpData(e,t,i)}getQpAverage(e){return this.videoQPEvents.getQpAverage(e)}captureMediaData(e,t,i){this.videoGeneralTelemetry.captureMediaData(e,t,i)}getIsRendering(){const e=this.configProvider.config.notRenderingTimeInterval["Video"===this.mediaType?"video":"sharing"];return this.videoFreezeTelemetry.getIsRendering(e)}captureFrameRate(e){this.videoGeneralTelemetry.captureFrameRate(e)}getTotalDuration(e){return this.videoGeneralTelemetry.getTotalDuration(e)}captureResolutionSample(e){this.videoResolutionTelemetry.captureSample(e)}countRecvStreams(e){this.videoStreamsCounters.countRecvStreams(e)}captureBitrateSample(e,t){this.videoBitrate.captureSample(e,t)}captureAllocateBandwidth(e){this.videoBitrate.captureAllocateBandwidth(e)}capturePreferredResolution(e,t){this.videoResolutionTelemetry.capturePreferredResolution(e,t)}setMaxCapabilitesRequested(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesRequested(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}setMaxCapabilitesApplied(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesApplied(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}getMaxCapabilitiesEvents(){const e=this.videoMaxCapabilities.getEvents();return JSON.stringify(e)}getMaxCapabilitiesResolutionChanges(){const e=this.videoMaxCapabilities.getResolutionRecords();return e?JSON.stringify(e):""}getMaxCapabilitiesErrors(){const e=this.videoMaxCapabilities.getErrors();return e?JSON.stringify(e):""}setCurrentParameters(e,t,i){this.videoOvershoot.setCurrentParams(e,t.height/16*(t.width/16),i)}setMaxCapabilitiesOvershoot(e){this.videoOvershoot.setMaxCapabilities(e)}getOvershootEvents(){let e=this.videoOvershoot.getEvents();return e=e.slice(Math.max(0,e.length-(this.configProvider.config.maxReportedOvershootingEvents+1)),e.length),e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify(e)}getOvershootTotalDurations(){const e=this.videoOvershoot.getEvents();return e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify({fs:e.reduce(((e,t)=>"fs"===t.overshootType?e+t.duration:e),0),fps:e.reduce(((e,t)=>"fps"===t.overshootType?e+t.duration:e),0)})}setQualityLimitationReason(e){this.videoQualityLimitations.setQualityLimitationReason(e)}getQualityLimitationReasonEvents(){return this.videoQualityLimitations.getQualityLimitationReasonEvents()}captureTimeToFirstFrame(e,t){-1!==e&&(this.timeToFirstFrame=e,this.timeToFirstFrameSinceSubscriptionStart=t)}getTimeToFirstFrame(){return this.timeToFirstFrame}setIsRendering(e){Sn(this.isRenderingEvents,{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.telemetryLimits.numIsRenderingEvents)}setMsi(e){this.msi=e}setLocalMsi(e){this.localMsi=e}prepareCollectingStatsOnSubscribed(e){this.videoStatsOnSubscribed.prepareCollectingStatsOnSubscribed(e)}captureStatsOnSubscribed(e,t){this.videoStatsOnSubscribed.captureStatsOnSubscribed(e,t)}calculateResolutinSwitches(e,t){this.videoResolutionSwitchTracker.captureSample(e,t)}getReport(e,t,i=!1){const n={};if(n[t+"DurationSeconds"]=this.getTotalDuration(e),n[t+"QpAvg"]=this.getQpAverage(e),n[t+"frameRateAvg"]=this.videoGeneralTelemetry.getAvgFrameRate(e),n[t+"bitrateAvg"]=this.videoBitrate.getAvg(e),n[t+"bitrateMax"]=this.videoBitrate.getMax(e),e===Gi.MEDIA_DIRECTION.SEND)n[t+"DelayCur"]=this.getDelayCur(),n[t+"DelayAvg"]=this.getDelayAvg(),n[t+"TimeSinceLastEncodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"AllocateBWAvg"]=this.videoBitrate.getAllocateBandwidthAvg(),n[t+"CaptureFramerateAvg"]=this.videoGeneralTelemetry.getSendCameraFramerate(),n[t+"FreezeIntervals"]=this.videoFreezeTelemetry.getSendCameraFreezeIntervals(),n[t+"MaxCapabilities"]=i?"":this.getMaxCapabilitiesEvents(),n[t+"MaxCapabilitiesErrors"]=i?"":this.getMaxCapabilitiesErrors(),n[t+"OvershootEvents"]=this.getOvershootEvents(),n[t+"OvershootDurations"]=this.getOvershootTotalDurations(),n[t+"qualityLimitationReasonEvents"]=JSON.stringify(this.getQualityLimitationReasonEvents()),n[t+"MaxCapabilitiesResolutions"]=this.getMaxCapabilitiesResolutionChanges(),n[t+"ResolutionsSwitches"]=this.videoResolutionSwitchTracker.switches?JSON.stringify(this.videoResolutionSwitchTracker.switches):"";else if(e===Gi.MEDIA_DIRECTION.RECV){n[t+"TimeSinceLastDecodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"FreezeHistogram"]=this.getRecvFreezeDurationCounts(),n[t+"FreezeTimestamps"]=this.getRecvFreezeDurationTimestamps(),n[t+"LongestFreezeDuration"]=this.videoFreezeTelemetry.getLongestRecvFreezeDuration(),n[t+"RecvAvgFreezeDuration"]=this.videoFreezeTelemetry.getRecvAvgFreezeDuration(),n[t+"TotalFreezeDuration"]=this.getRecvTotalFreezeDuration(),n[t+"TotalFreezeDurationMs"]=this.recvTotalFreezeDurationMs,n[t+"OngoingFreeze"]=this.videoFreezeTelemetry.getRecvFreezeIsOngoing(this.configProvider.config.webrtcEndOfCallFreezeThreshold),n[t+"NumResolutionSwitches"]=this.videoResolutionTelemetry.resolutionSwitchCount,n[t+"PreferredResolution"]=this.videoResolutionTelemetry.preferredResolution,n[t+"PreferredResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.preferredResolutionDurationRatios),n[t+"ResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.resolutionDurationRatios);const i=this.videoStreamsCounters.getStreamCounts();n[t+"StreamsMin"]=i.min,n[t+"StreamsMax"]=i.max,n[t+"StreamsMode"]=i.mode,n[t+"TimeToFirstFrame"]=this.timeToFirstFrame,n[t+"TimeToFirstFrameSinceSubscriptionStart"]=this.timeToFirstFrameSinceSubscriptionStart,n[t+"LocalMsi"]=this.localMsi,n[t+"Msi"]=this.msi,n[t+"isRenderingEvents"]=JSON.stringify(this.isRenderingEvents),n[t+"statsOnSubscribed"]=JSON.stringify(this.videoStatsOnSubscribed.videoStatsOnSubscribed)}return n}},lU=Symbol("mslbase"),cU=Symbol("mslsamples"),dU=class{constructor(e,t){this.logger=e,this.configProvider=t,this.currentLayouts={},this.collectedModalitySessions=[],this.startTimestamp=Date.now()}get collectedSessions(){return this.collectedModalitySessions}get highestFidelitySSRC(){if(!this.currentModalitySession)return;let e;for(const t in this.currentLayouts)e=this.getHigherFidelitySSRC(t,e);return parseInt(e)}processStats(e){const t=Object.values(e.ssrc??{}).filter((e=>e.rid&&e.ssrc&&e.googFrameHeightInput&&this.lastMaxCapabilitiesEvent?.capabilities.some((t=>t.rid===e.rid)))),i=new Map(t.map((e=>[`${e.ssrc}`,e.rid])));for(const e in this.currentLayouts)i.has(e)||this.collectLayout(e);!this.currentModalitySession&&i.size>0&&(this.currentModalitySession={timestamp:Date.now()-this.startTimestamp,duration:0,numLayouts:0,layouts:[]},this.logger.safe.info("Modality session started")),t.forEach((e=>{this.currentLayouts[`${e.ssrc}`]||this.addLayout(e)})),0===i.size&&this.currentModalitySession&&this.collectSession(),t.forEach((e=>this.processLayoutData(e)))}setMaxCapabilities(e,t){if(this.lastMaxCapabilitiesEvent=e,Object.keys(this.currentLayouts).length)for(const i of e.capabilities){const n=Object.values(this.currentLayouts).find((e=>e.rid===i.rid));n&&(t?(Sn(n.fmtp,{...i,timestamp:Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-n.timestamp,causeId:e.causeId},this.configProvider.config.simulcastTelemetryNumFMTP),n.gatherer.setMaxCapabilitesApplied(e)):n.gatherer.setMaxCapabilitesRequested(e),n.gatherer.setMaxCapabilitiesOvershoot([i]))}}finish(){this.logger.safe.info("Finishing statistics gathering");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession&&this.collectSession()}addLayout(e){const t=`${e.ssrc}`,i=e.rid,n=this.lastMaxCapabilitiesEvent?.capabilities.find((e=>e.rid===i));this.logger.safe.info(`Adding layout for ssrc ${t} rid ${i}`);const r=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,s=new oU(r,this.configProvider,this.logger.createChild(`Telemetry#${t}`));this.currentLayouts[t]={ssrc:e.ssrc,rid:i,fmtp:[{...n,timestamp:r,causeId:this.lastMaxCapabilitiesEvent?.causeId}],timestamp:r,duration:0,gatherer:s,[lU]:{firCount:e.googFirsReceived,nackCount:e.googNacksReceived,pliCount:e.googPlisReceived,framesEncoded:e.framesEncoded,bytesSent:e.bytesSent,packetsSent:e.packetsSent,packetsLost:e.packetsLost,qpSum:e.qpSum},[cU]:{firCount:[],nackCount:[],pliCount:[],framesEncoded:[],bytesSent:[],packetsSent:[],packetsLost:[],qpSum:[],frameHeightInput:[],frameHeightSent:[],frameRateInput:[],frameRateSent:[]}},s.setMaxCapabilitiesOvershoot([n]),this.currentModalitySession.numLayouts++}processLayoutData(e){const t=`${e.ssrc}`,i=this.currentLayouts[t];this.processMediaStats(i,e),i.gatherer.captureMediaData(Gi.MEDIA_DIRECTION.SEND,[String(e.googFrameRateSent)],[String(e.framesEncoded)]),i.gatherer.captureFrameRate([String(e.googFrameRateInput)]),i.gatherer.captureQpData(Gi.MEDIA_DIRECTION.SEND,String(e.qpSum),[String(e.framesEncoded)]),i.gatherer.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,e.bytesSent),i.gatherer.detectCaptureFreeze([String(e.googFrameRateInput)]),i.gatherer.setCurrentParameters(e.ssrc,{width:e.googFrameWidthSent,height:e.googFrameHeightSent},e.googFrameRateSent)}processMediaStats(e,t){const i=e[lU],n=t.googFirsReceived-i.firCount,r=t.googNacksReceived-i.nackCount,s=t.googPlisReceived-i.pliCount,a=t.framesEncoded-i.framesEncoded,o=t.bytesSent-i.bytesSent,l=t.packetsSent-i.packetsSent,c=t.packetsLost-i.packetsLost,d=t.qpSum-i.qpSum,u=e[cU],h=this.configProvider.config.webrtcStatStoredRecordsNumber;Sn(u.firCount,n,h),Sn(u.nackCount,r,h),Sn(u.pliCount,s,h),Sn(u.framesEncoded,a,h),Sn(u.bytesSent,o,h),Sn(u.packetsSent,l,h),Sn(u.packetsLost,c,h),Sn(u.qpSum,d,h),Sn(u.frameHeightInput,t.googFrameHeightInput,h),Sn(u.frameHeightSent,t.googFrameHeightSent,h),Sn(u.frameRateInput,t.googFrameRateInput,h),Sn(u.frameRateSent,t.googFrameRateSent,h)}collectLayout(e){this.logger.safe.info(`Collecting layout for ssrc ${e}`),this.currentLayouts[e].duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-this.currentLayouts[e].timestamp,this.currentLayouts[e].gatherer.isSendGathering()&&this.currentLayouts[e].gatherer.stopSendGathering();const t=this.currentLayouts[e].gatherer.getReport(Gi.MEDIA_DIRECTION.SEND,"",!1);for(const i in t)this.currentLayouts[e][i]=t[i];for(const t in this.currentLayouts[e][cU])this.currentLayouts[e][t]=Pn(this.currentLayouts[e][cU][t],(e=>e));delete this.currentLayouts[e].gatherer,Sn(this.currentModalitySession.layouts,this.currentLayouts[e],this.configProvider.config.simulcastTelemetryLayoutsPerSession),delete this.currentLayouts[e]}collectSession(){this.logger.safe.info("Collecting session");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession.duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,Sn(this.collectedModalitySessions,this.currentModalitySession,this.configProvider.config.simulcastTelemetryNumModalitySessions),this.currentModalitySession=void 0,this.lastMaxCapabilitiesEvent=void 0}getHigherFidelitySSRC(e,t){if(!e||!t)return e||t;const[i]=this.currentLayouts[e].fmtp.slice(-1),[n]=this.currentLayouts[t].fmtp.slice(-1);return(i?.maxMbps??0)>0&&(n?.maxMbps??0)>0?i.maxMbps>n.maxMbps?e:t:e||t}},uU=["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"],hU=["bytesSent","bytesReceived","googRtt","packetsSent","requestsSent","consentRequestsSent","responsesSent","requestsReceived","responsesReceived"],gU=["googAvailableReceiveBandwidth","googAvailableSendBandwidth","googTransmitBitrate"];function pU(e,t,i){const n=i.value;i.value=function(...e){try{return n.apply(this,e)}catch(e){this.processStatsError(t,e)}}}var mU=class{constructor(e,t,i,n,r,s){this.logger=e,this.sessionInfo=t,this.configProvider=i,this.mediaManager=n,this.multiparty=r,this.newStatsApi=s,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 HF(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 kL(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 oU(this.extensions.StartTime,this.configProvider,this.logger.createChild("Video"),"Video"),this.sharingTelemetry=new oU(this.extensions.StartTime,this.configProvider,this.logger.createChild("Sharing"),"ScreenShare"),this.bandwidthTelemetry=new $F(this.configProvider.config.webrtcBWJumpLowerLimit,this.configProvider.config.webrtcBWJumpUpperLimit),this.stabilizationTelemetry=new fF(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wp),this.storedRecordsNumber=Number(this.configProvider.config.webrtcStatStoredRecordsNumber),this.hwSilentDetectionDuration=Number(this.configProvider.config.webrtcStatHwSilentDetectionDuration),this.hwSilentDetectionLevel=Number(this.configProvider.config.webrtcStatHwSilentDetectionLevel),this.audioHealedRatioTelemetry=new VF(this.configProvider),this.networkQualityTelemetry=new WF(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 dU(this.logger.createChild("simulcastVideo"),this.configProvider),this.simulcastSharing=new dU(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(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.cameraOpenResolution=t.resolution)}}onMaxCapabilitiesRequested(e){(e.modality===Gi.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesRequested(e),(e.modality===Gi.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!1)}onMaxCapabilitiesApplied(e){(e.modality===Gi.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesApplied(e),(e.modality===Gi.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!0)}setSubscribedTrackIds(e){this.subscribedTrackIds=e||[]}setSubscribedTrackSsrc(e){this.subscribedTrackSsrc=e||[]}addSubscriptionEvent(e,t,i,n,r,s,a){const o={evt:e,ts:Date.now()-this.extensions.StartTime,msi:i,localMsi:n,duration:s};r&&(o.error=tt(r));const l=this.getHandlerForModality(t);if(l.addSubscriptionEvent(o),a&&this.setMSIDsPair(i,n,a),1===e||3===e){const t=1===e;l.startStopRecvDataGathering(t)}2===e&&l.prepareCollectingStatsOnSubscribed(i)}setMSIDsPair(e,t,i){const n=`ssrc_${i.replace(/\D/g,"")}_recv`;this.MSIDsPairs[n]={msi:e,localMsi:t}}getHandlerForModality(e){switch(e){case Gi.MODALITY.video:return this.videoTelemetry;case Gi.MODALITY.sharing:return this.sharingTelemetry;default:throw new Error(`Handler not found for modality: ${e}`)}}setTerminated(){this.extensions.EndTime=(new Date).getTime(),this.terminated=!0}startWaitingForStreamStart(e){this.streamStartDetection||this.sessionInfo.setOfferedModalities(e),this.streamStartDetection=!0}processStatsDict(e){if(this.processSimulcastStats(e),this.constructWebRtcReportForSingleStream(this.extensions.WebRTCStats,e),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,e),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 t=this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]?this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]:{};this.constructWebRtcReportForMultipleStreams(t,e);for(const e of Object.keys(t)){const i=t[e];this.processVideoStatsRecv(this.multiViewVideoTelemetry[e],i)}this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]=t}this.extensions.WebRTCStats.statsErrors=JSON.stringify(this.statsErrors)}setTimeToFirstFrame(e,t,i){i in this.timeToFirstFrame||(this.timeToFirstFrame[i]=e,this.timeToFirstFrameSinceSubscriptionStart[i]=t)}getCurrentTimeToFirstFrame(e){return this.timeToFirstFrame[e]?this.timeToFirstFrame[e]:-1}getCurrentTimeToFirstFrameSinceSubscriptionStart(e){return this.timeToFirstFrameSinceSubscriptionStart[e]?this.timeToFirstFrameSinceSubscriptionStart[e]:-1}getVideoTelemetryBySsrc(e){let t;return this.extensions.WebRTCStats.ssrc_video_recv&&this.extensions.WebRTCStats.ssrc_video_recv.id===e?t=this.videoTelemetry:this.extensions.WebRTCStats.ssrc_sharing_recv&&this.extensions.WebRTCStats.ssrc_sharing_recv.id===e?t=this.sharingTelemetry:this.isMultiViewVideoTelemetry&&(t=this.multiViewVideoTelemetry[e]),t}getIsRendering(e){const t=this.getVideoTelemetryBySsrc(e);return t?t.getIsRendering():void 0}setFreezeDuration(e,t){for(const i of Object.keys(this.multiViewVideoTelemetry))this.multiViewVideoTelemetry[i].trackId===t&&this.isSubscribed(t)&&this.multiViewVideoTelemetry[i].setRecvTotalFreezeDurationMs(e);this.currentSharingRecvTrackId===t&&this.isSubscribed(t)&&this.sharingTelemetry.setRecvTotalFreezeDurationMs(e),this.currentVideoRecvTrackId===t&&this.isSubscribed(t)&&this.videoTelemetry.setRecvTotalFreezeDurationMs(e)}addVideoControlMessage(e){this.totalVideoControlMessages++,e&&this.outOfOrderVideoControlMessages++}setStreamSenderStarted(e,t){this.streamSenderStarted[e]=t}addReportedReceiveBandwidth(e){this.limitCaptureAmount(this.extensions,"ReportedReceiveBandwidth",e)}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(e){this.simulcastVideo.processStats(e),this.simulcastSharing.processStats(e)}processBandwidthStats(){const e=this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth;if(e){const t=this.streamSenderStarted.Video||this.streamSenderStarted.ScreenShare;this.bandwidthTelemetry.recordSendBandwidth(e[e.length-1]),this.stabilizationTelemetry.processBandwidth(parseInt(e[e.length-1]),this.sessionInfo.activeModalities,t)}}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,UF.last)(this.extensions.WebRTCStats.ssrc_audio_recv.googJitterBufferMs)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.jitter&&this.audioTelemetry.captureJitter((0,UF.last)(this.extensions.WebRTCStats.ssrc_audio_recv.jitter)),this.extensions.WebRTCStats.ssrc_audio_send?.googRtt){const e=this.extensions.WebRTCStats.ssrc_audio_send.googRtt;this.audioTelemetry.captureRtt(e[e.length-1])}}stopGatheringIfNeeded(e,t,i,n){const r=`${t}${i}`;n!==this.lastSSRCs.get(r)&&(this.lastSSRCs.set(r,n),t===Gi.MEDIA_DIRECTION.SEND?e.stopSendGathering():e.stopRecvGathering())}processVideoStatsSend(e,t){t&&Wp(this.sessionInfo.activeModalities.video)?(this.stopGatheringIfNeeded(e,Gi.MEDIA_DIRECTION.SEND,"Video",t.ssrc),e.captureMediaData(Gi.MEDIA_DIRECTION.SEND,t.googFrameRateSent,t.framesEncoded),e.captureFrameRate(t.googFrameRateInput),e.analyzeDelay(this.videoDelayTimePeriod,t.googAvgEncodeMs),e.captureQpData(Gi.MEDIA_DIRECTION.SEND,t.qpSum,t.framesEncoded),e.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,this.getLastSampleInt(t.bytesSent)),e.detectCaptureFreeze(t.googFrameRateInput),e.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),e.setCurrentParameters(parseInt(t.ssrc),{width:this.getLastSampleInt(t.googFrameWidthSent),height:this.getLastSampleInt(t.googFrameHeightSent)},this.getLastSampleInt(t.googFrameRateSent)),e.setQualityLimitationReason(t.qualityLimitationReason),this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo&&e.calculateResolutinSwitches(this.getLastSampleInt(t.googFrameWidthSent),this.getLastSampleInt(t.googFrameHeightSent))):e.isSendGathering()&&(e.stopSendGathering(),this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.SEND}Video`))}processVideoStatsRecv(e,t,i=!1){t&&Kp(this.sessionInfo.activeModalities.video)&&this.videoTelemetry.isRecvDataGatheringEnabled?(i&&this.stopGatheringIfNeeded(e,Gi.MEDIA_DIRECTION.RECV,"Video",t.ssrc),e.trackId=t.googTrackId,e.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived,this.getLastSampleInt(t.bytesReceived)),e.captureMediaData(Gi.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),e.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),e.captureQpData(Gi.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),e.captureBitrateSample(Gi.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),e.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),e.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):i&&this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.RECV}Video`)}processSharingStats(){const e=this.extensions.WebRTCStats.ssrc_sharing_send,t=this.extensions.WebRTCStats.ssrc_sharing_recv;e&&Wp(this.sessionInfo.activeModalities.sharing)?(this.stopGatheringIfNeeded(this.sharingTelemetry,Gi.MEDIA_DIRECTION.SEND,"Sharing",e.ssrc),this.sharingTelemetry.captureMediaData(Gi.MEDIA_DIRECTION.SEND,e.googFrameRateSent,e.framesEncoded),this.sharingTelemetry.captureFrameRate(e.googFrameRateInput),this.sharingTelemetry.analyzeDelay(this.videoDelayTimePeriod,e.googAvgEncodeMs),this.sharingTelemetry.captureQpData(Gi.MEDIA_DIRECTION.SEND,e.qpSum,e.framesEncoded),this.sharingTelemetry.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,this.getLastSampleInt(e.bytesSent)),this.sharingTelemetry.detectCaptureFreeze(e.googFrameRateInput),this.sharingTelemetry.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),this.sharingTelemetry.setCurrentParameters(parseInt(e.ssrc),{width:this.getLastSampleInt(e.googFrameWidthSent),height:this.getLastSampleInt(e.googFrameHeightSent)},this.getLastSampleInt(e.googFrameRateSent)),this.limitCaptureAmount(this.extensions,"Sharing_send_RawInputVolume",this.audioTelemetry.getInputLevel("ScreenShare"))):this.sharingTelemetry.isSendGathering()&&(this.sharingTelemetry.stopSendGathering(),this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.SEND}Sharing`)),t&&Kp(this.sessionInfo.activeModalities.sharing)&&this.sharingTelemetry.isRecvDataGatheringEnabled?(this.stopGatheringIfNeeded(this.sharingTelemetry,Gi.MEDIA_DIRECTION.RECV,"Sharing",t.ssrc),this.sharingTelemetry.trackId=t.googTrackId,this.sharingTelemetry.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived),this.sharingTelemetry.captureMediaData(Gi.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),this.sharingTelemetry.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),this.sharingTelemetry.captureQpData(Gi.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),this.sharingTelemetry.captureBitrateSample(Gi.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),this.sharingTelemetry.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),this.sharingTelemetry.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.RECV}Sharing`)}processStreamsCounters(){const e=this.extensions.WebRTCStats.recvCounters;e&&(this.videoTelemetry.countRecvStreams(e[Gi.MODALITY.video]),this.sharingTelemetry.countRecvStreams(e[Gi.MODALITY.sharing]))}setMissedInitialPreferredResolution(){qi(this.missedInitialPreferredResolution,((e,t)=>{this.setPreferredResolution(t,e)})),this.missedInitialPreferredResolution={}}setPreferredResolution(e,t,i){if((i===Gi.MEDIA_TYPE.video&&!this.currentVideoRecvTrackId||i===Gi.MEDIA_TYPE.sharing&&!this.currentSharingRecvTrackId)&&(this.missedInitialPreferredResolution[e]=t),this.currentVideoRecvTrackId===e&&this.videoTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.currentSharingRecvTrackId===e&&this.sharingTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.isMultiViewVideoTelemetry){const i=this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(e)];i&&i.capturePreferredResolution(t,this.maxStoredPreferredResolutions)}}setIsRendering(e,t,i){t===Gi.MEDIA_TYPE.video&&this.videoTelemetry.setIsRendering(e),t===Gi.MEDIA_TYPE.sharing&&this.sharingTelemetry.setIsRendering(e),this.isMultiViewVideoTelemetry&&this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(i)]?.setIsRendering(e)}setMaxSessionBandwidth(e){this.extensions.MaxSessionBandwidth=e}isSubscribed(e,t){let i=this.subscribedTrackIds.some((t=>t===e));return!i&&this.configProvider.config.subscribeToSsrcForVideo&&(i=this.subscribedTrackSsrc.some((e=>e===`${t}`))),i||!this.multiparty&&this.configProvider.config.subscribeToSsrcForVideo}getReport(e=!1,t=!1){try{t&&this.resetPairValues(),e||(this.videoTelemetry.stopDataGathering(),this.sharingTelemetry.stopDataGathering());const i=this.videoTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.RECV),n=this.videoTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.SEND),r=this.sharingTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.RECV),s=this.sharingTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.SEND);if(i>=0&&(qi(this.videoTelemetry.getReport(Gi.MEDIA_DIRECTION.RECV,"Video_recv_",t),((e,t)=>this.extensions[t]=e)),!Xi(this.multiViewVideoTelemetry))){const e=[];for(const i of Object.keys(this.multiViewVideoTelemetry)){const n={id:i};qi(this.multiViewVideoTelemetry[i].getReport(Gi.MEDIA_DIRECTION.RECV,"Video",t),((e,t)=>{void 0!==e&&(n[t]=e)})),e.push(n)}this.extensions[Gi.MULTIPLE_RECV_STREAMS]=JSON.stringify(e)}r>=0&&qi(this.sharingTelemetry.getReport(Gi.MEDIA_DIRECTION.RECV,"Sharing_recv_",t),((e,t)=>this.extensions[t]=e)),n>=0&&(qi(this.videoTelemetry.getReport(Gi.MEDIA_DIRECTION.SEND,"Video_send_",t),((e,t)=>this.extensions[t]=e)),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),s>=0&&qi(this.sharingTelemetry.getReport(Gi.MEDIA_DIRECTION.SEND,"Sharing_send_",t),((e,t)=>this.extensions[t]=e)),e||t||(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=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionEvents()),this.extensions.Video_SubscriptionCounters=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionCounters()),this.extensions.Sharing_SubscriptionEvents=t?"":JSON.stringify(this.sharingTelemetry.getSubscriptionEvents()),this.extensions.Sharing_SubscriptionCounters=t?"":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 e of Object.keys(this.extensions))void 0===this.extensions[e]&&delete this.extensions[e];return delete this.extensions.WebRTCStats[Gi.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),nn(this.report)}catch(e){throw this.processStatsError("Report",e),{error:e,partialReport:nn(this.report)}}}getAudioHwSilent(){return this.hwSilent}getSpeakingState(){return this.isSpeaking}getNetworkSendLevel(){return this.networkSendLevel}getNetworkRecvLevel(){return this.networkRecvLevel}addIceCandidateError(e){this.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.iceCandidateErrors=[]}addH264AvailableProfiles(e){this.h264AvailableProfiles=[...new Set(this.h264AvailableProfiles.concat(e))]}setSupportedH264Profiles(e,t){this.h264CodecCapabilities.sendProfiles=e,this.h264CodecCapabilities.receiveProfiles=t}updateSendStream(e,t){this.audioTelemetry.updateSendStream(e,t)}getTimerTracker(e,t){return this.timerTrackerManager.getTimerTracker(e,t)}resetPairValues(){Object.keys(this.extensions.WebRTCStats).forEach((e=>{delete this.extensions.WebRTCStats[e].pair}))}limitCaptureAmount(e,t,i){void 0!==i&&(e[t]=Array.isArray(e[t])?e[t]:[],e[t].push(i),e[t].length>this.storedRecordsNumber&&e[t].shift())}setStartTime(e){const t=this.extensions.WebRTCStats;if(!t.ssrc_audio_send||!t.ssrc_audio_recv)return!1;const i=(e,t)=>!e||t&&-1===t?t:(new Date).getTime();return this.extensions.TimerAudioPayloadRecvBitrate=Kp(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioPayloadRecvBitrate):-1,this.extensions.TimerAudioPayloadSendBitrate=Wp(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioPayloadSendBitrate):-1,this.extensions.TimerAudioTransportRecvBitrate=Kp(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioTransportRecvBitrate):-1,this.extensions.TimerAudioTransportSendBitrate=Wp(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioTransportSendBitrate):-1,!!(t.ssrc_video_send&&t.ssrc_video_recv&&(this.extensions.TimerVideoPayloadRecvBitrate=Kp(e.video)?i(t.ssrc_video_recv.bytesReceived,this.extensions.TimerVideoPayloadRecvBitrate):-1,this.extensions.TimerVideoPayloadSendBitrate=Wp(e.video)?i(t.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 e=this.extensions.EndTime,t=(t,i)=>t&&e-i>0&&0!==i&&-1!==i?Math.round(8*t/(e-i)):0,i=e=>{const t=e.split(".").reduce(((e,t)=>null==e?e:e[t]),this.extensions.WebRTCStats);return Array.isArray(t)?t[t.length-1]:t};this.extensions.AudioPayloadRecvBitrate=t(i("ssrc_audio_recv.bytesReceived"),this.extensions.TimerAudioPayloadRecvBitrate),this.extensions.AudioPayloadSendBitrate=t(i("ssrc_audio_send.bytesSent"),this.extensions.TimerAudioPayloadSendBitrate),this.extensions.VideoPayloadRecvBitrate=t(i("ssrc_video_recv.bytesReceived"),this.extensions.TimerVideoPayloadRecvBitrate),this.extensions.VideoPayloadSendBitrate=t(i("ssrc_video_send.bytesSent"),this.extensions.TimerVideoPayloadSendBitrate),this.extensions.AudioTransportRecvBitrate=t(i("ssrc_audio_send.pair.bytesReceived"),this.extensions.TimerAudioTransportRecvBitrate),this.extensions.AudioTransportSendBitrate=t(i("ssrc_audio_send.pair.bytesSent"),this.extensions.TimerAudioTransportSendBitrate)}addFilteredFields(e,t,i=[]){for(const n in t)if(t.hasOwnProperty(n)&&"type"!==n)if(-1!==i.indexOf(n)){const i=e[n]||[];i.push(this.formatFields(t,n)),i.length>this.storedRecordsNumber&&i.shift(),e[n]||(e[n]=i)}else e[n]=t[n]}formatFields(e,t){const i=e[t];switch(t){case"audioInputLevel":case"audioOutputLevel":return this.newStatsApi?Math.floor(65535*i):2*i;case"googJitterBufferMs":return parseInt(i);case"healedRatio":return mn(parseFloat(i),this.configProvider.config.healedRatioPrecision);case"jitter":return mn(parseFloat(i),this.configProvider.config.jitterPrecision);default:return i}}processSource(e,t,i){let n;if(this.addFilteredFields(e,t,uU),t.transportId){const r=i.googComponent?.[t.transportId];e.transport||(e.transport={}),r&&(this.addFilteredFields(e.transport,r),r.selectedCandidatePairId&&(n=i.googCandidatePair?.[r.selectedCandidatePairId]))}else n=Object.values(i.googCandidatePair).find((e=>e.selected));n&&(e.pair||(e.pair={}),this.addFilteredFields(e.pair,n,hU))}getWebrtcReport(e,t,i,n){const r=e.ssrc[i],s=n?r.id.replace(/[0-9]+/,n):r.id;t[s]?r.ssrc!==t[s].ssrc&&(s.endsWith("video_send")?this.videoTelemetry.stopSendGathering():s.endsWith("video_recv")?this.videoTelemetry.stopRecvGathering():s.endsWith("sharing_send")?this.sharingTelemetry.stopSendGathering():s.endsWith("sharing_recv")&&this.sharingTelemetry.stopRecvGathering()):t[s]={},this.processSource(t[s],r,e)}constructWebRTCDataReport(e,t){if(!t.data?.length)return;const i=t.data.sort(((e,t)=>t.timestamp-e.timestamp)),n=i.find((e=>"open"===e.state));e.data=n||i[0]}constructWebRtcReportForSingleStream(e,t){if(!t.ssrc)return;const i=this.selectSsrcsToCollect(t.ssrc);e.recvCounters=i.recvCounters,delete i.recvCounters,delete i.multiRecv,qi(i,(i=>{qi(i,((i,n)=>{this.getWebrtcReport(t,e,i,n)}))})),t.VideoBwe?.bweforvideo&&(e.bweStat||(e.bweStat={}),this.addFilteredFields(e.bweStat,t.VideoBwe.bweforvideo,gU))}constructWebRtcReportForMultipleStreams(e,t){t.ssrc&&this.selectSsrcsToCollect(t.ssrc).multiRecv.forEach((i=>this.getWebrtcReport(t,e,i)))}getMediaType(e,t){let i=t?t.getModality():e.mediaType;return e.googTrackId?.match("applicationsharing")&&i!==Gi.MEDIA_TYPE.sharing&&(i=Gi.MEDIA_TYPE.sharing),i}selectSsrcsToCollect(e){const t={send:{},recv:{},recvCounters:{video:0,sharing:0},multiRecv:[]};if(!this.sessionInfo.activeModalities)return t;let i=[];for(const n of Object.keys(e)){const r=e[n],s=r.googTrackId;if(!s&&r.mediaType!==Gi.MEDIA_TYPE.audio)continue;const a=this.getMediaEntity(s,r),o=this.getMediaType(r,a),l=a?.getXSourceStreamId();if(n.endsWith("send"))switch(o){case Gi.MEDIA_TYPE.audio:Wp(this.sessionInfo.activeModalities.audio)&&(t.send.audio=n);break;case Gi.MEDIA_TYPE.video:if(this.extensions.Video_send_SourceId=l,this.simulcastVideo.highestFidelitySSRC){this.simulcastVideo.highestFidelitySSRC===r.ssrc&&(t.send.video=n);break}this.streamSenderStarted.Video&&Wp(this.sessionInfo.activeModalities.video)&&a?.getLocalTrackId()&&(a?.getLocalTrackId()===r.googTrackId||this.configProvider.config.statsAllowAnyVideoSendTrack&&!t.send.video)&&(!r.rid||"1"===r.rid)&&(t.send.video=n);break;case Gi.MEDIA_TYPE.sharing:if(this.simulcastSharing.highestFidelitySSRC){this.simulcastSharing.highestFidelitySSRC===r.ssrc&&(t.send.sharing=n);break}this.streamSenderStarted.ScreenShare&&Wp(this.sessionInfo.activeModalities.sharing)&&a?.getLocalTrackId()===r.googTrackId&&(t.send.sharing=n);break;default:this.logger.warn(`Unknown media type '${o}'`)}else if(n.endsWith("recv"))switch(o){case Gi.MEDIA_TYPE.audio:Kp(this.sessionInfo.activeModalities.audio)&&(t.recv.audio=n);break;case Gi.MEDIA_TYPE.video:void 0!==l&&this.MSIDs.add(l),this.isSubscribed(r.googTrackId,r.ssrc)&&Kp(this.sessionInfo.activeModalities.video)&&(i.push(r),+r.googFrameRateReceived>0&&t.recvCounters[Gi.MODALITY.video]++);break;case Gi.MEDIA_TYPE.sharing:this.isSubscribed(r.googTrackId,r.ssrc)&&Kp(this.sessionInfo.activeModalities.sharing)&&(t.recv.sharing=n,+r.googFrameRateReceived>0&&t.recvCounters[Gi.MODALITY.sharing]++);break;default:this.logger.warn(`Unknown media type '${o}'`)}}if(i.length>0){i=i.sort(((e,t)=>+t.googFrameHeightReceived-+e.googFrameHeightReceived));const e=i.find((e=>e.mediaType===Gi.MEDIA_TYPE.video));e&&(t.recv.video=e.id),this.multiparty&&this.configProvider.config.enableMultiViewStats&&(t.multiRecv=i.map((e=>e.id)),t.multiRecv.forEach((e=>{this.multiViewVideoTelemetry[e]||(this.multiViewVideoTelemetry[e]=new oU(this.extensions.StartTime,this.configProvider,this.logger.createChild(`Video[${e}]`,"Video")),this.multiViewVideoTelemetry[e].setMsi(this.MSIDsPairs[e]?.msi),this.multiViewVideoTelemetry[e].setLocalMsi(this.MSIDsPairs[e]?.localMsi),this.multiViewVideoTelemetry[e].prepareCollectingStatsOnSubscribed(this.MSIDsPairs[e]?.msi))})))}return t}getMediaEntityForTrack(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getLocalTrackId()===e||t.getRemoteTrackId()===e))}getMediaEntityByRemoteSsrc(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getRemoteSsrc()===+e))}getMediaEntity(e,t){const i=`${t.ssrc}`,n=t.id;let r=this.getMediaEntityForTrack(e);return!r&&this.configProvider.config.subscribeToSsrcForVideo&&n.endsWith("recv")&&(r=this.getMediaEntityByRemoteSsrc(i)),r}calculateHwSilentState(){const e=this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<2*this.hwSilentDetectionDuration)return;let t=!0;for(let i=e.length-this.hwSilentDetectionDuration-1;i<e.length;i++)if(e[i]>this.hwSilentDetectionLevel){t=!1;break}this.hwSilent!==t&&(this.hwSilent=t,this.logger.safe.info(`HW silent changed to ${this.hwSilent}`))}calculateSpeakingState(){const e=this.newStatsApi&&this.configProvider.config.useAudioAnalyzer?this.extensions.Audio_send_RawInputVolume:this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<=this.speakingWhileMutedBadDuration)return;let t=!1;for(let i=e.length-this.speakingWhileMutedBadDuration;i<e.length;i++)if(e[i]>this.speakingWhileMutedDetectionLevel){t=!0;break}this.isSpeaking=t}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(e,t){const i=tt(t);this.logger.safe.error(`webrtcStatistics error [${e}]: ${i}`);const n=this.statsErrors.find((t=>t.error===i&&t.origin===e));n?n.count++:this.statsErrors.push({origin:e,error:i,count:1}),this.statsErrors.length>10&&this.statsErrors.splice(1)}getLastSampleInt(e){return"number"==typeof e?e:e&&parseInt(e[e.length-1])||0}getSsrcIdFromMultipleVideoStream(e){let t;const i=this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]||{};for(const n in i){const r=i[n];if(r&&r.googTrackId===e){t=n;break}}return t}};m([pU],mU.prototype,"onDeviceEvent",1),m([pU],mU.prototype,"onMaxCapabilitiesRequested",1),m([pU],mU.prototype,"onMaxCapabilitiesApplied",1),m([pU],mU.prototype,"addSubscriptionEvent",1),m([pU],mU.prototype,"processSimulcastStats",1),m([pU],mU.prototype,"processBandwidthStats",1),m([pU],mU.prototype,"processAudioStats",1),m([pU],mU.prototype,"processVideoStatsSend",1),m([pU],mU.prototype,"processVideoStatsRecv",1),m([pU],mU.prototype,"processSharingStats",1),m([pU],mU.prototype,"processStreamsCounters",1),m([pU],mU.prototype,"setMissedInitialPreferredResolution",1),m([pU],mU.prototype,"setPreferredResolution",1),m([pU],mU.prototype,"setIsRendering",1),m([pU],mU.prototype,"setMaxSessionBandwidth",1),m([pU],mU.prototype,"setStartTime",1),m([pU],mU.prototype,"calculateAverages",1),m([pU],mU.prototype,"addFilteredFields",1),m([pU],mU.prototype,"formatFields",1),m([pU],mU.prototype,"processSource",1),m([pU],mU.prototype,"getWebrtcReport",1),m([pU],mU.prototype,"constructWebRTCDataReport",1),m([pU],mU.prototype,"constructWebRtcReportForSingleStream",1),m([pU],mU.prototype,"constructWebRtcReportForMultipleStreams",1),m([pU],mU.prototype,"selectSsrcsToCollect",1),m([pU],mU.prototype,"calculateHwSilentState",1),m([pU],mU.prototype,"calculateSpeakingState",1),m([pU],mU.prototype,"calculateNetworkRecvQualityLevel",1),m([pU],mU.prototype,"calculateNetworkSendQualityLevel",1);var fU=class extends Vi{constructor(e,t,i,n){super(),this.logger=e,this.configProvider=t,this.mediaManager=i,this.window=Mp.window,this._sessionInfo=new PL,this.statisticsMapper=new FF,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.webRtcStatistics=new mU(this.logger.createChild("WebrtcStatistics"),this._sessionInfo,this.configProvider,i,n,this.useNewStatsApi)}setAudioDecoderStatsProvider(e){this.statisticsMapper?.setAudioDecoderStatsProvider(e)}setAudioEncoderCodecName(e){this.statisticsMapper?.setAudioEncoderCodecName(e)}get sessionInfo(){return this._sessionInfo}get isDisposed(){return null===this.pc&&0===this.interval}initialize(e){this.pc=e}startWaitingForStreamStart(e){this.webRtcStatistics.startWaitingForStreamStart(e)}onDeviceEvent(e){this.webRtcStatistics.onDeviceEvent(e)}onMaxCapabilitiesRequested(e){this.webRtcStatistics.onMaxCapabilitiesRequested(e)}onMaxCapabilitiesApplied(e){this.webRtcStatistics.onMaxCapabilitiesApplied(e)}onSendersChanged(e,t){this.webRtcStatistics.setStreamSenderStarted(e,t)}addSubscriptionEvent(e,t,i,n,r,s,a){this.webRtcStatistics.addSubscriptionEvent(e,t,i,n,r,s,a)}setSubscribedTrackIds(e){this.webRtcStatistics.setSubscribedTrackIds(e)}setSubscribedTrackSsrc(e){this.webRtcStatistics.setSubscribedTrackSsrc(e)}setPreferredResolution(e,t,i){this.webRtcStatistics.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.webRtcStatistics.setIsRendering(e,t,i)}setMaxSessionBandwidth(e){this.webRtcStatistics.setMaxSessionBandwidth(e)}setTerminated(){this.webRtcStatistics.setTerminated()}addIceCandidateError(e){this.webRtcStatistics.addIceCandidateError(e)}clearIceCandidateErrors(){this.webRtcStatistics.clearIceCandidateErrors()}updateSendStream(e,t){this.webRtcStatistics.updateSendStream(e,t)}getTimerTracker(e,t){return this.webRtcStatistics.getTimerTracker(e,t)}setH264AvailableProfiles(e){if(!e?.codecs)return;let t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=/profile-level-id=(.{6})/.exec(e.sdpFmtpLine);i?.[1]&&(t=t.concat(i[1]))}})),this.webRtcStatistics.addH264AvailableProfiles(t)}setSupportedH264Profiles(e,t){if(!e?.codecs&&!t?.codecs)return;const i=e=>{const t=[];return e.codecs?.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=/profile-level-id=(.{6})/.exec(e.sdpFmtpLine)?.[1];i&&!t.includes(i)&&t.push(i)}})),t},n=i(e),r=i(t);this.webRtcStatistics.setSupportedH264Profiles(n,r)}processRawReport(e){this.processStatsDict(this.statisticsMapper.build(e))}processLegacyReport(e){this.processStatsDict(function(e){const t={};return e.result().forEach((e=>{e.names().forEach((i=>{t[e.type]=t[e.type]||{},t[e.type][e.id]=t[e.type][e.id]||{},t[e.type][e.id][i]=e.stat(i)})),t[e.type][e.id].id=e.id})),t}(e))}getReport(e,t=!1){const i=this.webRtcStatistics.getReport(e,t);return this.addStreamInfoForE2ETests(i),i}dispose(){this.interval&&(this.window.clearInterval(this.interval),this.interval=0),this.pc=null}getLastStatistics(){return this.statistics}setTimeToFirstFrame(e,t,i){this.webRtcStatistics.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.webRtcStatistics.setFreezeDuration(e,t)}addVideoControlMessage(e=!1){this.webRtcStatistics.addVideoControlMessage(e)}setSsrcTrackPair(e,t){this.statisticsMapper.setSsrcTrackPair(e,t)}updateStatsWithLocalSsrcTrackInfo(){for(const e of this.mediaManager.getMediaEntities()){const t=e.getLocalSsrc();t&&this.statisticsMapper.setSsrcTrackPair(t,e.getLocalTrackId())}}addReportedReceiveBandwidth(e){this.webRtcStatistics.addReportedReceiveBandwidth(e)}addStreamInfoForE2ETests(e){const t=this._sessionInfo.negotiatedModalities;if(t&&!this.isDisposed)try{e.localStreams=this.getSendersReport(this.pc.getSenders(),{audio:Wp(t.audio),video:Wp(t.video)}),e.remoteStreams=this.getReceiversReport(this.pc.getReceivers(),{audio:Kp(t.audio),video:Kp(t.video)})}catch(e){this.logger.safe.warn(`addStreamInfoForE2ETests failed: ${tt(e)}`)}}getReceiversReport(e,t){const i=[];return e.forEach((e=>{const n={tracks:[]};i.push(n),e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}getSendersReport(e,t){const i=[],n={tracks:[]};return i.push(n),e.forEach((e=>{e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}processStatsDict(e){this.webRtcStatistics.processStatsDict(e);let t=0,i=0;const n=e.VideoBwe?.bweforvideo;n&&(t=Number(n.googAvailableReceiveBandwidth),i=Number(n.googAvailableSendBandwidth));const r=1e3*((this.configProvider.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(this.configProvider.config.audioBandwidthInKbps||0)),s=isNaN(t)?0:t,a=isNaN(i)?0:i,o={estimatedReceiveBandwidth:Math.min(s,r),estimatedSendBandwidth:Math.min(a,r),remoteVideoStreams:{},localVideoStreams:{},isSpeaking:this.webRtcStatistics.getSpeakingState(),audioHwSilent:this.webRtcStatistics.getAudioHwSilent(),networkSendLevel:this.webRtcStatistics.getNetworkSendLevel(),networkRecvLevel:this.webRtcStatistics.getNetworkRecvLevel()};qi(e.ssrc,(e=>{if("video"!==e.mediaType)return;const t=e.googTrackId,i=e.id;-1!==i.indexOf("_recv")?(o.remoteVideoStreams[t]={trackId:t,frameRateReceived:Number(e.googFrameRateReceived),frameRateDecoded:Number(e.googFrameRateDecoded),framesDecoded:Number(e.framesDecoded)},this.configProvider.config.isRenderingBasedOnRawStatistics||(o.remoteVideoStreams[t].isRendering=this.webRtcStatistics.getIsRendering(i))):t&&-1!==i.indexOf("_send")&&(o.localVideoStreams[t]={trackId:t,ssrc:Number(e.ssrc),frameRateInput:Number(e.googFrameRateInput)})})),an(this.statistics,o)||(this.statistics=o,this.notifyStatisticsChanged())}notifyStatisticsChanged(){this.event("onStatisticsChanged").raise(this.statistics)}},vU=class extends Vi{constructor(e,t,i,n,r){super(),this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.window=Mp.window,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.loopIntervalTracker=new XM(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.loopIntervalAggregator=new eD,this.fetchTimeTracker=new XM(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.fetchTimeAggregator=new eD,this.gathererV1=new fU(this.logger.createChild("V1"),this.configProvider,this.mediaManager,r),this.gathererV1.on("onStatisticsChanged",(e=>this.event("onStatisticsChanged").raise(e))),this.useNewStatsApi&&t.config.diagnostics.sideBySide&&(this.gathererV2=new wF(this.logger.createChild("V2"),this.configProvider,this.diagnostics,this.mediaManager))}initialize(e){this.pc=e,this.gathererV1.initialize(e),this.interval??(this.interval=this.window.setInterval((()=>this.processStats()),this.configProvider.config.webrtcStatPollInterval))}setAudioDecoderStatsProvider(e){this.gathererV1.setAudioDecoderStatsProvider(e),this.gathererV2?.setAudioDecoderStatsProvider(e)}setAudioEncoderCodecName(e){this.gathererV1.setAudioEncoderCodecName(e),this.gathererV2?.setAudioEncoderCodecName(e)}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 e=_n(),t=void 0===this.loopTimer?-1:e-this.loopTimer;this.loopTimer=e,this.loopIntervalTracker.captureSample(t),this.loopIntervalAggregator.captureSample(this.loopIntervalTracker.getReport());const i=this.loopIntervalAggregator.getReport();i&&(this.diagnostics.loopIntervalMax=i.max,this.diagnostics.loopIntervalMedian=i.median);const n={};(await this.pc.getStats()).forEach((e=>{this.cleanupPii(e);const t=e.type;delete e.type,n[t]??(n[t]={}),n[t][e.id]=e}));const r=_n()-e;this.fetchTimeTracker.captureSample(r),this.fetchTimeAggregator.captureSample(this.fetchTimeTracker.getReport());const s=this.fetchTimeAggregator.getReport();s&&(this.diagnostics.fetchTimeMax=s.max,this.diagnostics.fetchTimeMedian=s.median);const a=this.gathererV2?.processRawReport(n);let o=_n();this.gathererV1.processRawReport(n),o=_n()-o,a&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Raising onDiagnosticUpdated event"),this.event("onDiagnosticUpdated").raise(a)),a?.perfCounters&&(a.perfCounters.loopTime=t,a.perfCounters.fetchTime=r,a.perfCounters.legacyProcessingTime=o)}else this.pc.getStats((e=>{e.result&&this.gathererV1.processLegacyReport(e)}))}cleanupPii(e){switch(e.type){case"local-candidate":case"remote-candidate":{const t=e;Object.defineProperty(t,"address",{enumerable:!1}),Object.defineProperty(t,"url",{enumerable:!1}),Object.defineProperty(t,"relatedAddress",{enumerable:!1}),Object.defineProperty(t,"ip",{enumerable:!1}),Object.defineProperty(t,"usernameFragment",{enumerable:!1});break}case"certificate":{const t=e;Object.defineProperty(t,"fingerprint",{enumerable:!1}),Object.defineProperty(t,"base64Certificate",{enumerable:!1});break}}}get sessionInfo(){return this.gathererV1.sessionInfo}onMaxCapabilitiesApplied(e){this.gathererV1.onMaxCapabilitiesApplied(e)}clearIceCandidateErrors(){this.gathererV1.clearIceCandidateErrors()}setSsrcTrackPair(e,t){this.gathererV1.setSsrcTrackPair(e,t),this.gathererV2?.setSsrcTrackPair(e,t)}addSubscriptionEvent(e,t,i,n,r,s,a){this.gathererV1.addSubscriptionEvent(e,t,i,n,r,s,a)}setSubscribedTrackSsrc(e){this.gathererV1.setSubscribedTrackSsrc(e)}addIceCandidateError(e){this.gathererV1.addIceCandidateError(e)}setH264AvailableProfiles(e){this.gathererV1.setH264AvailableProfiles(e)}setSupportedH264Profiles(e,t){this.gathererV1.setSupportedH264Profiles(e,t)}setTerminated(){this.gathererV1.setTerminated()}onDeviceEvent(e){this.gathererV1.onDeviceEvent(e)}getReport(e,t=!1){const i=this.gathererV1.getReport(e,t);if(this.gathererV2&&this.configProvider.config.diagnostics.sideBySide){const e=this.loopIntervalAggregator.getReport();e&&(i.data.Extensions.LoopIntervalMax=`${mn(e.max,1)}`,i.data.Extensions.LoopIntervalMedian=`${mn(e.median,1)}`);const t=this.fetchTimeAggregator.getReport();t&&(i.data.Extensions.FetchTimeMax=`${mn(t.max,1)}`,i.data.Extensions.FetchTimeMedian=`${mn(t.median,1)}`);const n=this.diagnostics.getObjectRef();i.data.Extensions.multipleVideoStreams=JSON.stringify(wn(n.multiViewStats,"startTime",n.startTime)),i.data.Extensions.OvcToSubscriptions=JSON.stringify(n.ovcToSubscriptionEvents),i.data.Extensions.videoPerformanceEvent=JSON.stringify(n.videoPerformanceEvent);const r=n.bandwidthReport;"REMB"===n.negotiation.bweType?(i.data.Extensions.StartCallBWE=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWE=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStd=JSON.stringify(r?.std),i.data.Extensions.BwPercentiles=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwe=JSON.stringify(r?.avgBwe)):(i.data.Extensions.StartCallBWESendSide=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWESendSide=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStdSendSide=JSON.stringify(r?.std),i.data.Extensions.BwPercentilesSendSide=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwSendSide=JSON.stringify(r?.avgBwe)),i.data.Extensions.InitialBWSeed=JSON.stringify(n.initialBWSeed),i.data.Extensions.SentBWSeed=JSON.stringify(n.sentBWSeed),i.data.Extensions.Bandwidth_downlinkStabilizationTime=JSON.stringify(n.bwDownlinkStabilizationTime),i.data.Extensions.ReinvitelessContext=JSON.stringify(n.reinvitelessContext),i.data.Extensions.ReportedSendBandwidth=JSON.stringify(n.reportedSendBandwidthLayouts),i.data.Extensions.Data_ProtocolCounters=JSON.stringify(n.dataChannel?.protocolCounters),i.data.Extensions.Data_Error=n.dataChannel?.error,i.data.Extensions.Data_SessionState=n.dataChannelSessionState?.toString(),i.data.Extensions.Data_CreateChannelError=n.dataChannelCreationError;const s=n.aggregatedModalityStats?.video?.recv||[],a=n.aggregatedModalityStats?.audio?.recv||[],o=n.aggregatedModalityStats?.sharing?.recv||[],l=n.aggregatedModalityStats?.video?.send||[],c=n.aggregatedModalityStats?.sharing?.send||[],d=i.data.Extensions.WebRTCStats,u=s[s.length-1],h=o[o.length-1],g=a[a.length-1],p=l[l.length-1],m=c[c.length-1],f=u?.aggregated?.macroblockRateStats??{},v=g?.aggregated?.customHealerStats??{};if(v?.pullPacketProcessingTimes){const e=kn(v.pullPacketProcessingTimes);v.pullPacketProcessingTimeP50=e.getPercentile(.5),v.pullPacketProcessingTimeP95=e.getPercentile(.95)}if(v?.pushPacketProcessingTimes){const e=kn(v.pushPacketProcessingTimes);v.pushPacketProcessingTimeP50=e.getPercentile(.5),v.pushPacketProcessingTimeP95=e.getPercentile(.95)}for(const e in f)i.data.Extensions[`Video_recv_${e}`]=`${mn(f[e],0)}`;for(const e in n.totalVideoRecvMblocksRates)i.data.Extensions[`totalVideoRecv_${e}`]=`${mn(n.totalVideoRecvMblocksRates[e],0)}`;for(const e in v)if(void 0!==v[e]){const t="number"!=typeof v[e]?JSON.stringify(v[e]):v[e];i.data.Extensions[`Audio_recv_customHealer_${e}`]=t}i.data.Extensions.MeetingScenario=JSON.stringify(n.negotiation.meetingScenario),i.data.Extensions.IsTownHall=JSON.stringify(n.negotiation.isTownHall),i.data.Extensions.Audio_send_presentationAPIUserDuration=JSON.stringify(n.presentationAPIUserDuration),i.data.Extensions.Audio_send_presentationDuration=JSON.stringify(n.presentationAudioDuration),i.data.Extensions.CodecSupport=JSON.stringify(n.codecSupport),i.data.Extensions.Video_recv_FpsHarmonicAverage=u?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_FpsHarmonicAverage=h?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_CodecReport=JSON.stringify(h?.aggregated?.codecReport),i.data.Extensions.Video_send_performanceEvents=JSON.stringify(vn(wn(n.localVideoPerformanceEvents,"timestamp",n.startTime),this.configProvider.config.diagnostics.telemetryLimits.numPerformanceEvents)),d?.ssrc_sharing_send&&((d?.ssrc_sharing_send).retransmittedPacketsSent=Pn(n.aggregatedModalityStats?.sharing?.send,(e=>e.outboundRTP.retransmittedPacketsSent))),this.configProvider.config.diagnostics.features.takeFreezeTelemetryFromGathererV2&&(s.length&&(i.data.Extensions.Video_recv_FreezeHistogram=JSON.stringify(u.aggregated?.freezeCountHistogram),i.data.Extensions.Video_recv_LongestFreezeDuration=JSON.stringify(u?.aggregated?.longestFreeze),i.data.Extensions.Video_recv_OngoingFreeze=JSON.stringify(u?.extensions?.isFrozen),i.data.Extensions.Video_recv_OngoingFreezeDuration=JSON.stringify(u?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Video_recv_TotalFreezeDuration=JSON.stringify(u?.aggregated?.totalFreezeDuration),i.data.Extensions.Video_recv_RecvAvgFreezeDuration=JSON.stringify(u?.aggregated?.avgFreezeDuration),i.data.Extensions.Video_recv_FreezeTimestamps=JSON.stringify(An(u?.aggregated?.freezeTimestampsHistogram,n.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples))),o.length&&(i.data.Extensions.Sharing_recv_FreezeHistogram=JSON.stringify(h.aggregated?.freezeCountHistogram),i.data.Extensions.Sharing_recv_LongestFreezeDuration=JSON.stringify(h?.aggregated?.longestFreeze),i.data.Extensions.Sharing_recv_OngoingFreeze=JSON.stringify(h?.extensions?.isFrozen),i.data.Extensions.Sharing_recv_OngoingFreezeDuration=JSON.stringify(h?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Sharing_recv_TotalFreezeDuration=JSON.stringify(h?.aggregated?.totalFreezeDuration),i.data.Extensions.Sharing_recv_RecvAvgFreezeDuration=JSON.stringify(h?.aggregated?.avgFreezeDuration),i.data.Extensions.Sharing_recv_FreezeTimestamps=JSON.stringify(An(h?.aggregated?.freezeTimestampsHistogram,n.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples)))),i.data.Extensions.EarlyMedia={NumStatsPolls:`${n.earlyMediaNumStatsPolls}`},i.data.Extensions.Audio_recv_packetsLostRateMax=`${mn(g?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Audio_recv_networkAvgLossRate=`${mn(g?.aggregated?.networkAvgLossRate,6)||0}`,i.data.Extensions.Video_recv_packetsLostRateMax=`${mn(u?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Sharing_recv_packetsLostRateMax=`${mn(h?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Video_send_packetsLostRateMax=`${mn(p?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Sharing_send_packetsLostRateMax=`${mn(m?.aggregated?.lossRateMax,6)||0}`,this.configProvider.config.diagnostics.features.useNewSimulcastTelemetryExtension&&(i.data.Extensions.Video_send_Simulcast=JSON.stringify(n.simulcast?.video),i.data.Extensions.Sharing_send_Simulcast=JSON.stringify(n.simulcast?.sharing)),i.data.Extensions.Video_send_powerEfficientEncoderEvents=xn(p?.extensions?.powerEfficientEncoderEvents,this.configProvider.config.diagnostics.telemetryLimits.numPowerEfficientEncoderEvents,"timestamp",n.startTime),i.data.Extensions.Video_send_powerEfficientEncoderEventOnCount=JSON.stringify(p?.extensions?.powerEfficientEncoderEventOnCount),i.data.Extensions.Video_send_powerEfficientEncoderEventOffCount=JSON.stringify(p?.extensions?.powerEfficientEncoderEventOffCount)}return rn(i)}startWaitingForStreamStart(e){this.gathererV1.startWaitingForStreamStart(e)}getTimerTracker(e,t){return this.gathererV1.getTimerTracker(e,t)}getLastStatistics(){return this.gathererV1.getLastStatistics()}updateSendStream(e,t){this.gathererV1.updateSendStream(e,t)}setSubscribedTrackIds(e){this.gathererV1.setSubscribedTrackIds(e)}setMaxSessionBandwidth(e){this.gathererV1.setMaxSessionBandwidth(e)}updateStatsWithLocalSsrcTrackInfo(){this.gathererV1.updateStatsWithLocalSsrcTrackInfo()}onSendersChanged(e,t){this.gathererV1.onSendersChanged(e,t)}setPreferredResolution(e,t,i){this.gathererV1.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.gathererV1.setIsRendering(e,t,i)}setTimeToFirstFrame(e,t,i){this.gathererV1.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.gathererV1.setFreezeDuration(e,t)}addVideoControlMessage(e){this.gathererV1.addVideoControlMessage(e)}onMaxCapabilitiesRequested(e){this.gathererV1.onMaxCapabilitiesRequested(e)}addReportedReceiveBandwidth(e){this.gathererV1.addReportedReceiveBandwidth(e)}},SU=101,yU=[48e3,32e3,24e3,16e3,12e3],CU=class{constructor(e){this.context=e,this.cname=sn(),this.dataMedia={type:Gi.MEDIA_TYPE.data,protocol:Gi.PROFILES.rtpSavp,port:0},this.configProvider=e.configProvider,this.logger=e.getLogger().createChild("WebkitSdpTrans")}fixTelephoneEvent(e){let t;return yU.forEach((t=>{_O(e,{codec:"telephone-event",rate:t})})),yO(e,SU,999),TO(e,{codec:"telephone-event",rate:8e3},(e=>(t=e.rtp.payload,e.rtp.payload=SU,e))),yO(e,999,t||SU),t}toLocal(e,t,i){const n=t.isEmpty(),r=nn(e);let s;return r.media.forEach((e=>{if("audio"===e.type)n&&(s=this.fixTelephoneEvent(e)),EU(e);else{s&&yO(e,SU,s);const i=t.getLocalSsrcs().get(MO(e));this.enforceFixedSsrc(e,i)}const r=fm(this.configProvider,e.type);"offer"===i&&wU(e,r,n,this.logger)})),new JN(this.configProvider).modify(r),delete r.extmapAllowMixed,r}toOffer(e,t,i){return this.fromNative(e,t,i,!0)}toAnswer(e,t,i){return this.fromNative(e,t,i,!1)}toRemote(e,t,i,n){const r=nn(e);let s,a,o=this.configProvider.mediaConfig.maxBandwidthInKbps;r.bandwidth&&(!o||o>+e.bandwidth[0].limit)&&(o=+e.bandwidth[0].limit),r.media.forEach(((e,i)=>{t.getMediaEntity(i).isDisabled()&&e.type!==Gi.MEDIA_TYPE.audio&&(e.port=0)}));let l=function(e){return e.groups?e.groups.find((e=>"BUNDLE"===e.type)):null}(r);if(!l){let e=!1;r.media.forEach(((i,n)=>{const r=t.getMediaEntity(n);!e&&r.isEnabled()?(i.mid=r.getMid(),e=!0):(r.disable(),i.port=0)})),e&&(r.groups||(r.groups=[]),l={type:"BUNDLE"},r.groups.push(l))}r.media.forEach((e=>{const t=MO(e);i[t]===Gi.MEDIA_STATE.send&&(e.direction&&e.direction.toLowerCase()===Gi.MEDIA_STATE.receive||(e.direction=Gi.MEDIA_STATE.receive))}));const c=r.media.filter((e=>e.type===Gi.MEDIA_TYPE.video));if(c.length>0){const e=c.filter((e=>0!==e.port));if(e.length>0){a=nn(e[0]),a.bandwidth&&delete a.bandwidth;const t=this.configProvider.config.audioBandwidthInKbps?this.configProvider.config.audioBandwidthInKbps:0;o&&o-t>0&&(a.bandwidth=[{limit:o-t,type:"AS"}]),a.mid="video",a.direction=null,delete a.label,a.ssrcs=[],a.ssrcGroups=[],delete a.msid,e.forEach((e=>{e.ssrcs&&(a.ssrcs=a.ssrcs.concat(e.ssrcs)),e.ssrcGroups&&(a.ssrcGroups=a.ssrcGroups.concat(e.ssrcGroups)),a.direction=function(e,t){return e===Gi.MEDIA_STATE.sendReceive||t===Gi.MEDIA_STATE.sendReceive?Gi.MEDIA_STATE.sendReceive:e===t?e:e&&t&&e!==t?Gi.MEDIA_STATE.sendReceive:e||t}(a.direction,e.direction||Gi.MEDIA_STATE.sendReceive)})),TU(a)}else a=_U(Gi.MEDIA_TYPE.video,void 0,c[0].protocol,c[0].payloads)}const d=r.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(d)if(0!==d.port)s=nn(d),s.mid="audio",delete s.label,function(e){_O(e,{codec:"g722",rate:8e3,encoding:2})}(s),EU(s),TU(s);else{s=_U(Gi.MEDIA_TYPE.audio,void 0,d.protocol,d.payloads);const e=r.media.find((e=>!!e.iceUfrag));e&&(s.port=9,s.direction="inactive",s.mid="audio",s.iceUfrag=e.iceUfrag,s.icePwd=e.icePwd,s.rtcpMux="rtcp-mux",e.crypto&&(s.crypto=e.crypto),e.fingerprint&&(s.fingerprint=e.fingerprint,s.setup=e.setup),s.rtp=[{payload:0,codec:"PCMU",rate:8e3}],s.payloads="0")}r.media.forEach(((e,t)=>{e.type===Gi.MEDIA_TYPE.data&&(e.type=Gi.MEDIA_TYPE.dataChannel,e.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL,e.protocol=Gi.PROFILES.udpDtlsSctp,e.mid="data",delete e.xDataProtocol,delete e.direction,NO(e)&&(r.media[t]=_U(e.type,void 0,e.protocol,e.payloads)))}));const u=mm(this.context)?r.media.find((e=>e.type===Gi.MEDIA_TYPE.dataChannel)):null;r.media=[s,a,u].filter((e=>e)),t.getMediaEntities()[0].getModality()!==Gi.MODALITY.audio&&r.media.reverse();const h=gm(this.context.configProvider,this.context.config.isPstnCall),g=im(e);return r.media.forEach((e=>{e.type!==Gi.MEDIA_TYPE.dataChannel&&(!h&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!g.dtls||g.sdes&&h?Gi.PROFILES.rtpSavpf:Gi.PROFILES.udpTlsRtpSavpf)})),"offer"===n&&(wU(s,this.configProvider.config.allowedAudioCodecs,!1,this.logger),wU(a,this.configProvider.config.allowedVideoCodecs,!1,this.logger)),bU(r,this.configProvider.mediaConfig.isTransportUnbundled),r}splitMedia(e,t,i,n,r){const s=e.getMid(),a=e.getModality(),o=nn(t);if(o.label=DO(a),o.direction=n,o.mid=s,o.ssrcs=[],o.ssrcGroups=[],e.getModality()===Gi.MODALITY.data)return o.type=Gi.MEDIA_TYPE.data,o.payloads=Gi.PAYLOAD_TYPE.X_DATA,o;const l=i.filter((e=>e.modality===a));if(l&&l.length){const e=[];t.ssrcs&&(l.forEach((i=>{const n=t.ssrcs.filter((e=>"msid"===e.attribute&&i.trackId===IU(e.value))).map((e=>e.id));e.push(...n)})),o.ssrcs=t.ssrcs.filter((t=>e.indexOf(+t.id)>-1)),o.ssrcs.forEach((e=>{"cname"===e.attribute&&(e.value=this.cname)}))),t.ssrcGroups&&(o.ssrcGroups=t.ssrcGroups.filter((t=>t.ssrcs.split(" ").find((t=>e.indexOf(+t)>-1)))))}else{if(n===Gi.MEDIA_STATE.send||n===Gi.MEDIA_STATE.sendReceive)return _U(t.type,DO(a),t.protocol,t.payloads);n!==Gi.MEDIA_STATE.receive&&n!==Gi.MEDIA_STATE.inactive||(r[t.type].ssrcs?.[0]?o.ssrcs=[{id:r[t.type].ssrcs[0].id,attribute:"cname",value:this.cname}]:t.type===Gi.MEDIA_TYPE.audio?o.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:t.type===Gi.MEDIA_TYPE.video&&(o.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}return o}fromNative(e,t,i,n){const r=nn(e),s=this.configProvider.mediaConfig.maxBandwidthInKbps;s&&(r.bandwidth=[{limit:s,type:"CT"}]),new YN(this.configProvider).modify(r);const a=r.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),o=r.media.find((e=>e.type===Gi.MEDIA_TYPE.video)),l=r.media.find((e=>e.type===Gi.MEDIA_TYPE.dataChannel)),c={};c[Gi.MODALITY.audio]=a,c[Gi.MODALITY.video]=o,c[Gi.MODALITY.sharing]=o,c[Gi.MODALITY.data]=l||this.dataMedia;const d={};d[Gi.MEDIA_TYPE.audio]=a,d[Gi.MEDIA_TYPE.video]=o,d[Gi.MEDIA_TYPE.data]=l||this.dataMedia;const u={};return u[Gi.MODALITY.audio]=t.getMediaEntitiesByModality(Gi.MODALITY.audio)[0],u[Gi.MODALITY.video]=t.getMediaEntitiesByModality(Gi.MODALITY.video)[0],u[Gi.MODALITY.sharing]=t.getMediaEntitiesByModality(Gi.MODALITY.sharing)[0],u[Gi.MODALITY.data]=t.getMediaEntitiesByModality(Gi.MODALITY.data)[0],r.media=[],t.getMediaEntities().forEach((e=>{let s,a=i[e.getModality()];!e.isEnabled()||0===c[e.getModality()].port||e!==u[e.getModality()]&&a===Gi.MEDIA_STATE.send?(s=_U(e.getType(),DO(e.getModality()),c[e.getModality()].protocol,c[e.getModality()].payloads),c[e.getModality()].payloads===Gi.PAYLOAD_TYPE.DATA_CHANNEL&&(s.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL)):(a!==Gi.MEDIA_STATE.inactive&&e!==u[e.getModality()]&&(a=Gi.MEDIA_STATE.receive),s=this.splitMedia(e,c[e.getModality()],t.getLocalTracksInfo(),a,d),e!==u[e.getModality()]&&(s.candidates=[]));const o=c[e.getModality()].setup;o&&("actpass"!==o?e.setExtension("setup",o):n&&void 0!==e.getExtension("setup")&&(s.setup="actpass"!==e.getExtension("setup")?e.getExtension("setup"):o));const l=c[e.getModality()].iceUfrag,h=e.getExtension("iceUfrag");e.setExtension("iceRestart",!!l&&!!h&&h!==l),e.setExtension("iceUfrag",l),NO(s)&&e.disable(),r.media.push(s)})),new hN(this.context,i.data).modify(r),bU(r,this.configProvider.mediaConfig.isTransportUnbundled),r}enforceFixedSsrc(e,t){let i=-1;if(!e.ssrcs)return;const n=[];if(e.ssrcs.forEach((e=>{"msid"===e.attribute&&n.push({ssrc:e.id,trackId:IU(e.value)})})),e.ssrcs.forEach((e=>{"cname"===e.attribute&&i++,t&&(e.id=this.getVideoSSRC(i,t))})),e.ssrcGroups){const t=e.ssrcs.filter((e=>"cname"===e.attribute)).map((e=>e.id));e.ssrcGroups.forEach(((e,i)=>{e.ssrcs=[t[2*i],t[2*i+1]].join(" ")}))}}getVideoSSRC(e,t){return e%2==1?t+50:t}};function TU(e){const t=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"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}function EU(e){_O(e,{codec:"CN",rate:16e3})}function bU(e,t){const i=e.groups?.findIndex((e=>"BUNDLE"===e.type)),n=e.groups?e.groups[i]:void 0;n&&(t?(n.mids=e.media.filter((e=>e.type===Gi.MEDIA_TYPE.video)).map((e=>e.mid)).filter((e=>e)).join(" "),n.mids||delete e.groups[i]):n.mids=e.media.map((e=>e.mid)).filter((e=>e)).join(" "))}function _U(e,t,i,n){return{type:e,port:0,label:t,payloads:n,protocol:i}}function IU(e){return e.split(" ")[1]}function wU(e,t,i,n){t.length&&e?.port&&PO(e,vm(t),i,n)}var AU=p(ye()),PU=class{getCapabilities(e){const t=RTCRtpReceiver.getCapabilities(e);return t.codecs.forEach((e=>{e.mimeType=e.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(t)}},RU=class{getCapabilities(e){const t=RTCRtpSender.getCapabilities(e);return t.codecs.forEach((e=>{e.mimeType=e.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(t)}},MU=class{constructor(e,t){this.noRequiredCodecsWorkaround=t,this.selfGlobal=e.global.capabilityGatherer=e.global.capabilityGatherer||{},this.getCapabilities("video")}async getCapabilities(e){if("video"!==e&&"audio"!==e)return Promise.reject(new Error(`capabilities for ${e} are not supported`));if(!this.selfGlobal.gatherTask){const e=new Kt;this.selfGlobal.gatherTask=e.promise;const t=void 0!==Mp.window.webkitRTCPeerConnection,i=t?new Mp.window.webkitRTCPeerConnection(null):new Mp.window.RTCPeerConnection(null),n=e=>t?new Promise(((t,n)=>{i.createOffer(t,n,e)})):(this.noRequiredCodecsWorkaround&&i.addTrack(i.addTransceiver("video").receiver.track),i.createOffer(e));try{const t=await n({offerToReceiveVideo:1,offerToReceiveAudio:1}),r={};AU.parse(t.sdp).media.forEach((e=>{r[e.type]=e.rtp.map((t=>{const i={mimeType:t.codec.toLowerCase()};if("video"===e.type){const n=e.fmtp?.find((e=>e.payload===t.payload));i.sdpFmtpLine=n?.config}return i}))})),i.close(),e.resolve(r)}catch(t){this.selfGlobal.gatherTask=null,i.close(),e.reject(t)}}return this.selfGlobal.gatherTask.then((t=>({codecs:t[e]})))}},DU=(e,t,i=!1,n=!1)=>n?new RU:!t&&Vp.hasCapabilitiesApi()?new PU:new MU(e,i),kU=p(ye()),OU="rollback";function NU(){const e=[].slice.apply(arguments);let t=e[0]&&LU(e[0].type);e.splice(0,t?1:0,null);const i=new(Function.prototype.bind.apply(Mp.window.RTCSessionDescription,e)),n=Object.getOwnPropertyDescriptor(Mp.window.RTCSessionDescription.prototype,"type");return Object.defineProperty(i,"type",{get:()=>t?OU:n.get.call(i),set(e){t=LU(e),t||n.set.call(i,e)}}),i}function LU(e){return OU===e}var xU=()=>NU,FU=[{codec:"telephone-event",rate:8e3},{codec:"cn",rate:16e3}];function UU(e){const t=[],i=xU(),n=[].slice.apply(arguments);n.splice(0,1,null),function(e){n[1]?.[e]&&(n[1].iceTransports=n[1][e])}("iceTransportPolicy");const r=new(Function.prototype.bind.apply(Mp.window.webkitRTCPeerConnection,n));function s(e,t){let i;Object.defineProperty(this,"dtmf",{get:()=>"audio"===e.kind?(i=i||r.createDTMFSender(e),i):null}),this.track=e,this._stream=t}return[{name:"createOffer",reverseArgs:!0},"createAnswer","setRemoteDescription","setLocalDescription"].forEach((function(e){const t=e.name||e,i=r[t];r[t]=function(){const t=arguments;return new Promise((function(n,s){const a=[n,s];t.length>0&&a.splice(e.reverseArgs?a.length:0,0,t[0]),i.apply(r,a)}))}})),function(){["createOffer","createAnswer","setLocalDescription"].forEach((function(t){const i=r[t];r[t]=function(){const t=arguments;return e.getCapabilities("video").then((function(){return i.apply(i,t)}))}}));const t=r.setRemoteDescription;r.setRemoteDescription=function(i){return e.getCapabilities("video").then((function(e){const n=e.codecs,r=kU.parse(i.sdp);return r.media.forEach((function(e){if("video"===e.type&&(e.rtp.some((function(e){return n.some((function(t){return e.codec.toLowerCase()===t.mimeType}))}))?function(e){TO(e,{codec:"h264",rate:9e4},(function(e){if(e.fmtp){const t=new SO,i=new SO(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((function(e){if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n="42C02A"),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}(e):e.port=0),!function(e){return"RTP/SAVPF"!==e.protocol}(e)){const t=OO(r);t?e.crypto=t.crypto:e.port||r.media.some((function(t){return!!t.port&&(e.crypto=t.crypto,!0)}))}})),i.sdp=kU.write(r),t(i)}))}}(),function(){const e=r.createAnswer;r.createAnswer=function(){const t=arguments;return e.apply(r,t).then((function(e){if(!r.localDescription?.sdp)return e;const t=kU.parse(r.localDescription.sdp),n=[];if(t.media.forEach((function(e){FU.forEach((function(t){TO(e,t,(function(e){n.push(e)}))}))})),n.length){const t=kU.parse(e.sdp);let r=!1;t.media.forEach((function(e){n.forEach((function(t){TO(e,{codec:t.rtp.codec,rate:t.rtp.rate},(function(e){e.rtp.payload!==t.rtp.payload&&(e.rtp.payload=t.rtp.payload,r=!0)}))}))})),r&&(e=new i({type:e.type,sdp:kU.write(t)}))}return e}))}}(),function(){const e=r.createOffer;r.createOffer=function(t){const i=arguments;return t&&t.offerToReceiveVideo>1&&(t.offerToReceiveVideo=1),e.apply(r,i)}}(),r.getSenders&&r.addTrack&&r.removeTrack||(r.getSenders=function(){return t.slice()},r.addTrack=function(e,i){if(!e||!i)throw new Error("both media track and stream need to be provided");r.getLocalStreams().some((function(e){return e.id===i.id}))||r.addStream(i);let n=t.find((function(t){return t.track.id===e.id}));return n||(n=new s(e,i),t.push(n)),n},r.removeTrack=function(e){r.getLocalStreams().filter((function(t){return t.id===e._stream.id})).forEach((function(e){r.removeStream(e)})),Qi(t,(t=>t===e))}),r}var BU=e=>UU.bind(null,e),VU=class{constructor(e){const t=e.configProvider.config.useSdpCapabilitiesLegacySession,i=e.configProvider.config.noRequiredCodecsWorkaround;this.RTCRtpReceiver=DU(e,t,i),this.SdpTransform=CU,this.RTCPeerConnection=BU(this.RTCRtpReceiver),this.RTCSessionDescription=xU()}};function HU(){function e(){throw new Error("unsupported platform")}this.SdpTransform=e,this.RTCPeerConnection=e,this.RTCSessionDescription=e,this.RTCRtpReceiver=e,this.RTCRtpSender=e}var $U=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.activeSpeakerManager=i,this.contributingSourcesProvider=n,this.lastSources=[],this.emptySourcesCount=0,this.poll=()=>{const e=this.contributingSourcesProvider?.getContributingSources();if(!e)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(e.filter((e=>{const t=this.lastSources.find((t=>t.source===e.source));return!t||t.timestamp!==e.timestamp})).map((e=>e.source))),this.updateLastSources(e),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(e){e?this.stopPolling():this.startPolling()}updateContributingSources(e){this.activeSpeakerManager.onContributingSourcesChanged(e)}startPolling(e=this.configProvider.config.webrtcContributingSourcesPollingInterval){!this.timer&&this.contributingSourcesProvider&&(this.logger.safe.info("Polling started"),this.timer=window.setTimeout(this.poll,e))}stopPolling(){this.timer&&(this.logger.safe.info("Polling stopped"),window.clearTimeout(this.timer),this.timer=void 0)}updateLastSources(e){this.lastSources=e.map((e=>({source:e.source,timestamp:e.timestamp})))}},jU=class{constructor(e,t,i,n){this.logger=e,this.peerConnection=t,this.logDiagnosticsError=i,this.sessionDiagnostics=n}getContributingSources(){try{if(!this.peerConnection?.getReceivers)return;const e=this.peerConnection.getReceivers().find((e=>"audio"===e.track.kind));return e?e.getContributingSources?.():[]}catch(e){return this.logger.safe.error("Failed to get contributing sources",e),void(this.logDiagnosticsError&&this.sessionDiagnostics&&(this.sessionDiagnostics.contributingSourcesError=`${e}`))}}},GU=class{constructor(e){this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.localSsrcs=new Map,this.ssrcGenerator=new WO,this.logger=e.logger.createChild("MM"),this.configProvider=e.configProvider,this.numVideoChannels=e.numVideoChannels}fromOffer(e,t){e.media.forEach((e=>{if(e.type===Gi.MEDIA_TYPE.audio)Gi.MODALITY.audio in t&&this.addMediaEntity(Gi.MODALITY.audio);else if(e.type===Gi.MEDIA_TYPE.video){if(Gi.MODALITY.video in t)for(let e=0;e<this.numVideoChannels;e++)this.addMediaEntity(Gi.MODALITY.video);Gi.MODALITY.sharing in t&&this.addMediaEntity(Gi.MODALITY.sharing)}else e.type===Gi.MEDIA_TYPE.data&&Gi.MODALITY.data in t&&this.addMediaEntity(Gi.MODALITY.data)}))}fromRemote(e,t){e.media.forEach(((e,i)=>{const n=MO(e);if(NO(e)||!(n in t))this.mediaEntities[i]?this.mediaEntities[i].disable():this.addDisabledMediaEntity(n),this.mediaEntities[i].setRemoteStreamId(null),this.mediaEntities[i].setRemoteTrackId(null);else{if(this.mediaEntities[i]?this.mediaEntities[i].update(n,e.mid||this.generateMid(i)):this.addMediaEntity(n,e.mid||this.generateMid(i)),e.msid)this.mediaEntities[i].setRemoteStreamId(e.msid.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(e.msid.split(" ")[1]);else if(e.ssrcs){const t=e.ssrcs.find((e=>"msid"===e.attribute));t?(this.mediaEntities[i].setRemoteStreamId(t.value.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(t.value.split(" ")[1])):this.logger.safe.warn(`No ssrc msid for media of type ${e.type} with mid ${e.mid}`)}const t=e.xSourceStreamId||this.generateSourceStreamId(i);this.mediaEntities[i].setXSourceStreamId(t)}}))}isEmpty(){return 0===this.mediaEntities.length}addMediaEntity(e,t){this.createMediaEntity(e,t||this.generateMid(this.mediaEntities.length))}addDisabledMediaEntity(e){this.createMediaEntity(e)}getMediaEntities(){return this.mediaEntities}createMediaEntity(e,t){const i=XO.create(this.configProvider,e,t);return this.mediaEntities.push(i),i}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[]}syncModalities(e,t,i){this.disableModalities(t),i||(this.enableModalities(t),this.addModalities(t))}enableModalities(e){this.mediaEntities.forEach(((t,i)=>{t.getModality()in e&&t.isDisabled()&&t.update(t.getModality(),this.generateMid(i))}))}disableModalities(e){this.mediaEntities.forEach((t=>{t.getModality()in e||t.disable()}))}setRollbackUpdateHandler(e){}addModalities(e){const t={};this.mediaEntities.map((e=>e.getModality())).forEach((e=>{t[e]=!0}));for(const i in e)i in t||this.addMediaEntity(i)}setLocalTracksInfo(e){this.mediaTracks=e,this.updateLocalSsrc(this.mediaTracks)}getLocalTracksInfo(){return this.mediaTracks}getLocalSsrcs(){return this.localSsrcs}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?t.setLocalTrackId(e.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)})))}updateMediaEntitiesWithActivityState(e,t){}backup(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[]}rollback(){this.mediaEntities=this.mediaEntitiesBackup}generateSourceStreamId(e){return e+10}generateMid(e){return`media_${e}`}updateLocalSsrc(e){e.forEach((e=>{if(!this.localSsrcs.get(e.modality)){const t=this.ssrcGenerator.nextVideoStreamSsrc().min;this.logger.safe.debug(`Ssrc updated for modality: ${e.modality}: ${t}`),this.localSsrcs.set(e.modality,t)}}))}},qU=p(ye()),zU=class{constructor(e,t,i,n,r){this.logger=e,this.RtcDescType=t,this.sessionDescription=i,this.negotiationQueue=n,this.mediaManager=r}configure(e){this.peerConnection=e}renegotiateNow(){return this.renegotiate(null,!0)}renegotiate(e,t=!1,i="local"){if(!this.peerConnection)throw new Error("trying to renegotiate without a peerConnection");const n="local"===i?this.createNegotiationTaskForHaveLocalOffer(e):this.createNegotiationTaskForHaveRemoteOffer();return t?(this.logger.safe.info(`forced ${i} renegotiation starting`),Promise.resolve(n())):this.negotiationQueue.add(n)}normalizeRemoteSdpSDES(e,t){if(t.media[0].crypto)e.media.forEach((e=>{delete e.fingerprint,delete e.setup,e.crypto=e.crypto.filter((e=>t.media[0].crypto.some((t=>t.id===e.id)))).slice(0,1)})),e.fingerprint&&delete e.fingerprint;else{const t=this.mediaManager.getMediaEntities().find((e=>void 0!==e.getExtension("setup")));e.media.forEach((e=>{const i=t?.getExtension("setup")||"actpass";"actpass"===e.setup&&(e.setup="active"===i?"passive":"active")}))}}normalizeRemoteSdpExtensions(e,t){e.media.forEach(((e,i)=>{const n=new Set(t.media[i].ext?.map((e=>e.value))||[]);e.ext=e.ext?.filter((e=>n.has(e.value)))}))}createNegotiationTaskForHaveLocalOffer(e){return async()=>{let t=this.peerConnection.remoteDescription.sdp;const i=this.peerConnection.localDescription.sdp;this.logger.safe.info(`local renegotiation starting remoteSdp=${!!t} localSdp=${!!i}`);const n=qU.parse(t),r=qU.parse(i);this.normalizeRemoteSdpSDES(n,r),this.normalizeRemoteSdpExtensions(n,r),t=qU.write(n);let s=new this.RtcDescType({sdp:t,type:"answer"});e&&e.forEach((e=>{s=e.modifyDescriptor(s)}));try{this.logger.safe.info("creating offer");const e=await this.peerConnection.createOffer(),t=this.sessionDescription.createLocalOffer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"offer"});this.logger.safe.info("setting local description"),this.logger.unsafe.debug(`local description, sdp: ${i.sdp}`),await this.peerConnection.setLocalDescription(i),this.logger.safe.info("setting remote description"),this.logger.unsafe.debug(`remote description, sdp: ${s.sdp}`),await this.peerConnection.setRemoteDescription(s),this.logger.safe.debug("local renegotiation done")}catch(e){throw this.logger.safe.error("local renegotiation failed: ",e.toString()),e}}}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 e=await this.peerConnection.createAnswer();this.logger.safe.info("applying answer");const t=this.sessionDescription.createLocalAnswer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"answer"});this.logger.safe.info("setting [answer] local description"),this.logger.unsafe.debug(`[answer] local description, sdp: ${i.sdp}`),await this.peerConnection.setLocalDescription(i),this.logger.safe.info("local answer for renegotiation is done")}catch(e){throw this.logger.safe.error("local answer for renegotiation failed: ",e.toString()),e}}}},WU=15e3,KU=class{constructor(e,t,i){this.settings=e,this.listener=t,this.logger=i,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(e){const t=Hn.Send.getResolutionByFs(e);t!==this.maxResolution&&(this.logger.safe.info(`Setting max resolution: ${t}`),this.maxResolution=t,this.lastSendBW&&this.processEstimatedBandwidth(this.lastSendBW))}updateEstimatedSendBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Send BW: ${e}`),this.processEstimatedBandwidth(e))}resetCurrentResolution(){this.currentResolution=null}getCurrentResolution(){return this.currentResolution?.fs}setCurrentResolution(e){this.currentResolution=e}applyRes(e){this.pendingResolution=e,this.coolingDown&&(!this.currentResolution||e.fs>this.currentResolution.fs)||(this.coolingDown=!0,this.logger.safe.info(`Changing resolution to ${e}`),this.listener&&this.listener.onResolutionChanged(e.fs).then((t=>{t?(e===this.pendingResolution&&(this.pendingResolution=null),this.coolingDown&&!this.currentResolution&&(this.coolingDown=!1),this.currentResolution=e,this.cooldown()):(this.logger.safe.info("Unable to apply resolution at the moment"),this.cooldown(5e3))})).catch((e=>{this.logger.safe.error(`Error while applying new resolution: ${JSON.stringify(e)}`),this.pendingResolution=null})))}cooldown(e=WU){!this.active||this.coolingDown&&this.cooldownEnd-Date.now()>WU||(this.cooldownTimer&&clearTimeout(this.cooldownTimer),this.coolingDown=!0,this.cooldownEnd=Date.now()+WU,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)}),e))}proposeResolution(e){let t=e;this.maxResolution&&this.maxResolution.fs<t.fs&&(t=this.maxResolution),this.currentResolution&&t.fs===this.currentResolution.fs||this.applyRes(t)}processEstimatedBandwidth(e){const{lowRes:t,highRes:i}=Hn.Send.getResolutionForBitrate(e),n=e<this.lastSendBW?i:t;e<this.lastSendBW&&n&&this.currentResolution&&this.currentResolution.fs<n.fs||(n&&this.proposeResolution(n),this.lastSendBW=e)}};function JU(e,t){const i=t.config.maxBandwidthInKbpsFallback>0?t.config.maxBandwidthInKbpsFallback:Math.floor(Number.MAX_SAFE_INTEGER/1e3),n=1e3*((t.mediaConfig.maxBandwidthInKbps||i)-(t.config.audioBandwidthInKbps||0)),r=e.transport?.selectedCandidatePair?.availableOutgoingBitrate??0;return Math.min(n,r)}var YU=class extends Vi{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.lastReportedAgo=1/0,this._forceUpdate=!1}forceUpdate(){this._forceUpdate=!0}onBandwidthChanged(e){this._forceUpdate?this.updateBandwidth(e,"forceUpdate"):this.processEstimatedBandwidth(e)}processEstimatedBandwidth(e){if(this.lastReportedAgo++,!e||this.bandwidth===e)return;const t=this.configProvider.config.webrtcSendBandwidthIgnoredUpdateLimit,i=this.configProvider.config.webrtcSendBandwidthThreshold,n=this.lastReportedAgo===1/0,r=!t&&!i,s=t&&this.lastReportedAgo>=t,a=i&&Math.abs((e-this.bandwidth)/this.bandwidth)>=i,o=this.configProvider.config.webrtcSendBandwidthAlwaysReportAfterDrop&&e<this.bandwidth;if(n||r||s||a||o){const t=+n|+r<<1|+s<<2|+a<<3|+o<<4,i=this.getUpdateReason(t);this.updateBandwidth(e,i)}}updateBandwidth(e,t){this.bandwidth=e,this.logger.safe.debug(`Updating send bandwidth: ${this.bandwidth}, reason: ${t}`),this.notifySendBandwidthChanged()}notifySendBandwidthChanged(){this._forceUpdate=!1,this.event("onSendBandwidthChanged").raise(this.bandwidth),this.lastReportedAgo=0}getUpdateReason(e){return 1&e?"firstReport":2&e?"throttlingDisabled":4&e?"noReportsForTooLong":8&e?"bigMovement":22&e?"drop":"none"}},QU=class{constructor(e,t,i,n,r,s,a){this.listener=e,this.statisticsGatherer=t,this.diagnostics=i,this.logger=n,this.configProvider=r,this.isSimulcastEnabled=a,this.serialQueue=new tk(this.logger),this.modality=Gi.MODALITY.video;const o=s.maxResolution?{maxFs:s.maxResolution.fs}:null;this.validator=new yD(this.logger.createChild("CapsValidator"),o),this.resolutionManager=new KU(s,this,this.logger.createChild("rm")),this.statisticsGatherer.on("onStatisticsChanged",(e=>this.onStatisticsChanged(e))),this.statisticsGatherer.on("onDiagnosticUpdated",(e=>this.onDiagnosticUpdated(e)))}async setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.causeId=e;const n=this.validator.ensureValidity(t[0]);this.streamSenderParams={...t[0],...n},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(e){this.resolutionManager.setCurrentResolution(e)}async onResolutionChanged(e){return this.applyCapabilities(this.getParamsToApply(e))}dispose(){this.resolutionManager.dispose(),this.resolutionManager=null}async applyCapabilities(e){return e?this.lastAppliedSenderParams===e?(this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}`),!0):(this.logger.safe.info(`Capabilities to apply: ${JSON.stringify(e)}`),this.lastAppliedSenderParams=e,this.listener.onReceiveCapabilitiesChanged(this.modality,this.causeId,[e])):(this.logger.safe.error("Send capabilities are not set. Cannot apply constraints"),!1)}getParamsToApply(e){if(!this.streamSenderParams)return null;const t=e||this.resolutionManager.getCurrentResolution();if(!t||this.streamSenderParams.maxFs<=t)return this.streamSenderParams;const i=tn(this.streamSenderParams);return i.maxFs=t,i}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.resolutionManager.updateEstimatedSendBandwidth(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){try{if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!e.video?.send?.length||!e.video.send[0])return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth");const t=JU(e.video.send[0],this.configProvider);this.resolutionManager.updateEstimatedSendBandwidth(t)}}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}};m([Uk()],QU.prototype,"applyCapabilities",1);var ZU=class{constructor(e,t,i,n,r){this.modality=e,this.listener=t,this.statisticsGatherer=i,this.diagnostics=n,this.isSimulcastEnabled=r}setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.listener.onReceiveCapabilitiesChanged(this.modality,e,t)}dispose(){}resetCurrentResolution(){}getCurrentResolution(){return null}setCurrentResolution(e){}},XU=class{constructor(e,t,i,n,r,s){this.logger=e,this.settings=t,this.listener=i,this.statsGatherer=n,this.diagnostics=r,this.configProvider=s,this.mediaSourceModels=[],this.pendingCapabilities=new Map}dispose(){this.mediaSourceModels.forEach((e=>{e.handler&&(e.handler.dispose(),e.handler=null)})),this.mediaSourceModels=null}updateRegisteredSources(e){this.logger.safe.info(`Local media params updated: ${JSON.stringify(e)}`);const t=[];this.mediaSourceModels.forEach((e=>t.push(e.sourceId)));const i=e.map((e=>e.sourceId)),n=hn(t,i);this.removeSourcesWithIds(n);const r=hn(i,t);this.addSourcesWithIds(r,e)}setMaxCapabilities(e,t){for(const i of e){if(!i.capabilities.length)continue;if(!i.sourceId){this.logger.safe.info(`SourceId is not defined to apply recv capabilities: ${JSON.stringify(i)}`);continue}const e=this.getModelWithSourceId(i.sourceId);if(!e){this.logger.safe.info(`Model is not registered for sourceId: ${i.sourceId}`),this.configProvider.config.enableCachingFMTP&&this.pendingCapabilities.set(i.sourceId,i);continue}this.logger.safe.info(`Capabilities handler found for sourceId: ${i.sourceId}`);const n=this.getOrCreateHandlerForModel(e,i.isSimulcast);n?n.setMaxCapabilities(i.causeId||t,i.capabilities):this.logger.safe.info(`Handler is not found for sourceId: ${i.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 e=Array.from(this.pendingCapabilities.values());this.setMaxCapabilities(e),this.pendingCapabilities.clear()}clearPendingCapabilities(){this.pendingCapabilities.clear()}resetCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));e?.handler&&e.handler.resetCurrentResolution()}getCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));return e?.handler?e.handler.getCurrentResolution():this.currentResolution?.fs}setCurrentResolution(e){const t=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));t?.handler?t.handler.setCurrentResolution(e):this.currentResolution=e}getOrCreateHandlerForModel(e,t){return e.handler||(e.handler=this.getCapabilitiesHandler(e.modality,t)),e.handler}addSourcesWithIds(e,t){e.forEach((e=>{const i=t.find((t=>t.sourceId===e));this.registerSource(e,i.modality)}))}removeSourcesWithIds(e){e.forEach((e=>this.unregisterSource(e)))}registerSource(e,t){this.logger.safe.info(`SourceId ${e} registered with mediaType: ${t}`),this.mediaSourceModels.push({modality:t,sourceId:e})}unregisterSource(e){const t=this.mediaSourceModels.find((t=>t.sourceId===e));t?(t.handler&&t.handler.dispose(),this.mediaSourceModels.splice(this.mediaSourceModels.indexOf(t),1),this.logger.safe.info(`SourceId ${e} unregistered`)):this.logger.safe.info(`Model doesn't exist with sourceId ${e}`)}getModelWithSourceId(e){return this.mediaSourceModels.find((t=>t.sourceId===e))}getCapabilitiesHandler(e,t){if(e===Gi.MODALITY.audio)return null;if(e===Gi.MODALITY.video&&!t&&this.settings.customBwEstimationEnabled){const e=new QU(this.listener,this.statsGatherer,this.diagnostics,this.logger.createChild("ach"),this.configProvider,this.settings,t);return this.currentResolution&&e.setCurrentResolution(this.currentResolution),e}return new ZU(e,this.listener,this.statsGatherer,this.diagnostics,t)}},eB=class extends Vi{constructor(e,t,i,n,r,s){super(e),this.logger=e,this.multiParty=t,this.configProvider=i,this.mediaManager=n,this.statsGatherer=r,this.diagnostics=s,this.rendererResolutions=new Map,this.rendererResolutionsApplied=new Map,this.rendererResolutionMax=new Map,this.hasPendingLimitResolutionUpdate=!1,this.spotlightedRenderers=[]}addRenderer(e){this.rendererResolutions.set(e,{width:0,height:0}),e.on("onRendererSizeChanged",((e,t)=>{this.onRendererSizeChanged(e,t)})),this.scheduleUpdateLimitedResolutions()}removeRenderer(e){this.rendererResolutions.delete(e),this.rendererResolutionsApplied.delete(e),this.rendererResolutionMax.delete(e),this.scheduleUpdateLimitedResolutions()}clearRenderers(){this.rendererResolutions.clear(),this.rendererResolutionsApplied.clear(),this.rendererResolutionMax.clear()}getMaxAllowedVideoFS(){const e=this.getMaxHeightFromConfig(this.sizedRenderersCount);return this.getMaxFSForHeight(e)}limitResolutionOnPoorPerformance(e){const t=this.getRendererByMsi(e);if(!t)return;const i=t.resolution.height>t.resolution.width,n=Hn.Recv.getNextLowerResolution(t.resolution.width,t.resolution.height);if(!n)return;const r={width:i?n.height:n.width,height:i?n.width:n.height};this.rendererResolutionMax.set(t.renderer,r),this.diagnostics?.registerResolutionChangeRequest({ts:Date.now(),msi:t.renderer.getMsi(),res:r}),this.logger.safe.info(`Poor perf. Limiting resolution for renderer msi: ${t.renderer.getMsi()} from ${t.resolution.height}p to ${r.height}p`),this.onRendererSizeChanged(t.renderer,r)}get renderersCount(){return this.rendererResolutions.size}get sizedRenderersCount(){return this.configProvider.config.excludeUnsizedRenderersFromMultiviewResolutionLimits?[...this.rendererResolutions.values()].filter((e=>e.height>0)).length:this.renderersCount}getMaxFSForHeight(e){return this.limitMaxFS(Hn.Recv.getMaxFsForHeight(e))}getRendererByMsi(e){for(const[t,i]of this.rendererResolutions.entries())if(t.getMsi()===e)return{renderer:t,resolution:i};return null}applyRendererResolution(e,t){this.setMaxFSCapabilities(e,t),this.rendererResolutionsApplied.set(e,t);const i=e.getMediaStream()&&e.getMediaStream().getVideoTracks();i?.[0]&&this.statsGatherer.setPreferredResolution(i[0].id,t,e.getModality())}onRendererSizeChanged(e,t){this.rendererResolutions.set(e,t),this.scheduleUpdateLimitedResolutions()}scheduleUpdateLimitedResolutions(){this.hasPendingLimitResolutionUpdate||(this.hasPendingLimitResolutionUpdate=!0,window.setTimeout((()=>{this.hasPendingLimitResolutionUpdate=!1;const e=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((e=>e.getMsi()))}, max spotlight height: ${this.configProvider.config.maxSpotlightResolution}`);for(const[t,i]of this.rendererResolutions.entries()){if(!i.height)continue;const n=e.get(t.getMsi()),r=this.limitRendererResolution(t,n||i),s=this.rendererResolutionsApplied.get(t);(!s||s.height!==r.height||s.width!==r.width)&&this.applyRendererResolution(t,r)}}),this.configProvider.config.multiviewResolutionLimitUpdateThrottleDelay))}findSpotlightedRenderers(){if(this.sizedRenderersCount<=1||!this.configProvider.config.isSpotlightEnabled)return[];let e=!1,t=0;for(const[i,n]of this.rendererResolutions.entries())n.height&&n.height!==t&&(t&&(e=!0),t=n.height);if(!e)return[];const i=new Gg(((e,t)=>e.resolution.width>t.resolution.width));for(const[e,t]of this.rendererResolutions.entries())i.enqueue({renderer:e,resolution:t});const n=[];let r=this.configProvider.config.maxNumberOfPinnedVideos;for(;r;){const e=i.peek()?.resolution?.width,t=[];for(;i.peek()?.resolution?.width===e;)t.push(i.dequeue().renderer);if(!(r-t.length>=0))break;r-=t.length,n.push(...t)}return n}getMaxHeightFromConfig(e,t=!1){return t?this.configProvider.config.maxSpotlightResolution:this.configProvider.config.multiviewResolutionLimits[`${e}`]||this.configProvider.config.multiviewResolutionLimits.more}getMaxHeight(e){const t=this.spotlightedRenderers.some((t=>t.getMsi()===e.getMsi()));let i=this.getMaxHeightFromConfig(this.sizedRenderersCount,t);const n=this.rendererResolutionMax.get(e);return n&&(i=Math.min(i,Math.min(n.height,n.width))),i}limitRendererResolution(e,t){const i=this.getMaxHeight(e);if(!i)return t;if(t.height>t.width&&t.width>i){const e=i/t.width;return{height:Math.ceil(t.height*e),width:i,limited:!0}}if(t.width>t.height&&t.height>i){const e=i/t.height;return{height:i,width:Math.ceil(t.width*e),limited:!0}}return t}setMaxFSCapabilities(e,t){const i=e.getMediaStream();if(!i)return void this.logger.safe.warn("renderer has no stream attached");const n=this.mediaManager.getMediaEntityByRemoteStreamId(i.id);if(!n?.getLocalRecvCapabilities())return void this.logger.safe.warn(`no capabilities for provided modality: ${e.getModality()}`);const r=t.limited?this.getMaxFSForHeight(t.height):this.getMaxFS(t.width,t.height),s=n.getLocalRecvCapabilities();s.setMaxFS(r,(()=>{if(this.logger.safe.info(`updated max-fs video capability to ${r} for renderer msi: ${e.getMsi()}`),this.multiParty&&this.configProvider.config.webrtcMultiPartyRecvVideoSignaling){const t=e.getMsi(),n=s.buildFmtp();this.event("onSourceRequestRequired").raise(i.id,t,n)}else this.event("onNegotiationRequired").raise()}))}getMaxFS(e,t){return this.limitMaxFS(Hn.Recv.getMaxFsForHeight(t))}limitMaxFS(e){return this.multiParty?Math.min(e,this.configProvider.config.webrtcMultiPartyRecvVideoMaxFS):Math.min(e,this.configProvider.config.webrtcRecvVideoMaxFS)}groupMaxRenderersResolutionsByMsi(){const e=new Map;return this.rendererResolutions.forEach(((t,i)=>{const n=i.getMsi(),r=e.get(n);(!r||t.width>r.width&&t.height>r.height)&&e.set(n,t)})),e}},tB=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.getModality=t,this.isRendering=!1,this.currentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0}captureRawStatistics(e){const t=e.googFrameRateDecoded,i=e.googFrameRateReceived,n=e.bytesReceived;void 0!==n&&this.getModality()!==Gi.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateBitrate(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}updateRenderingTracker(e){const t=e.extensions.frameRateDecoded||0,i=e.extensions.frameRateReceived||0,n=e.extensions.bitrate;void 0!==n&&this.getModality()!==Gi.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateLowBitrateDuration(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}calculateLowBitrateDuration(e,t){e/1e3<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}calculateBitrate(e,t){const i=8*(e-this.lastBytesRecv);this.lastBytesRecv=e,this.calculateLowBitrateDuration(i,t)}setIsRendering(e){const t=this.currentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted;t!==this.isRendering&&(this.isRendering=t,this.event("onIsRenderingChanged").raise(this.isRendering))}},iB=class extends Vi{constructor(e,t,i){super(),this.videoElement=e,this.configProvider=t,this.getTimeToFirstFrame=i,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 e=this.videoElement.currentTime,t=e===this.prevCurrentTime,i=this.videoElement.webkitDecodedFrameCount,n=void 0===i||i===this.prevDecodedFrameCount;if(this.prevCurrentTime=e,this.prevDecodedFrameCount=i,-1!==this.getTimeToFirstFrame())if(t&&n){const e=Date.now();this.currentFreezeDuration+=e-this.prevTimestamp,this.prevTimestamp=e}else{if(this.currentFreezeDuration>this.configProvider.config.freezeMinDuration){const e=this.calcFreeze();this.event("onFreezeEnded").raise(e)}this.currentFreezeDuration=0}this.prevTimestamp=Date.now()}getEndOfTheFreeze(){let e=0;return this.currentFreezeDuration>0&&(e=this.calcFreeze(),this.currentFreezeDuration=0),e}dispose(){const e=this.getEndOfTheFreeze();this.event("onFreezeEnded").raise(e),clearInterval(this.freezeDurationTimer)}calcFreeze(){const e=Date.now()-this.prevTimestamp;return this.currentFreezeDuration+e}},nB=class extends Vi{constructor(e,t,i,n){super(),this.videoElement=e,this.minInterval=t,this.maxInterval=i,this.window=Mp.window,this.devicePixelRatio=n&&window.devicePixelRatio||1,this.originalVideoElementSize={width:e.offsetWidth,height:e.offsetHeight},this.initializeSizeTracking()}get width(){return this.originalVideoElementSize.width*this.devicePixelRatio}get height(){return this.originalVideoElementSize.height*this.devicePixelRatio}initializeSizeTracking(){const e=Math.floor(Math.random()*Math.abs(this.maxInterval-this.minInterval))+this.minInterval;this.elementSizeTrackingRef=this.window.setInterval((()=>{this.videoElementSizeChanged()&&(this.saveCurrentVideoElementSize(),this.raiseChanged())}),e)}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}},rB=class extends dk{constructor(e,t,i,n,r,s){super(r,e.createChild("remote"),t),this.diagnostics=i,this.subscriptionManager=n,this.sessionDiagnostics=s,this.disposed=!1,this.currentIsRendering=!1,this.startTimeTTFF=0,this.timeToFirstFrame=-1,this.isTimeToFirstFrameReported=!1,this.configProvider.config.freezeIntervalFrequency&&(this.freezeTracker=new iB(this.getVideoElement(),this.configProvider,(()=>this.timeToFirstFrame)),this.freezeTracker.on("onFreezeEnded",(e=>{this.diagnostics?.addFreezeDuration(e),this.event("onFreezeEnded").raise(e)}))),this.configProvider.config.isRenderingBasedOnRawStatistics&&(this.isRenderingTracker=new tB(this.configProvider,this.getModality.bind(this)),this.isRenderingChangedSubscription=this.isRenderingTracker.on("onIsRenderingChanged",(e=>{this.setIsRendering(e)}))),this.overlayStats=new ok(this.configProvider.config.showStatsInCall,r,this)}getEndOfTheFreeze(){return this.freezeTracker?.getEndOfTheFreeze()}resetTimeToFirstFrameFlag(){this.isTimeToFirstFrameReported=!1}setIsRendering(e){this.currentIsRendering!==e&&(this.currentIsRendering=e,this.captureIsRenderingEvent(e))}updateStatsOverlay(e,t){this.overlayStats.setStats(e,t)}updateIsRenderingTracker(e){this.isRenderingTracker?.updateRenderingTracker(e)}subscribeVideoAsync(e,t){return this.timeToFirstFrameSinceSubscriptionStart=Date.now(),new Promise(((i,n)=>{this.modality=t?Gi.MODALITY.sharing:Gi.MODALITY.video,this.diagnostics&&(this.diagnostics.msi=e,this.diagnostics.modality=this.modality),this.trackElementSizeChange(),this.unsubscribe(),this.on("onVideoSizeChanged",((t,i)=>{if(this.modality===Gi.MODALITY.video&&this.sessionDiagnostics?.registerResolutionChangeEvent({ts:Date.now(),msi:e,res:{width:t,height:i}}),this.isTimeToFirstFrameReported)return;if(-1===this.timeToFirstFrame){const e=Date.now();this.timeToFirstFrame=e-this.startTimeTTFF,this.timeToFirstFrameSinceSubscriptionStart=Date.now()-this.timeToFirstFrameSinceSubscriptionStart}const n=this.getTrackId();n&&(this.diagnostics.timeToFirstFrameSinceSubscriptionStart=this.timeToFirstFrameSinceSubscriptionStart,this.diagnostics.timeToFirstFrame=this.timeToFirstFrame,this.sizeTracker?.triggerVideoElementSizeChange(),this.event("onVideoStarted").raise(this.timeToFirstFrame,this.timeToFirstFrameSinceSubscriptionStart,n),this.isTimeToFirstFrameReported=!0)})),this.on("onVideoRendererStateChanged",(e=>{this.diagnostics.addStateChange(e)}));const r=this.subscriptionManager.subscribeVideo(this.modality,e);this.subscription=r,this.logger.safe.info(`subscribing renderer to type: ${r.modality} msi: ${r.msi}`),r.setOnMediaStreamChangedHandler((e=>{const t=this.getMediaStream();this.attachMediaStream(e),e&&(this.startTimeTTFF=Date.now());const n=this.getTrackId();n&&this.diagnostics&&(this.diagnostics.trackId=n),this.logger.safe.info(`subscribed renderer to type: ${r.modality} msi: ${r.msi} on stream #${e?e.id:"none"}`),e&&t!==e&&this.sizeTracker?.triggerVideoElementSizeChange(),i()})),r.setOnErrorHandler((t=>{this.logger.safe.error(`failed to subscribe renderer ${tt(t)}`),"webRtcSession cleanup"===JSON.stringify(t)&&(this.logger.safe.info(`Retry to subscribe to video stream with msi: ${e}. Previous session was cleaned up`),this.subscriptionManager.streamChangedByMsi(e),i()),n(t)}))}))}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 e=this.modality===Gi.MODALITY.sharing,t=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMin:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,i=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMax:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax;t&&i?(this.sizeTracker=new nB(this.getVideoElement(),t,i,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(e){this.diagnostics&&(this.diagnostics.isRendering=e),this.event("onIsRenderingChanged").raise(e,this.getModality(),this.getTrackId())}},sB=class{constructor(e,t,i,n,r,s){this.logger=e,this.configProvider=t,this.statsGatherer=i,this.sessionDiagnostics=n,this.remoteVideoResolutionManager=r,this.domOverrides=s,this.remoteRendererSubscriptions=new Map,this.diagnostics=n?.newRemoteVideoManagerDiagnostics()}createRenderer(e,t,i){const n=new rB((i??this.logger).createChild("videorenderer"),this.configProvider,this.diagnostics?.newRendererDiagnostics(),t,e,this.sessionDiagnostics);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(n.getVideoElement()),this.addRenderer(n),n}moveRenderers(e){this.renderers.forEach((t=>{t.resetTimeToFirstFrameFlag(),e.addRenderer(t),this.removeRenderer(t)}))}getMaxAllowedVideoFS(){return this.remoteVideoResolutionManager.getMaxAllowedVideoFS()}dispose(){this.renderers.forEach((e=>e.resetTimeToFirstFrameFlag())),this.renderers.forEach((e=>{const t=e.getTrackId(),i=e.getEndOfTheFreeze();this.statsGatherer.setFreezeDuration(i,t)})),this.remoteRendererSubscriptions.forEach(((e,t)=>{t.dispose(),e.forEach((e=>e.dispose()))})),this.remoteRendererSubscriptions.clear(),this.remoteVideoResolutionManager.clearRenderers()}processStatsReport(e){this.configProvider.config.isRenderingBasedOnRawStatistics&&this.onDiagnosticUpdated(e),this.updateOverlayStats(e)}processLegacyStats(e){this.configProvider.config.isRenderingBasedOnRawStatistics||this.renderers.forEach((t=>{const i=t.getTrackId();if(e.remoteVideoStreams[i]){const n=e.remoteVideoStreams[i].isRendering;void 0!==n&&t.setIsRendering(n)}}))}playVideo(){this.renderers.forEach((e=>e.playVideo()))}get renderers(){return Array.from(this.remoteRendererSubscriptions,(([e])=>e))}addRenderer(e){this.remoteRendererSubscriptions.set(e,this.subscribeOnEvents(e)),this.logger.safe.info("Added renderer to manager"),this.remoteVideoResolutionManager.addRenderer(e)}generateVideoRecvStats(e){const t=new Map,i=e=>{e?.forEach((e=>{const i=e.track?.trackIdentifier??e.inboundRTP.trackIdentifier;t.set(i,e)}))};return i(e.sharing?.recv),i(e.video?.recv),t}updateOverlayStats(e){const t=this.generateVideoRecvStats(e);this.renderers.forEach((i=>{const n=i.getTrackId();t.has(n)&&e.audio?.recv?.length&&i.updateStatsOverlay(t.get(n),e.audio.recv[0])}))}onDiagnosticUpdated(e){const t=[...e.video?.recv??[],...e.sharing?.recv??[]];if(t.length){const e=new Map;t.forEach((t=>{e.set(t.track?.trackIdentifier,t)})),this.renderers.forEach((t=>{const i=t.getTrackId();e.has(i)&&t.updateIsRenderingTracker(e.get(i))}))}}subscribeOnEvents(e){return[e.on("onRendererDisposed",(e=>this.onRendererDisposed(e))),e.on("onVideoStarted",((e,t,i)=>this.onVideoStarted(e,t,i))),e.on("onFreezeEnded",(t=>{const i=e.getTrackId();this.statsGatherer.setFreezeDuration(t,i)})),e.on("onIsRenderingChanged",((e,t,i)=>this.statsGatherer.setIsRendering(e,t,i)))]}onRendererDisposed(e){this.logger.safe.debug("Renderer removed from manager"),this.removeRenderer(e),this.domOverrides.onMediaElementRemoved&&this.domOverrides.onMediaElementRemoved(e.getVideoElement())}removeRenderer(e){this.remoteRendererSubscriptions.get(e).forEach((e=>e.dispose())),this.remoteRendererSubscriptions.delete(e),this.remoteVideoResolutionManager.removeRenderer(e)}onVideoStarted(e,t,i){this.statsGatherer.setTimeToFirstFrame(e,t,i)}},aB=class extends Vi{constructor(e,t,i){super(),this.configProvider=t,this.callDeviceManager=i,this.lastFramerateInput=-1,this.trackInfo=[],this.timeoutId=null,this.logger=e.createChild("localStreamWatcher"),this.callDeviceManagerSub=i.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, updating subscriptions"),this.handleDeviceManagerChange()}))}get effectsManager(){return this.callDeviceManager.getDeviceManager("Video").effectsManager}startWatching(e,t){(this.configProvider.config.videoCaptureFreezeTimeout||t)&&(this.trackInfo=e,this.performanceMonitor=t,this.configProvider.config.videoCaptureFreezeTimeout&&(this.videoEffectManagerSubscription||(this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e))))))}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(e){this.callDeviceManagerSub?.dispose(),super.dispose(e),this.stopWatching()}onDiagnosticUpdated(e){if(!this.trackInfo.length||!e.video?.send?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Updating local video stream watcher");const t=e.video?.send[0],i=[];let n,r=0;[t,...t.altLayouts??[]].forEach((e=>{const t=e.mediaSource,s=t?.framesPerSecond??0;this.trackInfo.some((e=>e.trackId===t.trackIdentifier))&&((!n||r<s)&&(n=t,r=s),this.performanceMonitor&&i.push(e.outboundRTP))})),this.performanceMonitor?.monitor(i),this.configProvider.config.videoCaptureFreezeTimeout&&(n?r!==this.lastFramerateInput&&(0===r?this.scheduleCaptureFreezeStart(n.trackIdentifier,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${n.trackIdentifier}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=r):this.logger.safe.warn("WebRTC Stats for send video not found"))}onStatisticsChanged(e){if(!this.trackInfo.length||!this.configProvider.config.videoCaptureFreezeTimeout)return;let t;Object.keys(e.localVideoStreams).forEach((i=>{const n=e.localVideoStreams[i];this.trackInfo.some((e=>e.trackId===n.trackId))&&(!t||t.frameRateInput<n.frameRateInput)&&(t=n)})),t?t.frameRateInput!==this.lastFramerateInput&&(0===t.frameRateInput?this.scheduleCaptureFreezeStart(t.trackId,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${t.trackId}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=t.frameRateInput):this.logger.safe.warn("WebRTC Stats for send video not found")}onVideoFreezeDetected(e){this.logger.info(`onVideoCaptureFreeze, webcam freeze detected trackId: ${e}`),this.event("onVideoCaptureFreeze").raise(!1,!0)}scheduleCaptureFreezeStart(e,t){this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,this.logger.safe.info(`onVideoCaptureFreeze start for trackId: ${e} (isWebcamStream: ${t})`),this.event("onVideoCaptureFreeze").raise(!0,t)}),this.configProvider.config.videoCaptureFreezeTimeout)}disposeTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleDeviceManagerChange(){this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e)))}},oB=class{constructor(e){this.queue=[],this.logger=e}cleanup(){this.queue.forEach((e=>{e.reject({notSent:e.tones})})),this.queue=[]}waitForNotification(e){return e?(this.logger.unsafe.info("sending dtmf tones: ",e),new Promise(((t,i)=>{this.queue.push({tones:e,resolve:t,reject:i})}))):Promise.reject(new Error("invalid input"))}toneSent(e){this.queue[0]&&(e===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 '${e}'`)),this.queue.shift(),this.toneSent(e)))}},lB=class{constructor(e){this.webRtcSender=null,this.configProvider=e.configProvider,this.queue=new oB(e.logger)}sendDtmf(e,t){return e?.getSenders?(this.syncSender(e),this.webRtcSender?(this.webRtcSender.ontonechange=this.onToneChange.bind(this),this.webRtcSender.insertDTMF(this.webRtcSender.toneBuffer+t,this.configProvider.config.dtmf.toneDuration,this.configProvider.config.dtmf.toneGap),this.queue.waitForNotification(t)):Promise.reject(new Error("not available"))):Promise.reject(new Error("bad peerConnection"))}canSendDtmf(e){return!!e?.getSenders&&(this.syncSender(e),!!this.webRtcSender&&this.webRtcSender.canInsertDTMF)}dispose(){this.queue.cleanup()}syncSender(e){const t=e.getSenders().filter((e=>e.track&&"audio"===e.track.kind)).filter((e=>e.dtmf?.canInsertDTMF))[0];this.webRtcSender&&t&&t.dtmf!==this.webRtcSender&&(this.webRtcSender.ontonechange=null,this.queue.cleanup()),this.webRtcSender=t?t.dtmf:null}onToneChange(e){e.tone&&this.queue.toneSent(e.tone)}},cB=e=>new lB(e),dB=class extends Vi{constructor(e,t,i,n,r){super(i),this.pc=e,this.cryptoMethod=t,this.logger=i,this.configProvider=n,this.diagnostics=r,this.iceConnectionStateInternal="new",this.isWaitingAcceptProvisionalInternal=!1,this.state="new",this.toBeCalledOnConnected=[],this.toBeCalledOnProvisionalConnected=[],this.handleSignalingStateChange=()=>{const e=this.pc.signalingState,t=this.signalingStateInternal;if(this.logger.safe.info(`RTCPeerConnection onsignalingstatechange signalingState: ${this.signalingStateInternal} -> ${e}`),this.signalingStateInternal=e,this.diagnostics.signalingState=e,this.event("signalingStateChanged").raise(this.signalingStateInternal,t,be()),!this.configProvider.config.useDtlsTrasportConnectionCheck||this.transport||1!==this.cryptoMethod||this.hasPcConnectionState)return;const i=this.pc.getReceivers().find((e=>!!e.transport));this.transport=i?.transport,this.transport&&(this.transport.onstatechange=this.handleDtlsTransportStateChange)},this.handleIceConnectionStateChange=()=>{const e=this.pc.iceConnectionState;this.logger.safe.info(`RTCPeerConnection oniceconnectionstatechange iceConnectionState: ${e} pc.signalingState: ${this.pc.signalingState}`),this.iceConnectionStateInternal=e,this.diagnostics.iceConnectionState=e,this.event("iceConnectionStateChanged").raise(this.iceConnectionStateInternal,be()),this.shouldRaise(0)&&this.updateState(e)},this.handleConnectionStateChange=()=>{const e=this.pc.connectionState;this.logger.safe.info(`RTCPeerConnection onconnectionStatechange connectionState: ${e} pc.signalingState: ${this.pc.signalingState}`),this.connectionStateInternal=e,this.diagnostics.connectionState=e,this.event("connectionStateChanged").raise(this.connectionStateInternal,be()),this.shouldRaise(1)&&this.updateState(e)},this.handleDtlsTransportStateChange=()=>{const e=this.transport.state;this.logger.safe.info(`RTCDtlsTransport onstatechange state: ${e} pc.signalingState: ${this.pc.signalingState}`),this.dtlsStateInternal=e,this.diagnostics.dtlsTransportState=e,this.event("dtlsTransportStateChanged").raise(this.dtlsStateInternal,be()),this.shouldRaise(3)&&this.updateState(e)},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(e){this.isWaitingAcceptProvisionalInternal!==e&&(this.logger.safe.debug(`isProvisional set ${this.isWaitingAcceptProvisionalInternal} -> ${e}`),this.isWaitingAcceptProvisionalInternal=e,this.diagnostics.provisional=e,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(e,t="unknown",i=!1,n=!0){return this.diagnostics.scheduleDoOnConnected(e,t,i,n),n&&this.isConnected&&(i||!this.isWaitingAcceptProvisionalInternal)?(this.logger.safe.info(`Running callback immediately ${t}`),this.diagnostics.runDoOnConnected(e,!0),void e()):i?(this.logger.safe.info(`Queuing provisional connected callback '${t}'`),void this.toBeCalledOnProvisionalConnected.push(e)):(this.logger.safe.info(`Queuing connected callback '${t}'`),void this.toBeCalledOnConnected.push(e))}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(e,t=!0){if(t&&(this.statePrevious=this.state),this.state=e,this.event("stateChanged").raise(this.state,this.statePrevious,be()),this.diagnostics.transportState=e,this.isConnected){if(!this.isWaitingAcceptProvisionalInternal&&this.toBeCalledOnConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnConnected.length} callbacks on connected`);this.toBeCalledOnConnected.length;){const e=this.toBeCalledOnConnected.shift();this.diagnostics.runDoOnConnected(e),e()}if(this.toBeCalledOnProvisionalConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnProvisionalConnected.length} callbacks on provisional connected`);this.toBeCalledOnProvisionalConnected.length;){const e=this.toBeCalledOnProvisionalConnected.shift();this.diagnostics.runDoOnConnected(e),e()}}}shouldRaise(e){switch(e){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=${e}`),!1}}},uB=class{constructor(e,t,i,n,r,s){this.logger=e,this.emulator=t,this.qualityManager=i,this.diagnostics=n,this.configProvider=r,this.statsGatherer=s,this.previousSequenceNumber=new Map,this.modifiers=this.configProvider.mediaConfig.simulcastSessionEnabled?[]:[new Zx(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider)]}dispose(){this.cleanupDevToolsInjector(),this.modifiers&&(this.modifiers.forEach((e=>e.dispose())),this.modifiers=null),this.emulator=null,this.logger=this.logger.createChild("DISPOSED")}handleMessage(e){const t=e.controlInfo[0].sourceId;if(this.previousSequenceNumber.has(t)&&e.sequenceNumber<this.previousSequenceNumber.get(t))return this.statsGatherer.addVideoControlMessage(!0),this.diagnostics?.addVideoControlMessage(!0),this.logger.safe.info(`Discarded old media stream control message for sourceId ${t}: (${JSON.stringify(e)})`),Promise.resolve();this.previousSequenceNumber.set(t,e.sequenceNumber),this.statsGatherer.addVideoControlMessage(),this.diagnostics?.addVideoControlMessage(),this.configProvider.config.enableDevtoolsAPI&&this.injectFmtpHandler(e);const i={controlVideoStreaming:e};return this.configureResolution(i),this.modifiers.length?(this.modifiers.forEach((e=>e.setVideoControlMessage(i))),this.emulator.renegotiate(this.modifiers)):Promise.resolve()}configureResolution(e){this.logger.safe.info(`Signaling FMTP: ${JSON.stringify(e.controlVideoStreaming)}`);const t=String(e.controlVideoStreaming.sequenceNumber),i=e.controlVideoStreaming.controlInfo[0].fmtParamsList,n=e.controlVideoStreaming.controlInfo[0].fmtParams,r=i&&this.configProvider.config.webrtcFmtParamListSupported?this.parseFmtParamsList(i):[this.parseFmtParams(n)],s=+e.controlVideoStreaming.controlInfo[0].sourceId,a=[{causeId:t,isSimulcast:r.some((e=>void 0!==e.rid))||r.length>1,capabilities:r,sourceId:s}];this.qualityManager.setMaxCapabilities(a)}parseFmtParamsList(e){return e.map((e=>this.parseFmtParams(e)))}parseFmtParams(e){const t=new SO(e);return{maxFs:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Gi.VIDEO_CAPABILITIES.MAX_BR_PATH),ssrc:+t.get(Gi.VIDEO_CAPABILITIES.SSRC_PATH),rid:t.get(Gi.VIDEO_CAPABILITIES.RID_PATH),keyframe:this.shouldGenerateKeyFrame(t),vlaDebug:t.get(Gi.VIDEO_CAPABILITIES.VLA_DEBUG)}}shouldGenerateKeyFrame(e){return e.get(Gi.VIDEO_CAPABILITIES.KEYFRAME_PATH)?!!+e.get(Gi.VIDEO_CAPABILITIES.KEYFRAME_PATH):this.configProvider.config.webrtcAllowRestoreKeyframe}injectFmtpHandler(e){const t=window;t?.webMA&&(t.webMA.fmtp||(t.webMA.fmtp={handleMessage:this.handleMessage.bind(this)}),t.webMA.fmtp.lastFmtp=e)}cleanupDevToolsInjector(){const e=window;e?.webMA&&delete e.webMA.fmtp}},hB=(e=>(e[e.ThreeStreamSimulcast=0]="ThreeStreamSimulcast",e[e.HardwareEncoder=1]="HardwareEncoder",e[e.Encode1080P=2]="Encode1080P",e[e.BroadcastMode=3]="BroadcastMode",e))(hB||{}),gB=class extends Vi{constructor(e,t){super(t),this.mediaType=e,this.logger=t,this.features={}}notify(){super.raiseChanged()}find(e){var t;return(t=this.features)[e]??(t[e]={})}set(e,t,i){const n=this.find(e);let r=!1;return void 0!==t&&n.server!==t&&(this.logger.safe.info(`Server support for [${this.mediaType}][${hB[e]}] changed from ${n.server} to ${t}`),n.server=t,r=!0),void 0!==i&&n.client!==i&&(this.logger.safe.info(`Client support for [${this.mediaType}][${hB[e]}] changed from ${n.client} to ${i}`),n.client=i,r=!0),r}toggleServer(e,t){return!!this.set(e,t,void 0)&&(this.notify(),!0)}toggleClient(e,t){return!!this.set(e,void 0,t)&&(this.notify(),!0)}toggle(e,t){return!!this.set(e,t,t)&&(this.notify(),!0)}hasAnySupport(e){const t=this.find(e);return!0===t.client||!0===t.server}hasFullSupport(e){const t=this.find(e);return!0===t.client&&!0===t.server}hasClientSupport(e){return!0===this.find(e).client}hasServerSupport(e){return!0===this.find(e).server}},pB=class extends Vi{constructor(e){super(e),this.logger=e,this.modalities={Video:new gB("Video",this.logger),ScreenShare:new gB("ScreenShare",this.logger)},this.blocked=new Set;for(const e of Object.keys(this.modalities))this.modalities[e].changed((()=>{this.notify(this.modalities[e],!1)}))}notify(e,t){this.blocked.has(e.mediaType)&&!0!==t||(this.blocked.add(e.mediaType),this.logger.safe.info(`Notify: ${e.mediaType}`),this.event("onVideoFeaturesChanged").raise(e),this.blocked.delete(e.mediaType))}manageFeatureSupport(e){for(const e of Object.values(this.modalities))this.blocked.add(e.mediaType);e();for(const e of[...this.blocked])this.notify(this.modalities[e],!0)}get(e){if(!this.modalities[e])throw this.logger.safe.error(`Unsupported media type: ${e}`),new Error(`Unsupported media type: ${e}`);return this.modalities[e]}},mB=class e{constructor(e){this.configProvider=e}getVideoControlMessage(t,i,n){const r={controlVideoStreaming:{sequenceNumber:++e.sequence,globalTimeStamp:(new Date).toString(),controlInfo:[{control:"start",sourceId:i,streamMsid:t}]}};return n&&(r.controlVideoStreaming.controlInfo[0].fmtParams=vO(n)),r}getSourceRequestMessage(t,i,n,r){if(!n)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const s={sourceId:i,streamMsid:t,fmtParams:n};return s.subStreamIndex=r,{type:"sr",controlVideoStreaming:{sequenceNumber:++e.sequence,controlInfo:s}}}getSignalingSourceRequestMessage(t,i,n,r,s){if(!r)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const a={sourceId:i,streamMsid:t,fmtParams:r};return a.subStreamIndex=s,{applyChannelParameters:{multiChannelParameter:{mids:[n],mediaParameter:JSON.stringify({controlVideoStreaming:{sequenceNumber:++e.sequence,controlInfo:a}})}}}}getBandwidthInfoMessage(e){return{type:"ssbwe",BwMessage:e}}getMaxVideoSendCapabilitiesMessage(e){const{streamMIDs:t,capabilities:i,useMax:n,sendMaxFs:r,sendMaxMbps:s}=e;let a=Ln(i.maxWidth),o=Ln(i.maxHeight);n&&(a=o=Math.max(a,o));const l={[Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH]:i.maxFps,[Gi.VIDEO_CAPABILITIES.MAX_WIDTH]:a,[Gi.VIDEO_CAPABILITIES.MAX_HEIGHT]:o};return r&&(l[Gi.VIDEO_CAPABILITIES.MAX_FS_PATH]=i.maxFs),s&&(l[Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=i.maxMbps),{applyChannelParameters:{multiChannelParameter:{mids:t,mediaParameter:JSON.stringify({maxVideoSendCapabilities:{caps:l}})}}}}getMaxVideoSendCapabilitiesContent(e,t,i,n){const r={};if(i){let e=Ln(i.maxWidth),t=Ln(i.maxHeight);this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight&&(e=t=Math.max(e,t)),r[Gi.VIDEO_CAPABILITIES.MAX_WIDTH]=e,r[Gi.VIDEO_CAPABILITIES.MAX_HEIGHT]=t,r[Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH]=i.maxFps,this.configProvider.config.maxSendVideoCapabilities.sendMaxFs&&(r[Gi.VIDEO_CAPABILITIES.MAX_FS_PATH]=i.maxFs),this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps&&(r[Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=i.maxMbps)}else n&&[Gi.VIDEO_CAPABILITIES.MAX_WIDTH,Gi.VIDEO_CAPABILITIES.MAX_HEIGHT,Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH,Gi.VIDEO_CAPABILITIES.MAX_FS_PATH,Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH].forEach((e=>{n[e]&&(r[e]=n[e])}));const s=e.getSimulcastContext();let a,o,l,c;if(s&&s.config.layerScaleFactors.length>2&&(a=s.config.layerScaleFactors.length,o=s.config.layerScaleFactors.length,t.hasClientSupport(0)||(o=2),this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&i&&i.maxFs<this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&(o=2)),void 0!==a&&(r[Gi.VIDEO_CAPABILITIES.MAX_STREAMS]=a),void 0!==o&&(r[Gi.VIDEO_CAPABILITIES.MAX_LAYERS]=o),t.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnServer){const e=this.configProvider.config.broadcastMode;e.priorityLayoutMinFS&&e.priorityLayoutMinFPS&&(c=e.priorityLayoutMinFS,c*=e.priorityLayoutMinFPS),e.priorityLayoutMinBitrate&&(l=e.priorityLayoutMinBitrate)}return l&&(r[Gi.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_BITRATE]=l),c&&(r[Gi.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_MBPR]=c),t.hasClientSupport(1)&&this.configProvider.config.preferredHardwareLadderType&&(r[Gi.VIDEO_CAPABILITIES.LADDER_TYPE]=this.configProvider.config.preferredHardwareLadderType),r}getMultiChannelParametersMessage(e,t){return{applyChannelParameters:{multiChannelParameter:{mids:e,mediaParameter:JSON.stringify(t)}}}}};mB.sequence=0;var fB=mB,vB=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.sender=i,this.mediaControlPlane=n,this.messageGenerator=new fB(this.configProvider),this.lastVideoSendMaxCapabilities={}}sendSourceRequest(e,t,i,n,r){if(this.configProvider.config.useApplyChannelParametersForSourceRequests){const s=this.messageGenerator.getSourceRequestMessage(e,t,n,r),a=this.messageGenerator.getSignalingSourceRequestMessage(e,t,i,n,r);return this.sendMessage("ApplyChannelParametersSourceRequest",s,a)}const s=this.messageGenerator.getVideoControlMessage(e,t,n?.[0]);return this.sendMessage("ControlVideoStreaming",s)}sendMaxVideoSendCapabilities(e,t){const i=this.messageGenerator.getMaxVideoSendCapabilitiesMessage({streamMIDs:e,capabilities:t,sendMaxFs:this.configProvider.config.maxSendVideoCapabilities.sendMaxFs,sendMaxMbps:this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps,useMax:this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight});return this.sendMessage("ApplyChannelParametersVideoCapabilities",i)}async sendBandwidthInfo(e){const t=this.messageGenerator.getBandwidthInfoMessage(e);return this.mediaControlPlane?.sendMsg(t)}sendMaxVideoSendCapabilitiesV2(e,t,i){if(void 0===this.lastVideoSendMaxCapabilities[e.getMid()]){if(!i)return this.logger.safe.info("Skip sending empty max-capabilities message"),Promise.resolve();this.lastVideoSendMaxCapabilities[e.getMid()]={}}const n=this.messageGenerator.getMaxVideoSendCapabilitiesContent(e,t,i,this.lastVideoSendMaxCapabilities[e.getMid()]);if(i||!an(this.lastVideoSendMaxCapabilities[e.getMid()],n)){this.lastVideoSendMaxCapabilities[e.getMid()]=n;const t=this.messageGenerator.getMultiChannelParametersMessage([e.getMid()],{maxVideoSendCapabilities:{caps:n}});return this.sendMessage("ApplyChannelParametersVideoCapabilities",t)}return this.logger.safe.info("Skip sending duplicate max-capabilties message"),Promise.resolve()}async sendMessage(e,t,i){let n;return"ApplyChannelParametersSourceRequest"===e&&(n=t.controlVideoStreaming.sequenceNumber),this.logger.safe.info(`sending video control message: ${JSON.stringify(t)}`),this.sender.send(e,t,n,i)}},SB=0,yB=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc-"+ ++SB),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.webrtcAdapter=(e=>void 0!==Mp.window.webkitRTCPeerConnection?new VU(e):new HU)({global:this.context.maContext,configProvider:this.configProvider}),this.iceHostCandidateOnly=this.multiParty&&un("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new GU({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:!1}),this.sessionDescription=wL.build({sdpTransform:new this.webrtcAdapter.SdpTransform(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=un("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new Yx({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.stats=new vU(this.logger.createChild("stats"),this.configProvider,void 0,this.mediaManager,this.multiParty),this.maxResolution=this.multiParty?Hn.Send.getResolutionByFs(this.configProvider.config.webrtcMultipartyMaxScalingFs):Hn.Send.getResolutionByFs(this.configProvider.config.webrtcMaxScalingFs),this.qualityManager=new XU(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:(e,t,i)=>this.applyCapabilitiesForModality(e,t,i)},this.stats,void 0,this.configProvider),this.localVideoStreamWatcher=new aB(this.logger,this.configProvider,this.context.callDeviceManager),this.activeSpeakerManager=new Jx(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager")),this.senders={},this.negotiationQueue=new tk(this.logger),this.negotiationEmulator=new zU(this.logger.createChild("negotiationEmulator"),this.webrtcAdapter.RTCSessionDescription,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.streamConfigurationHandler=new uB(this.logger,this.negotiationEmulator,this.qualityManager,null,this.configProvider,this.stats),this.mediaMessageController=new vB(this.logger,this.configProvider,{send:this.context.sendWebRtcMediaNotificationAsyncCallback}),this.toBeCalledAfterConnected=[],this.iceTransportPolicy=this.configProvider.config.iceTransportPolicyForced||this.context.config.iceTransportPolicy||Gi.ICE_TRANSPORT_POLICY.all,this.isMuteHold=!1,this.peerConnection=null,this.mediaStreams=new Map,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new Kt,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=cB({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=un("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new cO(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.remoteVideoResolutionManager=new eB(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.stats),this.remoteVideoManager=new sB(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 Kt,this.ssrcGenerator=new WO,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=e.getUfdManager(),this.stats.on("onStatisticsChanged",(e=>{this.remoteVideoManager.processLegacyStats(e),this.localVideoStreamWatcher?.onStatisticsChanged(e),this.updateQualityLevels(e)})),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),this.setSubsForSubscriptionManager(),this.localVideoStreamWatcher.on("onVideoCaptureFreeze",(e=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"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(e,t){}setParticipantSpatialAudioPositions(e,t){}getAcceptedTypes(){return this.allowedMediaContentType}clone(t=!1){const i=tn(this.context);i.config=tn(this.context.config),i.config.webrtcMediaContentType=this.mediaContentType,i.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,t?i.config.isConference=!0:(i.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(i.config.webrtcIceGatheringTimeoutIncreased=!0));const n=new e(i,this.callId,this.callback);return this.relayManagerProvider&&(n.relayManagerProvider=this.relayManagerProvider),n.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,n}setInternals(e){e.subscriptionManager&&(this.subscriptionManager&&this.subscriptionManager.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setStreamProvider({getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager&&e.remoteVideoManager.moveRenderers(this.remoteVideoManager)}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.stats.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.stats.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,s)=>this.stats.addSubscriptionEvent(e,t,i,n,null,r,s))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.stats.addSubscriptionEvent(e,t,i,n,r)))]}move(e,t){e.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager}),e.muteHold(this.isMuteHold,t),this.doAudioMute?e.muteInputAsync(t):e.unmuteInputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMuteAsync with mute state ${t}, audio stream exists: ${!!this.audioStream}`),"Audio"===e&&this.audioStream?this.audioStream.setMuted(t,i):"Video"===e&&this.videoStream?this.videoStream.setMuted(t,i):"ScreenShare"===e&&this.displayStream&&this.displayStream.setMuted(t,i),this.updateQualityLevels(this.stats.getLastStatistics())}setCallConstraints(e,t){return Promise.reject(new Error("Not supported"))}configureModalitiesAsync(e,t){const i=this.configuredModalitiesPromise.then((()=>{if(!e||!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const i=!this.configuredModalities||!em(e,this.negotiatedModalities);return this.configuredModalities=e,this.logger.safe.info(`[${t}] configure modalities`,`audio: ${e.audio}`,`video: ${e.video}`,`sharing: ${e.sharing}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?this.peerConnection.signalingState:"-"}`,`needNewRenegotiation: ${i}`),i&&this.triggerRenegotiation(!1,t),this.configuredModalities}));return this.configuredModalitiesPromise=i.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${tt(e)}`)})).then((()=>{})),i.then((()=>{}))}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}getSubscriptionManager(){return null}createAudioElement(e){}createOfferAsync(e){const t=this.negotiationQueue.add((()=>new Promise((t=>{this.logger.safe.info(`[${e}] 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[Gi.MODALITY.data]&&this.multiParty&&(this.offeredModalities[Gi.MODALITY.data]=Gi.MEDIA_STATE.inactive),Yp(this.offeredModalities)&&!Xi(this.negotiatedModalities)&&Object.keys(this.offeredModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.offeredModalities[e]})),t(this.updatePeerConnectionStreamsAsync(this.offeredModalities,!0,!0,e).then((()=>{const t=this.createNegotiationConstraints(this.offeredModalities);return this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)} constraints: ${JSON.stringify(t)}`),this.peerConnection.createOffer(t)})).then((t=>{this.logger.unsafe.debug(`[${e}] create [offer] offer from peer connection`,"sdp:",t.sdp);const i=this.sessionDescription.createLocalOffer(t.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(e),this.stats.startWaitingForStreamStart(this.offeredModalities);const n=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"offer"});return this.setupIceGatheringTimeout(e),Promise.all([this.peerConnection.setLocalDescription(n),this.iceCandidatesDeferred.promise])})).then((()=>{const t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);t.updateModalities(this.offeredModalities),this.checkIceCandidates(t);const i=t.toOffer();this.logger.unsafe.debug("CREATE OFFER","sdp:",i);const n={blob:i,contentType:this.mediaContentType};return""===this.configProvider.config.webrtcRequiredFeatures||this.multiParty||(n.requiredFeatures=this.configProvider.config.webrtcRequiredFeatures),this.configProvider.countryCode&&(n.clientLocation=this.configProvider.countryCode),this.doRetargetIfNeeded(n,t,e),n})))}))),e);return this.resetNegotiationQueue(e),t}processOfferAsync(e,t){const i=this.negotiationQueue.add((()=>new Promise((i=>{const n=e.blob;if(this.logger.unsafe.debug(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&(on(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),e.requiredFeatures){const t=this.configProvider.config.webrtcRejectedFeatures.split(",");ln(e.requiredFeatures.split(","),t)}this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.canTriggerRenegotiation=!1,this.offeredModalities=qp(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 r=Promise.resolve(this.offeredModalities);if(Wp(this.offeredModalities.video)||Kp(this.offeredModalities.video)||Wp(this.offeredModalities.sharing)||Kp(this.offeredModalities.sharing)){const e=this.offeredDescription.getVideoCodecs();r=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((i=>{if(!i.codecs.some((t=>e.some((e=>t.mimeType===e))))){this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`);const e=tn(this.offeredModalities);return this.disabledModalities.video=e.video,this.disabledModalities.sharing=e.sharing,e.video=void 0,e.sharing=void 0,e}return this.offeredModalities})).catch((e=>(this.logger.safe.error(`[${t}] failed to get video capability ${tt(e)}`),this.offeredModalities)))}i(r.then((e=>(this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(e)}`),e))))}))),t);return this.resetNegotiationQueue(t),i}createAnswerAsync(e,t){return new Promise((i=>{if(e)return void i({blob:"",contentType:this.mediaContentType});this.logger.safe.info(`[${t}] 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 n=Qp(this.offeredModalities,this.negotiatingModalities);const r=this.offeredDescription.clone();i(this.updatePeerConnectionStreamsAsync(n,!0,!1,t).then((()=>this.handleCodecSwitchUnsupported(t))).then((()=>{this.offeredDescription.setModalities(n);const e=this.offeredDescription.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources();const i=new this.webrtcAdapter.RTCSessionDescription({sdp:e,type:"offer"});return this.updateDescriptor(i,r),this.logger.unsafe.info(`[${t}] create [answer] set remote description`,"negotiated:",n,"sdp:",i.sdp),this.peerConnection.setRemoteDescription(i)})).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.updatePeerConnectionStreamsAsync(n,!1,!0,t)))).then((()=>(this.handleSharingRecvCapabilities(r),this.handleVideoRecvCapabilities(r)))).then((()=>this.peerConnection.createAnswer())).then((e=>{this.logger.unsafe.debug(`[${t}] create [answer] answer from peer connection`,"sdp:",e.sdp);const i=this.sessionDescription.createLocalAnswer(e.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(t),this.stats.startWaitingForStreamStart(n);const r=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"answer"});return this.setupIceGatheringTimeout(t),Promise.all([this.peerConnection.setLocalDescription(r),this.iceCandidatesDeferred.promise])})).then((()=>{const e=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);e.updateModalities(n),this.checkIceCandidates(e);const i=e.toAnswer();n=e.getModalities(),Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,n)||this.triggerRenegotiation(!0,t),this.setNegotiatedModalities(n),this.stats.sessionInfo.setBweType(e.getBweType()),this.logger.unsafe.debug("CREATE ANSWER","sdp:",i);const r={blob:i,contentType:this.mediaContentType};return this.configProvider.countryCode&&(r.clientLocation=this.configProvider.countryCode),r})))}))}processAnswerAsync(e,t,i){const n=e.blob;if(this.logger.unsafe.debug(i?"PROCESS PRANSWER":"PROCESS ANSWER","sdp:",n),i)return this.logger.safe.info(`[${t}] process [pranswer] ignored`),Promise.resolve();this.mediaContentType=e.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType);const r=this.sessionDescription.createRemoteAnswer(n),s=r.clone(),a=qp(r.getModalities());this.setNegotiatedModalities(a),r.setModalities(this.negotiatedModalities);const o=r.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources(),this.stats.sessionInfo.setBweType(r.getBweType());const l=new this.webrtcAdapter.RTCSessionDescription({sdp:o,type:"answer"});return this.updateDescriptor(l,s),this.logger.unsafe.info(`[${t}] process [answer] set remote description`,"negotiated:",this.negotiatedModalities,"sdp:",l.sdp),this.peerConnection.setRemoteDescription(l).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.negotiatedModalities))).then((()=>(this.handleSharingRecvCapabilities(s),this.handleVideoRecvCapabilities(s)))).then((e=>{e&&this.triggerRenegotiation(!0,t)}))}completeNegotiationAsync(e){return new Promise((t=>{this.mediaManager.commit();const i=this.configuredModalities,n=this.forceMediaStreamUpdate&&!Yp(this.negotiatedModalities)||!Xp(this.configProvider,i,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,r=!n;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${r} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),n&&this.triggerRenegotiation(!1,e),this.negotiationCompletedPromise.resolve(),t({isComplete:r,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})}))}rejectNegotiationAsync(e,t,i=!1){return Promise.resolve().then((()=>{if(this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${tt(e)} 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(`[${t}] rolling back local description`),this.configProvider.config.webrtcHandleRollback?(this.logger.safe.info(`[${t}] rolling back using local renegotiation`),this.negotiationEmulator.renegotiateNow().then((()=>{this.logger.safe.info(`[${t}] rolling back using local complete`)}))):this.peerConnection.setLocalDescription(new this.webrtcAdapter.RTCSessionDescription({type:"rollback"}));this.logger.safe.error(`[${t}] 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((e=>{this.removeTrackByMediaType(e),this.disposeStreamByMediaType(e)})),this.registerLocalStreams()})).then((()=>(i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})))}startMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}completeMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}rejectMediaDescriptionsUpdateAsync(e,t){return Promise.reject(new Error("Not supported"))}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){return this.terminated||(this.statisticsReport=this.statisticsReport.then((()=>this.stats.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))),this.statisticsReport}getLastKnownStats(e=!1){return this.stats.getReport(!1,e)}muteHold(e,t){this.isMuteHold=e;const i=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing].filter((e=>Wp(this.negotiatedModalities[e])&&(e!==Gi.MODALITY.audio||!this.doAudioMute)));for(const n of i)this.setMute(sm(n),e,t)}async muteInputAsync(e){this.doAudioMute=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.doAudioMute=!1,this.setMute("Audio",!1,e)}muteOutputAsync(e){return this.audioRenderer.setMuted(!0,e),Promise.resolve()}unmuteOutputAsync(e){return this.audioRenderer.setMuted(!1,e),Promise.resolve()}async getSpeakerVolume(e){return this.audioRenderer.getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.audioRenderer.setSpeakerVolume(e,t)}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(e=be()){const t=new Kt;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}onDeviceEvent(e){this.stats.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&(this.audioRenderer&&this.audioRenderer.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),Yp(this.negotiatedModalities)||(this.forceMediaStreamUpdate=!0,this.triggerRenegotiation(!0)))}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.stats.setTerminated(),this.canTriggerRenegotiation=!1,this.cleanUp(e);try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${tt(t)}`)}finally{this.stats.dispose(),this.terminated=!0}}processNotification(e,t){"DominantSpeakerInfo"===e&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(t.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===e&&this.streamConfigurationHandler.handleMessage(t)}cleanUp(e){this.negotiationQueue.dispose(),this.localVideoStreamWatcher.dispose(),this.remoteVideoManager.dispose(),this.resetPeerConnection(e),this.subscriptionManagerSubs.forEach((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(e){this.logger.safe.info(`[${e}] 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(e),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(e=be()){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new Kt,e)}setNegotiationPromise(e,t=be()){this.terminated||(this.negotiationCompletedPromise=e,this.negotiationQueue.add(this.negotiationCompletedPromise,t))}updateQualityLevels(e){if(!e)return;this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel});const t=!(!e.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",t?"Bad":"Good")}triggerRenegotiation(e,t=be()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(t)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(e){if(!this.configuredModalities)throw new Error(e)}addTrack(e,t,i){if(!e)return;const n=this.modalityByMediaType(i);if(this.logger.safe.info(`add media track kind: ${e.kind} id: ${e.id}`),this.senders[n])throw new Error("track already created, modality:"+n+", kind:"+e.kind+", id:"+e.id);"closed"!==this.peerConnection.iceConnectionState&&(this.senders[n]=this.peerConnection.addTrack(e,t))}registerMediaSources(){const e=[];if(this.mediaStreams.forEach(((t,i)=>{const n={sourceId:this.getSourceIdForStream(t),defaultSSRC:this.ssrcs[i].min,modality:this.modalityByMediaType(i)};e.push(n)})),this.qualityManager.updateRegisteredSources(e),this.videoStream){const e=this.videoStream.getResolution();this.qualityManager.setCurrentResolution(new Bn(e.width,e.height))}}updateStream(e,t){return e.start().then((()=>{try{const i=this.mediaStreams.get(t);if(i&&e.isSameStream(i))return e.dispose(),null;if(this.updateSsrcRangeForMediaType(t),this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),!this.peerConnection)return e.dispose(),null;if(this.addTrack(e.rawTrack,e.rawStream,t),e.onApplyConstraints=i=>{this.removeTrackByMediaType(t),i.then((()=>{this.addTrack(e.rawTrack,e.rawStream,t),this.registerLocalStreams(),this.mediaManager.updateMediaEntitiesWithLocalTracks()}))},this.mediaStreams.set(t,e),"Video"===t){const e=[this.getMediaTrackInfo(t)];this.localVideoStreamWatcher.startWatching(e)}}catch(i){throw this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),e.dispose(),i}}))}getSourceIdForStream(e){const t=e.rawStream.getTracks()[0].id,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}updatePeerConnectionStreamsAsync(e,t,i,n){const r=Wp(this.negotiatedModalities.audio),s=Wp(this.negotiatedModalities.video),a=Wp(this.negotiatedModalities.sharing),o=Yp(this.negotiatedModalities),l=Wp(e.audio),c=Wp(e.video),d=Wp(e.sharing),u=Yp(e);return o||u||(this.stats.onSendersChanged("Audio",l),this.stats.onSendersChanged("Video",c),this.stats.onSendersChanged("ScreenShare",d)),this.assurePeerConnectionAsync(n).then((async()=>{if(this.logger.safe.info("updatePeerConnectionStreamsAsync","pc state",this.peerConnection.signalingState,"hold","[",o,"->",u,"]","audio","[",r,"->",l,"]","video","[",s,"->",c,"]","sharing","[",a,"->",d,"]"),o!==u){if(this.videoStream&&this.videoStream.setHold(u),this.audioStream&&this.audioStream.setHold(u),this.displayStream&&this.displayStream.setHold(u),u)return;if(!u&&this.audioStream){this.removeTrackByMediaType("Audio");const e=this.audioStream.clone();this.audioStream.dispose(),this.mediaStreams.set("Audio",e),this.addTrack(this.audioStream.rawStream.getAudioTracks()[0],this.audioStream.rawStream,"Audio")}}if((r!==l||s!==c||a!==d||this.forceMediaStreamUpdate)&&(i&&(this.forceMediaStreamUpdate=!1),t&&(this.logger.safe.info("not using any media(track api) track, remove all senders"),l||(this.removeTrackByMediaType("Audio"),this.disposeStreamByMediaType("Audio")),i&&c||(this.removeTrackByMediaType("Video"),this.disposeStreamByMediaType("Video")),i&&d||(this.removeTrackByMediaType("ScreenShare"),this.disposeStreamByMediaType("ScreenShare"))),i)){const e=[];if(c){const t=await this.deviceManager.getVideoStream(!1);e.push(this.updateStream(t,"Video"))}if(d){const t=this.deviceManager.getDisplayStream();e.push(this.updateStream(t,"ScreenShare"))}if(l){const t=await this.deviceManager.getAudioStream(!1);e.push(this.updateStream(t,"Audio").then((()=>{this.audioStream.setMuted(this.doAudioMute)})))}return Promise.all(e).then((()=>this.registerLocalStreams()))}}))}getMediaTrackInfo(e){const t=this.modalityByMediaType(e),i=this.mediaStreams.get(e).rawStream.getTracks()[0].id;return i||this.logger.safe.error(`No media track for modality found: ${t}`),{trackId:i,modality:t}}getSsrcRangeForMediaType(e){const t={min:1,max:1};switch(e){case"Audio":return this.ssrcGenerator.nextAudioStreamSsrc();case"Video":case"ScreenShare":return this.ssrcGenerator.nextVideoStreamSsrc();default:return t}}updateSsrcRangeForMediaType(e){"Video"!==e&&"ScreenShare"!==e||(this.ssrcs[e]=this.ssrcGenerator.nextVideoStreamSsrc())}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!1,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}registerLocalStreams(){const e=[];this.mediaStreams.forEach(((t,i)=>{e.push(this.getMediaTrackInfo(i))})),this.mediaManager.setLocalTracksInfo(e)}handleVideoRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&Kp(e.getModalities().video)){if(this.videoStream){const t=e.getVideoRecvCapabilities();if(!t)return this.logger.safe.error("No fmt params found for video modality"),Promise.resolve(!1);const i=this.generateReceiveCapabilities(t,this.videoStream);this.qualityManager.setMaxCapabilities([i])}this.logger.safe.error("remote endpoint didn't specify video receive capability")}return Promise.resolve(!1)}handleSharingRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&Kp(e.getModalities().sharing)&&this.displayStream){const t=e.getSharingRecvCapabilities();if(!t)return void this.logger.safe.error("No fmt params found for sharing modality");const i=this.generateReceiveCapabilities(t,this.displayStream);this.qualityManager.setMaxCapabilities([i])}}generateReceiveCapabilities(e,t){const i={ssrc:0,rid:"0",keyframe:!1,...e},n={causeId:be(),isSimulcast:!1,sourceId:this.getSourceIdForStream(t),capabilities:[i]};return this.logger.safe.info(`Generated receive capabilities for stream ${t.id}: ${JSON.stringify(n)}`),n}updateDescriptor(e,t){const i=t.getVideoRecvCapabilities(),n={sourceId:0,streamMsid:0,bandwidth:0};if(i&&this.videoStream&&!this.displayStream&&(n.sourceId=this.getSourceIdForStream(this.videoStream),n.streamMsid=this.videoStream.id,n.bandwidth=i.maxBr?i.maxBr:Number.MAX_VALUE),n.bandwidth>0){n.bandwidth=Math.floor(n.bandwidth/1200);const t=new Zx(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider);t.setControlItem(n),t.modifyDescriptor(e)}}removeTrackByMediaType(e){return this.removeTracksByModality(this.modalityByMediaType(e))}modalityByMediaType(e){switch(e){case"Audio":return Gi.MODALITY.audio;case"Video":return Gi.MODALITY.video;case"ScreenShare":return Gi.MODALITY.sharing;default:throw new Error(`Modality is not defined for media type: ${e}`)}}removeTracksByModality(e){this.forceKeyFramePromise&&"sharing"===e?this.forceKeyFramePromise.then((()=>{this.removeTracksByModality(e)})):e in this.senders&&(this.logger.safe.info(`remove sender track kind: ${this.senders[e].track.kind} track id: ${this.senders[e].track.id}`),"closed"!==this.peerConnection.iceConnectionState&&this.peerConnection.removeTrack(this.senders[e]),delete this.senders[e])}handleCodecSwitchUnsupported(e){return this.offeredDescription.isCodecSwitchSupported()?Promise.resolve():this.webrtcAdapter.RTCRtpReceiver.getCapabilities(Gi.MEDIA_TYPE.audio).then((e=>{const t=e.codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(t)})).catch((t=>{this.logger.safe.error(`[${e}] failed to set primary codec based on audio capability ${tt(t)}`)}))}disposeStreamByMediaType(e){const t=this.mediaStreams.get(e);t&&(this.mediaStreams.delete(e),t.dispose(),"Video"===e&&this.localVideoStreamWatcher.stopWatching())}disposeStreams(){this.mediaStreams.forEach(((e,t)=>this.disposeStreamByMediaType(t)))}assurePeerConnectionAsync(e){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 t={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};this.peerConnectionPromise=this.relayManagerProvider.getRelayManager().queryRelaysAsync(t).then((t=>{if(this.terminated)throw new Error("session already disposed");const i={optional:[]},n=Fx(t,this.configProvider.config),r=this.configureCrypto(i);this.configureCpuThreshold(i),this.logger.safe.info("create peer connection");const s=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle",a=this.peerConnection=new this.webrtcAdapter.RTCPeerConnection({iceServers:n,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,bundlePolicy:s,sdpSemantics:"plan-b",audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===r,offerExtmapAllowMixed:!1},i);this.negotiationEmulator.configure(a),this.stats.initialize(a),this.stats.sessionInfo.setIceServers(n),this.stats.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.stats.sessionInfo.setBundlePolicy(s);const o=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video"),l=this.webrtcAdapter.RTCRtpSender.getCapabilities("video");this.stats.setH264AvailableProfiles(o),this.stats.setSupportedH264Profiles(l,o),a.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${a.signalingState}`)},a.onsignalingstatechange=()=>{this.stats.sessionInfo.setSignalingConnectionState(a.signalingState),this.logger.safe.info(`onsignalingstatechange signalingState: ${a.signalingState}`)},a.onicecandidateerror=e=>{const[t,i]=[e.address,e.port];this.logger.safe.warn(`On ICE candidate error ${e.url} | ${t}:${i}: code ${e.errorCode}: ${e.errorText}`),this.isConnected()&&!this.iceCandidatesDeferred.isPending||this.stats.addIceCandidateError({address:t,port:+i,url:e.url,errorCode:e.errorCode,errorText:e.errorText})};const c=e=>{if(!this.isConnected())return this.logger.safe.info("onaddstream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>c(e)));const t=e.stream;this.logger.safe.info(`onaddstream stream: ${t.id}`);let i=this.mediaManager.getMediaEntityByRemoteStreamId(t.id);if(i||(this.logger.safe.info(`cannot find media entity with stream id ${t.id} trying to fallback`),t.getAudioTracks()[0]&&(i=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.audio)[0])),i){const e=this.createReceiveStream(t,i);this.receiveStreamCollection.add(e)}else this.logger.safe.error(`could not find media entity for an added stream: ${t.id}`)};a.onaddstream=c,a.ontrack=e=>{this.logger.safe.info(`ontrack track: ${e.track}`)};const d=e=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>d(e)));this.logger.safe.info(`onremovestream stream: ${e.stream.id}`),this.receiveStreamCollection.remove(e.stream.id)};a.onremovestream=d,a.onicecandidate=t=>{const i=t.candidate;if(i){const t=rm(i.candidate);this.logger.safe.info(`[${e}] onicecandidate candidate: prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1&&(this.stats.sessionInfo.setRelayCandidateInfo({priority:i.priority||i.candidate.split(" ")[3],time:Date.now()-this.iceRelayCandidatesGatherStartTime}),this.relayCandidateGathered=!0)}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const r=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,s=this.iceHostCandidateOnly||0===n.length;if(!i&&r||s){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.isConnected(),a.iceConnectionState,a.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.stats.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},a.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${a.iceGatheringState}`)},a.oniceconnectionstatechange=()=>{const e=be();if(!this.terminated){if(this.stats.sessionInfo.setIceConnectionState(a.iceConnectionState),this.logger.safe.info(`[${e}] oniceconnectionstatechange iceConnectionState: ${a.iceConnectionState} pc.signalingState: ${a.signalingState}`),"connected"===a.iceConnectionState||"completed"===a.iceConnectionState)this.onTransportConnected(e);else if("failed"===a.iceConnectionState){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${e}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(e);this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},e),this.configProvider.config.webrtcCloseAfterIceFailure&&a.close(),this.onTransportFailed()}"disconnected"===a.iceConnectionState?(this.onTransportDisconnected(e),this.startIceDisconnectedTimer(e)):this.clearIceDisconnectedTimer()}},this.multiParty&&(this.contributingSources=new $U(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new jU(this.logger.createChild("ContributingSourcesProvider"),a)))}))}return this.peerConnectionPromise}configureCrypto(e){let t=!1;const i=gm(this.context.configProvider,this.context.config.isPstnCall);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.stats.sessionInfo.setOfferedSrtpInfo(e),t=!e.dtls||e.sdes&&i}else t=i;return t&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1})),this.stats.sessionInfo.setNegotiatedSrtpInfo({dtls:!t,sdes:!!t}),t?0:1}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(e){if(this.logger.safe.info(`[${e}] audio transport connected`),this.stats.clearIceCandidateErrors(),!this.terminated)for(this.callbacks.onAudioStateChanged(Gi.STREAMING_STATE.active,e),this.callbacks.onTransportConnected&&this.callbacks.onTransportConnected(e);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}onTransportDisconnected(e){this.callbacks.onTransportDisconnected&&this.callbacks.onTransportDisconnected(e)}onTransportFailed(){this.callbacks.onTransportFailed&&this.callbacks.onTransportFailed()}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise CONSTANTS.MEDIAthis._ERROR.iceConnectionError`),this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=be()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}createNegotiationConstraints(e){function t(e){return!!e&&(Kp(e)||"inactive"===e)}return{offerToReceiveAudio:t(e.audio),offerToReceiveVideo:t(e.video)||t(e.sharing)}}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Kt}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Gi.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&("connected"===this.peerConnection.iceConnectionState||"completed"===this.peerConnection.iceConnectionState))return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}doRetargetIfNeeded(e,t,i){const n=t.isIceRestart();this.logger.safe.info(`[${i}] ICE restart: ${n}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&n&&!this.multiParty&&t.getSrtpInfo().sdes&&(e.newOffer=!0)}getAddedMediaTypes(e,t){e||(e={}),t||(t={});const i=[];return CB(e.audio,t.audio)&&i.push("Audio"),CB(e.video,t.video)&&i.push("Video"),CB(e.sharing,t.sharing)&&i.push("ScreenShare"),i}applyCapabilitiesForModality(e,t,i){return e===Gi.MODALITY.video?this.applyCapabilitiesForVideo(t,i[0]):e===Gi.MODALITY.sharing?this.applyCapabilitiesForSharing(t,i[0]):Promise.resolve(!1)}applyCapabilitiesForSharing(e,t){return this.displayStream?this.applyCapabilities(this.displayStream,t).then((i=>(this.stats.onMaxCapabilitiesApplied({causeId:e,modality:Gi.MODALITY.sharing,capabilities:[t]}),this.configProvider.config.webrtcAllowRestoreKeyframe?this.forceKeyframe(this.senders[Gi.MODALITY.sharing]).then((()=>i)):Promise.resolve(i)))):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no sharing stream is sent, no renegotiation`),Promise.resolve(!1))}forceKeyframe(e){if(!e)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 t=e.track;return this.forceKeyFramePromise=e.replaceTrack(null).then((()=>e.replaceTrack(t))).then((()=>{this.forceKeyFramePromise=null,this.logger.safe.info("Restoring keyframe finished")})).catch((e=>{this.forceKeyFramePromise=null,this.logger.safe.error(`Restoring keyframe failed: ${e}`),delete this.senders[Gi.MODALITY.sharing]})),this.forceKeyFramePromise}applyCapabilitiesForVideo(e,t){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,e,t):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no video is sent, no renegotiation`),Promise.resolve(!0))}scheduleApplyCapabilities(e,t,i){this.logger.safe.info("Queueing local renegotiation...");let n=!1;return this.negotiationQueue.add((()=>(this.logger.safe.info("############# LOCAL RENEGOTIATION START #############"),this.applyCapabilities(e,i).then((()=>{this.stats.onMaxCapabilitiesApplied({causeId:t,modality:Gi.MODALITY.video,capabilities:[i]}),n=!0})))),t),this.negotiationEmulator.renegotiate().then((()=>(this.logger.safe.info(`############# LOCAL RENEGOTIATION END. RESULT: ${n} #############`),n)))}applyCapabilities(e,t){return e?(this.logger.safe.info(`Changing resolution to ${JSON.stringify(t)}`),e.applyCapabilities(t)):(this.logger.safe.info(`Resolution ${JSON.stringify(t)} ignored, no stream is being sent`),Promise.resolve(!1))}onOptimalVideoReceiversCountChanged(e){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e)}getStreams(){return this.receiveStreamCollection.getStreams()}onStreamsChanged(e){this.streamsChangedListener=e}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(e){Gi.MODALITY.audio===e.getModality()&&(this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.play(e.getMediaStream())),this.notifyStreamsChanged()}streamRemoved(e){Gi.MODALITY.audio===e.getModality()&&this.audioRenderer.getStream()===e.getMediaStream()&&this.audioRenderer.stop(),this.notifyStreamsChanged()}setNegotiatedModalities(e){this.negotiatedModalities=e,this.stats.sessionInfo.setNegotiatedModalities(e)}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}createAudioRenderer(){this.audioRenderer=new ek(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 e=this.peerConnection;return e&&("connected"===e.iceConnectionState||"completed"===e.iceConnectionState)}isFailed(){return this.peerConnection&&("failed"===this.peerConnection.iceConnectionState||"closed"===this.peerConnection.iceConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(e,t){const i=this.configProvider.config.addFmtpToInitialSubscription?t.getLocalRecvCapabilities():null,n=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&t.getModality()!==Gi.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null;return new aO(e,null,t.getModality(),+t.getXSourceStreamId(),this,i,n)}requestSource(e,t,i){if(!this.multiParty)return Promise.resolve();const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);return!this.isMuteHold&&this.negotiatedModalities[n.getModality()]!==Gi.MEDIA_STATE.inactive||-1===t?this.negotiationCompletedPromise.isPending?this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>this.requestSource(e,t,i))):Promise.resolve().then((()=>this.mediaMessageController.sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex()))):Yt(10).then((()=>this.requestSource(e,t,i)))}getSessionConfig(){return this.configProvider}getUnmixedAudioProvider(){return null}};function CB(e,t){return!Wp(e)&&Wp(t)}var TB={build:(e,t,i)=>new yB(e,t,i)},EB=Z,bB=class extends Vi{constructor(e,t){super(t),this.logger=t,this.id=-1,this.parentId=-1,this.rawStream=null,this.rawTrack=null,this.deviceId=null,this.mediaType=e}start(){return this.logger.safe.debug("start"),Promise.resolve()}clone(){return this.logger.safe.debug("clone"),this}setMuted(e,t){this.logger.safe.debug("setMuted")}setHold(e){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(e){return this.logger.safe.debug("isSameStream"),e===this}applyCapabilities(e){return this.logger.safe.debug("applyCapabilities"),Promise.resolve(!1)}onApplyConstraints(e){this.logger.safe.debug("onApplyConstraints")}update(e){this.logger.safe.debug("update")}isActive(){return!1}isDisposed(){return!1}},_B=class e extends Vi{constructor(e,t,i,n,r){super(r),this.callDeviceManager=e,this.configProvider=t,this.sessionConfig=i,this.serialQueue=n,this.logger=r,this.mediaStreams={Audio:null,Video:null,ScreenShare:null},this.streamSubscriptions=new Map,this.deviceManagerSubscriptions=[],this.isNullAudioStream=!1}get currentMediaTypes(){return en(this.mediaStreams).filter((e=>!!this.mediaStreams[e]))}async getStreams(){return this.mediaStreams}useNullAudioStreamClient(){this.isNullAudioStream=!0}async update(e,t){const i=en(e).filter((t=>e[t]));return an(i,this.currentMediaTypes)?(this.logger.safe.info("Requested modalities have not changed. Do nothing"),om(this.mediaStreams)):(this.logger.safe.info(`Starting media session with modalities: ${JSON.stringify(e)}`),await this.updateStreams(i,t),this.subscribeOnDeviceManagerEvents(),om(this.mediaStreams))}async stopAsync(){this.logger.safe.info("Stopping streams async"),this.stop()}stop(){this.logger.safe.info("Stopping streams"),this.unsubscribeFromDeviceManagerEvents(),en(this.mediaStreams).forEach((e=>this.removeStreamByType(e)))}dispose(){this.stop(),super.dispose()}async updateStreams(e,t){const i=this.getAvailableMediaTypes(),n=(0,EB.intersection)(e,i),r=en(this.mediaStreams).filter((e=>this.mediaStreams[e])),s=t?[]:hn(n,r),a=hn(r,n);s.length&&this.logger.safe.info(`Adding media streams for types: ${JSON.stringify(s)}`),await Promise.all(s.map((async e=>{await this.addStream(e,!1),this.mediaStreams[e]&&this.event("onStreamAdded").raise(e)}))),a.length&&this.logger.safe.info(`Removing media streams for types: ${JSON.stringify(a)}`),a.forEach((e=>{this.event("onStreamRemoving").raise(e),this.removeStreamByType(e)}))}getAvailableMediaTypes(){const e=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices(),t=[];return e.microphone&&t.push("Audio"),e.camera&&t.push("Video"),t.push("ScreenShare"),t}async addStream(e,t){if(this.mediaStreams[e])return void this.logger.safe.warn(`Stream with type: ${e} is already registered`);const i=await this.getStream(e,t);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i}removeStreamByType(e){const t=this.mediaStreams[e];t?(this.unsubscribeFromMediaStreamEvents(t),t.dispose(),this.mediaStreams[e]=null):this.logger.safe.warn(`Stream with type: ${e} is not registered`)}async updateStream(e,t,i=!1){i&&"Audio"===e?await this.updateStreamWithEffect(e):(this.removeStreamByType(e),await this.addStream(e,t)),this.event("onStreamUpdated").raise(e)}async updateStreamWithEffect(e){const t=this.mediaStreams[e];t&&this.unsubscribeFromMediaStreamEvents(t);const i=await this.getStreamByMediaType(e,!0);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`updateStreamWithEffect. Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i,t?.dispose()}subscribeOnMediaStreamEvents(e){if(this.streamSubscriptions.has(e))return;const t=[];t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),this.streamSubscriptions.set(e,t)}unsubscribeFromMediaStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}async getStream(e,t){const i=this.mediaStreams[e];return i?(this.logger.safe.info(`Stream exists with id: ${i.id}, type: ${e}`),i):this.getStreamByMediaType(e,t)}async getStreamByMediaType(e,t){switch(e){case"Audio":return this.isNullAudioStream?new bB("Audio",this.logger.createChild("NullStreamClient")):this.getDeviceManagerByType("Audio").getAudioStream(t,"sessionStream");case"Video":return this.getDeviceManagerByType("Video").getVideoStream(t,"sessionStream",!1,this.sessionConfig.outgoingVideoMaxFS);case"ScreenShare":return this.getDeviceManagerByType("ScreenShare").getDisplayStream("sessionStream");default:throw new Error(`Media type is not supported: ${e}`)}}getMediaTypeForStream(e){const t=Object.keys(this.mediaStreams).find((t=>this.mediaStreams[t]===e));return t||this.logger.safe.error(`Media type is not found for stream: ${tt(e)}`),t}subscribeOnDeviceManagerEvents(){if(0!==this.deviceManagerSubscriptions.length)return;if(this.callDeviceManager.isVirtualDeviceEnabled){const e=this.callDeviceManager.on("onSelectedVirtualDevicesChanged",((e,t)=>{const i=e;if(!e.camera){this.logger.info("Virtual DeviceID for camera is undefined, falling back to default device");const{camera:e}=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices();i.camera=e}this.callDeviceManager.isModalityEnabled("Video")&&t.camera!==i.camera&&(this.logger.info("Updating stream for camera"),this.updateStreamForVirtualDeviceChange("Video")),this.callDeviceManager.isModalityEnabled("ScreenShare")&&t.screenshare!==i.screenshare&&(this.logger.info("Updating stream for screenshare"),this.updateStreamForVirtualDeviceChange("ScreenShare"))}));this.deviceManagerSubscriptions.push(e)}const e=this.callDeviceManager.getDefaultDeviceManager();this.deviceManagerSubscriptions.push(e.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),e.on("onStreamUpdateRequested",((e,t)=>this.requestStreamUpdate(e,!1,t))),e.on("onAudioSharingToggled",(e=>this.onAudioSharingToggled(e))))}unsubscribeFromDeviceManagerEvents(){0!==this.deviceManagerSubscriptions.length&&(this.deviceManagerSubscriptions.forEach((e=>e.dispose())),this.deviceManagerSubscriptions=[])}getMediaTypesToUpdate(e,t){const i=[];return this.currentMediaTypes.some((e=>"Audio"===e))&&e.microphone&&e.microphone!==t.microphone&&i.push("Audio"),!this.callDeviceManager.getSelectedDevices().camera&&this.currentMediaTypes.some((e=>"Video"===e))&&e.camera&&e.camera!==t.camera&&i.push("Video"),i}removeStream(e){const t=this.getMediaTypeForStream(e);this.removeStreamByType(t)}async onSelectedDevicesChanged(t,i){if(this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t,i))return void this.logger.safe.info("Device list is empty, permission workaround enabled");const n=this.getMediaTypesToUpdate(t,i);this.logger.safe.info(`Media types to update: ${JSON.stringify(n)}`),await Promise.all(n.map((e=>this.updateStream(e,!1))))}async onAudioSharingToggled(e){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&e)return this.updateStream("ScreenShare",!0)}async requestStreamUpdate(e,t,i=!1){if(this.currentMediaTypes.some((t=>t===e))||t)return this.logger.safe.debug(`UpdateStream with media type: ${e}, force: ${t}`),this.updateStream(e,t,i);this.logger.safe.debug(`Stream with media type: ${e} is not active. Do nothing`)}onStreamError(e,t){this.removeStream(e)}onStreamDisposing(e){this.removeStream(e)}static isDeviceListEmpty(e,t){return!e.camera&&!e.microphone||!t.microphone&&!t.camera}getDeviceManagerByType(e){return this.callDeviceManager.getDeviceManager(e)}async updateStreamForVirtualDeviceChange(e){return this.updateStream(e,!1)}};m([Uk()],_B.prototype,"getStreams",1),m([Uk()],_B.prototype,"update",1),m([Uk()],_B.prototype,"stopAsync",1),m([Uk()],_B.prototype,"onSelectedDevicesChanged",1),m([Uk()],_B.prototype,"onAudioSharingToggled",1),m([Uk()],_B.prototype,"requestStreamUpdate",1),m([Uk()],_B.prototype,"updateStreamForVirtualDeviceChange",1);var IB=_B,wB=Z,AB=[5e4,1e6,15e5,2e6,25e5,375e4,4e6],PB=[7e4,2e5,4e5,8e5,15e5,2499990,25e5],RB=class{constructor(e){this.logger=e,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladders={}}setAvailableBandwidth(e){this.availableBandwidth=e,this.logger.safe.debug(`Total available bandwidth updated: ${e}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(e,t){this.logger.safe.debug(`Receiver maxBr set: ${e}/${t}`),this.receivers.set(e,t),this.updateLayouts()}getReceiverCapabilities(){const e={};for(const t of Object.keys(this.receivers)){const i=this.receivers.get(t);i&&(e[t]=i)}return e}removeReceiver(e){this.logger.safe.debug(`Receiver maxBr removed: ${e}`),this.receivers.delete(e),this.updateLayouts()}getLayouts(){return this.currentLayout}setLadder(e,t){this.ladders[e]=t}updateLayouts(){const e=this.generateLayouts();(0,wB.isEqual)(e,this.currentLayout)||(this.currentLayout=e,this.logger.safe.debug(`Bandwidth distribution updated: ${tt(e)}`))}generateLayouts(){const e={},t={};for(const i of Object.keys(this.ladders)){const n=this.receivers.get(i);n&&(t[i]=n||Number.MAX_SAFE_INTEGER,e[i]=0)}let i=this.availableBandwidth,n=0;const r=()=>{if(!i)return!1;for(const e of Object.values(t))if(e)return!0;return!1};for(;r();){for(const r of Object.keys(e)){const s=this.ladders[r];let a=s[n]||s[s.length-1];a=Math.min(a,i,t[r]),e[r]+=a,i-=a,t[r]-=a}n++}return e}};function MB(e,t){const i=e.config.bandwidthAllocatorV2;let n=[],r=-1;for(const e of i.videoLadders)(t>=e.maxFS&&r<e.maxFS||-1===r)&&(n=e.ladder,r=e.maxFS);return n}var DB=class{constructor(e){this.logger=e,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladder=[],this.priority=[]}getReceiverCapabilities(){const e={};for(const t of Object.keys(this.receivers)){const i=this.receivers.get(t);i&&(e[t]=i)}return e}setAvailableBandwidth(e){this.availableBandwidth=e,this.logger.safe.debug(`Total available bandwidth updated: ${e}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(e,t){this.logger.safe.debug(`Receiver maxBr set: ${e}/${t}`),this.receivers.set(e,t),this.updateLayouts()}removeReceiver(e){this.logger.safe.debug(`Receiver maxBr removed: ${e}`),this.receivers.delete(e),this.updateLayouts()}getLayouts(){return this.currentLayout}setPriority(...e){this.priority=e}setLadder(e,t){this.logger.safe.info(`Set ladder for ${e}: ${JSON.stringify(t)}`);for(const t of this.ladder)delete t[e];-1===this.priority.indexOf(e)&&this.priority.push(e);for(let i=0;i<t.length;++i)i>=this.ladder.length&&this.ladder.push({}),this.ladder[i][e]=t[i]}updateLayouts(){const e=this.generateLayouts();(0,wB.isEqual)(e,this.currentLayout)||(this.currentLayout=e,this.logger.safe.debug(`Bandwidth distribution updated: ${tt(e)}`))}generateLayouts(){const e={};let t=this.availableBandwidth;for(const t of this.priority)this.receivers.get(t)&&(e[t]=0);for(let i=0;i<this.ladder.length&&t;++i){const n=this.ladder[i];for(const i of this.priority){const r=n[i];if(r&&this.receivers.get(i)){const n=Math.max(0,Math.min(r-e[i],t));t-=n,e[i]+=n}}}if(t){const i=t;let n=0;for(const e of this.priority)n+=this.receivers.get(e)??0;for(const r of this.priority){const s=this.receivers.get(r);if(s){const a=Math.min(t,Math.ceil(s*i/n));a&&this.logger.safe.info(`[AllocateSurplus][${r}] ${e[r]} + ${s} | ${t}`),t-=a,e[r]+=a}}}return e}},kB=class{constructor(e,t,i){this.timeout=t,this.logger=i,this.isFirstTimeDeferred=!0,this.internalCallback=t=>{this.logger.safe.debug(`Trigger reason: ${t}`),e()}}invoke(e){this.logger.safe.debug(`Schedule shouldDefer: ${e}`),this.isFirstTimeDeferred?e?(this.isFirstTimeDeferred=!1,this.startTimer()):(this.stopTimer(),this.internalCallback("request")):this.timeoutId&&e||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"))}},OB=class{constructor(e){this.logger=e,this.currentFrameSize=Hn.Send.initialResolution.fs}setAvailableBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Available bandwidth updated ${e}`),this.processEstimatedBandwidth(e))}setMaxFrameSize(e){this.logger.safe.debug(`SetMaxFrameSize ${e}`),e!==this.maxFrameSize?(this.maxFrameSize=e,this.lastSendBW?(this.logger.safe.debug(`Setting max frame size: ${e}`),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: ${e}`)}getFrameSize(){return this.currentFrameSize}processEstimatedBandwidth(e){if(this.logger.safe.debug(`Process estimated bandwidth ${e}`),0===e)return this.lastSendBW=0,void this.proposeResolution(0);const{lowRes:t,highRes:i}=Hn.Send.getResolutionForBitrate(e);this.logger.safe.debug("low",t,"hi",i);const n=e<this.lastSendBW?i.fs:t.fs;e<this.lastSendBW&&this.currentFrameSize<n?this.logger.safe.debug(`proposed resolution is above the existing one, so we should stay on the current resolution, last bw: ${e}`):(n&&this.proposeResolution(n),this.logger.safe.debug(`Updating last bw: ${e}`),this.lastSendBW=e)}proposeResolution(e){this.logger.safe.debug(`Propose resolution ${e}`);const t=this.maxFrameSize?Math.min(e,this.maxFrameSize):e;t!==this.currentFrameSize&&(this.currentFrameSize=t,this.logger.safe.debug(`Proposed new frame size: ${t} based on bandwidth: ${this.lastSendBW}`))}},NB=1e8,LB=[{bwe:2e5,param:5e5},{bwe:5e5,param:12e5},{bwe:8e5,param:25e5},{bwe:12e5,param:4e6}],xB=[{bwe:2e5,param:240},{bwe:3e5,param:405},{bwe:5e5,param:920},{bwe:9e5,param:2040}],FB=(e,t,i)=>{for(const n of i)if(t<n.bwe)return Math.min(e,n.param);return e},UB=(e,t,i=LB)=>FB(e,t,i),BB=(e,t,i=xB)=>FB(e,t,i),VB=class extends Vi{constructor(e,t,i){super(t),this.configProvider=e,this.logger=t,this.layoutsNumber=i,this.totalBandwidth=NB,this.totalBandwidthMax=0,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),this.outputLayouts=null,super.dispose()}setAvailableBandwidth(e){this.storeAvailableBandwidth(e),this.inputLayouts?(this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.debug("Layouts are not set. Skip update")}setLayouts(e,t){this.storeAvailableBandwidth(t),e.length===this.layoutsNumber?(this.logger.safe.debug(`Set layouts: ${JSON.stringify(e)}`),this.inputLayouts=this.getPrioritizedLayouts(e),this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.warn(`Incorrect number of layouts! ${JSON.stringify(e)}, expected ${this.layoutsNumber}`)}getLayouts(){return this.inputLayouts}getPrioritizedLayouts(e){return e}checkForChangesAndNotify(){const e=this.getLayouts();an(this.outputLayouts,e)?this.logger.safe.debug("Layout has not changed, skip update"):(this.outputLayouts=e.slice(),this.event("onLayoutsChanged").raise())}storeAvailableBandwidth(e){this.logger.safe.debug(`Set available bandwidth: ${e}`),this.totalBandwidth=e,this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth)}},HB=class extends VB{constructor(e,t){super(e,t,2),this.resolutionManager=new OB(this.logger.createChild("BWEControlledResolutionManager"))}getLayouts(){return this.hiFiLayout?[this.loFiLayout,this.hiFiLayout]:[this.loFiLayout]}dispose(){super.dispose(),this.resolutionManager=null}getHighLayoutBandwidth(e){const t=this.inputLayouts?.[0].maxBr||0,i=Math.max(e-t,0);this.logger.safe.debug(`Setting available bandwidth for layouts. High: ${i}, low: ${t||"not set"}, total: ${e}`);const n=this.configProvider.config.specCompliantSimulcast?.allowedBweOvershootRatio||1;return Math.floor(i*n)}recalculateLayouts(){const e=this.hiFiLayout,t=this.getHighLayoutBandwidth(this.totalBandwidth);this.resolutionManager.setAvailableBandwidth(t),this.resolutionManager.setMaxFrameSize(this.inputLayouts[1].maxFs),this.loFiLayout=this.getMinimalLayoutParams(this.inputLayouts),this.hiFiLayout=this.getHighLayoutParams(this.inputLayouts,t,this.loFiLayout),this.loFiLayout=this.adjustLowLayoutBasedOnHighLayout(this.hiFiLayout,this.loFiLayout,e)}adjustLowLayoutBasedOnHighLayout(e,t,i){return this.configProvider.config.useMediaQualityControllerForceKeyFrame&&!e&&i&&(this.logger.safe.debug("Forcing kayframe on low layout due to disabling high layout"),t.keyframe=!0),e?(t.maxBr===e.maxBr&&t.maxBr--,t):t}getPrioritizedLayouts(e){return e.sort(((e,t)=>e.maxFs-t.maxFs?e.maxFs-t.maxFs:e.maxFps-t.maxFps))}getHighLayoutParams(e,t,i){const n=e[1];if(n.maxBr<=t)return this.logger.safe.debug(`High layout bandwidth suits requested caps. Applying as-is: ${JSON.stringify(n)}`),n;const r={...e[1],maxFs:this.resolutionManager.getFrameSize(),maxBr:Math.min(t,e[1].maxBr),maxFps:e[1].maxFps},s=r.maxBr<i.maxBr||r.maxFs<i.maxFs||r.maxFs===i.maxFs&&r.maxFps<=i.maxFps,a=`Potential high layout: ${JSON.stringify(r)}`;return!this.hiFiLayout&&s?(this.logger.safe.debug(`High layout is already disabled. Do nothing. ${a}`),null):this.hiFiLayout&&s?(this.logger.safe.debug(`High layout gets disabled. ${a}`),null):(this.hiFiLayout&&an(r,this.hiFiLayout)?this.logger.safe.debug(`High layout has not been changed. Do nothing. ${a}`):this.hiFiLayout?this.logger.safe.debug(`High layout updated. ${a}`):this.logger.safe.debug(`High layout enabled. ${a}`),r)}getMinimalLayoutParams(e){const t=Math.min(e[0].maxBr,e[1].maxBr),i=this.configProvider.config.specCompliantSimulcast.maxBrControlEnabled?UB(t,this.totalBandwidth,this.configProvider.config.specCompliantSimulcast.bitrateToBweTable):t;return{...e[0],maxBr:i,maxFps:Math.min(e[0].maxFps,e[1].maxFps),maxFs:Math.min(e[0].maxFs,e[1].maxFs)}}},$B=class extends VB{constructor(e,t,i){super(t,i,1),this.couldLimitFs=e}getLayouts(){return[this.layout]}recalculateLayouts(){let e=this.inputLayouts[0].maxFs;if(this.configProvider.config.specCompliantSimulcast.allowResLimit&&this.couldLimitFs&&this.totalBandwidthMax){const t=this.configProvider.config.specCompliantSimulcast.fsToBweTable;e=BB(this.inputLayouts[0].maxFs,this.totalBandwidthMax,t)}const t=this.configProvider.config.specCompliantSimulcast.bitrateToBweTable,i=UB(this.inputLayouts[0].maxBr,this.totalBandwidth,t);this.layout={...this.inputLayouts[0],maxFs:e,maxBr:i}}},jB=class extends Vi{constructor(e){super(e),this.logger=e,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(e){this.logger.safe.debug(`Available bandwidth updated ${e}`)}setLayouts(e,t){this.layouts=e,this.setAvailableBandwidth(t)}getLayouts(){return this.layouts}},GB=(e,t)=>e.maxFs===t.maxFs?e.maxFps===t.maxFps?e.maxBr-t.maxBr:e.maxFps-t.maxFps:e.maxFs-t.maxFs,qB=(e,t)=>e.maxFs===t.maxFs?e.maxFps-t.maxFps:e.maxFs-t.maxFs,zB=class extends Vi{constructor(e,t,i){super(i),this.settings=e,this.configProvider=t,this.logger=i,this.totalBandwidthMax=0,this.totalBandwidth=NB,this.inputLayouts=null,this.outputLayouts=null,this.maxOutputLayers=0,this.ladder=[],this.settings.ladder?this.ladder.push(...this.settings.ladder):this.ladder.push(...Hn.Send.getResolutions())}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(e){this.updateAvailableBandwidth(e),this.update()}setLayouts(e,t){this.inputLayouts=e,this.updateAvailableBandwidth(t),this.update()}getLayouts(){return this.outputLayouts??[]}updateAvailableBandwidth(e){this.totalBandwidth!==Math.max(1,e)&&(this.logger.safe.debug(`Available bandwidth updated ${e}`),this.totalBandwidth=Math.max(1,e),this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth))}debug(e,t,...i){let n;const r=e=>({FS:e.maxFs,FPS:e.maxFps,BR:e.maxBr,KF:e.keyframe?"1":"0",id:`rid:${e.rid}`??0});n=Array.isArray(t)?t.map(r):r(t),this.logger.safe.info(`${e}: <${i.map((e=>JSON.stringify(e))).join("><")}> ${JSON.stringify(n)}`)}update(){const e=this.settings.allowedOvershoot||1,t=this.adjustLayout(this.inputLayouts,this.totalBandwidth*e);if(an(this.outputLayouts,t))this.logger.safe.debug("Layout has not changed, skip update");else{if(this.settings.allowLayerBitrateOverlap&&t.length&&t.length<this.inputLayouts.length&&(this.setMinimumQuality(t[0],this.inputLayouts),this.debug("SetMinimumQuality",t[0])),this.outputLayouts&&this.settings.forceKeyFrameWhenLayerIsRemoved&&this.outputLayouts.length>t.length)for(const e of t)this.logger.safe.debug(`Force key frame for rid:${e.rid}`),e.keyframe=!0;this.outputLayouts=t,this.maxOutputLayers=Math.max(this.maxOutputLayers,this.outputLayouts.length),this.event("onLayoutsChanged").raise()}}adjustLayout(e,t){const i=[];if(e.length){if(e=e.map((e=>Object.assign({},e))).sort(GB),this.debug("OriginalLayout",e),this.settings.minFrameSizeForSimulcast?.length>1){const t=this.settings.minFrameSizeForSimulcast;3===e.length&&2===t?.length&&e[e.length-1].maxFs<t[1]&&this.debug("DisableLowResStream",e.pop())}for(this.settings.highPriorityLayoutMinFS&&e.length>1&&e[e.length-1].maxFs>=this.settings.highPriorityLayoutMinFS&&this.settings.lowPriorityLayoutMaxFS?.length&&this.limitResolutionOnLowerSimulcastStreams(e);e.length>0&&t>0;){const n=e.shift();this.debug("Next",n,t),this.settings.allowLayerBitrateOverlap||this.setMinimumQuality(n,e);let r=t-n.maxBr;if(i.length>0){if(r<0&&this.degradeBitrateOrResolution(n,t)&&(this.debug("DegradeBitrateOrResolution",n),r=t-n.maxBr),r>=0){let e=!1;for(const t of i)if(e=qB(t,n)>=0,this.settings.allowLayerBitrateOverlap||n.maxBr<t.maxBr&&(e=!0),e){this.debug("Drop",n,i.length);break}e||(i.push(n),this.debug("Accept",n,i.length))}}else i.push(n),this.debug("Accept",n,i.length);t=r}this.debug("AdjustedLayout",i,t)}if(1===i.length)if(this.settings.minSinglecastBitrate||this.settings.singlecastLadder){const e=Math.max(this.settings.minSinglecastBitrate??this.totalBandwidth,this.totalBandwidth);this.settings.forceSinglecastLadder&&this.settings.singlecastLadder?this.forceLadder(i[0],e,this.settings.singlecastLadder)&&this.debug("ForceSinglecastLadder",i[0],e):i[0].maxBr>e&&this.degradeBitrateOrResolution(i[0],e,this.settings.singlecastLadder)&&this.debug("DegradeSinglecast",i[0],e)}else{if(this.settings.limitMaxResolution&&this.maxOutputLayers<=1){const e=this.configProvider.config.specCompliantSimulcast?.fsToBweTable;i[0].maxFs=BB(i[0].maxFs,this.totalBandwidthMax,e),this.debug("LimitMaxFS",i[0],this.totalBandwidthMax)}if(this.settings.limitMaxBitrate){const e=this.configProvider.config.specCompliantSimulcast?.bitrateToBweTable;i[0].maxBr=UB(i[0].maxBr,this.totalBandwidth,e),this.debug("LimitMaxBitrate",i[0],this.totalBandwidth)}}return i}limitResolutionOnLowerSimulcastStreams(e){const t=e.pop();if(1===e.length){const t=this.settings.lowPriorityLayoutMaxFS[0];this.degradeResolutionTo(e[0],t)&&this.debug("DegradeResolutionTo",e[0],0,t)}else{const t=[...this.settings.lowPriorityLayoutMaxFS];t.sort(),e.splice(Math.min(2,t.length));for(let i=0;i<e.length;++i)this.degradeResolutionTo(e[i],t[i])&&this.debug("DegradeResolutionTo",e[i],i,t[i])}e.push(t)}setMinimumQuality(e,t){for(const i of t)e.maxBr=Math.min(i.maxBr,e.maxBr),e.maxFs=Math.min(i.maxFs,e.maxFs),e.maxFps=Math.min(i.maxFps,e.maxFps),e.maxMbps=e.maxFs*e.maxFps}degradeResolutionTo(e,t){for(;e.maxFs>t;)if(!this.degradeResolution(e))return!1;return!0}degradeResolution(e){const t=this.mapLayoutToLadder(e);if(t>=this.ladder.length)return!1;if(t>0){const i=this.ladder[t-1];return e.maxBr=Math.min(e.maxBr,i.maxBitrate),e.maxMbps=i.fs*i.fps,e.maxFps=i.fps,e.maxFs=i.fs,!0}return!1}degradeBitrateOrResolution(e,t,i){i??(i=this.ladder);const n=this.mapLayoutToLadder(e,i);if(n>=i.length)return!1;if(t>=i[n].minBitrate)return e.maxBr=t,!0;let r=n;for(;r>0;){const n=i[--r];if(t>=n.minBitrate)return e.maxMbps=n.fs*n.fps,e.maxFps=n.fps,e.maxFs=n.fs,e.maxBr=Math.min(t,n.maxBitrate),!0}return!1}forceLadder(e,t,i){i??(i=this.ladder);const n=this.mapLayoutToLadder(e,i);if(n>=i.length)return!1;let r=Math.min(t,e.maxBr);if(r>=i[n].minBitrate){const t=i[n];return r=Math.min(r,t.maxBitrate),(e.maxMbps!==t.fs*t.fps||e.maxBr!==r)&&(e.maxMbps=t.fs*t.fps,e.maxFps=t.fps,e.maxFs=t.fs,e.maxBr=r,!0)}return this.degradeBitrateOrResolution(e,r,i)}mapLayoutToLadder(e,t){let i=0,n=0;for(t??(t=this.ladder);n<t.length&&!(t[n].fs>e.maxFs)&&!(t[n].fs===e.maxFs&&t[n].fps>e.maxFps);)i=n++;return i}},WB=class extends Vi{constructor(e,t,i,n){super(n),this.supportSingleBwControl=e,this.firstTime=t,this.configProvider=i,this.logger=n,this.multiStream=!1,this.wasMultistream=!0,this.deferredOperation=new kB((()=>this.updateStrategy()),this.configProvider.config.layoutControlTimeout,this.logger.createChild("DeferredOperation")),this.simulcastStrategySettings=void 0,this.wasMultistream=!1,this.createStrategy(this.multiStream,this.firstTime)}configure(e){const t=this.isMultiStream(e);this.multiStream!==t&&(this.multiStream=t,this.simulcastStrategySettings||this.deferredOperation.invoke(this.multiStream&&!this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled))}onFeaturesChanged(e){const t={},i=this.configProvider.config.specCompliantSimulcast;let n=!1;e.hasServerSupport(0)&&(n=!0),e.hasClientSupport(2)&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&(n=!0),e.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&(n=!0),t.limitMaxBitrate=i?.maxBrControlEnabled,t.limitMaxResolution=i?.allowResLimit,t.allowedOvershoot=i?.allowedBweOvershootRatio,t.forceKeyFrameWhenLayerIsRemoved=this.configProvider.config.useMediaQualityControllerForceKeyFrame,n&&t.limitMaxResolution&&(t.limitMaxResolution=this.firstTime&&!this.wasMultistream),e.hasClientSupport(2)&&(e.hasClientSupport(1)||(t.highPriorityLayoutMinFS=this.configProvider.config.video1080p?.software?.highPriorityLayoutMinFS,t.lowPriorityLayoutMaxFS=this.configProvider.config.video1080p?.software?.lowPriorityLayoutMaxFS),t.minSinglecastBitrate=this.configProvider.config.video1080p?.minSinglecastBitrate,this.configProvider.config.video1080p?.singlecastLayoutLadder&&(t.singlecastLadder=Un(this.configProvider.config.video1080p.singlecastLayoutLadder)),t.forceSinglecastLadder=this.configProvider.config.video1080p?.forceSinglecastLadder),e.hasClientSupport(3)&&(t.highPriorityLayoutMinFS=this.configProvider.config.broadcastMode?.priorityLayoutMinFS,t.lowPriorityLayoutMaxFS=this.configProvider.config.broadcastMode?.lowPriorityLayoutMaxFS),e.hasServerSupport(0)&&(t.minSinglecastBitrate=t.minSinglecastBitrate??i?.minSinglecastBitrate,t.allowLayerBitrateOverlap=i?.allowLayerBitrateOverlap,i?.singlecastLadder&&(t.singlecastLadder=t.singlecastLadder??Un(i?.singlecastLadder)),i.dropLowResolutionHigherStreams&&(t.minFrameSizeForSimulcast=i.video?.minFsForSimulcast)),!!this.simulcastStrategySettings===n&&an(t,this.simulcastStrategySettings)||(n?(this.logger.safe.info(`[SLCS] Configure [${this.simulcastStrategySettings?"existing":"initial"}][${this.wasMultistream}]: ${JSON.stringify(t)}`),this.simulcastStrategySettings=t):(this.simulcastStrategySettings&&this.logger.safe.info("[SLCS] Disable"),this.simulcastStrategySettings=void 0),this.deferredOperation.invoke(!1))}setLayouts(e,t){an(this.latestLayouts,e)&&this.latestBandwidth===t?this.logger.safe.debug("Layouts and bandwidth are not changed. Skipping update"):(this.latestLayouts=e,this.latestBandwidth=t,this.strategy.setLayouts(this.latestLayouts,t))}setAvailableBandwidth(e){this.latestBandwidth!==e?(this.strategy.setAvailableBandwidth(e),this.latestBandwidth=e):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(e){return e>1}createStrategy(e,t=!1){this.strategy=this.getNewStrategy(e,t),this.strategy.on("onLayoutsChanged",(()=>{this.wasMultistream=this.wasMultistream||this.isMultiStream(this.strategy.getLayouts().length),this.event("onLayoutsChanged").raise()}))}getNewStrategy(e,t){return this.simulcastStrategySettings?new zB(this.simulcastStrategySettings,this.configProvider,this.logger.createChild("SimulcastLayoutControlStrategy")):e?new HB(this.configProvider,this.logger.createChild("BWEControlledStrategy")):this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled&&this.supportSingleBwControl?new $B(t,this.configProvider,this.logger.createChild("BWEControlledStrategySingle")):new jB(this.logger.createChild("NoControlStrategy"))}},KB=class extends Vi{constructor(e,t,i){super(t),this.configProvider=e,this.logger=t,this.videoFeatures=i,this.bandwidthAllocator=null,this.sendBandwidthCalculator=new YU(this.configProvider,this.logger.createChild("SendBandwidthCalculator")),this.layoutProviders=new Map,this.hadLayoutProvider=new Set,this.useNewBandwidthAllocator=!1,this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator=function(e,t){const i=new RB(e.createChild("BandwidthAllocator"));return i.setLadder("ScreenShare",t.config.sharingBitrateLadderOverride||AB),i.setLadder("Video",t.config.videoBitrateLadderOverride||PB),i}(this.logger,this.configProvider),this.sendBandwidthCalculator.on("onSendBandwidthChanged",(e=>this.onAvailableBandwidthChanged(e))),this.configProvider.config.sendBandwidthSeedValue&&this.bandwidthAllocator.setAvailableBandwidth(this.configProvider.config.sendBandwidthSeedValue),this.useVideoFeatures("Video")&&this.videoFeatures.on("onVideoFeaturesChanged",(e=>{if(this.useVideoFeatures(e.mediaType)){const t=this.layoutProviders.get(e.mediaType);t&&t.onFeaturesChanged(e)}if(!this.useNewBandwidthAllocator&&this.configProvider.config.bandwidthAllocatorV2.enableAllocator){let t=!1;e.hasServerSupport(0)&&(t=!0),e.hasClientSupport(2)&&this.configProvider.config.video1080p?.useNewBandwidthAllocator&&(t=!0),t&&this.switchBandwidthAllocator()}}))}dispose(){this.bandwidthAllocator=null,this.layoutProviders.forEach((e=>e.dispose())),this.layoutProviders.clear(),this.layoutProviders=null,super.dispose()}addReceiver(e,t){this.logger.safe.debug(`Set receiver max capabilities for ${e}: ${JSON.stringify(t)}`),this.configureProviders(e,t.length);const i=t.map((e=>e.maxBr)).reduce(((e,t)=>e+t));if(this.useNewBandwidthAllocator&&"Video"===e&&this.layoutProviders.has("ScreenShare")&&this.configProvider.config.bandwidthAllocatorV2.enableDynamicVideoLadder){const e=Math.max(...t.map((e=>e.maxFs)));e>this.highestVideoMaxFsWithSharingEnabled&&(this.highestVideoMaxFsWithSharingEnabled=e,this.bandwidthAllocator.setLadder("Video",MB(this.configProvider,e)))}this.bandwidthAllocator.addReceiverCapability(e,i);const n=this.bandwidthAllocator.getLayouts();this.layoutProviders.get(e).setLayouts(t,n[e]),this.updateBandwidthDistribution()}removeReceiver(e){this.logger.safe.debug(`Removing receiver for ${e}`),this.layoutProviders.get(e)?.dispose(),this.layoutProviders.delete(e),this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator.removeReceiver(e),this.updateBandwidthDistribution()}getLayouts(e){return this.layoutProviders.get(e).getLayouts()}onStatisticsChanged(e){this.sendBandwidthCalculator.onBandwidthChanged(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){e.video?.send?.length&&e.video?.send[0]&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth"),this.sendBandwidthCalculator.onBandwidthChanged(JU(e.video.send[0],this.configProvider)))}useVideoFeatures(e){return!("Video"!==e||!this.configProvider.config.specCompliantSimulcast?.enableSimulcastLayoutControlStrategy&&!this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&!this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy)}switchBandwidthAllocator(){const e=function(e,t){const i=new DB(e.createChild("BandwidthAllocator2"));return i.setPriority("ScreenShare","Video"),i.setLadder("ScreenShare",t.config.bandwidthAllocatorV2.sharingLadder),i.setLadder("Video",MB(t,t.config.bandwidthAllocatorV2.defaultVideoMaxFS)),i}(this.logger,this.configProvider);e.setAvailableBandwidth(this.bandwidthAllocator.getAvailableBandwidth());const t=this.bandwidthAllocator.getReceiverCapabilities();for(const i of Object.keys(t))e.addReceiverCapability(i,t[i]);this.useNewBandwidthAllocator=!0,this.bandwidthAllocator=e,this.updateBandwidthDistribution()}configureProviders(e,t){if(!this.layoutProviders.has(e)){const t=this.createProvider(e);this.layoutProviders.set(e,t)}this.useVideoFeatures(e)&&t>2&&this.videoFeatures.get(e).toggleServer(0,!0),this.layoutProviders.get(e).configure(t)}createProvider(e){const t=new WB("Video"===e,!this.hadLayoutProvider.has(e),this.configProvider,this.logger.createChild(`LG:${e}`));return t.on("onLayoutsChanged",(()=>{const i=t.getLayouts();this.logger.safe.debug(`New layouts generated: ${JSON.stringify(i)}`),this.event("onLayoutsUpdated").raise(e)})),this.hadLayoutProvider.add(e),this.useVideoFeatures(e)&&t.onFeaturesChanged(this.videoFeatures.get(e)),t}onAvailableBandwidthChanged(e){this.bandwidthAllocator.setAvailableBandwidth(e),this.updateBandwidthDistribution()}adjustBandwidthDistribution(e,t){const i=new Map;t?(i.set("ScreenShare",this.configProvider.config.bandwidthAllocatorV2?.sharing?.remote),i.set("Video",this.configProvider.config.bandwidthAllocatorV2?.video?.remote)):(i.set("ScreenShare",this.configProvider.config.bandwidthAllocatorV2?.sharing?.local),i.set("Video",this.configProvider.config.bandwidthAllocatorV2?.video?.local));const n=function(e,t){const i=Object.keys(e).filter((t=>e[t]>0)).length>1;for(const n of Object.keys(e)){const r=t.get(n);if(void 0===e[n])continue;if(!r?.minValue&&!r?.minValueMixedMode)continue;const s=i?r?.minValueMixedMode:r?.minValue;e[n]=Math.max(s??r?.minValue??0,e[n])}return e}({...e},i);for(const i of["Video","ScreenShare"])n[i]!==e[i]&&this.logger.safe.info(`Adjusted ${t?"remote":"local"} ${i} BWE from ${e[i]} to ${n[i]}`);return n}updateBandwidthDistribution(){const e=this.bandwidthAllocator.getLayouts();let t;t=e,this.useNewBandwidthAllocator&&(t=this.adjustBandwidthDistribution(e,!1));for(const[e,i]of Object.entries(t))this.layoutProviders.get(e)?.setAvailableBandwidth(i);this.configProvider.config.mediaControlPlaneConfig?.enableSendBandwidthNotificationsEnabled&&(t=e,this.useNewBandwidthAllocator&&(t=this.adjustBandwidthDistribution(e,!0)),this.event("onBandwidthAllocationUpdated").raise(t))}},JB=Z;function YB(e,t,i){if("Video"!==e||!i)return i;const{maxBitrate:n,maxResolution:r,maxFramerate:s}=t.config.outgoingVideoLimit??{},a=n??1/0;let o=r?jn(r):1/0,l=s??1/0;return t.config.sendVideoCapabilityManager?.isEnabled&&(o=1/0,l=1/0),a===1/0&&o===1/0&&l===1/0?i:i.map((e=>({...e,maxFs:Ki(e.maxFs,o),maxBr:Ki(e.maxBr,a),maxFps:Ki(e.maxFps,l)})))}var QB=new Set(["maintain-framerate","maintain-resolution","balanced"]),ZB=class{constructor(e,t){this.configProvider=e,this.logger=t}async setActive(e,t){const i=this.getSenderParameters(e);return i.encodings[0].active=t,this.setSenderParameters(e,i,"setActive")}getScaleFactor(e,t){if(!t.width||!t.height)return this.logger.safe.warn("Stream resolution is not set yet. Cannot calculate scale factor. Returning 1"),1;const i=Hn.Send.getResolutionByFs(e);let n=Math.min(t.width,t.height)/i.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(t)} and new Fs: ${e} as ${n}`),n<1&&(this.logger.safe.warn("Scale factor cannot be less than 1! Limiting to 1"),n=1),n}async generateKeyFrameIfNeeded(e,t){if(!t.track)return void this.logger.safe.info("No track attached. Skipping");const i=this.getSenderParameters(t),n=e.filter((e=>e.keyframe)).map((e=>e.rid));if(0!==n.length&&i.encodings.some((e=>e.active)))if(this.configProvider.config.useKeyFrameApi){const e=[];i.encodings.forEach((t=>{!t.active||t.rid&&!n.includes(t.rid)?e.push({keyFrame:!1}):e.push({keyFrame:!0})})),await this.setSenderParameters(t,i,"generateKeyFrameAPI",!0,{encodingOptions:e})}else{const e=i.encodings.map(((e,t)=>e.active?e.rid&&!n.includes(e.rid)?null:{idx:t,factor:e.scaleResolutionDownBy||1}:null)).filter((e=>e));for(const t of e)i.encodings[t.idx].scaleResolutionDownBy=t.factor*this.configProvider.config.forceKeyFrameV2ScaleFactor;this.logger.safe.debug(`Restoring keyframe starting. Update scaleResolutionDownBy for encodings: ${JSON.stringify(i.encodings)}`),await this.setSenderParameters(t,i,"generateKeyFrameStart");const r=this.getSenderParameters(t);for(const t of e)r.encodings[t.idx].scaleResolutionDownBy=t.factor;await this.setSenderParameters(t,r,"generateKeyFrameEnd"),this.logger.safe.debug(`Restoring keyframe completed. Set scaleResolutionDownBy back for encodings: ${JSON.stringify(r.encodings)}`)}else this.logger.safe.info("No keyframes needed. Skipping")}getSenderParameters(e){const t=e.getParameters();if(t.encodings?.length||(t.encodings=[{}]),this.configProvider.config.reuseLastSetParameters&&this.lastSetEncodings){this.logger.safe.info(`Override returned encodings ${JSON.stringify(t.encodings)}`);const e=(0,JB.merge)((0,JB.cloneDeep)(t.encodings),this.lastSetEncodings);this.logger.safe.info(`Overrided encodings ${JSON.stringify(e)}`),t.encodings=e}return t}async setSenderParameters(e,t,i,n=!0,r){try{await e.setParameters(t,r),this.logger.safe.info(`${i}: Parameters applied for sender: encodings: ${JSON.stringify(t.encodings)}, degradationPreference: ${t.degradationPreference}`),this.lastSetEncodings=t.encodings}catch(e){const r=`${i}: setParameters failed. Parameters: ${JSON.stringify(t.encodings)}, error: ${tt(e)}`;if(this.logger.safe.error(r),n)throw new Error(r)}}getAdjustedBitrate(e,t){let i=e||0;const{maxBitrate:n}=Hn.Send.getBitrateForResolution(t.width,t.height);return i=Math.min(i||n,n),i}async updateStreamParameters(e,t,i){if(e.getCurrentConstraints().withEffect&&t?.maxFs){const i=Hn.Send.getResolutionByFs(t.maxFs),n={width:i.width,height:i.height};this.logger.safe.info(`Applying video constrains for video effetcs ${JSON.stringify(n)}`),e.resetEffectsOutputConstraints(n)}i&&await e.applyCapabilities(t)}augmentDegradationPreference(e,t){QB.has(t)&&e.degradationPreference!==t&&(e.degradationPreference=t,this.logger.safe.info(`degradationPreference changed to: ${e.degradationPreference}`))}async setEncodingsActiveState(e,t,i){this.logger.safe.info(i);const n=this.getSenderParameters(e);return n.encodings.forEach((e=>e.active=t)),this.setSenderParameters(e,n,i)}},XB=class{constructor(e,t,i){this.config=e,this.configProvider=t,this.logger=i,this.capabilitiesHelper=new ZB(this.configProvider,this.logger)}get streamResolution(){return this.stream?.getCurrentConstraints().withEffect?this._streamResolutionFromCapabilities:this._streamResolution}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this._streamResolution=e.getResolution(),this._streamResolutionFromCapabilities=this._streamResolution}setActive(e){return this.capabilitiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,JB.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):(this.defaultCapabilities=(0,JB.cloneDeep)(e),this.currentCapabilities=(0,JB.cloneDeep)(e),await this.applyLastCapabilities(),await this.capabilitiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender))}async updateStreamQualityParams(e,t,i){if(e&&!(0,JB.isEqual)(this.streamResolution,e))return this._streamResolution=e,this._streamResolutionFromCapabilities=e,this.logger.safe.info(`Stream params changed: ${JSON.stringify(e)}@${t}@${i} id: ${this.rtpSender.track?.id}`),this.applyLastCapabilities();this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(){return Em(this.configProvider,this.stream)||bm(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=YB(this.stream.mediaType,this.configProvider,this.defaultCapabilities),await this.applyStreamCapabilities(this.currentCapabilities);const e=this.capabilitiesHelper.getSenderParameters(this.rtpSender),t=(0,JB.cloneDeep)(e);return this.currentCapabilities.forEach((t=>{const i=this.getEncondingIndexForRid(t.rid,e.encodings);this.updateEncodingsWithCaps(e.encodings[i],t)})),this.capabilitiesHelper.augmentDegradationPreference(e,this.configProvider.config.degradationPreference),this.updateActiveStates(e,this.currentCapabilities),this.logger.safe.info(`Encoding params new: ${JSON.stringify(e.encodings)}, old: ${JSON.stringify(t.encodings)}`),this.capabilitiesHelper.setSenderParameters(this.rtpSender,e,"applyCapabilities")}async applyCallConstraints(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities()}async applyStreamCapabilities(e){if("Video"!==this.stream.mediaType||!e.length)return;let t=e[0];for(const i of e)t.maxFs<i.maxFs&&(t=i);if(e.length>1){const i=this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast;if(t=(0,JB.cloneDeep)(t),i?.length>0)for(let n=0;n<i.length;++n)e.length>n+1&&(t.maxFs=Math.max(i[n]||0,t.maxFs),t.maxFps=Math.max(...e.map((e=>e.maxFps))))}const i=this.configProvider.config.specCompliantSimulcast.video.useApplyConstraints;await this.capabilitiesHelper.updateStreamParameters(this.stream,t,i),i&&(this._streamResolution=this.stream.getResolution())}getEncondingIndexForRid(e,t){if(!e)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const i=t.findIndex((t=>t.rid===e));return i<0||i-1>this.config.layerScaleFactors.length?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):i}updateEncodingsWithCaps(e,t){e?(e.maxBitrate=t.maxBr,e.scaleResolutionDownBy=this.capabilitiesHelper.getScaleFactor(t.maxFs,this.streamResolution),e.maxFramerate=t.maxFps,this.config.defaultScalabilityMode&&(e.scalabilityMode=this.config.defaultScalabilityMode)):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(t)}`)}updateActiveStates(e,t){const i=e.encodings.map((e=>e.rid)),n=i.filter((e=>t.some((t=>e===t.rid)))),r=hn(i,n);n.forEach((t=>this.changeEncodingState(e,t,!0))),r.forEach((t=>this.changeEncodingState(e,t,!1)))}changeEncodingState(e,t,i){const n=e.encodings.find((e=>e.rid===t));n?n.active=i:this.logger.safe.error(`Encoding not found for RID: ${t}`)}},eV=class{constructor(e,t){this.configProvider=e,this.logger=t,this.capabilitiesHelper=new ZB(this.configProvider,this.logger)}get params(){return this.currentCapabilities?.find((e=>"1"===e.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(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities(3)}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this.streamResolution=e.getResolution()}setActive(e){return this.capabilitiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,JB.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):1===e.length?(this.defaultCapabilities=(0,JB.cloneDeep)(e),this.currentCapabilities=(0,JB.cloneDeep)(e),await this.applyLastCapabilities(0),await this.capabilitiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender)):this.logger.safe.error("Incorrect number of sender params!")}async updateStreamQualityParams(e,t,i){if(e&&!(0,JB.isEqual)(this.streamResolution,e))return this.streamResolution=e,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(e)}@${t}`),this.applyLastCapabilities(i);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(e){this.logger.safe.info(`Replace sender with track: ${e.id}`),await this.rtpSender.replaceTrack(e),this.logger.safe.info("replaceTrack completed"),Em(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),bm(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 Em(this.configProvider,this.stream)||bm(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(e){this.currentCapabilities?(this.currentCapabilities=YB(this.stream.mediaType,this.configProvider,this.defaultCapabilities),this.logger.safe.info(`Applying params: ${JSON.stringify(this.params)}`),await this.applyParams(this.params,e),await this.applyBitrate(this.params.maxBr)):this.logger.safe.debug("Capabilities are not yet set, nothing to apply")}applyBitrate(e){let t=e||0;return"Video"===this.stream.mediaType&&(t=this.capabilitiesHelper.getAdjustedBitrate(t,this.streamResolution)),this.setSingleEncodingParameters(this.rtpSender,{maxBitrate:t},"applyBitrate",!1)}async applyParams(e,t){if(this.useSetParameter)return this.setSingleEncodingParameters(this.rtpSender,{scaleResolutionDownBy:this.capabilitiesHelper.getScaleFactor(e.maxFs,this.streamResolution),maxFramerate:e.maxFps},"applyParams");2!==t&&await this.capabilitiesHelper.updateStreamParameters(this.stream,e,!0)}async setSingleEncodingParameters(e,t,i,n=!0){const r=this.capabilitiesHelper.getSenderParameters(e);return(0,JB.merge)(r.encodings[0],t),0===r.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?r.encodings[0].maxBitrate=void 0:delete r.encodings[0].maxBitrate),this.capabilitiesHelper.augmentDegradationPreference(r,this.configProvider.config.degradationPreference),this.capabilitiesHelper.setSenderParameters(this.rtpSender,r,i,n)}},tV=class{constructor(e,t,i){this.transitionStates=e,this.logger=i,this.stateCurrent=t}get state(){return this.stateCurrent}isDestinationStateValid(e){return this.transitionStates[this.stateCurrent].indexOf(e)>-1}setState(e){return this.isDestinationStateValid(e)?(this.stateCurrent=e,!0):(e!==this.stateCurrent&&this.logger.safe.info(`Invalid state transition ${this.stateCurrent} -> ${e}`),!1)}isCurrentStateMatchedWith(e){return this.stateCurrent===e||(this.logger.safe.info(`State does not match. Current: ${this.stateCurrent} required: ${e}`),!1)}},iV=class extends Vi{constructor(e,t){super(e),this.logger=e,this.configProvider=t,this.audioContext=new Mp.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(e){if(!e.rawStream)return;if(this.streamNodeMap.has(e.rawStream))return;const t=e.on("onStreamClientDisposing",(()=>{this.removeSourceStream(e.rawStream),t.dispose()}));this.logger.safe.info(`Add stream: ${e.rawStream.id}, track: ${nV(e.rawStream).id}`),this.addStream(e.rawStream,e.mediaType)}getDestinationTrack(){return nV(this.destination.stream)}dispose(){super.dispose(),this.unsubscribeFromMediaTrackEvents(this.getDestinationTrack());for(const e of this.streamNodeMap.keys())this.removeSourceStream(e);this.audioContext.close(),this.audioContext=null}addStream(e,t="Audio"){const i=this.audioContext.createMediaStreamSource(e);i.connect(this.destination),this.streamNodeMap.set(e,{mediaType:t,sourceNode:i})}removeSourceStream(e){const t=this.streamNodeMap.get(e);t&&(this.logger.safe.info(`Remove stream: ${e.id}, track: ${nV(e).id}`),t.sourceNode.disconnect(),this.streamNodeMap.delete(e))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.id} unmuted`)}}unsubscribeFromMediaTrackEvents(e){e.onended=null,e.onmute=null,e.onunmute=null}};function nV(e){return e.getAudioTracks()[0]}var rV=class extends Vi{constructor(e,t,i,n,r,s,a){super(),this.mediaConnection=e,this.contextStream=i,this.logger=n,this.configProvider=r,this.encStreamsManager=s,this.capabilitiesManager=a,this.isMuted=!1,this.isActiveInternal=!1,this.stream=t.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(e){return this.capabilitiesManager.applyCallConstraints(e)}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(e){this.configProvider.config.applySenderParamsBeforeStart||await this.start();try{await this.capabilitiesManager.setCapabilities(e)}catch(e){this.logger.safe.error(`Error setting capabilities: ${tt(e)}`)}await this.start()}updateStreamQualityParams(e,t,i){return this.capabilitiesManager.updateStreamQualityParams(e,t,i)}setMuted(e,t,i){this.isMuted=e,this.stream.setMuted(e,t),e&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(e),!this.configProvider.config.requestNewStreamOnUnmute||e||i||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(e,t){if(this.configProvider.config.holdSkipActivation)return;const i=!e;this.logger.safe.info(`[${t}] change isActive state to ${i}`);try{return this.capabilitiesManager.setActive(i)}catch(e){const n=this.configProvider.config.holdRetryActivationDelay;if(n>=0)return this.logger.safe.info(`[${t}] retrying after delay of ${n}`),await Yt(n),this.logger.safe.info(`[${t}] change isActive state to ${i}, second attempt`),this.capabilitiesManager.setActive(i);throw e}}async setMainStream(e){return this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=e.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(e){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(e),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((e=>e.active)).map((e=>+e.rid))}isActive(){return this.sender&&(Em(this.configProvider,this.stream)||bm(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(e){this.logger.safe.warn(`Error removing sender: ${tt(e)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${tt(e)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.rawTrack,this.contextStream,am(this.stream.mediaType))}addStreamTransforms(){const e=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);e&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new Tf(this.logger.createChild("SendAudioPayload")),e.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&e.addTransform(new Sf(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 iV(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 e=this.sender.getParameters();return e.encodings?.length||(e.encodings=[{}]),e}subscribeOnStreamClientMuted(){this.configProvider.config.recoverOnStreamUnmute&&(this.onStreamClientMutedSubscription=this.stream.on("onStreamClientMuted",(async(e,t)=>{t||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}},sV=class e extends Vi{constructor(t,i,n,r,s,a,o,l,c,d,u){super(),this.mediaConnection=t,this.mainStream=i,this.contextStream=n,this.mediaType=r,this.serialQueue=s,this.logger=a,this.configProvider=o,this.isAlwaysActive=l,this.encStreamsManager=c,this.simulcastContext=d,this.sendVideoCapabilityManager=u,this.isMuted=!1,this.isHold=!1,this.previousParameters=[],this.state=new tV(e.transitionStates,"NotStarted",this.logger.createChild("state")),this.pendingStream=null,this.pendingParams=null,this.lastAppliedParams=null,this.subscribeOnQualityUpdates(this.mainStream),u&&this.sendVideoCapabilityManager.on("onCapabilitiesChanged",(e=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(e),this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly&&this.lastAppliedParams&&!this.pendingParams&&this.updateParameters(this.lastAppliedParams)}))}async start(){this.state.setState("Started")&&(this.sender=new rV(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 e=async()=>{this.configProvider.config.enableCachingFMTPDelay>0&&(this.logger.safe.info("Applying delay before applying pending parameters"),await Yt(this.configProvider.config.enableCachingFMTPDelay)),this.logger.safe.info("Apply pending parameters");const e=this.updateParametersInternal(this.pendingParams);return this.pendingParams=null,e};this.configProvider.config.enableCachingFMTPAwait?(this.logger.safe.info("Apply pending parameters"),await e()):(this.logger.safe.info("Apply pending parameters in background"),e().catch((e=>this.logger.safe.error("Error applying pending parameters",e))))}}updateStream(e){return this.updateStreamInternal(e)}async addAdditionalStream(e){return this.sender.addAdditionalStream(e)}async updateParameters(e){if(this.state.isCurrentStateMatchedWith("Active"))return this.updateParametersInternal(e);this.configProvider.config.enableCachingFMTP?(this.logger.safe.info("Postpone params update until sender is activated"),this.pendingParams=e):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(e,t){if(this.isHold!==e)return this.logger.safe.info(`[${t}] Setting hold to: ${e}`),this.isHold=e,this.sender.setHold(e,t);this.logger.safe.info(`[${t}] Already in hold=${e} state`)}setMuted(e,t,i){this.logger.safe.info(`[${t}] Setting muted to: ${e}`),this.isMuted=e,this.sender.setMuted(this.isMuted,t,i),!this.isMuted&&"Audio"===this.mediaType&&this.state.isCurrentStateMatchedWith("Active")&&this.sender.start()}getActiveStreamIndexes(){return this.sender?this.sender.getActiveStreamIndexes():[]}getTrackInfo(){return{modality:am(this.mediaType),trackId:this.sender.trackId}}applyCallConstraints(e){return this.sendVideoCapabilityManager?.applyCallConstraints(e),this.sender.applyCallConstraints(e)}getCapabilitiesManager(e){return e?.shouldUseSimulcast()?new XB(e.config,this.configProvider,this.logger.createChild("SimCapMgrV2")):new eV(this.configProvider,this.logger.createChild("SnglCapMgrV2"))}async updateStreamInternal(e){return this.logger.info(`updateStreamInternal(): id: ${e.id}, parentId: ${e.parentId}), mediaType: ${this.mediaType}`),this.state.isCurrentStateMatchedWith("Active")?this.mainStream!==e?(this.logger.safe.debug(`Switching streams: ${this.mainStream.parentId}:${this.mainStream.id} -> ${e.parentId}:${e.id}`),this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=e,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(e))}async updateParametersInternal(e){if(this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly){this.lastAppliedParams=e;const t=this.sendVideoCapabilityManager?.getCapabilities();t&&(e=e.map((e=>{const i={...e};return i.maxFs>t.maxFs&&(this.logger.safe.info(`Reducing SSRC:${i.ssrc} video FS from ${i.maxFs} to ${t.maxFs}`),i.maxFs=t.maxFs),i.maxFps>t.maxFps&&(this.logger.safe.info(`Reducing SSRC:${i.ssrc} video FPS from ${i.maxFps} to ${t.maxFps}`),i.maxFps=t.maxFps),i})))}await this.sender.setCapabilities(e),function(e,t){const i=[];return e.forEach((e=>{t.some((t=>((e,t)=>e.ssrc===t.ssrc)(e,t)))||i.push(e)})),0===i.length&&e.length===t.length}(this.previousParameters,e)||(this.previousParameters=e,this.event("onSendersChanged").raise(this,!0))}setPendingStream(e){this.pendingStream=e;const t=e.on("onStreamClientDisposing",(()=>{this.pendingStream===e&&(this.pendingStream=null,t.dispose())}))}subscribeOnQualityUpdates(e){this.sub=e.on("onStreamQualityChanged",((e,t,i,n)=>this.updateStreamQualityParams(t,i,n)))}updateStreamQualityParams(e,t,i){return i===vh.EffectQualityChangeReason.Performance&&this.notifyMaxVideoSendCapabilitiesChanged({resolution:e,fps:t}),this.sender.updateStreamQualityParams(e,t,2)}unsubscribeFromQualityEvents(){this.sub?.dispose(),this.sub=null}notifyMaxVideoSendCapabilitiesChanged(e){if(!["Video","ScreenShare"].includes(this.mediaType))return;const{width:t,height:i}=e?.resolution??this.mainStream.getResolution(),n=e?.fps??this.mainStream.getFrameRate();if(!t||!i||!n)return;const r=new Bn(t,i),s={maxFs:r.fs,maxMbps:r.fs*n,maxFps:n,maxWidth:r.width,maxHeight:r.height};this.logger.safe.info(`Capabilities for ${this.mediaType} stream: ${JSON.stringify(s)}`),this.sendVideoCapabilityManager?this.sendVideoCapabilityManager.manage(s,!e):this.event("onMaxVideoSendCapabilitiesChanged").raise(s)}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()}};sV.transitionStates={NotStarted:["Started","Disposed"],Started:["Active","Disposed"],Active:["NotStarted","Disposed"],Disposed:[]},m([Uk()],sV.prototype,"start",1),m([Uk()],sV.prototype,"activate",1),m([Uk()],sV.prototype,"updateStream",1),m([Uk()],sV.prototype,"addAdditionalStream",1),m([Uk()],sV.prototype,"updateParameters",1),m([Uk()],sV.prototype,"terminateAsync",1),m([Uk()],sV.prototype,"setHold",1),m([Uk()],sV.prototype,"updateStreamQualityParams",1);var aV=sV,oV=class{constructor(e){this.durationThreshold=e,this.signals={}}track(e,t){void 0===this.signals[e]&&(this.signals[e]={wasNotified:!1}),this.signals[e].currentTime=_n(),!!this.signals[e].currentState!=!!t&&(this.signals[e].currentState=t,this.signals[e].lastChanged=this.signals[e].currentTime,this.signals[e].wasNotified=!1)}update(e){const t=[];for(const t of Object.keys(e))void 0===this.signals[t]&&(this.signals[t]={wasNotified:!1});for(const t of Object.keys(this.signals))this.track(t,e[t]);for(const e in this.signals){const i=this.signals[e];if(void 0!==i.currentState){if(i.wasNotified)continue;i.currentTime-i.lastChanged>=this.durationThreshold&&(i.wasNotified=!0,t.push(i.currentState))}}return t}},lV=class extends Vi{constructor(e,t){super(),this.logger=e,this.timeout=-1,this.signals=new oV(t.performanceMonitor.durationThreshold??3e3),this.config={monitorQualityLimitationReasons:t.performanceMonitor?.monitorQualityLimitationReasons,monitorMaxFS:t.performanceMonitor?.monitorMaxFS,mitigationTimeout:t.performanceMonitor?.mitigation?.timeout,startupDelay:t.performanceMonitor?.startupDelay}}key(e,t){return`${e.rid}:${t}`}suspend(e){e>0&&(this.logger.safe.info(`Suspending for ${(e/1e3).toFixed(1)} seconds`),this.timeout=_n()+e)}acceptLayout(e){return e.some((e=>void 0===e.rid))?(this.logger.safe.info("Ignore layout with missing RID"),!1):!(this.caps&&Math.max(0,...e.map((e=>e.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(e){this.logger.safe.info(`Max capabilities updated: ${JSON.stringify(e)}`),this.caps&&e.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=e}updateLayout(e){if((e||this.layout)&&this.logger.safe.info(`New layout: ${JSON.stringify(e)}`),e&&this.acceptLayout(e)){if((e=e.map((e=>Object.assign({},e)))).sort(((e,t)=>e.maxFs===t.maxFs?e.maxFps===t.maxFps?e.maxBr-t.maxBr:e.maxFps-t.maxFps:e.maxFs-t.maxFs)),this.layout?.length)for(let t=0;t<e?.length;++t){const i=e[t],n=this.layout.find((e=>e.rid===i.rid));n&&n.maxFs!==i.maxFs&&(this.logger.safe.info(`Reset '${this.key(n,"FS")}'`),this.signals.track(this.key(n,"FS"),void 0))}this.layout=e,-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(e){const t={};let i=0;if(!this.layout||this.layout.length<1||e.length<this.layout.length||this.timeout>_n())return void this.signals.update(t);for(this.timeout>0&&(this.logger.safe.info("Resuming"),this.timeout=0),i=0;i<this.layout.length;++i){const n=this.layout[i],r=e.find((e=>e.rid===n.rid));if(r){const e=Math.ceil(r.frameWidth/Gi.MACROBLOCK_SIZE)*Math.ceil(r.frameHeight/Gi.MACROBLOCK_SIZE);if(this.config.monitorQualityLimitationReasons){const e=r.qualityLimitationReason;-1!==this.config.monitorQualityLimitationReasons.indexOf(`${e}`)&&(t[this.key(n,"QL")]={layout:n,type:"QL",expected:"none",actual:e})}this.config.monitorMaxFS&&e<n.maxFs&&(t[this.key(n,"FS")]={layout:n,type:"FS",expected:n.maxFs,actual:e})}}const n=this.signals.update(t).map((e=>{const t=Object.assign({},e);return t.layout=this.layout?.find((e=>e.rid===t.layout.rid))??t.layout,t}));n.length&&(this.logger.safe.info(`Raise event: ${JSON.stringify(n)}`),this.event("onVideoQualityDegraded").raise(n))}},cV=class extends Vi{constructor(e,t,i,n){super(e),this.logger=e,this.configProvider=t,this.diagnostics=i,this.videoFeatureManager=n,this.activeModalities=new Set,this.callbacks=[];const r=this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation??{};this.config={allowDisabling1080pSinglecast:r.enableFor1080pSinglecast,allowDisabling1080pSimulcast:r.enableFor1080pSimulcast,allowDisablingThreeStreamSimulcast:r.enableForThreeStreamSimulcast,allowReversals:r.enableReversals}}hasSoftwareEncodedVideoAndSharing(){return!this.videoFeatureManager.get("Video").hasClientSupport(1)&&!this.videoFeatureManager.get("ScreenShare").hasClientSupport(1)&&this.hasActiveSenders("Video","ScreenShare")}hasActiveSenders(...e){return e.every((e=>this.activeModalities.has(e)))}getAdaptationInfo(e,t){return{description:e,activeModalities:[...this.activeModalities],isTransient:t&&this.config.allowReversals}}notify(e){this.logger.safe.warn(`${e.description} activeModalities: ${e.activeModalities.join("/")} isTansient: ${e.isTransient}`),this.diagnostics.registerLocalVideoPerformanceEvent(e)}schedule(e,t,i){this.callbacks.push({mediaType:e,state:t,callback:i})}override(e,t,i){this.configProvider.config[e]=t,this.logger.safe.info(`Overwriting ${e} with ${this.configProvider.config[e]}. Reason: ${i}`)}disable1080pSoftwareEncode(e){const t=this.videoFeatureManager.get("Video");if(!e.find((e=>e.maxFs===Gi.MAX_FS_1080P)))return!1;if(!t.hasClientSupport(2))return!1;if(t.hasClientSupport(1))return!1;if(1===e.length&&!this.config.allowDisabling1080pSinglecast)return this.logger.safe.info("Will not disable 1080p for singlecast"),!1;if(e.length>1&&!this.config.allowDisabling1080pSimulcast)return this.logger.safe.info("Will not disable 1080p for simulcast"),!1;const i=this.configProvider.config.performanceFallbackMaxFsFor1080pSend,n={},r={webrtcCameraOpenFs:this.configProvider.config.webrtcCameraOpenFs,maxCameraFsViaCallConstraints:this.configProvider.config.maxCameraFsViaCallConstraints,webrtcVideoCapabilityMaxFS:this.configProvider.config.webrtcVideoCapabilityMaxFS};for(const e in r)r[e]>0&&(n[e]=Math.min(i,r[e]));const s=Object.keys(n);if(s.some((e=>r[e]!==n[e]))){s.forEach((e=>{this.override(e,n[e],"mitigating 1080p performance issues")})),this.event("onNewStreamNeeded").raise(n.webrtcCameraOpenFs);const e=this.getAdaptationInfo("Disabled software 1080p",this.hasSoftwareEncodedVideoAndSharing());return e.isTransient&&this.schedule("ScreenShare",!1,(()=>{s.forEach((e=>{this.override(e,r[e],"removing mitigation for 1080p performance issues")})),this.event("onNewStreamNeeded").raise(),this.notify(this.getAdaptationInfo("Re-enabled software 1080p",!0))})),this.notify(e),!0}return!1}disableThreeStreamSimulcast(e){const t=this.videoFeatureManager.get("Video");if(3!==e.length)return!1;if(!this.config.allowDisablingThreeStreamSimulcast)return this.logger.safe.info("Will not disable 3-stream simulcast"),!1;if(t.hasClientSupport(1))return!1;if(t.hasFullSupport(0)){const e=this.getAdaptationInfo("Disabled 3-stream simulcast",this.hasSoftwareEncodedVideoAndSharing());return t.toggleClient(0,!1),e.isTransient&&this.schedule("ScreenShare",!1,(()=>{t.toggleClient(0,!0),this.notify(this.getAdaptationInfo("Re-enabled Three stream simulcast",!0))})),this.notify(e),!0}return!1}updateSenderState(e,t){if(t===this.activeModalities.has(e))return;t?this.activeModalities.add(e):this.activeModalities.delete(e);const i=this.callbacks.filter((i=>i.mediaType===e&&i.state===t));this.callbacks=this.callbacks.filter((i=>i.mediaType!==e||i.state!==t));for(const e of i)e.callback()}mitigatePerformanceIssue(e){return!!this.disable1080pSoftwareEncode(e)||!!this.disableThreeStreamSimulcast(e)}},dV=class{constructor(e,t,i){this.callback=e,this.logger=t,this.settings=i,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()}},uV=class extends Vi{constructor(e,t,i,n){super(e),this.logger=e,this.configProvider=t,this.frameSizeLimits={},this.initialMaxFS=this.configProvider.config.webrtcCameraOpenFs,this.subs=[],this.cadence=new dV(this.commitCallConstraints.bind(this),this.logger.createChild("Cadence"),this.configProvider.config.sendVideoCapabilityManager?.constraintsCadence),this.configProvider.config.enableVideoFeatureManager&&i&&(this.features=i.get("Video"),this.subs.push(i.on("onVideoFeaturesChanged",(e=>{"Video"===e.mediaType&&this.onFeaturesChanged(e)})))),n&&this.subs.push(n.on("onNewStreamNeeded",(e=>{this.limitFrameSize("Performance",e),this.updateConstraintsAndNotify()}))),this.configProvider.config.video1080p?.software?.isEnabled&&this.limitFrameSize("Software1080P",Gi.MAX_FS_1080P),this.settings=this.configProvider.config.sendVideoCapabilityManager,this.settings.defaultFS&&(this.initialMaxFS=this.settings.defaultFS);const r=this.getCallConstraints().maxFS;r&&r!==this.initialMaxFS&&(this.logger.safe.info(`Detected initial resolution opt-in: ${this.initialMaxFS} => ${r}`),this.limitFrameSize("Opt-In",r))}getCapabilities(){if(this.appliedCapabilities)return{...this.appliedCapabilities}}applyCallConstraints(e){this.lastCauseId=e,this.cadence.trigger()}manage(e,t){t&&(this.streamConstraints={maxFPS:e.maxFps,maxFS:e.maxFs},this.features&&this.streamConstraints.maxFS>=Gi.MAX_FS_1080P&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&this.features.toggleClient(2,!0)),this.requestedCapabilities={...e},this.updateConstraintsAndNotify()}dispose(e){for(const t of this.subs)t.dispose(e);this.subs=[],this.cadence.dispose(),super.dispose()}onFeaturesChanged(e){const t=(t,i)=>{this.limitFrameSize(hB[t],e.hasClientSupport(t)?i:void 0)};t(1,this.configProvider.config.hardwareEncodedVideoMaxFS),t(3,this.configProvider.config.broadcastMode?.maxVideoFS),this.updateConstraintsAndNotify()}getCallConstraints(){const e=this.configProvider.config.outgoingVideoLimit,t={},i="number"==typeof e?e:e?.maxResolution;return i&&(t.maxFS=jn(i)),t.maxFPS="number"==typeof e?void 0:e?.maxFramerate,t}commitCallConstraints(){this.limitFrameSize("Opt-In",this.getCallConstraints().maxFS,this.lastCauseId),this.updateConstraintsAndNotify()}buildCapabilities(){const e={...this.requestedCapabilities};if(this.constraints?.maxFS<e.maxFs||this.constraints?.maxFPS<e.maxFps){e.maxFps=Ki(this.constraints.maxFPS,e.maxFps),e.maxFs=Ki(this.constraints.maxFS,e.maxFs);const t={...Hn.Send.getResolutionByFs(e.maxFs)};e.maxMbps=t.fs*e.maxFps,e.maxWidth=t.width,e.maxHeight=t.height}return e}limitFrameSize(e,t,i){this.frameSizeLimits[e]!==t&&(i?this.logger.safe.info(`[${i}] FS limit for '${e}' changed from ${this.frameSizeLimits[e]} to ${t}`):this.logger.safe.info(`FS limit for '${e}' changed from ${this.frameSizeLimits[e]} to ${t}`),this.frameSizeLimits[e]=t)}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 e=this.getCallConstraints(),t={};let i=!1;for(const e of this.settings.priorityOrder)if(this.frameSizeLimits[e]>0){i=-1!==this.settings.allowOptIn.indexOf(e),t.maxFS=this.frameSizeLimits[e],this.logger.safe.info(`Using FS ${t.maxFS} from '${e}'. Opt-In is ${i?"allowed":"not allowed"}`);break}if(void 0===t.maxFS&&(t.maxFS=this.initialMaxFS,i=this.settings.maxFS>this.initialMaxFS),t.maxFPS=e.maxFPS,this.frameSizeLimits["Opt-In"]>0){const e=this.frameSizeLimits["Opt-In"];(e<t.maxFS||i)&&(this.logger.safe.info(`Applying opt-in: ${t.maxFS} => ${e}`),t.maxFS=e)}if(this.streamConstraints&&(this.logger.safe.debug(`Applying stream constraints: ${JSON.stringify(this.streamConstraints)} to ${JSON.stringify(t)}`),t.maxFS&&(t.maxFS=Ki(t.maxFS,this.streamConstraints.maxFS)),t.maxFPS&&(t.maxFPS=Ki(t.maxFPS,this.streamConstraints.maxFPS))),t.maxFS===this.constraints?.maxFS&&t.maxFPS===this.constraints?.maxFPS||(this.logger.safe.info(`Final constraints changed from ${JSON.stringify(this.constraints)} to ${JSON.stringify(t)}`),this.constraints=t),this.constraints&&this.requestedCapabilities){if(this.appliedCapabilities){const e=this.buildCapabilities();return e.maxFs!==this.appliedCapabilities.maxFs||e.maxFps!==this.appliedCapabilities.maxFps}return!0}return!1}},hV=class extends Vi{constructor(e,t,i,n,r,s,a,o,l,c,d){super(t),this.mediaManager=e,this.logger=t,this.callDeviceManager=i,this.configProvider=n,this.sessionConfig=r,this.statisticsGatherer=s,this.diagnostics=a,this.qmDiagnostics=o,this.isMultiparty=l,this.encStreamsManager=c,this.videoFeatureManager=d,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 tk(this.logger),this.streamsProvider=new IB(this.callDeviceManager,this.configProvider,this.sessionConfig,this.serialQueue,this.logger.createChild("StreamsProvider")),this.streamProviderSubscriptions=[this.streamsProvider.on("onStreamAdded",(e=>this.onStreamUpdated(e,!1))),this.streamsProvider.on("onStreamUpdated",(e=>this.onStreamUpdated(e,!0)))],this.localVideoStreamWatcher=new aB(this.logger,this.configProvider,this.callDeviceManager),this.localVideoStreamWatcherSub=this.localVideoStreamWatcher.on("onVideoCaptureFreeze",((e,t)=>this.onVideoCaptureFreeze(e,t))),this.configProvider.config.useMediaQualityController&&(this.mediaQualityController=new KB(this.configProvider,this.logger.createChild("MQC"),this.videoFeatureManager),this.mediaQualityController.on("onLayoutsUpdated",(e=>{const t=this.mediaQualityController.getLayouts(e);return this.logger.safe.debug(`Update layouts for ${e}: ${JSON.stringify(t)}`),"Video"===e&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(t),this.updateParameters(this.lastCauseId,e,t)})),this.mediaQualityController.on("onBandwidthAllocationUpdated",(e=>{this.event("onBandwidthAllocationChanged").raise(e)}))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor&&(this.simulcastPerformanceMonitor=new lV(this.logger.createChild("SPM"),this.configProvider.config.specCompliantSimulcast),this.simulcastPerformanceMonitor.on("onVideoQualityDegraded",(e=>this.onVideoQualityDegraded(e)))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation&&(this.simulcastPerformanceAdaptationManager=new cV(this.logger.createChild("SPAM"),this.configProvider,this.diagnostics,this.videoFeatureManager),this.simulcastPerformanceAdaptationManager.on("onNewStreamNeeded",(e=>{this.configProvider.config.sendVideoCapabilityManager?.isEnabled||(this.sessionConfig.outgoingVideoMaxFS=e,this.streamsProvider.requestStreamUpdate("Video",!0))})))}dispose(){this.senders.forEach(((e,t)=>{this.event("onSendStreamChanged").raise(null,t),this.configProvider.config.disposeSendersSync?e.dispose():e.terminateAsync()})),this.senders.clear(),this.senderSubs.forEach((e=>e.forEach((e=>e.dispose())))),this.senderSubs.clear(),this.streamProviderSubscriptions.forEach((e=>e.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(e){this.logger.safe.debug(`Registering RTP sender manager ${e}`),this.mediaConnection=e}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(e,t,i,n){n?.mark("startUpdateStreams");let r=function(e,t=!0){const i={Audio:Wp(e.audio),Video:Wp(e.video),ScreenShare:Wp(e.sharing)};return t||(i.Data=Wp(e.data)),i}(e,this.configProvider.config.streamModalitiesExcludeData);const s=!!(1&t),a=!!(2&t),o=!!(4&t);o&&(r={Audio:!0,Video:!1,Data:!1,ScreenShare:!1});const l=o?Promise.resolve(r):this.streamsProvider.update(r,s);let c,d;return a||o?(delete r.Data,c=tn(r),d=s?void 0:c):(c=await l,d=c),this.logger.safe.info(`[${i}] Streams updated, modalities requested: ${JSON.stringify(r)} (flags: ${t}), result: ${JSON.stringify(c)}`),n?.markAndMeasure("startUpdateStreams","updateStreamsWithModalities"),await this.updateSenders(d,i),n?.markAndMeasure("updateStreamsWithModalities","updateSenders"),a&&(this.streamsPromise=(async()=>{const t=await l;return this.streamsPromise=void 0,await this.updateSenders(t,i),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(t,e)})()),this.applyMuteState(i,!0),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(c,e)}mergeAndSaveModalities(e,t){this.previousMediaModalities=tn(e);const i=tn(t);return qi(t,((t,n)=>{const r=sm(n);Wp(t)&&!e[r]&&(i[n]=zp(t))})),i}async activate(e){this.logger.safe.info(`[${e}] activate senders`),await Promise.all([...this.senders.values()].map((async e=>e.activate()))),this.setAndUpdateLocalTracksInfo(!1)}applyCallConstraints(e){const t=this.senders.get("Video");return t?t.applyCallConstraints(e):(this.logger.info(`[${e}] Caching call constraints until sender is created`),this.callConstraintsCauseId=e,this.applyCallConstraintsDeferred=new Kt,this.applyCallConstraintsDeferred.promise)}async applyCapabilities(e,t,i){this.logger.safe.info(`[${e}] Applying incoming ${t} FMTP: ${JSON.stringify(i)}`);const n=sm(t);this.lastCauseId=e;let r=i;return this.mediaQualityController&&(this.mediaQualityController.addReceiver(n,i),r=this.mediaQualityController.getLayouts(n)),this.simulcastPerformanceAdaptationManager?.updateSenderState(n,!0),this.updateParameters(e,n,r)}getLocalMediaSources(){const e=this.getTracksInfo(),t=[];return e.forEach((e=>{t.some((t=>t.modality===e.modality))||t.push({sourceId:this.getSourceIdForTrack(e),modality:e.modality})})),t}setMuted(e,t,i){this.muted.set(e,t),this.applyMuteState(i,!1)}async setHold(e,t){await Promise.all([...this.senders.values()].map((async i=>i.setHold(e,t))))}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.mediaQualityController?.onStatisticsChanged(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher||this.localVideoStreamWatcher.onStatisticsChanged(e)}onDiagnosticUpdated(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation&&this.mediaQualityController?.onDiagnosticUpdated(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher&&this.localVideoStreamWatcher.onDiagnosticUpdated(e)}async updateParameters(e,t,i){try{const n=this.senders.get(t);n?await n.updateParameters(i):this.logger.safe.info(`[${this.lastCauseId}] Capabilities ignored ${JSON.stringify(i)}, no ${JSON.stringify(t)} sender`),this.logger.safe.debug(`[${e}] Capabilities completed`);const r={modality:am(t),causeId:e,capabilities:i};this.statisticsGatherer.onMaxCapabilitiesApplied(r),this.qmDiagnostics.onMaxCapabilitiesApplied(r)}catch(n){const r=tt(n);this.logger.safe.error(`[${e}] Error applying capabilities ${r}`);const s={modality:am(t),causeId:e,capabilities:i,error:r};this.statisticsGatherer.onMaxCapabilitiesApplied(s),this.qmDiagnostics.onMaxCapabilitiesApplied(s)}}applyMuteState(e,t){for(const[i,n]of this.muted)this.senders.get(i)&&this.senders.get(i).setMuted(n,e,t)}setAndUpdateLocalTracksInfo(e){const t=this.getTracksInfo();this.logger.safe.debug(`Local tracks info: ${JSON.stringify(t)}`),this.mediaManager.setLocalTracksInfo(t),e&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statisticsGatherer.updateStatsWithLocalSsrcTrackInfo())}getTracksInfo(){const e=[];return this.senders.forEach((t=>e.push(t.getTrackInfo()))),e}async updateSenders(e,t=be()){const i=await this.streamsProvider.getStreams(),n=e||om(i);this.logger.safe.info(`[${t}] Updating senders with modalities: ${JSON.stringify(n)}, override: ${!!e}`),await Promise.all(en(n).map((async e=>{const i=n[e];if(i===this.previousMediaModalities[e])return;if(!i)return this.logger.safe.info(`[${t}] Removing sender for ${JSON.stringify(e)}`),void await this.removeSender(e);const r=(await this.streamsProvider.getStreams())?.[e];if(await this.createAndStartSender(r,e),this.logger.safe.info(`[${t}] Sender for ${JSON.stringify(e)} is added`),this.applyCallConstraintsDeferred&&"Video"===e){const t=this.senders.get("Video");try{await t.applyCallConstraints(this.callConstraintsCauseId),this.applyCallConstraintsDeferred.resolve()}catch(e){this.applyCallConstraintsDeferred.reject(e)}this.applyCallConstraintsDeferred=void 0,this.callConstraintsCauseId=void 0}await this.addAudioSharingStream(r),this.event("onSendStreamChanged").raise(r,e)}))),this.logger.safe.info(`[${t}] Senders updated. Enabled: ${JSON.stringify(Object.keys(n).filter((e=>n[e])))}`)}createCapabilityManager(e,t){if("Video"===e&&this.configProvider.config.sendVideoCapabilityManager?.isEnabled)return new uV(t.createChild("SVCM"),this.configProvider,this.videoFeatureManager,this.simulcastPerformanceAdaptationManager)}createAndStartSender(e,t){if(this.senders.get(t))return this.logger.safe.error(`Sender already created, modality: ${JSON.stringify(t)}`),this.senders.get(t).start();const i=this.mediaManager.getMediaEntitiesByModality(am(t))[0],n=i?.getSimulcastContext(),r=!this.configProvider.config.specCompliantSimulcast?.disableTilde&&!!n?.shouldUseSimulcast(),s="Audio"===t||!this.isMultiparty||r,a=this.logger.createChild(`Sender_${JSON.stringify(t)}:${this.senderId++}`),o=this.createCapabilityManager(t,a),l=new aV(this.mediaConnection,e||new bB(t,this.logger.createChild("tempStream")),new MediaStream,t,this.serialQueue,a,this.configProvider,s,this.encStreamsManager,n,o);this.senders.set(t,l);const c=[l.on("onSendersChanged",((e,t)=>this.onSenderStateChanged(e,t))),l.on("onNewStreamNeeded",(()=>this.streamsProvider.requestStreamUpdate(t,!0))),l.on("onMaxVideoSendCapabilitiesChanged",(e=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(t,e),"Video"===t&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateMaxCapabilities(e)}))];return this.senderSubs.set(l,c),l.start()}async removeSender(e){const t=this.senders.get(e);t&&(this.senders.delete(e),this.event("onSendStreamChanged").raise(null,e),await t.terminateAsync(),this.senderSubs.get(t).forEach((e=>e.dispose())),this.senderSubs.delete(t),this.logger.safe.info(`Removed sender with mediaType: ${JSON.stringify(e)}`)),this.mediaQualityController?.removeReceiver(e),this.simulcastPerformanceAdaptationManager?.updateSenderState(e,!1),"Video"===e&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(void 0)}getSourceIdForTrack(e){const t=e.trackId,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}onVideoCaptureFreeze(e,t){e||(t?this.qmDiagnostics.registerWebcamFreeze():this.qmDiagnostics.registerProcessedStreamFreeze()),this.event("onVideoCaptureFreeze").raise(e)}onVideoQualityDegraded(e){const t=this.mediaQualityController?.getLayouts("Video")??[];let i=!1;for(const n of e)if(this.logger.safe.warn(`rid:${n.layout.rid} ${n.type} degraded - expected: ${n.expected}, actual: ${n.actual}`),!i&&this.simulcastPerformanceAdaptationManager)switch(n.type){case"QL":"cpu"===n.actual&&(i=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(t));break;case"FS":"1"===n.layout.rid&&(i=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(t))}i&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.onMitigationApplied()}async onStreamUpdated(e,t){if(!this.senders.has(e))return void this.logger.safe.warn(`Sender with media type ${e} does not exist, do not update media stream`);let i=(await this.streamsProvider.getStreams())[e];if(i||(this.logger.safe.info(`Stream is missing for mediaType: ${e}, using fake stream...`),i=new bB(e,this.logger.createChild("NullStreamClient"))),i.isDisposed())return void this.logger.safe.info(`Stream is already disposed for mediaType: ${e}`);this.event("onSendStreamChanged").raise(i,e);const n=this.senders.get(e);await this.addAudioSharingStream(i),await n.updateStream(i),this.logger.safe.debug(`Stream updated for mediaType: ${e}, updated: ${t}`),this.setAndUpdateLocalTracksInfo(t)}onSenderStateChanged(e,t){if(this.mediaManager.updateMediaEntitiesWithActivityState(e.mediaType,e.getActiveStreamIndexes()),this.statisticsGatherer.onSendersChanged(e.mediaType,t),"Video"===e.mediaType)if(t){const e=this.getTracksInfo().filter((e=>e.modality===Gi.MODALITY.video));this.localVideoStreamWatcher.startWatching(e,this.simulcastPerformanceMonitor)}else this.localVideoStreamWatcher.stopWatching()}async addAudioSharingStream(e){"ScreenShare"===e?.mediaType&&e?.hasAudio()&&(this.logger.safe.info("Adding audio stream from sharing to audio sender"),await(this.senders.get("Audio")?.addAdditionalStream(e)))}},gV=class{constructor(e,t,i,n,r){this.recvStream=e,this.mainTrack=t,this.receiveStreamCollection=i,this.logger=n,this.settings=r,this.removeOtherTracks(t),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(e){return this.recvStream.requestSource(e)}getSourceStreamId(){return this.recvStream.getSourceStreamId()}getSubstreamIndex(){return this.recvStream.getSubstreamIndex()}removeOtherTracks(e){this.settings.onAddTrackRemoveOtherTracks&&this.stream.getTracks().forEach((t=>{t.id!==e.id&&this.stream.removeTrack(t)}))}subscribeOnStreamEvents(){const e=e=>this.logger.safe.info(`${e} track: ${this.mainTrack.id}, stream: ${this.stream.id}`);this.stream.onremovetrack=()=>{e("onremovetrack"),this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onended=()=>{e("onended"),this.settings.removeRecvStreamOnEnded&&this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onmute=()=>e("onmute"),this.mainTrack.onunmute=()=>e("onunmute")}unsubscribeFromStreamEvents(){this.stream.onremovetrack=null,this.mainTrack.onended=null,this.mainTrack.onmute=null,this.mainTrack.onunmute=null}},pV=class{constructor(e){this.startTimestamp=0,this.totalTime=0,this.lastActiveTime=0,this.id=e}},mV=class{constructor(e){this.speakersHistory=[],this.sources=[],this.configProvider=e.configProvider,this.ping=this.setupTimer()}setSources(e=[]){const t=e.map(this.getOrCreateSource.bind(this)),i=this.excludeSources(this.sources,t);t.forEach((e=>{this.isAlreadyActive(e)||this.updateSourceTimestamp(e),this.updateSourceLastActiveTime(e)})),i.forEach((e=>{this.updateTotalTime(e),this.resetStartTimestamp(e)})),this.ping||(this.ping=this.setupTimer())}setOnDominantSpeakerChanged(e){this.callback=e}dispose(){this.clearTimer(),this.sources=null,this.callback=null}excludeSources(e,t){return e.filter((e=>!t.some((t=>e.id===t.id))))}trigger(){if(!this.hasAnyoneSpoken())return void this.clearTimer();const e=this.sources.map(this.updateTotalTime).sort(((e,t)=>t.totalTime-e.totalTime||t.lastActiveTime-e.lastActiveTime)).map((e=>e.id)).slice(0,this.configProvider.config.ovcMaxCount);e.length&&!an(this.speakersHistory,e)&&(this.speakersHistory=e,this.callback&&this.callback(this.speakersHistory,"client")),this.sources.map(this.resetTotalTime).filter(this.isAlreadyActive).forEach(this.updateSourceTimestamp)}isAlreadyActive(e){return!!e.startTimestamp}setupTimer(){return window.setInterval(this.trigger.bind(this),this.configProvider.config.activeSpeaker.timeToPromote)}clearTimer(){this.ping&&(clearInterval(this.ping),this.ping=null)}getOrCreateSource(e){if(this.isExist(e))return this.sourceById(e);{const t=new pV(e);return this.sources.push(t),t}}isExist(e){return this.sources.some((t=>e===t.id))}hasAnyoneSpoken(){return this.sources.some((e=>0!==e.startTimestamp||0!==e.totalTime))}sourceById(e){return this.sources.find((t=>e===t.id))}updateSourceTimestamp(e){e.startTimestamp=Date.now()}updateSourceLastActiveTime(e){e.lastActiveTime=Date.now()}updateTotalTime(e){return e.startTimestamp&&(e.totalTime+=Date.now()-e.startTimestamp),e}resetStartTimestamp(e){return e.startTimestamp=0,e}resetTotalTime(e){return e.totalTime=0,e}},fV=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.logger=t,this.bandwidthEstimationAvailable=!1,this.smoothingWindow=[],this.totalSamples=0,this.isStarted=!1,this.maxCountStatic=this.configProvider.config.ovcMaxCount,this.previousParticipantsCount=0,this.isMcpSrAvailable=!1;const i=window.navigator;this.updateStaticConstraint(i.hardwareConcurrency,this.configProvider.config.ovcAvailableConcurrencyForBiggerGrid,4),this.updateStaticConstraint(i.deviceMemory,this.configProvider.config.ovcMemoryForBiggerGrid,4),this.throttler=new vV(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(e){this.bandwidthConstrainedOvc=this.getOVCEstimate(e),this.payload={bandwidth:e,reason:0},this.throttler.setValue(this.getOvcValue(),0)}updateParticipantCount(e){if(!this.configProvider||e===this.previousParticipantsCount)return;const t=this.configProvider.config.ovcXLParticipantsCount;e>t&&this.previousParticipantsCount<=t&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountXL),e<=t&&this.previousParticipantsCount>t&&(this.configProvider.config.multiStreamSupported&&this.isMcpSrAvailable?this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream:this.maxCountStatic=this.configProvider.config.ovcMaxCount),this.previousParticipantsCount=e,this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2)}setPerfConstrainedValue(e){this.perfConstrainedOvc=e,this.logger.safe.info(`Setting perfConstrainedOvc to ${e}`),this.payload&&this.getOvcValue()===e&&(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(e){this.bandwidthEstimationAvailable||(this.bandwidthEstimationAvailable=this.isStarted&&e>0&&(this.totalSamples++>=this.configProvider.config.ovcIgnoreFirstSamples||Math.floor(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver>=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount));let t=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount;return this.bandwidthEstimationAvailable&&(t=Math.floor(this.sampleSmoothed(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver)),t}getOvcValue(){return Math.max(1,Math.min(this.bandwidthConstrainedOvc??this.maxCountStatic,this.perfConstrainedOvc??this.maxCountStatic,this.maxCountStatic))}sampleSmoothed(e){if(this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples?this.smoothingWindow.shift():this.smoothingWindow.length===this.configProvider.config.ovcSlidingWindowSamples-1&&(this.smoothingWindow=this.smoothingWindow.map((()=>e))),this.smoothingWindow.push(e),this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples){const e=this.smoothingWindow.slice().sort(),t=Yi(e);return e[e.length-1]-(e[e.length-1]-t*(1-this.configProvider.config.ovcSlidingWindowPercentile))}return e}updateStaticConstraint(e,t,i){e&&e<t&&(this.maxCountStatic=Math.min(this.maxCountStatic,i))}},vV=class extends Vi{constructor(e,t,i){super(e),this.logger=e,this.throttleDownCooldown=t,this.throttleUpCooldown=i,this.wasRampingUp=!0,this.lastUpdateTime=0}get value(){return this.lastValue}setValue(e,t){if(e===this.lastValue)return;const i=e>this.lastValue,n=void 0!==this.lastValue&&i!==this.wasRampingUp?i?this.throttleUpCooldown:this.throttleDownCooldown:-1,r=Date.now();r-this.lastUpdateTime<n&&(2!==t||i)||(void 0!==this.lastValue&&(this.lastUpdateTime=r,this.wasRampingUp=i),this.logger.safe.info(`optimal video receivers count updated ${this.lastValue} -> ${e}, reason: ${t}`),this.lastValue=e,this.raiseChanged())}},SV=class e{constructor(e,t=30){this.logger=e,this.maxEventNum=t,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(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{e&&Sn(this.report,{timeStamp:Date.now(),value:e},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 Cn(this.report)}getCurrentCpuSample(){return new Promise(((t,i)=>{this.started&&t(Cn(this.report)),this.isSupported()||i("Not supported"),this.port=window.chrome.runtime.connect(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{this.stop(),e||i("Not supported"),t({timeStamp:Date.now(),value:e})}))}))}clearStats(){this.report=[]}};SV.extensionID="nkeimhogjdpnpccoofpliimaahmaaome",SV.extensionName="processCpu";var yV=SV,CV=class{constructor(e){this.logger=e,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((e=>{e.forEach((t=>{"cpu"===t.source&&this.currentCpuState!==t.state&&(this.logger.safe.debug(`CPU pressure state changed: ${JSON.stringify(e)}`),this.currentCpuState=t.state)}))}),{sampleRate:1})}catch(e){throw this.logger.safe.error(`Error while creating pressure observer: ${e}`),e}this.started=!0,this.cpuObserver?.observe("cpu")}}stop(){this.started=!1,this.cpuObserver?.disconnect()}},TV=class extends Vi{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,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&&CV.isSupported()&&(this.cpuPressureObserver=new CV(this.logger)),this.configProvider.config.diagnostics.performanceMonitoring.useCpuSample&&(this.cpuMetricCollector=new yV(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=KD.getStrategy(this.configProvider),this.started=!0,this.cpuPressureObserver?.start(),this.subs.push(this.statsGatherer.on("onDiagnosticUpdated",(e=>this.processStats(e)))))}stop(){this.logger.safe.debug("Stopping RemoteVideoPerformanceCalculator"),this.started=!1,this.subs.forEach((e=>{e.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(e){try{if(this.paused)return;if(!e.video?.recv?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Calculating remote video performance"),e.video?.recv?.forEach((async t=>{const i=t.renderer?.msi;if(!this.perfTrackerMap.has(i)){const e={id:t.mediaEntity?.remoteTrackId,decodeTimeTracker:new XM(this.trackInterval),macroblockLossTracker:new XM(this.trackInterval),macroblockMaxLossTracker:0,freezeDurationPercent:0,frameHeight:0,frameWidth:0,rendererFps:new XM(this.trackInterval),incomingFps:new XM(this.trackInterval),framesReceived:0,framesDecoded:0,decoder:"",msi:i};this.perfTrackerMap.set(i,e)}const n=this.perfTrackerMap.get(i);if(t.inboundRTP.totalDecodeTime&&t.inboundRTP.framesDecoded){const e=mn(t.inboundRTP.totalDecodeTime/t.inboundRTP.framesDecoded*1e3,2);n.decodeTimeTracker.captureSample(e)}const r=t.extensions?.macroblockRateStats?.macroblockRateDecoderLossPercent;n.macroblockLossTracker.captureSample(r),n.macroblockMaxLossTracker=t.extensions?.macroblockRateStats?.macroblockRateMaxDecoderLossPercent,t.extensions?.duration&&(n.freezeDurationPercent=t.extensions?.totalFreezeDuration/t.extensions?.duration*100),n.frameHeight=t.inboundRTP.frameHeight||0,n.frameWidth=t.inboundRTP.frameWidth||0,void 0!==t.extensions?.frameRateDecoded&&void 0!==t.inboundRTP.framesPerSecond&&t.extensions?.frameRateDecoded<=this.rendererFpsCap&&t.inboundRTP.framesPerSecond<=this.rendererFpsCap&&(n.rendererFps.captureSample(t.extensions?.frameRateDecoded),n.incomingFps.captureSample(t.inboundRTP.framesPerSecond)),t.inboundRTP.framesReceived&&t.inboundRTP.framesDecoded&&(n.framesReceived=t.inboundRTP.framesReceived,n.framesDecoded=t.inboundRTP.framesDecoded),n.decoder=t.inboundRTP.decoderImplementation,n.rendererFps.isReportComplete()&&n.incomingFps.isReportComplete()&&n.decodeTimeTracker.isReportComplete()&&(this.paused=!0,await this.checkQuality(n,e.perfCounters,e.video?.recv?.length),this.paused=!1)}))}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}async checkQuality(e,t,i){if(!i)return;const n=[];let r;try{r=await(this.cpuMetricCollector?.getCurrentCpuSample())}catch{this.logger.safe.debug("CPU sampling is not supported")}const s={ts:Date.now(),trackId:e.id,decodeTime:e.decodeTimeTracker.getReport(),macroblockLossPercent:e.macroblockLossTracker.getReport(),macroblockMaxLossPercent:e.macroblockMaxLossTracker,freezeDurationPercent:e.freezeDurationPercent,perfCounters:t,cpuUsage:r,rendererFps:e.rendererFps.getReport(),incomingFps:e.incomingFps.getReport(),framesDecoded:e.framesDecoded,framesReceived:e.framesReceived,msi:e.msi,frameHeight:e.frameHeight,decoder:e.decoder};n.push(s);const a=this.calculatorStrategy.checkQuality(e);if(0===a){if(this.logger.safe.debug(`Bad perf detected for msi ${e.msi}: ${JSON.stringify(n)}`),this.configProvider.config.diagnostics.performanceMonitoring.usePerfConstrainedOvc&&!Hn.Recv.getNextLowerResolution(e.frameWidth,e.frameHeight)){const e=Math.max(i-1,1);return this.logger.info(`Min resolution reached, decreasing OVC to: ${e}`),this.diagnostics.registerVideoPerformanceEvent(n,1,e),this.event("calculatorStateChanged").raise(2,{ovc:e}),void this.perfTrackerMap.clear()}this.diagnostics.registerVideoPerformanceEvent(n,1),this.event("calculatorStateChanged").raise(1,{msi:e.msi})}2===a&&(this.diagnostics.registerVideoPerformanceEvent(n,0),this.logger.safe.debug(`Good perf detected for msi ${e.msi}: ${JSON.stringify(n)}`),this.event("calculatorStateChanged").raise(0,{msi:e.msi})),this.perfTrackerMap.delete(e.msi)}},EV=class extends Vi{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,this.calculators=new Map,this.subs=[]}on(e,t){switch(e){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(e),handler:t}})}addCalculator(e){let t=this.calculators.get(e);if(!t){switch(e){case 0:if(!this.configProvider.config.diagnostics.performanceMonitoring.enableRemoteVideoCalculator)return;t=new TV(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("RemoteVideoPerformanceCalculator"));break;case 2:if(!this.configProvider.config.enableOptimalVideoCount)return;t=new fV(this.configProvider,this.logger.createChild("OptimalVideoCountCalculator"));break;case 1:throw new Error("Not implemented")}this.subs.push(t.on("calculatorStateChanged",((t,i)=>{this.handleChanged(e,t,i)}))),this.calculators.set(e,t)}}startCalculator(e){this.logger.safe.debug(`adding calculator with id ${e}`);const t=this.calculators.get(e);t&&t.start()}stopCalculator(e){this.logger.safe.debug(`stopping calculator with id ${e}`);const t=this.calculators.get(e);t&&t.stop()}processNotification(e,t){switch(e){case"BandwidthNotification":this.calculators.get(2)?.processEstimatedBandwidth(t.bw);break;case"ParticipantCountChanged":this.calculators.get(2)?.updateParticipantCount(t.count);break;case"McpSourceRequestsAvailable":this.calculators.get(2)?.mcpSourceRequestsAvailable();break;default:this.logger.safe.info(`Notification message handler not found for type: ${e}`)}}dispose(){super.dispose(),this.calculators.forEach((e=>{e.dispose()})),this.subs.forEach((e=>{e.dispose()}))}handleChanged(e,t,i){switch(this.logger.info(`calculatorStateChanged ${t}: calculatorType ${e} ${JSON.stringify(i)}`),e){case 0:if(2===t){this.calculators.get(2)?.setPerfConstrainedValue(i?.ovc);break}this.configProvider.config.diagnostics.performanceMonitoring.enableLowerResolution&&this.event("onIncomingVideoQualityChanged").raise(t,i?.msi);break;case 2:this.event("onOptimalVideoCountChanged").raise(i?.ovc,i?.ovcPayload)}}},bV=Z,_V=class{constructor(e){this.configProvider=e,this.outboundNetworkQuality="Good",this.inboundNetworkQuality="Good",this.jitterAccumulator=new $M(this.configProvider.config.webrtcJitterWindowSize),this.healedRatioAccumulator=new $M(this.configProvider.config.webrtcHealedRatioWindowSize),this.jitterStateProcessor=new GF(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),this.lossRateStateProcessor=new GF(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime)}processReport(e){e.audio?.recv?.length&&(this.inboundNetworkQuality=this.processInboundSample((0,bV.last)(e.audio.recv))),e.audio?.send?.length&&(this.outboundNetworkQuality=this.processOutboundSample((0,bV.last)(e.audio.send)))}getInboundNetworkQuality(){return this.inboundNetworkQuality}getOutboundNetworkQuality(){return this.outboundNetworkQuality}processInboundSample(e){const t=this.inboundNetworkQuality,{totalSamplesReceived:i}=e.inboundRTP,{healedRatio:n}=e.extensions??{};null!=n&&this.healedRatioAccumulator.add(n);const r=(0,bV.mean)(this.healedRatioAccumulator.items);return!i||i<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality?t:r&&this.healedRatioAccumulator.isFull?this.determineInboundQualityLevel(r):t}determineInboundQualityLevel(e){const t=this.inboundNetworkQuality,i=this.configProvider.config.webrtcStatNetworkDetectionHysteresis,n=this.configProvider.config.webrtcStatNetworkDetectionBadLevel,r=this.configProvider.config.webrtcStatNetworkDetectionGoodLevel;return e<r-i/2?"Good":e<r+i/2?"Good"===t?"Good":"Poor":e<n-i/2?"Poor":e<n+i/2?"Bad"===t?"Bad":"Poor":"Bad"}processOutboundSample(e){const t=this.outboundNetworkQuality,{packetsSent:i,timestamp:n}=e.outboundRTP,{jitter:r}=e.remoteInboundRTP??{},{lossRate:s}=e.extensions??{};if(!i||i<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return t;null!=r&&this.jitterAccumulator.add(r);const a=(0,bV.mean)(this.jitterAccumulator.items),o=this.jitterAccumulator.isFull?this.jitterStateProcessor.onSample(a,n):"Good",l=s?this.lossRateStateProcessor.onSample(s,n):"Good";return"Good"===o&&"Good"===l?"Good":"Bad"}},IV=Z,wV=class{constructor(e){this.configProvider=e,this.speechWindow=new $M(e.config.webrtcSpeakingWhileMutedDetectionWindow)}processReport(e){if(!e.audio?.send?.length)return!1;const t=e.audio.send[0],{rawInputVolume:i,callIsMuted:n}=t.extensions??{},{audioLevel:r}=t.mediaSource??{},{useAudioAnalyzer:s,webrtcSpeakingWhileMutedDetectionLevel:a}=this.configProvider.config;if(!n)return this.speechWindow.clear(),!1;const o=s?i:r;return null!=o&&this.speechWindow.add(o),!!this.speechWindow.isFull&&(0,IV.mean)(this.speechWindow.items)>a}},AV=class{constructor(e){this.context=e,this.cname=sn()}toLocal(e,t,i){return this.modify({sdpSource:0,sdpType:i},e,t)}toOffer(e,t,i){return this.modify({sdpSource:1,sdpType:"offer"},e,t,i)}toAnswer(e,t,i){return this.modify({sdpSource:1,sdpType:"answer"},e,t,i)}toRemote(e,t,i,n,r=!1){return this.modify({sdpSource:2,sdpType:n,isOrWasProvisional:r},e,t,i)}modify(e,t,i,n){const r=new nN(this.context,i,n,this.cname).build(e),s=nn(t);return r.modify(s),s}},PV=class{get sdp(){return this.originalDescription.sdp}set sdp(e){this.originalDescription=new Mp.window.RTCSessionDescription({sdp:e,type:this.originalDescription.type})}get type(){return this.originalDescription.type}set type(e){this.originalDescription=new Mp.window.RTCSessionDescription({sdp:this.originalDescription.sdp,type:e})}constructor(e){this.originalDescription=new Mp.window.RTCSessionDescription(e)}toJSON(){return this.originalDescription.toJSON()}},RV=class{constructor(e,t,i,n,r,s,a,o,l,c,d){this.logger=e,this.configProvider=t,this.diagnostics=i,this.reinvitelessContext=n,this.mediaManager=r,this.audioCodecManager=s,this.ufdManager=a,this.sessionContext=o,this.qualityManager=l,this.streamSendersManager=c,this.callbacks=d,this.negotiationQueue=new tk(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=DU({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.mediaContentTypeInternal=un("webrtcMediaContentType",this.sessionContext.config,this.configProvider.config),this.allowedMediaContentTypeInternal=un("webrtcAllowedMediaContentType",this.sessionContext.config,this.configProvider.config).concat(),this.useNGC1webrtcContentType=un("useNGC1webrtcContentType",this.sessionContext.config,this.configProvider.config),this.negotiationCompletedDefer=new Kt,this.iceCandidatesDeferred=new Kt,this.iceCandidateReceivedInternal=!1,this.initialNegotiationCompleted=!1,this.terminated=!1,this.sessionDescription=wL.build({sdpTransform:new AV(this.sessionContext),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:{unifiedPlanEnabled:!0,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}),this.negotiationEmulator=new zU(this.logger.createChild("negotiationEmulator"),PV,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(e){this.isRollbackSupported=e}set iceCandidateReceived(e){this.iceCandidateReceivedInternal=e}get mediaContentType(){return this.useNGC1webrtcContentType?Gi.CONTENT_TYPE.SDP_NGC:this.mediaContentTypeInternal}setInternals(e,t,i){this.logger.safe.debug(`Setting internals tm: ${!!e} tsp: ${!!t} dc: ${!!i}`),this.transceiverManager=e,this.transportStateProvider=t,this.dataChannel=i}terminate(e){this.logger.safe.info(`[${e}] terminating`),this.terminated=!0,this.canTriggerRenegotiation=!1,this.negotiatedModalitiesInternal={},this.resetCandidateGathering(e),this.negotiationCompletedDefer.reject("webRtcSession cleanup"),this.negotiationQueue.dispose()}pauseNegotiations(e=be()){const t=new Kt;return this.negotiationCompletedDefer.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}async configureModalities(e,t,i){return this.configureModalitiesPromise=(async()=>{if(await this.configureModalitiesPromise,!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const n=tn(e),r=tn(this.negotiatedModalities);this.configProvider.config.alwaysNegotiateDataChannel&&(delete n.data,delete r.data);const s=!this.configuredModalities||!em(n,r);this.logger.safe.info(`[${t}] configureModalities ${tt(this.configuredModalities)} -> ${tt(e)} (${s?`update from ${tt(this.negotiatedModalities)}`:"fulfilled"})`),this.configuredModalities=e,s&&!this.updateSendStreamsReinviteless(t,i)&&(this.configProvider.config.removeSendersOnConfigureModalities&&!Yp(this.configuredModalities)&&await this.streamSendersManager.update(e,1,t),this.triggerRenegotiation(!1,t,i))})(),this.configureModalitiesPromise.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${tt(e)}`)})),this.configureModalitiesPromise}async completeNegotiation(e){this.mediaManager.commit();let t=Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,this.negotiatedModalities)&&!this.triggerRenegotiationFlag;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${t} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`);let i=this.negotiatedModalities;if(this.streamSendersManager.pendingStreamsPromise){this.logger.safe.info(`[${e}] Waiting for stream acquisitions to complete...`);const n=await this.streamSendersManager.pendingStreamsPromise;this.streamSendersManager.clearStreamsPromise(),this.logger.safe.info(`[${e}] Stream acquisitions completed: ${tt(n)}`),Xp(this.configProvider,n,this.negotiatingModalities,this.negotiatedModalities)||(this.logger.safe.warn(`[${e}] Some streams were not acquired successfully, considering the negotiation as incomplete`),i=n,t=!1)}return t||this.triggerRenegotiation(!1,e),this.initialNegotiationCompleted=!0,this.negotiationCompletedDefer.resolve(),{isComplete:t,activeModalities:i,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal}}async rejectNegotiation(e,t,i=!1){let n;this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${tt(e)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.qualityManager.clearPendingCapabilities();const r=nm(this.negotiatedModalities,this.negotiatingModalities);this.logger.safe.debug(`[${t}] configured modalities for rollback: ${JSON.stringify(r)}`),this.transceiverManager?.syncTransceivers(r),this.sessionContext.getSmallCallTelemetry()?.setEventType("rejectNegotiation"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const s=Yp(r);Yp(this.negotiatedModalities)!==s&&await this.streamSendersManager.setHold(s,t),s?this.logger.safe.info(`[${t}] Hold is configured. Not updating streams`):await this.streamSendersManager.update(r,0,t);const a=this.transportStateProvider?.signalingState;if("have-local-offer"===a){n={},this.logger.safe.info(`[${t}] rolling back local description`);try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRollback){n.type="LocalRN",this.logger.safe.info(`[${t}] rolling back using local renegotiation`);const e=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(e,!0),this.logger.safe.info(`[${t}] rolling back using local complete`)}else this.logger.safe.info(`[${t}] rolling back using rollback`),n.type="Rollback",await this.callbacks.setLocalDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error: ${tt(e)}`),n.error=e}}else if("have-remote-offer"===a){n={};try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRemoteRollback){n.type="RemoteRN",this.logger.safe.info(`[${t}] applying answer for remote renegotiation`);const e=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(e,!0,"remote")}else this.logger.safe.info(`[${t}] rolling back using rollback on remote description`),n.type="Rollback",await this.callbacks.setRemoteDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error: ${tt(e)}`),n.error=e}}else this.callbacks.hasPC()&&this.logger.safe.error(`[${t}] cannot rollback local description in current state: ${this.transportStateProvider.signalingState}`);return this.canTriggerRenegotiation=!0,this.negotiationCompletedDefer.reject("negotiation rejected"),i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:r,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal,rollback:n}}triggerRenegotiation(e,t=be(),i){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired(t,i)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}configureCrypto(e,t){let i=!1;const n=gm(this.configProvider,t);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.diagnostics.offeredSrtp=e,i=!e.dtls||e.sdes&&n}else i=n;return i&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1})),this.diagnostics.negotiatedSrtp={dtls:!i,sdes:!!i},i?0:1}createOffer(e,t){const i=this.negotiationQueue.add((()=>this.createOfferAsync(e,t)),e);return this.resetNegotiationQueue(e),i}processOffer(e,t){const i=this.negotiationQueue.add((()=>this.processOfferAsync(e,t)),t);return this.resetNegotiationQueue(t),i}async createAnswer(e,t){if((this.sessionContext.config.isPstnCall?!this.configProvider.config.createProvisionalAnswer.enabledPstn:!this.configProvider.config.createProvisionalAnswer.enabled)&&e)return this.logger.safe.info("createAnswer(): Ignoring provisional answer"),{blob:"",contentType:this.mediaContentType};const i=e?"pranswer":"answer",n=e?"createProvisionalAnswerAsync":"createAnswerAsync",r=this.diagnostics.getTimerTracker(n,{first:!0});if(r.mark("start"),this.logger.safe.info(`[${t}] create [${i}] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),!this.configuredModalities)throw new Error("no configured modalities to create answer for");let s=this.negotiatingModalities=Qp(this.offeredModalities,this.configuredModalities);await this.callbacks.assurePC(t,r.clone("assurePeerConnectionAsync"));const a=this.transportStateProvider.isWaitingAcceptProvisional;if(this.transportStateProvider.isWaitingAcceptProvisional=e,r.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${t}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),!this.offeredDescription.isCodecSwitchSupported())try{const e=(await this.capabilityGatherer.getCapabilities(Gi.MEDIA_TYPE.audio)).codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(e)}catch(e){this.logger.safe.error(`[${t}] failed to set primary codec based on audio capability ${tt(e)}`)}r.markAndMeasure("assurePeerConnectionAsync","handleCodecSwitchUnsupported"),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.offeredDescription.setModalities(s),await this.detectSendProfileSupport();const o=this.offeredDescription.toRemote(e||a);this.configProvider.config.createProvisionalAnswer.streamsBeforeSetFullRD&&!e&&a&&["have-remote-offer","stable"].includes(this.transportStateProvider.signalingState)&&!this.initialNegotiationCompleted&&(this.logger.safe.info(`[${t}] create [${i}] provisional was applied, requesting streams and activating senders before set remote description is finished`),await this.updateStreamSenders(r,t,e,s)),this.logger.unsafe.info(`[${t}] create [${i}] set remote description', 'negotiated:`,s,"sdp:",o),await this.callbacks.setRemoteDescription({sdp:o,type:"offer"}),r.markAndMeasure("handleCodecSwitchUnsupported","setRemoteDescription"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data),await this.updateStreamSenders(r,t,e,s),r.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),r.markAndMeasure("setRemoteDescription","assureStreamsAndDataChannel"),this.callbacks.onTransportInitialized();const l=this.configProvider.config.createProvisionalAnswer.setProperAnswerType?await this.callbacks.createAnswer({type:i}):await this.callbacks.createAnswer();r.markAndMeasure("assureStreamsAndDataChannel","createAnswer"),this.logger.unsafe.info(`[${t}] create [${i}] answer from peer connection type: ${l.type}, sdp:`,l.sdp);const c=this.sessionDescription.createLocalAnswer(l.sdp);this.hasIceCandidates(c)||this.resetCandidateGathering(t),this.callbacks.startWaitingForStreamStart(s),this.setupIceGatheringTimeout(t);const d=c.toLocal();this.logger.unsafe.info(`[${t}] create [${i}] set local description sdp:`,d),await this.callbacks.setLocalDescription({sdp:d,type:this.configProvider.config.createProvisionalAnswer.setProperAnswerType?i:"answer"}),r.markAndMeasure("createAnswer","sLD"),await this.iceCandidatesDeferred.promise,r.markAndMeasure("sLD","candidates");const u=this.sessionDescription.createLocalAnswer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(u),u.updateModalities(s),this.checkIceCandidates(u),e&&this.configProvider.config.createProvisionalAnswer.forceRecvonly&&(this.logger.safe.info(`[${t}] create [${i}] munge returned local sdp to recvonly modalities`),u.forceRecvonly());const h=u.toAnswer();this.audioCodecManager.decoder?.setRecvPayloads(u.getPayloadsForMedia(Gi.MEDIA_TYPE.audio)),this.checkAudioCodecNegotiated(t),e?this.logger.safe.debug(`[${t}] create [${i}] skip stream senders manager activation`):(this.logger.safe.debug(`[${t}] create [${i}] activating stream senders manager`),await this.streamSendersManager.activate(t)),r.markAndMeasure("candidates","streamSendersManagerActivate"),e?this.logger.safe.debug(`[${t}] create [${i}] skip updating sources and capabilities`):(this.logger.safe.debug(`[${t}] create [${i}] updating sources and capabilities`),this.callbacks.updateLocalMediaSources(),this.applyReceiveCapabilities(t)),s=u.getModalities(),this.reinvitelessContext.enabled&&(s=nm(this.negotiatingModalities,s)),Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,s)||this.triggerRenegotiation(!0,t),this.negotiatedModalities=s,this.diagnostics.bweType=u.getBweType(),this.logger.unsafe.info(`[${t}] CREATE ANSWER`,"sdp:",h);const g={blob:h,contentType:this.mediaContentType};return this.configProvider.countryCode&&(g.clientLocation=this.configProvider.countryCode),this.reinvitelessContext.enabled&&(g.mediaDescriptions=this.getMediaDescriptions(s)),this.callbacks.setBWSeed(g),r.markAndMeasure("start",n),g}async detectSendProfileSupport(){if(this.configProvider.config.preferredH264VideoSendProfile||this.configProvider.config.preferredH264SharingSendProfile){let e=this.capabilityGatherer;this.configProvider.config.learnCodecSendCapabilitiesFromSenderApi&&(e=DU({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0));const t=await e.getCapabilities("video"),i=this.mediaManager.getMediaEntities().filter((e=>{const t=e.getModality();return t===Gi.MEDIA_TYPE.video||t===Gi.MEDIA_TYPE.sharing})).filter((e=>e.isEnabled()));for(const e of t.codecs)if(e.sdpFmtpLine&&e.mimeType.toLocaleLowerCase().includes("h264")){const t=e.sdpFmtpLine.match(/profile-level-id=([a-fA-F0-9]{6})/);2===t?.length&&i.forEach((e=>e.addSupportedSendProfile("H264",t[1])))}}}async updateStreamSenders(e,t,i,n){this.transceiverManager.syncTransceivers(n),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)}));const r=Yp(this.negotiatingModalities);if(Yp(this.negotiatedModalities)!==r&&(e?.mark("startConfigureHold"),await this.streamSendersManager.setHold(r,t),e?.markAndMeasure("startConfigureHold","configureHold")),r)this.logger.safe.info(`[${t}] Hold is configured. Not updating streams`);else{let r=this.configProvider.config.negotiationParallelStreamAcquisitionCreateAnswer&&!this.initialNegotiationCompleted?2:0;i&&(r=4),await this.streamSendersManager.update(n,r,t),e?.markAndMeasure("configureHold","updateStreams")}}configureBroadcastScenario(e,t){const i=this.configProvider.config.broadcastMode;this.diagnostics.meetingScenario=e.meetingScenario,(i?.prioritizeLayoutOnServer||i?.prioritizeLayoutOnClient||i?.maxSessionBandwidthKbps)&&e.meetingScenario&&i.townHallScenarioNames?.length&&-1!==i.townHallScenarioNames.map((e=>e.toLowerCase())).indexOf(e.meetingScenario.toLowerCase())&&(this.sessionContext.config.isTownHall=!0,this.diagnostics.isTownHall=!0,i?.maxSessionBandwidthKbps&&this.configProvider.overrideMaxSessionBandwidth(i.maxSessionBandwidthKbps)&&(this.logger.safe.info(`Adjusting maxSessionBandwidth for TownHall: ${this.configProvider.mediaConfig.maxBandwidthInKbps}`),this.triggerRenegotiation(!0,t)))}async processAnswer(e,t,i,n=!1){try{const r=e.blob;this.logger.unsafe.debug(i?`[${t}] PROCESS PRANSWER`:`[${t}] PROCESS ANSWER`,"sdp:",r);const s=i?"pranswer":"answer";if(i&&(!function(e,t=!1){const i=!e.configProvider.config.acceptProvisionalAnswerFromPstnOnly||t;return e.config.isPstnCall?e.configProvider.config.acceptProvisionalAnswerPstn&&i:e.configProvider.config.acceptProvisionalAnswer}(this.sessionContext,n)||"have-local-offer"!==this.transportStateProvider.signalingState))return void this.logger.safe.info(`[${t}] process [${s}] ignored`);this.configureBroadcastScenario(e,t);const a=this.diagnostics.getTimerTracker(i?"processProvisionalAnswerAsync":"processAnswerAsync",{first:!0});a.mark("start");const o=this.sessionDescription.createRemoteAnswer(r);let l=qp(o.getModalities());this.reinvitelessContext.enabled&&(l=nm(this.offeredModalities,l)),o.setModalities(l),await this.detectSendProfileSupport();const c=o.toRemote();if(i||(this.useNGC1webrtcContentType||(this.mediaContentType=e.contentType),-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType),Yp(l)||(await this.streamSendersManager.update(l,1,t),a.markAndMeasure("start","streamSendersManagerUpdate"),Wp(this.offeredModalities.data)&&!l.data&&this.dataChannel?.disable()),this.negotiatedModalities=l,this.callbacks.updateLocalMediaSources(),this.diagnostics.bweType=o.getBweType()),this.callbacks.onTransportInitialized(),this.logger.unsafe.info(`[${t}] process [${s}] set remote description`,"negotiated:",l,"sdp:",c),a.mark("startSetRemoteDescription"),await this.callbacks.setRemoteDescription({sdp:c,type:s}),a.markAndMeasure("startSetRemoteDescription","setRemoteDescription"),i)return;await this.streamSendersManager.activate(t),a.markAndMeasure("setRemoteDescription","streamSendersManagerActivate"),this.applyReceiveCapabilities(t),this.checkAudioCodecNegotiated(t),this.transceiverManager.syncTransceivers(l),a.markAndMeasure("start","processAnswerAsync")}catch(e){if(i)return void this.logger.safe.warn(`Error thrown during pranswer generation, ignoring: ${tt(e)}`);throw e}}async createOfferAsync(e,t){const i=this.diagnostics.getTimerTracker("createOfferAsync",{first:!0});if(i.mark("start"),this.logger.safe.info(`[${e}] 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(e,i.clone("assurePeerConnectionAsync")),i.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${e}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),Yp(this.negotiatingModalities)&&!Xi(this.negotiatedModalities)&&Object.keys(this.negotiatingModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.negotiatingModalities[e]})),this.transceiverManager?.assureTransceivers(this.negotiatingModalities),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const n=Yp(this.negotiatingModalities);let r;Yp(this.negotiatedModalities)!==n&&(i?.mark("startConfigureHold"),await this.streamSendersManager.setHold(n,e),i?.markAndMeasure("startConfigureHold","configureHold")),n?(this.logger.safe.info(`[${e}] Hold is configured. Not updating streams`),r=this.negotiatingModalities):(r=await this.streamSendersManager.update(this.negotiatingModalities,this.configProvider.config.negotiationParallelStreamAcquisitionCreateOffer&&!this.initialNegotiationCompleted?2:0,e),i?.markAndMeasure("configureHold","updateStreams"),this.dataChannel&&this.negotiatingModalities.data&&(r.data=this.negotiatingModalities.data)),i.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),this.offeredModalities=r,!mm(this.sessionContext)&&this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[Gi.MODALITY.data]&&this.sessionContext.config?.isConference&&(this.offeredModalities[Gi.MODALITY.data]=Gi.MEDIA_STATE.inactive),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)}`);const s=await this.callbacks.createOffer();i.markAndMeasure("assureStreamsAndDataChannel","createOffer"),this.logger.unsafe.info(`[${e}] create [offer] offer from peer connection, sdp: ${s.sdp}`);const a=this.sessionDescription.createLocalOffer(s.sdp);this.hasIceCandidates(a)||this.resetCandidateGathering(e),this.callbacks.startWaitingForStreamStart(r),this.setupIceGatheringTimeout(e);const o=a.toLocal();this.logger.unsafe.info(`[${e}] create [offer] set local description`,"sdp:",o),await this.callbacks.setLocalDescription({sdp:o,type:"offer"}),i.markAndMeasure("createOffer","sLD"),await this.iceCandidatesDeferred.promise,i.markAndMeasure("sLD","candidates");const l=this.sessionDescription.createLocalOffer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(l),l.updateModalities(this.offeredModalities),this.checkIceCandidates(l);const c=l.toOffer();this.logger.unsafe.info(`[${e}] CREATE OFFER`,"sdp:",c);const d={blob:c,contentType:this.mediaContentType};""===this.configProvider.mediaConfig.webrtcRequiredFeatures||this.sessionContext.config.isConference||(d.requiredFeatures=this.configProvider.mediaConfig.webrtcRequiredFeatures),this.audioCodecManager.decoder?.setRecvPayloads(l.getPayloadsForMedia(Gi.MEDIA_TYPE.audio)),this.configProvider.countryCode&&(d.clientLocation=this.configProvider.countryCode),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)}));const u=a.isIceRestart();return this.logger.safe.info(`[${e}] ICE restart: ${u}`),this.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&u&&!this.sessionContext.config.isConference&&a.getSrtpInfo().sdes&&(d.newOffer=!0),this.reinvitelessContext.enabled&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),d.mediaDescriptions=this.getMediaDescriptions(this.offeredModalities)),t&&(d.negotiationTag=t),this.callbacks.setBWSeed(d),i.markAndMeasure("start","createOfferAsync"),d}async processOfferAsync(e,t){const i=this.diagnostics.getTimerTracker("processOfferAsync",{first:!0});i.mark("start"),this.mediaManager.backup();const n=e.blob;if(this.logger.unsafe.info(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&!this.useNGC1webrtcContentType&&(on(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),this.configureBroadcastScenario(e,t),this.offerOriginator&&this.offerOriginator!==e.originator&&this.configProvider.config.rejectIncompatibleOriginator)throw{detail:"mediaContent.originator is different on renegotiation",type:Gi.MEDIA_ERROR.incompatibleOriginator};if(this.offerOriginator=e.originator,e.requiredFeatures){const t=this.configProvider.mediaConfig.webrtcRejectedFeatures.split(",");ln(e.requiredFeatures.split(","),t)}if(this.initiatorInternal=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.configProvider.config.multiStreamSupported){const e=function(e){const t=e.match(/a=x-multi-stream:(\d+)/);if(t)return parseInt(t[1])}(n),i=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;this.configProvider.mediaConfig.multiStreamChannelsOffered=e,e<i&&(this.logger.safe.info(`Received ${e} multi stream channels, ${i} channels supported`),this.triggerRenegotiation(!0,t))}this.canTriggerRenegotiation=!1,this.offeredModalities=qp(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 r=this.configProvider.config.removeUnsupportedVideoModality?this.offeredModalities:tn(this.offeredModalities);if(Wp(this.offeredModalities.video)||Kp(this.offeredModalities.video)||Wp(this.offeredModalities.sharing)||Kp(this.offeredModalities.sharing)){const n=this.offeredDescription.getVideoCodecs();try{i.mark("startGetCapabilities");const e=await this.capabilityGatherer.getCapabilities("video");i.markAndMeasure("startGetCapabilities","getCapabilities"),e.codecs.some((e=>n.some((t=>e.mimeType===t&&this.configProvider.config.primaryVideoCodecs.includes(t)))))||(this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`),this.disabledModalities.video=r.video,this.disabledModalities.sharing=r.sharing,delete r.video,delete r.sharing)}catch(e){this.logger.safe.error(`[${t}] failed to get video capability ${tt(e)}`)}}return(!mm(this.sessionContext)&&(Wp(this.offeredModalities.data)||Kp(this.offeredModalities.data))||"Failed"===this.dataChannel?.state)&&(this.logger.safe.info(`[${t}] Supressing data modality as data channel is not possible`),r=tn(r),delete r.data),i.markAndMeasure("start","processOfferAsync"),this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(r)}`),r}async startMediaDescriptionsUpdate(e,t){this.dataChannel?.updateDataModalityState(this.reinvitelessRequestedModalities?.data);const i=Yp(this.negotiatedModalities),n=Yp(this.reinvitelessRequestedModalities);return i!==n&&await this.streamSendersManager.setHold(n,e),n?this.reinvitelessAppliedModalities=this.reinvitelessRequestedModalities:(this.reinvitelessAppliedModalities=await this.streamSendersManager.update(this.reinvitelessRequestedModalities,0,e),this.dataChannel&&this.reinvitelessRequestedModalities.data&&(this.reinvitelessAppliedModalities.data=this.reinvitelessRequestedModalities.data)),this.callbacks.updateLocalMediaSources(),await this.streamSendersManager.activate(e),this.getMediaDescriptions(this.reinvitelessAppliedModalities,t)}async completeMediaDescriptionsUpdate(e){this.logger.safe.info(`[${e}] complete media descriptions update`),this.negotiatedModalities=this.reinvitelessAppliedModalities;const t=this.reinvitelessAppliedModalities,i=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:t,requestedModalities:i}}async rejectMediaDescriptionsUpdate(e,t=!1){this.logger.safe.info(`[${e}] reject media descriptions update`),t&&(this.logger.safe.info(`[${e}] trigger renegotiation after failed media descriptions update`),this.triggerRenegotiation(!1,e));const i=await this.streamSendersManager.update(this.negotiatedModalities,1,e),n=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:i,requestedModalities:n}}getMediaDescriptions(e,t){if(Yp(e))return{};const i=[];for(const t of this.mediaManager.getMediaEntities()){if(!t.getExtension("reinviteless"))continue;const n=e[t.getModality()],r={mid:t.getMid(),direction:!t.getLocalTrackId()&&Wp(n)?zp(n):n};i.push(r)}return{descriptions:i,negotiationTag:t}}updateSendStreamsReinviteless(e,t){if(Xi(this.negotiatedModalities)||Yp(this.negotiatedModalities)||Yp(this.configuredModalities))return!1;this.reinvitelessRequestedModalities=tn(this.negotiatedModalities);for(const[e,t]of Object.entries(this.configuredModalities)){const i=this.mediaManager.getMediaEntitiesByModality(e)[0];i?.getExtension("reinviteless")&&(this.reinvitelessRequestedModalities[e]=t)}return!an(this.reinvitelessRequestedModalities,this.negotiatedModalities)&&(this.callbacks.onUpdateMediaDescriptionsRequired(e,t),an(this.reinvitelessRequestedModalities,this.configuredModalities))}checkAudioCodecNegotiated(e){const t=this.audioCodecManager.negotiationCompleted();if(this.audioCodecManager.decoder?.getUnmixedAudioProvider()?.configured){const i=t?"Good":"Bad";this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable",i,"Audio",!0,e)}}fixLocalDescription(e){this.configProvider.config.insertFakeCandidateIfNeeded&&(this.iceCandidateReceivedInternal||!this.iceCandidateReceivedInternal&&this.transportStateProvider.isIceConnected)&&(this.diagnostics.fakeCandidate=e.insertFakeCandidateIfNeeded()),e.fixDataModality()}applyReceiveCapabilities(e){const t=this.mediaManager.getMediaEntities().map((e=>e.getRemoteRecvCapabilities()));this.sessionContext.config?.isConference?this.qualityManager.setPendingCapabilities():this.qualityManager.setMaxCapabilities(t,e)}resetNegotiationQueue(e){this.negotiationCompletedDefer.reject("promise expired"),this.setNegotiationPromise(new Kt,e)}setNegotiationPromise(e,t=be()){this.terminated||(this.negotiationCompletedDefer=e,this.negotiationQueue.add(this.negotiationCompletedDefer,t))}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Gi.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&this.transportStateProvider.isIceConnected)return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.sessionContext.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=window.setTimeout((()=>{this.iceCandidatesTimer=void 0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Kt,this.iceCandidateReceivedInternal=!1}set offeredModalities(e){this.offeredModalitiesInternal=e,this.diagnostics.offeredModalities=e}set negotiatedModalities(e){this.logger.safe.info(`setNegotiatedModalities ${JSON.stringify(e)}`),this.negotiatedModalitiesInternal=e,this.diagnostics.negotiatedModalities=e}set configuredModalities(e){this.configuredModalitiesInternal=e}set mediaContentType(e){this.mediaContentTypeInternal=e}},MV=class{constructor(e){this.mcpConfig=e,this.data={sourceRequestsSignaling:{},sourceRequestsMCP:{},fallbackMCPMessagesCounter:0,sourceRequestsResponses:{},errors:[]}}setRecord(e,t,i){const n={sequenceNumber:t,timestamp:Date.now(),sourceId:i?.sourceId,fmtp:i?.fmtParams};e.records??(e.records=[]),Sn(e.records,n,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperation(e,t){var i;(i=this.data.sourceRequestsSignaling)[e]??(i[e]={counter:0}),this.data.sourceRequestsSignaling[e].counter++}recordMCPOperation(e,t,i){var n;(n=this.data.sourceRequestsMCP)[e]??(n[e]={counter:0}),this.data.sourceRequestsMCP[e].counter++,this.mcpConfig.verboseTelemetry&&this.setRecord(this.data.sourceRequestsMCP[e],t,i)}recordError(e,t){const i=[Date.now(),t,e];Sn(this.data.errors,i,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperationDuration(e,t){const i=this.data.sourceRequestsSignaling[e]?.records?.find((e=>e.sequenceNumber===t));i&&(i.duration=Date.now()-i.timestamp)}recordMCPMessageFallback(e,t){if(this.data.fallbackMCPMessagesCounter++,this.mcpConfig.verboseTelemetry){const i=this.data.sourceRequestsMCP[t]?.records?.find((t=>t.sequenceNumber===e));i&&(i.fallback=!0,i.fallbackTimestamp=Date.now())}}recordSrResultReceived(e,t,i){var n;if(this.mcpConfig.verboseTelemetry){const n=this.data.sourceRequestsMCP[i]?.records?.find((e=>e.sequenceNumber===t));n&&(n.duration=Date.now()-n.timestamp,n.result=e)}(n=this.data.sourceRequestsResponses)[e]??(n[e]=0),this.data.sourceRequestsResponses[e]++}getObjectRef(){return this.data}},DV=class{constructor(e){this.mcpConfig=e,this.storage={createTime:Date.now(),startedCount:0,stoppedCount:0,clientCapabilities:[],events:[]},this.sourceRequestSenderDiagnostics=new MV(this.mcpConfig)}get getSourceRequestSenderDiagnostics(){return this.sourceRequestSenderDiagnostics}logStarted(){if(this.storage.startedCount++,this.storage.startedCount>5)return;const e={startedTs:kV(this.storage.createTime),mpCapabilities:{},sentMessages:{},recvMessages:{},sentFailed:0,recvFailed:0,cachedDshReceived:!1};this.storage.events.push(e),this.lastEventConnecting=!0}logStopped(){this.storage.stoppedCount++;const e=this.getCurrentDCSessionEvent();e&&(e.stoppedTs=kV(this.storage.createTime)),this.lastEventConnecting=!1}logSentMsg(e){var t,i;const n=this.getCurrentDCSessionEvent();n&&((t=n.sentMessages)[i=e.type]??(t[i]=0),n.sentMessages[e.type]++)}logReceivedMsg(e){var t,i;this.lastEventConnecting=!1;const n=this.getCurrentDCSessionEvent();n&&((t=n.recvMessages)[i=e.type]??(t[i]=0),n.recvMessages[e.type]++,"dsh"!==e.type||n.handshakeDuration||(n.cachedDshReceived=!0))}logHandshakeStarted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeStartedTs=Date.now()),this.storage.clientCapabilities=e}logHandshakeCompleted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeDuration||(t.handshakeDuration=kV(t.handshakeStartedTs)),t.mpCapabilities.send=e.send_capabilities,t.mpCapabilities.recv=e.receive_capabilities)}logHandshakeFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeDuration=kV(t.handshakeStartedTs),t.handshakeFailedWithError=e)}logSentFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.sentFailed++,t.lastSentFailed={ts:kV(this.storage.createTime),error:e})}logRecvFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.recvFailed++,t.lastRecvFailed={ts:kV(this.storage.createTime),error:e})}logTimeout(){if(this.storage.startedCount>=5&&!this.lastEventConnecting)return;const e={timeoutTs:Date.now()},t=this.getCurrentDCSessionEvent();t&&(e.handshakeStartedTs=t.handshakeStartedTs),this.lastEventConnecting&&this.storage.events.pop(),this.storage.events.push(e),this.lastEventConnecting=!1}getReport(){const e=this.sourceRequestSenderDiagnostics.getObjectRef();return this.storage.sourceRequestsReport=e,this.storage}getCurrentDCSessionEvent(){const e=this.storage.events[this.storage.events.length-1];return this.storage.startedCount<=5&&void 0!==e?.startedTs?e:null}};function kV(e){return Date.now()-e}var OV=class extends gt{constructor(e,t,i){super(),this.dataChannel=e,this.logger=t,this.mcpConfig=i,this.mcpState="Created",this.handshakeTimeout=null,this.telemetryLogger=new DV(this.mcpConfig),this.mcpSupportedFeatures={sourceRequestsEnabled:!1,sourceRequestsResponseEnabled:!1,dominantSpeakerHistoryEnabled:this.mcpConfig?.enableDominantSpeakerHistory,senderSideBandwidthEstimationEnabled:!1},this.subscribeToDataChannel()}getTelemetryLogger(){return this.telemetryLogger}mcpFeaturesSupported(e){return this.mcpSupportedFeatures[e]}switchMcpFeature(e,t){this.logger.warn(`Switching ${e} to ${t}`),this.mcpSupportedFeatures[e]=t}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(e){return this.sendMsgInternal(e)}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",((e,t,i)=>this.processIncomingData(e,i)))}onDataChannelStateChanged(){switch(this.dataChannel.state){case"Connected":this.onDCStarted();break;case"Closed":case"Destroyed":this.onDCStopped()}}async startHandshake(){try{this.mcpState="Handshaking";const e=[];this.mcpConfig.enableDominantSpeakerHistory&&e.push("dsh"),this.mcpConfig.enableBweNotifications&&e.push("bwe"),this.mcpConfig.enableSourceRequests&&e.push("sr"),this.mcpConfig.enableSendBandwidthNotificationsEnabled&&e.push("ssbwe"),this.telemetryLogger.logHandshakeStarted(e),this.logger.info(`Send syn, client capabilities: ${JSON.stringify(e)}`),await this.sendMsgInternal({type:"syn",client_capabilities:e}),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(e){this.logger.error(`Handshake failed with: ${tt(e)}`),this.telemetryLogger.logHandshakeFailed(tt(e))}}async sendMsgInternal(e){const t=Array.isArray(e)?e:[e],i=(new TextEncoder).encode(JSON.stringify(t)),n=new Uint8Array(1+i.length);n[0]=1,n.set(i,1);try{await this.dataChannel.sendMessage(18,void 0,n,[4294967292]);for(const e of t)this.telemetryLogger.logSentMsg(e)}catch(e){throw this.logger.error(`Send failed: ${tt(e)}`),this.telemetryLogger.logSentFailed(tt(e)),e}}processIncomingData(e,t){if(18!==e)return;if(1!==t[0]){const e=`Unsupported header version ${t[0]}`;return this.logger.info(e),void this.telemetryLogger.logRecvFailed(e)}const i=new DataView(t.buffer,1);let n;try{const e=(new TextDecoder).decode(i);n=JSON.parse(e)}catch(e){return this.logger.error(`Failed to parse received data, error ${tt(e)}`),void this.telemetryLogger.logRecvFailed(tt(e))}for(const e of n)switch(this.telemetryLogger.logReceivedMsg(e),e.type){case"syn":break;case"ack":this.processAckMsg(e);break;case"bwe":this.processBweMsg(e);break;case"dsh":this.processDshMsg(e);break;case"sr_res":this.processSrResMsg(e);break;default:{const t=`Unsupported msg type ${e.type}`;this.logger.error(t),this.telemetryLogger.logRecvFailed(t)}}}processDshMsg(e){this.mcpConfig.enableDominantSpeakerHistory&&(this.logger.debug(`DSH received: ${JSON.stringify(e)}`),this.event("mpDshChanged").raise(e.history))}processSrResMsg(e){this.mcpConfig.enableSourceRequests&&this.event("mpSrResReceived").raise(e.sequenceNumber,e.result),this.mcpState="Active"}processBweMsg(e){this.mcpConfig.enableBweNotifications&&this.event("mpSendBandwidthChanged").raise(e.bw)}processAckMsg(e){this.telemetryLogger.logHandshakeCompleted(e),this.logger.info(`Ack received: ${JSON.stringify(e)}`),this.switchMcpFeature("dominantSpeakerHistoryEnabled",!(!this.mcpConfig.enableDominantSpeakerHistory||!e.send_capabilities?.includes("dsh"))),this.switchMcpFeature("sourceRequestsEnabled",!(!this.mcpConfig.enableSourceRequests||!e.receive_capabilities?.includes("sr"))),this.switchMcpFeature("sourceRequestsResponseEnabled",!(!this.mcpConfig.enableSourceRequests||!e.send_capabilities?.includes("sr_res"))),this.switchMcpFeature("senderSideBandwidthEstimationEnabled",!(!this.mcpConfig.enableSendBandwidthNotificationsEnabled||!e.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"}},NV=class{constructor(e,t,i){this.mediaControlPlane=e,this.sendSignalingMessage=t,this.logger=i,this.pendingSourceRequests=new Map,this.mediaControlPlane&&(this.diagnostics=this.mediaControlPlane.getTelemetryLogger().getSourceRequestSenderDiagnostics,this.mediaControlPlane.on("mpSrResReceived",((e,t)=>this.onMsgReceived(e,t))))}mapToSignalingOperation(e){switch(e){case"ApplyChannelParametersSourceRequest":case"ApplyChannelParametersVideoCapabilities":return 0;case"ControlVideoStreaming":return 1;default:return this.logger.error("Unknown send operation"),null}}send(e,t,i,n){switch(e){case"ApplyChannelParametersSourceRequest":return this.sendMcpMessage(e,t,i,n);case"ApplyChannelParametersVideoCapabilities":case"ControlVideoStreaming":return this.sendSignalingMessage?(this.diagnostics?.recordSignalingOperation(e),this.sendSignalingMessage(this.mapToSignalingOperation(e),t)):Promise.reject(new Error("no signaling session"));default:return this.logger.warn(`Unable to send message reason: Operation unknown ${e}`),Promise.reject(new Error("Unable to send message"))}}setResendingMechanism(e,t,i,n){const r=window.setTimeout((()=>{this.logger.warn(`Timed out message ${e}, sending message through signaling`),this.resendPendingMessageThroughSignaling(e,n)}),this.mediaControlPlane?.getConfig().sourceRequestsMessagesTimeout);this.pendingSourceRequests.set(e,{sequenceNumber:e,timeoutId:r,deferred:t,message:i,operation:n})}isAllowedToSendMcpMessage(){if(!this.mediaControlPlane)return!1;const e=this.mediaControlPlane.getMcpState(),t=this.mediaControlPlane.getConfig();return"Created"!==e&&("Handshaking"===e?t.sendBeforeAck&&t.enableSourceRequests:"Active"===e&&this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled"))}isResendingMechanismRequired(e){return this.mediaControlPlane.getConfig().setResendingMechanism&&"ApplyChannelParametersSourceRequest"===e}async sendMcpMessage(e,t,i,n){if(this.isAllowedToSendMcpMessage()){const r=new Kt;this.isResendingMechanismRequired(e)&&this.setResendingMechanism(i,r,n,e);try{return this.diagnostics.recordMCPOperation(e,i,t.controlVideoStreaming?.controlInfo),await this.mediaControlPlane.sendMsg(t),this.logger.info(`Sending ${t.type} by MCP sequenceNumber:${i}`),this.isResendingMechanismRequired(e)?r.promise:Promise.resolve()}catch(t){const n=tt(t);this.diagnostics.recordError(n,i),this.logger.error(`sendMsgInternal failed with error: ${n}`),this.isResendingMechanismRequired(e)&&this.clearPendingSourceRequestTimeout(i)}}if(!this.sendSignalingMessage)throw new Error("no signaling session");return this.diagnostics?.recordSignalingOperation(e),this.logger.info(`Sending SR by signaling sequenceNumber:${i}`),this.sendSignalingMessage(this.mapToSignalingOperation(e),n)}async resendPendingMessageThroughSignaling(e,t){this.diagnostics.recordMCPMessageFallback(e,t);const i=this.pendingSourceRequests.get(e);try{this.diagnostics.recordSignalingOperation(i.operation),await this.sendSignalingMessage(this.mapToSignalingOperation(i.operation),i.message),i.deferred.resolve()}catch{this.logger.warn(`Failed to resend source request via signaling ${e}`),i.deferred.reject(new Error("Sending source request failed via signaling"))}finally{this.clearPendingSourceRequestTimeout(e)}}clearPendingSourceRequestTimeout(e){const t=this.pendingSourceRequests.get(e);t&&(this.pendingSourceRequests.delete(e),clearTimeout(t.timeoutId))}onMsgReceived(e,t){this.logger.info(`Received SR result: ${t} for sequenceNumber: ${e}`);const i=this.pendingSourceRequests.get(e);if(i){switch(this.diagnostics.recordSrResultReceived(t,e,i.operation),t){case"ok":case"duplicate":case"out_of_order":i.deferred.resolve();break;default:i.deferred.reject(`SequenceNumber: ${e} failed with ${t}!`)}this.clearPendingSourceRequestTimeout(e)}else this.logger.warn(`No pending SR found for sequenceNumber: ${e}`)}},LV=0,xV=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc2-"+ ++LV),this.videoFeatureManager=new pB(this.logger.createChild("VFM")),this.ufdManager=this.context.getUfdManager(),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.capabilityGatherer=DU({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.reinvitelessContext=function(e,t){const i=(t?e?.maxReinvitelessMediaForVideoMultiparty:e?.maxReinvitelessMediaForVideo1on1)||0,n=(t?e?.maxReinvitelessMediaForVBSSMultiparty:e?.maxReinvitelessMediaForVBSS1on1)||0;return{enabled:i>0||n>0,maxStreamsForModality:{video:i,sharing:n}}}(this.context.config.reinvitelessConfig,this.multiParty),this.iceHostCandidateOnly=this.multiParty&&un("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new tN({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:this.multiParty,reinviteltessContext:this.reinvitelessContext}),this.receiveStreamCollection=new Yx({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.diagnostics=this.context.diagnostics,this.qmDiagnostics=this.diagnostics.newQualityManagerDiagnostics(),this.statsGatherer=new vU(this.logger.createChild("stats"),this.configProvider,this.diagnostics,this.mediaManager,this.multiParty),this.networkQualityDiagnostics=new _V(this.configProvider),this.speechDetectionDiagnostics=new wV(this.configProvider),this.qualityManager=new XU(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,customBwEstimationEnabled:this.configProvider.config.webrtcEnabledCustomBwEstimationForVideo},this,this.statsGatherer,this.qmDiagnostics,this.configProvider),this.activeSpeakerManager=new Jx(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=cB({logger:this.logger,configProvider:this.configProvider}),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new cO(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e},this.diagnostics.newSubscriptionManagerDiagnostics()),this.remoteVideoResolutionManager=new eB(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.statsGatherer,this.diagnostics),this.remoteVideoManager=new sB(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.statsGatherer,this.diagnostics,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.encStreamsManager=new zm(this.configProvider,this.context.maContext.getEncodedStreamsWorkerProvider?.(),this.logger.createChild("EncodedStreamsManager")),this.streamSendersManager=new hV(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 Mg(this.logger.createChild("rawIncomingAudioStream")),this.useNullAudioStream=!1,this.audioCodecManager=new hf(this.encStreamsManager,this.logger,this.configProvider),this.perfMonitorSubs=[],this.performanceMonitor=new EV(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("PerformanceMonitor")),this.negotiation=new RV(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:(e,t)=>this.callbacks.onNegotiationRequired?.(e,t),onUpdateMediaDescriptionsRequired:(e,t)=>this.callbacks.onUpdateMediaDescriptionsRequired?.(e,t),updateLocalMediaSources:this.updateLocalMediaSources.bind(this),assurePC:this.assurePeerConnectionAsync.bind(this),hasPC:()=>!!this.peerConnection,createOffer:e=>this.peerConnection.createOffer(e),createAnswer:e=>this.peerConnection.createAnswer(e),setLocalDescription:e=>this.peerConnection.setLocalDescription(e),getLocalDescription:()=>this.peerConnection.localDescription,setRemoteDescription:e=>this.peerConnection.setRemoteDescription(e),setBWSeed:this.setBWSeed.bind(this),onTransportInitialized:()=>this.callbacks.onTransportInitialized(),startWaitingForStreamStart:e=>{this.statsGatherer.startWaitingForStreamStart(e)},getRollbackModifier:e=>new Xx(this.peerConnection,this.configProvider,e)}),this.streamConfigurationHandler=new uB(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",(e=>this.processStatsReport(e))),this.statsGatherer.on("onStatisticsChanged",(e=>this.processLegacyStats(e))),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.negotiation.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),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 mV({configProvider:this.configProvider})),this.perfMonitorSubs.push(this.performanceMonitor.on("onIncomingVideoQualityChanged",((e,t)=>{this.onIncomingVideoQualityChanged(e,t)}))),this.configProvider.config.webrtcVideoScaling&&(this.perfMonitorSubs.push(this.performanceMonitor.on("onOptimalVideoCountChanged",((e,t)=>{this.onOptimalVideoCountChanged(e,t)}))),this.onOptimalVideoCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)),this.configProvider.config.setBWSeed&&(this.bandwidthCache=new hD(this.configProvider)),this.diagnostics.reinvitelessContext=this.reinvitelessContext,this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&this.videoFeatureManager.manageFeatureSupport((()=>{if(this.detectVideoFeatures(),this.configProvider.config.enableDevtoolsAPI){const e=window?.webMA;e?.initVideoFeatures&&e.initVideoFeatures(this.videoFeatureManager)}}))}initializeMediaControlPlane(e){const t=this.dataChannel.getDataChannel(e);t?(this.mediaControlPlane=new OV(t,this.logger.createChild("MediaControlPlane"),this.configProvider.config.mediaControlPlaneConfig),this.mediaControlPlane.on("mpSendBandwidthChanged",(e=>{this.performanceMonitor.processNotification("BandwidthNotification",{bw:e}),this.bandwidthCache?.saveSeed(e),this.statsGatherer.addReportedReceiveBandwidth(e),this.diagnostics.addReportedReceiveBandwidth(e)})),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",(e=>{this.activeSpeakerManager.onDominantSpeakerHistoryChanged(e,"server")}))):this.logger.safe.error(`[${e}] Unable to initialize MediaControlPlane due to datachannel creation failure`)}getMediaControlPlaneInstance(){return this.mediaControlPlane}getAcceptedTypes(){return this.negotiation.allowedMediaContentType}clone(t,i){const n=tn(this.context);n.config=tn(this.context.config),n.config.webrtcMediaContentType=this.negotiation.mediaContentType,n.config.webrtcAllowedMediaContentType=this.negotiation.allowedMediaContentType,n.configProvider=i,n.diagnostics=this.context.diagnostics?.newNativeSession(!1),t?(n.config.isConference=!0,n.config.isPstnCall=!1):(n.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(n.config.webrtcIceGatheringTimeoutIncreased=!0));const r=new e(n,this.callId,this.callback);return this.useNullAudioStream&&r.useNullAudioStreamClient(),this.relayManagerProvider&&(r.relayManagerProvider=this.relayManagerProvider),r.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,r}async setCallConstraints(e,t){const i=this.configProvider.setCallConstraints(e);if(this.logger.safe.info(`[${t}] Setting call constraints ${JSON.stringify(i)}, enableDynamicCallConstraints: ${this.configProvider.config.enableDynamicCallConstraints}`),this.configProvider.config.enableDynamicCallConstraints)try{await this.streamSendersManager.applyCallConstraints(t),this.configProvider.addCallConstraintsTelemetryEvent(i,"applied")}catch(e){throw this.logger.safe.error(`Error while applying constraints: ${e}`),e}else this.configProvider.addCallConstraintsTelemetryEvent(i,"applied");return i}setInternals(e,t){this.logger.safe.info(`[${t}] Setting internals from previous session`),this.diagnostics.commitNativeSession(),e.subscriptionManager&&(this.subscriptionManager?.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setDiagnostics(this.diagnostics.newSubscriptionManagerDiagnostics()),this.subscriptionManager.setStreamProvider({getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e}),this.subscriptionManager.setLogger(this.logger.createChild("subs")),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager?.moveRenderers(this.remoteVideoManager),e.rawIncomingAudioStreamManager&&this.rawIncomingAudioStreamManager.updateHandlers(e.rawIncomingAudioStreamManager.handlerMap),this.audioRenderer.getStream()&&this.rawIncomingAudioStreamManager.streamChanged(this.audioRenderer.getStream())}setSubsForDeviceManager(){const e=this.getVideoDeviceManager();this.configProvider.config.enablePlayVideoOnStreamUnmuteWorkaround&&this.deviceManagerSubs.push(e.on("onAudioStreamMuted",(t=>{t||(this.remoteVideoManager.playVideo(),e.getLocalVideoRenderers().forEach((e=>e.playVideo())))})))}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.statsGatherer.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.statsGatherer.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,s)=>this.onSubscriptionChanged(e,t,i,n,r,s))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.statsGatherer.addSubscriptionEvent(e,t,i,n,r)))]}onSubscriptionChanged(e,t,i,n,r,s){t===Gi.MODALITY.video&&(2===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount()),3===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount())),this.statsGatherer.addSubscriptionEvent(e,t,i,n,null,r,s)}setSubsForStreamManagerEvents(){this.streamSendersManager.on("onSendStreamChanged",((e,t)=>{this.statsGatherer.updateSendStream(e,t),e?.hasAudio()&&this.diagnostics.setAudioSendStream(e,t),this.diagnostics.setPresentationAudioOnScreenSharing(e,t)})),this.streamSendersManager.on("onVideoCaptureFreeze",(e=>{this.transportStateProvider.isConnected&&!this.transportStateProvider.isWaitingAcceptProvisional&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"Bad":"Good","Video")})),this.streamSendersManager.on("onMaxVideoSendCapabilitiesChanged",((e,t)=>this.onMaxVideoSendCapabilitiesChanged(e,t))),this.streamSendersManager.on("onBandwidthAllocationChanged",(e=>this.onSendBandwidthChanged(e)))}move(e,t){this.logger.safe.info(`[${t}] moving to new session`),e.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager,rawIncomingAudioStreamManager:this.rawIncomingAudioStreamManager},t),e.muteHold(this.isMuteHold,t),this.isAudioInputMuted?e.muteInputAsync(t):e.unmuteInputAsync(t),this.isAudioOutputMuted?e.muteOutputAsync(t):e.unmuteOutputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.rawIncomingAudioStreamManager=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMute for ${e} with mute state ${t}`),this.streamSendersManager.setMuted(e,t,i),this.processLegacyStats(this.statsGatherer.getLastStatistics())}getConfiguredModalities(){return this.negotiation.configuredModalities}getDisabledModalities(){return this.negotiation.disabledModalities}createAudioElement(e){this.configProvider.config.devices.setSinkImmediately&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.assureAudioElement(e)}useNullAudioStreamClient(){this.useNullAudioStream=!0,this.streamSendersManager.useNullAudioStreamClient()}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){if(this.statsGatherer&&!this.statsGatherer.isDisposed){if(this.audioCodecManager){const e=this.audioCodecManager.getSessionEvents();this.statsGatherer.sessionInfo.setAudioCodecEvents(e),this.diagnostics.audioCodecEvents=e}this.statisticsReport=this.statisticsReport.then((()=>this.statsGatherer.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))}return this.statisticsReport}getLastKnownStats(e){return this.statsGatherer.getReport(!1,e)}muteHold(e,t){this.logger.safe.info(`[${t}] set muteHold state ${e}`),this.isMuteHold=e;const i=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing].filter((e=>Wp(this.negotiation.negotiatedModalities[e])&&(e!==Gi.MODALITY.audio||!this.isAudioInputMuted)));for(const n of i)this.setMute(sm(n),e,t)}async muteInputAsync(e){this.isAudioInputMuted=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.isAudioInputMuted=!1,this.setMute("Audio",!1,e)}async muteOutputAsync(e){return this.isAudioOutputMuted=!0,this.audioCodecManager.decoder?.disableStreamsMixer(!0),this.audioRenderer?.setMuted(!0,e)}async unmuteOutputAsync(e){return this.isAudioOutputMuted=!1,this.audioCodecManager.decoder?.disableStreamsMixer(!1),this.audioRenderer?.setMuted(!1,e)}async getSpeakerVolume(e){return this.audioRenderer?.getSpeakerVolume(e)||0}async setSpeakerVolume(e,t){return this.audioRenderer?.setSpeakerVolume(e,t)}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}onDeviceEvent(e){this.statsGatherer.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&this.audioRenderer?.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId())}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.statsGatherer.setTerminated(),this.diagnostics.terminate(),this.perfMonitorSubs.forEach((e=>e?.dispose())),this.performanceMonitor.dispose(),this.terminated=!0,this.negotiation.terminate(e),await(this.audioCodecManager.decoder?.storeApiRecording()),this.rawIncomingAudioStreamManager?.dispose(),this.remoteVideoManager.dispose(),this.dataChannel&&(this.dataChannel.dispose(),this.dataChannel=null),this.logger.safe.info(`[${e}] 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((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.deviceManagerSubs.forEach((e=>e.dispose())),this.callDeviceManagerSub?.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated();try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${tt(t)}`)}finally{this.statsGatherer.dispose()}}getIncomingRawAudioStream(e){this.logger.info("IRawStream for incoming audio stream requested");const t=this.audioRenderer.getStream();return this.rawIncomingAudioStreamManager.createIRawStreamClient(t,e)}getUnmixedAudioProvider(){return this.audioCodecManager.decoder?.getUnmixedAudioProvider()}configureSpatialAudio(e,t){this.configProvider.mediaConfig.spatialAudioEnabled=e,this.audioCodecManager.configureSpatialAudio(e,t)||this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable","Bad","Audio",!0,t)}setParticipantSpatialAudioPositions(e,t){if(!this.audioCodecManager?.decoder||!this.getUnmixedAudioProvider()?.configured)throw this.logger.safe.error(`[${t}] setParticipantSpatialAudioPositions is called while MUCH audio decoder is not created or not enabled`),"setParticipantSpatialAudioPositions not allowed";this.audioCodecManager.decoder?.setParticipantSpatialAudioPositions(e)}processNotification(e,t){"McpSourceRequestsAvailable"===e&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),"DominantSpeakerInfo"===e&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(t.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===e&&this.streamConfigurationHandler.handleMessage(t),this.performanceMonitor.processNotification(e,t)}processStatsReport(e){try{if(this.remoteVideoManager.processStatsReport(e),this.configProvider.config.diagnostics.features.useNewNetworkUFD){this.networkQualityDiagnostics.processReport(e);const t=this.networkQualityDiagnostics.getInboundNetworkQuality();this.ufdManager.signalEvent("NetworkRecvQuality",t);const i=this.networkQualityDiagnostics.getOutboundNetworkQuality();this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":i)}this.ufdManager.signalEvent("DeviceSpeakWhileMuted",this.speechDetectionDiagnostics.processReport(e)?"Bad":"Good"),this.streamSendersManager.onDiagnosticUpdated(e);for(const t of this.getVideoDeviceManager().getLocalVideoRenderers())t.onDiagnosticUpdated(e)}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}processLegacyStats(e){e&&(this.remoteVideoManager.processLegacyStats(e),this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.configProvider.config.diagnostics.features.useNewNetworkUFD||(this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel})),this.streamSendersManager.onStatisticsChanged(e))}assurePeerConnectionAsync(e,t){return this.peerConnectionPromise??(this.peerConnectionPromise=this.getPeerConnectionPromise(e,t)),this.peerConnectionPromise}async getPeerConnectionPromise(e,t){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info(`[${e}] fetching relay details from RelayManager...`);const i={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};t.mark("startQueryRelaysAsync");const n=await this.relayManagerProvider.getRelayManager().queryRelaysAsync(i);if(t.markAndMeasure("startQueryRelaysAsync","queryRelaysAsync"),this.terminated)throw new Error("session already disposed");const r={optional:[]},s=Fx(n,this.configProvider.config),a=this.negotiation.configureCrypto(r,this.context.config.isPstnCall);this.configureCpuThreshold(r),this.logger.safe.info("create peer connection");const o="unified-plan",l=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle";try{this.peerConnection=new Mp.window.RTCPeerConnection({iceServers:s,rtcpMuxPolicy:"require",iceTransportPolicy:this.configProvider.getIceTransportPolicy(),iceCandidatePoolSize:this.configProvider.config.iceCandidatePoolSize,bundlePolicy:l,sdpSemantics:o,audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===a,encodedInsertableStreams:!!this.configProvider.config.useInsertableStreams},r)}catch(e){throw e.code===DOMException.INVALID_STATE_ERR&&this.ufdManager.signalEvent("NoNetwork","Bad"),e}const c=this.peerConnection;this.negotiation.rollbackSupported=1===a&&this.context.configProvider.userAgentConfig.isBrowserRollbackSupported,this.negotiation.negotiationEmulator.configure(c),this.statsGatherer.initialize(c),this.statsGatherer.sessionInfo.setIceServers(s),this.statsGatherer.sessionInfo.setIceTransportPolicy(this.configProvider.getIceTransportPolicy()),this.statsGatherer.sessionInfo.setSdpSemantics(o),this.statsGatherer.sessionInfo.setBundlePolicy(l),this.diagnostics.iceServers=s,this.diagnostics.iceTransportPolicy=this.configProvider.getIceTransportPolicy(),this.diagnostics.sdpSemantics=o,this.diagnostics.bundlePolicy=l,await this.checkVideoCodecsSupport(),t.markAndMeasure("queryRelaysAsync","checkVideoCodecsSupport"),c.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${c.signalingState}`)},c.onicecandidateerror=e=>{const t=e,[i,n]=[t.address,t.port];if(this.logger.safe.warn(`On ICE candidate error ${t.url} | ${i}:${n}: code ${t.errorCode}: ${t.errorText}`),!this.transportStateProvider.isConnected||this.negotiation.iceCandidatesDefer.isPending){const e={address:i,port:+n,url:t.url,errorCode:t.errorCode,errorText:t.errorText};this.statsGatherer.addIceCandidateError(e),this.diagnostics.addIceCandidateError(e)}},c.onaddstream=e=>{this.logger.safe.info(`onaddstream stream: ${e.stream.id}`)};const d=(e,t,i,n)=>{this.logger.safe.info(`ontrack processing ${e.kind}: ${t.id}`);let r=t.active;if(!t.active&&this.configProvider.config.useInactiveAudioTrack&&"audio"===e.kind&&(this.logger.safe.warn("ontrack override forcing to use inactive audio stream"),r=!0),!r||"stopped"===n?.currentDirection||n?.stopped)return void this.logger.safe.info("ontrack ignore non active stream");let s=this.mediaManager.getMediaEntityByRemoteStreamId(t.id);if(s||(this.logger.safe.info(`cannot find media entity with stream id ${t.id} trying to fallback`),t.getAudioTracks()[0]&&(s=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.audio)[0])),s){const n=this.createReceiveStream(t,i,e,s);s.setRemoteTrackId(e.id),this.addReceiveStreamTransforms(i,s.getModality()),this.receiveStreamCollection.add(n)}else this.logger.safe.error(`could not find media entity for an added stream: ${t.id}`)};c.ontrack=e=>{const{track:t,receiver:i,transceiver:n}=e,r=e.streams[0]??new MediaStream([t]),s=()=>d(t,r,i,n);if((!this.configProvider.config.addAudioStreamBeforeConnection||Gi.TRACK_KIND.audio!==t.kind)&&!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`ontrack queueing to be run once connected ${t.kind}: ${r.id}`),void this.transportStateProvider.doOnConnected(s,"ontrack",!1);s()},c.onremovestream=e=>{this.logger.safe.info(`onremovestream ${e.stream.id}`),this.transportStateProvider.doOnConnected((()=>this.receiveStreamCollection.remove(e.stream.id)),"onremovestream")},c.onicecandidate=t=>{const i=t.candidate;if(i){const t=rm(i.candidate);if(this.logger.safe.info(`[${e}] onicecandidate candidate: component:${t.component} protocol:${t.protocol} prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),"1"!==t.component)return;if(this.negotiation.iceCandidateReceived=!0,this.statsGatherer.sessionInfo.setCandidateDetails(t),this.diagnostics.setCandidateDetails(t),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1){const e={priority:i.priority?.toString()||t.priority,time:Date.now()-this.negotiation.iceRelayGatheringStartTime};this.statsGatherer.sessionInfo.setRelayCandidateInfo(e),this.diagnostics.relayCandidateInfo=e,this.relayCandidateGathered=!0}}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.negotiation.iceCandidatesDefer.isPending)return;const n=!this.context.config.webrtcIceGatheringTimeoutIncreased||this.configProvider.config.emptyIceCandidateMarksGatheredAnswerer&&!this.negotiation.initiator,r=this.iceHostCandidateOnly||0===s.length;if(!i&&n||r){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.transportStateProvider.isConnected,this.transportStateProvider.iceConnectionState,this.transportStateProvider.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.negotiation.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.negotiation.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},c.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${c.iceGatheringState}`)},this.transportStateProvider=new dB(c,a,this.logger.createChild("TransportStateProvider"),this.configProvider,this.diagnostics.newTransportStateDiagnostics()),this.transportStateProvider.on("stateChanged",((i,n,r)=>{if(this.terminated)return;const s=this.wasConnected?r:e;if(this.statsGatherer.sessionInfo.setIceConnectionState(i),"connecting"===i&&t.mark("transportConnecting"),"connected"===i||"completed"===i)t.markAndMeasure("transportConnecting","transportConnected"),this.onTransportConnected(s);else if("failed"===i||"closed"===i&&"failed"!==n){if(this.negotiation.iceCandidatesDefer.isPending)return this.logger.safe.info(`[${s}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(s);this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},s),this.configProvider.config.webrtcCloseAfterIceFailure&&c.close(),this.callbacks.onTransportFailed?.()}"disconnected"===i?(this.callbacks.onTransportDisconnected?.(e),this.startIceDisconnectedTimer(s)):this.clearIceDisconnectedTimer()})),this.transportStateProvider.on("signalingStateChanged",((t,i,n)=>{this.configProvider.config.reconnectOnPcClose&&!this.terminated&&"closed"===t&&this.transportStateProvider.isTransportConnected&&this.raiseError({type:Gi.MEDIA_ERROR.unexpectedClose,detail:"PeerConnection is closed"},n),"have-remote-pranswer"===i&&"stable"===t&&this.configProvider.config.webrtcPranswerWaitFinalAnswer&&this.transportStateProvider.isTransportConnected&&(this.logger.safe.info(`[${n}] remote final answer, activating audio`),this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e))})),this.transceiverManager=new Hm(this.logger,this.peerConnection,this.mediaManager,this.context,this.reinvitelessContext),this.streamSendersManager.registerRtpSenderManager(this.transceiverManager),mm(this.context)&&!this.dataChannel&&(this.dataChannel=new ep(this.peerConnection,this.diagnostics,this.logger,this.configProvider),this.callback.onDataChannelUpdated?.(this.dataChannel),this.multiParty&&this.initializeMediaControlPlane(e)),this.sourceRequestSender=new NV(this.mediaControlPlane,this.context.sendWebRtcMediaNotificationAsyncCallback,this.logger.createChild("SourceRequestSender")),this.mediaMessageController=new vB(this.logger.createChild("SourceRequester"),this.configProvider,this.sourceRequestSender,this.mediaControlPlane),this.negotiation.setInternals(this.transceiverManager,this.transportStateProvider,this.dataChannel),this.multiParty&&(this.contributingSources=new $U(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new jU(this.logger.createChild("ContributingSourcesProvider"),c,this.configProvider.config.diagnostics.features.logContributingSourcesError,this.diagnostics))),t.mark("startInitialize"),await this.encStreamsManager.initialize(),t.markAndMeasure("startInitialize","encStreamsManagerInitialize");const u=this.encStreamsManager.isWorkerLoaded();this.initAudioCodec(u),this.statsGatherer.sessionInfo.setEncodedStreamWorkerLoaded(u),this.diagnostics.encodedStreamWorker=u}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.negotiation.iceCandidatesDefer.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.negotiation.iceCandidatesDefer.resolve())}detectVideoFeatures(){const e=this.videoFeatureManager.get("Video"),t=this.configProvider.config.specCompliantSimulcast;if(t?.enableSimulcastLayoutControlStrategy&&t?.video?.layerScaleFactors?.length>2&&e.toggleClient(0,!0),this.context.config.isTownHall){const t=this.configProvider.config.broadcastMode;(t?.prioritizeLayoutOnServer||t?.prioritizeLayoutOnClient)&&e.toggleClient(3,!0),t?.maxSessionBandwidthKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps)}const i=this.mediaManager.getMediaEntitiesByModality("video"),n=this.configProvider.config.preferredH264VideoSendProfile;n?.startsWith("64")&&i.length>0&&i[0].isSendProfileSupported("H264",n)&&e.toggleClient(1,!0)}onTransportConnected(e){if(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),!this.terminated){if(this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`[${e}] transport connected provisional`),this.configProvider.config.createProvisionalAnswer.audioState&&this.callbacks.onAudioStateChanged?.(this.configProvider.config.createProvisionalAnswer.audioState,e),void(this.configProvider.config.createProvisionalAnswer.connectTransport&&this.callbacks.onTransportConnected?.(e));this.logger.safe.info(`[${e}] audio transport connected`),this.wasConnected=!0,this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval&&"have-remote-pranswer"===this.transportStateProvider.signalingState?this.handleEarlyMediaAudioState(e):this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e),this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&(this.videoFeatureManager.manageFeatureSupport((()=>{this.detectVideoFeatures()})),this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2&&this.videoFeatureManager.on("onVideoFeaturesChanged",(e=>{if("Video"===e.mediaType&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2){const t=this.mediaManager.getMediaEntitiesByModality("video");t.length>0&&this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(t[0],e)}}))),this.callbacks.onTransportConnected?.(e)}}async getAudioSenderStats(e=.5){const t=this.peerConnection?.getSenders().filter((e=>"audio"===e.track?.kind))[0];if(!t)return Promise.resolve(void 0);try{const i=Jt(1e3*e,"Unable to get audio receiver stats report");t.getStats().then(i.resolve,i.reject);const n=await i.promise;for(const e of n.values())if("outbound-rtp"===e.type)return Promise.resolve(e)}catch(e){return this.logger.safe.error(`Error getting audio sender stats: ${tt(e)}`),Promise.resolve(void 0)}return Promise.resolve(void 0)}handleEarlyMediaAudioState(e){const t=this.peerConnection.getReceivers().filter((e=>"audio"===e.track.kind))[0];if(!t)return this.logger.safe.warn(`[${e}] Connected transport with provisional answer with no audio receiver`),void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.started,e);const i=this.configProvider.config.webrtcPranswerMediaPollingTimeout,n=this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval;this.logger.safe.info(`[${e}] Starting polling for early media audio stats`);const r=async()=>{try{if(!this.canPollAudioStats())return;let s;this.logger.safe.debug(`[${e}] Polling audio receiver stats to detect early media start`);const a=Jt(i,"Unable to get audio receiver stats report");t.getStats().then(a.resolve,a.reject);const o=await a.promise;this.diagnostics.registerEarlyMediaPoll();for(const e of o.values())if("inbound-rtp"===e.type){s=e;break}if(!this.canPollAudioStats())return void this.logger.safe.info(`[${e}] Finished polling early media audio stats, terminated: ${!this.terminated}`);if((this.configProvider.config.webrtcPranswerCheckAudioEnergy?s?.totalAudioEnergy:s?.bytesReceived)>this.configProvider.config.webrtcPranswerAudioThreshold)return this.logger.safe.info(`[${e}] Finished polling early media audio stats, activating audio`),void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);this.logger.safe.info(`[${e}] No audio data received yet, polling again in ${n}ms`),setTimeout(r,n)}catch(t){const i=tt(t);if(this.logger.safe.error(`[${e}] Error polling stats for pranswer: ${i}. Will stop polling: ${this.configProvider.config.webrtcPranswerStopPollingAfterError}`),this.diagnostics.addStatsError("WebrtcSession::earlyMediaPolling",i),this.configProvider.config.webrtcPranswerStopPollingAfterError)return void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);setTimeout(r,n)}};setTimeout(r,this.configProvider.config.webrtcPranswerWaitIntervalBeforePolling)}canPollAudioStats(){return!this.terminated&&"have-remote-pranswer"===this.transportStateProvider.signalingState}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise ${Gi.MEDIA_ERROR.iceConnectionError}`),this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=be()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}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(e){if(Gi.MODALITY.audio===e.getModality()&&(this.webrtcAudioRecvStream=e.getMediaStream(),await this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),await this.updateAudioRendererStream(this.webrtcAudioRecvStream)),this.configProvider.config.mapSsrcToTrackForStats){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);this.statsGatherer.setSsrcTrackPair(t.getRemoteSsrc(),t.getRemoteTrackId())}this.notifyStreamsChanged()}async updateAudioRendererStream(e){await this.audioRenderer.play(e),this.rawIncomingAudioStreamManager.streamChanged(e)}streamRemoved(e){if(Gi.MODALITY.audio===e.getModality())this.audioRenderer.getStream()===e.getMediaStream()&&(this.audioRenderer.stop(),this.rawIncomingAudioStreamManager.streamChanged(null)),this.webrtcAudioRecvStream=null;else if(Gi.MODALITY.video===e.getModality()){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);t?.getLocalRecvCapabilities()?.resetToInitial()}this.clearReceiveStreamTransforms(e.getReceiver()),e.dispose(),this.notifyStreamsChanged()}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(e,t,i,n){const r=this.configProvider.config.addFmtpToInitialSubscription?n.getLocalRecvCapabilities():null,s=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&n.getModality()!==Gi.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null,a=new aO(e,t,n.getModality(),+n.getXSourceStreamId(),this,r,s,n.getSubstreamIndex());return new gV(a,i,this.receiveStreamCollection,this.logger.createChild("RecvStream"),this.configProvider.config)}async requestSource(e,t,i){if(!this.multiParty)return;const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);if((this.isMuteHold||this.negotiation.negotiatedModalities[n.getModality()]===Gi.MEDIA_STATE.inactive)&&-1!==t)return await Yt(10),this.requestSource(e,t,i);if(this.negotiation.negotiationCompletedPromise.isPending)try{await this.negotiation.negotiationCompletedPromise.promise}catch(e){this.logger.safe.info("source request should be sent even if negotiation rejected",e)}if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional){this.logger.safe.info("requestSource is postponed till transport is connected");const e=new Kt;this.transportStateProvider.doOnConnected((()=>e.resolve()),"requestSource"),await e.promise}return this.mediaMessageController.sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex())}async onReceiveCapabilitiesChanged(e,t,i){if(!this.streamSendersManager)return!1;try{return await this.streamSendersManager.applyCapabilities(t,e,i),!0}catch(e){return!1}}onOptimalVideoCountChanged(e,t){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e),this.diagnostics.addOvcSubscriptionReport(e,this.subscriptionManager?.getSubscriptionsCount(),t)}async onSendBandwidthChanged(e){if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional||!this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled"))return;const t=[],i=Object.keys(e);for(const n of i){const i=this.mediaManager.getMediaEntitiesByModality(am(n)).filter((e=>e.isEnabled()&&null!==e.getLocalTrackId()));if(0===i.length||0===e[n])return;t.push({streamMsid:i[0].getXSourceStreamId(),bw:e[n]})}await this.mediaMessageController.sendBandwidthInfo(t),this.diagnostics.reportedSendBandwidthLayouts(e)}onMaxVideoSendCapabilitiesChanged(e,t){("Video"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForVideo||"ScreenShare"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForSharing)&&this.transportStateProvider.doOnConnected((()=>this.notifyMaxVideoCapabilitiesChanged(e,t)),"maxCapabilities")}notifyMaxVideoCapabilitiesChanged(e,t){const i=am(e),n=this.mediaManager.getMediaEntitiesByModality(i)[0];if(!n)return;const r=n.getMid();"Video"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2?this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(n,this.videoFeatureManager.get("Video"),t):this.mediaMessageController.sendMaxVideoSendCapabilities([r],t)}createAudioRenderer(){this.audioRenderer=new ek(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",((e,t,i)=>this.onAudioPlaybackError(e,t,i))),this.audioRenderer.on("onAudioStateChanged",((e,t)=>this.deviceManager.effectsManager.setAecRefStream(e,t)))}onAudioPlaybackError(e,t,i){const n={type:t,detail:i,isAudio:!0};this.ufdManager.signalDeviceEvent(1,"Bad","Audio"),this.deviceManager.raiseTelemetryEvent("reconnect_on_audio_playback_error",{error:e,mediaError:t,message:i}),this.context.reconnectRetry&&this.configProvider.config.audioRendererFailedRetryCodes?.includes(e)&&(this.logger.warn(`Reconnect required, attempt No: ${this.context.reconnectRetry}`),this.context.reconnectRetry--,this.raiseError(n))}getSessionConfig(){return this.configProvider}getLocalMediaTrackId(e){const t=this.mediaManager.getLocalTracksInfo(),i=am(e),n=t.find((e=>e.modality===i));return n?n.trackId:null}addReceiveStreamTransforms(e,t){const i=this.encStreamsManager.initTransformsCollection(e,"Receiver",sm(t));i&&t!==Gi.MODALITY.audio&&this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&i.addTransform(new Sf(this.logger.createChild(`RecvStreamAnalyzer [${t}/${e.track.id}]`)))}clearReceiveStreamTransforms(e){this.encStreamsManager.clearTransformsCollection(e)}async checkVideoCodecsSupport(){try{const e=await this.capabilityGatherer.getCapabilities("video");this.statsGatherer.setH264AvailableProfiles(e);const t=DU({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0),i=await t.getCapabilities("video"),n=DU({global:this.context.maContext},!1),r=await n.getCapabilities("video");this.statsGatherer.setSupportedH264Profiles(i,r);const s=await Vp.isCodecsSupported(this.configProvider.config.hevcCodecs);this.diagnostics.videoCapabilities=e,this.diagnostics.setSupportedH264Profiles(i,r),this.diagnostics.isCodecsSupported=s;const a=new Set(e?.codecs?.map((e=>e.mimeType.toLocaleLowerCase()))||[]);for(const e of this.configProvider.config.requiredVideoCodecs)if(!a.has(e)){this.ufdManager.signalEvent("NoRequiredVideoCodecs","Bad","Video");break}}catch(e){this.logger.safe.error(`failed to get video capability ${tt(e)}`)}}setBWSeed(e){if(!this.bandwidthCache)return;const t=this.bandwidthCache.getSeed();e.applyChannelParameters={multiChannelParameter:{mids:this.configProvider.config.bwSeedOptions.mids,mediaParameter:JSON.stringify({sendSideBWSeed:{seedValueBitsPerSec:t}})}},this.diagnostics.sentBWSeed=t}getSubscriptionManager(){return this.subscriptionManager}initAudioCodec(e){this.audioCodecManager.init(e,this.isAudioOutputMuted),this.audioCodecManager.encoder?.on("codecChanged",(e=>this.statsGatherer.setAudioEncoderCodecName(e)));const t=this.audioCodecManager.decoder;t&&(t.on("usedDecoderChanged",(e=>{this.updateAudioRendererStream(e?t.stream:this.webrtcAudioRecvStream),this.statsGatherer.setAudioDecoderStatsProvider(e?t.getStatsProvider():void 0),this.contributingSources?.useCustomCodec(e)})),t.on("contributingSourcesChanged",(e=>this.contributingSources?.updateContributingSources(e))),this.audioCodecManager.on("negotiationNeeded",(e=>this.negotiation.triggerRenegotiation(!0,e))))}onIncomingVideoQualityChanged(e,t){1===e&&this.remoteVideoResolutionManager.limitResolutionOnPoorPerformance(t)}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((e=>e.dispose())),this.logger.info("New subscriptions for deviceManager created"),this.setSubsForDeviceManager()}))}updateLocalMediaSources(){this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statsGatherer.updateStatsWithLocalSsrcTrackInfo();const e=this.streamSendersManager.getLocalMediaSources();this.qualityManager.updateRegisteredSources(e)}},FV={build:(e,t,i)=>new xV(e,t,i)},UV=class{constructor(e,t,i,n,r,s,a,o){this.logger=e,this.context=t,this.configProvider=i,this.diagnostics=n,this.ufdManager=r,this.deviceManager=s,this.capabilities=a,this.midCallTelemetry=o,this.activeSessions=[],this.pendingDeviceTelemetryEvents=[],this.pendingVideoEffectsTelemetryEvents=[],this.pendingAudioEffectsTelemetryEvents=[],this.callsCount=0,this.mediaConfig={},this.configProvider.on("configUpdated",(()=>this.configApplied())),this.deviceManager.on("onDeviceTelemetryEvent",(e=>this.onDeviceTelemetryEvent(e))),this.deviceManager.on("onVideoEffectsTelemetryEvent",(e=>this.onVideoEffectsTelemetryEvent(e))),this.deviceManager.on("onAudioEffectsTelemetryEvent",(e=>this.onAudioEffectsTelemetryEvent(e)))}createSession(e,t,i,n,r,s){const a=(0,Ix.merge)({},this.mediaConfig,s);this.configProvider.setMediaConfiguration(a);const o=this.configProvider.getConfigView(i?.isConference),l=this.logger,c=t.correlationId,d=this.diagnostics.newSession(o,c,this.logger.createChild("sessionDiagnostics"));r?.setDiagnosticsReport(this.diagnostics.reportGenerator);const u={getLogger:()=>l,getUfdManager:()=>this.ufdManager,sendWebRtcMediaNotificationAsyncCallback:(e,i)=>t.sendWebRtcMediaNotificationAsync(e,i),maContext:this.context,config:i??{},configProvider:o,diagnostics:d.newNativeSessionDiag(),reconnectRetry:o.config.audioRendererFailedReconnectTimes,callDeviceManager:n,getSmallCallTelemetry:()=>r},h=(o.mediaConfig.simulcastSessionEnabled?FV:TB).build(u,c,e),g=new Kx(o,++this.callsCount,d);g.setMediaQosEnabled(!!a.enableMediaQoS),g.setPortRangeConfigured(!!a.mediaPortRanges);const p=new $x(h,c,u,e,g,this.configProvider,d);for(p.on("onTerminated",(e=>this.onSessionTerminated(e))),this.activeSessions.push(p),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector=Ax.getInstance(this.logger.createChild("WebRtcInternals"),o),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length);this.pendingDeviceTelemetryEvents.length>0;)p.registerDeviceTelemetryEvent(this.pendingDeviceTelemetryEvents.pop());for(;this.pendingVideoEffectsTelemetryEvents.length>0;)p.registerVideoEffectsTelemetryEvent(this.pendingVideoEffectsTelemetryEvents.pop());for(;this.pendingAudioEffectsTelemetryEvents.length>0;)p.registerAudioEffectsTelemetryEvent(this.pendingAudioEffectsTelemetryEvents.pop());return p}getDeviceManager(){return this.deviceManager}getCapabilities(){return this.capabilities}getScreenSharingManager(){return new Mx(this.deviceManager)}updateConfig(e,t,i,n){this.configProvider.updateConfig(e,t,i,n)}getConfig(){return this.configProvider.config}getConfigProvider(){return this.configProvider}setMediaConfig(e){(0,Ix.merge)(this.mediaConfig,e),this.diagnostics.mediaConfig=this.mediaConfig}getMediaLogs(){return this.webRtcInternalsCollector?this.webRtcInternalsCollector.collect():Promise.resolve("")}getDiagnosticsData(){return this.diagnostics.rootRef}dispose(e){return Promise.all([...this.activeSessions.map((async t=>{await t.terminate(e,{}).catch((()=>{})),t.dispose()}))]).then((()=>{}),(()=>{}))}handleSendMidCallTelemetry(e){this.midCallTelemetry?.on("sendMidCallTelemetry",e)}configApplied(){window&&(this.configProvider.config.enableDevtoolsAPI?window.webMA||this.injectDevtoolsAPI():window.webMA&&delete window.webMA)}injectDevtoolsAPI(){const e=[],t={config:{addOverride:(e,t)=>this.configProvider.setConsoleOverride(e,t),setOverrides:e=>this.configProvider.setConsoleOverrides(e),clearOverride:e=>this.configProvider.clearConsoleOverride(e),clearAllOverrides:()=>this.configProvider.clearAllConsoleOverrides(),setPlatformConstraints:e=>this.configProvider.setCallConstraints(e),setCallConstraints:e=>{this.activeSessions.length&&this.activeSessions[this.activeSessions.length-1].setCallConstraints(e,"webMA")},setRelayConfigOverride:e=>this.context.getRelayManager().setRelayOverride(e),manageVideoFeatures:t=>{e.push(t)}},diagnosticsReport:this.diagnostics.reportGenerator,initVideoFeatures:t=>{e.forEach((e=>{e(((e,i,n)=>{let r;const s=hB[n];return void 0!==s&&(("video"===i||"sharing"===i)&&(r=t.get("Video")),void 0!==r)&&(e?(r.toggleServer(s,!0),!0):(r.toggleClient(s,!0),!0))}))}))},deviceManager:{setAudioProcessingFlags:e=>this.deviceManager.setAudioProcessingFlags(e)},ufdManager:{raiseUFD:(e,t="Bad",i="Video")=>this.ufdManager.signalEvent(e,t,i)}};window.webMA=t}onDeviceTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerDeviceTelemetryEvent(e))):this.pendingDeviceTelemetryEvents.push(e)}onVideoEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerVideoEffectsTelemetryEvent(e))):this.pendingVideoEffectsTelemetryEvents.push(e)}onAudioEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerAudioEffectsTelemetryEvent(e))):this.pendingAudioEffectsTelemetryEvents.push(e)}onSessionTerminated(e){Qi(this.activeSessions,(t=>t===e)),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length),0===this.activeSessions.length&&this.ufdManager.reset()}},BV=class{static build(e,t,i,n,r,s,a,o){return new UV(e,t,i,n,r,s,a,o)}};BV.constants=Gi,BV.helper=Bp;var VV=class extends gt{constructor(e,t,i){super(),this.logger=e,this.callbacks=t,this.deviceManagerDiagnostics=i,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(e){if(this.logger.info(`getWorkerFunction, loaderName: ${e}`),!this.callbacks?.createGenericWebRTCWorker)switch(e){case"encoded-stream":return this.callbacks?.createEncodedStreamsWorker;case"wasmcv":return this.callbacks?.createWasmCVWorker;default:return}switch(e){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,getEncodedStreamsTimerWorklet:this.callbacks?.audioWorklet?.getEncodedStreamsTimerWorklet}:this.callbacks?.audioWorklet}create(e){let t;try{t=this.callbacks.createGenericWebRTCWorker()}catch(e){return}const i=Date.now(),n=i=>{const r=JSON.stringify(i);this.logger.error(`Worker ${JSON.stringify(e)} error: ${r}`),this.deviceManagerDiagnostics?.registerWorkerEvent({timestamp:Date.now(),workerType:e.msg,msg:"generic-worker-error",payload:r}),t.removeEventListener("error",n),this.event("onLoadError").raise(e.msg)},r=s=>{let a;"wasm-worker-loaded"===s?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(e)} event: ${JSON.stringify(s.data)}`),a={timestamp:Date.now(),workerType:e.msg,workerLoadTimeMs:Date.now()-i,msg:JSON.stringify(s?.data?.msg),payload:JSON.stringify(s?.data?.payload)},t.removeEventListener("message",r)),"wasm-worker-load-error"===s?.data?.msg&&n(s),a&&this.deviceManagerDiagnostics?.registerWorkerEvent(a)};return t.addEventListener("error",n),t.addEventListener("message",r),t.postMessage(e),t}},HV=class e{constructor(e,t,i){this.workerProvider=e,this.workerUrl=t,this.workletUrl=i}static async create(t,i){const n=t.getWorkerFunction("encoded-stream"),r=!n&&i?await i.getWorkerUrl():void 0;try{const i=await(t.audioWorklet?.getEncodedStreamsTimerWorklet?.());return new e(n,r,i)}catch(t){return new e(n,r,void 0)}}getTimerWorkletUrl(){return this.workletUrl}getWorker(e){try{if(e.safe.info("creating worker"),this.workerProvider)return this.workerProvider();if(this.workerUrl)return e.safe.warn("WasmLoader didn't provide worker function, falling back to legacy worker provider"),new Worker(this.workerUrl);e.safe.error("no worker provider")}catch(t){e.safe.error(`failed to create worker ${tt(t)}`)}return null}},$V=class{constructor(){this.data={count:{}}}registerQualityChangedEvent(e){var t,i,n;(t=this.data.count)[i=Rf(e)]??(t[i]={});const r=this.data.count[Rf(e)];r[n=e.value.toLowerCase()]??(r[n]=0),r[e.value.toLowerCase()]++}getObjectRef(){return this.data}},jV=class{constructor(e,t,i){this.mediaAgents=[],e.logger??(e.logger=new iv),e.domOverrides??(e.domOverrides={}),this.config=e;const n=e.mediaSettings;(function(e=""){const t=e.match(new RegExp("^SkypeSpaces/(\\d+)/"));t?.length&&Object.values(wp).includes(t[1])&&(Tp=t[1]),"undefined"!=typeof window&&"undefined"!=typeof navigator&&(void 0!==navigator.webkitGetUserMedia&&"undefined"!=typeof webkitRTCPeerConnection&&Ap()?(window.RTCPeerConnection=webkitRTCPeerConnection,navigator.getUserMedia=(e,t,i)=>{const n=e=>{e?.deviceId?.exact&&(e.mandatory||(e.mandatory={}),e.mandatory.sourceId=e.deviceId.exact,delete e.deviceId)};return e&&(n(e.audio),n(e.video)),navigator.webkitGetUserMedia(e,t,i)}):Ip&&Rp())})(e.clientInformation),this.logger=new _x(e.safeLogger?.createChild("MA",n.debug),e.logger.createChild("MA",n.debug)),this.configProvider=new rO(this.logger.createChild("configProvider"),i,n);const r=new fk(this.configProvider),s=new $V;this.mediaAgentDiagnostics=new bx(this.configProvider,r,s),this.ufdManager=new sv(this.logger.createChild("UFD"),this.configProvider,s),this.wasmLoader=new VV(this.logger.createChild("WasmLoader"),e.createWasmWorkerCbs,r),this.deviceManager=new Kk(this.logger.createChild("DeviceManager"),this.configProvider,r,e.domOverrides,this.ufdManager,e.webcvProvider,e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.wasmLoader),this.capabilities=new nv(this.configProvider),Hn.initialize(this.configProvider),t.on("OnECSChanged",(()=>{const e=t.getEcsConfig("SkypeWebMedia","mediaAgent");e?this.configProvider.updateConfig(e,t.ETag,t.getEcsConfig("ConfigIDs","SkypeWebMedia"),t.getEcsConfig("Headers","CountryCode")):this.logger.warn("No SkypeWebMedia.mediaAgent config.")}))}getDeviceManager(){return this.deviceManager}async buildAgent(e,t,i){if(!Vp.hasMediaApi())throw[new GV(`${e} not supported by media agent provider`,"not_supported")];if(this.config?.detectH264Support&&!await Vp.hasH264CodecSupport(this.config.logger))throw[new GV("H264 is not supported","not_supported")];const n=await HV.create(this.wasmLoader,this.config.encodedStreamsWorkerProvider),r={getRelayManager:()=>t.getOrCreateRelayManager(),getWebCVProvider:()=>this.config.webcvProvider,getWasmDnsProvider:()=>this.config.wasmdnsProvider,getWasmAecProvider:()=>this.config.wasmaecProvider,getWasmVqeProvider:()=>this.config.wasmVqeProvider,getEncodedStreamsWorkerProvider:()=>n,domOverrides:this.config.domOverrides,configProvider:this.configProvider};t.setConfigProvider(this.configProvider);const s=BV.build(this.logger,r,this.configProvider,this.mediaAgentDiagnostics,this.ufdManager,this.deviceManager,this.capabilities,i);return s.constants=BV.constants,this.mediaAgents.push(s),s}async dispose(e){return Promise.all([this.deviceManager.dispose(),this.ufdManager.dispose(),this.configProvider.dispose(),this.capabilities.dispose(),...this.mediaAgents.map((t=>t.dispose(e)))]).then((()=>{this.mediaAgents=[]}))}},GV=class extends Error{constructor(e,t="failure"){super(e),this.reason=t}},qV=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(e){const t=Ot.getBrowserInfo(),i=this.supportedPlatforms.get(t.name);if(e&&i&&Ot.isVersionGreaterOrEqual(i))return 1;if(e&&!i){if(Ot.isEngine("Chromium","ChromiumAVD"))return 2;const e=this.experimentalPlatforms.get(t.name);if(e&&Ot.isVersionGreaterOrEqual(e))return 2}return 0}},zV=class extends gt{constructor(e,t,i){super(),this.relayManagerProvider=e,this.configProvider=t,this.logger=i,this.currentInfo={},this.currentAreaContent={},this.isEnabled=!1,this.isEnabled=this.configProvider.config.enableE911,t.on("configUpdated",(()=>{const e=this.isEnabled;this.isEnabled=this.configProvider.config.enableE911,!this.isEnabled||e===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(e,t){if(this.isEnabled)switch(this.logger.info(`Client info for ${e} set`),e){case 3:this.mergeClientAreaInfo(JSON.parse(t));break;case 1:break;case 2:this.mergeClientNetworkInfo(JSON.parse(t))}}mergeClientAreaInfo(e){const t=JSON.stringify(this.currentAreaContent);this.currentAreaContent.geoCoordinates=e.geoCoordinates,rn(this.currentAreaContent),JSON.stringify(this.currentAreaContent)!==t&&this.raiseChanged()}mergeClientNetworkInfo(e){if(0===Object.keys(e).length){const e=Object.keys(this.currentInfo).length+Object.keys(this.currentAreaContent).length;return this.currentInfo={},this.currentAreaContent={},void(e>0&&this.raiseChanged())}const t=this.currentInfo.bssid!==e.bssid||this.currentInfo.bssidv6!==e.bssidv6||this.currentInfo.mac!==e.mac||this.currentInfo.macv6!==e.macv6||this.currentInfo.subnetLengthIpv4!==e.subnetLengthIpv4||this.currentInfo.subnetLengthIpv6!==e.subnetLengthIpv6,i=this.currentInfo.e911;this.currentInfo.bssid=e.bssid,this.currentInfo.bssidv6=e.bssidv6,this.currentInfo.e911=e.e911,this.currentInfo.mac=e.mac,this.currentInfo.macv6=e.macv6,this.currentInfo.subnetLengthIpv4=e.subnetLengthIpv4,this.currentInfo.subnetLengthIpv6=e.subnetLengthIpv6,rn(this.currentInfo),t?this.probeForIP("clientNetworkInfoChanged").then((e=>{e||this.raiseChanged()})):JSON.stringify(i)!==JSON.stringify(e.e911)&&this.raiseChanged()}async probeForIP(e){return this.probingPromise?(this.logger.info(`Probing already in progress, tried to start for: ${e}`),this.probingPromise):(this.probingPromise=this.probeForIPInternal(e),this.probingPromise.then((e=>(this.probingPromise=void 0,e))).catch((e=>(this.probingPromise=void 0,this.logger.error(`E911 probing failed: ${tt(e)}`),!1))))}async probeForIPInternal(e){this.logger.info(`Probing for public IP address: ${e}`);const t=await this.ensureProber();if(await t.ensureOnline(),t.ipFromRelay){if((this.currentInfo.ipv4||this.currentInfo.ipv6)!==t.ipFromRelay)return delete this.currentInfo.ipv4,delete this.currentInfo.ipv6,this.currentInfo[Hp.test(t.ipFromRelay)?"ipv4":"ipv6"]=t.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 e=Ux(await this.relayManagerProvider.getOrCreateRelayManager().queryRelaysAsync({relayType:"turn"}),this.configProvider.config);return this.prober=new xx(e,new _x(this.logger.createChild("Prober"),this.logger.createChild("ProberUnsafe"))),this.prober}},WV=class extends gt{constructor(e){super(),this.ecsFilters=e,this.config=null}get ETag(){return this.etag}async setEcsConfig(e){this.config=JSON.parse(e.ecsBlob),this.etag=e.etag,this.event("OnECSChanged").raise()}async setUserEcsServerUrl(e,t){throw new Error("Not implemented")}async getUserEcsServerUrl(e){throw new Error("Not implemented")}async setActiveUserForEcs(e){throw new Error("Not implemented")}async getEcsQueryParameters(){const e={CLRelease:"2025.07.01.15"},t="_TS_BUILC_VERSION_".replace("C","D"),i=this.ecsFilters?.["UserInfo.Ring"]?.value,n=this.getTeamsExperience();e.CLRelease===t&&(e.CLRelease="9999.99"),i&&(e.audienceGroup=i,e.teamsRing=i),n&&(e.Experience=n),"vdi3"===this.ecsFilters?.vdi?.value&&(e.vdi="vdi3");const r=Ot.getBrowserInfo();return e.BrowserName=r.name,e.BrowserEngine=r.engine,e.BrowserVersion=r.version,e.FormFactor=r.formFactor,e.OsName=r.osName,e.OsVer=r.osVersion,Vp.hardwareConcurrency&&(e.CPUCount=Vp.hardwareConcurrency),JSON.stringify(e)}async ecsGetUserQueryParameters(e){return this.getEcsQueryParameters()}async shouldTriggerCQF(e,t,i){throw new Error("Not implemented")}getEcsConfig(e,t){const i=this.config?.[e];return t?i?.[t]:i}createEcsConfiguration(){return new class{constructor(e){this.provider=e}getBoolean(e,t){return this.provider.getEcsConfig(e,t)}getNumber(e,t){return this.provider.getEcsConfig(e,t)}getString(e,t){const i=this.provider.getEcsConfig(e,t);return JSON.stringify(i)}}(this)}getTeamsExperience(){return!0===this.ecsFilters?.isTeams2?.value?"teams2":!1===this.ecsFilters?.isTeams2?.value?"teams1":void 0}},KV=class{constructor(e){this._sharingSource=e}getId(){return this._sharingSource.getId()}getDeviceId(){return this._sharingSource.getDeviceId()}getType(){return this.mapSharingSourceType(this._sharingSource.getType())}getPreview(e,t,i){return Promise.reject("not implemented")}getPreviewAsync(e,t){return this._sharingSource.getPreviewAsync(e,t)}getDescription(){return this._sharingSource.getDescription()}getIcon(e,t){return this._sharingSource.getIcon(e,t)}getBounds(){}mapSharingSourceType(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 3;default:throw new Error("Invalid sharing source type")}}},JV=class extends gt{constructor(e){super(),this._screenSharingManager=e,this._screenSharingManager.onScreensChanged((()=>{this.event("screensChanged").raise()}))}enumerateScreensAsync(){return this._screenSharingManager.enumerateScreensAsync().then((e=>e.map((e=>new KV(e)))))}enumerateWindowsAsync(){return this._screenSharingManager.enumerateWindowsAsync().then((e=>e.map((e=>new KV(e)))))}enumerateCamerasAsync(){return this._screenSharingManager.enumerateCamerasAsync().then((e=>e.map((e=>new KV(e)))))}},YV=Q;function QV(e,t){return null==e?t:e}function ZV(e,t){return e||t}var XV,eH=class{constructor(e,t,i,n){this.signalingAgentConfig=e,this.ecsProvider=t,this.logger=i,this.telemetryLogger=n,this.ecsProvider.on("OnECSChanged",(()=>this.onEcsUpdate())),this.signalingAgentConfig.clientInformation+="/TsCallingVersion=2025.07.01.15/Ovb=8962f6ae8324f6a345d7997ae8f276ff81198956",this.signalingAgentConfig.piiScrubber={omit:YV.pii.Omit,mri:YV.pii.Mri},this.signalingAgent=new lh(this.getSignalingAgentConfig())}getSignalingAgent(){return this.signalingAgent}onEcsUpdate(){const e=this.ecsProvider.getEcsConfig("SkypeCalling");this.logger.info(`onEcsUpdate, ecsTag=${this.ecsProvider.ETag||""}, ecsConfig=${JSON.stringify(e)}`),this.signalingAgentConfig=((e,t)=>{if(!t)return e;const i={...e};if(t.ngIncoming&&t.ngOutgoing){const n=function(e,t){return t&&e?"enabled":e?"recvOnly":!1===e&&!1===t?"disabled":void 0}(t.ngIncoming.isVBSSEnabled,t.ngOutgoing.isVBSSEnabled);i.cloudScreenSharingFlag=QV(n,e.cloudScreenSharingFlag)}return t.ngOutgoing&&(i.emergencyCallCountry=function(e,t){return!1===e?"":t}(t.ngOutgoing.isEmergencyCallingEnabled,e.emergencyCallCountry),i.isGVCOutgoingEnabled=QV(t.ngOutgoing.isGVCEnabled,e.isGVCOutgoingEnabled),i.brokerEnabledOutgoing=QV(t.ngOutgoing.isBrokerEnabled,e.brokerEnabledOutgoing)),t.ngIncoming&&(i.isGVCJoiningEnabled=QV(t.ngIncoming.isGVCEnabled,e.isGVCJoiningEnabled),i.brokerEnabledIncoming=QV(t.ngIncoming.isBrokerEnabled,e.brokerEnabledIncoming)),i.conversationServiceUrl=ZV(t.conversationServiceUrl,e.conversationServiceUrl),i.uploadLogRequestUrl=ZV(t.uploadLogRequestUrl,e.uploadLogRequestUrl),i.isConversationServiceUrlFromEcs=!!t.conversationServiceUrl,i.isUploadLogRequestUrlFromEcs=!!t.uploadLogRequestUrl,i.callingTokenLogicalUrl=ZV(t.callingTokenLogicalUrl,e.callingTokenLogicalUrl),i.doHostlessCalling=QV(t.allowHostlessCalls,e.doHostlessCalling),i.supportsCompressedServicePayload=QV(t.supportCompressedTrouterPayload,e.supportsCompressedServicePayload),i.brokerRequestBatching=QV(t.allowBrokerSubscribeBatching,e.brokerRequestBatching),i.brokerExclusively=QV(t.brokerExclusively,e.brokerExclusively),i.handleMediaOfferFromPushNotification=QV(t.handleMediaOfferFromPushNotification,e.handleMediaOfferFromPushNotification),i.handleNewOfferRequest=QV(t.handleNewOfferRequest,e.handleNewOfferRequest),i.sendProgressFromCC=QV(t.sendProgressFromCC,e.sendProgressFromCC),i.useInternalHttpDispatcher=QV(t.webInternalHttpDispatcher,e.useInternalHttpDispatcher),(t.webInternalHttpDispatcherConfigNetworkRequest||e.requestTypeHttpDispatcherConfigMap)&&(t.webInternalHttpDispatcherConfigNetworkRequest=t.webInternalHttpDispatcherConfigNetworkRequest||{},e.requestTypeHttpDispatcherConfigMap=e.requestTypeHttpDispatcherConfigMap||{},i.requestTypeHttpDispatcherConfigMap={...e.requestTypeHttpDispatcherConfigMap,...t.webInternalHttpDispatcherConfigNetworkRequest}),(t.operationTypeHttpDispatcherConfigMap||e.operationTypeHttpDispatcherConfigMap)&&(t.operationTypeHttpDispatcherConfigMap=t.operationTypeHttpDispatcherConfigMap||{},e.operationTypeHttpDispatcherConfigMap=e.operationTypeHttpDispatcherConfigMap||{},i.operationTypeHttpDispatcherConfigMap={...e.operationTypeHttpDispatcherConfigMap,...t.operationTypeHttpDispatcherConfigMap}),(t.csaTimeoutConfiguration||e.csaTimeoutConfiguration)&&(t.csaTimeoutConfiguration=t.csaTimeoutConfiguration||{},e.csaTimeoutConfiguration=e.csaTimeoutConfiguration||{},i.csaTimeoutConfiguration={...e.csaTimeoutConfiguration,...t.csaTimeoutConfiguration}),i.autoJoinOnConflict=QV(t.autoJoinOnConflict,e.autoJoinOnConflict),i.enableQuickSendAcceptanceAck=QV(t.enableQuickSendAcceptanceAck,e.enableQuickSendAcceptanceAck),i.supportMediaRetargetWhileIncomingRenegotiation=QV(t.supportMediaRetargetWhileIncomingRenegotiation,e.supportMediaRetargetWhileIncomingRenegotiation),i.enableCallEstablishmentTimeoutsForStartJoinCall=QV(t.enableCallEstablishmentTimeoutsForStartJoinCall,e.enableCallEstablishmentTimeoutsForStartJoinCall),i.callingServiceSupportsCAETokens=QV(t.callingServiceSupportsCAETokens,e.callingServiceSupportsCAETokens),i.callingServiceSupportsAADTokens=QV(t.callingServiceSupportsAADTokens,e.callingServiceSupportsAADTokens),i.aadTokenExpirationTimeInSeconds=QV(t.aadTokenExpirationTimeInSeconds,e.aadTokenExpirationTimeInSeconds),i.caeTokenExpirationTimeInSeconds=QV(t.caeTokenExpirationTimeInSeconds,e.caeTokenExpirationTimeInSeconds),i.disableTokenMigrationHeader=QV(t.disableTokenMigrationHeader,e.disableTokenMigrationHeader),i.enablePublishTokenTelemetry=QV(t.enablePublishTokenTelemetry,e.enablePublishTokenTelemetry),i.refreshTimeBeforeTokenTimeoutInSeconds=QV(t.refreshTimeBeforeTokenTimeoutInSeconds,e.refreshTimeBeforeTokenTimeoutInSeconds),i.forceClearExpiredTokens=QV(t.forceClearExpiredTokens,e.forceClearExpiredTokens),i.enableRefreshToken=QV(t.enableRefreshToken,e.enableRefreshToken),i.enableAsyncDisablePreheat=QV(t.enableAsyncDisablePreheat,e.enableAsyncDisablePreheat),i.forceLowercaseHttpHeaders=QV(t.forceLowercaseHttpHeaders,e.forceLowercaseHttpHeaders),i.enableResolveScreenSharingWhenNegotiationComplete=QV(t.enableResolveScreenSharingWhenNegotiationComplete,e.enableResolveScreenSharingWhenNegotiationComplete),i.maxReinvitelessMediaForVideoForWeb=QV(t.maxReinvitelessMediaForVideoForWeb,e.maxReinvitelessMediaForVideoForWeb),i.maxReinvitelessMediaForVBSSForWeb=QV(t.maxReinvitelessMediaForVBSSForWeb,e.maxReinvitelessMediaForVBSSForWeb),i.enableRefreshTokenRetry=QV(t.enableRefreshTokenRetry,e.enableRefreshTokenRetry),i.enableRefreshTokenRetryInSeconds=QV(t.enableRefreshTokenRetryInSeconds,e.enableRefreshTokenRetryInSeconds),i.enableConversationTypeUpdateOnCallEnd=QV(t.enableConversationTypeUpdateOnCallEnd,e.enableConversationTypeUpdateOnCallEnd),i.supportMissingTokenTypesInResponse=QV(t.supportMissingTokenTypesInResponse,e.supportMissingTokenTypesInResponse),i.useSkypeTokenWhenNoAuthenticateHeader=QV(t.useSkypeTokenWhenNoAuthenticateHeader,e.useSkypeTokenWhenNoAuthenticateHeader),i.enableAutoPromotion=QV(t.enableAutoPromotion,e.enableAutoPromotion),i.enableTokenCache=QV(t.enableTokenCache,e.enableTokenCache),i.enableBatchedSendMessageStatus=QV(t.enableBatchedSendMessageStatus,e.enableBatchedSendMessageStatus),i.enableBatchedReceiveMessage=QV(t.enableBatchedReceiveMessage,e.enableBatchedReceiveMessage),i.enableTokenCacheForGenericTokenAPI=QV(t.enableTokenCacheForGenericTokenAPI,e.enableTokenCacheForGenericTokenAPI),i.disableRealTimeModeFromRoster=QV(t.disableRealTimeModeFromRoster,e.disableRealTimeModeFromRoster),i.enableLongOutgoing1To1SetupTimeoutForWeb=QV(t.enableLongOutgoing1To1SetupTimeoutForWeb,e.enableLongOutgoing1To1SetupTimeoutForWeb),i.checkAttendeeRoleInCreateContentSharing=QV(t.checkAttendeeRoleInCreateContentSharing,e.checkAttendeeRoleInCreateContentSharing),i.enableSpecificErrorCodesForCallEnd=QV(t.enableSpecificErrorCodesForCallEnd,e.enableSpecificErrorCodesForCallEnd),i.enableSplitConversationEndUrl=QV(t.enableSplitConversationEndUrl,e.enableSplitConversationEndUrl),i.enableFetchRequestWithKeepAlive=QV(t.enableFetchRequestWithKeepAlive,e.enableFetchRequestWithKeepAlive),i.enableFetchApi=QV(t.enableFetchApi,e.enableFetchApi),i.enableFetchApiForBeacon=QV(t.enableFetchApiForBeacon,e.enableFetchApiForBeacon),i})(this.signalingAgentConfig,e),this.signalingAgentConfig.ecsEtag=this.ecsProvider.ETag,this.signalingAgent.updateSignalingAgentConfig(this.getSignalingAgentConfig())}getSignalingAgentConfig(){return this.signalingAgentConfig.oneDsTelemetryLogger=this.telemetryLogger,this.signalingAgentConfig}},tH=p(Z),iH="blkVal",nH="length",rH="rdOnly",sH="notify",aH="warnToConsole",oH="throwInternal",lH="setDf",cH="watch",dH="logger",uH="apply",hH="push",gH="hdlr",pH="identifier",mH="isInitialized",fH="getPlugin",vH="time",SH="processNext",yH="unload",CH="createNew",TH="teardown",EH="messageId",bH="message",_H="isAsync",IH="diagLog",wH="_doTeardown",AH="update",PH="getNext",RH="setNextPlugin",MH="userAgent",DH="nodeType",kH="replace",OH="isChildEvt",NH="getCtx",LH="setCtx",xH="complete",FH="",UH="core",BH="extensionConfig",VH="processTelemetry",HH="getPerfMgr",$H=/-([a-z])/g,jH=/([^\w\d_$])/g,GH=/^(\d+[\w\d_$])/;function qH(e){var t=e;return t&&jv(t)&&(t=(t=(t=t[kH]($H,(function(e,t){return t.toUpperCase()})))[kH](jH,"_"))[kH](GH,(function(e,t){return"_"+t}))),t}function zH(e,t){return!(!e||!t)&&-1!==Ny(e,t)}function WH(e,t,i,n,r){e&&t&&i&&(!1!==r||Bv(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return Gv(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][uH](n,e)}}(i,n))}var KH="JSON",JH=null,YH=null;function QH(){return Boolean(typeof JSON===ov&&JSON||null!==qS(KH))}var ZH=4294967296,XH=4294967295,e$=123456789,t$=987654321,i$=!1,n$=e$,r$=t$;function s$(e){var t=0,i=qS("crypto")||qS("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&XH),0===t&&function(){var e=ZS();if(e&&(e[MH]!==YH||null===JH)){var t=((YH=e[MH])||FH).toLowerCase();JH=zH(t,"msie")||zH(t,"trident/")}return JH}()&&(i$||function(){try{var e=2147483647&Sy();!function(e){e<0&&(e>>>=0),n$=e$+e&XH,r$=t$-e&XH,i$=!0}((Math.random()*ZH^e)+e)}catch(e){}}(),t=function(){var e=((r$=36969*(65535&r$)+(r$>>16)&XH)<<16)+(65535&(n$=18e3*(65535&n$)+(n$>>16)&XH))>>>0&XH;return e>>>=0}()&XH),0===t&&(t=Math.floor(ZH*Math.random()|0)),e||(t>>>=0),t}var a$="3.3.1",o$="."+function(e){void 0===e&&(e=22);for(var t=s$()>>>0,i=0,n=FH;n[nH]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(s$()<<2&4294967295|3&t)>>>0,i=0);return n}(6),l$=0;function c$(e){return 1===e[DH]||9===e[DH]||!+e[DH]}function d$(e,t){return void 0===t&&(t=!1),qH(e+l$+++(t?"."+a$:FH)+o$)}function u$(e){return e&&qv(e)&&(e.isVal||e.fb||tS(e,"v")||tS(e,"mrg")||tS(e,"ref")||e.set)}function h$(e,t,i){var n,r=i.dfVal||Hv;if(t&&i.fb){var s=i.fb;zv(s)||(s=[s]);for(var a=0;a<s[nH];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,uS(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function g$(e,t,i){var n,r=i;return i&&u$(i)&&(r=h$(e,t,i)),r&&(u$(r)&&(r=g$(e,t,r)),zv(r)?(n=[])[nH]=r[nH]:_y(r)&&(n={}),n&&(iS(r,(function(i,r){r&&u$(r)&&(r=g$(e,t,r)),n[i]=r})),r=n)),r}function p$(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;u$(h)?(r=h.isVal,s=h.set,c=h[rH],d=h[iH],o=h.mrg,!(l=h.ref)&&Bv(l)&&(l=!!o),a=h$(e,t,h)):a=n,d&&e[iH](t,i);var g=!0,p=t[i];!p&&Vv(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?g$(e,t,a):a:(_y(u)||zv(a))&&o&&a&&(_y(a)||zv(a))&&iS(a,(function(t,i){p$(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[rH](t,i)}var m$=ry("[[ai_dynCfg_1]]"),f$=ry("[[ai_blkDynCfg_1]]"),v$=ry("[[ai_frcDynCfg_1]]");function S$(e){var t;return e&&(zv(e)?(t=[])[nH]=e[nH]:_y(e)&&(t={}),t)?(iS(e,(function(e,i){t[e]=S$(i)})),t):e}function y$(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[v$])||i[f$]||(n=_y(i)||zv(i))),n}function C$(e){pS("InvalidAccess:"+e)}var T$=["push","pop","shift","unshift","splice"],E$=function(e,t,i,n){e&&e[oH](3,108,"".concat(i," [").concat(t,"] failed - ")+hS(n))};function b$(e,t){var i=Xv(e,t);return i&&i.get}function _$(e,t,i,n){if(t){var r=b$(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===dy(r.h,t)&&r.h[hH](t),e.trk(t,r))},clr:function(e){var t=dy(r.h,e);-1!==t&&r.h.splice(t,1)}},s=!0,a=!1;function o(){s&&(a=a||y$(o,e,n),n&&!n[m$]&&a&&(n=w$(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},oS(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&C$("["+i+"] is read-only:"+hS(t)),s&&(a=a||y$(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){iS(n,(function(e){n[e]=l?l[e]:void 0}));try{iS(l,(function(t,i){_$(e,n,t,i)})),l=n}catch(t){E$((e.hdlr||{})[dH],i,"Assigning",t),a=!1}}else n&&n[m$]&&iS(n,(function(t){var i=b$(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&y$(o,e,l);!c&&d&&(l=w$(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function I$(e,t,i,n){if(t){var r=b$(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(_y(e)||zv(e)))try{e[f$]=!0}catch(e){}}(t)}catch(t){E$((e.hdlr||{})[dH],i,"Blocking",t)}try{_$(e,t,i,t[i]),r=b$(t,i)}catch(t){E$((e.hdlr||{})[dH],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function w$(e,t,i,n){try{iS(t,(function(i,n){_$(e,t,i,n)})),t[m$]||(sS(t,m$,{get:function(){return e[gH]}}),function(e,t,i){zv(t)&&cy(T$,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[uH](this,n);return w$(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){E$((e.hdlr||{})[dH],i,n,t)}return t}var A$="[[ai_",P$="]]";function R$(e,t,i){var n,r=function(e){if(e){var t=e[m$]||e;if(t.cfg&&(t.cfg===e||t.cfg[m$]===t))return t}return null}(t);if(r)return r;var s,a=d$("dyncfg",!0),o=t&&!1!==i?t:S$(t),l=((n={uid:null,cfg:o})[dH]=e,n[sH]=function(){s[sH]()},n.set=function(t,i,n){try{t=_$(s,t,i,n)}catch(t){E$(e,i,"Setting value",t)}return t[i]},n[lH]=function(e,t){return t&&iS(t,(function(t,i){p$(l,e,t,i)})),e},n[cH]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return oS(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return I$(s,e,t,(i={},i[0]=!0,i))[t]},n[rH]=function(e,t){var i;return I$(s,e,t,(i={},i[1]=!0,i))[t]},n[iH]=function(e,t){var i;return I$(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Bv(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return oS(l,"uid",{c:!1,e:!1,w:!1,v:a}),w$(s=function(e){var t,i,n=ny(A$+"get"+e.uid+P$),r=ny(A$+"ro"+e.uid+P$),s=ny(A$+"rf"+e.uid+P$),a=ny(A$+"blkVal"+e.uid+P$),o=ny(A$+"dtl"+e.uid+P$),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(cy(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[lH].bind(e),ref:e.ref.bind(e),rdOnly:e[rH].bind(e)})}catch(t){var s=e[dH];throw s&&s[oH](1,107,hS(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c.cancel(),c=null;var t=[];if(cy(e,(function(e){if(e&&(e[o]&&(cy(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[hH](e)}})),l)try{u()}catch(e){t[hH](e)}t[nH]>0&&function(e,t){XV||(XV=vy("AggregationError",(function(e,t){t[nH]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw cy(t,(function(e,t){i+="\n".concat(t," > ").concat(hS(e))})),new XV(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[iH]=a,t[gH]=e,t.add=function(e){if(e&&e.h[nH]>0){l||(l=[]),c||(c=Vy((function(){c=null,u()}),0));for(var t=0;t<e.h[nH];t++){var i=e.h[t];i&&-1===dy(l,i)&&l[hH](i)}}},t[sH]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===dy(i,t)&&i[hH](t)}},i=t}(l),o,"config","Creating"),l}function M$(e,t,i,n){var r=R$(i,e||{},n);return t&&r[lH](r.cfg,t),r}function D$(e,t,i){var n=e[m$]||e;return!n.cfg||n.cfg!==e&&n.cfg[m$]!==n?(function(e,t){e?(e[aH](t),e[oH](2,108,t)):C$(t)}(i,"Not dynamic - "+hS(e)),M$(e,null,i)[cH](t)):n[cH](t)}var k$,O$=null;var N$="warnToConsole",L$={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},x$=((k$={})[0]=null,k$[1]="errorToConsole",k$[2]=N$,k$[3]="debugToConsole",k$);function F$(e){return e?'"'+e[kH](/\"/g,FH)+'"':FH}function U$(e,t){var i=typeof console!==lv?console:qS("console");if(i){var n="log";i[e]&&(n=e),Gv(i[n])&&i[n](t)}}var B$=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[EH]=e,r[bH]=(i?"AI: ":"AI (Internal): ")+e;var s=FH;QH()&&(s=(QH()?JSON||qS(KH):null).stringify(n));var a=(t?" message:"+F$(t):FH)+(n?" props:"+F$(s):FH);r[bH]+=a}return e.dataType="MessageData",e}();function V$(e,t){return(e||{})[dH]||new H$(t)}var H$=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};TC(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[EH];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[hH](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new B$(23,c,!1);e.queue[hH](u),1===t?e.errorToConsole(c):e[aH](c)}}}function d(e,i){var n=function(e){var t=O$;return t||!0===e.disableDbgExt||(t=O$||function(){var e=qS("Microsoft");return e&&(O$=e.ApplicationInsights),O$}()),t?t.ChromeDbgExt:null}(t||{});n&&n[IH]&&n[IH](e,i)}a=function(t){return D$(M$(t,L$,e).cfg,(function(e){var t=e.cfg;i=t.loggingLevelConsole,n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[oH]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new B$(n,r,o,a);if(s)throw hS(u);var h=x$[t]||N$;if(Bv(u[bH]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[EH];!l[g]&&i>=t&&(e[h](u[bH]),l[g]=!0)}else i>=t&&e[h](u[bH]);c(t,u)}},e.debugToConsole=function(e){U$("debug",e),d("warning",e)},e[aH]=function(e){U$("warn",e),d("warning",e)},e.errorToConsole=function(e){U$("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[yH]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function $$(e,t,i,n,r,s){void 0===s&&(s=!1),function(e){return e||new H$}(e)[oH](t,i,n,r,s)}var j$="ctx",G$="ParentContextKey",q$="ChildrenContextKey",z$=function(){function e(t,i,n){var r,s=this;s.start=Sy(),s.name=t,s[_H]=n,s[OH]=function(){return!1},Gv(i)&&oS(s,"payload",{g:function(){return!r&&Gv(i)&&(r=i(),i=null),r}}),s[NH]=function(t){return t?t===e[G$]||t===e[q$]?s[t]:(s[j$]||{})[t]:null},s[LH]=function(t,i){t&&(t===e[G$]?(s[t]||(s[OH]=function(){return!0}),s[t]=i):t===e[q$]?s[t]=i:(s[j$]=s[j$]||{})[t]=i)},s[xH]=function(){var t=0,i=s[NH](e[q$]);if(zv(i))for(var n=0;n<i[nH];n++){var r=i[n];r&&(t+=r[vH])}s[vH]=Sy()-s.start,s.exTime=s[vH]-t,s[xH]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),W$="CoreUtils.doPerf";function K$(e,t,i,n,r){if(e){var s=e;if(s[HH]&&(s=s[HH]()),s){var a=void 0,o=s[NH](W$);try{if(a=s.create(t(),n,r)){if(o&&a[LH]&&(a[LH](z$[G$],o),o[NH]&&o[LH])){var l=o[NH](z$[q$]);l||(l=[],o[LH](z$[q$],l)),l[hH](a)}return s[LH](W$,a),i(a)}}catch(e){a&&a[LH]&&a[LH]("exception",e)}finally{a&&s.fire(a),s[LH](W$,o)}}}return i()}function J$(){var e=function(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=FH,n=0;n<4;n++)i+=t[15&(e=s$())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&s$())|0];return DS(i,0,8)+DS(i,9,4)+"4"+DS(i,13,3)+r+DS(i,16,3)+DS(i,19,12)}();return MS(e,0,8)+"-"+MS(e,8,12)+"-"+MS(e,12,16)+"-"+MS(e,16,20)+"-"+MS(e,20)}var Y$=function(){var e={id:d$("_aiData-plugin."+a$),accept:function(e){return c$(e)},get:function(t,i,n,r){var s=t[e.id];return s?s[qH(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{c$(t)&&oS(t,e.id,{e:!1,v:i})}catch(e){}}return i}(e,t))[qH(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return e}();function Q$(e){return Y$.get(e,"state",{},!0)}var Z$,X$="_hasRun",ej="_getTelCtx",tj=0;function ij(e,t,i,n){var r=null,s=[];t||(t=M$({},null,i[dH])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[fH]()===i)return e;e=e[PH]()}return aj([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[PH]():null,!e){var t=s;t&&t[nH]>0&&(cy(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){$$(i[dH],2,73,"Unexpected Exception during onComplete - "+hS(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return V$(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&iS(i,(function(e,i){if(Vv(n[e])){var r=t.cfg[e];!r&&Vv(r)||(n[e]=r)}p$(t,n,e,i)})),t[lH](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Vv(s[i])?!a[i]&&Vv(a[i])||(r=a[i]):r=s[i],r||!Vv(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[fH]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[hH]({func:e,self:Bv(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[BH];!s&&i&&(s={}),r[BH]=s,(s=t.ref(r,BH))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function nj(e,t,i,n){var r=M$(t),s=ij(e,r,i,n),a=s.ctx;return a[SH]=function(e){var t=s._next();return t&&t[VH](e,a),!t},a[CH]=function(e,t){return void 0===e&&(e=null),zv(e)&&(e=aj(e,r.cfg,i,t)),nj(e||a[PH](),r.cfg,i,t)},a}function rj(e,t,i){var n=M$(t.config),r=ij(e,n,t,i),s=r.ctx;return s[SH]=function(e){var t=r._next();return t&&t[yH](s,e),!t},s[CH]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=aj(e,n.cfg,t,i)),rj(e||s[PH](),t,i)},s}function sj(e,t,i){var n=M$(t.config),r=ij(e,n,t,i).ctx;return r[SH]=function(e){return r.iterate((function(t){Gv(t[AH])&&t[AH](r,e)}))},r[CH]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=aj(e,n.cfg,t,i)),sj(e||r[PH](),t,i)},r}function aj(e,t,i,n){var r=null,s=!n;if(zv(e)&&e[nH]>0){var a=null;cy(e,(function(e){if(s||n!==e||(s=!0),s&&e&&Gv(e[VH])){var o=function(e,t,i){var n,r=null,s=Gv(e[VH]),a=Gv(e[RH]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=Q$(e);return!n[TH]&&!n.disabled&&(a&&e[RH](r),e[VH](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[SH](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=Q$(e),s=e[UH]||r[UH];!e||s&&s!==t.core()||r[TH]||(r[UH]=null,r[TH]=!0,r[mH]=!1,e[TH]&&!0===e[TH](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[_H])||t[SH](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=Q$(e),s=e[UH]||r[UH];!e||s&&s!==t.core()||r[TH]||e[AH]&&!0===e[AH](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[SH](i)},_id:n=e?e[pH]+"-"+e.priority+"-"+tj++:"Unknown-0-"+tj++,_setNext:function(e){r=e}};function l(){var n;return e&&Gv(e[ej])&&(n=e[ej]()),n||(n=nj(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[pH]:"TelemetryPluginChain",d=t[X$];return d||(d=t[X$]={}),t.setNext(r),e&&K$(t[UH](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:FH;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||$$(t[IH](),1,73,"Plugin ["+c+"] failed during "+s+" - "+hS(e)+", run flags: "+hS(d))}}),a,o),l}return CS(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?aj([n],t,i):r}var oj,lj="getPlugin",cj=((Z$={})[BH]={isVal:function(e){return!Vv(e)},v:{}},Z$),dj=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||nj(null,{},a[UH]);t=n&&n[lj]?r[CH](null,n[lj]):r[CH](null,n)}return t}function l(e,t,r){M$(e,cj,V$(t)),!r&&t&&(r=t.getProcessTelContext()[PH]());var s=n;n&&n[lj]&&(s=n[lj]()),a[UH]=t,i=nj(r,e,t,s)}function c(){t=!1,a[UH]=null,i=null,n=null,s=function(){var e=[];return{run:function(t){var i=e;e=[],cy(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){$$(t,2,73,"Unloading:"+hS(e))}}))},add:function(t){t&&ly(e,t)}}}(),r=function(){var e=[];return{add:function(t){t&&e[hH](t)},run:function(t,i){cy(e,(function(e){try{e(t,i)}catch(e){$$(t[IH](),2,73,"Unexpected error calling unload handler - "+hS(e))}})),e=[]}}}()}c(),TC(e,a,(function(e){e.initialize=function(e,i,n,r){l(e,i,r),t=!0},e[TH]=function(t,i){var a,o=e[UH];if(o&&(!t||o===t[UH]())){var l,d=!1,u=t||rj(null,o,n&&n[lj]?n[lj]():n),h=i||((a={reason:0})[_H]=!1,a);return e[wH]&&!0===e[wH](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[IH]()),!0===l&&u[SH](h),c())}},e[AH]=function(t,i){var r=e[UH];if(r&&(!t||r===t[UH]())){var s,a=!1,o=t||sj(null,r,n&&n[lj]?n[lj]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[PH]()))}},WH(e,"_addUnloadCb",(function(){return r}),"add"),WH(e,"_addHook",(function(){return s}),"add"),oS(e,"_unloadHooks",{g:function(){return s}})})),a[IH]=function(e){return o(e)[IH]()},a[mH]=function(){return t},a.setInitialized=function(e){t=e},a[RH]=function(e){n=e},a[SH]=function(e,t){t?t[SH](e):n&&Gv(n[VH])&&n[VH](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),uj="timings",hj="processTelemetryStart";function gj(e){if(e){var t=Ny(e,"-");if(t>-1)return kS(e,t)}return""}(oj={})[0]=0,oj[2]=6,oj[1]=1,oj[3]=7,oj[4098]=6,oj[4097]=1,oj[4099]=7;var pj,mj,fj=ky;function vj(e){return e>0}function Sj(e){return Kv(e)&&e>=1&&e<=2}(mj=pj||(pj={}))[mj.LocalStorage=1]="LocalStorage",mj[mj.SessionStorage=2]="SessionStorage",mj[mj.IndexedDb=3]="IndexedDb";var yj="result",Cj="DBError: Unable to open database",Tj="Database is not open",Ej="DBError: Failed to delete the database",bj=["indexedDB"],_j=Gv,Ij=jv,wj=0;function Aj(e,t){qS("QUnit")&&console&&console.log(" ["+function(e){return e&&e.toISOString()||""}(new Date)+"]: IndexedDbHelper ["+e+"] "+t)}function Pj(e,t,i){e&&e.warnToConsole("IndexedDbHelper ["+t+"] "+i)}function Rj(e,t,i,n){return function(r){i(new Error(t)),Aj(e,"["+n+"] event rejected")}}var Mj=[];function Dj(e,t){for(var i=null,n=0;n<Mj.length;n++)if((i=Mj[n]).name===e)return i;return i={name:e,sch:yE(eE,"IndexedDbHelper["+e+"]"),dbHdl:[],add:function(t){i.dbHdl.push(t),Aj(e,"- dbOpened (add) -- hdls ["+i.dbHdl.length+"]")},remove:function(t){for(var n=i.dbHdl,r=0;r<n.length;r++)if(n[r]===t){n.splice(r,1);break}Aj(e,"- dbClosed (remove) -- hdls ["+i.dbHdl.length+"]")},isOpen:function(){return i.dbHdl.length>0},openHdl:function(){return i.dbHdl.length>0?i.dbHdl[0]:null}},Mj.push(i),i}var kj=function(){function e(t){var i=wj++,n=0;TC(e,this,(function(e){var r=function(){var e=GS()||{},t=null;if(e)try{for(var i=0;i<bj.length;i++)if((t=e[bj[i]])&&_j(t.open))return t}catch(e){t=null}return t||null}()||null;function s(e,r,s){var l=e.db,c=n++;Aj(e.dbName,"["+i+":"+c+"] txn.open - "+r+" -- "+s);var d=l.transaction(r,"readwrite");return d.onabort=function(){Pj(t,e.dbName,"["+i+":"+c+"] txn.onabort - "+r+" -- "+s+" -- "+hS(d.error))},d.onerror=function(){Pj(t,e.dbName,"["+i+":"+c+"] txn.onerror - "+r+" -- "+s)},d.oncomplete=function(){Aj(e.dbName,"["+i+":"+c+"] txn.oncomplete - "+r+" -- "+s)},{db:e,store:d.objectStore(r),tx:d,tbl:r,openCursor:function(t,i){return o(e,r,t,i)},newTransaction:function(t){return a(e,r,t)}}}function a(e,t,i){if(!e||!e.db)return sE(new Error(Tj));try{var n=i(s(e,t,"openStore"));return Qv(n)?n:rE(n)}catch(e){return sE(e)}}function o(e,t,i,n){if(!e||!e.db)return sE(new Error(Tj));var r=null;return i&&Ij(i)?r=new Oj(i):i&&i.isMatch&&(r=i),eE((function(i,a){var o=[],l=null,c=null;r&&r.keyRange&&(c=r.keyRange());var d=s(e,t,"openCursor");(l=c?d.store.openCursor(c):d.store.openCursor()).onerror=Rj(d.db.dbName,"DBError: Failed to Open Cursor",a,"openCursor"),l.onsuccess=function(e){var t=e.target[yj];if(t){var s={store:d,cursor:t,continue:function(){t.continue()},done:function(){i(o)}},l=t.value;if(!r||r.isMatch(l))if(n)try{switch(n(s,l,o)){case 2:i(o);break;case 1:break;default:s.continue()}}catch(e){a(e)}else o.push(l),s.continue();else s.continue()}else i(o)}}))}function l(e,t,i,n){return Dj(e).sch.queue(i,t,n)}e.isAvailable=function(){return!!r},e.openDb=function(e,i,n,s){return l(e,"openDb",(function(l){return eE((function(c,d){var u=!1;function h(t,n,r,s,l){var c={db:n,dbName:e,dbVersion:i,ctx:null,isNew:s,txn:r?r.transaction:null};return l||(c.openStore=function(e,t){return a(c,e,t)},c.openCursor=function(e,t,i){return o(c,e,t,i)}),c}function g(i,r){var s=Dj(e);s.add(i),i.onabort=function(n){Pj(t,e,"onabort -- closing the Db"),s.remove(i)},i.onerror=function(n){Pj(t,e,"onerror -- closing the Db"),s.remove(i)},i.onclose=function(n){Pj(t,e,"onclose -- closing the Db"),s.remove(i)},i.onversionchange=function(n){Pj(t,e,"onversionchange -- force closing the Db"),i.close(),s.remove(i)};var a,o=null;s.dbHdl.length>0&&(o=s.dbHdl[0]),a=h(0,o,r,u);try{HT(n(a),c,d)}catch(e){d(e)}}var p=Dj(e);if(null==r)d(new Error("No available storage factory"));else if(p.isOpen()){var m=h(0,p.openHdl(),null,!1);HT(n(m),c,d)}else{var f=r.open(e,i);f.onblocked=function(i){Pj(t,e,"Db Open Blocked event ["+l+"] - "+(f.error||"")),d(new Error(Cj))},f.onerror=function(i){Pj(t,e,"Db Open Error event ["+l+"] - "+(f.error||"")),d(new Error(Cj))},f.onupgradeneeded=function(t){Aj(e,"Db Open Create/Upgrade needed event ["+l+"]");try{var i=t.target[yj];if(!i)return void d(new Error(Cj));!function(e,t){var i=h(0,e,t,!0,!0);if(s)u=!0,VT(s(i),(function(e){if(e.rejected)try{t.transaction&&t.transaction.abort()}finally{d(e.reason)}else i.txn||(i.txn=t.transaction)}));else try{t.transaction&&t.transaction.abort()}finally{d(new Error("DBError: Database upgrade required"))}}(i,f)}catch(t){Rj(e,Cj,d,l)(t)}},f.onsuccess=function(e){var t=e.target[yj];t?g(t,f):d(new Error(Cj))}}}))}))},e.closeDb=function(e){l(e,"closeDb",(function(t){var i=Dj(e),n=i.dbHdl,r=n.length;if(r>0){for(var s=0;s<r;s++)n[s].close();i.dbHdl=[]}return 1})).catch((function(e){}))},e.deleteDb=function(e){return null!=r&&l(e,"deleteDb",(function(i){var n=Dj(e),s=n.dbHdl,a=s.length;if(a>0){Pj(t,e,"Db is open ["+a+"] force closing");for(var o=0;o<a;o++)s[o].close();n.dbHdl=[]}return eE((function(n,s){setTimeout((function(){try{Aj(e,"["+i+"] starting");var a=r.deleteDatabase(e);a.onerror=function(n){Pj(t,e,"["+i+"] error!!"),s(new Error(Ej))},a.onblocked=function(n){Pj(t,e,"["+i+"] blocked!!"),s(new Error(Ej))},a.onupgradeneeded=function(n){Pj(t,e,"["+i+"] upgrade needed!!"),s(new Error(Ej))},a.onsuccess=function(t){Aj(e,"["+i+"] complete"),n(!0)},Aj(e,"["+i+"] started")}catch(n){Pj(t,e,"["+i+"] threw - "+n),s(new Error(Ej+" - "+n))}}),0)}))}))},e.getDbDetails=function(e){return l(e,"getDbDetails",(function(t){return null!=r&&r.databases?eE((function(t,i){r.databases().then((function(n){for(var r=0;r<n.length;r++)if(n[r].name===e)return void t(n[r]);i(new Error("DBError: Database does not exist"))}),i)})):sE(new Error("DBError: Feature not supported"))}),2e3)}}))}return e.__ieDyn=1,e}(),Oj=function(){function e(t){var i=[],n=null;TC(e,this,(function(e){e.keyRange=function(){return n},e.parseQuery=function(t){if(i=[],t)for(var r=t.split(";"),s=0;s<r.length;s++){var a=r[s],o=a.indexOf("=");if(-1!==o){var l=a.substring(0,o),c=a.substring(o+1);0===l.indexOf("#")&&(l=l.substring(1),n||(n=IDBKeyRange.bound(c,c+"￿"))),e.startsWith(l,c)}}},e.startsWith=function(e,t){i.push({name:e,value:t,type:0})},e.contains=function(e,t){i.push({name:e,value:t,type:1})},e.isMatch=function(e){if(!i||0===i.length)return!0;if(!e)return!1;for(var t=0;t<i.length;t++){var n=i[t],r=e[n.name];if(r)if(0===n.type){if(0!==r.indexOf(n.value))return!1}else if(1===n.type&&-1===r.indexOf(n.value))return!1}return!0},t&&e.parseQuery(t)}))}return e.__ieDyn=1,e}(),Nj=6048e5,Lj="DBError: Unable to add event",xj="Evts",Fj="iKey",Uj=Sj;function Bj(){return(new Date).getTime()}function Vj(e){return e.openStore(Fj,(function(t){return eE((function(i,n){var r={iKey:e.ctx.iKey,tm:Bj()},s=t.store.put(r);s.onsuccess=function(e){i(s.result.toString())},s.onerror=function(e){n(new Error(Lj))},s.onerror=function(e,t){return function(e){return t(new Error("DBError: Unable to update iKey"))}}(0,n)}))}))}function Hj(e){for(var t=[],i=2;i>=1;i--)for(var n=0;n<e.length;n++){var r=e[n];r&&r.evt.persistence===i&&t.push(r.evt)}return t}function $j(e){return function(t){return e.continue()}}function jj(e){var t=e.cursor.delete();return t.onerror=$j(e),t.onsuccess=$j(e),1}function Gj(e,t,i){return e.openCursor(xj,t,(function(e,t,n){return i(t)?(n.push(t),jj(e)):0}))}function qj(e,t){return eE((function(i,n){(function(e){return eE((function(t,i){var n=!1;e.openCursor(Fj,null,(function(e,t,i){var r=t.tm;return Bj()-r<Nj?0:(n=!0,2)})).then((function(){if(n){var r={};Gj(e,null,(function(e){if(!e||!e.evt||!e.evt.iKey)return!0;var t=e.tm;return Bj()-t>Nj||(r[e.evt.iKey]=1,!1)})).then((function(){var n=[];e.openCursor(Fj,null,(function(e,t,i){var s=t.tm;return Bj()-s<Nj||r[t.iKey]?0:(n.push(t),jj(e))})).then((function(){t(n)}),i)}),i)}else t([])}),i)}))})(e).then((function(){(function(e,t){return e.openCursor(xj,"#key="+e.ctx.iKeyPrefix(),(function(i,n){var r=n.key;if(0===r.indexOf(e.ctx.iKeyPrefix())&&-1===r.indexOf(e.ctx.evtKeyPrefix())&&function(e,t){var i=e.tm;return Bj()-i>t}(n,t)){n.key=e.ctx.evtKeyPrefix()+n.id;var s=i.store.store.put(n);return s.onerror=$j(i),s.onsuccess=function(e){try{jj(i)}catch(e){i.continue()}},1}return 0}))})(e,t).then(i,i)}),n)}))}var zj=function(){function e(t,i){TC(e,this,(function(e){var n=null,r=null,s="Unknown",a=null,o=null,l=null,c=-1,d=0,u=6e5;function h(e){return n.openDb(r,1,(function(t){return eE((function(i,n){var r={iKey:s,storageId:a,iKeyPrefix:function(){return o},evtKeyPrefix:function(){return l}};t.ctx=r,HT(Vj(t),(function(){HT(e(t),i,n)}),n)}))}),(function(e){return eE((function(t,i){(function(e){e.objectStoreNames.contains(xj)||e.createObjectStore(xj,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),e.objectStoreNames.contains(Fj)||e.createObjectStore(Fj,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})})(e.db),t()}))}))}function g(e,t,i){return eE((function(n,r){function s(t,i){(function(e,t){return eE((function(i,n){var r=0,s=e.ctx.evtKeyPrefix();function a(){i(r)}function o(e,t){return eE((function(i){var n=e.store.delete(t.key);n.onsuccess=function(e){r++,i()},n.onerror=function(e){i()}}))}e.openCursor(xj,"#key="+s,(function(e,i,n){return i.evt.persistence<=t&&0===i.key.indexOf(s)&&(function(e,t){for(var i=0;i<e.length;i++)if(t.tm<e[i].tm)return void e.splice(i,0,t);e.push(t)}(n,i),n.length>10&&n.splice(n.length-1,1)),0})).then((function(t){0!==t.length?e.openStore(xj,(function(e){for(var i=[],n=0;n<t.length;n++)i.push(o(e,t[n]));return nE(i).then(a,a)})):a()}),(function(){i(0)}))}))})(e,t).then((function(e){e>0&&(d-=e),i(e)}),(function(e){i(0)}))}function a(e){n(t.evt)}function o(){e.openStore(xj,(function(o){var l=o.store.put(t);l.onsuccess=function(r){i&&Vj(e).then(a,a),d++,n(t.evt)},l.onerror=function(a){function o(i){0===i&&r(new Error(Lj)),g(e,t,!1).then((function(e){n(t.evt)}),(function(){r(new Error(Lj))}))}i?s(1,(function(e){e>0?o(e):t.evt.persistence>=2?s(2,(function(e){o(e)})):r(new Error(Lj))})):r(new Error(Lj))}}))}c>0&&d>=c?s(1,(function(e){0===e?t.evt.persistence>=2?s(2,(function(e){o()})):r(new Error(Lj)):o()})):o()}))}e.id=t,e.initialize=function(t){var d=t.itemCtx.diagLog();if(!(n=new kj(d)).isAvailable())return n=null,!1;var g=t.itemCtx.getCfg(),p=t.storageConfig;s=g.instrumentationKey||s,a=e.id||t.id||J$(),l=(o=s+"::")+a+"::",u=p.accessThresholdInMs||u;var m=D$(p,(function(){c=p.maxStorageItems;var t=p.indexedDbName;r&&t!==r&&r&&VT(e.clear(),(function(e){r=t,h((function(e){return e.isNew?[]:qj(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null}))})),r=t}));return i&&i.add(m),h((function(e){return e.isNew?[]:qj(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null})),!0},e._getDbgPlgTargets=function(){return[r]},e.supportsSyncRequests=function(){return!1},e.getAllEvents=function(){return null!=n&&n.isAvailable()?h((function(e){return eE((function(t,i){(function(e,t){return e.openCursor(xj,t,(function(e,t,i){return i.push(t),0}))})(e,"#key="+e.ctx.evtKeyPrefix()).then((function(e){d=e.length,t(Hj(e))}),i)}))})):[]},e.addEvent=function(e,t,i){return null!=n&&n.isAvailable()?(t.id=t.id||J$(),Uj(t.persistence)||(t.persistence=1),h((function(i){var n=e||t.id,r={key:i.ctx.evtKeyPrefix()+n,id:n,evt:t,tm:Bj(),v:1};return g(i,r,!0)}))):t},e.removeEvents=function(e){if(null==n||!n.isAvailable())return[];var t=[];return eE((function(i,n){h((function(i){return i.openCursor(xj,"#key="+i.ctx.iKey,(function(i,n,r){if(-1!==function(e,t){for(var i=t.length,n=0;n<i;n++)if(e===t[n].id)return n;return-1}(n.id,e)){var s=i.cursor.delete();return s.onerror=$j(i),s.onsuccess=function(){t.push(n.evt),i.continue()},1}return 0}))})).then((function(e){d-=t.length,i(t)}),(function(e){d-=t.length,i(t)}))}))},e.clear=function(){return null!=n&&n.isAvailable()?eE((function(e,t){h((function(e){return Gj(e,"#key="+e.ctx.evtKeyPrefix(),(function(t){return 0===t.key.indexOf(e.ctx.evtKeyPrefix())}))})).then((function(t){d=0,e(Hj(t))}),t)})):[]},e.moveStaleEvents=function(){h((function(e){return qj(e,u)}))},e.teardown=function(){n&&n.closeDb(r)}}))}return e.__ieDyn=1,e}(),Wj="Version";function Kj(e,t){if(e)for(var i=vS(e),n=0;n<i.length;n++){var r=i[n];if(!t(e[r],r))break}}function Jj(e){var t=!0;return Kj(e,(function(e,i){return e&&(t=!1),t})),t}function Yj(e,t){for(var i=1,n=0,r=function(){var e=[],r=t[i];if(Kj(r,(function(t,i){return e.push(i),++n<10})),n>0){for(var s=0;s<e.length;s++)delete r[e[s]];return{value:!0}}i++};i<=e&&n<10;){var s=r();if("object"==typeof s)return s.value}return n>0}var Qj=Sj,Zj=function(){function e(t,i,n){TC(e,this,(function(e){var r=null,s="AWTEvents",a=null,o=null,l=null,c=5e6,d=6e5,u=null,h=null;function g(e,t){return{key:e,db:t}}function p(e,t){void 0===t&&(t=!0);var i=null;if(r){var n=r.getItem(e);if(n)try{i=JSON.parse(n)}catch(t){r.removeItem(e)}}return t&&!i&&(i={events:{1:{},2:{},3:{}},lastAccessTime:0}),g(e,i)}function m(e,t){void 0===t&&(t=!0);var i=!0,n=e.db;if(n){t&&(n.lastAccessTime=(new Date).getTime());for(var s=1;s<=2;s++)if(!Jj(n.events[s])){i=!1;break}}try{if(i)r&&r.removeItem(e.key);else{var a=JSON.stringify(n);if(a.length>c)return!1;r&&r.setItem(e.key,a)}}catch(e){return!1}return!0}function f(e){var t=[],i=p(e,!1),n=i.db;if(n){var s=n.events;try{for(var a=1;a<=2;a++)Kj(s[a],(function(e,i){return e&&t.push(e),!0}))}catch(e){}r&&r.removeItem(i.key)}return t}function v(){if(r){for(var e=r.getItem(u),t=[],i=p(h),n=!1,a=0;a<r.length;a++){var o=r.key(a);if(0===o.indexOf(s)&&o!==u){if("3"!==e){t.push(g(o,null));continue}var c=p(o,!1),f=c.db;if(f){if((new Date).getTime()-f.lastAccessTime>d){for(var v=1,S=function(){var e=f.events[v],t=i.db.events[v];Kj(e,(function(i,n){return(gj(i.iKey)||i.iKey)===l&&(t[n]=i,delete e[n]),!0})),v++};v<=2;)S();n=!0,t.push(c)}}else t.push(g(o,null))}}for(a=0;a<t.length;a++)m(t[a],!1);n&&m(i),r.setItem(u,"3")}}e.id=i,r=function(e){var t=GS()||{},i=null;try{if(i=t[e]){var n="__storage_test__";i.setItem(n,n),i.removeItem(n)}}catch(e){(function(e,t){var i=!1;return t instanceof DOMException&&(22!==t.code&&"QuotaExceededError"!==t.name&&1014!==t.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||e&&0!==e.length&&(i=!0)),i})(i,e)||(i=null)}return i}(t)||null,e._getDbgPlgTargets=function(){return[s,c]},e.initialize=function(t){if(!r)return!1;var i=t.storageConfig;a=e.id||t.id||J$(),o=t.itemCtx.getCfg().instrumentationKey,l=gj(o)||o,d=i.accessThresholdInMs?i.accessThresholdInMs:d;var g=D$(i,(function(){c=i.maxStorageSizeInBytes;var t=i.storageKey;s&&t!==s&&VT(e.clear(),(function(e){h=(s=t)+"."+a,u=s+Wj,v()}))}));return n&&n.add(g),s=i.storageKey,h=s+"."+a,u=s+Wj,v(),!0},e.supportsSyncRequests=function(){return!0},e.getAllEvents=function(){try{var e=[],t=p(h,!1).db;if(t)for(var i=t.events,n=2;n>=1;n--)Kj(i[n],(function(t){return t&&(gj(t.iKey)||t.iKey)===l&&e.push(t),!0}));return e}catch(e){return sE(e)}},e.addEvent=function(e,t,i){try{var n=p(h);t.id=t.id||J$(),Qj(t.persistence)||(t.persistence=1);for(var r=t.persistence,s=t.id,a=n.db.events;;){if(a[r][s]=t,m(n))return t;if(delete a[r][s],!Yj(r,a))return sE(new Error("Unable to free up event space"))}}catch(e){return sE(e)}},e.removeEvents=function(e){try{var t=p(h,!1),i=t.db;if(i){var n=i.events;try{for(var r=0;r<e.length;++r){var s=e[r];delete n[s.persistence][s.id]}if(m(t))return e}catch(e){}e=f(t.key)}return e}catch(e){return sE(e)}},e.clear=function(){try{var e=[],t=p(h,!1),i=t.db;if(i){for(var n=i.events,r=function(t){var i=n[t];Kj(i,(function(t){return t&&(gj(t.iKey)||t.iKey)===l&&(delete i[t.id],e.push(t)),!0}))},s=2;s>=1;s--)r(s);m(t)}return e}catch(e){return sE(e)}},e.teardown=function(){try{var e=p(h,!1),t=e.db;t&&(t.lastAccessTime=0,m(e,!1))}catch(e){}},e.moveStaleEvents=function(){v()}}))}return e.__ieDyn=1,e}(),Xj=Sj,eG=SS({maxStorageSizeInBytes:{isVal:vj,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:Xj,v:1},providers:[pj.LocalStorage,pj.IndexedDb],indexedDbName:"AppInsightEvents.1",maxStorageItems:{isVal:vj,v:void 0}}),tG=function(e){function t(){var i=e.call(this)||this;return i.identifier="LocalStorage",i.priority=1009,i.version="4.3.1",TC(t,i,(function(e,t){var i,n,r,s;function a(){i=!1,n=!1,r=null,s=[]}function o(e,t){r||(r=yE(eE,"LocalStorage")),r.queue((function(e){return t(e)}),e).catch((function(e){}))}function l(t){K$(e.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){o("sendToNext",(function(i){return VT(t.provider.getAllEvents(),(function(i){for(var n=i.value||[],r=0;r<n.length;r++)try{var s=n[r];(gj(s.iKey)||s.iKey)===t.tenantId&&e.processNext(s,t.coreRootCtx.createNew())}catch(e){}}))}))}),(function(){return{iKeyConfig:t}}))}function c(t,i){K$(e.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){o("removeEvents",(function(e){var n=[];if(cy(i,(function(e){(gj(e.iKey)||e.iKey)===t.tenantId&&n.push(e)})),n.length>0)return VT(t.provider.removeEvents(n),(function(e){}))}))}),(function(){return{iKeyConfig:t,events:i}}))}function d(t){var i=new zj(void 0,e._unloadHooks);return i.initialize(t)||(i=null),i}function u(t,i){var n=new Zj(t,void 0,e._unloadHooks);return n.initialize(i)||(n=null),n}function h(e){for(var t=e.storageConfig.providers,i=null,n=0;!i&&n<t.length&&n<5;)switch(t[n++]){case pj.LocalStorage:i=u("localStorage",e);break;case pj.SessionStorage:i=u("sessionStorage",e);break;case pj.IndexedDb:i=d(e)}return i}function g(t,i,n,r){var a=!1;if(cy(s,(function(e){if(e.iKey===t.instrumentationKey)return a=!0,-1})),!a){var o=null;e._addHook(D$(t,(function(n){var r=nj(null,n.cfg,i);o=r.getExtCfg(e.identifier,eG);var a=!1,d=null,u=t.instrumentationKey;if(cy(s,(function(e){if(e.iKey===u)return a=!0,d=e,-1})),a&&d){var p=o.providers,m=d.preProviders;(function(e,t){if(e.length!==t.length)return!1;var i=!0;return cy(e,(function(e,n){if(e!==t[n])return i=!1,-1})),i})(p,m)||VT(g.clear(),(function(e){if(!e.rejected)try{var t=s.indexOf(d);-1!==t&&s.splice(t,1);var n=h(d.providerContext);d.provider=n,d.preProviders=p.slice();var r=d.preListener;r&&i.removeNotificationListener(r);var a={eventsSent:function(e){c(d,e)},eventsDiscarded:function(e,t){c(d,e)}};d.preListener=a,s.push(d),i.addNotificationListener(a),l(d)}catch(e){}}))}})));var d=function(t,i,n,r){t&&(t.extensionConfig=t.extensionConfig||[]),!r&&i&&(r=i.getProcessTelContext().getNext());var s=null,a=e._getTelCtx().getNext();return a&&(s=a.getPlugin()),nj(r,t,i,s)}(t,i,0,r),u={itemCtx:d,storageConfig:o,id:e.id};if(!jv(t.instrumentationKey))return;var g=h(u),p={iKey:t.instrumentationKey,tenantId:gj(t.instrumentationKey)||t.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:d,providerContext:u,provider:g,preProviders:o.providers.slice()};if(g){Xj(o.minPersistenceLevel||-1)&&(p.minPersistenceCacheLevel=o.minPersistenceLevel);var m={eventsSent:function(e){c(p,e)},eventsDiscarded:function(e,t){c(p,e)}};p.preListener=m,s.push(p),i.addNotificationListener(m),l(p)}else s.push(p)}}a(),e.initialize=function(e,n,s,a){K$(n,(function(){return"LocalStorageChannel.initialize"}),(function(){i||(t.initialize(e,n,s),t.setInitialized(!1),i=!0,r=yE(eE,"LocalStorage")),g(e,n,0,a)}),(function(){return{coreConfig:e,core:n,extensions:s,pluginChain:a}}))},e.processTelemetry=function(t,r){var a=t;if(i&&!n){r=e._getTelCtx(r),function(e,t){var i=e;i[uj]=i[uj]||{},i[uj][hj]=i[uj][hj]||{},i[uj][hj][t]=fj()}(t,e.identifier);var l=null;cy(s,(function(e){e.iKey===t.iKey&&(l=e)}));var c=l?l.provider:null;if(a.sync||!c)return void e.processNext(a,r);a.id=a.id||J$(),Sj(a.persistence)||(a.persistence=1),function(e,t){return!(t.sync||t.persistence<e.minPersistenceCacheLevel)}(l,a)&&o("processTelemetry",(function(e){return c.addEvent(a.id,a,r)}))}e.processNext(a,r)},e.pause=function(){n=!0},e.resume=function(){K$(e.core,(function(){return"LocalStorageChannel:resume"}),(function(){n=!1,cy(s,(function(e){e.provider&&l(e)}))}))},e._doTeardown=function(e,t){cy(s,(function(e){var t=e.provider;t&&t.teardown()})),a()},e.flush=function(e,t,i){},e._getDbgPlgTargets=function(){return[s]},e._sendStale=function(e){cy(s,(function(t){if(t&&t.iKey===e&&t.provider)return t.provider.moveStaleEvents(),l(t),-1}))}})),i}return jy(t,e),t.__ieDyn=1,t}(dj),iG="LocalStorage",nG=class{constructor(e,t,i,n,r,s){this.logger=e,this.configProvider=t,this.clientInfo=i,this.contextProvider=n,this.accountCollectorURL=r,this.envOverride=s,this.manager=new LM,this.managerConfig=this.createConfigForManager(),this.currentTransmitProfile=Gi.REPORTING_PROFILE.RT_PROFILE,this.initManager(),this.uiVersion=this.getUiVersion(),this.configProvider.on("configUpdated",(()=>this.updateChannelConfig()))}createLogger(e,t){return new rG(e,this.manager,this.logger,this.configProvider,this.uiVersion,t,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 e=this.clientInfo.match(/^.*?\/(\d+\/)(.*?)\/.*$/);return e?e[1]+e[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:(e,t)=>this.logDiscardedEvents(e,t),eventsSent:e=>this.logSentEvents(e)}),this.setTransmitProfile()}initLocalStorageChannel(){if(!this.configProvider.config.useLocalStorageForOneDs)return;const e=new tG;this.managerConfig.channels.push([e]);const t={storageKey:"TsCalling",accessThresholdInMs:this.configProvider.config.oneDSLocalStorage.accessThresholdInMs??6e5};this.managerConfig.extensionConfig[iG]=t}logDiscardedEvents(e,t){let i="discarded events:";e.forEach((e=>i=`${i+e.name};`)),this.logger.info(`${i} reason:${t}`)}logSentEvents(e){let t=`sent events: ${e[0]?.data?.CorrelationId&&un("value",e[0].data.CorrelationId)}:`;e.forEach((e=>{t=`${t+e.name};`})),this.logger.info(`${t}`)}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}},rG=class{constructor(e,t,i,n,r,s,a,o){this.tenant=e,this.manager=t,this.logger=i,this.configProvider=n,this.uiVersion=r,this.eventLatency=s,this.contextProvider=a,this.envOverride=o,this.instanceConfig={extensions:[],extensionConfig:{}};const{oneDSLocalStorage:l,oneDSNotificationManager:c}=this.configProvider.config;c.blockEventsDiscardedNotifications&&this.blockEventsDiscarded(),c.blockNotificationsOnPageUnload&&this.blockNotificationListenersOnPageUnload(),l.sendStaleEvents&&this.sendStaleEvents()}sendEvent(e){this.setEnvPropertiesToEveryEvent();const t=e.props,i={};switch(this.logger.info(`preparing event for delivery: ${e.props?.CorrelationId??""}/${e.eventName}`),this.tenant){case"signaling":t.SkypeId&&(i.user_id={value:t.SkypeId,kind:10},i.Skype_InitiatingUser_Username={value:t.SkypeId,kind:10},i.SkypeId={value:t.SkypeId,kind:10},delete t.SkypeId),this.uiVersion&&(i.ui_version={value:this.uiVersion,kind:0});break;case"media":case"tlePlayer":this.uiVersion&&(i.uiVersion={value:this.uiVersion,kind:0});break;case"realtimeMedia":this.uiVersion&&(i["AppInfo.Version"]={value:this.uiVersion,kind:0})}for(const e of Object.keys(t)){const n=t[e];i[e]={value:n?.value??n,kind:n?.piiKind??0}}const n={name:e.eventName,data:i,latency:this.eventLatency,persistence:Kw.Normal,sync:this.configProvider.config.oneDSEventSendType};this.configProvider.config.smallCallTelemetry.enable&&"mdsc_webrtc_call_session"===n.name&&(n.sync=this.configProvider.config.smallCallTelemetry.eventSendType),this.logger.info(`about to send event ${JSON.stringify(tH.omit(n,["LocalUser","TargetUser"]))}`),this.applicationInsights.track(n)}sendStaleEvents(){this.logger.info("preparing to send stalled telemetry events");const e=this.applicationInsights.getPlugin(iG).plugin;e._sendStale&&e._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 e=!1;const t=()=>{e=!0};window.addEventListener("beforeunload",t),window.addEventListener("unload",t),window.addEventListener("pagehide",t),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?t():e=!1})),this.applicationInsights.getNotifyMgr().listeners.forEach((t=>{const{eventsSent:i,eventsDiscarded:n}=t;i&&(t.eventsSent=t=>{e?this.logger.info("1DS eventSent was not raised due to page unload"):i(t)}),n&&(t.eventsDiscarded=(t,i)=>{e?this.logger.log("1DS eventsDiscarded was not raised due to page unload"):n(t,i)})}))}blockEventsDiscarded(){this.applicationInsights.getNotifyMgr().listeners.forEach((e=>{e.eventsDiscarded=(e,t)=>{this.logger.log(`1DS eventsDiscarded with reason ${t} was not raised due to configuration`)}}))}setEnvPropertiesToEveryEvent(){const e=this.contextProvider?.();if(!an(this.ctx,e)&&(this.ctx=e,this.ctx))if(this.envOverride){for(const e of Object.keys(this.envOverride||{}))if(this.ctx[e]){const t=this.ctx[e].piiKind??0,i=Dn(this.ctx[e].value);this.manager.getPropertyManager().setProperty(this.envOverride[e],{value:i,kind:t})}}else for(const e of Object.keys(this.ctx)){const t=this.ctx[e].piiKind??0,i=Dn(this.ctx[e].value);this.manager.getPropertyManager().setProperty(e,{value:i,kind:t})}}},sG=class extends Error{constructor(e,t=1){super(e),this.callSupport=t}};function aG(e){let t={};return e.telemetryLoggers?t=e.telemetryLoggers:e.telemetryService?.getGenericTelemetryLogger&&e.telemetryTenants?Object.keys(e.telemetryTenants).forEach((i=>t[i]=e.telemetryService.getGenericTelemetryLogger(e.telemetryTenants[i]))):e.telemetryService&&(e.telemetryService.sendEvents||e.telemetryService.getCallingAdapter)&&(e.telemetryService.sendEvents&&(t.media={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}},t.tlePlayer={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}}),e.telemetryService?.sendRealTimeEvents&&(t.realtimeMedia={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendRealTimeEvents([t])}}),e.telemetryService.getCallingAdapter&&(t.signaling={sendEvent(t){e.telemetryService.getCallingAdapter().sendEvent(t.eventName,t.props)}})),t}var oG=class e extends gt{constructor(e,t){super(),this._config=e,this._ecsProvider=t,this.callRegistries=[],this._logger=new ct(this._config.logger).createChild("PluginlessStack"),this._platformManager=new qV,this._waitForAccountConfiguration=new Kt,this.platformCallConstraintsProvider=new tr(this._logger.createChild("PlatformConstraintsProvider"))}async initializeMediaAgent(e){if(this._mediaAgent)throw new sG("Media agent is already initialized");let t,i=null;if(!this._mediaAgentProvider)throw new sG("PluginlessStack initialize MediaAgent error, Media Stack not initialized",i);try{this._relayManagerProvider=new pr(e,this._signalingAgentProvider,this._ecsProvider,this._logger),t=await this._mediaAgentProvider.buildAgent(this._config.platformType,this._relayManagerProvider,this._midCallTelemetry)}catch(e){i=e.some((e=>"incompatible_version"===e.reason))?2:1}if(!this._config.usePlatformSupportApi&&!this._config.callSettings?.useLwjForAllCalls){if(i)throw new sG("PluginlessStack initialization failed",i);{const e=(new qV).getPlatformSupportLevel(!0);if(1!==e&&2!==e)throw new sG("PluginlessStack initialization failed",1)}}t?(this._screenSharingManager=new JV(t.getScreenSharingManager()),this._waitForAccountConfigurationTimeout=window.setTimeout((()=>{this._waitForAccountConfiguration.resolve(void 0),this._waitForAccountConfigurationTimeout=void 0}),3e4),this._oneDsTelemetryLoggers=function(e,t,i,n,r,s){const a={signaling:[],media:[],tlePlayer:[],realtimeMedia:[]};let o={signaling:{sendEvent:e=>a.signaling.push(e)},media:{sendEvent:e=>a.media.push(e)},tlePlayer:{sendEvent:e=>a.tlePlayer.push(e)},realtimeMedia:{sendEvent:e=>a.realtimeMedia.push(e)},gtcAudit:{sendEvent:e=>a.realtimeMedia.push(e)}};return t.getConfigReceivedOrTimeout().then((async()=>{let l=(await r)?.serviceUrls?.OneDsCollectorUrl;if(l=l??t.config.collectorUrl,l){const r=new nG(e,t,i,n,l);o.signaling=r.createLogger("signaling",t.config.eventLatency),o.media=r.createLogger("media",t.config.eventLatency),o.tlePlayer=r.createLogger("tlePlayer",t.config.eventLatency),o.gtcAudit=r.createLogger("gtcAudit",Ww.Immediate);const s=new nG(e,t,i,n,l,{"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"});o.realtimeMedia=s.createLogger("realtimeMedia",t.config.eventLatencyRealTime)}else o=aG(s);for(const[e,t]of Object.entries(a))for(const i of t)o[e].sendEvent(i)})),o}(this._logger.createChild("OneDsLogger"),t.getConfigProvider(),e.clientInformation,this._config.telemetryContextProvider,this._waitForAccountConfiguration.promise,this._config),t.getConfigProvider().config.useOneDsLogger&&(this.signalingLoggerAdapter={sendEvent:(e,t)=>{const i={eventName:e,props:t};this._oneDsTelemetryLoggers.signaling.sendEvent(i)}}),this._mediaAgent=t,this._e911=new zV(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 xi}async initializeSignalingAgentProvider(e){this._trouterService=e.trouterService,this._signalingAgentProvider=((e,t,i,n)=>new eH(e,t,i,n))(e.signalingAgentConfig,this._ecsProvider,this._config.logger,this.signalingLoggerAdapter)}static async build(t,i,n){try{const r=new e({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.logger,telemetryLoggers:t.telemetryLoggers,telemetryService:t.telemetryService,telemetryTenants:t.telemetryTenants,telemetryContextProvider:t.telemetryContextProvider,platformType:t.platformType,callSettings:t.callSettings,usePlatformSupportApi:t.usePlatformSupportApi,clientInformation:t.signalingAgentConfig.clientInformation,vdi3diagnostics:t.vdi3diagnostics},i);return r.initializeMediaProvider({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.mediaAgentFactoryConfig.logger,safeLogger:t.mediaAgentFactoryConfig.safeLogger,webcvProvider:t.mediaAgentFactoryConfig.webcvProvider,wasmdnsProvider:t.mediaAgentFactoryConfig.wasmdnsProvider,wasmaecProvider:t.mediaAgentFactoryConfig.wasmaecProvider,wasmVqeProvider:t.mediaAgentFactoryConfig.wasmVqeProvider,createWasmWorkerCbs:t.mediaAgentFactoryConfig.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.mediaAgentFactoryConfig.encodedStreamsWorkerProvider,clientInformation:t.signalingAgentConfig.clientInformation}),r.setMidCallTelemetry(n),r.initializeSignalingAgentProvider({signalingAgentConfig:t.signalingAgentConfig,trouterService:t.trouterService}),await r.initializeMediaAgent({httpRequestDispatcher:t.mediaAgentFactoryConfig.httpRequestDispatcher,tokenProvider:t.mediaAgentFactoryConfig.tokenProvider,configProvider:t.mediaAgentFactoryConfig.configProvider,appStateProvider:t.mediaAgentFactoryConfig.appStateProvider,clientInformation:t.signalingAgentConfig.clientInformation,trapTokenCredentialsProvider:t.mediaAgentFactoryConfig.trapTokenCredentialsProvider,relayManager:t.mediaAgentFactoryConfig.relayManager}),r}catch(t){throw t instanceof sG?t:new sG(`${t}`)}}static async buildBaseStack(t,i){const n=new e(t,i);return n.initializeMediaProvider({detectH264Support:t.detectH264Support,domOverrides:t.domOverrides,mediaSettings:t.mediaSettings,logger:t.logger,safeLogger:t.safeLogger,webcvProvider:t.webcvProvider,wasmdnsProvider:t.wasmdnsProvider,wasmaecProvider:t.wasmaecProvider,wasmVqeProvider:t.wasmVqeProvider,createWasmWorkerCbs:t.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.encodedStreamsWorkerProvider,clientInformation:t.clientInformation}),n}async init(){}async dispose(e=be()){const t=this._logger.createFnLogger("dispose",e);t.info("Dispose"),this._ecsProvider.dispose(),this._e911?.dispose();const i=e=>{t.warn("Failed:",e)},n=this.callRegistries.map((t=>t.dispose(e).catch(i)));await Promise.all(n),await this._mediaAgentProvider.dispose(e),t.info("media agent is disposed"),this.callRegistries=[],t.info("call registries are disposed"),this._screenSharingManager&&(this._screenSharingManager.dispose(e),this._screenSharingManager=void 0,t.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(e,t=be()){const i=e?Le(e.id):void 0,n=this._logger.createFnLogger(`createCallRegistry[identity=${i}]`,t),r=this.callRegistries.find((t=>t.identity===e.id));return r&&!r.isDisposing?(n.info(`callRegistry already exists for ${Le(e.id)}`),r):(r?.isDisposing&&await r.disposePromise,this._createCallRegistry(e))}createCompositor(e){throw new Error("Method not implemented.")}_createCallRegistry(e){if(!this._trouterService)throw new sG("Unable to create call registry, trouter service undefined");if(!this._mediaAgent)throw new sG("Unable to create call registry, media agent undefined");if(!this._signalingAgentProvider)throw new sG("Unable to create call registry, signaling agent undefined");const t=new Hf(this._trouterService,this._signalingAgentProvider,this._mediaAgent,this._logger,aG(this._config),this._ecsProvider,e,this._oneDsTelemetryLoggers,this._config.vdi3diagnostics);return t.on("disposed",(()=>{this.callRegistries.splice(this.callRegistries.indexOf(t),1)})),t.on("accountConfigurationReceived",(e=>{this._waitForAccountConfiguration.isPending&&(this._waitForAccountConfiguration.resolve(e),window.clearTimeout(this._waitForAccountConfigurationTimeout)),this._relayManagerProvider.getOrCreateRelayManager().setDefaultRelayConfig(e.relayConfig),this._relayManagerProvider.getOrCreateRelayManager().setClientSupportsGenericTokenApi(e.clientSupportsGenericTokenAPI)})),t.on("locationInfoSet",((e,t)=>{this._e911?.setClientInfo(e,t)})),this._relayManagerProvider.getOrCreateRelayManager(),this.callRegistries.push(t),t}initializeMediaProvider(e){const t=(0,lt.assign)({},e);this._mediaAgentProvider=new jV(t,this._ecsProvider,this.platformCallConstraintsProvider),this._deviceManager=new qf(this._mediaAgentProvider.getDeviceManager())}setMidCallTelemetry(e){this._midCallTelemetry=e}getDeviceManager(){return this._deviceManager}async getDeviceManagerAsync(){return this._deviceManager}createDeviceManager(e){return this._deviceManager}getScreenSharingManager(){return this._screenSharingManager}getSetup(){}getEcsProvider(){return this._ecsProvider}async getEcsProviderAsync(){return this._ecsProvider}getCallFeedback(){return null}getAiMdp(){return null}fireIntent(e,t){}getVersion(){return{build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"}}async getVersionAsync(){return{build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"}}getMediaStatus(){return null}getVideoCapabilityLimits(){return null}async setMediaConfig(e){this._mediaAgent.setMediaConfig(e)}async getE911Info(){return this._e911?.getInfo()}setPlatformCallConstraints(e){this.platformCallConstraintsProvider.setConstraints(e)}getPlatformSupportLevel(){return this._platformManager.getPlatformSupportLevel(!!this._mediaAgent)}async getPlatformSupportLevelAsync(){return this.getPlatformSupportLevel()}getLiveStreamClient(){return new Li(this._ecsProvider.createEcsConfiguration(),this._logger.createChild("LiveStreamClient"),(()=>aG(this._config).tlePlayer))}createVoipCallCoordinator(){}async setLogFileName(e,t,i){throw new Error("not supported")}aggregateDiagnosticLogs(e){return Promise.reject("not supported")}submitBrbReport(e,t){return Promise.reject("not supported")}extendBrbFeedback(e,t){return Promise.reject("not supported")}async addOcclusion(e,t,i,n,r,s){}async removeOcclusion(e,t,i,n){}async flushLogs(){throw new Error("not supported")}getDebugDump(){return this._mediaAgent&&function(e){if(!e)return null;const t=Ue("[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 function(e){if(!e)return null;const t=Ue("[U|u]ser[N|n]ame|[O|o]rg[I|i]d");return e.replace(t,Be(De))}(e.replace(t,Be((()=>"<redacted>"))))}(JSON.stringify(this._mediaAgent.getDiagnosticsData()))}async getStageCapability(){throw new Error("not supported")}async getAiCameraCapability(){throw new Error("not supported")}createAiCameraManager(){throw new Error("not supported")}async disposeMediaAgent(e=be()){if(!this._mediaAgent)throw new sG("_mediaAgent is not initialized");await(this._mediaAgent?.dispose(e)),this._mediaAgent=null}async updateSignalingAgentProviderConfig(e){if(!this._signalingAgentProvider)throw new sG("_signalingAgentProvider not initialized");this._trouterService=e.trouterService,this._signalingAgentProvider.getSignalingAgent().updateSignalingAgentConfig(e.signalingAgentConfig)}},lG={build(e,t=!0){const i=e.telemetryContextProvider?.(),n=new WV(i),r=new Xf;return t&&function(e,t,i){if(!zf.RootToolsManager.isDelegateSet()){const n=new ev(e.telemetryService,t);if(zf.RootToolsManager.setDelegate(n),n.on("onMidCallTelemetry",(e=>i.send(e))),e.logger){const t=new Kf(e.logger);zf.LogFactory.instance().addAppender(t)}}e.logger=new Ae("JS.TsCalling.Pluginless",!0),e.mediaAgentFactoryConfig.logger=new Ae("JS.TsCalling.MediaAgentUnsafe",!1),e.mediaAgentFactoryConfig.safeLogger=new Ae("JS.TsCalling.MediaAgent",!0),e.signalingAgentConfig.logger=new Ae("JS.TsCalling.SignalingAgent",!0)}(e,n,r),oG.build(e,n,r)},buildBaseStack(e){const t=e.telemetryContextProvider?.(),i=new WV(t);return oG.buildBaseStack(e,i)},getVersion:()=>({build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"})},cG=[{className:xf,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:Hf,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:Ug,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:qf,props:["getPermissionState","getPermissionStateAsync","isAudioOutputSelectionSupported","askDevicePermission","enumerateDevicesAsync","getPreferredCamera","selectDevices","getSelectedDevices","startPreview","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:WV,props:["setEcsConfig","setUserEcsServerUrl","getUserEcsServerUrl","setActiveUserForEcs","getEcsQueryParameters","ecsGetUserQueryParameters","shouldTriggerCQF"]},{className:Fp,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:Bg,props:["contentSharingState","contentSharingStatus","contentSharingTerminationReason","contentSharingIdentity","contentSharingGuid","startContentSharing","joinContentSharing","updateContentSharingSessionState","takeContentSharingControl","updateContentSharingParticipantStateToViewer","stopContentSharing","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:tp,props:["addHandler","removeHandler","updateNegotiationTag"]},{className:Ng,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:Og,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:oG,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"])}];return"object"==typeof r.exports&&(r.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||undefined===i||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(n=Object.getOwnPropertyDescriptor(t,i))||n.enumerable});return e})(r.exports,n)),r.exports}))}));const ee={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"]},CTE_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:["ExpectedError"]},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:["ExpectedError"]},STOP_DISPOSED:{message:"VideoEffects feature is disposed. Create a new VideoEffects Feature instance.",code:400,subCode:46157,resultCategories:["ExpectedError"]},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"]}},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"]}},VDI3:{INVALID_CDN_URL:{message:"The remote stack is unavailable due to invalid CDN path",code:400,subCode:46600,resultCategories:["UnexpectedClientError"]},METHOD_UNAVAILABLE:{message:"This method is unavailable when VDI remoting is enabled",code:405,subCode:46601,resultCategories:["ExpectedError"]},PROPERTY_UNAVAILABLE:{message:"This property is unavailable when VDI remoting is enabled",code:405,subCode:46602,resultCategories:["ExpectedError"]},METHOD_MISSING:{message:"This method is missing",code:405,subCode:46603,resultCategories:["UnexpectedClientError"]},CALL_INITIALIZING:{message:"The call object is initializing",code:400,subCode:46604,resultCategories:["ExpectedError"]},REMOTE_STACK_TERMINATED:{message:"The remote stack has been terminated. Please re-initialize the CallClient",code:500,subCode:46605,resultCategories:["UnexpectedClientError"]}}}},te={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"]},10056:{public:!0,code:408,subCode:10056,message:"Call setup failed due to timeout and lack of response from the participant attempting to join meeting or start a 1:1 or 1:n call. This may be caused by the participant leaving abruptly by closing the browser/application, losing network connectivity, or other reasons. Please ensure the participant did not leave abruptly and has a stable network connection.",resultCategories:["UnexpectedClientError"]},10057:{public:!0,code:408,subCode:10057,message:"Call setup failed due to timeout and lack of response from the participant accepting incoming 1:1 or 1:n call or meeting join request. This may be caused by the participant leaving abruptly by closing the browser/application, losing network connectivity, or other reasons. Please ensure the participant did not leave abruptly and has a stable network connection.",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:["ExpectedError"]}},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"]}}},ie=422,ne=500,re="19:preview-",se={Date:!0,RegExp:!0,String:!0,Number:!0},ae=Symbol("INTERNAL_TELEMETRY_ERROR_MESSAGE_SYMBOL");var oe;class le extends Error{constructor(e){if(super(),this._code=0,this._subCode=0,this._resultCategories=[],this[oe]="",this.name="CallingCommunicationError",e.originalError instanceof le)return this._code=e.originalError.code,this._subCode=e.originalError.subCode,this._resultCategories=e.originalError.resultCategories,this.message=e.originalError.message,this.stack=e.originalError.stack,void(this[ae]=e.originalError[ae]);e.defaultErrorMessageArgs?this.message=e.defaultError.message.replace(/{(\d+)}/g,(function(t,i){return e.defaultErrorMessageArgs&&void 0!==e.defaultErrorMessageArgs[i]?e.defaultErrorMessageArgs[i]:t})):this.message=e.defaultError.message,this._code=e.defaultError.code,this._subCode=e.defaultError.subCode,this._resultCategories=e.defaultError.resultCategories,e.originalError instanceof Error&&(this.stack=e.originalError.stack,this[ae]=e.originalError.message)}get code(){return this._code}get subCode(){return this._subCode}get resultCategories(){return this._resultCategories}}oe=ae;const ce=Symbol("loggerKeySymbol");var de,ue,he;function ge(e){return fe(e||"",!1)}function pe(e){return fe(e||"",!0)}!function(e){e.CallAgent="CallAgent",e.TeamsCallAgent="TeamsCallAgent"}(de||(de={})),function(e){e.Call="Call",e.TeamsCall="TeamsCall"}(ue||(ue={})),function(e){e.IncomingCall="IncomingCall",e.TeamsIncomingCall="TeamsIncomingCall"}(he||(he={}));const me=e=>(t,i,n)=>{const r=n.value;return n.value=function(...t){if(this.kind===ue.TeamsCall&&this.isEmergencyCallInProgress())throw new le({defaultError:ee.CALL.OPERATION_NOT_ALLOWED_DURING_EMERGENCY_CALL,defaultErrorMessageArgs:[e]});return r.apply(this,t)},n},fe=(e,t)=>t?(t,i,n)=>{const r=n.value;return n.value=async function(...t){let i;const n=+new Date;ve(this,e,"started");try{i=await r.apply(this,t),ve(this,e,"succeeded",n)}catch(t){const i=new le({defaultError:ee.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[e],originalError:t});throw Se(this,e,t,n),i}return i},n}:(t,i,n)=>{const r=n.value;return n.value=function(...t){let i;const n=+new Date;ve(this,e,"started");try{i=r.apply(this,t),ve(this,e,"succeeded",n)}catch(t){const i=new le({defaultError:ee.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[e],originalError:t});throw Se(this,e,t,n),i}return i},n};function ve(e,t,i,n){const r=ye(e);if(r){const e=n?`in ${(+new Date-n)/1e3}s`:"";r.info(`op:${t}, ${i} ${e}`)}}function Se(e,t,i,n){const r=ye(e);try{if(r){const e=n?`in ${(+new Date-n)/1e3}s`:"";r.error(`op:${t} failed, message=${i.message}, code=${i.code}${i.subCode?`, subCode=${i.subCode}`:""} ${e}`),i&&r.error(`op:${t} failed, message=${i.message}, code=${i.code}, subCode=${i.subCode}, resultCategories=${i.resultCategories}, time elapsed=${e}`)}}catch(i){}}function ye(e){try{const t=Reflect.getMetadata(ce,e);if(t)return e[t]}catch(e){}}var Ce="object",Te="undefined",Ee="prototype",be=Object,_e=be[Ee];function Ie(e,t){return e||t}function we(e,t){return e[t]}var Ae,Pe=void 0,Re=null,Me="function",De="object",ke="prototype",Oe="__proto__",Ne="undefined",Le="constructor",xe="Symbol",Fe="length",Ue="name",Be="call",Ve="toString",He=Ie(Object),$e=we(He,ke),je=Ie(String),Ge=we(je,ke),qe=Ie(Math),ze=Ie(Array),We=we(ze,ke),Ke=we(We,"slice");function Je(e,t){try{return{v:e.apply(this,t)}}catch(e){return{e}}}function Ye(e){return function(t){return typeof t===e}}function Qe(e){var t="[object "+e+"]";return function(e){return!(!e||function(e){return $e[Ve].call(e)}(e)!==t)}}function Ze(e){return typeof e===Ne||e===Ne}function Xe(e){return e===Re||Ze(e)}function et(e){return!!e||e!==Pe}var tt=Ye("string"),it=Ye(Me);function nt(e){return!(!e&&Xe(e)||!e||typeof e!==De)}var rt=we(ze,"isArray"),st=Qe("Date"),at=Ye("number"),ot=Ye("boolean"),lt=Qe("Error");function ct(e){return!!(e&&e.then&&it(e.then))}function dt(e){return!(!e||function(e,t){var i=Je(e);return i.e?t:i.v}((function(){return!(e&&0+e)}),!e))}var ut=we(He,"getOwnPropertyDescriptor");function ht(e,t){return!!e&&$e.hasOwnProperty[Be](e,t)}var gt=Ie(we(He,"hasOwn"),(function(e,t){return ht(e,t)||!!ut(e,t)}));function pt(e,t,i){if(e&&nt(e))for(var n in e)if(gt(e,n)&&-1===t[Be](i||e,n,e[n]))break}var mt={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function ft(e){var t={};if(t[mt.c]=!0,t[mt.e]=!0,e.l){t.get=function(){return e.l.v};var i=ut(e.l,"v");i&&i.set&&(t.set=function(t){e.l.v=t})}return pt(e,(function(e,i){t[mt[e]]=function(e){return!et(e)}(i)?t[mt[e]]:i})),t}var vt=we(He,"defineProperty"),St=we(He,"defineProperties");function yt(e,t,i){return vt(e,t,ft(i))}function Ct(e,t,i,n,r){var s={};return pt(e,(function(e,n){Tt(s,e,t?n:e,r),Tt(s,n,i?n:e,r)})),n?n(s):s}function Tt(e,t,i,n){vt(e,t,{value:i,enumerable:!0,writable:!!n})}var Et=Ie(je);function bt(e,t){var i="",n=$e[Ve][Be](e);"[object Error]"===n&&(e={stack:Et(e.stack),message:Et(e.message),name:Et(e.name)});try{i=((i=JSON.stringify(e,Re,t?"number"==typeof t?t:4:Pe))?i.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: "):Re)||Et(e)}catch(e){i=" - "+bt(e,t)}return n+": "+i}function _t(e){throw new Error(e)}function It(e){throw new TypeError(e)}var wt=we(He,"freeze"),At=we(He,"assign"),Pt=we(He,"keys");function Rt(e){return wt&&pt(e,(function(e,t){(rt(t)||nt(t))&&Rt(t)})),Dt(e)}var Mt,Dt=Ie(wt,(function(e){return e})),kt=Ie(we(He,"getPrototypeOf"),(function(e){return e[Oe]||Re})),Ot=Ct({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},0,0,Dt),Nt="__tsUtils$gblCfg";function Lt(){var e;return typeof globalThis!==Ne&&(e=globalThis),e||typeof self===Ne||(e=self),e||typeof window===Ne||(e=window),e||typeof r.g===Ne||(e=r.g),e}function xt(){if(!Mt){var e=Je(Lt).v||{};Mt=e[Nt]=e[Nt]||{}}return Mt}var Ft=Ut;function Ut(e,t,i){var n=t?t[e]:Re;return function(t){var r=(t?t[e]:Re)||n;if(r||i){var s=arguments;return(r||i).apply(t,r?Ke[Be](s,1):s)}It('"'+Et(e)+'" not defined for '+bt(t))}}var Bt=we(qe,"max"),Vt=Ft("slice",Ge),Ht=Ft("substring",Ge),$t=Ut("substr",Ge,(function(e,t,i){return Xe(e)&&It("Invalid "+bt(e)),i<0?"":((t=t||0)<0&&(t=Bt(t+e[Fe],0)),Ze(i)?Vt(e,t):Vt(e,t,t+i))}));function jt(e,t){return Ht(e,0,t)}var Gt,qt,zt,Wt="_urid";function Kt(e){return{description:Et(e),toString:function(){return xe+"("+e+")"},_polyfill:!0}}function Jt(e){var t=function(){if(!Gt){var e=xt();Gt=e.gblSym=e.gblSym||{k:{},s:{}}}return Gt}();if(!gt(t.k,e)){var i=Kt(e),n=Pt(t.s).length;i[Wt]=function(){return n+"_"+i[Ve]()},t.k[e]=i,t.s[i[Wt]()]=Et(e)}return t.k[e]}function Yt(){zt=xt()}function Qt(e){return vt({toJSON:function(){return e}},"v",{value:e})}var Zt,Xt="window";function ei(e,t){var i;return function(){return!zt&&Yt(),i&&!zt.lzy||(i=Qt(Je(e,t).v)),i.v}}function ti(e){return!zt&&Yt(),Zt&&!1!==e&&!zt.lzy||(Zt=Qt(Je(Lt).v||Re)),Zt.v}function ii(e,t){var i;if((i=Zt&&!1!==t?Zt.v:ti(t))&&i[e])return i[e];if(e===Xt)try{return window}catch(e){}return Re}function ni(){return!!oi()}var ri,si,ai,oi=ei(ii,["document"]),li=ei(ii,[Xt]),ci=ei(ii,["navigator"]),di=ei((function(){return!!Je((function(){return process&&(process.versions||{}).node})).v}));function ui(){return ri=Qt(Je(ii,[xe]).v)}function hi(e){var t=(zt.lzy?0:ri)||ui();return t.v?t.v[e]:Pe}function gi(e,t){var i=Ot[e];!zt&&Yt();var n=(zt.lzy?0:ri)||ui();return n.v?n.v[i||e]:t?Pe:function(e){var t;!qt&&(qt={});var i=Ot[e];return i&&(t=qt[i]=qt[i]||Kt(xe+"."+i)),t}(e)}function pi(e,t){!zt&&Yt();var i=(zt.lzy?0:ri)||ui();return i.v?i.v(e):t?Re:Kt(e)}function mi(e){return!zt&&Yt(),((si=(zt.lzy?0:si)||Qt(Je(hi,["for"]).v)).v||Jt)(e)}function fi(e){return!!e&&it(e.next)}function vi(e){return!function(e){return e===Re||!et(e)}(e)&&it(e[gi(3)])}function Si(e,t,i){if(e&&(fi(e)||(!ai&&(ai=Qt(gi(3))),e=e[ai.v]?e[ai.v]():Re),fi(e))){var n=Pe,r=Pe;try{for(var s=0;!(r=e.next()).done&&-1!==t[Be](i||e,r.value,s,e);)s++}catch(t){n={e:t},e.throw&&(r=Re,e.throw(n))}finally{try{r&&!r.done&&e.return&&e.return(r)}finally{if(n)throw n.e}}}}function yi(e,t,i){return e.apply(t,i)}function Ci(e,t){return!Ze(t)&&e&&(rt(t)?yi(e.push,e,t):fi(t)||vi(t)?Si(t,(function(t){e.push(t)})):e.push(t)),e}function Ti(e,t,i){if(e)for(var n=e[Fe]>>>0,r=0;r<n&&(!(r in e)||-1!==t[Be](i||e,e[r],r,e));r++);}var Ei=Ft("indexOf",We);function bi(e,t,i){return((e?e.slice:Re)||Ke).apply(e,Ke[Be](arguments,1))}var _i,Ii=Ie(we(He,"create"),(function(e){if(!e)return{};var t=typeof e;function i(){}return t!==De&&t!==Me&&It("Prototype must be an Object or function: "+bt(e)),i[ke]=e,new i}));function wi(e,t){var i=He.setPrototypeOf||function(e,t){var i;!_i&&(_i=Qt(((i={})[Oe]=[],i instanceof Array))),_i.v?e[Oe]=t:pt(t,(function(t,i){return e[t]=i}))};return i(e,t)}function Ai(e,t){t&&(e[Ue]=t)}function Pi(e,t,i){var n=i||Error,r=n[ke][Ue],s=Error.captureStackTrace;return function(e,t,i){function n(){this[Le]=t,Je(yt,[this,Ue,{v:e,c:!0,e:!1}])}return Je(yt,[t,Ue,{v:e,c:!0,e:!1}]),(t=wi(t,i))[ke]=i===Re?Ii(i):(n[ke]=i[ke],new n),t}(e,(function(){var i=this,a=arguments;try{Je(Ai,[n,e]);var o=yi(n,i,Ke[Be](a))||i;if(o!==i){var l=kt(i);l!==kt(o)&&wi(o,l)}return s&&s(o,i[Le]),t&&t(o,a),o}finally{Je(Ai,[n,r])}}),n)}function Ri(){return(Date.now||Mi)()}function Mi(){return(new Date).getTime()}var Di,ki,Oi,Ni=Ut("trim",Ge,function(e){return function(t){return Xe(t)&&It("strTrim called ["+bt(t)+"]"),t&&t.replace&&(t=t.replace(e,"")),t}}(/^\s+|(?=\s)\s+$/g));function Li(e){if(!e||typeof e!==De)return!1;Oi||(Oi=!li()||li());var t=!1;if(e!==Oi){ki||(Di=Function[ke][Ve],ki=Di[Be](He));try{var i=kt(e);(t=!i)||(ht(i,Le)&&(i=i[Le]),t=!(!i||typeof i!==Me||Di[Be](i)!==ki))}catch(e){}}return t}function xi(e){return e.value&&Vi(e),!0}var Fi=[function(e){var t=e.value;if(rt(t)){var i=e.result=[];return i.length=t.length,e.copyTo(i,t),!0}return!1},Vi,function(e){return e.type===Me},function(e){var t=e.value;return!!st(t)&&(e.result=new Date(t.getTime()),!0)}];function Ui(e,t,i,n){var r=i.handler,s=i.path?n?i.path.concat(n):i.path:[],a={handler:i.handler,src:i.src,path:s},o=typeof t,l=!1,c=t===Re;c||(t&&o===De?l=Li(t):c=function(e){return!Ae&&(Ae=["string","number","boolean",Ne,"symbol","bigint"]),!(e===De||-1===Ae.indexOf(e))}(o));var d={type:o,isPrim:c,isPlain:l,value:t,result:t,path:s,origin:i.src,copy:function(t,n){return Ui(e,t,n?a:i,n)},copyTo:function(t,i){return Bi(e,t,i,a)}};return d.isPrim?r&&r[Be](i,d)?d.result:t:function(e,t,i,n){var r;return Ti(e,(function(e){if(e.k===t)return r=e,-1})),r||(r={k:t,v:t},e.push(r),n(r)),r.v}(e,t,0,(function(e){yt(d,"result",{g:function(){return e.v},s:function(t){e.v=t}});for(var t=0,n=r;!(n||(t<Fi.length?Fi[t++]:xi))[Be](i,d);)n=Re}))}function Bi(e,t,i,n){if(!Xe(i))for(var r in i)t[r]=Ui(e,i[r],n,r);return t}function Vi(e){var t=e.value;if(t&&e.isPlain){var i=e.result={};return e.copyTo(i,t),!0}return!1}function Hi(e,t,i,n,r,s,a){return function(e,t){return Ti(t,(function(t){!function(e,t){Bi([],e,t,{handler:void 0,src:t,path:[]})}(e,t)})),e}(function(e){return Ui([],e,{handler:void 0,src:e})}(e)||{},Ke[Be](arguments))}var $i,ji=function(e){return function(t){return t[e]}}(Fe);function Gi(){var e=(!zt&&Yt(),$i&&!zt.lzy||($i=Qt(Je(ii,["performance"]).v)),$i.v);return e&&e.now?e.now():Ri()}var qi=Ut("endsWith",Ge,(function(e,t,i){tt(e)||It("'"+bt(e)+"' is not a string");var n=tt(t)?t:Et(t),r=!Ze(i)&&i<e[Fe]?i:e[Fe];return Ht(e,r-n[Fe],r)===n})),zi=Ft("indexOf",Ge),Wi=Ut("startsWith",Ge,(function(e,t,i){tt(e)||It("'"+bt(e)+"' is not a string");var n=tt(t)?t:Et(t),r=i>0?i:0;return Ht(e,r,r+n[Fe])===n})),Ki="ref",Ji="unref",Yi="hasRef";function Qi(e,t,i){var n=rt(t),r=n?t.length:0,s=(r>0?t[0]:n?Pe:t)||setTimeout,a=(r>1?t[1]:Pe)||clearTimeout,o=i[0];i[0]=function(){l.dn(),yi(o,Pe,Ke[Be](arguments))};var l=function(e,t){var i,n=!0,r=e?t(Re):Re;function s(){return n=!1,r&&r[Ji]&&r[Ji](),i}function o(){r&&function(e){yi(a,Pe,[e])}(r),r=Re}function l(){return r=t(r),n||s(),i}return(i={cancel:o,refresh:l})[Yi]=function(){return r&&r[Yi]?r[Yi]():n},i[Ki]=function(){return n=!0,r&&r[Ki]&&r[Ki](),i},i[Ji]=s,{h:i=vt(i,"enabled",{get:function(){return!!r},set:function(e){!e&&r&&o(),e&&!r&&l()}}),dn:function(){r=Re}}}(e,(function(e){if(e){if(e.refresh)return e.refresh(),e;yi(a,Pe,[e])}return yi(s,Pe,i)}));return l.h}function Zi(e,t){return Qi(!0,Pe,Ke[Be](arguments))}(ti()||{}).Symbol,(ti()||{}).Reflect;var Xi,en=function(e,t){return en=be.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},en(e,t)};function tn(e,t){function i(){this.constructor=e}"function"!=typeof t&&null!==t&&It("Class extends value "+String(t)+" is not a constructor or null"),en(e,t),e[Ee]=null===t?Ii(t):(i[Ee]=t[Ee],new i)}function nn(e,t){for(var i=0,n=t.length,r=e.length;i<n;i++,r++)e[r]=t[i];return e}var rn="constructor",sn="prototype",an="function",on="_dynInstFuncs",ln="_isDynProxy",cn="_dynClass",dn="_dynInstChk",un=dn,hn="_dfOpts",gn="_unknown_",pn="__proto__",mn="_dyn"+pn,fn="__dynProto$Gbl",vn="_dynInstProto",Sn="useBaseInst",yn="setInstFuncs",Cn=Object,Tn=Cn.getPrototypeOf,En=Cn.getOwnPropertyNames,bn=ti(),_n=bn[fn]||(bn[fn]={o:(Xi={},Xi[yn]=!0,Xi[Sn]=!0,Xi),n:1e3});function In(e){return e&&(e===Cn[sn]||e===Array[sn])}function wn(e){return In(e)||e===Function[sn]}function An(e){var t;if(e){if(Tn)return Tn(e);var i=e[pn]||e[sn]||(e[rn]?e[rn][sn]:null);t=e[mn]||i,ht(e,mn)||(delete e[vn],t=e[mn]=e[vn]||e[mn],e[vn]=i)}return t}function Pn(e,t){var i=[];if(En)i=En(e);else for(var n in e)"string"==typeof n&&ht(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function Rn(e,t,i){return t!==rn&&typeof e[t]===an&&(i||ht(e,t))&&t!==pn&&t!==sn}function Mn(e){It("DynamicProto: "+e)}function Dn(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function kn(e,t,i,n,r){if(!In(e)){var s=i[on]=i[on]||Ii(null);if(!In(s)){var a=s[t]=s[t]||Ii(null);!1!==s[un]&&(s[un]=!!r),In(a)||Pn(i,(function(t){Rn(i,t,!1)&&i[t]!==n[t]&&(a[t]=i[t],delete i[t],(!ht(e,t)||e[t]&&!e[t][ln])&&(e[t]=function(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&ht(i,cn)){var s=e[on]||Ii(null);if((r=(s[i[cn]]||Ii(null))[t])||Mn("Missing ["+t+"] "+an),!r[dn]&&!1!==s[un]){for(var a=!ht(e,t),o=An(e),l=[];a&&o&&!wn(o)&&!Dn(l,o);){var c=o[t];if(c){a=c===n;break}l.push(o),o=An(o)}try{a&&(e[t]=r),r[dn]=1}catch(e){s[un]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=An(t)[e]),typeof n!==an&&Mn("["+e+"] is not a "+an),n}(t,e,i)).apply(this,arguments)};return i[ln]=1,i}(e,t)))}))}}}function On(e,t){return ht(e,sn)?e.name||t||gn:((e||{})[rn]||{}).name||t||gn}function Nn(e,t,i,n){ht(e,sn)||Mn("theClass is an invalid class definition.");var r=e[sn];(function(e,t){if(Tn){for(var i=[],n=An(t);n&&!wn(n)&&!Dn(i,n);){if(n===e)return!0;i.push(n),n=An(n)}return!1}return!0})(r,t)||Mn("["+On(e)+"] not in hierarchy of ["+On(t)+"]");var s=null;ht(r,cn)?s=r[cn]:(s="_dynCls$"+On(e,"_")+"$"+_n.n,_n.n++,r[cn]=s);var a=Nn[hn],o=!!a[Sn];o&&n&&void 0!==n[Sn]&&(o=!!n[Sn]);var l=function(e){var t=Ii(null);return Pn(e,(function(i){!t[i]&&Rn(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[ln]&&n){var s=e[on]||{};!1!==s[un]&&(r=(s[t[cn]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var s=Ii(null);Pn(i,(function(e){s[e]=r(t,i,e)}));for(var a=An(e),o=[];a&&!wn(a)&&!Dn(o,a);)Pn(a,(function(e){!s[e]&&Rn(a,e,!Tn)&&(s[e]=r(t,a,e))})),o.push(a),a=An(a);return s}(r,t,l,o));var c=!!Tn&&!!a[yn];c&&n&&(c=!!n[yn]),kn(r,s,t,l,!1!==c)}Nn[hn]=_n.o;var Ln,xn=function(e){return Ct(e,1,0,Dt)},Fn=xn({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),Un=(xn({Unknown:0,NonRetryableStatus:1,CleanStorage:2,MaxInStorageTimeExceeded:3}),xn({NONE:0,PENDING:3,INACTIVE:1,ACTIVE:2})),Bn="toLowerCase",Vn="blkVal",Hn="length",$n="rdOnly",jn="notify",Gn="warnToConsole",qn="throwInternal",zn="setDf",Wn="watch",Kn="logger",Jn="apply",Yn="push",Qn="splice",Zn="hdlr",Xn="cancel",er="initialize",tr="identifier",ir="removeNotificationListener",nr="addNotificationListener",rr="isInitialized",sr="instrumentationKey",ar="INACTIVE",or="value",lr="getNotifyMgr",cr="getPlugin",dr="name",ur="iKey",hr="time",gr="processNext",pr="getProcessTelContext",mr="pollInternalLogs",fr="enabled",vr="stopPollingInternalLogs",Sr="unload",yr="onComplete",Cr="version",Tr="loggingLevelConsole",Er="createNew",br="teardown",_r="messageId",Ir="message",wr="isAsync",Ar="diagLog",Pr="_doTeardown",Rr="update",Mr="getNext",Dr="setNextPlugin",kr="protocol",Or="userAgent",Nr="split",Lr="nodeType",xr="replace",Fr="type",Ur="handler",Br="status",Vr="getResponseHeader",Hr="getAllResponseHeaders",$r="isChildEvt",jr="data",Gr="getCtx",qr="setCtx",zr="complete",Wr="urlString",Kr="sendPOST",Jr="headers",Yr="timeout",Qr="setRequestHeader",Zr="traceId",Xr="spanId",es="traceFlags",ts="Promise",is="rejected";function ns(e,t){return rs(e,(function(e){return t?t({status:"fulfilled",rejected:!1,value:e}):e}),(function(e){return t?t({status:is,rejected:!0,reason:e}):e}))}function rs(e,t,i,n){var r=e;try{if(ct(e))(t||i)&&(r=e.then(t,i));else try{t&&(r=t(e))}catch(e){if(!i)throw e;r=i(e)}}finally{n&&function(e,t){t&&(ct(e)?e.finally?e.finally(t):e.then((function(e){return t(),e}),(function(e){throw t(),e})):t())}(r,n)}return r}var ss,as=["pending","resolving","resolved",is],os="dispatchEvent";function ls(e){var t;return e&&e.createEvent&&(t=e.createEvent("Event")),!!t&&t.initEvent}var cs,ds="unhandledRejection",us=ds.toLowerCase(),hs=[],gs=0;function ps(e){return it(e)?e.toString():bt(e)}function ms(e,t,i){var n,r,s=bi(arguments,3),a=0,o=!1,l=[],c=gs++,d=!1,u=null;function h(t,i){try{return hs.push(c),d=!0,u&&u.cancel(),u=null,e((function(e,r){l.push((function(){try{var s=2===a?t:i,o=Ze(s)?n:it(s)?s(n):s;ct(o)?o.then(e,r):s?e(o):3===a?r(o):e(o)}catch(e){r(e)}})),o&&p()}),s)}finally{hs.pop()}}function g(){return as[a]}function p(){if(l.length>0){var e=l.slice();l=[],d=!0,u&&u.cancel(),u=null,t(e)}}function m(e,t){return function(i){if(a===t){if(2===e&&ct(i))return a=1,void i.then(m(2,1),m(3,1));a=e,o=!0,n=i,p(),d||3!==e||u||(u=Zi(f,10))}}}function f(){if(!d)if(d=!0,di())process.emit(ds,n,r);else{var e=li()||ti();!cs&&(cs=Qt(Je(ii,[ts+"RejectionEvent"]).v)),function(e,t,i,n){var r=oi();!ss&&(ss=Qt(!!Je(ls,[r]).v));var s=ss.v?r.createEvent("Event"):n?new Event(t):{};if(i&&i(s),ss.v&&s.initEvent(t,!1,!0),s&&e[os])e[os](s);else{var a=e["on"+t];if(a)a(s);else{var o=ii("console");o&&(o.error||o.log)(t,bt(s))}}}(e,us,(function(e){return yt(e,"promise",{g:function(){return r}}),e.reason=n,e}),!!cs.v)}}return vt(r={then:h,catch:function(e){return h(void 0,e)},finally:function(e){var t=e,i=e;return it(e)&&(t=function(t){return e&&e(),t},i=function(t){throw e&&e(),t}),h(t,i)}},"state",{get:g}),!zt&&Yt(),!!((zt.lzy?0:ri)||ui()).v&&(r[gi(11)]="IPromise"),r.toString=function(){return"IPromise "+g()+(o?" - "+ps(n):"")},function(){it(i)||It(ts+": executor is not a function - "+ps(i));var e=m(3,0);try{i.call(r,m(2,0),e)}catch(t){e(t)}}(),r}function fs(e){return function(t){var i=bi(arguments,1);return e((function(e,i){try{var n=[],r=1;Si(t,(function(t,s){t&&(r++,rs(t,(function(t){n[s]=t,0==--r&&e(n)}),i))})),0==--r&&e(n)}catch(e){i(e)}}),i)}}function vs(e,t){return ms(vs,function(e){var t=at(e)?e:0;return function(e){Zi((function(){!function(e){Ti(e,(function(e){try{e()}catch(e){}}))}(e)}),t)}}(t),e,t)}var Ss,ys,Cs,Ts=fs(vs),Es=function(e){return function(t){var i=bi(arguments,1);return ct(t)?t:e((function(e){e(t)}),i)}}(vs),bs=function(e){return function(t){var i=bi(arguments,1);return e((function(e,i){i(t)}),i)}}(vs);function _s(e,t){!Ss&&(Ss=Qt(Je(ii,[ts]).v||null));var i=Ss.v;if(!i)return vs(e);it(e)||It(ts+": executor is not a function - "+bt(e));var n=0,r=new i((function(t,i){e((function(e){n=2,t(e)}),(function(e){n=3,i(e)}))}));return vt(r,"state",{get:function(){return as[n]}}),r}function Is(e,t){return!ys&&(ys=Qt(_s)),ys.v.call(this,e,t)}var ws=fs(Is);var As,Ps,Rs="reject",Ms="Rejected",Ds=0,ks={};function Os(){}function Ns(e,t,i){!ks[e]&&(ks[e]=Pi(e));var n=Ri();return new ks[e]("Task [".concat(t.id,"] ").concat(i||"","- ").concat(t.st?"Running":"Waiting",": ").concat(function(e,t){return(e-t||"0")+" ms"}(n,t.st||t.cr)))}function Ls(e,t){var i=Ri()-t;Ti(e,(function(e){(e&&!e.rj&&e.st&&e.st<i||!e.st&&e.cr&&e.cr<i)&&e&&e[Rs](e.rj||Ns("Aborted",e,"Stale "))}))}function xs(e,t){var i=Ei(e,t);-1!==i&&e.splice(i,1)}function Fs(e,t){var i,n,r=[],s=[],a=6e5,o=a/10,l=0,c=(t?t+".":"")+Ds++;e=e||Is;var d=function(){var e=ji(r)+ji(s)>0;a>0&&(n||(n=Zi((function(){Ls(r,a),Ls(s,a),n&&(n.enabled=ji(r)+ji(s)>0)}),o)).unref(),n&&(n.enabled=e))},u=function(e,t){return e.st=Ri(),r.push(e),d(),function(i,n){var r=function(t){e.rj=e.rj||t||Ns(Ms,e),e[Rs]=Os,g(e),i=null,n&&n(t),n=null},s=e.id;if(e.rj)r(e.rj);else{e[Rs]=r;try{var a=t(s);e.to&&ct(a)&&(e.t=Zi((function(){r(Ns("Timeout",e))}),e.to)),rs(a,(function(t){g(e);try{i&&i(t)}catch(e){n&&n(e)}n=null,i=null}),r)}catch(e){r(e)}}}},h=function(t,i,n){return s.push(t),d(),e((function(e,r){ns(i.p,(function(){xs(s,t),u(t,n)(e,r)}))}))},g=function(e){xs(r,e),e.t&&e.t.cancel(),e.t=null,i&&i===e&&(i=null,ji(r)+ji(s)===0&&(n&&n.cancel(),n=null))},p={idle:!0,queue:function(t,n,r){var s,a=c+"."+l++;n&&(a+="-("+n+")");var o=((s={id:a,cr:Ri(),to:r})[Rs]=function(e){o.rj=e||Ns(Ms,o),o[Rs]=Os},s);return o.p=i?h(o,i,t):e(u(o,t)),i=o,o.p},setStaleTimeout:function(e,t){n&&n.cancel(),n=null,a=e,o=t||e/10,d()}};return yt(p,"idle",{g:function(){return ji(r)+ji(s)===0}}),function(e,t,i){Ps=Ps||{toString:function(){return"[[SchedulerState]]"}},vt(e,As=As||{toString:function(){return"[[SchedulerName]]"}},{get:function(){return c}}),vt(e,Ps,{get:i})}(p,0,(function(){return{l:i,r,w:s}})),p}gi(11);var Us=void 0,Bs="",Vs="channels",Hs="core",$s="createPerfMgr",js="disabled",Gs="extensionConfig",qs="extensions",zs="processTelemetry",Ws="priority",Ks="eventsSent",Js="eventsDiscarded",Ys="eventsSendRequest",Qs="perfEvent",Zs="offlineEventsStored",Xs="offlineBatchSent",ea="offlineBatchDrop",ta="getPerfMgr",ia="domain",na="path",ra=/-([a-z])/g,sa=/([^\w\d_$])/g,aa=/^(\d+[\w\d_$])/;function oa(e){return!Xe(e)}function la(e){var t=e;return t&&tt(t)&&(t=(t=(t=t[xr](ra,(function(e,t){return t.toUpperCase()})))[xr](sa,"_"))[xr](aa,(function(e,t){return"_"+t}))),t}function ca(e,t){return!(!e||!t)&&-1!==zi(e,t)}function da(e){return e&&e.toISOString()||""}function ua(e){return lt(e)?e[dr]:Bs}function ha(e,t,i,n,r){var s=i;return e&&((s=e[t])===i||r&&!r(s)||n&&!n(i)||(s=i,e[t]=s)),s}function ga(e,t,i,n,r){e&&t&&i&&(!1!==r||Ze(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return it(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][Jn](n,e)}}(i,n))}function pa(e,t,i,n){return e&&t&&nt(e)&&rt(i)&&Ti(i,(function(i){tt(i)&&ga(e,i,t,i,n)})),e}function ma(e){return e&&At&&(e=be(At({},e))),e}function fa(e){try{return e.responseText}catch(e){}return null}function va(e,t){return e?"XMLHttpRequest,Status:"+e[Br]+",Response:"+fa(e)||0:t}function Sa(e,t){return t&&(at(t)?e=[t].concat(e):rt(t)&&(e=t.concat(e))),e}var ya="withCredentials";function Ca(e,t,i){if(!e[i]&&t&&t[Vr]){var n=t[Vr](i);n&&(e[i]=Ni(n))}return e}function Ta(e,t){var i={};return e[Hr]?i=function(e){var t={};return tt(e)&&Ti(Ni(e)[Nr](/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=Ni(e.substring(0,i))[Bn](),r=Ni(e.substring(i+1));t[n]=r}else t[Ni(e)]=1}})),t}(e[Hr]()):t&&(i=Ca(i,e,"time-delta-millis"),i=Ca(i,e,"kill-duration"),i=Ca(i,e,"kill-duration-seconds")),i}var Ea="JSON",ba="XMLHttpRequest",_a=null,Ia=null,wa=null,Aa=null;function Pa(e,t){var i=!1;if(e){try{if(!(i=t in e)){var n=e[Ee];n&&(i=t in n)}}catch(e){}if(!i)try{i=!Ze((new e)[t])}catch(e){}}return i}function Ra(e){return typeof location===Ce&&location?location:ii("location")}function Ma(){return Boolean(typeof JSON===Ce&&JSON||null!==ii(Ea))}function Da(){var e=ci();return!(!e||!e.product)&&"ReactNative"===e.product}function ka(){var e=ci();if(e&&(e[Or]!==Ia||null===_a)){var t=((Ia=e[Or])||Bs)[Bn]();_a=ca(t,"msie")||ca(t,"trident/")}return _a}function Oa(e){return null!==Aa&&!1!==e||(Aa=!!ci()&&Boolean(ci().sendBeacon)),Aa}function Na(e){var t=!1;try{t=!!ii("fetch");var i=ii("Request");t&&e&&i&&(t=Pa(i,"keepalive"))}catch(e){}return t}function La(){var e=!1;try{e=!!ii(ba)}catch(e){}return e}var xa=4294967296,Fa=4294967295,Ua=123456789,Ba=987654321,Va=!1,Ha=Ua,$a=Ba;function ja(e){var t=0,i=ii("crypto")||ii("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&Fa),0===t&&ka()&&(Va||function(){try{var e=2147483647&Ri();!function(e){e<0&&(e>>>=0),Ha=Ua+e&Fa,$a=Ba-e&Fa,Va=!0}((Math.random()*xa^e)+e)}catch(e){}}(),t=function(){var e=(($a=36969*(65535&$a)+($a>>16)&Fa)<<16)+(65535&(Ha=18e3*(65535&Ha)+(Ha>>16)&Fa))>>>0&Fa;return e>>>=0}()&Fa),0===t&&(t=Math.floor(xa*Math.random()|0)),e||(t>>>=0),t}function Ga(e){void 0===e&&(e=22);for(var t=ja()>>>0,i=0,n=Bs;n[Hn]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(ja()<<2&4294967295|3&t)>>>0,i=0);return n}var qa="3.3.2",za="."+Ga(6),Wa=0;function Ka(e){return 1===e[Lr]||9===e[Lr]||!+e[Lr]}function Ja(e,t){return void 0===t&&(t=!1),la(e+Wa+++(t?"."+qa:Bs)+za)}function Ya(e){var t={id:Ja("_aiData-"+(e||Bs)+"."+qa),accept:function(e){return Ka(e)},get:function(e,i,n,r){var s=e[t.id];return s?s[la(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{Ka(t)&&yt(t,e.id,{e:!1,v:i})}catch(e){}}return i}(t,e))[la(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return t}function Qa(e){return e&&nt(e)&&(e.isVal||e.fb||gt(e,"v")||gt(e,"mrg")||gt(e,"ref")||e.set)}function Za(e,t,i){var n,r=i.dfVal||et;if(t&&i.fb){var s=i.fb;rt(s)||(s=[s]);for(var a=0;a<s[Hn];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,Et(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function Xa(e,t,i){var n,r=i;return i&&Qa(i)&&(r=Za(e,t,i)),r&&(Qa(r)&&(r=Xa(e,t,r)),rt(r)?(n=[])[Hn]=r[Hn]:Li(r)&&(n={}),n&&(pt(r,(function(i,r){r&&Qa(r)&&(r=Xa(e,t,r)),n[i]=r})),r=n)),r}function eo(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;Qa(h)?(r=h.isVal,s=h.set,c=h[$n],d=h[Vn],o=h.mrg,!(l=h.ref)&&Ze(l)&&(l=!!o),a=Za(e,t,h)):a=n,d&&e[Vn](t,i);var g=!0,p=t[i];!p&&Xe(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?Xa(e,t,a):a:(Li(u)||rt(a))&&o&&a&&(Li(a)||rt(a))&&pt(a,(function(t,i){eo(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[$n](t,i)}var to=mi("[[ai_dynCfg_1]]"),io=mi("[[ai_blkDynCfg_1]]"),no=mi("[[ai_frcDynCfg_1]]");function ro(e){var t;return e&&(rt(e)?(t=[])[Hn]=e[Hn]:Li(e)&&(t={}),t)?(pt(e,(function(e,i){t[e]=ro(i)})),t):e}function so(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[no])||i[io]||(n=Li(i)||rt(i))),n}function ao(e){It("InvalidAccess:"+e)}var oo=["push","pop","shift","unshift","splice"],lo=function(e,t,i,n){e&&e[qn](3,108,"".concat(i," [").concat(t,"] failed - ")+bt(n))};function co(e,t){var i=ut(e,t);return i&&i.get}function uo(e,t,i,n){if(t){var r=co(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===Ei(r.h,t)&&r.h[Yn](t),e.trk(t,r))},clr:function(e){var t=Ei(r.h,e);-1!==t&&r.h[Qn](t,1)}},s=!0,a=!1;function o(){s&&(a=a||so(o,e,n),n&&!n[to]&&a&&(n=go(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},yt(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&ao("["+i+"] is read-only:"+bt(t)),s&&(a=a||so(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){pt(n,(function(e){n[e]=l?l[e]:Us}));try{pt(l,(function(t,i){uo(e,n,t,i)})),l=n}catch(t){lo((e.hdlr||{})[Kn],i,"Assigning",t),a=!1}}else n&&n[to]&&pt(n,(function(t){var i=co(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&so(o,e,l);!c&&d&&(l=go(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function ho(e,t,i,n){if(t){var r=co(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(Li(e)||rt(e)))try{e[io]=!0}catch(e){}}(t)}catch(t){lo((e.hdlr||{})[Kn],i,"Blocking",t)}try{uo(e,t,i,t[i]),r=co(t,i)}catch(t){lo((e.hdlr||{})[Kn],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function go(e,t,i,n){try{pt(t,(function(i,n){uo(e,t,i,n)})),t[to]||(vt(t,to,{get:function(){return e[Zn]}}),function(e,t,i){rt(t)&&Ti(oo,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[Jn](this,n);return go(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){lo((e.hdlr||{})[Kn],i,n,t)}return t}var po="[[ai_",mo="]]";function fo(e,t,i){var n,r=function(e){if(e){var t=e[to]||e;if(t.cfg&&(t.cfg===e||t.cfg[to]===t))return t}return null}(t);if(r)return r;var s,a=Ja("dyncfg",!0),o=t&&!1!==i?t:ro(t),l=((n={uid:null,cfg:o})[Kn]=e,n[jn]=function(){s[jn]()},n.set=function(t,i,n){try{t=uo(s,t,i,n)}catch(t){lo(e,i,"Setting value",t)}return t[i]},n[zn]=function(e,t){return t&&pt(t,(function(t,i){eo(l,e,t,i)})),e},n[Wn]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return yt(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return ho(s,e,t,(i={},i[0]=!0,i))[t]},n[$n]=function(e,t){var i;return ho(s,e,t,(i={},i[1]=!0,i))[t]},n[Vn]=function(e,t){var i;return ho(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Ze(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return yt(l,"uid",{c:!1,e:!1,w:!1,v:a}),go(s=function(e){var t,i,n=pi(po+"get"+e.uid+mo),r=pi(po+"ro"+e.uid+mo),s=pi(po+"rf"+e.uid+mo),a=pi(po+"blkVal"+e.uid+mo),o=pi(po+"dtl"+e.uid+mo),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(Ti(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[zn].bind(e),ref:e.ref.bind(e),rdOnly:e[$n].bind(e)})}catch(t){var s=e[Kn];throw s&&s[qn](1,107,bt(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c[Xn](),c=null;var t=[];if(Ti(e,(function(e){if(e&&(e[o]&&(Ti(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[Yn](e)}})),l)try{u()}catch(e){t[Yn](e)}t[Hn]>0&&function(e,t){Ln||(Ln=Pi("AggregationError",(function(e,t){t[Hn]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw Ti(t,(function(e,t){i+="\n".concat(t," > ").concat(bt(e))})),new Ln(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[Vn]=a,t[Zn]=e,t.add=function(e){if(e&&e.h[Hn]>0){l||(l=[]),c||(c=Zi((function(){c=null,u()}),0));for(var t=0;t<e.h[Hn];t++){var i=e.h[t];i&&-1===Ei(l,i)&&l[Yn](i)}}},t[jn]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===Ei(i,t)&&i[Yn](t)}},i=t}(l),o,"config","Creating"),l}function vo(e,t,i,n){var r=fo(i,e||{},n);return t&&r[zn](r.cfg,t),r}function So(e,t,i){var n=e[to]||e;return!n.cfg||n.cfg!==e&&n.cfg[to]!==n?(function(e,t){e?(e[Gn](t),e[qn](2,108,t)):ao(t)}(i,"Not dynamic - "+bt(e)),vo(e,null,i)[Wn](t)):n[Wn](t)}function yo(e,t){if(e&&e[Sr])return e[Sr](t)}function Co(e,t,i){var n;return i||(n=Is((function(e){i=e}))),e&&ji(e)>0?ns(yo(e[0],t),(function(){Co(bi(e,1),t,i)})):i(),n}var To,Eo,bo="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",_o=[Ks,Js,Ys,Qs],Io=null;function wo(e,t){return function(){var i=arguments,n=Ao(t);if(n){var r=n.listener;r&&r[e]&&r[e][Jn](r,i)}}}function Ao(e){var t=Io;return t||!0===e.disableDbgExt||(t=Io||function(){var e=ii("Microsoft");return e&&(Io=e.ApplicationInsights),Io}()),t?t.ChromeDbgExt:null}var Po="warnToConsole",Ro={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},Mo=((Eo={})[0]=null,Eo[1]="errorToConsole",Eo[2]=Po,Eo[3]="debugToConsole",Eo);function Do(e){return e?'"'+e[xr](/\"/g,Bs)+'"':Bs}function ko(e,t){var i=typeof console!==Te?console:ii("console");if(i){var n="log";i[e]&&(n=e),it(i[n])&&i[n](t)}}var Oo=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[_r]=e,r[Ir]=(i?"AI: ":"AI (Internal): ")+e;var s=Bs;Ma()&&(s=(Ma()?JSON||ii(Ea):null).stringify(n));var a=(t?" message:"+Do(t):Bs)+(n?" props:"+Do(s):Bs);r[Ir]+=a}return e.dataType="MessageData",e}();function No(e,t){return(e||{})[Kn]||new Fo(t)}var Lo,xo,Fo=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};Nn(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[_r];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[Yn](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new Oo(23,c,!1);e.queue[Yn](u),1===t?e.errorToConsole(c):e[Gn](c)}}}function d(e,i){var n=Ao(t||{});n&&n[Ar]&&n[Ar](e,i)}a=function(t){return So(vo(t,Ro,e).cfg,(function(e){var t=e.cfg;i=t[Tr],n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[qn]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new Oo(n,r,o,a);if(s)throw bt(u);var h=Mo[t]||Po;if(Ze(u[Ir]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[_r];!l[g]&&i>=t&&(e[h](u[Ir]),l[g]=!0)}else i>=t&&e[h](u[Ir]);c(t,u)}},e.debugToConsole=function(e){ko("debug",e),d("warning",e)},e[Gn]=function(e){ko("warn",e),d("warning",e)},e.errorToConsole=function(e){ko("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[Sr]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function Uo(e){return e||new Fo}function Bo(e,t,i,n,r,s){void 0===s&&(s=!1),Uo(e)[qn](t,i,n,r,s)}function Vo(e,t){Uo(e)[Gn](t)}var Ho,$o="toGMTString",jo="toUTCString",Go="cookie",qo="expires",zo="isCookieUseDisabled",Wo="disableCookiesUsage",Ko="_ckMgr",Jo=null,Yo=null,Qo=null,Zo={},Xo={},el=((Lo={cookieCfg:function(e){return{mrg:!0,v:e}}((xo={},xo[ia]={fb:"cookieDomain",dfVal:oa},xo.path={fb:"cookiePath",dfVal:oa},xo.enabled=Us,xo.ignoreCookies=Us,xo.blockedCookies=Us,xo)),cookieDomain:Us,cookiePath:Us})[Wo]=Us,Lo);function tl(){var e;!Ho&&(e={},!zt&&Yt(),e.b=zt.lzy,vt(e,"v",{configurable:!0,get:function(){var t=oi();return zt.lzy||vt(e,"v",{value:t}),e.b=zt.lzy,t}}),Ho=e)}function il(e){return!e||e.isEnabled()}function nl(e,t){return!!(t&&e&&rt(e.ignoreCookies))&&-1!==Ei(e.ignoreCookies,t)}function rl(e,t){var i=t[fr];if(Xe(i)){var n=void 0;Ze(e[zo])||(n=!e[zo]),Ze(e[Wo])||(n=!e[Wo]),i=n}return i}function sl(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=t.cookieCfg;i=n&&n[Ko]?n[Ko]:al(t)}return i||(i=function(e,t){var i=al[Ko]||Xo[Ko];return i||(i=al[Ko]=al(e,t),Xo[Ko]=i),i}(t,(e||{})[Kn])),i}function al(e,t){var i,n,r,s,a,o,l,c,d;e=vo(e||Xo,null,t).cfg,a=So(e,(function(t){t[zn](t.cfg,el),n=t.ref(t.cfg,"cookieCfg"),r=n[na]||"/",s=n[ia],o=!1!==rl(e,n),l=n.getCookie||ul,c=n.setCookie||hl,d=n.delCookie||hl}),t);var u=((i={isEnabled:function(){var i=!1!==rl(e,n)&&o&&ol(t),r=Xo[Ko];return i&&r&&u!==r&&(i=il(r)),i},setEnabled:function(e){o=!1!==e,n[fr]=e},set:function(e,t,i,a,o){var l=!1;if(il(u)&&!function(e,t){return!!(t&&e&&rt(e.blockedCookies)&&-1!==Ei(e.blockedCookies,t))||nl(e,t)}(n,e)){var d={},h=Ni(t||Bs),g=zi(h,";");if(-1!==g&&(h=Ni(jt(t,g)),d=ll(Ht(t,g+1))),ha(d,ia,a||s,dt,Ze),!Xe(i)){var p=ka();if(Ze(d[qo])){var m=Ri()+1e3*i;if(m>0){var f=new Date;f.setTime(m),ha(d,qo,cl(f,p?$o:jo)||cl(f,p?$o:jo)||Bs,dt)}}p||ha(d,"max-age",Bs+i,null,Ze)}var v=Ra();v&&"https:"===v[kr]&&(ha(d,"secure",null,null,Ze),null===Yo&&(Yo=!function(e){return!(!tt(e)||!ca(e,"CPU iPhone OS 12")&&!ca(e,"iPad; CPU OS 12")&&!(ca(e,"Macintosh; Intel Mac OS X 10_14")&&ca(e,"Version/")&&ca(e,"Safari"))&&(!ca(e,"Macintosh; Intel Mac OS X 10_14")||!qi(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!ca(e,"Chrome/5")&&!ca(e,"Chrome/6")&&(!ca(e,"UnrealEngine")||ca(e,"Chrome"))&&!ca(e,"UCBrowser/12")&&!ca(e,"UCBrowser/11"))}((ci()||{})[Or])),Yo&&ha(d,"SameSite","None",null,Ze)),ha(d,na,o||r,null,Ze),c(e,dl(h,d)),l=!0}return l},get:function(e){var t=Bs;return il(u)&&!nl(n,e)&&(t=l(e)),t},del:function(e,t){var i=!1;return il(u)&&(i=u.purge(e,t)),i},purge:function(e,i){var n,r=!1;if(ol(t)){var s=((n={})[na]=i||"/",n[qo]="Thu, 01 Jan 1970 00:00:01 GMT",n);ka()||(s["max-age"]="0"),d(e,dl(Bs,s)),r=!0}return r}})[Sr]=function(e){a&&a.rm(),a=null},i);return u[Ko]=u,u}function ol(e){if(null===Jo){Jo=!1,!Ho&&tl();try{var t=Ho.v||{};Jo=void 0!==t[Go]}catch(t){Bo(e,2,68,"Cannot access document.cookie - "+ua(t),{exception:bt(t)})}}return Jo}function ll(e){var t={};return e&&e[Hn]&&Ti(Ni(e)[Nr](";"),(function(e){if(e=Ni(e||Bs)){var i=zi(e,"=");-1===i?t[e]=null:t[Ni(jt(e,i))]=Ni(Ht(e,i+1))}})),t}function cl(e,t){return it(e[t])?e[t]():null}function dl(e,t){var i=e||Bs;return pt(t,(function(e,t){i+="; "+e+(Xe(t)?Bs:"="+t)})),i}function ul(e){var t=Bs;if(!Ho&&tl(),Ho.v){var i=Ho.v[Go]||Bs;Qo!==i&&(Zo=ll(i),Qo=i),t=Ni(Zo[e]||Bs)}return t}function hl(e,t){!Ho&&tl(),Ho.v&&(Ho.v[Go]=e+"="+t)}var gl={perfEvtsSendAll:!1};function pl(e){e.h=null;var t=e.cb;e.cb=[],Ti(t,(function(e){Je(e.fn,[e.arg])}))}function ml(e,t,i,n){Ti(e,(function(e){e&&e[t]&&(i?(i.cb[Yn]({fn:n,arg:e}),i.h=i.h||Zi(pl,0,i)):Je(n,[e]))}))}var fl=function(){function e(t){var i,n;this.listeners=[];var r=[],s={h:null,cb:[]},a=vo(t,gl);n=a[Wn]((function(e){i=!!e.cfg.perfEvtsSendAll})),Nn(e,this,(function(e){yt(e,"listeners",{g:function(){return r}}),e[nr]=function(e){r[Yn](e)},e[ir]=function(e){for(var t=Ei(r,e);t>-1;)r[Qn](t,1),t=Ei(r,e)},e[Ks]=function(e){ml(r,Ks,s,(function(t){t[Ks](e)}))},e[Js]=function(e,t){ml(r,Js,s,(function(i){i[Js](e,t)}))},e[Ys]=function(e,t){ml(r,Ys,t?s:null,(function(i){i[Ys](e,t)}))},e[Qs]=function(e){e&&(!i&&e[$r]()||ml(r,Qs,null,(function(t){e[wr]?Zi((function(){return t[Qs](e)}),0):t[Qs](e)})))},e[Zs]=function(e){e&&e[Hn]&&ml(r,Zs,s,(function(t){t[Zs](e)}))},e[Xs]=function(e){e&&e[jr]&&ml(r,Xs,s,(function(t){t[Xs](e)}))},e[ea]=function(e,t){if(e>0){var i=t||0;ml(r,ea,s,(function(t){t[ea](e,i)}))}},e[Sr]=function(e){var t,i=function(){n&&n.rm(),n=null,r=[],s.h&&s.h[Xn](),s.h=null,s.cb=[]};if(ml(r,"unload",null,(function(i){var n=i[Sr](e);n&&(t||(t=[]),t[Yn](n))})),t)return Is((function(e){return ns(ws(t),(function(){i(),e()}))}));i()}}))}return e.__ieDyn=1,e}(),vl="ctx",Sl="ParentContextKey",yl="ChildrenContextKey",Cl=function(){function e(t,i,n){var r,s=this;s.start=Ri(),s[dr]=t,s[wr]=n,s[$r]=function(){return!1},it(i)&&yt(s,"payload",{g:function(){return!r&&it(i)&&(r=i(),i=null),r}}),s[Gr]=function(t){return t?t===e[Sl]||t===e[yl]?s[t]:(s[vl]||{})[t]:null},s[qr]=function(t,i){t&&(t===e[Sl]?(s[t]||(s[$r]=function(){return!0}),s[t]=i):t===e[yl]?s[t]=i:(s[vl]=s[vl]||{})[t]=i)},s[zr]=function(){var t=0,i=s[Gr](e[yl]);if(rt(i))for(var n=0;n<i[Hn];n++){var r=i[n];r&&(t+=r[hr])}s[hr]=Ri()-s.start,s.exTime=s[hr]-t,s[zr]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),Tl=function(){function e(t){this.ctx={},Nn(e,this,(function(e){e.create=function(e,t,i){return new Cl(e,t,i)},e.fire=function(e){e&&(e[zr](),t&&it(t[Qs])&&t[Qs](e))},e[qr]=function(t,i){t&&((e[vl]=e[vl]||{})[t]=i)},e[Gr]=function(t){return(e[vl]||{})[t]}}))}return e.__ieDyn=1,e}(),El="CoreUtils.doPerf";function bl(e,t,i,n,r){if(e){var s=e;if(s[ta]&&(s=s[ta]()),s){var a=void 0,o=s[Gr](El);try{if(a=s.create(t(),n,r)){if(o&&a[qr]&&(a[qr](Cl[Sl],o),o[Gr]&&o[qr])){var l=o[Gr](Cl[yl]);l||(l=[],o[qr](Cl[yl],l)),l[Yn](a)}return s[qr](El,a),i(a)}}catch(e){a&&a[qr]&&a[qr]("exception",e)}finally{a&&s.fire(a),s[qr](El,o)}}}return i()}function _l(){var e=Il();return Ht(e,0,8)+"-"+Ht(e,8,12)+"-"+Ht(e,12,16)+"-"+Ht(e,16,20)+"-"+Ht(e,20)}function Il(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=Bs,n=0;n<4;n++)i+=t[15&(e=ja())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&ja())|0];return $t(i,0,8)+$t(i,9,4)+"4"+$t(i,13,3)+r+$t(i,16,3)+$t(i,19,12)}function wl(e,t,i){return!(!e||e[Hn]!==t||e===i||!e.match(/^[\da-f]*$/i))}function Al(e){return wl(e,32,"00000000000000000000000000000000")}function Pl(e){return wl(e,16,"0000000000000000")}var Rl=Ya("plugin");function Ml(e){return Rl.get(e,"state",{},!0)}function Dl(e,t){for(var i,n=[],r=null,s=e[Mr]();s;){var a=s[cr]();if(a){r&&r[Dr]&&a[zs]&&r[Dr](a);var o=!!(i=Ml(a))[rr];a[rr]&&(o=a[rr]()),o||n[Yn](a),r=a,s=s[Mr]()}}Ti(n,(function(n){var r=e[Hs]();n[er](e.getCfg(),r,t,e[Mr]()),i=Ml(n),n[Hs]||i[Hs]||(i[Hs]=r),i[rr]=!0,delete i[br]}))}function kl(e){return e.sort((function(e,t){var i=0;if(t){var n=t[zs];e[zs]?i=n?e[Ws]-t[Ws]:1:n&&(i=-1)}else i=e?1:-1;return i}))}var Ol,Nl="_hasRun",Ll="_getTelCtx",xl=0;function Fl(e,t,i,n){var r=null,s=[];t||(t=vo({},null,i[Kn])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[cr]()===i)return e;e=e[Mr]()}return Hl([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[Mr]():null,!e){var t=s;t&&t[Hn]>0&&(Ti(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){Bo(i[Kn],2,73,"Unexpected Exception during onComplete - "+bt(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return No(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&pt(i,(function(e,i){if(Xe(n[e])){var r=t.cfg[e];!r&&Xe(r)||(n[e]=r)}eo(t,n,e,i)})),t[zn](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Xe(s[i])?!a[i]&&Xe(a[i])||(r=a[i]):r=s[i],r||!Xe(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[cr]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[Yn]({func:e,self:Ze(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[Gs];!s&&i&&(s={}),r[Gs]=s,(s=t.ref(r,Gs))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function Ul(e,t,i,n){var r=vo(t),s=Fl(e,r,i,n),a=s.ctx;return a[gr]=function(e){var t=s._next();return t&&t[zs](e,a),!t},a[Er]=function(e,t){return void 0===e&&(e=null),rt(e)&&(e=Hl(e,r.cfg,i,t)),Ul(e||a[Mr](),r.cfg,i,t)},a}function Bl(e,t,i){var n=vo(t.config),r=Fl(e,n,t,i),s=r.ctx;return s[gr]=function(e){var t=r._next();return t&&t[Sr](s,e),!t},s[Er]=function(e,i){return void 0===e&&(e=null),rt(e)&&(e=Hl(e,n.cfg,t,i)),Bl(e||s[Mr](),t,i)},s}function Vl(e,t,i){var n=vo(t.config),r=Fl(e,n,t,i).ctx;return r[gr]=function(e){return r.iterate((function(t){it(t[Rr])&&t[Rr](r,e)}))},r[Er]=function(e,i){return void 0===e&&(e=null),rt(e)&&(e=Hl(e,n.cfg,t,i)),Vl(e||r[Mr](),t,i)},r}function Hl(e,t,i,n){var r=null,s=!n;if(rt(e)&&e[Hn]>0){var a=null;Ti(e,(function(e){if(s||n!==e||(s=!0),s&&e&&it(e[zs])){var o=function(e,t,i){var n,r=null,s=it(e[zs]),a=it(e[Dr]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=Ml(e);return!n[br]&&!n[js]&&(a&&e[Dr](r),e[zs](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[gr](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=Ml(e),s=e[Hs]||r[Hs];!e||s&&s!==t.core()||r[br]||(r[Hs]=null,r[br]=!0,r[rr]=!1,e[br]&&!0===e[br](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[wr])||t[gr](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=Ml(e),s=e[Hs]||r[Hs];!e||s&&s!==t.core()||r[br]||e[Rr]&&!0===e[Rr](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[gr](i)},_id:n=e?e[tr]+"-"+e[Ws]+"-"+xl++:"Unknown-0-"+xl++,_setNext:function(e){r=e}};function l(){var n;return e&&it(e[Ll])&&(n=e[Ll]()),n||(n=Ul(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[tr]:"TelemetryPluginChain",d=t[Nl];return d||(d=t[Nl]={}),t.setNext(r),e&&bl(t[Hs](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:Bs;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||Bo(t[Ar](),1,73,"Plugin ["+c+"] failed during "+s+" - "+bt(e)+", run flags: "+bt(d))}}),a,o),l}return Dt(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?Hl([n],t,i):r}function $l(){var e=[];return{add:function(t){t&&e[Yn](t)},run:function(t,i){Ti(e,(function(e){try{e(t,i)}catch(e){Bo(t[Ar](),2,73,"Unexpected error calling unload handler - "+bt(e))}})),e=[]}}}function jl(){var e=[];return{run:function(t){var i=e;e=[],Ti(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){Bo(t,2,73,"Unloading:"+bt(e))}}))},add:function(t){t&&Ci(e,t)}}}var Gl,ql="getPlugin",zl=((Ol={})[Gs]={isVal:oa,v:{}},Ol),Wl=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||Ul(null,{},a[Hs]);t=n&&n[ql]?r[Er](null,n[ql]):r[Er](null,n)}return t}function l(e,t,r){vo(e,zl,No(t)),!r&&t&&(r=t[pr]()[Mr]());var s=n;n&&n[ql]&&(s=n[ql]()),a[Hs]=t,i=Ul(r,e,t,s)}function c(){t=!1,a[Hs]=null,i=null,n=null,s=jl(),r=$l()}c(),Nn(e,a,(function(e){e[er]=function(e,i,n,r){l(e,i,r),t=!0},e[br]=function(t,i){var a,o=e[Hs];if(o&&(!t||o===t[Hs]())){var l,d=!1,u=t||Bl(null,o,n&&n[ql]?n[ql]():n),h=i||((a={reason:0})[wr]=!1,a);return e[Pr]&&!0===e[Pr](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[Ar]()),!0===l&&u[gr](h),c())}},e[Rr]=function(t,i){var r=e[Hs];if(r&&(!t||r===t[Hs]())){var s,a=!1,o=t||Vl(null,r,n&&n[ql]?n[ql]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[Mr]()))}},ga(e,"_addUnloadCb",(function(){return r}),"add"),ga(e,"_addHook",(function(){return s}),"add"),yt(e,"_unloadHooks",{g:function(){return s}})})),a[Ar]=function(e){return o(e)[Ar]()},a[rr]=function(){return t},a.setInitialized=function(e){t=e},a[Dr]=function(e){n=e},a[gr]=function(e,t){t?t[gr](e):n&&it(n[zs])&&n[zs](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),Kl=function(e){function t(){var i,n,r=e.call(this)||this;function s(){i=0,n=[]}return r.identifier="TelemetryInitializerPlugin",r.priority=199,s(),Nn(t,r,(function(e,t){e.addTelemetryInitializer=function(e){return function(e,t,i){var n={id:t,fn:i};return Ci(e,n),{remove:function(){Ti(e,(function(t,i){if(t.id===n.id)return e[Qn](i,1),-1}))}}}(n,i++,e)},e[zs]=function(t,i){(function(e,t,i){for(var n=!1,r=e[Hn],s=0;s<r;++s){var a=e[s];if(a)try{if(!1===a.fn[Jn](null,[t])){n=!0;break}}catch(e){Bo(i,2,64,"Telemetry initializer failed: "+ua(e),{exception:bt(e)},!0)}}return!n})(n,t,i?i[Ar]():e[Ar]())&&e[gr](t,i)},e[Pr]=function(){s()}})),r}return tn(t,e),t.__ieDyn=1,t}(Wl),Jl="Plugins must provide initialize method",Yl="SDK is still unloading...",Ql=Rt(((Gl={cookieCfg:{}})[qs]={rdOnly:!0,ref:!0,v:[]},Gl[Vs]={rdOnly:!0,ref:!0,v:[]},Gl[Gs]={ref:!0,v:{}},Gl[$s]=Us,Gl.loggingLevelConsole=0,Gl.diagnosticLogInterval=Us,Gl));function Zl(e,t){return new Tl(t)}function Xl(e,t){var i=!1;return Ti(t,(function(t){if(t===e)return i=!0,-1})),i}function ec(e,t,i,n){i&&pt(i,(function(i,r){n&&Li(r)&&Li(t[i])&&ec(e,t[i],r,n),n&&Li(r)&&Li(t[i])?ec(e,t[i],r,n):e.set(t,i,r)}))}function tc(e,t){var i=null,n=-1;return Ti(e,(function(e,r){if(e.w===t)return i=e,n=r,-1})),{i:n,l:i}}var ic=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R,M,D,k;Nn(e,this,(function(e){function O(){R=!0,Xe(T)?(w=Un[ar],Bo(n,1,112,"ikey can't be resolved from promises")):w=Un.ACTIVE,N()}function N(){i&&(e.releaseQueue(),e[mr]())}function L(e){return M&&M[fr]||k||(e||n&&n.queue[Hn]>0)&&(D||(D=!0,J(t[Wn]((function(e){var t=e.cfg.diagnosticLogInterval;t&&t>0||(t=1e4);var i=!1;M&&(i=M[fr],M[Xn]()),(M=function(e,t){return Qi(!1,Pe,Ke[Be](arguments))}(j,t)).unref(),M[fr]=i})))),M[fr]=!0),M}function x(){var e={};_=[];var t=function(t){t&&Ti(t,(function(t){if(t[tr]&&t[Cr]&&!e[t.identifier]){var i=t[tr]+"="+t[Cr];_[Yn](i),e[t.identifier]=t}}))};t(h),u&&Ti(u,(function(e){t(e)})),t(d)}function F(){i=!1,(t=vo({},Ql,e[Kn])).cfg[Tr]=1,yt(e,"config",{g:function(){return t.cfg},s:function(t){e.updateCfg(t,!1)}}),yt(e,"pluginVersionStringArr",{g:function(){return _||x(),_}}),yt(e,"pluginVersionString",{g:function(){return I||(_||x(),I=_.join(";")),I||Bs}}),yt(e,"logger",{g:function(){return n||(n=new Fo(t.cfg),t[Kn]=n),n},s:function(e){t[Kn]=e,n!==e&&(yo(n,!1),n=e)}}),e[Kn]=new Fo(t.cfg),b=[];var y=e.config[qs]||[];y.splice(0,y[Hn]),Ci(y,b),p=new Kl,r=[],yo(s,!1),s=null,a=null,o=null,yo(l,!1),l=null,c=null,d=[],u=null,h=null,g=!1,m=null,f=Ja("AIBaseCore",!0),v=$l(),C=null,T=null,S=jl(),E=[],I=null,_=null,k=!1,M=null,D=!1,w=0,A=null,P=null,R=!1}function U(){var i=Ul(H(),t.cfg,e);return i[yr](L),i}function B(t){var i=function(e,t,i){var n,r=[],s=[],a={};return Ti(i,(function(t){(Xe(t)||Xe(t[er]))&&_t(Jl);var i=t[Ws],n=t[tr];t&&i&&(Xe(a[i])?a[i]=n:Vo(e,"Two extensions have same priority #"+i+" - "+a[i]+", "+n)),!i||i<500?r[Yn](t):s[Yn](t)})),(n={})[Hs]=r,n[Vs]=s,n}(e[Kn],0,d);c=null,I=null,_=null,h=kl(Ci(h=(u||[])[0]||[],i[Vs]));var n=Ci(kl(i[Hs]),h);b=Dt(n);var r=e.config[qs]||[];r.splice(0,r[Hn]),Ci(r,b);var s=U();h&&h[Hn]>0&&Dl(s[Er](h),n),Dl(s,n),t&&z(t)}function V(e){var t=null,i=null,n=[];return Ti(b,(function(t){if(t[tr]===e&&t!==p)return i=t,-1;t.getChannel&&n[Yn](t)})),!i&&n[Hn]>0&&Ti(n,(function(t){if(!(i=t.getChannel(e)))return-1})),i&&(t={plugin:i,setEnabled:function(e){Ml(i)[js]=!e},isEnabled:function(){var e=Ml(i);return!e[br]&&!e[js]},remove:function(e,t){var n;void 0===e&&(e=!0);var r=[i],s=((n={reason:1})[wr]=e,n);$(r,s,(function(e){e&&B({reason:32,removed:r}),t&&t(e)}))}}),t}function H(){if(!c){var i=(b||[]).slice();-1===Ei(i,p)&&i[Yn](p),c=Hl(kl(i),t.cfg,e)}return c}function $(i,n,r){if(i&&i[Hn]>0){var s=Bl(Hl(i,t.cfg,e),e);s[yr]((function(){var e=!1,t=[];Ti(d,(function(n,r){Xl(n,i)?e=!0:t[Yn](n)})),d=t,I=null,_=null;var n=[];u&&(Ti(u,(function(t,r){var s=[];Ti(t,(function(t){Xl(t,i)?e=!0:s[Yn](t)})),n[Yn](s)})),u=n),r&&r(e),L()})),s[gr](n)}else r(!1)}function j(){if(n&&n.queue){var t=n.queue.slice(0);n.queue[Hn]=0,Ti(t,(function(t){var i,n=((i={})[dr]=m||"InternalMessageId: "+t[_r],i[ur]=T,i[hr]=da(new Date),i.baseType=Oo.dataType,i.baseData={message:t[Ir]},i);e.track(n)}))}}function G(e,t,i,n){var r=1,s=!1,a=null;function o(){r--,s&&0===r&&(a&&a[Xn](),a=null,t&&t(s),t=null)}return n=n||5e3,h&&h[Hn]>0&&U()[Er](h).iterate((function(t){if(t.flush){r++;var s=!1;t.flush(e,(function(){s=!0,o()}),i)||s||(e&&null==a?a=Zi((function(){a=null,o()}),n):o())}})),s=!0,o(),!0}function q(){var i;J(t[Wn]((function(t){if(t.cfg.enablePerfMgr){var n=t.cfg[$s];i!==n&&(n||(n=Zl),function(e,t,i){var n;e?!(n=e[t])&&Xe(n)&&(n=Ze(i)?{}:i,e[t]=n):n=Ze(i)?{}:i}(t.cfg,$s,n),i=n,o=null),a||o||!it(n)||(o=n(e,e[lr]()))}else o=null,i=null})))}function z(t){var i=Vl(H(),e);i[yr](L),e._updateHook&&!0===e._updateHook(i,t)||i[gr](t)}function W(t){var i=e[Kn];i?(Bo(i,2,73,t),L()):_t(t)}function K(t){var i=e[lr]();i&&i[Js]([t],2)}function J(e){S.add(e)}F(),e._getDbgPlgTargets=function(){return[b,r]},e[rr]=function(){return i},e.activeStatus=function(){return w},e._setPendingStatus=function(){w=3},e[er]=function(r,a,o,l){g&&_t(Yl),e[rr]()&&_t("Core cannot be initialized more than once"),t=vo(r,Ql,o||e[Kn],!1),r=t.cfg,J(t[Wn]((function(e){var t=e.cfg;if(3!==w){P=t.initInMemoMaxSize||100;var s=t[sr],a=t.endpointUrl;if(Xe(s)){T=null,w=Un[ar];var o="Please provide instrumentation key";i?(Bo(n,1,100,o),N()):_t(o)}else{var l=[];if(ct(s)?(l[Yn](s),T=null):T=s,ct(a)?(l[Yn](a),A=null):A=a,l[Hn]){R=!1,w=3;var c=oa(t.initTimeOut)?t.initTimeOut:5e4,d=function(e,t){return!Cs&&(Cs=function(e){return Qt((function(t){var i=bi(arguments,1);return e((function(e,i){var n=[],r=1;function s(t,i){r++,ns(t,(function(t){t.rejected?n[i]={status:is,reason:t.reason}:n[i]={status:"fulfilled",value:t.value},0==--r&&e(n)}))}try{rt(t)?Ti(t,s):vi(t)?Si(t,s):It("Input is not an iterable"),0==--r&&e(n)}catch(e){i(e)}}),i)}))}(Is)),Cs.v(e,t)}(l);Zi((function(){R||O()}),c),ns(d,(function(e){try{if(R)return;if(!e.rejected){var t=e[or];if(t&&t[Hn]){var i=t[0];if(T=i&&i[or],t[Hn]>1){var n=t[1];A=n&&n[or]}}T&&(r[sr]=T,r.endpointUrl=A)}O()}catch(e){R||O()}}))}else O();var u=e.ref(e.cfg,Gs);pt(u,(function(t){e.ref(u,t)}))}}}))),y=function(e,t,i,n){return t.add(e[Wn]((function(e){var t=e.cfg.disableDbgExt;!0===t&&n&&(i[ir](n),n=null),i&&!n&&!0!==t&&(n=function(e){if(!To){To={};for(var t=0;t<_o[Hn];t++)To[_o[t]]=wo(_o[t],e)}return To}(e.cfg),i[nr](n))}))),n}(t,S,(s=l)&&e[lr](),y),q(),e[Kn]=o;var c=r[qs];if((d=[])[Yn].apply(d,nn(nn([],a),c)),u=r[Vs],B(null),h&&0!==h[Hn]||_t("No "+Vs+" available"),u&&u[Hn]>1){var p=e[cr]("TeeChannelController");p&&p.plugin||Bo(n,1,28,"TeeChannel required")}(function(e,t,i){Ti(t,(function(t){var n=So(e,t.w,i);delete t.w,t.rm=function(){n.rm()}}))})(r,E,n),E=null,i=!0,w===Un.ACTIVE&&N()},e.getChannels=function(){var e=[];return h&&Ti(h,(function(t){e[Yn](t)})),Dt(e)},e.track=function(t){bl(e[ta](),(function(){return"AppInsightsCore:track"}),(function(){null===t&&(K(t),_t("Invalid telemetry item")),!t[dr]&&Xe(t[dr])&&(K(t),_t("telemetry name required")),t[ur]=t[ur]||T,t[hr]=t[hr]||da(new Date),t.ver=t.ver||"4.0",!g&&e[rr]()&&w===Un.ACTIVE?U()[gr](t):w!==Un[ar]&&r[Hn]<=P&&r[Yn](t)}),(function(){return{item:t}}),!t.sync)},e[pr]=U,e[lr]=function(){return s||(s=new fl(t.cfg),e._notificationManager=s),s},e[nr]=function(t){e.getNotifyMgr()[nr](t)},e[ir]=function(e){s&&s[ir](e)},e.getCookieMgr=function(){return l||(l=al(t.cfg,e[Kn])),l},e.setCookieMgr=function(e){l!==e&&(yo(l,!1),l=e)},e[ta]=function(){return a||o||null},e.setPerfMgr=function(e){a=e},e.eventCnt=function(){return r[Hn]},e.releaseQueue=function(){if(i&&r[Hn]>0){var e=r;r=[],2===w?Ti(e,(function(e){e[ur]=e[ur]||T,U()[gr](e)})):Bo(n,2,20,"core init status is not active")}},e[mr]=function(e){return m=e||null,k=!1,M&&M[Xn](),L(!0)},e[vr]=function(){k=!0,M&&M[Xn](),j()},pa(e,(function(){return p}),["addTelemetryInitializer"]),e[Sr]=function(t,r,a){var o;void 0===t&&(t=!0),i||_t("SDK is not initialized"),g&&_t(Yl);var c,d=((o={reason:50})[wr]=t,o.flushComplete=!1,o);t&&!r&&(c=Is((function(e){r=e})));var u=Bl(H(),e);return u[yr]((function(){S.run(e[Kn]),Co([l,s,n],t,(function(){F(),r&&r(d)}))}),e),j(),G(t,(function(t){d.flushComplete=t,g=!0,v.run(u,d),e[vr](),u[gr](d)}),6,a),c},e[cr]=V,e.addPlugin=function(e,t,i,n){if(!e)return n&&n(!1),void W(Jl);var r=V(e[tr]);if(r&&!t)return n&&n(!1),void W("Plugin ["+e[tr]+"] is already loaded!");var s={reason:16};function a(t){d[Yn](e),s.added=[e],B(s),n&&n(!0)}if(r){var o=[r.plugin];$(o,{reason:2,isAsync:!!i},(function(e){e?(s.removed=o,s.reason|=32,a()):n&&n(!1)}))}else a()},e.updateCfg=function(i,n){var r;if(void 0===n&&(n=!0),e[rr]()){r={reason:1,cfg:t.cfg,oldCfg:Hi({},t.cfg),newConfig:Hi({},i),merge:n},i=r.newConfig;var s=t.cfg;i[qs]=s[qs],i[Vs]=s[Vs]}t._block((function(e){var t=e.cfg;ec(e,t,i,n),n||pt(t,(function(n){gt(i,n)||e.set(t,n,Us)})),e[zn](t,Ql)}),!0),t[jn](),r&&z(r)},e.evtNamespace=function(){return f},e.flush=G,e.getTraceCtx=function(e){return C||(C=function(){var e={};return{getName:function(){return e[dr]},setName:function(t){e[dr]=t},getTraceId:function(){return e[Zr]},setTraceId:function(t){Al(t)&&(e[Zr]=t)},getSpanId:function(){return e[Xr]},setSpanId:function(t){Pl(t)&&(e[Xr]=t)},getTraceFlags:function(){return e[es]},setTraceFlags:function(t){e[es]=t}}}()),C},e.setTraceCtx=function(e){C=e||null},e.addUnloadHook=J,ga(e,"addUnloadCb",(function(){return v}),"add"),e.onCfgChange=function(n){return function(e){return yt({rm:function(){e.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(e)+">"}})}(i?So(t.cfg,n,e[Kn]):function(e,t){var i=tc(e,t).l;return i||(i={w:t,rm:function(){var i=tc(e,t);-1!==i.i&&e[Qn](i.i,1)}},e[Yn](i)),i}(E,n))},e.getWParam=function(){return ni()||t.cfg.enableWParam?0:-1}}))}return e.__ieDyn=1,e}(),nc="",rc="&NoResponseBody=true",sc="POST",ac=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m=0;Nn(e,this,(function(e,f){var v=!0;function S(e,t){Bo(n,2,26,"Failed to send telemetry.",{message:e}),C(t,400,{})}function y(e){S("No endpoint url is provided for the batch",e)}function C(e,t,i,n){try{e&&e(t,i,n)}catch(e){}}function T(e,t){var i=ci(),n=e[Wr];if(!n)return y(t),!0;n=e[Wr]+(g?rc:nc);var s=e[jr],a=r?s:new Blob([s],{type:"text/plain;charset=UTF-8"});return i.sendBeacon(n,a)}function E(e,t,i){var a=e[jr];try{if(a)if(T(e,t))!function(e,t){C(t,200,{},"")}(0,t);else{var o=s&&s.beaconOnRetry;o&&it(o)?o(e,t,T):(l&&l[Kr](e,t,!0),Bo(n,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(e){r&&Vo(n,"Failed to send telemetry using sendBeacon API. Ex:"+bt(e)),C(t,r?0:400,{},nc)}}function b(e,i,n){var a,o,l,c=e[Jr]||{};!n&&t&&(a=Is((function(e,t){o=e,l=t}))),r&&n&&e.disableXhrSync&&(n=!1);var d=e[Wr];if(!d)return y(i),void(o&&o(!1));var u=function(e,t,i,n,r,s){function a(e,t,i){try{e[t]=i}catch(e){}}void 0===n&&(n=!1),void 0===r&&(r=!1);var o=new XMLHttpRequest;return n&&a(o,"Microsoft_ApplicationInsights_BypassAjaxInstrumentation",n),i&&a(o,ya,i),o.open(e,t,!r),i&&a(o,ya,i),!r&&s&&a(o,"timeout",s),o}(sc,d,v,!0,n,e[Yr]);function h(t){var n=s&&s.xhrOnComplete;if(n&&it(n))n(t,i,e);else{var a=fa(t);C(i,t[Br],Ta(t,r),a)}}return r||u[Qr]("Content-type","application/json"),Ti(Pt(c),(function(e){u[Qr](e,c[e])})),u.onreadystatechange=function(){r||(h(u),4===u.readyState&&o&&o(!0))},u.onload=function(){r&&h(u)},u.onerror=function(e){C(i,r?u[Br]:400,Ta(u,r),r?nc:va(u)),l&&l(e)},u.ontimeout=function(){C(i,r?u[Br]:500,Ta(u,r),r?nc:va(u)),o&&o(!1)},u.send(e[jr]),a}function _(e,i,n){var a,l,c,d,u=e[Wr],h=e[jr],f=r?h:new Blob([h],{type:"application/json"}),S=new Headers,T=h[Hn],E=!1,b=!1,_=e[Jr]||{},I=((a={method:sc,body:f})[bo]=!0,a);e.headers&&Pt(e.headers)[Hn]>0&&(Ti(Pt(_),(function(e){S.append(e,_[e])})),I[Jr]=S),o?I.credentials=o:v&&r&&(I.credentials="include"),n&&(I.keepalive=!0,m+=T,r?2===e._sendReason&&(E=!0,g&&(u+=rc)):E=!0);var w=new Request(u,I);try{w[bo]=!0}catch(e){}if(!n&&t&&(l=Is((function(e,t){c=e,d=t}))),!u)return y(i),void(c&&c(!1));function A(e){C(i,r?0:400,{},r?nc:e)}function P(e,t,n){var r=e[Br],a=s.fetchOnComplete;a&&it(a)?a(e,i,n||nc,t):C(i,r,{},n||nc)}try{ns(fetch(r?u:w,r?I:null),(function(t){if(n&&(m-=T,T=0),!b)if(b=!0,t.rejected)A(t.reason&&t.reason[Ir]),d&&d(t.reason);else{var i=t[or];try{r||i.ok?r&&!i.body?(P(i,null,nc),c&&c(!0)):ns(i.text(),(function(t){P(i,e,t[or]),c&&c(!0)})):(A(i.statusText),c&&c(!1))}catch(t){A(bt(t)),d&&d(t)}}}))}catch(e){b||(A(bt(e)),d&&d(e))}return E&&!b&&(b=!0,C(i,200,{}),c&&c(!0)),r&&!b&&e[Yr]>0&&p&&p.set((function(){b||(b=!0,C(i,500,{}),c&&c(!0))}),e[Yr]),l}function I(e,t,i){var a=li(),o=new XDomainRequest,l=e[jr];o.onload=function(){var i=fa(o),n=s&&s.xdrOnComplete;n&&it(n)?n(o,t,e):C(t,200,{},i)},o.onerror=function(){C(t,400,{},r?nc:function(e){return e?"XDomainRequest,Response:"+fa(e)||0:void 0}(o))},o.ontimeout=function(){C(t,500,{})},o.onprogress=function(){};var c=a&&a.location&&a.location[kr]||"",d=e[Wr];if(d){if(!r&&0!==d.lastIndexOf(c,0)){var u="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return Bo(n,2,40,". "+u),void S(u,t)}var h=r?d:d[xr](/^(https?:)/,"");o.open(sc,h),e[Yr]&&(o[Yr]=e[Yr]),o.send(l),r&&i?p&&p.set((function(){o.send(l)}),0):o.send(l)}else y(t)}function w(){m=0,i=!1,t=!1,n=null,r=null,s=null,a=null,o=null,l=null,c=!1,d=!1,u=!1,h=!1,g=!1,p=null}w(),e[er]=function(t,r){n=r,i&&Bo(n,1,28,"Sender is already initialized"),e.SetConfig(t),i=!0},e._getDbgPlgTargets=function(){return[i,r,a,t]},e.SetConfig=function(e){try{if(s=e.senderOnCompleteCallBack||{},a=!!e.disableCredentials,o=e.fetchCredentials,r=!!e.isOneDs,t=!!e.enableSendPromise,c=!!e.disableXhr,d=!!e.disableBeacon,u=!!e.disableBeaconSync,p=e.timeWrapper,g=!!e.addNoResponse,h=!!e.disableFetchKeepAlive,l={sendPOST:b},r||(v=!1),a){var i=Ra();i&&i.protocol&&"file:"===i.protocol[Bn]()&&(v=!1)}return!0}catch(e){}return!1},e.getSyncFetchPayload=function(){return m},e.getSenderInst=function(e,t){return e&&e[Hn]?function(e,t){for(var i,n=0,r=null,s=0;null==r&&s<e[Hn];)n=e[s],c||1!==n?2!==n||!Na(t)||t&&h?3!==n||!Oa()||(t?u:d)||(r=E):r=_:(null===wa&&(wa=typeof XDomainRequest!==Te)&&La()&&(wa=wa&&!Pa(ii(ba),"withCredentials")),wa?r=I:La()&&(r=b)),s++;return r?((i={_transport:n,_isSync:t})[Kr]=r,i):null}(e,t):null},e.getFallbackInst=function(){return l},e[Pr]=function(e,t){w()}}))}return e.__ieDyn=1,e}(),oc="attachEvent",lc="addEventListener",cc="detachEvent",dc="removeEventListener",uc="events",hc="visibilitychange",gc="pagehide",pc="pageshow",mc="unload",fc="beforeunload",vc=Ja("aiEvtPageHide"),Sc=Ja("aiEvtPageShow"),yc=/\.[\.]+/g,Cc=/[\.]+$/,Tc=1,Ec=Ya("events"),bc=/^([^.]*)(?:\.(.+)|)/;function _c(e){return e&&e[xr]?e[xr](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Bs):e}function Ic(e,t){var i;if(t){var n=Bs;rt(t)?(n=Bs,Ti(t,(function(e){(e=_c(e))&&("."!==e[0]&&(e="."+e),n+=e)}))):n=_c(t),n&&("."!==n[0]&&(n="."+n),e=(e||Bs)+n)}var r=bc.exec(e||Bs)||[];return(i={})[Fr]=r[1],i.ns=(r[2]||Bs).replace(yc,".").replace(Cc,Bs)[Nr](".").sort().join("."),i}function wc(e,t,i){void 0===i&&(i=!0);var n=Ec.get(e,uc,{},i),r=n[t];return r||(r=n[t]=[]),r}function Ac(e,t,i,n){e&&t&&t[Fr]&&(e[dc]?e[dc](t[Fr],i,n):e[cc]&&e[cc]("on"+t[Fr],i))}function Pc(e,t,i,n){for(var r=t[Hn];r--;){var s=t[r];s&&(i.ns&&i.ns!==s.evtName.ns||n&&!n(s)||(Ac(e,s.evtName,s[Ur],s.capture),t[Qn](r,1)))}}function Rc(e,t){return t?Ic("xx",rt(t)?[e].concat(t):[e,t]).ns[Nr]("."):e}function Mc(e,t,i,n,r){var s;void 0===r&&(r=!1);var a=!1;if(e)try{var o=Ic(t,n);if((a=function(e,t,i,n){var r=!1;return e&&t&&t[Fr]&&i&&(e[lc]?(e[lc](t[Fr],i,n),r=!0):e[oc]&&(e[oc]("on"+t[Fr],i),r=!0)),r}(e,o,i,r))&&Ec.accept(e)){var l=((s={guid:Tc++,evtName:o})[Ur]=i,s.capture=r,s);wc(e,o.type)[Yn](l)}}catch(e){}return a}function Dc(e,t,i,n,r){if(void 0===r&&(r=!1),e)try{var s=Ic(t,n),a=!1;(function(e,t,i){if(t[Fr])Pc(e,wc(e,t[Fr]),t,i);else{var n=Ec.get(e,uc,{});pt(n,(function(n,r){Pc(e,r,t,i)})),0===Pt(n)[Hn]&&Ec.kill(e,uc)}})(e,s,(function(e){return!((!s.ns||i)&&e[Ur]!==i||(a=!0,0))})),a||Ac(e,s,i,r)}catch(e){}}function kc(e,t,i,n){var r=!1;return t&&e&&e[Hn]>0&&Ti(e,(function(e){e&&(i&&-1!==Ei(i,e)||(r=function(e,t,i){var n=!1,r=li();r&&(n=Mc(r,e,t,i),n=Mc(r.body,e,t,i)||n);var s=oi();return s&&(n=Mc(s,e,t,i)||n),n}(e,t,n)||r))})),r}function Oc(e,t,i){e&&rt(e)&&Ti(e,(function(e){e&&function(e,t,i){var n=li();n&&(Dc(n,e,t,i),Dc(n.body,e,t,i));var r=oi();r&&Dc(r,e,t,i)}(e,t,i)}))}function Nc(e,t,i){var n=Rc(vc,i),r=kc([gc],e,t,n);return t&&-1!==Ei(t,hc)||(r=kc([hc],(function(t){var i=oi();e&&i&&"hidden"===i.visibilityState&&e(t)}),t,n)||r),!r&&t&&(r=Nc(e,null,i)),r}function Lc(e,t,i){var n=Rc(Sc,i),r=kc([pc],e,t,n);return!(r=kc([hc],(function(t){var i=oi();e&&i&&"visible"===i.visibilityState&&e(t)}),t,n)||r)&&t&&(r=Lc(e,null,i)),r}var xc,Fc="",Uc="version",Bc="properties",Vc="initialize",Hc="logger",$c="timings",jc="pollInternalLogs",Gc="value",qc="kind",zc="length",Wc="processTelemetryStart",Kc="1DS-Web-JS-4.3.2",Jc=_e.hasOwnProperty,Yc=((xc={})[0]=0,xc[2]=6,xc[1]=1,xc[3]=7,xc[4098]=6,xc[4097]=1,xc[4099]=7,xc);function Qc(e){return!(e===Fc||Xe(e))}function Zc(e,t,i){var n=-1;if(!Ze(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=Yc[rd(e)]||-1;-1!==n&&-1!==r?n|=r:6===r&&(n=r)}return n}function Xc(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||Fc}function ed(e){void 0===e&&(e="D");var t=_l();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,Fc)),t}function td(e,t,i,n,r){var s={},a=!1,o=0,l=arguments[zc],c=arguments;for(ot(c[0])&&(a=c[0],o++);o<l;o++)pt(c[o],(function(e,t){a&&t&&nt(t)?rt(t)?(s[e]=s[e]||[],Ti(t,(function(t,i){t&&nt(t)?s[e][i]=td(!0,s[e][i],t):s[e][i]=t}))):s[e]=td(!0,s[e],t):s[e]=t}));return s}var id=Gi;function nd(e,t){var i=e;i[$c]=i[$c]||{},i[$c][Wc]=i[$c][Wc]||{},i[$c][Wc][t]=id()}function rd(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===Ce&&(t=4,rt(e)?(t=4096,e[zc]>0&&(t|=rd(e[0]))):Jc.call(e,"value")&&(t=8192|rd(e[Gc])))}return t}function sd(e){return e>0}var ad,od=Rt({endpointUrl:"https://browser.events.data.microsoft.com/OneCollector/1.0/",propertyStorageOverride:{isVal:function(e){return!e||e.getProperty&&e.setProperty||_t("Invalid property storage override passed."),!0}}}),ld=function(e){function t(){var i=e.call(this)||this;return Nn(t,i,(function(e,t){e[Vc]=function(i,n,r,s){bl(e,(function(){return"AppInsightsCore.initialize"}),(function(){try{t[Vc](vo(i,od,r||e[Hc],!1).cfg,n,r,s)}catch(t){var a=e[Hc],o=bt(t);-1!==o.indexOf("channels")&&(o+="\n - Channels must be provided through config.channels only!"),Bo(a,1,514,"SDK Initialization Failed - no telemetry will be sent: "+o)}}),(function(){return{config:i,extensions:n,logger:r,notificationManager:s}}))},e.track=function(i){bl(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n[$c]=n[$c]||{},n[$c].trackStart=id(),function(e){return!!(e&&at(e)&&e>=1&&e<=4)}(n.latency)||(n.latency=1);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=Kc;var s=n.baseData=n.baseData||{};s[Bc]=s[Bc]||{};var a=s[Bc];a[Uc]=a[Uc]||e.pluginVersionString||Fc}t.track(n)}),(function(){return{item:i}}),!i.sync)},e[jc]=function(e){return t[jc](e||"InternalLog")}})),i}return tn(t,e),t.__ieDyn=1,t}(ic),cd=(xn({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}),xn({Normal:1,CostDeferred:2,RealTime:3,Immediate:4})),dd=(xn({Unspecified:0,String:1,Int32:2,UInt32:3,Int64:4,UInt64:5,Double:6,Bool:7,Guid:8,DateTime:9}),xn({Normal:1,Critical:2}),xn({NONE:0,ERROR:1,WARNING:2,INFORMATION:3}),"toLowerCase"),ud="blkVal",hd="length",gd="rdOnly",pd="notify",md="warnToConsole",fd="throwInternal",vd="setDf",Sd="watch",yd="logger",Cd="apply",Td="push",Ed="hdlr",bd="identifier",_d="isInitialized",Id="getPlugin",wd="time",Ad="processNext",Pd="unload",Rd="createNew",Md="teardown",Dd="messageId",kd="message",Od="isAsync",Nd="diagLog",Ld="_doTeardown",xd="update",Fd="getNext",Ud="setNextPlugin",Bd="userAgent",Vd="nodeType",Hd="replace",$d="isChildEvt",jd="getCtx",Gd="setCtx",qd="complete",zd="",Wd="core",Kd="extensionConfig",Jd="processTelemetry",Yd="getPerfMgr",Qd=/-([a-z])/g,Zd=/([^\w\d_$])/g,Xd=/^(\d+[\w\d_$])/;function eu(e){var t=e;return t&&tt(t)&&(t=(t=(t=t[Hd](Qd,(function(e,t){return t.toUpperCase()})))[Hd](Zd,"_"))[Hd](Xd,(function(e,t){return"_"+t}))),t}function tu(e,t){return!(!e||!t)&&-1!==zi(e,t)}function iu(e,t,i,n,r){e&&t&&i&&(!1!==r||Ze(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return it(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][Cd](n,e)}}(i,n))}var nu="JSON",ru=null,su=null;function au(){return Boolean(typeof JSON===Ce&&JSON||null!==ii(nu))}var ou=4294967296,lu=4294967295,cu=123456789,du=987654321,uu=!1,hu=cu,gu=du;function pu(e){var t=0,i=ii("crypto")||ii("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&lu),0===t&&function(){var e=ci();if(e&&(e[Bd]!==su||null===ru)){var t=((su=e[Bd])||zd)[dd]();ru=tu(t,"msie")||tu(t,"trident/")}return ru}()&&(uu||function(){try{var e=2147483647&Ri();!function(e){e<0&&(e>>>=0),hu=cu+e&lu,gu=du-e&lu,uu=!0}((Math.random()*ou^e)+e)}catch(e){}}(),t=function(){var e=((gu=36969*(65535&gu)+(gu>>16)&lu)<<16)+(65535&(hu=18e3*(65535&hu)+(hu>>16)&lu))>>>0&lu;return e>>>=0}()&lu),0===t&&(t=Math.floor(ou*Math.random()|0)),e||(t>>>=0),t}var mu="3.3.1",fu="."+function(e){void 0===e&&(e=22);for(var t=pu()>>>0,i=0,n=zd;n[hd]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(pu()<<2&4294967295|3&t)>>>0,i=0);return n}(6),vu=0;function Su(e){return 1===e[Vd]||9===e[Vd]||!+e[Vd]}function yu(e,t){return void 0===t&&(t=!1),eu(e+vu+++(t?"."+mu:zd)+fu)}function Cu(e){return e&&nt(e)&&(e.isVal||e.fb||gt(e,"v")||gt(e,"mrg")||gt(e,"ref")||e.set)}function Tu(e,t,i){var n,r=i.dfVal||et;if(t&&i.fb){var s=i.fb;rt(s)||(s=[s]);for(var a=0;a<s[hd];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,Et(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function Eu(e,t,i){var n,r=i;return i&&Cu(i)&&(r=Tu(e,t,i)),r&&(Cu(r)&&(r=Eu(e,t,r)),rt(r)?(n=[])[hd]=r[hd]:Li(r)&&(n={}),n&&(pt(r,(function(i,r){r&&Cu(r)&&(r=Eu(e,t,r)),n[i]=r})),r=n)),r}function bu(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;Cu(h)?(r=h.isVal,s=h.set,c=h[gd],d=h[ud],o=h.mrg,!(l=h.ref)&&Ze(l)&&(l=!!o),a=Tu(e,t,h)):a=n,d&&e[ud](t,i);var g=!0,p=t[i];!p&&Xe(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?Eu(e,t,a):a:(Li(u)||rt(a))&&o&&a&&(Li(a)||rt(a))&&pt(a,(function(t,i){bu(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[gd](t,i)}var _u=mi("[[ai_dynCfg_1]]"),Iu=mi("[[ai_blkDynCfg_1]]"),wu=mi("[[ai_frcDynCfg_1]]");function Au(e){var t;return e&&(rt(e)?(t=[])[hd]=e[hd]:Li(e)&&(t={}),t)?(pt(e,(function(e,i){t[e]=Au(i)})),t):e}function Pu(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[wu])||i[Iu]||(n=Li(i)||rt(i))),n}function Ru(e){It("InvalidAccess:"+e)}var Mu=["push","pop","shift","unshift","splice"],Du=function(e,t,i,n){e&&e[fd](3,108,"".concat(i," [").concat(t,"] failed - ")+bt(n))};function ku(e,t){var i=ut(e,t);return i&&i.get}function Ou(e,t,i,n){if(t){var r=ku(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===Ei(r.h,t)&&r.h[Td](t),e.trk(t,r))},clr:function(e){var t=Ei(r.h,e);-1!==t&&r.h.splice(t,1)}},s=!0,a=!1;function o(){s&&(a=a||Pu(o,e,n),n&&!n[_u]&&a&&(n=Lu(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},yt(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&Ru("["+i+"] is read-only:"+bt(t)),s&&(a=a||Pu(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){pt(n,(function(e){n[e]=l?l[e]:void 0}));try{pt(l,(function(t,i){Ou(e,n,t,i)})),l=n}catch(t){Du((e.hdlr||{})[yd],i,"Assigning",t),a=!1}}else n&&n[_u]&&pt(n,(function(t){var i=ku(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&Pu(o,e,l);!c&&d&&(l=Lu(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function Nu(e,t,i,n){if(t){var r=ku(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(Li(e)||rt(e)))try{e[Iu]=!0}catch(e){}}(t)}catch(t){Du((e.hdlr||{})[yd],i,"Blocking",t)}try{Ou(e,t,i,t[i]),r=ku(t,i)}catch(t){Du((e.hdlr||{})[yd],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function Lu(e,t,i,n){try{pt(t,(function(i,n){Ou(e,t,i,n)})),t[_u]||(vt(t,_u,{get:function(){return e[Ed]}}),function(e,t,i){rt(t)&&Ti(Mu,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[Cd](this,n);return Lu(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){Du((e.hdlr||{})[yd],i,n,t)}return t}var xu="[[ai_",Fu="]]";function Uu(e,t,i){var n,r=function(e){if(e){var t=e[_u]||e;if(t.cfg&&(t.cfg===e||t.cfg[_u]===t))return t}return null}(t);if(r)return r;var s,a=yu("dyncfg",!0),o=t&&!1!==i?t:Au(t),l=((n={uid:null,cfg:o})[yd]=e,n[pd]=function(){s[pd]()},n.set=function(t,i,n){try{t=Ou(s,t,i,n)}catch(t){Du(e,i,"Setting value",t)}return t[i]},n[vd]=function(e,t){return t&&pt(t,(function(t,i){bu(l,e,t,i)})),e},n[Sd]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return yt(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return Nu(s,e,t,(i={},i[0]=!0,i))[t]},n[gd]=function(e,t){var i;return Nu(s,e,t,(i={},i[1]=!0,i))[t]},n[ud]=function(e,t){var i;return Nu(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Ze(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return yt(l,"uid",{c:!1,e:!1,w:!1,v:a}),Lu(s=function(e){var t,i,n=pi(xu+"get"+e.uid+Fu),r=pi(xu+"ro"+e.uid+Fu),s=pi(xu+"rf"+e.uid+Fu),a=pi(xu+"blkVal"+e.uid+Fu),o=pi(xu+"dtl"+e.uid+Fu),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(Ti(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[vd].bind(e),ref:e.ref.bind(e),rdOnly:e[gd].bind(e)})}catch(t){var s=e[yd];throw s&&s[fd](1,107,bt(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c.cancel(),c=null;var t=[];if(Ti(e,(function(e){if(e&&(e[o]&&(Ti(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[Td](e)}})),l)try{u()}catch(e){t[Td](e)}t[hd]>0&&function(e,t){ad||(ad=Pi("AggregationError",(function(e,t){t[hd]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw Ti(t,(function(e,t){i+="\n".concat(t," > ").concat(bt(e))})),new ad(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[ud]=a,t[Ed]=e,t.add=function(e){if(e&&e.h[hd]>0){l||(l=[]),c||(c=Zi((function(){c=null,u()}),0));for(var t=0;t<e.h[hd];t++){var i=e.h[t];i&&-1===Ei(l,i)&&l[Td](i)}}},t[pd]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===Ei(i,t)&&i[Td](t)}},i=t}(l),o,"config","Creating"),l}function Bu(e,t,i,n){var r=Uu(i,e||{},n);return t&&r[vd](r.cfg,t),r}function Vu(e,t,i){var n=e[_u]||e;return!n.cfg||n.cfg!==e&&n.cfg[_u]!==n?(function(e,t){e?(e[md](t),e[fd](2,108,t)):Ru(t)}(i,"Not dynamic - "+bt(e)),Bu(e,null,i)[Sd](t)):n[Sd](t)}var Hu,$u=null;var ju="warnToConsole",Gu={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},qu=((Hu={})[0]=null,Hu[1]="errorToConsole",Hu[2]=ju,Hu[3]="debugToConsole",Hu);function zu(e){return e?'"'+e[Hd](/\"/g,zd)+'"':zd}function Wu(e,t){var i=typeof console!==Te?console:ii("console");if(i){var n="log";i[e]&&(n=e),it(i[n])&&i[n](t)}}var Ku=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[Dd]=e,r[kd]=(i?"AI: ":"AI (Internal): ")+e;var s=zd;au()&&(s=(au()?JSON||ii(nu):null).stringify(n));var a=(t?" message:"+zu(t):zd)+(n?" props:"+zu(s):zd);r[kd]+=a}return e.dataType="MessageData",e}();function Ju(e,t){return(e||{})[yd]||new Yu(t)}var Yu=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};Nn(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[Dd];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[Td](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new Ku(23,c,!1);e.queue[Td](u),1===t?e.errorToConsole(c):e[md](c)}}}function d(e,i){var n=function(e){var t=$u;return t||!0===e.disableDbgExt||(t=$u||function(){var e=ii("Microsoft");return e&&($u=e.ApplicationInsights),$u}()),t?t.ChromeDbgExt:null}(t||{});n&&n[Nd]&&n[Nd](e,i)}a=function(t){return Vu(Bu(t,Gu,e).cfg,(function(e){var t=e.cfg;i=t.loggingLevelConsole,n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[fd]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new Ku(n,r,o,a);if(s)throw bt(u);var h=qu[t]||ju;if(Ze(u[kd]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[Dd];!l[g]&&i>=t&&(e[h](u[kd]),l[g]=!0)}else i>=t&&e[h](u[kd]);c(t,u)}},e.debugToConsole=function(e){Wu("debug",e),d("warning",e)},e[md]=function(e){Wu("warn",e),d("warning",e)},e.errorToConsole=function(e){Wu("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[Pd]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function Qu(e,t,i,n,r,s){void 0===s&&(s=!1),function(e){return e||new Yu}(e)[fd](t,i,n,r,s)}var Zu="ctx",Xu="ParentContextKey",eh="ChildrenContextKey",th=function(){function e(t,i,n){var r,s=this;s.start=Ri(),s.name=t,s[Od]=n,s[$d]=function(){return!1},it(i)&&yt(s,"payload",{g:function(){return!r&&it(i)&&(r=i(),i=null),r}}),s[jd]=function(t){return t?t===e[Xu]||t===e[eh]?s[t]:(s[Zu]||{})[t]:null},s[Gd]=function(t,i){t&&(t===e[Xu]?(s[t]||(s[$d]=function(){return!0}),s[t]=i):t===e[eh]?s[t]=i:(s[Zu]=s[Zu]||{})[t]=i)},s[qd]=function(){var t=0,i=s[jd](e[eh]);if(rt(i))for(var n=0;n<i[hd];n++){var r=i[n];r&&(t+=r[wd])}s[wd]=Ri()-s.start,s.exTime=s[wd]-t,s[qd]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),ih="CoreUtils.doPerf";function nh(e,t,i,n,r){if(e){var s=e;if(s[Yd]&&(s=s[Yd]()),s){var a=void 0,o=s[jd](ih);try{if(a=s.create(t(),n,r)){if(o&&a[Gd]&&(a[Gd](th[Xu],o),o[jd]&&o[Gd])){var l=o[jd](th[eh]);l||(l=[],o[Gd](th[eh],l)),l[Td](a)}return s[Gd](ih,a),i(a)}}catch(e){a&&a[Gd]&&a[Gd]("exception",e)}finally{a&&s.fire(a),s[Gd](ih,o)}}}return i()}function rh(){var e=function(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=zd,n=0;n<4;n++)i+=t[15&(e=pu())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&pu())|0];return $t(i,0,8)+$t(i,9,4)+"4"+$t(i,13,3)+r+$t(i,16,3)+$t(i,19,12)}();return Ht(e,0,8)+"-"+Ht(e,8,12)+"-"+Ht(e,12,16)+"-"+Ht(e,16,20)+"-"+Ht(e,20)}var sh,ah=(sh={id:yu("_aiData-plugin."+mu),accept:function(e){return Su(e)},get:function(e,t,i,n){var r=e[sh.id];return r?r[eu(t)]:(n&&((r=function(e,t){var i=t[e.id];if(!i){i={};try{Su(t)&&yt(t,e.id,{e:!1,v:i})}catch(e){}}return i}(sh,e))[eu(t)]=i),i)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}},sh);function oh(e){return ah.get(e,"state",{},!0)}var lh,ch="_hasRun",dh="_getTelCtx",uh=0;function hh(e,t,i,n){var r=null,s=[];t||(t=Bu({},null,i[yd])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[Id]()===i)return e;e=e[Fd]()}return fh([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[Fd]():null,!e){var t=s;t&&t[hd]>0&&(Ti(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){Qu(i[yd],2,73,"Unexpected Exception during onComplete - "+bt(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return Ju(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&pt(i,(function(e,i){if(Xe(n[e])){var r=t.cfg[e];!r&&Xe(r)||(n[e]=r)}bu(t,n,e,i)})),t[vd](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Xe(s[i])?!a[i]&&Xe(a[i])||(r=a[i]):r=s[i],r||!Xe(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[Id]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[Td]({func:e,self:Ze(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[Kd];!s&&i&&(s={}),r[Kd]=s,(s=t.ref(r,Kd))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function gh(e,t,i,n){var r=Bu(t),s=hh(e,r,i,n),a=s.ctx;return a[Ad]=function(e){var t=s._next();return t&&t[Jd](e,a),!t},a[Rd]=function(e,t){return void 0===e&&(e=null),rt(e)&&(e=fh(e,r.cfg,i,t)),gh(e||a[Fd](),r.cfg,i,t)},a}function ph(e,t,i){var n=Bu(t.config),r=hh(e,n,t,i),s=r.ctx;return s[Ad]=function(e){var t=r._next();return t&&t[Pd](s,e),!t},s[Rd]=function(e,i){return void 0===e&&(e=null),rt(e)&&(e=fh(e,n.cfg,t,i)),ph(e||s[Fd](),t,i)},s}function mh(e,t,i){var n=Bu(t.config),r=hh(e,n,t,i).ctx;return r[Ad]=function(e){return r.iterate((function(t){it(t[xd])&&t[xd](r,e)}))},r[Rd]=function(e,i){return void 0===e&&(e=null),rt(e)&&(e=fh(e,n.cfg,t,i)),mh(e||r[Fd](),t,i)},r}function fh(e,t,i,n){var r=null,s=!n;if(rt(e)&&e[hd]>0){var a=null;Ti(e,(function(e){if(s||n!==e||(s=!0),s&&e&&it(e[Jd])){var o=function(e,t,i){var n,r=null,s=it(e[Jd]),a=it(e[Ud]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=oh(e);return!n[Md]&&!n.disabled&&(a&&e[Ud](r),e[Jd](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[Ad](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=oh(e),s=e[Wd]||r[Wd];!e||s&&s!==t.core()||r[Md]||(r[Wd]=null,r[Md]=!0,r[_d]=!1,e[Md]&&!0===e[Md](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[Od])||t[Ad](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=oh(e),s=e[Wd]||r[Wd];!e||s&&s!==t.core()||r[Md]||e[xd]&&!0===e[xd](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[Ad](i)},_id:n=e?e[bd]+"-"+e.priority+"-"+uh++:"Unknown-0-"+uh++,_setNext:function(e){r=e}};function l(){var n;return e&&it(e[dh])&&(n=e[dh]()),n||(n=gh(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[bd]:"TelemetryPluginChain",d=t[ch];return d||(d=t[ch]={}),t.setNext(r),e&&nh(t[Wd](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:zd;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||Qu(t[Nd](),1,73,"Plugin ["+c+"] failed during "+s+" - "+bt(e)+", run flags: "+bt(d))}}),a,o),l}return Dt(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?fh([n],t,i):r}var vh,Sh="getPlugin",yh=((lh={})[Kd]={isVal:function(e){return!Xe(e)},v:{}},lh),Ch=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||gh(null,{},a[Wd]);t=n&&n[Sh]?r[Rd](null,n[Sh]):r[Rd](null,n)}return t}function l(e,t,r){Bu(e,yh,Ju(t)),!r&&t&&(r=t.getProcessTelContext()[Fd]());var s=n;n&&n[Sh]&&(s=n[Sh]()),a[Wd]=t,i=gh(r,e,t,s)}function c(){t=!1,a[Wd]=null,i=null,n=null,s=function(){var e=[];return{run:function(t){var i=e;e=[],Ti(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){Qu(t,2,73,"Unloading:"+bt(e))}}))},add:function(t){t&&Ci(e,t)}}}(),r=function(){var e=[];return{add:function(t){t&&e[Td](t)},run:function(t,i){Ti(e,(function(e){try{e(t,i)}catch(e){Qu(t[Nd](),2,73,"Unexpected error calling unload handler - "+bt(e))}})),e=[]}}}()}c(),Nn(e,a,(function(e){e.initialize=function(e,i,n,r){l(e,i,r),t=!0},e[Md]=function(t,i){var a,o=e[Wd];if(o&&(!t||o===t[Wd]())){var l,d=!1,u=t||ph(null,o,n&&n[Sh]?n[Sh]():n),h=i||((a={reason:0})[Od]=!1,a);return e[Ld]&&!0===e[Ld](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[Nd]()),!0===l&&u[Ad](h),c())}},e[xd]=function(t,i){var r=e[Wd];if(r&&(!t||r===t[Wd]())){var s,a=!1,o=t||mh(null,r,n&&n[Sh]?n[Sh]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[Fd]()))}},iu(e,"_addUnloadCb",(function(){return r}),"add"),iu(e,"_addHook",(function(){return s}),"add"),yt(e,"_unloadHooks",{g:function(){return s}})})),a[Nd]=function(e){return o(e)[Nd]()},a[_d]=function(){return t},a.setInitialized=function(e){t=e},a[Ud]=function(e){n=e},a[Ad]=function(e,t){t?t[Ad](e):n&&it(n[Jd])&&n[Jd](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),Th="timings",Eh="processTelemetryStart";function bh(e){if(e){var t=zi(e,"-");if(t>-1)return jt(e,t)}return""}(vh={})[0]=0,vh[2]=6,vh[1]=1,vh[3]=7,vh[4098]=6,vh[4097]=1,vh[4099]=7;var _h,Ih=Gi;function wh(e){return e>0}function Ah(e){return at(e)&&e>=1&&e<=2}!function(e){e[e.LocalStorage=1]="LocalStorage",e[e.SessionStorage=2]="SessionStorage",e[e.IndexedDb=3]="IndexedDb"}(_h||(_h={}));var Ph="result",Rh="DBError: Unable to open database",Mh="Database is not open",Dh="DBError: Failed to delete the database",kh=["indexedDB"],Oh=it,Nh=tt,Lh=0;function xh(e,t){ii("QUnit")&&console&&console.log(" ["+function(e){return e&&e.toISOString()||""}(new Date)+"]: IndexedDbHelper ["+e+"] "+t)}function Fh(e,t,i){e&&e.warnToConsole("IndexedDbHelper ["+t+"] "+i)}function Uh(e,t,i,n){return function(r){i(new Error(t)),xh(e,"["+n+"] event rejected")}}var Bh=[];function Vh(e,t){for(var i=null,n=0;n<Bh.length;n++)if((i=Bh[n]).name===e)return i;return i={name:e,sch:Fs(vs,"IndexedDbHelper["+e+"]"),dbHdl:[],add:function(t){i.dbHdl.push(t),xh(e,"- dbOpened (add) -- hdls ["+i.dbHdl.length+"]")},remove:function(t){for(var n=i.dbHdl,r=0;r<n.length;r++)if(n[r]===t){n.splice(r,1);break}xh(e,"- dbClosed (remove) -- hdls ["+i.dbHdl.length+"]")},isOpen:function(){return i.dbHdl.length>0},openHdl:function(){return i.dbHdl.length>0?i.dbHdl[0]:null}},Bh.push(i),i}var Hh=function(){function e(t){var i=Lh++,n=0;Nn(e,this,(function(e){var r=function(){var e=ti()||{},t=null;if(e)try{for(var i=0;i<kh.length;i++)if((t=e[kh[i]])&&Oh(t.open))return t}catch(e){t=null}return t||null}()||null;function s(e,r,s){var l=e.db,c=n++;xh(e.dbName,"["+i+":"+c+"] txn.open - "+r+" -- "+s);var d=l.transaction(r,"readwrite");return d.onabort=function(){Fh(t,e.dbName,"["+i+":"+c+"] txn.onabort - "+r+" -- "+s+" -- "+bt(d.error))},d.onerror=function(){Fh(t,e.dbName,"["+i+":"+c+"] txn.onerror - "+r+" -- "+s)},d.oncomplete=function(){xh(e.dbName,"["+i+":"+c+"] txn.oncomplete - "+r+" -- "+s)},{db:e,store:d.objectStore(r),tx:d,tbl:r,openCursor:function(t,i){return o(e,r,t,i)},newTransaction:function(t){return a(e,r,t)}}}function a(e,t,i){if(!e||!e.db)return bs(new Error(Mh));try{var n=i(s(e,t,"openStore"));return ct(n)?n:Es(n)}catch(e){return bs(e)}}function o(e,t,i,n){if(!e||!e.db)return bs(new Error(Mh));var r=null;return i&&Nh(i)?r=new $h(i):i&&i.isMatch&&(r=i),vs((function(i,a){var o=[],l=null,c=null;r&&r.keyRange&&(c=r.keyRange());var d=s(e,t,"openCursor");(l=c?d.store.openCursor(c):d.store.openCursor()).onerror=Uh(d.db.dbName,"DBError: Failed to Open Cursor",a,"openCursor"),l.onsuccess=function(e){var t=e.target[Ph];if(t){var s={store:d,cursor:t,continue:function(){t.continue()},done:function(){i(o)}},l=t.value;if(!r||r.isMatch(l))if(n)try{switch(n(s,l,o)){case 2:i(o);break;case 1:break;default:s.continue()}}catch(e){a(e)}else o.push(l),s.continue();else s.continue()}else i(o)}}))}function l(e,t,i,n){return Vh(e).sch.queue(i,t,n)}e.isAvailable=function(){return!!r},e.openDb=function(e,i,n,s){return l(e,"openDb",(function(l){return vs((function(c,d){var u=!1;function h(t,n,r,s,l){var c={db:n,dbName:e,dbVersion:i,ctx:null,isNew:s,txn:r?r.transaction:null};return l||(c.openStore=function(e,t){return a(c,e,t)},c.openCursor=function(e,t,i){return o(c,e,t,i)}),c}function g(i,r){var s=Vh(e);s.add(i),i.onabort=function(n){Fh(t,e,"onabort -- closing the Db"),s.remove(i)},i.onerror=function(n){Fh(t,e,"onerror -- closing the Db"),s.remove(i)},i.onclose=function(n){Fh(t,e,"onclose -- closing the Db"),s.remove(i)},i.onversionchange=function(n){Fh(t,e,"onversionchange -- force closing the Db"),i.close(),s.remove(i)};var a,o=null;s.dbHdl.length>0&&(o=s.dbHdl[0]),a=h(0,o,r,u);try{rs(n(a),c,d)}catch(e){d(e)}}var p=Vh(e);if(null==r)d(new Error("No available storage factory"));else if(p.isOpen()){var m=h(0,p.openHdl(),null,!1);rs(n(m),c,d)}else{var f=r.open(e,i);f.onblocked=function(i){Fh(t,e,"Db Open Blocked event ["+l+"] - "+(f.error||"")),d(new Error(Rh))},f.onerror=function(i){Fh(t,e,"Db Open Error event ["+l+"] - "+(f.error||"")),d(new Error(Rh))},f.onupgradeneeded=function(t){xh(e,"Db Open Create/Upgrade needed event ["+l+"]");try{var i=t.target[Ph];if(!i)return void d(new Error(Rh));!function(e,t){var i=h(0,e,t,!0,!0);if(s)u=!0,ns(s(i),(function(e){if(e.rejected)try{t.transaction&&t.transaction.abort()}finally{d(e.reason)}else i.txn||(i.txn=t.transaction)}));else try{t.transaction&&t.transaction.abort()}finally{d(new Error("DBError: Database upgrade required"))}}(i,f)}catch(t){Uh(e,Rh,d,l)(t)}},f.onsuccess=function(e){var t=e.target[Ph];t?g(t,f):d(new Error(Rh))}}}))}))},e.closeDb=function(e){l(e,"closeDb",(function(t){var i=Vh(e),n=i.dbHdl,r=n.length;if(r>0){for(var s=0;s<r;s++)n[s].close();i.dbHdl=[]}return 1})).catch((function(e){}))},e.deleteDb=function(e){return null!=r&&l(e,"deleteDb",(function(i){var n=Vh(e),s=n.dbHdl,a=s.length;if(a>0){Fh(t,e,"Db is open ["+a+"] force closing");for(var o=0;o<a;o++)s[o].close();n.dbHdl=[]}return vs((function(n,s){setTimeout((function(){try{xh(e,"["+i+"] starting");var a=r.deleteDatabase(e);a.onerror=function(n){Fh(t,e,"["+i+"] error!!"),s(new Error(Dh))},a.onblocked=function(n){Fh(t,e,"["+i+"] blocked!!"),s(new Error(Dh))},a.onupgradeneeded=function(n){Fh(t,e,"["+i+"] upgrade needed!!"),s(new Error(Dh))},a.onsuccess=function(t){xh(e,"["+i+"] complete"),n(!0)},xh(e,"["+i+"] started")}catch(n){Fh(t,e,"["+i+"] threw - "+n),s(new Error(Dh+" - "+n))}}),0)}))}))},e.getDbDetails=function(e){return l(e,"getDbDetails",(function(t){return null!=r&&r.databases?vs((function(t,i){r.databases().then((function(n){for(var r=0;r<n.length;r++)if(n[r].name===e)return void t(n[r]);i(new Error("DBError: Database does not exist"))}),i)})):bs(new Error("DBError: Feature not supported"))}),2e3)}}))}return e.__ieDyn=1,e}(),$h=function(){function e(t){var i=[],n=null;Nn(e,this,(function(e){e.keyRange=function(){return n},e.parseQuery=function(t){if(i=[],t)for(var r=t.split(";"),s=0;s<r.length;s++){var a=r[s],o=a.indexOf("=");if(-1!==o){var l=a.substring(0,o),c=a.substring(o+1);0===l.indexOf("#")&&(l=l.substring(1),n||(n=IDBKeyRange.bound(c,c+"￿"))),e.startsWith(l,c)}}},e.startsWith=function(e,t){i.push({name:e,value:t,type:0})},e.contains=function(e,t){i.push({name:e,value:t,type:1})},e.isMatch=function(e){if(!i||0===i.length)return!0;if(!e)return!1;for(var t=0;t<i.length;t++){var n=i[t],r=e[n.name];if(r)if(0===n.type){if(0!==r.indexOf(n.value))return!1}else if(1===n.type&&-1===r.indexOf(n.value))return!1}return!0},t&&e.parseQuery(t)}))}return e.__ieDyn=1,e}(),jh=6048e5,Gh="DBError: Unable to add event",qh="Evts",zh="iKey",Wh=Ah;function Kh(){return(new Date).getTime()}function Jh(e){return e.openStore(zh,(function(t){return vs((function(i,n){var r={iKey:e.ctx.iKey,tm:Kh()},s=t.store.put(r);s.onsuccess=function(e){i(s.result.toString())},s.onerror=function(e){n(new Error(Gh))},s.onerror=function(e,t){return function(e){return t(new Error("DBError: Unable to update iKey"))}}(0,n)}))}))}function Yh(e){for(var t=[],i=2;i>=1;i--)for(var n=0;n<e.length;n++){var r=e[n];r&&r.evt.persistence===i&&t.push(r.evt)}return t}function Qh(e){return function(t){return e.continue()}}function Zh(e){var t=e.cursor.delete();return t.onerror=Qh(e),t.onsuccess=Qh(e),1}function Xh(e,t,i){return e.openCursor(qh,t,(function(e,t,n){return i(t)?(n.push(t),Zh(e)):0}))}function eg(e,t){return vs((function(i,n){(function(e){return vs((function(t,i){var n=!1;e.openCursor(zh,null,(function(e,t,i){var r=t.tm;return Kh()-r<jh?0:(n=!0,2)})).then((function(){if(n){var r={};Xh(e,null,(function(e){if(!e||!e.evt||!e.evt.iKey)return!0;var t=e.tm;return Kh()-t>jh||(r[e.evt.iKey]=1,!1)})).then((function(){var n=[];e.openCursor(zh,null,(function(e,t,i){var s=t.tm;return Kh()-s<jh||r[t.iKey]?0:(n.push(t),Zh(e))})).then((function(){t(n)}),i)}),i)}else t([])}),i)}))})(e).then((function(){(function(e,t){return e.openCursor(qh,"#key="+e.ctx.iKeyPrefix(),(function(i,n){var r=n.key;if(0===r.indexOf(e.ctx.iKeyPrefix())&&-1===r.indexOf(e.ctx.evtKeyPrefix())&&function(e,t){var i=e.tm;return Kh()-i>t}(n,t)){n.key=e.ctx.evtKeyPrefix()+n.id;var s=i.store.store.put(n);return s.onerror=Qh(i),s.onsuccess=function(e){try{Zh(i)}catch(e){i.continue()}},1}return 0}))})(e,t).then(i,i)}),n)}))}var tg=function(){function e(t,i){Nn(e,this,(function(e){var n=null,r=null,s="Unknown",a=null,o=null,l=null,c=-1,d=0,u=6e5;function h(e){return n.openDb(r,1,(function(t){return vs((function(i,n){var r={iKey:s,storageId:a,iKeyPrefix:function(){return o},evtKeyPrefix:function(){return l}};t.ctx=r,rs(Jh(t),(function(){rs(e(t),i,n)}),n)}))}),(function(e){return vs((function(t,i){(function(e){e.objectStoreNames.contains(qh)||e.createObjectStore(qh,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),e.objectStoreNames.contains(zh)||e.createObjectStore(zh,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})})(e.db),t()}))}))}function g(e,t,i){return vs((function(n,r){function s(t,i){(function(e,t){return vs((function(i,n){var r=0,s=e.ctx.evtKeyPrefix();function a(){i(r)}function o(e,t){return vs((function(i){var n=e.store.delete(t.key);n.onsuccess=function(e){r++,i()},n.onerror=function(e){i()}}))}e.openCursor(qh,"#key="+s,(function(e,i,n){return i.evt.persistence<=t&&0===i.key.indexOf(s)&&(function(e,t){for(var i=0;i<e.length;i++)if(t.tm<e[i].tm)return void e.splice(i,0,t);e.push(t)}(n,i),n.length>10&&n.splice(n.length-1,1)),0})).then((function(t){0!==t.length?e.openStore(qh,(function(e){for(var i=[],n=0;n<t.length;n++)i.push(o(e,t[n]));return Ts(i).then(a,a)})):a()}),(function(){i(0)}))}))})(e,t).then((function(e){e>0&&(d-=e),i(e)}),(function(e){i(0)}))}function a(e){n(t.evt)}function o(){e.openStore(qh,(function(o){var l=o.store.put(t);l.onsuccess=function(r){i&&Jh(e).then(a,a),d++,n(t.evt)},l.onerror=function(a){function o(i){0===i&&r(new Error(Gh)),g(e,t,!1).then((function(e){n(t.evt)}),(function(){r(new Error(Gh))}))}i?s(1,(function(e){e>0?o(e):t.evt.persistence>=2?s(2,(function(e){o(e)})):r(new Error(Gh))})):r(new Error(Gh))}}))}c>0&&d>=c?s(1,(function(e){0===e?t.evt.persistence>=2?s(2,(function(e){o()})):r(new Error(Gh)):o()})):o()}))}e.id=t,e.initialize=function(t){var d=t.itemCtx.diagLog();if(!(n=new Hh(d)).isAvailable())return n=null,!1;var g=t.itemCtx.getCfg(),p=t.storageConfig;s=g.instrumentationKey||s,a=e.id||t.id||rh(),l=(o=s+"::")+a+"::",u=p.accessThresholdInMs||u;var m=Vu(p,(function(){c=p.maxStorageItems;var t=p.indexedDbName;r&&t!==r&&r&&ns(e.clear(),(function(e){r=t,h((function(e){return e.isNew?[]:eg(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null}))})),r=t}));return i&&i.add(m),h((function(e){return e.isNew?[]:eg(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null})),!0},e._getDbgPlgTargets=function(){return[r]},e.supportsSyncRequests=function(){return!1},e.getAllEvents=function(){return null!=n&&n.isAvailable()?h((function(e){return vs((function(t,i){(function(e,t){return e.openCursor(qh,t,(function(e,t,i){return i.push(t),0}))})(e,"#key="+e.ctx.evtKeyPrefix()).then((function(e){d=e.length,t(Yh(e))}),i)}))})):[]},e.addEvent=function(e,t,i){return null!=n&&n.isAvailable()?(t.id=t.id||rh(),Wh(t.persistence)||(t.persistence=1),h((function(i){var n=e||t.id,r={key:i.ctx.evtKeyPrefix()+n,id:n,evt:t,tm:Kh(),v:1};return g(i,r,!0)}))):t},e.removeEvents=function(e){if(null==n||!n.isAvailable())return[];var t=[];return vs((function(i,n){h((function(i){return i.openCursor(qh,"#key="+i.ctx.iKey,(function(i,n,r){if(-1!==function(e,t){for(var i=t.length,n=0;n<i;n++)if(e===t[n].id)return n;return-1}(n.id,e)){var s=i.cursor.delete();return s.onerror=Qh(i),s.onsuccess=function(){t.push(n.evt),i.continue()},1}return 0}))})).then((function(e){d-=t.length,i(t)}),(function(e){d-=t.length,i(t)}))}))},e.clear=function(){return null!=n&&n.isAvailable()?vs((function(e,t){h((function(e){return Xh(e,"#key="+e.ctx.evtKeyPrefix(),(function(t){return 0===t.key.indexOf(e.ctx.evtKeyPrefix())}))})).then((function(t){d=0,e(Yh(t))}),t)})):[]},e.moveStaleEvents=function(){h((function(e){return eg(e,u)}))},e.teardown=function(){n&&n.closeDb(r)}}))}return e.__ieDyn=1,e}(),ig="Version";function ng(e,t){if(e)for(var i=Pt(e),n=0;n<i.length;n++){var r=i[n];if(!t(e[r],r))break}}function rg(e){var t=!0;return ng(e,(function(e,i){return e&&(t=!1),t})),t}function sg(e,t){for(var i=1,n=0,r=function(){var e=[],r=t[i];if(ng(r,(function(t,i){return e.push(i),++n<10})),n>0){for(var s=0;s<e.length;s++)delete r[e[s]];return{value:!0}}i++};i<=e&&n<10;){var s=r();if("object"==typeof s)return s.value}return n>0}var ag=Ah,og=function(){function e(t,i,n){Nn(e,this,(function(e){var r=null,s="AWTEvents",a=null,o=null,l=null,c=5e6,d=6e5,u=null,h=null;function g(e,t){return{key:e,db:t}}function p(e,t){void 0===t&&(t=!0);var i=null;if(r){var n=r.getItem(e);if(n)try{i=JSON.parse(n)}catch(t){r.removeItem(e)}}return t&&!i&&(i={events:{1:{},2:{},3:{}},lastAccessTime:0}),g(e,i)}function m(e,t){void 0===t&&(t=!0);var i=!0,n=e.db;if(n){t&&(n.lastAccessTime=(new Date).getTime());for(var s=1;s<=2;s++)if(!rg(n.events[s])){i=!1;break}}try{if(i)r&&r.removeItem(e.key);else{var a=JSON.stringify(n);if(a.length>c)return!1;r&&r.setItem(e.key,a)}}catch(e){return!1}return!0}function f(e){var t=[],i=p(e,!1),n=i.db;if(n){var s=n.events;try{for(var a=1;a<=2;a++)ng(s[a],(function(e,i){return e&&t.push(e),!0}))}catch(e){}r&&r.removeItem(i.key)}return t}function v(){if(r){for(var e=r.getItem(u),t=[],i=p(h),n=!1,a=0;a<r.length;a++){var o=r.key(a);if(0===o.indexOf(s)&&o!==u){if("3"!==e){t.push(g(o,null));continue}var c=p(o,!1),f=c.db;if(f){if((new Date).getTime()-f.lastAccessTime>d){for(var v=1,S=function(){var e=f.events[v],t=i.db.events[v];ng(e,(function(i,n){return(bh(i.iKey)||i.iKey)===l&&(t[n]=i,delete e[n]),!0})),v++};v<=2;)S();n=!0,t.push(c)}}else t.push(g(o,null))}}for(a=0;a<t.length;a++)m(t[a],!1);n&&m(i),r.setItem(u,"3")}}e.id=i,r=function(e){var t=ti()||{},i=null;try{if(i=t[e]){var n="__storage_test__";i.setItem(n,n),i.removeItem(n)}}catch(e){(function(e,t){var i=!1;return t instanceof DOMException&&(22!==t.code&&"QuotaExceededError"!==t.name&&1014!==t.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||e&&0!==e.length&&(i=!0)),i})(i,e)||(i=null)}return i}(t)||null,e._getDbgPlgTargets=function(){return[s,c]},e.initialize=function(t){if(!r)return!1;var i=t.storageConfig;a=e.id||t.id||rh(),o=t.itemCtx.getCfg().instrumentationKey,l=bh(o)||o,d=i.accessThresholdInMs?i.accessThresholdInMs:d;var g=Vu(i,(function(){c=i.maxStorageSizeInBytes;var t=i.storageKey;s&&t!==s&&ns(e.clear(),(function(e){h=(s=t)+"."+a,u=s+ig,v()}))}));return n&&n.add(g),s=i.storageKey,h=s+"."+a,u=s+ig,v(),!0},e.supportsSyncRequests=function(){return!0},e.getAllEvents=function(){try{var e=[],t=p(h,!1).db;if(t)for(var i=t.events,n=2;n>=1;n--)ng(i[n],(function(t){return t&&(bh(t.iKey)||t.iKey)===l&&e.push(t),!0}));return e}catch(e){return bs(e)}},e.addEvent=function(e,t,i){try{var n=p(h);t.id=t.id||rh(),ag(t.persistence)||(t.persistence=1);for(var r=t.persistence,s=t.id,a=n.db.events;;){if(a[r][s]=t,m(n))return t;if(delete a[r][s],!sg(r,a))return bs(new Error("Unable to free up event space"))}}catch(e){return bs(e)}},e.removeEvents=function(e){try{var t=p(h,!1),i=t.db;if(i){var n=i.events;try{for(var r=0;r<e.length;++r){var s=e[r];delete n[s.persistence][s.id]}if(m(t))return e}catch(e){}e=f(t.key)}return e}catch(e){return bs(e)}},e.clear=function(){try{var e=[],t=p(h,!1),i=t.db;if(i){for(var n=i.events,r=function(t){var i=n[t];ng(i,(function(t){return t&&(bh(t.iKey)||t.iKey)===l&&(delete i[t.id],e.push(t)),!0}))},s=2;s>=1;s--)r(s);m(t)}return e}catch(e){return bs(e)}},e.teardown=function(){try{var e=p(h,!1),t=e.db;t&&(t.lastAccessTime=0,m(e,!1))}catch(e){}},e.moveStaleEvents=function(){v()}}))}return e.__ieDyn=1,e}(),lg=Ah,cg=Rt({maxStorageSizeInBytes:{isVal:wh,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:lg,v:1},providers:[_h.LocalStorage,_h.IndexedDb],indexedDbName:"AppInsightEvents.1",maxStorageItems:{isVal:wh,v:void 0}}),dg=function(e){function t(){var i=e.call(this)||this;return i.identifier="LocalStorage",i.priority=1009,i.version="4.3.1",Nn(t,i,(function(e,t){var i,n,r,s;function a(){i=!1,n=!1,r=null,s=[]}function o(e,t){r||(r=Fs(vs,"LocalStorage")),r.queue((function(e){return t(e)}),e).catch((function(e){}))}function l(t){nh(e.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){o("sendToNext",(function(i){return ns(t.provider.getAllEvents(),(function(i){for(var n=i.value||[],r=0;r<n.length;r++)try{var s=n[r];(bh(s.iKey)||s.iKey)===t.tenantId&&e.processNext(s,t.coreRootCtx.createNew())}catch(e){}}))}))}),(function(){return{iKeyConfig:t}}))}function c(t,i){nh(e.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){o("removeEvents",(function(e){var n=[];if(Ti(i,(function(e){(bh(e.iKey)||e.iKey)===t.tenantId&&n.push(e)})),n.length>0)return ns(t.provider.removeEvents(n),(function(e){}))}))}),(function(){return{iKeyConfig:t,events:i}}))}function d(t){var i=new tg(void 0,e._unloadHooks);return i.initialize(t)||(i=null),i}function u(t,i){var n=new og(t,void 0,e._unloadHooks);return n.initialize(i)||(n=null),n}function h(e){for(var t=e.storageConfig.providers,i=null,n=0;!i&&n<t.length&&n<5;)switch(t[n++]){case _h.LocalStorage:i=u("localStorage",e);break;case _h.SessionStorage:i=u("sessionStorage",e);break;case _h.IndexedDb:i=d(e)}return i}function g(t,i,n,r){var a=!1;if(Ti(s,(function(e){if(e.iKey===t.instrumentationKey)return a=!0,-1})),!a){var o=null;e._addHook(Vu(t,(function(n){var r=gh(null,n.cfg,i);o=r.getExtCfg(e.identifier,cg);var a=!1,d=null,u=t.instrumentationKey;if(Ti(s,(function(e){if(e.iKey===u)return a=!0,d=e,-1})),a&&d){var p=o.providers,m=d.preProviders;(function(e,t){if(e.length!==t.length)return!1;var i=!0;return Ti(e,(function(e,n){if(e!==t[n])return i=!1,-1})),i})(p,m)||ns(g.clear(),(function(e){if(!e.rejected)try{var t=s.indexOf(d);-1!==t&&s.splice(t,1);var n=h(d.providerContext);d.provider=n,d.preProviders=p.slice();var r=d.preListener;r&&i.removeNotificationListener(r);var a={eventsSent:function(e){c(d,e)},eventsDiscarded:function(e,t){c(d,e)}};d.preListener=a,s.push(d),i.addNotificationListener(a),l(d)}catch(e){}}))}})));var d=function(t,i,n,r){t&&(t.extensionConfig=t.extensionConfig||[]),!r&&i&&(r=i.getProcessTelContext().getNext());var s=null,a=e._getTelCtx().getNext();return a&&(s=a.getPlugin()),gh(r,t,i,s)}(t,i,0,r),u={itemCtx:d,storageConfig:o,id:e.id};if(!tt(t.instrumentationKey))return;var g=h(u),p={iKey:t.instrumentationKey,tenantId:bh(t.instrumentationKey)||t.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:d,providerContext:u,provider:g,preProviders:o.providers.slice()};if(g){lg(o.minPersistenceLevel||-1)&&(p.minPersistenceCacheLevel=o.minPersistenceLevel);var m={eventsSent:function(e){c(p,e)},eventsDiscarded:function(e,t){c(p,e)}};p.preListener=m,s.push(p),i.addNotificationListener(m),l(p)}else s.push(p)}}a(),e.initialize=function(e,n,s,a){nh(n,(function(){return"LocalStorageChannel.initialize"}),(function(){i||(t.initialize(e,n,s),t.setInitialized(!1),i=!0,r=Fs(vs,"LocalStorage")),g(e,n,0,a)}),(function(){return{coreConfig:e,core:n,extensions:s,pluginChain:a}}))},e.processTelemetry=function(t,r){var a=t;if(i&&!n){r=e._getTelCtx(r),function(e,t){var i=e;i[Th]=i[Th]||{},i[Th][Eh]=i[Th][Eh]||{},i[Th][Eh][t]=Ih()}(t,e.identifier);var l=null;Ti(s,(function(e){e.iKey===t.iKey&&(l=e)}));var c=l?l.provider:null;if(a.sync||!c)return void e.processNext(a,r);a.id=a.id||rh(),Ah(a.persistence)||(a.persistence=1),function(e,t){return!(t.sync||t.persistence<e.minPersistenceCacheLevel)}(l,a)&&o("processTelemetry",(function(e){return c.addEvent(a.id,a,r)}))}e.processNext(a,r)},e.pause=function(){n=!0},e.resume=function(){nh(e.core,(function(){return"LocalStorageChannel:resume"}),(function(){n=!1,Ti(s,(function(e){e.provider&&l(e)}))}))},e._doTeardown=function(e,t){Ti(s,(function(e){var t=e.provider;t&&t.teardown()})),a()},e.flush=function(e,t,i){},e._getDbgPlgTargets=function(){return[s]},e._sendStale=function(e){Ti(s,(function(t){if(t&&t.iKey===e&&t.provider)return t.provider.moveStaleEvents(),l(t),-1}))}})),i}return tn(t,e),t.__ieDyn=1,t}(Ch),ug="REAL_TIME",hg="",gg="drop",pg="requeue",mg="no-cache, no-store",fg="application/x-json-stream",vg="cache-control",Sg="content-type",yg="client-version",Cg="client-id",Tg="time-delta-to-apply-millis",Eg="upload-time",bg="apikey",_g="AuthMsaDeviceTicket",Ig="WebAuthToken",wg="AuthXToken",Ag="msfpc",Pg="trace",Rg="user",Mg="allowRequestSending",Dg="firstRequestSent",kg="shouldAddClockSkewHeaders",Og="getClockSkewHeaderValue",Ng="setClockSkew",Lg="length",xg="concat",Fg="iKey",Ug="count",Bg="events",Vg="push",Hg="split",$g="splice",jg="toLowerCase",Gg="hdrs",qg="useHdrs",zg="initialize",Wg="setTimeoutOverride",Kg="clearTimeoutOverride",Jg="overrideEndpointUrl",Yg="avoidOptions",Qg="enableCompoundKey",Zg="disableXhrSync",Xg="disableFetchKeepAlive",ep="useSendBeacon",tp="fetchCredentials",ip="alwaysUseXhrOverride",np="serializeOfflineEvt",rp="getOfflineRequestDetails",sp="createPayload",ap="createOneDSPayload",op="payloadBlob",lp="headers",cp="_thePayload",dp="urlString",up="batches",hp="sendType",gp="addHeader",pp="canSendRequest",mp="sendQueuedRequests",fp="isCompletelyIdle",vp="setUnloading",Sp="sendSynchronousBatch",yp="_transport",Cp="getWParam",Tp="isBeacon",Ep="timings",bp="isTeardown",_p="isSync",Ip="data",wp="_sendReason",Ap="setKillSwitchTenants",Pp="_backOffTransmission",Rp="identifier",Mp="eventsLimitInMem",Dp="autoFlushEventsLimit",kp="baseData",Op="sendAttempt",Np="latency",Lp="sync";function xp(e){var t=(e.ext||{}).intweb;return t&&Qc(t[Ag])?t[Ag]:null}function Fp(e){for(var t=null,i=0;null===t&&i<e[Lg];i++)t=xp(e[i]);return t}var Up=function(){function e(t,i){var n=i?[][xg](i):[],r=this,s=Fp(n);r[Fg]=function(){return t},r.Msfpc=function(){return s||hg},r[Ug]=function(){return n[Lg]},r[Bg]=function(){return n},r.addEvent=function(e){return!!e&&(n[Vg](e),s||(s=xp(e)),!0)},r[Hg]=function(i,r){var a;if(i<n[Lg]){var o=n[Lg]-i;Xe(r)||(o=r<o?r:o),a=n[$g](i,o),s=Fp(n)}return new e(t,a)}}return e.create=function(t,i){return new e(t,i)},e}(),Bp=function(){function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",s=!1;Nn(e,this,(function(e){e[Mg]=function(){return t},e[Dg]=function(){n&&(n=!1,s||(t=!1))},e[kg]=function(){return i},e[Og]=function(){return r},e[Ng]=function(e){s||(e?(r=e,i=!0,s=!0):i=!1,t=!0)}}))}return e.__ieDyn=1,e}(),Vp=function(){function e(){var t={};Nn(e,this,(function(e){e[Ap]=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&Ti(e,(function(e){t[Vg](Ni(e))})),t}(e[Hg](","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),s=0;s<n[Lg];++s)t[n[s]]=Ri()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=Ni(e);return void 0!==i[n]&&i[n]>Ri()||(delete i[n],!1)}}))}return e.__ieDyn=1,e}();function Hp(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)}var $p,jp=2e6,Gp=Math.min(jp,65e3),qp="metadata",zp="f",Wp=/\./,Kp=function(){function e(t,i,n,r,s,a){var o="data",l="baseData",c=!!r,d=!0,u=i,h={},g=!!a,p=s||Zc;Nn(e,this,(function(e){function i(e,t){var i=h[e];return void 0===i&&(e.length>=7&&(i=Wi(e,"ext.metadata")||Wi(e,"ext.web")),h[e]=i),i}function r(e,t,s,a,o,l,d){pt(e,(function(e,h){var g=null;if(h||Qc(h)){var p=s,m=e,f=o,v=t;if(c&&!a&&Wp.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var T=S[C];v=v[T]=v[T]||{},p+="."+T,f&&f.push(T)}m=S[y-1]}}if(g=a&&i(p)||!u||!u.handleField(p,m)?function(e,t,i){if(!t&&!Qc(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||rt(t))t={value:t};else if("object"!==n||Jc.call(t,"value")){if(Xe(t[Gc])||t[Gc]===Fc||!tt(t[Gc])&&!at(t[Gc])&&!ot(t[Gc])&&!rt(t[Gc]))return null}else t={value:i?JSON.stringify(t):t};if(rt(t[Gc])&&!function(e){return e[zc]>0}(t[Gc]))return null;if(!Xe(t[qc])){if(rt(t[Gc])||!function(e){return 0===e||e>0&&e<=13||32===e}(t[qc]))return null;t[Gc]=t[Gc].toString()}return t}(m,h,n):u.value(p,m,h,n)){var E=g.value;if(v[m]=E,l&&l(f,m,g),d&&"object"==typeof E&&!rt(E)){var b=f;b&&(b=b.slice()).push(m),r(h,E,p+"."+m,a,b,l,d)}}}}))}e.createPayload=function(e,t,i,n,r,s){return{apiKeys:[],payloadBlob:hg,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendType:s,sendReason:r}},e.appendPayload=function(i,n,r){var s=i&&n&&!i.overflow;return s&&bl(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),s=i.payloadBlob,a=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?Gp:jp,g=0,p=0;g<t.length;){var m=t[g];if(m){if(a>=r){i.overflow=n.split(g);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(s.length+v>u){i.overflow=n.split(g);break}s&&(s+="\n"),s+=f,++p>20&&($t(s,0,1),p=0),o=!0,a++}else f?l.push(m):c.push(m),t.splice(g,1),g--}g++}if(l.length>0&&i.sizeExceed.push(Up.create(n.iKey(),l)),c.length>0&&i.failedEvts.push(Up.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=s,i.numEvents=a;var S=n.iKey();-1===Ei(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),s},e.getEventBlob=function(e){try{return bl(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+function(e){if(e){var t=zi(e,"-");if(t>-1)return jt(e,t)}return Fc}(e.iKey);var i,n={};g||(i=function(e,t,i){!function(e,t,i,n,r){if(r&&t){var s=e(r.value,r.kind,r.propertyType);if(s>-1){var a=t[qp];a||(a=t[qp]={f:{}});var o=a[zp];if(o||(o=a[zp]={}),i)for(var l=0;l<i.length;l++){var c=i[l];o[c]||(o[c]={f:{}});var d=o[c][zp];d||(d=o[c][zp]={}),o=d}o=o[n]={},rt(r.value)?o.a={t:s}:o.t=s}}}(p,n,e,t,i)});var s=e.ext;s&&(t.ext=n,pt(s,(function(e,t){r(t,n[e]={},"ext."+e,!0,null,null,!0)})));var a=t[o]={};a.baseType=e.baseType;var c=a[l]={};return r(e.baseData,c,l,!1,[l],i,d),r(e.data,a,o,!1,[],i,d),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))}return e.__ieDyn=1,e}();function Jp(e,t){return{set:function(i,n){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return function(e,t,i){return Qi(!0,e,Ke[Be](arguments,1))}([e,t],i,n,r)}}}var Yp="sendAttempt",Qp="?cors=true&"+Sg[jg]()+"="+fg,Zp=(($p={})[1]=pg,$p[100]=pg,$p[200]="sent",$p[8004]=gg,$p[8003]=gg,$p),Xp={},em={};function tm(e,t,i){Xp[e]=t,!1!==i&&(em[t]=e)}function im(e,t){var i=!1;if(e&&t){var n=Pt(e);if(n&&n[Lg]>0)for(var r=t[jg](),s=0;s<n[Lg];s++){var a=n[s];if(a&&ht(t,a)&&a[jg]()===r){i=!0;break}}}return i}function nm(e,t,i,n){t&&i&&i[Lg]>0&&(n&&Xp[t]?(e[Gg][Xp[t]]=i,e[qg]=!0):e.url+="&"+t+"="+i)}tm(_g,_g,!1),tm(yg,yg),tm(Cg,"Client-Id"),tm(bg,bg),tm(Tg,Tg),tm(Eg,Eg),tm(wg,wg);var rm=function(){function e(t,i,n,r){var s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x,F=!1;Nn(e,this,(function(e){function U(e,t){try{return L&&L.getSenderInst(e,t)}catch(e){}return null}function B(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!1,fetchCredentials:x,disableXhr:!1,disableBeacon:!F,disableBeaconSync:!F,disableFetchKeepAlive:I,timeWrapper:O,addNoResponse:A,senderOnCompleteCallBack:{xdrOnComplete:V,fetchOnComplete:H,xhrOnComplete:$,beaconOnRetry:G}}}catch(e){}return null}function V(e,t,i){var n=fa(e);j(t,200,{},n),re(n)}function H(e,t,i,n){var r={},s=e[lp];s&&s.forEach((function(e,t){r[t]=e})),function(e,i,n){j(t,e,i,n),re(n)}(e.status,r,i||hg)}function $(e,t,i){var n=fa(e);j(t,e.status,Ta(e,!0),n),re(n)}function j(e,t,i,n){try{e(t,i,n)}catch(e){Bo(u,2,518,bt(e))}}function G(e,t,i){var n=200,r=e[cp],s=e[dp]+(A?"&NoResponseBody=true":hg);try{var a=ci();if(r){var o=!!g.getPlugin("LocalStorage"),l=[],c=[];Ti(r[up],(function(e){if(l&&e&&e[Ug]()>0)for(var t=e[Bg](),i=0;i<t[Lg];i++){if(!a.sendBeacon(s,S.getEventBlob(t[i]))){l[Vg](e[Hg](i));break}c[Vg](e[i])}else l[Vg](e[Hg](0))})),c[Lg]>0&&(r.sentEvts=c),o||se(l,8003,r[hp],!0)}else n=0}catch(e){Vo(u,"Failed to send telemetry using sendBeacon API. Ex:"+bt(e)),n=0}finally{j(t,n,{},hg)}}function q(e){return 2===e||3===e}function z(e){return T&&q(e)&&(e=2),e}function W(){return!o&&c<i}function K(){var e=v;return v=[],e}function J(e,t,i){var n=!1;return e&&e[Lg]>0&&!o&&h[t]&&S&&(n=0!==t||W()&&(i>0||l[Mg]())),n}function Y(e){var t={};return e&&Ti(e,(function(e,i){t[i]={iKey:e[Fg](),evts:e[Bg]()}})),t}function Q(e,i,n,r,s){if(e&&0!==e[Lg])if(o)se(e,1,r);else{r=z(r);try{var l=e,c=0!==r;bl(g,(function(){return"HttpManager:_sendBatches"}),(function(o){o&&(e=e.slice(0));for(var l=[],d=null,u=id(),g=h[r]||(c?h[1]:h[0]),p=g&&g[yp],m=w&&(T||q(r)||3===p||g._isSync&&2===p);J(e,r,i);){var f=e.shift();f&&f[Ug]()>0&&(a.isTenantKilled(f[Fg]())?l[Vg](f):(d=d||S[sp](i,n,c,m,s,r),S.appendPayload(d,f,t)?null!==d.overflow&&(e=[d.overflow][xg](e),d.overflow=null,ee(d,u,id(),s),u=id(),d=null):(ee(d,u,id(),s),u=id(),e=[f][xg](e),d=null)))}d&&ee(d,u,id(),s),e[Lg]>0&&(v=e[xg](v)),se(l,8004,r)}),(function(){return{batches:Y(l),retryCount:i,isTeardown:n,isSynchronous:c,sendReason:s,useSendBeacon:q(r),sendType:r}}),!c)}catch(e){Bo(u,2,48,"Unexpected Exception sending batch: "+bt(e))}}}function Z(e,t){var i={url:s,hdrs:{},useHdrs:!1};t?(i[Gg]=td(i[Gg],f),i.useHdrs=Pt(i.hdrs)[Lg]>0):pt(f,(function(e,t){em[e]?nm(i,em[e],t,!1):(i[Gg][e]=t,i[qg]=!0)})),nm(i,Cg,"NO_AUTH",t),nm(i,yg,Kc,t);var n=hg;Ti(e.apiKeys,(function(e){n[Lg]>0&&(n+=","),n+=e})),nm(i,bg,n,t),nm(i,Eg,Ri().toString(),t);var r=function(e){for(var t=0;t<e.batches[Lg];t++){var i=e[up][t].Msfpc();if(i)return encodeURIComponent(i)}return hg}(e);if(Qc(r)&&(i.url+="&ext.intweb.msfpc="+r),l[kg]()&&nm(i,Tg,l[Og](),t),g[Cp]){var a=g[Cp]();a>=0&&(i.url+="&w="+a)}for(var o=0;o<m[Lg];o++)i.url+="&"+m[o].name+"="+m[o].value;return i}function X(e,t,i){e[t]=e[t]||{},e[t][d.identifier]=i}function ee(e,t,i,n){if(e&&e.payloadBlob&&e.payloadBlob[Lg]>0){var r=!!R,s=h[e.sendType];!q(e[hp])&&e[Tp]&&2===e.sendReason&&(s=h[2]||h[3]||s);var a=E;(e.isBeacon||3===s[yp])&&(a=!1);var o=Z(e,a);a=a||o[qg];var d=id();bl(g,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var h=0;h<e.batches[Lg];h++)for(var m=e[up][h][Bg](),f=0;f<m[Lg];f++){var v=m[f];if(y){var S=v[Ep]=v[Ep]||{};X(S,"sendEventStart",d),X(S,"serializationStart",t),X(S,"serializationCompleted",i)}v[Yp]>0?v[Yp]++:v[Yp]=1}se(e[up],1e3+(n||0),e[hp],!0);var C={data:e[op],urlString:o.url,headers:o[Gg],_thePayload:e,_sendReason:n,timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};a&&(im(C[lp],vg)||(C[lp][vg]=mg),im(C[lp],Sg)||(C[lp][Sg]=fg));var T=null;s&&(T=function(t){l[Dg]();var i=function(t,i){te(t,i,e,n)},r=e[bp]||e[_p];try{s.sendPOST(t,i,r),M&&M(C,t,r,e[Tp])}catch(e){Vo(u,"Unexpected exception sending payload. Ex:"+bt(e)),j(i,0,{})}}),bl(g,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(T)if(0===e[hp]&&c++,r&&!e.isBeacon&&3!==s[yp]){var t={data:C[Ip],urlString:C[dp],headers:td({},C[lp]),timeout:C.timeout,disableXhrSync:C[Zg],disableFetchKeepAlive:C[Xg]},i=!1;bl(g,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{R(t,(function(e){i=!0,p||e[cp]||(e[cp]=e[cp]||C[cp],e[wp]=e[wp]||C[wp]),T(e)}),e.isSync||e[bp])}catch(e){i||T(C)}}))}else T(C)}))}),(function(){return{thePayload:e,serializationStart:t,serializationCompleted:i,sendReason:n}}),e[_p])}e.sizeExceed&&e.sizeExceed[Lg]>0&&se(e.sizeExceed,8003,e[hp]),e.failedEvts&&e.failedEvts[Lg]>0&&se(e.failedEvts,8002,e[hp])}function te(e,t,i,r){var s=9e3,o=null,d=!1,u=!1;try{var h=!0;if(typeof e!==Te){if(t){l[Ng](t["time-delta-millis"]);var g=t["kill-duration"]||t["kill-duration-seconds"];Ti(a[Ap](t["kill-tokens"],g),(function(e){Ti(i[up],(function(t){if(t[Fg]()===e){o=o||[];var n=t[Hg](0);i.numEvents-=n[Ug](),o[Vg](n)}}))}))}if(200==e||204==e)return void(s=200);(!function(e){return!(e>=300&&e<500&&429!=e||501==e||505==e)}(e)||i.numEvents<=0)&&(h=!1),s=9e3+e%1e3}if(h){s=100;var p=i.retryCnt;0===i[hp]&&(p<n?(d=!0,ne((function(){0===i[hp]&&c--,Q(i[up],p+1,i[bp],T?2:i[hp],5)}),T,Hp(p))):(u=!0,T&&(s=8001)))}}finally{d||(l[Ng](),ie(i,s,r,u)),se(o,8004,i[hp])}}function ie(t,i,n,r){try{r&&d[Pp]();var s=t[up];200===i&&(s=t.sentEvts||t[up],r||t[_p]||d._clearBackOff(),function(e){if(y){var t=id();Ti(e,(function(e){e&&e[Ug]()>0&&function(e,t){y&&Ti(e,(function(e){X(e[Ep]=e[Ep]||{},"sendEventCompleted",t)}))}(e[Bg](),t)}))}}(s)),se(s,i,t[hp],!0)}finally{0===t[hp]&&(c--,5!==n&&e.sendQueuedRequests(t[hp],n))}}function ne(e,t,i){t?e():O.set(e,i)}function re(e){var t=D;try{for(var i=0;i<t[Lg];i++)try{t[i](e)}catch(e){Bo(u,1,519,"Response handler failed: "+e)}if(e){var n=JSON.parse(e);Qc(n.webResult)&&Qc(n.webResult[Ag])&&C.set("MSFPC",n.webResult[Ag],31536e3)}}catch(e){}}function se(e,t,i,n){if(e&&e[Lg]>0&&r){var s=r[function(e){var t=Zp[e];return Qc(t)||(t="oth",e>=9e3&&e<=9999?t="rspFail":e>=8e3&&e<=8999?t=gg:e>=1e3&&e<=1999&&(t="send")),t}(t)];if(s){var a=0!==i;bl(g,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){ne((function(){try{s.call(r,e,t,a,i)}catch(e){Bo(u,1,74,"send request notification failed: "+e)}}),n||a,0)}),(function(){return{batches:Y(e),reason:t,isSync:a,sendSync:n,sendType:i}}),!a)}}}!function(){var e;s=null,a=new Vp,o=!1,l=new Bp,F=!1,c=0,d=null,u=null,h=null,g=null,p=!0,m=[],f={},v=[],S=null,y=!1,C=null,T=!1,E=!1,b=e,_=e,I=e,w=e,A=e,P=[],R=e,M=e,D=[],k=!1,O=Jp(),N=!1,L=null}(),e[zg]=function(e,t,i){k||(g=t,C=t.getCookieMgr(),u=(d=i).diagLog(),Ci(P,So(e,(function(e){var n,r=e.cfg,a=e.cfg.extensionConfig[i.identifier];O=Jp(a[Wg],a[Kg]),Qc(r.anonCookieName)?function(e,t,i){for(var n=0;n<e[Lg];n++)if(e[n].name===t)return void(e[n].value=i);e[Vg]({name:t,value:i})}(m,"anoncknm",r.anonCookieName):function(e){for(var t=0;t<e[Lg];t++)if("anoncknm"===e[t].name)return void e[$g](t,1)}(m),R=a.payloadPreprocessor,M=a.payloadListener;var o=a.httpXHROverride,l=a[Jg]?a[Jg]:r.endpointUrl;s=l+Qp,E=!!Ze(a[Yg])||!a[Yg],y=!a.disableEventTimings;var c=a.valueSanitizer,d=a.stringifyObjects,f=!!r[Qg];Ze(a[Qg])||(f=!!a[Qg]),b=a.xhrTimeout,_=!!a[Zg],I=!!a[Xg],A=!1!==a.addNoResponse,N=!!a.excludeCsMetaData,t.getPlugin("LocalStorage")&&(I=!0),F=!Da(),S=new Kp(g,c,d,f,Zc,N),Xe(a[ep])||(F=!!a[ep]),a[tp]&&(x=a[tp]);var v=B();L?L.SetConfig(v):(L=new ac)[zg](v,u);var C=o,T=a[ip]?o:null,P=a[ip]?o:null,D=[3,2];if(!o){p=!1;var k=[];Da()?(k=[2,1],D=[2,1,3]):k=[1,2,3],(o=U(k=Sa(k,a.transports),!1))||Vo(u,"No available transport to send events"),C=U(k,!0)}T||(T=U(D=Sa(D,a.unloadTransports),!0)),w=!p&&(F&&Oa()||!I&&Na(!0)),(n={})[0]=o,n[1]=C||U([1,2,3],!0),n[2]=T||C||U([1],!0),n[3]=P||U([2,3],!0)||C||U([1],!0),h=n}))),k=!0)},e.addResponseHandler=function(e){return D[Vg](e),{rm:function(){var t=D.indexOf(e);t>=0&&D[$g](t,1)}}},e[np]=function(e){try{if(S)return S.getEventBlob(e)}catch(e){}return hg},e[rp]=function(){try{return Z(S&&S[sp](0,!1,!1,!1,1,0),E)}catch(e){}return null},e[ap]=function(e,i){try{var n=[];Ti(e,(function(e){i&&(e=ma(e));var t=Up.create(e[Fg],[e]);n[Vg](t)}));for(var r=null;n[Lg]>0&&S;){var s=n.shift();s&&s[Ug]()>0&&(r=r||S[sp](0,!1,!1,!1,1,0),S.appendPayload(r,s,t))}var a=Z(r,E),o={data:r[op],urlString:a.url,headers:a[Gg],timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};return E&&(im(o[lp],vg)||(o[lp][vg]=mg),im(o[lp],Sg)||(o[lp][Sg]=fg)),o}catch(e){}return null},e._getDbgPlgTargets=function(){return[h[0],a,S,h,B()]},e[gp]=function(e,t){f[e]=t},e.removeHeader=function(e){delete f[e]},e[pp]=function(){return W()&&l[Mg]()},e[mp]=function(e,t){Ze(e)&&(e=0),T&&(e=z(e),t=2),J(v,e,0)&&Q(K(),0,!1,e,t||0)},e[fp]=function(){return!o&&0===c&&0===v[Lg]},e[vp]=function(e){T=e},e.addBatch=function(e){if(e&&e[Ug]()>0){if(a.isTenantKilled(e[Fg]()))return!1;v[Vg](e)}return!0},e.teardown=function(){v[Lg]>0&&Q(K(),0,!0,2,2),Ti(P,(function(e){e&&e.rm&&e.rm()})),P=[]},e.pause=function(){o=!0},e.resume=function(){o=!1,e[mp](0,4)},e[Sp]=function(e,t,i){e&&e[Ug]()>0&&(Xe(t)&&(t=1),T&&(t=z(t),i=2),Q([e],0,!1,t,i||0))}}))}return e.__ieDyn=1,e}(),sm=1e4,am="eventsDiscarded",om=void 0,lm=Rt({eventsLimitInMem:{isVal:sd,v:sm},immediateEventLimit:{isVal:sd,v:500},autoFlushEventsLimit:{isVal:sd,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:function(e){return e&&e.sendPOST},v:om},overrideInstrumentationKey:om,overrideEndpointUrl:om,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:om,clearTimeoutOverride:om,payloadPreprocessor:om,payloadListener:om,disableEventTimings:om,valueSanitizer:om,stringifyObjects:om,enableCompoundKey:om,disableOptimizeObj:!1,fetchCredentials:om,transports:om,unloadTransports:om,useSendBeacon:om,disableFetchKeepAlive:om,avoidOptions:!1,xhrTimeout:om,disableXhrSync:om,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:at,v:6},maxUnloadEventRetryAttempts:{isVal:at,v:2},addNoResponse:om,excludeCsMetaData:om}),cm=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="4.3.2";var r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R=!1,M=[],D=!1,k=0,O=0,N={},L=ug;return Nn(t,n,(function(e,t){function n(){(function(e,t){Oc([fc,mc,gc],null,t)})(0,T),function(e,t){var i=Rc(vc,t);Oc([gc],null,i),Oc([hc],null,i)}(0,T),function(e,t){var i=Rc(Sc,t);Oc([pc],null,i),Oc([hc],null,i)}(0,T)}function x(e){var t="";return e&&e[Lg]&&Ti(e,(function(e){t&&(t+="\n"),t+=e})),t}function F(e){var t="";try{V(e),t=u[np](e)}catch(e){}return t}function U(e){"beforeunload"!==(e||li().event).type&&(S=!0,u[vp](S)),K(2,2)}function B(e){S=!1,u[vp](S)}function V(e){e.ext&&e.ext[Pg]&&delete e.ext[Pg],e.ext&&e.ext[Rg]&&e.ext[Rg].id&&delete e.ext[Rg].id,v&&(e.ext=ma(e.ext),e[kp]&&(e[kp]=ma(e[kp])),e[Ip]&&(e[Ip]=ma(e[Ip])))}function H(e,t){if(e[Op]||(e[Op]=0),e[Np]||(e[Np]=1),V(e),e[Lp])if(c||D)e[Np]=3,e[Lp]=!1;else if(u)return v&&(e=ma(e)),void u[Sp](Up.create(e[Fg],[e]),!0===e[Lp]?1:e[Lp],3);var i=e[Np],n=O,r=a;4===i&&(n=k,r=s);var o=!1;if(n<r)o=!Q(e,t);else{var l=1,d=20;4===i&&(l=4,d=1),o=!0,function(e,t,i,n){for(;i<=t;){var r=J(e,t,!0);if(r&&r[Ug]()>0){var s=r[Hg](0,n),a=s[Ug]();if(a>0)return 4===i?k-=a:O-=a,ae(am,[s],Fn.QueueFull),!0}i++}return Z(),!1}(e[Fg],e[Np],l,d)&&(o=!Q(e,t))}o&&se(am,[e],Fn.QueueFull)}function $(e,t,i){var n=X(e,t,i);return u[mp](t,i),n}function j(){return O>0}function G(){if(m>=0&&X(m,0,f)&&u[mp](0,f),k>0&&!l&&!D){var e=N[L][2];e>=0&&(l=z((function(){l=null,$(4,0,1),G()}),e))}var t=N[L][1];!o&&!r&&t>=0&&!D&&(j()?o=z((function(){o=null,$(0===d?3:1,0,1),d++,d%=2,G()}),t):d=0)}function q(){i=null,R=!1,M=[],r=null,D=!1,k=0,s=500,O=0,a=sm,N={},L=ug,o=null,l=null,c=0,d=0,h={},g=0,w=!1,p=0,m=-1,f=null,v=!0,S=!1,y=6,C=2,T=null,A=null,P=!1,E=Jp(),u=new rm(500,2,1,{requeue:ne,send:oe,sent:le,drop:ce,rspFail:de,oth:ue}),ie(),h[4]={batches:[],iKeyMap:{}},h[3]={batches:[],iKeyMap:{}},h[2]={batches:[],iKeyMap:{}},h[1]={batches:[],iKeyMap:{}},he()}function z(e,t){0===t&&c&&(t=1);var i=1e3;return c&&(i=Hp(c-1)),E.set(e,t*i)}function W(){return null!==o&&(o.cancel(),o=null,d=0,!0)}function K(e,t){W(),r&&(r.cancel(),r=null),D||$(1,e,t)}function J(e,t,i){var n=h[t];n||(n=h[t=1]);var r=n.iKeyMap[e];return!r&&i&&(r=Up.create(e),n.batches[Vg](r),n.iKeyMap[e]=r),r}function Y(t,i){u[pp]()&&!c&&(g>0&&O>g&&(i=!0),i&&null==r&&e.flush(t,(function(){}),20))}function Q(e,t){v&&(e=ma(e));var i=e[Np],n=J(e[Fg],i,!0);return!!n.addEvent(e)&&(4!==i?(O++,t&&0===e[Op]&&Y(!e.sync,p>0&&n[Ug]()>=p)):k++,!0)}function Z(){for(var e=0,t=0,i=function(i){var n=h[i];n&&n[up]&&Ti(n[up],(function(n){4===i?e+=n[Ug]():t+=n[Ug]()}))},n=1;n<=4;n++)i(n);O=t,k=e}function X(t,i,n){var r=!1,s=0===i;return!s||u[pp]()?bl(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=4;i>=t;){var n=h[i];n&&n.batches&&n.batches[Lg]>0&&(Ti(n[up],(function(t){u.addBatch(t)?r=r||t&&t[Ug]()>0:e=e[xg](t[Bg]()),4===i?k-=t[Ug]():O-=t[Ug]()})),n[up]=[],n.iKeyMap={}),i--}e[Lg]>0&&se(am,e,Fn.KillSwitch),r&&m>=t&&(m=-1,f=0)}),(function(){return{latency:t,sendType:i,sendReason:n}}),!s):(m=m>=0?Math.min(m,t):t,f=Math.max(f,n)),r}function ee(e,t){$(1,0,t),Z(),te((function(){e&&e(),M[Lg]>0?r=z((function(){r=null,ee(M.shift(),t)}),0):(r=null,G())}))}function te(e){u[fp]()?e():r=z((function(){r=null,te(e)}),.25)}function ie(){(N={})[ug]=[2,1,0],N.NEAR_REAL_TIME=[6,3,0],N.BEST_EFFORT=[18,9,0]}function ne(t,i){var n=[],r=y;S&&(r=C),Ti(t,(function(t){t&&t[Ug]()>0&&Ti(t[Bg](),(function(t){t&&(t[Lp]&&(t[Np]=4,t[Lp]=!1),t[Op]<r?(nd(t,e[Rp]),H(t,!1)):n[Vg](t))}))})),n[Lg]>0&&se(am,n,Fn.NonRetryableStatus),S&&K(2,2)}function re(t,i){var n=I||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){Bo(e.diagLog(),1,74,t+" notification failed: "+i)}}function se(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[Lg]>0&&re(e,[t][xg](i))}function ae(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[Lg]>0&&Ti(t,(function(t){t&&t[Ug]()>0&&re(e,[t.events()][xg](i))}))}function oe(e,t,i){e&&e[Lg]>0&&re("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])}function le(e,t){ae("eventsSent",e,t),G()}function ce(e,t){ae(am,e,t>=8e3&&t<=8999?t-8e3:Fn.Unknown)}function de(e){ae(am,e,Fn.NonRetryableStatus),G()}function ue(e,t){ae(am,e,Fn.Unknown),G()}function he(){p=_?0:Math.max(1500,a/6)}q(),e._getDbgPlgTargets=function(){return[u,i]},e[zg]=function(r,o,l){bl(o,(function(){return"PostChannel:initialize"}),(function(){t[zg](r,o,l),I=o.getNotifyMgr();try{T=Rc(Ja(e[Rp]),o.evtNamespace&&o.evtNamespace()),e._addHook(So(r,(function(t){var r=t.cfg,l=Ul(null,r,o);i=l.getExtCfg(e[Rp],lm),E=Jp(i[Wg],i[Kg]),v=!i.disableOptimizeObj&&!!ii("chrome"),b=i.ignoreMc1Ms0CookieProcessing,function(e){var t=e[Cp];e[Cp]=function(){var i=0;return b&&(i|=2),i|t.call(e)}}(o),a=i[Mp],s=i.immediateEventLimit,g=i[Dp],y=i.maxEventRetryAttempts,C=i.maxUnloadEventRetryAttempts,_=i.disableAutoBatchFlushLimit,he(),A=i.overrideInstrumentationKey,P=!!i.disableTelemetry,w&&n();var c=r.disablePageUnloadEvents||[];w=function(e,t,i){return function(e,t,i,n){var r=!1;return t&&e&&rt(e)&&!(r=kc(e,t,i,n))&&i&&i[Hn]>0&&(r=kc(e,t,null,n)),r}([fc,mc,gc],e,t,i)}(U,c,T),w=Nc(U,c,T)||w,w=Lc(B,r.disablePageShowEvents,T)||w}))),u[zg](r,e.core,e)}catch(t){throw e.setInitialized(!1),t}}),(function(){return{theConfig:r,core:o,extensions:l}}))},e.processTelemetry=function(t,i){nd(t,e[Rp]),i=i||e._getTelCtx(i);var n=t;P||R||(A&&(n[Fg]=A),H(n,!0),S?K(2,2):G()),e.processNext(n,i)},e.getOfflineSupport=function(){try{var e=u&&u[rp]();if(u)return{getUrl:function(){return e?e.url:null},serialize:F,batch:x,shouldProcess:function(e){return!P},createPayload:function(e){return null},createOneDSPayload:function(e){if(u[ap])return u[ap](e,v)}}}catch(e){}return null},e._doTeardown=function(e,t){K(2,2),R=!0,u.teardown(),n(),q()},e.setEventQueueLimits=function(e,t){i[Mp]=a=sd(e)?e:sm,i[Dp]=g=sd(t)?t:0,he();var n=O>e;if(!n&&p>0)for(var r=1;!n&&r<=3;r++){var s=h[r];s&&s[up]&&Ti(s[up],(function(e){e&&e[Ug]()>=p&&(n=!0)}))}Y(!0,n)},e.pause=function(){W(),D=!0,u.pause()},e.resume=function(){D=!1,u.resume(),G()},e._loadTransmitProfiles=function(e){W(),ie(),L=ug,G(),pt(e,(function(e,t){var i=t[Lg];if(i>=2){var n=i>2?t[2]:0;if(t[$g](0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t[Vg](n),N[e]=t}}))},e.flush=function(e,t,i){var n;if(void 0===e&&(e=!0),!D)if(i=i||1,e)t||(n=Is((function(e){t=e}))),null==r?(W(),X(1,0,i),r=z((function(){r=null,ee(t,i)}),0)):M[Vg](t);else{var s=W();$(1,1,i),t&&t(),s&&G()}return n},e.setMsaAuthTicket=function(e){u[gp](_g,e)},e.setAuthPluginHeader=function(e){u[gp](Ig,e)},e.removeAuthPluginHeader=function(){u.removeHeader(Ig)},e.hasEvents=j,e._setTransmitProfile=function(e){L!==e&&void 0!==N[e]&&(W(),L=e,G())},pa(e,(function(){return u}),["addResponseHandler"]),e[Pp]=function(){c<4&&(c++,W(),G())},e._clearBackOff=function(){c&&(c=0,W(),G())}})),n}return tn(t,e),t.__ieDyn=1,t}(Wl),dm=function(e){return function(e){var t={};return pt(e,(function(e,i){Tt(t,e,i[1]),Tt(t,i[0],i[1])})),Dt(t)}(e)};function um(e){return{mrg:!0,v:e}}function hm(e){return{isVal:tt,v:Et(e||"")}}var gm,pm="locale",mm="ver",fm="name",vm=dm({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"]}),Sm=dm({id:[0,"id"],ver:[1,mm],appName:[2,fm],locale:[3,pm],expId:[4,"expId"],env:[5,"env"]}),ym=dm({domain:[0,"domain"],browser:[1,"browser"],browserVer:[2,"browserVer"],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),Cm=dm({locale:[0,pm],localId:[1,"localId"],id:[2,"id"]}),Tm=dm({osName:[0,fm],ver:[1,mm]}),Em=dm({ver:[0,mm],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),bm=dm({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,"serviceName"]}),_m=dm({popSample:[0,"popSample"],eventFlags:[1,"eventFlags"]}),Im=dm({tz:[0,"tz"]}),wm=dm({sessionId:[0,"sesId"]}),Am=dm({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),Pm=dm({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),Rm=dm({traceId:[0,"traceID"],traceName:[1,fm],parentId:[2,"parentID"]}),Mm=dm({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function Dm(){return void 0===gm&&(gm=!!Om(0)),gm}function km(){return Dm()?Om(0):null}function Om(e){var t,i,n=null;try{var r=ti();if(!r)return null;i=new Date,(n=0===e?r.localStorage:r.sessionStorage)&&it(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}function Nm(){return this.getId()}function Lm(e){this.setId(e)}var xm=function(){function e(){Nn(e,this,(function(e){e.setId=function(t){e.customId=t},e.getId=function(){return tt(e.customId)?e.customId:e.automaticId}}))}return e._staticInit=void yt(e.prototype,"id",{g:Nm,s:Lm}),e}(),Fm="ai_session",Um=function(){function e(t,i,n){var r,s,a,o=No(t),l=sl(t);Nn(e,this,(function(t){var c=So(i,(function(){a=i,t.config=a}));function d(){var e=l.get(s());if(e&&it(e.split))u(e);else{var i=function(e,t){var i=km();if(null!==i)try{return i.getItem(t)}catch(t){gm=!1,Bo(e,1,503,"Browser failed read of local storage. "+t)}return null}(o,s());i&&u(i)}t.automaticSession.getId()||h()}function u(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){Bo(o,1,510,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&Bo(o,2,517,"AI session renewal date is 0, session will be reset.")}function h(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid;!Ze(n)&&n?ot(n)?e.setId(ed()):e.setId(ed(n)):e.setId(Ga(a.idLength||22)),e.acquisitionDate=i,e.renewalDate=i,g(e.getId(),e.acquisitionDate,e.renewalDate),Dm()||Bo(o,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function g(e,i,n){var a=i+t.config.sessionExpirationMs,o=n+t.config.sessionRenewalMs,c=new Date,d=[e,i,n];a<o?c.setTime(a):c.setTime(o);var u=t.config.cookieDomain||null;l.set(s(),d.join("|")+";expires="+c.toUTCString(),null,u),r=(new Date).getTime()}n&&n.add(c),s=function(){return t.config.namePrefix?Fm+t.config.namePrefix:Fm},t.automaticSession=new xm,t.update=function(){t.automaticSession.getId()||d();var i=t.automaticSession,n=t.config,s=(new Date).getTime(),a=s-i.acquisitionDate>n.sessionExpirationMs,o=s-i.renewalDate>n.sessionRenewalMs;a||o?h():(!r||s-r>e.cookieUpdateInterval)&&(i.renewalDate=s,g(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;!function(e,t,i){!function(e,t,i){var n=km();if(null!==n)try{return n.setItem(t,i),!0}catch(t){gm=!1,Bo(e,1,504,"Browser failed write to local storage. "+t)}}(o,s(),[e,t,i].join("|"))}(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.cookieUpdateInterval=6e4,e}(),Bm=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function Vm(e,t){void 0===t&&(t=Bm);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)Hm(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function Hm(e,t){if(void 0===t&&(t=Bm),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}function $m(){return this.getExpId()}var jm=function(){function e(t,i,n){var r,s=null,a=Bm.slice(0),o=null;Nn(e,this,(function(e){if(function(t){var s=So(t,(function(){r=i&&i.getCookieMgr(),o=t||{},e.env=o.env||function(e){var t,i={},n=oi();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var s=t[r];s.name&&0===s.name.toLowerCase().indexOf(e)&&(i[s.name.replace(e,"")]=s.content)}}return i}("awa-").env}));n&&n.add(s)}(t),ni()){var l=oi().documentElement;l&&(e.locale=l.lang)}function c(e){e!==s&&(s=Vm(e,a))}e.getExpId=function(){return o.expId?function(e){return c(e),s}(o.expId):(c(Xc(r,"Treatments")),s)}}))}return e.validateAppExpId=Vm,e._staticInit=void yt(e.prototype,"expId",{g:$m}),e}(),Gm=function(){},qm=function(){};function zm(){return this.getMsfpc()}function Wm(){return this.getAnid()}var Km=function(){function e(t,i,n){var r;Nn(e,this,(function(e){(function(t){var s=So(t,(function(){r=i&&i.getCookieMgr();var n=t||{};n.serviceName&&(e.serviceName=n.serviceName)}));n&&n.add(s)})(t),e.getMsfpc=function(){return Xc(r,"MSFPC")},e.getAnid=function(){return Xc(r,"ANON").slice(0,34)}}))}var t;return e._staticInit=(yt(t=e.prototype,"msfpc",{g:zm}),void yt(t,"anid",{g:Wm})),e}(),Jm=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},Ym={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},Qm={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},Zm="([\\d,_,.]+)",Xm="Unknown",ef=[{r:Ym.WINPHONE,os:"Windows Phone"},{r:Ym.WINRT,os:"Windows RT"},{r:Ym.WIN,os:"Windows"},{r:Ym.IOS,os:"iOS"},{r:Ym.ANDROID,os:"Android"},{r:Ym.LINUX,os:"Linux"},{r:Ym.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:Ym.OSX,os:"Mac OS X"}];function tf(e,t){var i=e.match(new RegExp(t+" ([\\d,.]+)"));return i?Qm[i[1]]?Qm[i[1]]:i[1]:Xm}function nf(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null}var rf=function(e,t){var i=null,n=null,r=null,s=null,a=So(e,(function(){if((e||{}).populateOperatingSystemInfo){var t=ci()||{},r=e.userAgent||t.userAgent||"",s=(e.userAgentData||{}).platform||(t.userAgentData||{}).platform;if(r){var a=function(e){for(var t=0;t<ef.length;t++){var i=ef[t];if(i.r&&e.match(i.r))return i.os;if(i.s&&-1!==e.indexOf(i.s))return i.os}return Xm}(r.toLowerCase());i=a,n=function(e,t){return"Windows"===t?tf(e,"Windows NT"):"Android"===t?tf(e,t):"Mac OS X"===t?function(e){var t=e.match(new RegExp("Mac OS X "+Zm));if(t){var i=t[1].replace(/_/g,".");if(i){var n=nf(i);return n?i.split(n)[0]:i}}return Xm}(e):"iOS"===t?function(e){var t=e.match(new RegExp("OS "+Zm));if(t){var i=t[1].replace(/_/g,".");if(i){var n=nf(i);return n?i.split(n)[0]:i}}return Xm}(e):Xm}(r,a)}i&&i!==Xm||!tt(s)||(i=s)}}));t&&t.add(a),yt(this,"name",{s:function(e){r=e},g:function(){return r||i}}),yt(this,"ver",{s:function(e){s=e},g:function(){return s||n}})},sf="MicrosoftApplicationsTelemetryDeviceId",af=function(){function e(t,i,n){var r,s=0;Nn(e,this,(function(e){e.seq=s,e.epoch=ja(!1).toString(),e.getSequenceId=function(){return++s};var a=So(t,(function(t){r=i&&i.getCookieMgr();var n=t.cfg.propertyStorageOverride;if(r.isEnabled()||n){var s=function(e,t,i){return t?t.getProperty(i)||"":Xc(e,i)}(r,n,sf);s||(s=_l()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(r,n,sf,s),e.installId=s}else r.purge(sf)}));n&&n.add(a)}))}return e.__ieDyn=1,e}(),of=function(e,t,i,n,r){var s=this;s.traceId=t||Il();var a=So(e,(function(){var t=e;if(t.enableDistributedTracing&&!i&&(i=Il().substring(0,16)),s.parentId=s.parentId||i,t.enableApplicationInsightsTrace&&!n){var r=Ra();r&&r.pathname&&(n=r.pathname)}s.name=s.name||n}));r&&r.add(a)},lf="setLocalId";function cf(){return this.getLocalId()}function df(e){this[lf](e)}var uf=function(){function e(t,i,n,r){var s,a,o;Nn(e,this,(function(l){if(function(i){var c=So(i,(function(){if(o=n&&n.getCookieMgr(),s=i,a=null,o&&o.isEnabled()&&(d(),s.enableApplicationInsightsUser)){var r=Xc(o,e.userCookieName);if(r){var c=r.split(e.cookieSeparator);c.length>0&&(l.id=c[0])}if(!l.id){l.id=Ga(t&&!Ze(t.idLength)?t.idLength:22);var u=da(new Date);l.accountAcquisitionDate=u;var h=[l.id,u],g=s.cookieDomain?s.cookieDomain:void 0;o.set(e.userCookieName,h.join(e.cookieSeparator),31536e3,g)}}}));r&&r.add(c)}(i),"undefined"!=typeof navigator){var c=navigator;l.locale=c.userLanguage||c.language}function d(){if(!s.hashIdentifiers&&!s.dropIdentifiers){var e=Xc(o,"MUID");e&&(a="t:"+e)}return a}l.getLocalId=function(){return a||d()},l[lf]=function(e){a=e}}))}return e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void yt(e.prototype,"localId",{g:cf,s:df}),e}(),hf=function(e,t){var i=this;i.popSample=100;var n=So(e,(function(){i.eventFlags=0,e.hashIdentifiers&&(i.eventFlags=1048576|i.eventFlags),e.dropIdentifiers&&(i.eventFlags=2097152|i.eventFlags),e.scrubIpOnly&&(i.eventFlags=4194304|i.eventFlags)}));t&&t.add(n)},gf=["Required","Analytics","SocialMedia","Advertising"],pf="([\\d,.]+)",mf="Unknown",ff="Edg/",vf="EdgiOS/",Sf=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:ff,b:"Edge"},{ua:vf,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"}],yf=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function Cf(e,t){return t.indexOf(e)>-1}function Tf(e,t){for(var i=0;i<t.length;i++)if(e==t[i].brand)return t[i].version;return null}function Ef(){return this.getUserConsent()}var bf=function(){function e(t,i,n){sl(i);var r=t||{},s=null,a=null,o=null,l=null,c=null,d=null,u=null;Nn(e,this,(function(e){!function(e){var t=So(e,(function(){if((r=e).populateBrowserInfo){var t=r.userAgent,i=(r.userAgentData||{}).brands;if(t!==s||i!==a){if(!t||!i||0===i.length){var n=ci();n&&(t=t||n.userAgent||"",i=i||(n.userAgentData||{}).brands)}(function(e,t){if(rt(t))try{for(var i=0;i<yf.length;i++){var n=Tf(yf[i].br,t);if(n)return c=yf[i].b,void(d=n)}}catch(e){}if(e){var r=function(e){if(e)for(var t=0;t<Sf.length;t++)if(Cf(Sf[t].ua,e))return Sf[t].b;return mf}(e);c=r,d=function(e,t){return"MSIE"===t?function(e){var t=e.match(new RegExp("MSIE "+pf));if(t)return t[1];var i=e.match(new RegExp("rv:"+pf));return i?i[1]:void 0}(e):function(e,t){"Safari"===e?e="Version":"Edge"===e&&(Cf(ff,t)?e="Edg":Cf(vf,t)&&(e="EdgiOS"));var i=t.match(new RegExp(e+"/"+pf));return i||"Opera"===e&&(i=t.match(new RegExp("OPR/"+pf)))?i[1]:mf}(t,e)}(e,r)}})(t,i),s=t,a=i}}u=ot(r.gpcDataSharingOptIn)?r.gpcDataSharingOptIn:null}));n&&n.add(t)}(t);var i=Ra();if(i){var h=i.hostname;h&&(e.domain="file:"===i.protocol?"local":h)}var g=function(){var e={h:0,w:0},t=li();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e}();e.screenRes=g.w+"X"+g.h,e.getUserConsent=function(){return!1},e.getUserConsentDetails=function(){var e=null;try{var t=r.callback;if(t&&t.userConsentDetails){var i=t.userConsentDetails();if(i){e=r.disableConsentDetailsSanitize?i:{};for(var n=0;n<gf.length;n++){var s=gf[n];e[s]=i[s]||!1}}}return null!==u&&((e=e||{}).GPC_DataSharingOptIn=!!u),e?JSON.stringify(e):null}catch(e){}},function(e,t){var i={};pt(t,(function(e,t){i[e]=ft(t)})),St(e,i)}(e,{userConsent:{g:e.getUserConsent},browser:{s:function(e){o=e},g:function(){return o||c}},browserVer:{s:function(e){l=e},g:function(){return l||d}},gpcDataSharingOptIn:{g:function(){return u},s:function(e){u=ot(e)?e:null,r.gpcDataSharingOptIn=u}}})}))}return e._staticInit=void yt(e.prototype,"userConsent",{g:Ef}),e}();function _f(e,t,i,n,r){var s=t.ext[vm[e]];if(s)try{pt(n,(function(e,t){if(tt(t)||at(t)||ot(t)){var n=s[i[e]];!r&&(n||tt(n)||at(n)||ot(n))&&(t=n),s[i[e]]=t}}))}catch(e){}return s}var If,wf=function(){function e(t,i,n,r){Nn(e,this,(function(e){e.app=new jm(i,n,r),e.cloud=new Gm,e.user=new uf(t,i,n,r),e.os=new rf(i,r),e.web=new bf(i,n,r);var s=new af(t,n,r),a=new Km(i,n,r),o=new hf(i,r);e.loc=new Jm,e.device=new qm;var l=new Um(n,i,r);e.session=new xm;var c=void 0,d=function(e,t){var i=e||{};return{getName:function(){return i.name},setName:function(e){t&&t.setName(e),i.name=e},getTraceId:function(){return i.traceId},setTraceId:function(e){t&&t.setTraceId(e),Al(e)&&(i.traceId=e)},getSpanId:function(){return i.parentId},setSpanId:function(e){t&&t.setSpanId(e),Pl(e)&&(i.parentId=e)},getTraceFlags:function(){return i.traceFlags},setTraceFlags:function(e){t&&t.setTraceFlags(e),i.traceFlags=e}}}(new of(i,c,c,c,r),g()),u=!(i||{}).eventContainExtFields;function h(){var t=e.session;if(t&&tt(t.customId))return t.customId;l.update();var i=l.automaticSession;if(i){var n=i.getId();n&&tt(n)&&(t.automaticId=n)}return t.automaticId}function g(){var e=d;return n&&n.getTraceCtx&&(e=n.getTraceCtx(!1)||d),e}e.getTraceCtx=function(){return d},e.getSessionId=h,e.applyApplicationContext=function(t){var i,n=e.app;_f(4,t,Sm,((i={})[0]=n.id,i[1]=n.ver,i[2]=n.name,i[3]=n.locale,i[4]=n.getExpId(),i[5]=n.env,i),u)},e.applyUserContext=function(t){var i,n=e.user;_f(0,t,Cm,((i={})[1]=n.getLocalId(),i[0]=n.locale,i[2]=n.id,i),u)},e.applyWebContext=function(t){var i,n=e.web;_f(3,t,ym,((i={})[0]=n.domain,i[1]=n.browser,i[2]=n.browserVer,i[3]=n.screenRes,i[5]=n.getUserConsentDetails(),i[4]=!1,i),u)},e.applyOsContext=function(t){var i,n=e.os;_f(5,t,Tm,((i={})[0]=n.name,i[1]=n.ver,i),u)},e.applySdkContext=function(e){var t;_f(6,e,Em,((t={})[2]=s.installId,t[1]=s.getSequenceId(),t[3]=s.epoch,t),u)},e.applyIntWebContext=function(e){var t;_f(7,e,bm,((t={})[0]=a.getMsfpc(),t[1]=a.getAnid(),t[2]=a.serviceName,t),u)},e.applyUtcContext=function(e){var t,i=((t={})[0]=o.popSample,t);o.eventFlags>0&&(i[1]=o.eventFlags),_f(8,e,_m,i,u)},e.applyLocContext=function(t){var i;_f(9,t,Im,((i={})[0]=e.loc.tz,i),u)},e.applySessionContext=function(e){var t;_f(4,e,wm,((t={})[0]=h(),t),u)},e.applyDeviceContext=function(t){var i,n=e.device;_f(1,t,Am,((i={})[0]=n.localId,i[2]=n.make,i[3]=n.model,i[1]=n.deviceClass,i),u)},e.applyCloudContext=function(t){var i,n=e.cloud;_f(10,t,Pm,((i={})[0]=n.role,i[1]=n.roleInstance,i[2]=n.roleVer,i),u)},e.applyAITraceContext=function(e){var t;if(i.enableApplicationInsightsTrace){var n=g();n&&_f(2,e,Rm,((t={})[0]=n.getTraceId(),t[1]=n.getName(),t[2]=n.getSpanId(),t),!1)}},e.applyDistributedTraceContext=function(e){var t,i=g();if(i){var n=((t={})[0]=i.getTraceId(),t[1]=i.getSpanId(),t),r=i.getTraceFlags();Xe(r)||(n[2]=r),_f(11,e,Mm,n,!1)}}}))}return e.__ieDyn=1,e}(),Af=[vm[4],vm[0],vm[3],vm[5],vm[6],vm[7],vm[8],vm[9],vm[1],vm[2],vm[11],vm[10]],Pf=Rt({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:hm(),userAgentData:um({brands:If,mobile:If,platform:If}),userConsentCookieName:hm(),userConsented:!1,serviceName:hm(),env:hm(),expId:hm(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:hm(),namePrefix:hm(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:um({userConsentDetails:null}),gpcDataSharingOptIn:If,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),Rf=function(e){function t(){var i,n,r,s=e.call(this)||this;return s.identifier="SystemPropertiesCollector",s.priority=3,s.version="4.3.2",Nn(t,s,(function(e,t){function s(){i=null,n={}}function a(t){var n=e.identifier,s=e.core;e._addHook(So(t,(function(){var e=Ul(null,t,s);r=e.getExtCfg(n,Pf)}))),i=new wf(t,r,s,e._unloadHooks),s&&s.setTraceCtx&&s.setTraceCtx(i.getTraceCtx())}s(),e.initialize=function(e,i,n){t.initialize(e,i,n),a(e)},e.processTelemetry=function(t,s){nd(t,e.identifier),s=e._getTelCtx(s);var a=t.ext=t.ext?t.ext:{};t.data=t.data?t.data:{},Ti(Af,(function(e){a[e]=a[e]||{}})),i&&(i.applyUtcContext(t),i.applyApplicationContext(t),i.applyUserContext(t),i.applyWebContext(t),i.applyOsContext(t),i.applySdkContext(t),i.applyIntWebContext(t),i.applyLocContext(t),i.applySessionContext(t),i.applyDeviceContext(t),r.enableApplicationInsightsTrace&&i.applyAITraceContext(t),r.enableDistributedTracing&&i.applyDistributedTraceContext(t),i.applyCloudContext(t)),Ti(Pt(a),(function(e){0===Pt(a[e]).length&&delete a[e]})),function(e,t){e&&pt(e,(function(e,i){t[e]||(t[e]=i)}))}(n,t.data),e.processNext(t,s)},e.getPropertiesContext=function(){return i},e.setProperty=function(e,t){n[e]=t},e._doTeardown=function(e,t){var n=(e||{}).core();if(n&&n.getTraceCtx&&i){var r=n.getTraceCtx(!1);r&&r===i.getTraceCtx()&&n.setTraceCtx(null)}s()},e._getDbgPlgTargets=function(){return[r]}})),s}return tn(t,e),t.__ieDyn=1,t}(Wl);function Mf(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const Df="Skype",kf="https://ic3.events.data.microsoft.com/OneCollector/1.0/";var Of,Nf,Lf;!function(e){e.Public="Public",e.GccHigh="GCCHigh",e.Dod="DoD",e.AirGap08="AirGap08",e.AirGap09="AirGap09"}(Of||(Of={})),function(e){e.OrgId="orgid",e.Acs="acs",e.Spool="spool",e.GccHigh="gcch",e.GccHighAcs="gcch-acs",e.Dod="dod",e.DodAcs="dod-acs",e.AirGap08="ag08",e.AirGap08Acs="ag08-acs",e.AirGap09="ag09",e.AirGap09Acs="ag09-acs"}(Nf||(Nf={})),function(e){e.Public_ConversationServiceUrl_EUDB="https://api.flightproxy.skype.com/api/v2/cpconv",e.Public_TrouterServiceUrl_EUDB="https://go-eu.trouter.communication.microsoft.com/v4/a",e.Public_RegistrarServiceUrl_EUDB="https://emea.prod.registrar.skype.com/v3/registrations",e.Public_MdnTrapServiceUrl_EUDB="https://edge.skype.com/trap",e.Public_MdnTrapServiceTokenUrl_EUDB="https://edge.skype.com/trap/tokens",e.Public_MdnTrapRelaySkypeFqdns_EUDB="eu.relay.skype.com",e.Public_MdnTrapRelayTurnFqdns_EUDB="eu.relay.skype.com",e.Public_MdnTrapRelayTurnUrl_EUDB="",e.Enterprise_ConversationServiceUrl_EUDB="https://api.flightproxy.teams.microsoft.com/api/v2/epconv",e.Enterprise_TrouterServiceUrl_EUDB="https://go-eu.trouter.teams.microsoft.com/v4/a",e.Enterprise_RegistrarServiceUrl_EUDB="https://teams.microsoft.com/registrar/prod/v3/registrations",e.Enterprise_MdnTrapServiceUrl_EUDB="https://teams.microsoft.com/trap",e.Enterprise_MdnTrapServiceTokenUrl_EUDB="https://teams.microsoft.com/trap/tokens",e.Enterprise_MdnTrapRelaySkypeFqdns_EUDB="euaz.relay.teams.microsoft.com",e.Enterprise_MdnTrapRelayTurnFqdns_EUDB="euaz.relay.teams.microsoft.com",e.Enterprise_MdnTrapRelayTurnUrl_EUDB=""}(Lf||(Lf={}));const xf="https://api.flightproxy.skype.com/api/v2/cpconv",Ff="https://go.trouter.communication.microsoft.com/v4/a",Uf="https://prod.registrar.skype.com/v3/registrations",Bf="https://edge.skype.com/trap",Vf="https://edge.skype.com/trap/tokens",Hf="worldaz.tr.skype.com",$f="turn.azure.com",jf="",Gf="https://api.cc.gov.teams.microsoft.us/conv/",qf="https://go.trouter.gov.teams.microsoft.us/v4/a",zf="https://registrar.gov.teams.microsoft.us/v3/registrations",Wf="https://trap.gov.teams.microsoft.us",Kf="https://trap.gov.teams.microsoft.us/tokens",Jf="tr.gov.teams.microsoft.us",Yf="turn.gov.teams.microsoft.us",Qf="https://turn.gov.teams.microsoft.us/relay",Zf="https://api.cc.dod.teams.microsoft.us/conv/",Xf="https://go.trouter.dod.teams.microsoft.us/v4/a",ev="https://registrar.dod.teams.microsoft.us/v3/registrations",tv="https://trap.dod.teams.microsoft.us",iv="https://trap.dod.teams.microsoft.us/tokens",nv="tr.dod.teams.microsoft.us",rv="turn.dod.teams.microsoft.us",sv="https://turn.dod.teams.microsoft.us/relay",av="https://api.cc.skype.com/conv/",ov="https://go.trouter.teams.eaglex.ic.gov/v4/a",lv="https://api.registrar.teams.eaglex.ic.gov/v3/registrations",cv="https://api.cc.skype.com/conv/",dv="https://go.trouter.teams.microsoft.scloud/v4/a",uv="https://api.registrar.teams.microsoft.scloud/v3/registrations",hv="https://api.flightproxy.teams.microsoft.com/api/v2/epconv",gv="https://go.trouter.teams.microsoft.com/v4/a",pv="https://teams.microsoft.com/registrar/prod/v3/registrations",mv="https://teams.microsoft.com/trap",fv="https://teams.microsoft.com/trap/tokens",vv="worldaz.relay.teams.microsoft.com",Sv="worldaz.relay.teams.microsoft.com",yv="",Cv="https://ecs.communication.microsoft.com",Tv="https://config.ecs.gov.teams.microsoft.us",Ev="https://config.ecs.dod.teams.microsoft.us",bv="https://config.ecs.teams.eaglex.ic.go",_v="https://config.ecs.teams.microsoft.scloud",Iv="https://config.teams.microsoft.com";var wv;!function(e){e.Consumer="consumer",e.Enterprise="enterprise"}(wv||(wv={}));const Av=["europe","france","germany","norway","switzerland","sweden"],Pv=["emea","fr","de","se"],Rv=Array.from(new Set(Av.concat(["qatar","uae","africa","uk"]))),Mv=["asiapacific","india","japan","korea","australia"],Dv=["unitedstates","brazil","canada"];var kv,Ov;!function(e){e.EU="EU",e.RoW="RoW"}(kv||(kv={})),function(e){e.APAC="APAC",e.NOAM="NOAM",e.EMEA="EMEA",e.UNKNOWN=""}(Ov||(Ov={}));const Nv={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:Mf(),AGGREGATION:{INTERVAL:1e3,DATAPOINTS:1},VIDEO_SIZE:{heigth:720,width:1280},MEDIASTREAM_TIMEOUT_IN_SEC:15,CONNECT_TIMEOUT_IN_SEC:10}};var Lv;!function(e){e.AcsOrganizerRole="acsorganizer",e.AcsPresenterRole="acspresenter",e.AcsAttendeeRole="acsattendee",e.AcsConsumerRole="acsconsumer",e.TeamsOrganizer="organizer",e.TeamsAttendee="attendee",e.TeamsPresenter="presenter",e.TeamsCoorganizer="coorganizer"}(Lv||(Lv={}));const xv="4cf9ed87f7dc4e148f77855cd1f2fdca-61fb83a7-6672-4264-806f-7aded29f9b49-7618",Fv="53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",Uv="1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",Bv="2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326",Vv="28:8133db4c-c049-4346-9edd-273f164a9227",Hv="28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5",$v="28:4b25d9f8-18f5-4d09-a582-cd0a28f63181",jv="ACS-Public",Gv=["en-us"],qv="setLanguage",zv="mode",Wv="Transcription",Kv=["closedCaptions"],Jv=["scheduledMeeting","adhocMeeting"],Yv="0.0",Qv=!0,Zv=Symbol("global_telemetry_logger"),Xv=Symbol("global_call_client_index"),eS="orgid",tS="gcch",iS="28:",nS="4:",rS=":",sS="Unknown",aS="8:orgid:",oS="8:dod:",lS="8:gcch:",cS="8:teamsvisitor:",dS="8:acs:",uS="8:spool:",hS="8:dod-acs:",gS="8:gcch-acs:",pS=iS+(eS+rS),mS=iS+(tS+rS),fS=iS+"dod:",vS={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 SS,yS;!function(e){e.GroupCall="joinGroupId",e.GroupChatCall="joinThreadId",e.TeamsCoordinates="joinMeetingCoordinates",e.TeamsMeetingId="joinMeetingId",e.TeamsMeetingLink="joinMeetingLink",e.RoomCall="joinRoom",e.Unknown="Unknown"}(SS||(SS={})),function(e){e.Organizer="Organizer",e.Coorganizer="Co-organizer",e.Attendee="Attendee",e.Presenter="Presenter",e.Consumer="Consumer",e.Unknown="Unknown"}(yS||(yS={}));const CS={"msft-acs-room-deviceType":"room","msft-acs-3proom-deviceType":"3proom","msft-acs-mesh-deviceType":"mesh","msft-acs-mesh-deviceType-v2":"meshV2"};var TS,ES;!function(e){e.onlyUsedProxy="onlyUsedProxy",e.onlyUsedNonMsftTurn="onlyUsedNonMsftTurn",e.usedProxyAndNonMsftTurn="usedProxyAndNonMsftTurn",e.noCustomProxyAndTurnUsed="noCustomProxyAndTurnUsed"}(TS||(TS={})),function(e){e.RoleRestricted="RoleRestricted",e.FeatureNotSupported="FeatureNotSupported",e.ClientRestricted="ClientRestricted",e.MeetingRestricted="MeetingRestricted",e.UserPolicyRestricted="UserPolicyRestricted",e.TeamsPremiumLicenseRestricted="TeamsPremiumLicenseRestricted",e.NotInitialized="NotInitialized",e.Capable="Capable",e.NotCapable="NotCapable",e.CapabilityNotApplicableForTheCallType="CapabilityNotApplicableForTheCallType",e.IpModeUserPolicyRestricted="IpModeUserPolicyRestricted",e.ExplicitConsentRequired="ExplicitConsentRequired"}(ES||(ES={}));const bS="roomsRoleBasedCapabilities",_S="teamsRoleBasedCapabilities",IS=/^(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]?)$/,wS=/(\:[0-9]{1,6})(?=$|\/|\?)/;var AS,PS;!function(e){e.TeamsProMgmt="TeamsProMgmt"}(AS||(AS={})),function(e){e.Disabled="Disabled",e.DisabledUserOverride="DisabledUserOverride"}(PS||(PS={}));const RS="ScreenSharing";var MS;function DS(e){const t=B(e);switch(t.kind){case MS.communicationUser:return t.communicationUserId;case MS.phoneNumber:if(t.rawId)return`${t.rawId}`;if(t.phoneNumber)return`${nS}${t.phoneNumber}`;throw new le({defaultError:ee.IDENTIFIER.PARSE_PHONENUMBER});case MS.microsoftTeamsUser:if(t.rawId)return t.rawId;if(t.microsoftTeamsUserId){if(t.isAnonymous)return`${cS}${t.microsoftTeamsUserId}`;if("public"===t.cloud)return`${aS}${t.microsoftTeamsUserId}`;if("dod"===t.cloud)return`${oS}${t.microsoftTeamsUserId}`;if("gcch"===t.cloud)return`${lS}${t.microsoftTeamsUserId}`;if(!t.cloud)return`${aS}${t.microsoftTeamsUserId}`}throw new le({defaultError:ee.IDENTIFIER.PARSE_MSFT_TEAMS_USER});case MS.microsoftTeamsApp:if(t.rawId)return t.rawId;if(t.teamsAppId){if("public"===t.cloud)return`${pS}${t.teamsAppId}`;if("dod"===t.cloud)return`${fS}${t.teamsAppId}`;if("gcch"===t.cloud)return`${mS}${t.teamsAppId}`;if(!t.cloud)return`${pS}${t.teamsAppId}`}throw new le({defaultError:ee.IDENTIFIER.PARSE_MSFT_TEAMS_APP});case"unknown":return t.id;default:throw new le({defaultError:ee.IDENTIFIER.PARSE_IDENTIFIER})}}function kS(e){return e.startsWith(aS)?{kind:MS.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(8),isAnonymous:!1,cloud:"public"}:e.startsWith(oS)?{kind:MS.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(6),isAnonymous:!1,cloud:"dod"}:e.startsWith(lS)?{kind:MS.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(7),isAnonymous:!1,cloud:"gcch"}:e.startsWith(cS)?{kind:MS.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(15),isAnonymous:!0}:e.startsWith(nS)?{kind:MS.phoneNumber,rawId:e,phoneNumber:e.substring(2)}:e.startsWith(dS)||e.startsWith(uS)||e.startsWith(gS)||e.startsWith(hS)?{kind:MS.communicationUser,communicationUserId:e}:e.startsWith(pS)?{kind:MS.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(9),cloud:"public"}:e.startsWith(mS)?{kind:MS.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(8),cloud:"gcch"}:e.startsWith(fS)?{kind:MS.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(7),cloud:"dod"}:{kind:MS.unknown,id:e}}function OS(e){return!!e.startsWith(iS)}function NS(e){const t=B(e);switch(t.kind){case MS.communicationUser:if(!(t.communicationUserId.startsWith(dS)||t.communicationUserId.startsWith(uS)||t.communicationUserId.startsWith(gS)||t.communicationUserId.startsWith(hS)))throw new le({defaultError:ee.IDENTIFIER.INVALID_COMM_USER});return t;case"phoneNumber":return t;case MS.microsoftTeamsUser:if(t.rawId&&!t.rawId.startsWith(aS)&&!t.rawId.startsWith(oS)&&!t.rawId.startsWith(lS)&&!t.rawId.startsWith(cS))throw new le({defaultError:ee.IDENTIFIER.INVALID_MSFT_TEAMS_USER_RAWID});if(!t.microsoftTeamsUserId)throw new le({defaultError:ee.IDENTIFIER.INVALID_MSFT_TEAMS_USER_USERID});return t;case MS.microsoftTeamsApp:if(t.rawId&&!t.rawId.startsWith(iS))throw new le({defaultError:ee.IDENTIFIER.INVALID_MSFT_TEAMS_APP_RAWID});if(!t.teamsAppId)throw new le({defaultError:ee.IDENTIFIER.INVALID_MSFT_TEAMS_APP_APPID});return t;case MS.unknown:if(!t.id)throw new le({defaultError:ee.IDENTIFIER.INVALID_UNKNOWN_IDENTIFIER});return t;default:throw new le({defaultError:ee.IDENTIFIER.PARSE_INVALID_IDENTIFIER})}}!function(e){e.communicationUser="communicationUser",e.microsoftTeamsUser="microsoftTeamsUser",e.microsoftTeamsApp="microsoftTeamsApp",e.phoneNumber="phoneNumber",e.unknown="unknown",e.group="group"}(MS||(MS={}));const LS="1.34.1.1_beta",xS="1.34.1-beta.1";function FS(){const e="ACS_CLIENT_INTERNAL_SZK_VERSION".replace("Z","D");return LS===e?"1.0.0.0":LS}function US(){const e="ACS_CLIENT_SZK_VERSION".replace("Z","D");return xS===e?"1.0.0.0":xS}function BS(e,t){if(Array.isArray(e))return t.slice()}function VS(e){try{const t="string"==typeof e?new URL(e):e;return`${t.protocol}//${t.host}${t.pathname}`}catch(e){return""}}function HS(e){return Array.isArray(e)&&0!==e.length}function $S(e){return null==e||void 0===e}function jS(e,t){return void 0!==e?e:t}function GS(e){try{return JSON.stringify(e,null,2)}catch(t){return`failed to stringify obj ${e}`}}const qS=e=>e*(Math.PI/180);var zS,WS,KS,JS,YS,QS,ZS,XS,ey,ty,iy,ny,ry,sy,ay,oy,ly,cy,dy,uy,hy,gy,py;!function(e){e.Outgoing="Outgoing",e.Incoming="Incoming",e.TransferOutgoing="TransferOutgoing"}(zS||(zS={})),function(e){e.CreateCallAgent="CreateCallAgent",e.CreateTeamsCallAgent="CreateTeamsCallAgent",e.GetDeviceManager="GetDeviceManager",e.GetEnvironmentInfo="GetEnvironmentInfo",e.GetSDKVersion="GetSDKVersion",e.Feature="Feature"}(WS||(WS={})),function(e){e.StartCall="StartCall",e.Join="Join",e.HandlePushNotification="HandlePushNotification",e.Initialize="Initialize",e.Dispose="Dispose",e.CreateCall="CreateCall",e.Feature="Feature"}(KS||(KS={})),function(e){e.Call="Call",e.StartCall="StartCall",e.CallGroup="CallGroup",e.JoinGroup="JoinGroup",e.Accept="Accept",e.Reject="Reject",e.Mute="Mute",e.Unmute="Unmute",e.MuteAllRemoteParticipants="MuteAllRemoteParticipants",e.MuteIncomingAudio="MuteIncomingAudio",e.UnmuteIncomingAudio="UnmuteIncomingAudio",e.SendDtmf="SendDtmf",e.HangUp="HangUp",e.StartVideo="StartVideo",e.StartAudio="StartAudio",e.StopAudio="StopAudio",e.StopVideo="StopVideo",e.AddParticipant="AddParticipant",e.RemoveParticipant="RemoveParticipant",e.LobbyAdmitParticipant="LobbyAdmitParticipant",e.LobbyRejectParticipant="LobbyRejectParticipant",e.LobbyAdmitAll="LobbyAdmitAll",e.Hold="Hold",e.Resume="Resume",e.StartScreenShare="StartScreenShare",e.StopScreenShare="StopScreenShare",e.Transfer="Transfer",e.BindToCall="BindToCall",e.Feature="Feature",e.SetConstraints="SetConstraints"}(JS||(JS={})),function(e){e.Mute="Mute"}(YS||(YS={})),function(e){e.GetServerCallId="GetServerCallId"}(QS||(QS={})),function(e){e.CreateStackBase="CreateStackBase",e.GetDeviceManager="GetDeviceManager",e.InitializeStackForUser="InitializeStackForUser",e.InitializeEcsBase="InitializeEcsBase",e.InitializeEcsForUser="InitializeEcsForUser",e.Dispose="Dispose"}(ZS||(ZS={})),function(e){e.GetDeviceManager="GetDeviceManager",e.GetCameras="GetCameras",e.GetMicrophones="GetMicrophones",e.GetSpeakers="GetSpeakers",e.GetCamera="GetCamera",e.SelectCamera="SelectCamera",e.GetSelectedMicrophone="GetSelectedMicrophone",e.SelectMicrophone="SelectMicrophone",e.GetSelectedSpeaker="GetSelectedSpeaker",e.SelectSpeaker="SelectSpeaker",e.RenderPreviewVideo="RenderPreviewVideo",e.AskDevicePermission="AskDevicePermission"}(XS||(XS={})),function(e){e.Dispose="Dispose",e.UpdateScalingMode="UpdateScalingMode",e.Render="Render",e.RenderRemoteStream="RenderRemoteStream",e.RenderLocalStream="RenderLocalStream"}(ey||(ey={})),function(e){e.Dispose="Dispose",e.CreateView="CreateView"}(ty||(ty={})),function(e){e.SwitchSource="SwitchSource",e.Render="Render",e.GetMediaStream="GetMediaStream",e.SetMediaStream="SetMediaStream",e.SwitchVideo="SwitchVideo",e.Feature="Feature"}(iy||(iy={})),function(e){e.SwitchSource="SwitchSource",e.GetMediaStream="GetMediaStream",e.SetMediaStream="SetMediaStream",e.Feature="Feature"}(ny||(ny={})),function(e){e.SetScalingMode="SetScalingMode",e.Start="Start",e.Stop="Stop",e.SwitchDevice="SwitchDevice",e.Dispose="Dispose"}(ry||(ry={})),function(e){e.Render="Render",e.GetMediaStream="GetMediaStream"}(sy||(sy={})),function(e){e.Start="Start",e.Resume="Resume",e.Pause="Pause",e.SetScalingMode="SetScalingMode",e.Dispose="Dispose"}(ay||(ay={})),function(e){e.Start="Start",e.Resume="Resume",e.Pause="Pause",e.SetScalingMode="SetScalingMode",e.Dispose="Dispose",e.SetSourceObject="SetSourceObject"}(oy||(oy={})),function(e){e.SourceUnavailableError="SourceUnavailableError",e.permissionDeniedError="permissionDeniedError",e.PermissionDeniedError="PermissionDeniedError",e.DevicesNotFoundError="DevicesNotFoundError",e.MediaStreamRequestError="MediaStreamRequestError",e.PermissionsDeniedBySystem="PermissionsDeniedBySystem",e.UnknownFailureForVideoOperation="UnknownFailureForVideoOperation",e.noDeviceSelected="noDeviceSelected",e.NoDeviceSelected="NoDeviceSelected",e.MediaStreamRequestTimedout="MediaStreamRequestTimedout",e.UnsupportedStream="UnsupportedStream",e.ConstraintNotSatisfiedError="ConstraintNotSatisfiedError"}(ly||(ly={})),function(e){e.BrowserNotSupported="BrowserNotSupported",e.IncompatibleVersions="IncompatibleVersions"}(cy||(cy={})),function(e){e.JoinTeamMeeting="JoinTeamMeeting",e.JoinRoom="JoinRoom",e.JoinWithGroupId="JoinWithGroupId",e.PlaceCall="PlaceCall",e.AcceptCall="AcceptCall",e.TransferToParticipant="TransferToParticipant",e.TransferToCall="TransferToCall",e.CallQueue="CallQueue"}(dy||(dy={})),function(e){e.TeamsMeeting="TeamsMeeting",e.Rooms="Rooms",e.GroupIdCall="GroupIdCall",e.TwoParty="TwoParty",e.MultiParty="MultiParty"}(uy||(uy={})),function(e){e.Enabled="Enabled",e.UserOverride="UserOverride",e.Disabled="Disabled"}(hy||(hy={})),function(e){e.Standard="standard",e.MusicOnHold="musicOnHold"}(gy||(gy={})),function(e){e.Disabled="Disabled",e.EnabledOutgoingIncoming="EnabledOutgoingIncoming"}(py||(py={}));const my={telemetry:{callStatsFlushTimeout:6e3,discardedTelemetryRetryTimeout:5e3,discardedEventsBufferMaxLength:1e3,discardedEventsMaxRetries:3,telemetryFlushTimeout:2e3,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:["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"]},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:{"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}}}}},liveStreamStats:{activeState:[3],fetchInterval:1,aggregationInterval:10,dataPointsPerAggregation:6,pollingMethod:"interval"},debugInfo:{broadcastChannelName:"acs_broadcast_channel",tabsBroadcastDelay:5e3,tabsUpdateDelay:500,enableLogDump:!1,maxLogDumpLength:500,includeList:[],excludeList:[]},volumeIndicator:{fftSize:512,minDecibels:-127,maxDecibels:0,smoothingConstant:.4,microphoneVolumeSampleIntervalMs:200,normalisedMaxVolume:100,maxAvailableVolume:255},telemetryEvents:{eventNameToPriority:{eventName:["acs_calling_call_stats"],priority:[cd.Immediate]}},rendering:{remoteVideo:{createViewTimeout:6e3,maxRendererRetries:1,speedupCreateViewWithPlayEvent:!1,createViewUnsubscribeTimeout:2500,debounceTimeout:1500,createViewSendMediaStats:!0,createViewSendMediaStatsMaxLength:120,createViewSendMediaStatsInitialMaxLength:1,createViewFailureNetworkUfdCheckWindowInMs:2e3,forceCheckIfVideoWasAttachedToDom:!0,checkIfVideoAttachedToDom_poll:!0,checkIfVideoAttachedToDom_intervalTime:5e3,checkIfVideoAttachedToDom_intervalMaxTries:12,checkIfVideoAttachedToDom_timeout:2e4,createViewSenderStatsDuration:6e4,registeredViewIdsMaxLength:0,getMediaStreamTimeout:6e3,largeMeeting:{handleVideoRendering:!0,participantCountThreshold:100,dominantSpeakersWithVideoOn_topCount:4}}},captions:{acsBotMri:Vv,teamsBotMri:Hv,teamsGccBotMri:$v,clientInfo:jv,availableLanguages:Gv,enabled:!0,dataChannelId:3,useCapabilities:!0,setBotMetadataWhenEmptyFix:!0,acs:{enabled:!0,botMri:Vv,modeKey:zv,modeVal:Wv,modesKey:"transcriptionModes",modesVal:Kv,clientInfo:{ring:jv},spokenLanguages:{enabled:!0,languages:Gv}},teams:{enabled:!0,legacyBotMri:"28:b1902c3e-b9f7-4650-9b23-5772bd429747",botMri:Hv,gccBotMri:$v,modeKey:zv,modeVal:"RecordingAndTranscription",modesKey:"processingModes",modesVal:Kv,clientInfo:{ring:"Teams-Public"},spokenLanguages:{enabled:!0,languages:Gv},captionLanguages:{enabled:!1,languages:["en"]}}},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,allowMutePstnRemoteParticipant:!0,constraints:{enabled:!1,maxOutgoingResolution:0,maxOutgoingFrameRate:0,maxOutgoingVideoBitrate:0},sharedLineAppearance:{enabled:!1},supportLiveStreaming:!1,liveStreamingBotIds:["28:f4693563-c70b-4e4d-bda6-01792aa21440","28:e32c9418-a835-4eb1-bfb9-733fa74dd6e8"],composedStreamBotIds:["28:5f2511f1-6da9-41d9-80d9-af7da23a2c27","28:accb0009-8d12-4cfe-969c-39b204e3ed0c"],teamsCallQualityFeedback:{enabled:!0,tenantId:Uv},setDeviceType:!1,devicePermissions:{splitAskAudioVideo:!1,timeoutInBetween:0,getCurrentState:!0},applicationSettingsUrls:{Public_ConversationServiceUrl:xf,Public_TrouterServiceUrl:Ff,Public_RegistrarServiceUrl:Uf,Public_MdnTrapServiceUrl:Bf,Public_MdnTrapServiceTokenUrl:Vf,Public_MdnTrapRelaySkypeFqdns:Hf,Public_MdnTrapRelayTurnFqdns:$f,Public_MdnTrapRelayTurnUrl:jf,GccHigh_ConversationServiceUrl:Gf,GccHigh_TrouterServiceUrl:qf,GccHigh_RegistrarServiceUrl:zf,GccHigh_MdnTrapServiceUrl:Wf,GccHigh_MdnTrapServiceTokenUrl:Kf,GccHigh_MdnTrapRelaySkypeFqdns:Jf,GccHigh_MdnTrapRelayTurnFqdns:Yf,GccHigh_MdnTrapRelayTurnUrl:Qf,Dod_ConversationServiceUrl:Zf,Dod_TrouterServiceUrl:Xf,Dod_RegistrarServiceUrl:ev,Dod_MdnTrapServiceUrl:tv,Dod_MdnTrapServiceTokenUrl:iv,Dod_MdnTrapRelaySkypeFqdns:nv,Dod_MdnTrapRelayTurnFqdns:rv,Dod_MdnTrapRelayTurnUrl:sv,AirGap08_ConversationServiceUrl:av,AirGap08_TrouterServiceUrl:ov,AirGap08_RegistrarServiceUrl:lv,AirGap09_ConversationServiceUrl:cv,AirGap09_TrouterServiceUrl:dv,AirGap09_RegistrarServiceUrl:uv,Enterprise_ConversationServiceUrl:hv,Enterprise_TrouterServiceUrl:gv,Enterprise_RegistrarServiceUrl:pv,Enterprise_MdnTrapServiceUrl:mv,Enterprise_MdnTrapServiceTokenUrl:fv,Enterprise_MdnTrapRelaySkypeFqdns:vv,Enterprise_MdnTrapRelayTurnFqdns:Sv,Enterprise_MdnTrapRelayTurnUrl:yv},applicationSettingsEudbUrls:{Public_ConversationServiceUrl_EUDB:Lf.Public_ConversationServiceUrl_EUDB,Public_TrouterServiceUrl_EUDB:Lf.Public_TrouterServiceUrl_EUDB,Public_RegistrarServiceUrl_EUDB:Lf.Public_RegistrarServiceUrl_EUDB,Public_MdnTrapServiceUrl_EUDB:Lf.Public_MdnTrapServiceUrl_EUDB,Public_MdnTrapServiceTokenUrl_EUDB:Lf.Public_MdnTrapServiceTokenUrl_EUDB,Public_MdnTrapRelaySkypeFqdns_EUDB:Lf.Public_MdnTrapRelaySkypeFqdns_EUDB,Public_MdnTrapRelayTurnFqdns_EUDB:Lf.Public_MdnTrapRelayTurnFqdns_EUDB,Public_MdnTrapRelayTurnUrl_EUDB:Lf.Public_MdnTrapRelayTurnUrl_EUDB,Enterprise_ConversationServiceUrl_EUDB:Lf.Enterprise_ConversationServiceUrl_EUDB,Enterprise_TrouterServiceUrl_EUDB:Lf.Enterprise_TrouterServiceUrl_EUDB,Enterprise_RegistrarServiceUrl_EUDB:Lf.Enterprise_RegistrarServiceUrl_EUDB,Enterprise_MdnTrapServiceUrl_EUDB:Lf.Enterprise_MdnTrapServiceUrl_EUDB,Enterprise_MdnTrapServiceTokenUrl_EUDB:Lf.Enterprise_MdnTrapServiceTokenUrl_EUDB,Enterprise_MdnTrapRelaySkypeFqdns_EUDB:Lf.Enterprise_MdnTrapRelaySkypeFqdns_EUDB,Enterprise_MdnTrapRelayTurnFqdns_EUDB:Lf.Enterprise_MdnTrapRelayTurnFqdns_EUDB,Enterprise_MdnTrapRelayTurnUrl_EUDB:Lf.Enterprise_MdnTrapRelayTurnUrl_EUDB},maxDisplayNameLength:256,callDiagnostics:Nv,eudb:{isEnabled:!0,countries:Av,regions:Pv,defaultDataLocationEurope:!1,EmeaTenants:Rv,ApacTenants:Mv,NoamTenants:Dv,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:"28:9cd07db6-fab5-438c-8e34-44117fac7650",gccBotId:"28:b102ccd8-1925-448b-90a7-b083aba25074",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},vdi3:{enabled:!0,cdnBaseUrl:"https://res.public.onecdn.static.microsoft/ic3-1/pluginless/",cdnUrl:"",customTsVersion:"",loaderHtmlPath:"skype-calling-pluginless.loader.html",pluginlessJsPath:"skype-calling-pluginless.cdn.js",transportConnectionTimeoutInMs:3e4,remoteExecutionTimeoutInMs:3e4,chunkSize:7e5,customEcsConfig:""},roles:{acsOrganizer:Lv.AcsOrganizerRole,acsPresenter:Lv.AcsPresenterRole,acsAttendee:Lv.AcsAttendeeRole,acsConsumer:Lv.AcsConsumerRole,teamsAttendee:Lv.TeamsAttendee,teamsOrganizer:Lv.TeamsOrganizer,teamsPresenter:Lv.TeamsPresenter,teamsCoorganizer:Lv.TeamsCoorganizer},roomsRoleBasedCapabilities:{presenter:yy(uy.Rooms,"Presenter"),attendee:yy(uy.Rooms,"Attendee"),consumer:yy(uy.Rooms,"Consumer")},teamsRoleBasedCapabilities:{organizer:yy(uy.TeamsMeeting,"Organizer"),coorganizer:yy(uy.TeamsMeeting,"Co-organizer"),presenter:yy(uy.TeamsMeeting,"Presenter"),attendee:yy(uy.TeamsMeeting,"Attendee")},environments:{android:{chrome:{minVersion:Yv,isSupportedOnSdkVersion:Qv},edgeanaheim:{minVersion:Yv,isSupportedOnSdkVersion:Qv}},ios:{safari:{minVersion:Yv,isSupportedOnSdkVersion:Qv},chrome:{minVersion:Yv,isSupportedOnSdkVersion:!US().includes("stable")},edgeanaheim:{minVersion:Yv,isSupportedOnSdkVersion:!US().includes("stable")},applewebview:{minVersion:Yv,isSupportedOnSdkVersion:Qv}},mac:{chrome:{minVersion:Yv,isSupportedOnSdkVersion:Qv},safari:{minVersion:Yv,isSupportedOnSdkVersion:Qv},edgeanaheim:{minVersion:Yv,isSupportedOnSdkVersion:Qv},firefox:{minVersion:Yv,isSupportedOnSdkVersion:!US().includes("stable")}},windows:{chrome:{minVersion:Yv,isSupportedOnSdkVersion:Qv},chromium:{minVersion:Yv,isSupportedOnSdkVersion:Qv},edgeanaheim:{minVersion:Yv,isSupportedOnSdkVersion:Qv},firefox:{minVersion:Yv,isSupportedOnSdkVersion:!US().includes("stable")}},linux:{chrome:{minVersion:Yv,isSupportedOnSdkVersion:Qv},firefox:{minVersion:Yv,isSupportedOnSdkVersion:!US().includes("stable")}}},MiddleTier:{enabled:!1,maxRetry:3,baseServiceUrl:"https://global.mtgw.prod.communication.microsoft.com/",policyUrlSuffix:"acsmt/v1/useraggregatepolicysettings/",policyUrlSuffixV2:"acsmt/v2/useraggregatepolicysettings/",userPolicySettingsApi:!1,serverManagedThreadIdApiConfiguration:{allowServerThreadCreation:!0,decoupleChatThreadFromCalls:!0,createThreadSuffix:"acsmt/v1/threads/",addParticipantSuffix:"acsmt/v1/addParticipantsToThread/"}},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 fy;function vy(){return my}function Sy(){return fy}function yy(e,t){const i={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(e==uy.TeamsMeeting){if("Co-organizer"==t||"Organizer"==t)return{...i};if("Presenter"==t){const e={...i};return e.hangUpForEveryOne=!1,e}if("Attendee"==t){const e={...i};return e.removeParticipant=!1,e.manageLobby=!1,e.spotlightParticipant=!1,e.removeParticipantsSpotlight=!1,e.shareScreen=!1,e.muteOthers=!1,e.hangUpForEveryOne=!1,e.startTogetherMode=!1,e.joinBreakoutRooms=!0,e.forbidOthersAudio=!1,e.forbidOthersVideo=!1,e}}if(e==uy.Rooms){const e={...i};if(e.removeParticipant=!1,e.hangUpForEveryOne=!1,e.addCommunicationUser=!1,e.addTeamsUser=!1,e.manageLobby=!1,e.spotlightParticipant=!1,e.removeParticipantsSpotlight=!1,e.blurBackground=!1,e.startLiveMeetingCaptions=!0,e.startLiveCallingCaptions=!0,e.setCaptionLanguage=!1,e.raiseHand=!1,e.startTogetherMode=!1,e.joinBreakoutRooms=!1,e.forbidOthersAudio=!1,e.forbidOthersVideo=!1,"Presenter"==t)return{...e};if("Attendee"==t){const t={...e};return t.shareScreen=!1,t.muteOthers=!1,t.addPhoneNumber=!1,t.pstnDialOut=!1,t}if("Consumer"==t){const t={...e};return t.turnVideoOn=!1,t.unmuteMic=!1,t.shareScreen=!1,t.muteOthers=!1,t.addPhoneNumber=!1,t.pstnDialOut=!1,t}}return i}const Cy=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason"];function Ty(e){switch(e){case"Crop":return 1;case"Fit":return 2;default:return 0}}function Ey(e){return e.toString===Object.prototype.toString?JSON.stringify(e):e.toString()}function by(e,t){try{return"string"==typeof e?new Blob([e]).size:e.byteLength}catch(e){return t.error(e),0}}function _y(e){let t={};return e.forEach(((e,i)=>{t[i]=e})),Object.freeze(t)}function Iy(e,t="Timed promise; rejected."){let i,n,r,s=!0;const a=()=>{window.clearTimeout(r)};let o=new Promise(((e,t)=>{i=t=>{a(),s=!1,e(t)},n=e=>{a(),s=!1,t(e)}}));return{timerStart:()=>{r=window.setTimeout((()=>{n(new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EFFECT_PROVIDER_TIMEOUT}))}),e)},timerStop:a,deferredPromise:{promise:o,resolve:i,reject:n,isPending:()=>s,dispose:()=>{n("disposed")}}}}function wy(e,t){if(null==e)throw new le({defaultError:t})}function Ay(e,t){if("object"!=typeof e)throw new le({defaultError:t})}function Py(e){let[,t]=e?.split(".");if(void 0===t)throw new le({defaultError:ee.INTERNAL.TOKEN_PAYLOAD_UNDEFINED});return t=t.replace(/-/g,"+").replace(/_/g,"/"),JSON.parse(decodeURIComponent(escape(atob(t))))}function Ry(e,t){throw t.error(`CallingCommunicationError: Message={${e.message},Code={${e.code}}, SubCode={${e.subCode}}, ResultCategories={${e.resultCategories}}`),new le({defaultError:e})}function My(){}function Dy(e,t){return vy().calling.eudb.isEnabled&&function(e,t){const i=function(e){return ky(e)?vy().calling.eudb.regions:vy().calling.eudb.countries}(e);return!!t&&!!i.find((e=>e===t))}(e,t||"")}function ky(e){return vy().calling.eudb.isRgnClaimEnabledForACS||!!e&&e===wv.Enterprise||!1}async function Oy(e,t,i){let n;try{if(!e)throw new le({defaultError:ee.INTERNAL.NO_TOKEN_PROVIDED});try{n=(await e.getToken(i))?.token}catch(e){throw new le("The token returned from the tokenRefresher is expired."===e.message?{defaultError:ee.CALL_AGENT.ACCESSTOKEN_EXPIRED}:{defaultError:ee.INTERNAL.GET_TOKEN})}if(!n)throw new le({defaultError:ee.INTERNAL.EMPTY_TOKEN})}catch(e){throw new le({defaultError:ee.INTERNAL.GET_TOKEN,originalError:e})}try{let e=Py(n);if(!e)throw new le({defaultError:ee.INTERNAL.TOKEN_UNDEFINED});if("string"!=typeof e.acsScope)throw new le({defaultError:ee.INTERNAL.INVALID_TOKEN_SCOPE_FORMAT});if(!e.acsScope.split(",").find((e=>"voip"===e||"voip.join"===e)))throw new le({defaultError:ee.INTERNAL.INVALID_TOKEN_SCOPE});const i=e.resourceId,r=kS(`8:${e.skypeid}`);if(!i&&"microsoftTeamsUser"!==r?.kind)throw new le({defaultError:ee.INTERNAL.RESOURCE_NOT_FOUND_IN_TOKEN});let s=e.skypeid;if(!s)throw new le({defaultError:ee.INTERNAL.USERID_NOT_FOUND_IN_TOKEN});const a=function(e){const t=e.substring(0,e.indexOf(":"));if(!t)throw new le({defaultError:ee.IDENTIFIER.NO_CLOUD_PREFIX_FOUND});switch(t){case Nf.OrgId:case Nf.Acs:case Nf.Spool:return Of.Public;case Nf.GccHigh:case Nf.GccHighAcs:return Of.GccHigh;case Nf.Dod:case Nf.DodAcs:return Of.Dod;case Nf.AirGap08:case Nf.AirGap08Acs:return Of.AirGap08;case Nf.AirGap09:case Nf.AirGap09Acs:return Of.AirGap09;default:return Of.Public}}(s),o=!!e.tid,l=!!e.rgn,c=(o||t?e.rgn:e.resourceLocation)||"";let d=!1;return o&&(d=!!e.aad_pft),{jwtToken:n,acsResourceId:i,identityMri:s,cloudType:a,isCte:o,region:c,rgnClaimExists:l,exp:1e3*e.exp,aadpftClaimExists:d}}catch(e){throw new le({defaultError:ee.INTERNAL.PARSE_TOKEN_FAIL,originalError:e})}}function Ny(e,t=!1){if(void 0===e)return"void";if(e instanceof Error)return e.toString();if(e instanceof String||e instanceof Number||e instanceof Boolean)return e.toString();try{return e.stack&&(e.stack=(e=>{try{return e.split("\n")[0]}catch(e){return"invalid stack"}})(e.stack)),(t?JSON.stringify(e):JSON.stringify(e,Cy,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(t){return`failed to get error information:${e&&"function"==typeof e.toString&&e.toString()} ${e&&e.response&&JSON.stringify(e.response)}`}}function Ly(e,t){return t.info("permission state to boolean",e),"granted"===e}function xy(e,t,i=[]){let n=[];try{const r=Array.isArray(e);for(const s in e){const a=e[s],o=r?+s:s;if(!(s in t)){n.push({type:"REMOVE",path:[o],oldValue:e[s]});continue}const l=t[s],c="object"==typeof a&&"object"==typeof l;if(a&&l&&c&&!se[Object.getPrototypeOf(a).constructor.name]&&!i.includes(a)){const e=xy(a,l);n.push.apply(n,e.map((e=>(e.path.unshift(o),e))))}else a===l||c&&(isNaN(a)?a+""==l+"":+a==+l)||n.push({path:[o],type:"CHANGE",value:l,oldValue:a})}const s=Array.isArray(t);for(const i in t)i in e||n.push({type:"CREATE",path:[s?+i:i],value:t[i]})}catch(e){}return n}function Fy(e,t){const i={[e.roles.acsOrganizer.toLowerCase()]:yS.Organizer,[e.roles.teamsOrganizer.toLowerCase()]:yS.Organizer,[e.roles.acsPresenter.toLowerCase()]:yS.Presenter,[e.roles.teamsPresenter.toLowerCase()]:yS.Presenter,[e.roles.acsAttendee.toLowerCase()]:yS.Attendee,[e.roles.teamsAttendee.toLowerCase()]:yS.Attendee,[e.roles.acsConsumer.toLowerCase()]:yS.Consumer,[e.roles.teamsCoorganizer.toLowerCase()]:yS.Coorganizer};return t&&i[t.toString().toLowerCase()]?i[t.toString().toLowerCase()]:yS.Unknown}function Uy(e){let t=1;return e.participantCounts&&e.participantCounts.totalParticipants>0&&(t=e.participantCounts.totalParticipants),e.participants&&(t-=e.participants.filter((e=>By(e))).length),t}function By(e){if(OS(e.id)){if(function(e){return!(!e.startsWith(iS)||e.startsWith(pS)||e.startsWith(fS)||e.startsWith(mS))}(e.id))return!0;if(vy()?.calling?.blacklistedBots?.includes(e.id))return!0;if(e.endpoints?.endpointDetails&&e.endpoints?.endpointDetails.length>0)return e.endpoints?.endpointDetails[0].endpointMetadata?.__platform?.ui?.hidden}return!1}function Vy(e,t,i,n,r){if(i||n&&"microsoftTeamsUser"===n.kind||r&&function(e){return!!(e.meetingId||e.meetingLink||e.messageId||e.organizerId||e.tenantId||e.threadId)}(r)){const i=vy().calling.allowProxyForTeamsCalls,n=e.proxyInUse,r=vy().calling.allowCustomTurnForTeamsCalls,s=t.customRelayManagerInUse;if(n&&!i)return!1;if(s&&!r)return!1}return!0}function Hy(e,t){let i=t==de.TeamsCallAgent?"communicationUser":"microsoftTeamsUser";return!!e.find((e=>B(e).kind===i))}function $y(e){if(!e||!e.customContext)return;const t={},i={};if(e.customContext.userToUser&&(t[vy().calling.customContext.userToUser.headerKey]=e.customContext.userToUser),e.customContext.xHeaders&&!e.customContext.sipHeaders){const i=vy().calling.customContext.xHeaders.headerKeyPrefix,n=new RegExp(vy().calling.customContext.xHeaders.headerKeyRegex),r=new RegExp(vy().calling.customContext.xHeaders.headerValueRegex);e.customContext.xHeaders.forEach((e=>{const t=e.key.toLowerCase().startsWith(i.toLowerCase());e.key=t?`${i}${e.key.slice(i.length)}`:`${i}${e.key}`})),e.customContext.xHeaders.filter((e=>n.test(e.key)&&r.test(e.value))).slice(0,vy().calling.customContext.xHeaders.maxCount).forEach((e=>t[e.key]=e.value))}if(e.customContext.sipHeaders){const i=vy().calling.customContext.xHeaders.headerKeyPrefix,n=new RegExp(vy().calling.customContext.xHeaders.headerKeyRegex),r=new RegExp(vy().calling.customContext.xHeaders.headerValueRegex);e.customContext.sipHeaders.forEach((e=>{const t=e.key.toLowerCase().startsWith(i.toLowerCase());e.key=t?`${i}${e.key.slice(i.length)}`:`${i}${e.key}`})),e.customContext.sipHeaders.filter((e=>n.test(e.key)&&r.test(e.value))).slice(0,vy().calling.customContext.xHeaders.maxCount).forEach((e=>t[e.key]=e.value))}e.customContext.voipHeaders&&e.customContext.voipHeaders.forEach((e=>i[e.key]=e.value));const n={};return Object.keys(t).length>0&&(n.sipHeaders=t),Object.keys(i).length>0&&(n.voipHeaders=i),Object.keys(t).length>0||Object.keys(i).length>0?n:void 0}function jy(e){return Gy(e.customHeaderContext)||Gy(e.clientTransferContext)}function Gy(e){if(!e)return;const t=e.sipHeaders||e.customContext?.sipHeaders,i=e.voipHeaders||e.customContext?.voipHeaders;if(!t&&!i)return;const n=vy().calling.customContext.userToUser.headerKey,r=vy().calling.customContext.xHeaders.headerKeyPrefix,s=t&&Object.entries(t).find((e=>e[0]?.toLowerCase()===n.toLowerCase())),a=t&&Object.entries(t).filter((e=>e[0]?.toLowerCase().startsWith(r?.toLowerCase()))).map((e=>({key:e[0],value:e[1]}))),o=i&&Object.entries(i).map((e=>({key:e[0],value:e[1]}))),l={};return t&&s&&(l.userToUser=s[1]),a&&a.length>0&&(l.xHeaders=a,l.sipHeaders=a),o&&o.length>0&&(l.voipHeaders=o),void 0===l.userToUser&&0===l.xHeaders?.length&&0===l.sipHeaders?.length&&0===l.voipHeaders?.length?void 0:l}var qy=G((function(e,t){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;t.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},t.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),r);else for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){var t,i,n,r,s,a;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(a=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)s=e[t],a.set(s,r),r+=s.length;return a}},r={arraySet:function(e,t,i,n,r){for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){return[].concat.apply([],e)}};t.setTyped=function(e){e?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,n)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,r))},t.setTyped(i)}));function zy(e){for(var t=e.length;--t>=0;)e[t]=0}var Wy=[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],Ky=[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],Jy=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Yy=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Qy=new Array(576);zy(Qy);var Zy=new Array(60);zy(Zy);var Xy=new Array(512);zy(Xy);var eC=new Array(256);zy(eC);var tC=new Array(29);zy(tC);var iC,nC,rC,sC=new Array(30);function aC(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function oC(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function lC(e){return e<256?Xy[e]:Xy[256+(e>>>7)]}function cC(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function dC(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,cC(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function uC(e,t,i){dC(e,i[2*t],i[2*t+1])}function hC(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function gC(e,t,i){var n,r,s=new Array(16),a=0;for(n=1;n<=15;n++)s[n]=a=a+i[n-1]<<1;for(r=0;r<=t;r++){var o=e[2*r+1];0!==o&&(e[2*r]=hC(s[o]++,o))}}function pC(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function mC(e){e.bi_valid>8?cC(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function fC(e,t,i,n){var r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]}function vC(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&fC(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!fC(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function SC(e,t,i){var n,r,s,a,o=0;if(0!==e.last_lit)do{n=e.pending_buf[e.d_buf+2*o]<<8|e.pending_buf[e.d_buf+2*o+1],r=e.pending_buf[e.l_buf+o],o++,0===n?uC(e,r,t):(uC(e,(s=eC[r])+256+1,t),0!==(a=Wy[s])&&dC(e,r-=tC[s],a),uC(e,s=lC(--n),i),0!==(a=Ky[s])&&dC(e,n-=sC[s],a))}while(o<e.last_lit);uC(e,256,t)}function yC(e,t){var i,n,r,s=t.dyn_tree,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<l;i++)0!==s[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):s[2*i+1]=0;for(;e.heap_len<2;)s[2*(r=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[r]=0,e.opt_len--,o&&(e.static_len-=a[2*r+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)vC(e,s,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],vC(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,s[2*r]=s[2*i]+s[2*n],e.depth[r]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,s[2*i+1]=s[2*n+1]=r,e.heap[1]=r++,vC(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,r,s,a,o,l=t.dyn_tree,c=t.max_code,d=t.stat_desc.static_tree,u=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,g=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=15;s++)e.bl_count[s]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(s=l[2*l[2*(n=e.heap[i])+1]+1]+1)>p&&(s=p,m++),l[2*n+1]=s,n>c||(e.bl_count[s]++,a=0,n>=g&&(a=h[n-g]),o=l[2*n],e.opt_len+=o*(s+a),u&&(e.static_len+=o*(d[2*n+1]+a)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(n=e.bl_count[s];0!==n;)(r=e.heap[--i])>c||(l[2*r+1]!==s&&(e.opt_len+=(s-l[2*r+1])*l[2*r],l[2*r+1]=s),n--)}}(e,t),gC(s,c,e.bl_count)}function CC(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=a,a=t[2*(n+1)+1],++o<l&&r===a||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4))}function TC(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),n=0;n<=i;n++)if(r=a,a=t[2*(n+1)+1],!(++o<l&&r===a)){if(o<c)do{uC(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==s&&(uC(e,r,e.bl_tree),o--),uC(e,16,e.bl_tree),dC(e,o-3,2)):o<=10?(uC(e,17,e.bl_tree),dC(e,o-3,3)):(uC(e,18,e.bl_tree),dC(e,o-11,7));o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4)}}zy(sC);var EC=!1;function bC(e,t,i,n){dC(e,0+(n?1:0),3),function(e,t,i){mC(e),cC(e,i),cC(e,~i),qy.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}(e,t,i)}var _C,IC={_tr_init:function(e){EC||(function(){var e,t,i,n,r,s=new Array(16);for(i=0,n=0;n<28;n++)for(tC[n]=i,e=0;e<1<<Wy[n];e++)eC[i++]=n;for(eC[i-1]=n,r=0,n=0;n<16;n++)for(sC[n]=r,e=0;e<1<<Ky[n];e++)Xy[r++]=n;for(r>>=7;n<30;n++)for(sC[n]=r<<7,e=0;e<1<<Ky[n]-7;e++)Xy[256+r++]=n;for(t=0;t<=15;t++)s[t]=0;for(e=0;e<=143;)Qy[2*e+1]=8,e++,s[8]++;for(;e<=255;)Qy[2*e+1]=9,e++,s[9]++;for(;e<=279;)Qy[2*e+1]=7,e++,s[7]++;for(;e<=287;)Qy[2*e+1]=8,e++,s[8]++;for(gC(Qy,287,s),e=0;e<30;e++)Zy[2*e+1]=5,Zy[2*e]=hC(e,5);iC=new aC(Qy,Wy,257,286,15),nC=new aC(Zy,Ky,0,30,15),rC=new aC(new Array(0),Jy,0,19,7)}(),EC=!0),e.l_desc=new oC(e.dyn_ltree,iC),e.d_desc=new oC(e.dyn_dtree,nC),e.bl_desc=new oC(e.bl_tree,rC),e.bi_buf=0,e.bi_valid=0,pC(e)},_tr_stored_block:bC,_tr_flush_block:function(e,t,i,n){var r,s,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),yC(e,e.l_desc),yC(e,e.d_desc),a=function(e){var t;for(CC(e,e.dyn_ltree,e.l_desc.max_code),CC(e,e.dyn_dtree,e.d_desc.max_code),yC(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Yy[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?bC(e,t,i,n):4===e.strategy||s===r?(dC(e,2+(n?1:0),3),SC(e,Qy,Zy)):(dC(e,4+(n?1:0),3),function(e,t,i,n){var r;for(dC(e,t-257,5),dC(e,i-1,5),dC(e,n-4,4),r=0;r<n;r++)dC(e,e.bl_tree[2*Yy[r]+1],3);TC(e,e.dyn_ltree,t-1),TC(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),SC(e,e.dyn_ltree,e.dyn_dtree)),pC(e),n&&mC(e)},_tr_tally:function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(eC[i]+256+1)]++,e.dyn_dtree[2*lC(t)]++),e.last_lit===e.lit_bufsize-1},_tr_align:function(e){dC(e,2,3),uC(e,256,Qy),function(e){16===e.bi_valid?(cC(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},wC=function(e,t,i,n){for(var r=65535&e,s=e>>>16&65535,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{s=s+(r=r+t[n++]|0)|0}while(--a);r%=65521,s%=65521}return r|s<<16},AC=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}(),PC=function(e,t,i,n){var r=AC,s=n+i;e^=-1;for(var a=n;a<s;a++)e=e>>>8^r[255&(e^t[a])];return~e},RC={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"},MC=-2,DC=258,kC=262,OC=103,NC=113,LC=666;function xC(e,t){return e.msg=RC[t],t}function FC(e){return(e<<1)-(e>4?9:0)}function UC(e){for(var t=e.length;--t>=0;)e[t]=0}function BC(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(qy.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function VC(e,t){IC._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,BC(e.strm)}function HC(e,t){e.pending_buf[e.pending++]=t}function $C(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function jC(e,t,i,n){var r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,qy.arraySet(t,e.input,e.next_in,r,i),1===e.state.wrap?e.adler=wC(e.adler,t,r,i):2===e.state.wrap&&(e.adler=PC(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)}function GC(e,t){var i,n,r=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,l=e.strstart>e.w_size-kC?e.strstart-(e.w_size-kC):0,c=e.window,d=e.w_mask,u=e.prev,h=e.strstart+DC,g=c[s+a-1],p=c[s+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(c[(i=t)+a]===p&&c[i+a-1]===g&&c[i]===c[s]&&c[++i]===c[s+1]){s+=2,i++;do{}while(c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&s<h);if(n=DC-(h-s),s=h-DC,n>a){if(e.match_start=t,a=n,n>=o)break;g=c[s+a-1],p=c[s+a]}}}while((t=u[t&d])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function qC(e){var t,i,n,r,s,a=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=a+(a-kC)){qy.arraySet(e.window,e.window,a,a,0),e.match_start-=a,e.strstart-=a,e.block_start-=a,t=i=e.hash_size;do{n=e.head[--t],e.head[t]=n>=a?n-a:0}while(--i);t=i=a;do{n=e.prev[--t],e.prev[t]=n>=a?n-a:0}while(--i);r+=a}if(0===e.strm.avail_in)break;if(i=jC(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=i,e.lookahead+e.insert>=3)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+3-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<kC&&0!==e.strm.avail_in)}function zC(e,t){for(var i,n;;){if(e.lookahead<kC){if(qC(e),e.lookahead<kC&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-kC&&(e.match_length=GC(e,i)),e.match_length>=3)if(n=IC._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=IC._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(VC(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(VC(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(VC(e,!1),0===e.strm.avail_out)?1:2}function WC(e,t){for(var i,n,r;;){if(e.lookahead<kC){if(qC(e),e.lookahead<kC&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-kC&&(e.match_length=GC(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=IC._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(VC(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=IC._tr_tally(e,0,e.window[e.strstart-1]))&&VC(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=IC._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(VC(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(VC(e,!1),0===e.strm.avail_out)?1:2}function KC(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}function JC(){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=8,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 qy.Buf16(1146),this.dyn_dtree=new qy.Buf16(122),this.bl_tree=new qy.Buf16(78),UC(this.dyn_ltree),UC(this.dyn_dtree),UC(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new qy.Buf16(16),this.heap=new qy.Buf16(573),UC(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new qy.Buf16(573),UC(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 YC(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:NC,e.adler=2===t.wrap?0:1,t.last_flush=0,IC._tr_init(t),0):xC(e,MC)}function QC(e){var t=YC(e);return 0===t&&function(e){e.window_size=2*e.w_size,UC(e.head),e.max_lazy_match=_C[e.level].max_lazy,e.good_match=_C[e.level].good_length,e.nice_match=_C[e.level].nice_length,e.max_chain_length=_C[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0}(e.state),t}function ZC(e,t,i,n,r,s){if(!e)return MC;var a=1;if(-1===t&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),r<1||r>9||8!==i||n<8||n>15||t<0||t>9||s<0||s>4)return xC(e,MC);8===n&&(n=9);var o=new JC;return e.state=o,o.strm=e,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new qy.Buf8(2*o.w_size),o.head=new qy.Buf16(o.hash_size),o.prev=new qy.Buf16(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new qy.Buf8(o.pending_buf_size),o.d_buf=o.lit_bufsize>>1,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=s,o.method=i,QC(e)}_C=[new KC(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(qC(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,VC(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-kC&&(VC(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(VC(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(VC(e,!1),e.strm.avail_out),1)})),new KC(4,4,8,4,zC),new KC(4,5,16,8,zC),new KC(4,6,32,32,zC),new KC(4,4,16,16,WC),new KC(8,16,32,32,WC),new KC(8,16,128,128,WC),new KC(8,32,128,256,WC),new KC(32,128,258,1024,WC),new KC(32,258,258,4096,WC)];var XC={deflateInit:function(e,t){return ZC(e,t,8,15,8,0)},deflateInit2:ZC,deflateReset:QC,deflateResetKeep:YC,deflateSetHeader:function(e,t){return e&&e.state?2!==e.state.wrap?MC:(e.state.gzhead=t,0):MC},deflate:function(e,t){var i,n,r,s;if(!e||!e.state||t>5||t<0)return e?xC(e,MC):MC;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||n.status===LC&&4!==t)return xC(e,0===e.avail_out?-5:MC);if(n.strm=e,i=n.last_flush,n.last_flush=t,42===n.status)if(2===n.wrap)e.adler=0,HC(n,31),HC(n,139),HC(n,8),n.gzhead?(HC(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),HC(n,255&n.gzhead.time),HC(n,n.gzhead.time>>8&255),HC(n,n.gzhead.time>>16&255),HC(n,n.gzhead.time>>24&255),HC(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),HC(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(HC(n,255&n.gzhead.extra.length),HC(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=PC(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(HC(n,0),HC(n,0),HC(n,0),HC(n,0),HC(n,0),HC(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),HC(n,3),n.status=NC);else{var a=8+(n.w_bits-8<<4)<<8;a|=(n.strategy>=2||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(a|=32),a+=31-a%31,n.status=NC,$C(n,a),0!==n.strstart&&($C(n,e.adler>>>16),$C(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),BC(e),r=n.pending,n.pending!==n.pending_buf_size));)HC(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),BC(e),r=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,HC(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),0===s&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),BC(e),r=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,HC(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>r&&(e.adler=PC(e.adler,n.pending_buf,n.pending-r,r)),0===s&&(n.status=OC)}else n.status=OC;if(n.status===OC&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&BC(e),n.pending+2<=n.pending_buf_size&&(HC(n,255&e.adler),HC(n,e.adler>>8&255),e.adler=0,n.status=NC)):n.status=NC),0!==n.pending){if(BC(e),0===e.avail_out)return n.last_flush=-1,0}else if(0===e.avail_in&&FC(t)<=FC(i)&&4!==t)return xC(e,-5);if(n.status===LC&&0!==e.avail_in)return xC(e,-5);if(0!==e.avail_in||0!==n.lookahead||0!==t&&n.status!==LC){var o=2===n.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(qC(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=IC._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(VC(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(VC(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(VC(e,!1),0===e.strm.avail_out)?1:2}(n,t):3===n.strategy?function(e,t){for(var i,n,r,s,a=e.window;;){if(e.lookahead<=DC){if(qC(e),e.lookahead<=DC&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=a[r=e.strstart-1])===a[++r]&&n===a[++r]&&n===a[++r]){s=e.strstart+DC;do{}while(n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&r<s);e.match_length=DC-(s-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=IC._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=IC._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(VC(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(VC(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(VC(e,!1),0===e.strm.avail_out)?1:2}(n,t):_C[n.level].func(n,t);if(3!==o&&4!==o||(n.status=LC),1===o||3===o)return 0===e.avail_out&&(n.last_flush=-1),0;if(2===o&&(1===t?IC._tr_align(n):5!==t&&(IC._tr_stored_block(n,0,0,!1),3===t&&(UC(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),BC(e),0===e.avail_out))return n.last_flush=-1,0}return 4!==t?0:n.wrap<=0?1:(2===n.wrap?(HC(n,255&e.adler),HC(n,e.adler>>8&255),HC(n,e.adler>>16&255),HC(n,e.adler>>24&255),HC(n,255&e.total_in),HC(n,e.total_in>>8&255),HC(n,e.total_in>>16&255),HC(n,e.total_in>>24&255)):($C(n,e.adler>>>16),$C(n,65535&e.adler)),BC(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?0:1)},deflateEnd:function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==OC&&t!==NC&&t!==LC?xC(e,MC):(e.state=null,t===NC?xC(e,-3):0):MC},deflateSetDictionary:function(e,t){var i,n,r,s,a,o,l,c,d=t.length;if(!e||!e.state)return MC;if(2===(s=(i=e.state).wrap)||1===s&&42!==i.status||i.lookahead)return MC;for(1===s&&(e.adler=wC(e.adler,t,d,0)),i.wrap=0,d>=i.w_size&&(0===s&&(UC(i.head),i.strstart=0,i.block_start=0,i.insert=0),c=new qy.Buf8(i.w_size),qy.arraySet(c,t,d-i.w_size,i.w_size,0),t=c,d=i.w_size),a=e.avail_in,o=e.next_in,l=e.input,e.avail_in=d,e.next_in=0,e.input=t,qC(i);i.lookahead>=3;){n=i.strstart,r=i.lookahead-2;do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+3-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--r);i.strstart=n,i.lookahead=2,qC(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=o,e.input=l,e.avail_in=a,i.wrap=s,0},deflateInfo:"pako deflate (from Nodeca project)"},eT=!0,tT=!0;try{String.fromCharCode.apply(null,[0])}catch($){eT=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch($){tT=!1}for(var iT=new qy.Buf8(256),nT=0;nT<256;nT++)iT[nT]=nT>=252?6:nT>=248?5:nT>=240?4:nT>=224?3:nT>=192?2:1;function rT(e,t){if(t<65537&&(e.subarray&&tT||!e.subarray&&eT))return String.fromCharCode.apply(null,qy.shrinkBuf(e,t));for(var i="",n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i}iT[254]=iT[254]=1;var sT=function(e){var t,i,n,r,s,a=e.length,o=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new qy.Buf8(o),s=0,r=0;s<o;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},aT=function(e){return rT(e,e.length)},oT=function(e,t){var i,n,r,s,a=t||e.length,o=new Array(2*a);for(n=0,i=0;i<a;)if((r=e[i++])<128)o[n++]=r;else if((s=iT[r])>4)o[n++]=65533,i+=s-1;else{for(r&=2===s?31:3===s?15:7;s>1&&i<a;)r=r<<6|63&e[i++],s--;s>1?o[n++]=65533:r<65536?o[n++]=r:(r-=65536,o[n++]=55296|r>>10&1023,o[n++]=56320|1023&r)}return rT(o,n)},lT=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+iT[e[i]]>t?i:t},cT=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},dT=Object.prototype.toString;function uT(e){if(!(this instanceof uT))return new uT(e);this.options=qy.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new cT,this.strm.avail_out=0;var i=XC.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==i)throw new Error(RC[i]);if(t.header&&XC.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"==typeof t.dictionary?sT(t.dictionary):"[object ArrayBuffer]"===dT.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(i=XC.deflateSetDictionary(this.strm,n)))throw new Error(RC[i]);this._dict_set=!0}}function hT(e,t){var i=new uT(t);if(i.push(e,!0),i.err)throw i.msg;return i.result}uT.prototype.push=function(e,t){var i,n,r=this.strm,s=this.options.chunkSize;if(this.ended)return!1;n=t===~~t?t:!0===t?4:0,"string"==typeof e?r.input=sT(e):"[object ArrayBuffer]"===dT.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(0===r.avail_out&&(r.output=new qy.Buf8(s),r.next_out=0,r.avail_out=s),1!==(i=XC.deflate(r,n))&&0!==i)return this.onEnd(i),this.ended=!0,!1;0!==r.avail_out&&(0!==r.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(aT(qy.shrinkBuf(r.output,r.next_out))):this.onData(qy.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||0===r.avail_out)&&1!==i);return 4===n?(i=XC.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,0===i):2!==n||(this.onEnd(0),r.avail_out=0,!0)},uT.prototype.onData=function(e){this.chunks.push(e)},uT.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=qy.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var gT={Deflate:uT,deflate:hT,deflateRaw:function(e,t){return(t=t||{}).raw=!0,hT(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,hT(e,t)}},pT=function(e,t){var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w;i=e.state,n=e.next_in,I=e.input,r=n+(e.avail_in-5),s=e.next_out,w=e.output,a=s-(t-e.avail_out),o=s+(e.avail_out-257),l=i.dmax,c=i.wsize,d=i.whave,u=i.wnext,h=i.window,g=i.hold,p=i.bits,m=i.lencode,f=i.distcode,v=(1<<i.lenbits)-1,S=(1<<i.distbits)-1;e:do{p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=m[g&v];t:for(;;){if(g>>>=C=y>>>24,p-=C,0==(C=y>>>16&255))w[s++]=65535&y;else{if(!(16&C)){if(64&C){if(32&C){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}y=m[(65535&y)+(g&(1<<C)-1)];continue t}for(T=65535&y,(C&=15)&&(p<C&&(g+=I[n++]<<p,p+=8),T+=g&(1<<C)-1,g>>>=C,p-=C),p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=f[g&S];;){if(g>>>=C=y>>>24,p-=C,16&(C=y>>>16&255)){if(E=65535&y,p<(C&=15)&&(g+=I[n++]<<p,(p+=8)<C&&(g+=I[n++]<<p,p+=8)),(E+=g&(1<<C)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(g>>>=C,p-=C,E>(C=s-a)){if((C=E-C)>d&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(b=0,_=h,0===u){if(b+=c-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}else if(u<C){if(b+=c+u-C,(C-=u)<T){T-=C;do{w[s++]=h[b++]}while(--C);if(b=0,u<T){T-=C=u;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}}else if(b+=u-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}for(;T>2;)w[s++]=_[b++],w[s++]=_[b++],w[s++]=_[b++],T-=3;T&&(w[s++]=_[b++],T>1&&(w[s++]=_[b++]))}else{b=s-E;do{w[s++]=w[b++],w[s++]=w[b++],w[s++]=w[b++],T-=3}while(T>2);T&&(w[s++]=w[b++],T>1&&(w[s++]=w[b++]))}break}if(64&C){e.msg="invalid distance code",i.mode=30;break e}y=f[(65535&y)+(g&(1<<C)-1)]}}break}}while(n<r&&s<o);n-=T=p>>3,g&=(1<<(p-=T<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=s<o?o-s+257:257-(s-o),i.hold=g,i.bits=p},mT=[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],fT=[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],vT=[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],ST=[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],yT=function(e,t,i,n,r,s,a,o){var l,c,d,u,h,g,p,m,f,v=o.bits,S=0,y=0,C=0,T=0,E=0,b=0,_=0,I=0,w=0,A=0,P=null,R=0,M=new qy.Buf16(16),D=new qy.Buf16(16),k=null,O=0;for(S=0;S<=15;S++)M[S]=0;for(y=0;y<n;y++)M[t[i+y]]++;for(E=v,T=15;T>=1&&0===M[T];T--);if(E>T&&(E=T),0===T)return r[s++]=20971520,r[s++]=20971520,o.bits=1,0;for(C=1;C<T&&0===M[C];C++);for(E<C&&(E=C),I=1,S=1;S<=15;S++)if(I<<=1,(I-=M[S])<0)return-1;if(I>0&&(0===e||1!==T))return-1;for(D[1]=0,S=1;S<15;S++)D[S+1]=D[S]+M[S];for(y=0;y<n;y++)0!==t[i+y]&&(a[D[t[i+y]]++]=y);if(0===e?(P=k=a,g=19):1===e?(P=mT,R-=257,k=fT,O-=257,g=256):(P=vT,k=ST,g=-1),A=0,y=0,S=C,h=s,b=E,_=0,d=-1,u=(w=1<<E)-1,1===e&&w>852||2===e&&w>592)return 1;for(;;){p=S-_,a[y]<g?(m=0,f=a[y]):a[y]>g?(m=k[O+a[y]],f=P[R+a[y]]):(m=96,f=0),l=1<<S-_,C=c=1<<b;do{r[h+(A>>_)+(c-=l)]=p<<24|m<<16|f}while(0!==c);for(l=1<<S-1;A&l;)l>>=1;if(0!==l?(A&=l-1,A+=l):A=0,y++,0==--M[S]){if(S===T)break;S=t[i+a[y]]}if(S>E&&(A&u)!==d){for(0===_&&(_=E),h+=C,I=1<<(b=S-_);b+_<T&&!((I-=M[b+_])<=0);)b++,I<<=1;if(w+=1<<b,1===e&&w>852||2===e&&w>592)return 1;r[d=A&u]=E<<24|b<<16|h-s}}return 0!==A&&(r[h+A]=S-_<<24|64<<16),o.bits=E,0},CT=-2,TT=12,ET=30;function bT(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function _T(){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 qy.Buf16(320),this.work=new qy.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function IT(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new qy.Buf32(852),t.distcode=t.distdyn=new qy.Buf32(592),t.sane=1,t.back=-1,0):CT}function wT(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,IT(e)):CT}function AT(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?CT:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,wT(e))):CT}function PT(e,t){var i,n;return e?(n=new _T,e.state=n,n.window=null,0!==(i=AT(e,t))&&(e.state=null),i):CT}var RT,MT,DT=!0;function kT(e){if(DT){var t;for(RT=new qy.Buf32(512),MT=new qy.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(yT(1,e.lens,0,288,RT,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;yT(2,e.lens,0,32,MT,0,e.work,{bits:5}),DT=!1}e.lencode=RT,e.lenbits=9,e.distcode=MT,e.distbits=5}function OT(e,t,i,n){var r,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new qy.Buf8(s.wsize)),n>=s.wsize?(qy.arraySet(s.window,t,i-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((r=s.wsize-s.wnext)>n&&(r=n),qy.arraySet(s.window,t,i-n,r,s.wnext),(n-=r)?(qy.arraySet(s.window,t,i-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0}var NT={inflateReset:wT,inflateReset2:AT,inflateResetKeep:IT,inflateInit:function(e){return PT(e,15)},inflateInit2:PT,inflate:function(e,t){var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w=0,A=new qy.Buf8(4),P=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return CT;(i=e.state).mode===TT&&(i.mode=13),a=e.next_out,r=e.output,l=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,u=o,h=l,b=0;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;d<16;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(2&i.wrap&&35615===c){i.check=0,A[0]=255&c,A[1]=c>>>8&255,i.check=PC(i.check,A,2,0),c=0,d=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=ET;break}if(8!=(15&c)){e.msg="unknown compression method",i.mode=ET;break}if(d-=4,E=8+(15&(c>>>=4)),0===i.wbits)i.wbits=E;else if(E>i.wbits){e.msg="invalid window size",i.mode=ET;break}i.dmax=1<<E,e.adler=i.check=1,i.mode=512&c?10:TT,c=0,d=0;break;case 2:for(;d<16;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(i.flags=c,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=ET;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=ET;break}i.head&&(i.head.text=c>>8&1),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=PC(i.check,A,2,0)),c=0,d=0,i.mode=3;case 3:for(;d<32;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.head&&(i.head.time=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,A[2]=c>>>16&255,A[3]=c>>>24&255,i.check=PC(i.check,A,4,0)),c=0,d=0,i.mode=4;case 4:for(;d<16;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.head&&(i.head.xflags=255&c,i.head.os=c>>8),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=PC(i.check,A,2,0)),c=0,d=0,i.mode=5;case 5:if(1024&i.flags){for(;d<16;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.length=c,i.head&&(i.head.extra_len=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=PC(i.check,A,2,0)),c=0,d=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((g=i.length)>o&&(g=o),g&&(i.head&&(E=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),qy.arraySet(i.head.extra,n,s,g,E)),512&i.flags&&(i.check=PC(i.check,n,g,s)),o-=g,s+=g,i.length-=g),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===o)break e;g=0;do{E=n[s+g++],i.head&&E&&i.length<65536&&(i.head.name+=String.fromCharCode(E))}while(E&&g<o);if(512&i.flags&&(i.check=PC(i.check,n,g,s)),o-=g,s+=g,E)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===o)break e;g=0;do{E=n[s+g++],i.head&&E&&i.length<65536&&(i.head.comment+=String.fromCharCode(E))}while(E&&g<o);if(512&i.flags&&(i.check=PC(i.check,n,g,s)),o-=g,s+=g,E)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;d<16;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(c!==(65535&i.check)){e.msg="header crc mismatch",i.mode=ET;break}c=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=TT;break;case 10:for(;d<32;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}e.adler=i.check=bT(c),c=0,d=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=a,e.avail_out=l,e.next_in=s,e.avail_in=o,i.hold=c,i.bits=d,2;e.adler=i.check=1,i.mode=TT;case TT:if(5===t||6===t)break e;case 13:if(i.last){c>>>=7&d,d-=7&d,i.mode=27;break}for(;d<3;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}switch(i.last=1&c,d-=1,3&(c>>>=1)){case 0:i.mode=14;break;case 1:if(kT(i),i.mode=20,6===t){c>>>=2,d-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=ET}c>>>=2,d-=2;break;case 14:for(c>>>=7&d,d-=7&d;d<32;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if((65535&c)!=(c>>>16^65535)){e.msg="invalid stored block lengths",i.mode=ET;break}if(i.length=65535&c,c=0,d=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(g=i.length){if(g>o&&(g=o),g>l&&(g=l),0===g)break e;qy.arraySet(r,n,s,g,a),o-=g,s+=g,l-=g,a+=g,i.length-=g;break}i.mode=TT;break;case 17:for(;d<14;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(i.nlen=257+(31&c),c>>>=5,d-=5,i.ndist=1+(31&c),c>>>=5,d-=5,i.ncode=4+(15&c),c>>>=4,d-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=ET;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;d<3;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.lens[P[i.have++]]=7&c,c>>>=3,d-=3}for(;i.have<19;)i.lens[P[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,_={bits:i.lenbits},b=yT(0,i.lens,0,19,i.lencode,0,i.work,_),i.lenbits=_.bits,b){e.msg="invalid code lengths set",i.mode=ET;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;v=(w=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(S<16)c>>>=f,d-=f,i.lens[i.have++]=S;else{if(16===S){for(I=f+2;d<I;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(c>>>=f,d-=f,0===i.have){e.msg="invalid bit length repeat",i.mode=ET;break}E=i.lens[i.have-1],g=3+(3&c),c>>>=2,d-=2}else if(17===S){for(I=f+3;d<I;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}d-=f,E=0,g=3+(7&(c>>>=f)),c>>>=3,d-=3}else{for(I=f+7;d<I;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}d-=f,E=0,g=11+(127&(c>>>=f)),c>>>=7,d-=7}if(i.have+g>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=ET;break}for(;g--;)i.lens[i.have++]=E}}if(i.mode===ET)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=ET;break}if(i.lenbits=9,_={bits:i.lenbits},b=yT(1,i.lens,0,i.nlen,i.lencode,0,i.work,_),i.lenbits=_.bits,b){e.msg="invalid literal/lengths set",i.mode=ET;break}if(i.distbits=6,i.distcode=i.distdyn,_={bits:i.distbits},b=yT(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,_),i.distbits=_.bits,b){e.msg="invalid distances set",i.mode=ET;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(o>=6&&l>=258){e.next_out=a,e.avail_out=l,e.next_in=s,e.avail_in=o,i.hold=c,i.bits=d,pT(e,h),a=e.next_out,r=e.output,l=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,i.mode===TT&&(i.back=-1);break}for(i.back=0;v=(w=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(v&&!(240&v)){for(y=f,C=v,T=S;v=(w=i.lencode[T+((c&(1<<y+C)-1)>>y)])>>>16&255,S=65535&w,!(y+(f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}c>>>=y,d-=y,i.back+=y}if(c>>>=f,d-=f,i.back+=f,i.length=S,0===v){i.mode=26;break}if(32&v){i.back=-1,i.mode=TT;break}if(64&v){e.msg="invalid literal/length code",i.mode=ET;break}i.extra=15&v,i.mode=22;case 22:if(i.extra){for(I=i.extra;d<I;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.length+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;v=(w=i.distcode[c&(1<<i.distbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(!(240&v)){for(y=f,C=v,T=S;v=(w=i.distcode[T+((c&(1<<y+C)-1)>>y)])>>>16&255,S=65535&w,!(y+(f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}c>>>=y,d-=y,i.back+=y}if(c>>>=f,d-=f,i.back+=f,64&v){e.msg="invalid distance code",i.mode=ET;break}i.offset=S,i.extra=15&v,i.mode=24;case 24:if(i.extra){for(I=i.extra;d<I;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}i.offset+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=ET;break}i.mode=25;case 25:if(0===l)break e;if(g=h-l,i.offset>g){if((g=i.offset-g)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=ET;break}g>i.wnext?(g-=i.wnext,p=i.wsize-g):p=i.wnext-g,g>i.length&&(g=i.length),m=i.window}else m=r,p=a-i.offset,g=i.length;g>l&&(g=l),l-=g,i.length-=g;do{r[a++]=m[p++]}while(--g);0===i.length&&(i.mode=21);break;case 26:if(0===l)break e;r[a++]=i.length,l--,i.mode=21;break;case 27:if(i.wrap){for(;d<32;){if(0===o)break e;o--,c|=n[s++]<<d,d+=8}if(h-=l,e.total_out+=h,i.total+=h,h&&(e.adler=i.check=i.flags?PC(i.check,r,h,a-h):wC(i.check,r,h,a-h)),h=l,(i.flags?c:bT(c))!==i.check){e.msg="incorrect data check",i.mode=ET;break}c=0,d=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;d<32;){if(0===o)break e;o--,c+=n[s++]<<d,d+=8}if(c!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=ET;break}c=0,d=0}i.mode=29;case 29:b=1;break e;case ET:b=-3;break e;case 31:return-4;default:return CT}return e.next_out=a,e.avail_out=l,e.next_in=s,e.avail_in=o,i.hold=c,i.bits=d,(i.wsize||h!==e.avail_out&&i.mode<ET&&(i.mode<27||4!==t))&&OT(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,i.total+=h,i.wrap&&h&&(e.adler=i.check=i.flags?PC(i.check,r,h,e.next_out-h):wC(i.check,r,h,e.next_out-h)),e.data_type=i.bits+(i.last?64:0)+(i.mode===TT?128:0)+(20===i.mode||15===i.mode?256:0),(0===u&&0===h||4===t)&&0===b&&(b=-5),b},inflateEnd:function(e){if(!e||!e.state)return CT;var t=e.state;return t.window&&(t.window=null),e.state=null,0},inflateGetHeader:function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,0):CT},inflateSetDictionary:function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?CT:11===i.mode&&wC(1,t,n,0)!==i.check?-3:OT(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,0):CT},inflateInfo:"pako inflate (from Nodeca project)"},LT={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},xT=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},FT=Object.prototype.toString;function UT(e){if(!(this instanceof UT))return new UT(e);this.options=qy.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new cT,this.strm.avail_out=0;var i=NT.inflateInit2(this.strm,t.windowBits);if(i!==LT.Z_OK)throw new Error(RC[i]);this.header=new xT,NT.inflateGetHeader(this.strm,this.header)}function BT(e,t){var i=new UT(t);if(i.push(e,!0),i.err)throw i.msg;return i.result}UT.prototype.push=function(e,t){var i,n,r,s,a,o,l=this.strm,c=this.options.chunkSize,d=this.options.dictionary,u=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?LT.Z_FINISH:LT.Z_NO_FLUSH,"string"==typeof e?l.input=function(e){for(var t=new qy.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t}(e):"[object ArrayBuffer]"===FT.call(e)?l.input=new Uint8Array(e):l.input=e,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new qy.Buf8(c),l.next_out=0,l.avail_out=c),(i=NT.inflate(l,LT.Z_NO_FLUSH))===LT.Z_NEED_DICT&&d&&(o="string"==typeof d?sT(d):"[object ArrayBuffer]"===FT.call(d)?new Uint8Array(d):d,i=NT.inflateSetDictionary(this.strm,o)),i===LT.Z_BUF_ERROR&&!0===u&&(i=LT.Z_OK,u=!1),i!==LT.Z_STREAM_END&&i!==LT.Z_OK)return this.onEnd(i),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&i!==LT.Z_STREAM_END&&(0!==l.avail_in||n!==LT.Z_FINISH&&n!==LT.Z_SYNC_FLUSH)||("string"===this.options.to?(r=lT(l.output,l.next_out),s=l.next_out-r,a=oT(l.output,r),l.next_out=s,l.avail_out=c-s,s&&qy.arraySet(l.output,l.output,r,s,0),this.onData(a)):this.onData(qy.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(u=!0)}while((l.avail_in>0||0===l.avail_out)&&i!==LT.Z_STREAM_END);return i===LT.Z_STREAM_END&&(n=LT.Z_FINISH),n===LT.Z_FINISH?(i=NT.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===LT.Z_OK):n!==LT.Z_SYNC_FLUSH||(this.onEnd(LT.Z_OK),l.avail_out=0,!0)},UT.prototype.onData=function(e){this.chunks.push(e)},UT.prototype.onEnd=function(e){e===LT.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=qy.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var VT={Inflate:UT,inflate:BT,inflateRaw:function(e,t){return(t=t||{}).raw=!0,BT(e,t)},ungzip:BT},HT={};(0,qy.assign)(HT,gT,VT,LT);var $T=HT;function jT(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)},dispose:()=>{i&&(t("disposed"),i=!1)}}}function GT(e){return new Promise((t=>qT(t,e)))}function qT(e,t){return globalThis.setTimeout(e,t)}function zT(e){globalThis.clearTimeout(e)}function WT(e,t){const i=jT();let n;try{n=e()}catch(e){return Promise.reject(i.reject(e))}if(t<0)return n.finally((()=>{i.resolve(n)})),i.promise;const r=qT((()=>{i.isPending()&&i.reject(new le({defaultError:ee.INTERNAL.OPERATION_TIMEDOUT}))}),t);return n.catch((e=>{zT(r),i.isPending()&&i.reject(e)})).finally((()=>{zT(r),i.isPending()&&i.resolve(n)})),i.promise}var KT=function(e,t){var i=e.toString(),n=t.toString();return i>n?1:i<n?-1:0};function JT(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function YT(e,t,i){return t&&JT(e.prototype,t),i&&JT(e,i),e}var QT=function(){function e(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).comparator,i=void 0===t?KT:t;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(this,"comparator",void 0),this.comparator=i}return YT(e,null,[{key:"from",value:function(e,t){throw new Error("not implemented")}}]),YT(e,[{key:"clear",value:function(){throw new Error("not implemented")}},{key:"toArray",value:function(){throw new Error("not implemented")}},{key:"push",value:function(e){throw new Error("not implemented")}},{key:"enqueue",value:function(e){return this.push(e)}},{key:"top",value:function(){throw new Error("not implemented")}},{key:"peek",value:function(){return this.top()}},{key:"pop",value:function(){throw new Error("not implemented")}},{key:"dequeue",value:function(){return this.pop()}},{key:"merge",value:function(e){throw new Error("not implemented")}},{key:"isEmpty",value:function(){throw new Error("not implemented")}},{key:"length",get:function(){throw new Error("not implemented")}}]),e}();function ZT(e){return ZT="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ZT(e)}function XT(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function eE(e){return eE=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},eE(e)}function tE(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function iE(e,t){return iE=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},iE(e,t)}function nE(e,t,i){var n=function(e,t,i){var n=2*t,r=2*t+1,s=t;return n<e.length&&i(e[s],e[n])<0&&(s=n),r<e.length&&i(e[s],e[r])<0&&(s=r),s}(e,t,i);if(n!==t){var r=e[t];e[t]=e[n],e[n]=r,nE(e,n,i)}}function rE(e){for(var t=Math.floor(e.collection.length/2)-1;t>=0;--t)nE(e.collection,t,e.comparator)}var sE,aE,oE,lE,cE,dE,uE,hE=function(){function e(){var t,i;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(tE(i=function(e,t){return!t||"object"!==ZT(t)&&"function"!=typeof t?tE(e):t}(this,(t=eE(e)).call.apply(t,[this].concat(r)))),"collection",[]),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&iE(e,t)}(e,QT),function(e,t,i){t&&XT(e.prototype,t),i&&XT(e,i)}(e,[{key:"clear",value:function(){this.collection.length=0}},{key:"toArray",value:function(){return function(e){return function(e){if(Array.isArray(e)){for(var t=0,i=new Array(e.length);t<e.length;t++)i[t]=e[t];return i}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}(this.collection).sort(this.comparator)}},{key:"top",value:function(){if(0===this.length)throw new Error("invalid operation: top() called for empty BinaryHeap");return this.collection[0]}},{key:"pop",value:function(){if(0===this.length)throw new Error("invalid operation: pop() called for empty BinaryHeap");var e=this.collection[0];return this.collection.length>1?(this.collection[0]=this.collection.pop(),nE(this.collection,0,this.comparator)):this.collection.pop(),e}},{key:"push",value:function(e){this.collection.push(e);for(var t=this.collection,i=t.length-1,n=Math.floor(i/2);i>0&&this.comparator(t[n],t[i])<0;i=n,n=Math.floor(n/2)){var r=t[i];t[i]=t[n],t[n]=r}}},{key:"merge",value:function(t){this.collection=t instanceof e?this.collection.concat(t.collection):this.collection.concat(t.toArray()),rE(this),t.clear()}},{key:"isEmpty",value:function(){return!this.collection.length}},{key:"length",get:function(){return this.collection.length}}],[{key:"from",value:function(t){var i=new e(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return i.collection=Array.from(t),rE(i),i}}]),e}(),gE=hE;class pE{constructor(e,t){this._tenantId=e,this.listeners=[],this._logger=t.createChild(`TelemetryLogger[${e}]`);const i=this._tenantId;t.log(`Notification Manager Notification Manager logger initialized for tenant ${i}`),this._discardedEventsBufferPQ=new gE({comparator:(e,t)=>t.latency-e.latency})}addNotificationListener(e){this.listeners.find((t=>t===e))||this.listeners.push(e)}removeNotificationListener(e){this.listeners=this.listeners.filter((t=>t!==e))}eventsSent(e){const t=JSON.stringify(e);this._logger.log(`Notification Manager sent telemetry events ${t}`),this.listeners.forEach((t=>t.eventsSent&&t.eventsSent(e)))}eventsDiscarded(e,t){this._logger.log(`Notification Manager discarded telemetry events ${JSON.stringify(e)}, reason ${t} adding to retry buffer`),e.forEach((e=>{e.latency=e.latency||cd.Normal;const t=e;(t.sendAttempt||0)<=vy().telemetry.discardedEventsMaxRetries?this._discardedEventsBufferPQ.push(t):this._logger.log(`Notification Manager dropping event due to too many retries ${JSON.stringify(e)}`)}));const i=vy().telemetry.discardedEventsBufferMaxLength;for(;this._discardedEventsBufferPQ.length>i;)this._logger.log(` dropping event from retry buffer ${this._discardedEventsBufferPQ.dequeue()} due to overflow`);this.listeners.forEach((i=>i.eventsDiscarded&&i.eventsDiscarded(e,t)))}getDiscardedEvents(){const e=[],t=this._discardedEventsBufferPQ.length;for(let i=0;i<t;i++)e.push(this._discardedEventsBufferPQ.dequeue());return e}}class mE{constructor(e,t,i,n){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=e.createChild("TelemetryLogManager"),this.sdkDiagnosticInformation=t,this._sdkInternaVersion=FS(),this._acsProxy=i,this._acsCustomRelayManager=n,vy().telemetry.limit.rates.forEach((e=>{this._telemetryRateLimit.set(e.eventName,{...e,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(e){if(!e.cloudType)throw this._logger.error("Failed to initialize telemetry loggers, invalid cloud type provided."),new le({defaultError:ee.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 le({defaultError:ee.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE_ALREADY_INITIALIZED});this._telemetryLoggers.forEach(((t,i)=>{try{t.initialize(e),this._logger.log(`Initialized and flushed buffered telemetry logger for ${i}`)}catch(e){this._logger.warn(`Failed to initialize and flush buffered telemetry logger for ${i}`),this._telemetryLoggers.delete(i)}})),this._initialized=!0,this._caConfigBag=e,this._logger.log(`Telemetry log manager has been initialized for Call Client: ${this._caConfigBag.clientId}`)}clearTelemetryLoggers(){const e=this._telemetryLoggers.size;return this._telemetryLoggers=new Map,this._caConfigBag=void 0,this._initialized=!1,e}getMediaEventReportedPromise(e){if(!this._mediaEventsReportedForTheCall[e]){const t=jT();t.promise.catch(My),this._mediaEventsReportedForTheCall[e]=t}return this._mediaEventsReportedForTheCall[e].promise}_reportMediaEventForTheCall(e){if(this._mediaEventsReportedForTheCall[e])this._mediaEventsReportedForTheCall[e].resolve();else{const t=jT();t.promise.catch(My),t.resolve(),this._mediaEventsReportedForTheCall[e]=t}}_getEventDataWithoutPii(e){const t={};if(e.properties)for(const i of Object.keys(e.properties)){const n=e.properties[i];t[i]={value:n?.value??n,kind:n?.piiKind??0}}return t}sendEvent(e,t,i){try{const n=this._sentEventsMap.get(e.properties?.correlationId),r=n?.get(i)??0;if(void 0!==i&&r>0)return;if(i&&"attempt"!==i&&0===(n?.get("attempt")??0))return;if(this._logger.debug(`sending event=${e.name}`),this.checkIfEventIsBlocked(e)||this.shouldLimitSendingTelemetry(e.name)||this.isRateLimitExceeded(e.name))return void this._logger.debug(`event=${e.name} is blocked`);const s={name:e.name,data:e.properties};s?.name in TE&&(s.data=this._getEventDataWithoutPii(e)),void 0===s.data&&(s.data={}),s?.name===TE.mdsc_webrtc_session&&this._reportMediaEventForTheCall(s?.data?.CorrelationId),void 0!==typeof e.priority?s.latency=e.priority:s.latency=cd.Normal;const a=vy().telemetryEvents.eventNameToPriority.eventName.indexOf(e.name);-1!==a&&(s.latency=vy().telemetryEvents.eventNameToPriority.priority[a]),s.data.sdkVersion=this._sdkInternaVersion,s.data.platformId="3617";const o=`3617/${this._sdkInternaVersion}`;s.data.uiVersion=o,s.data.ui_version=o,s.data.Platform_Uiversion=o,s.data.userAgent=`${this.sdkDiagnosticInformation} ${navigator.userAgent}`,s.data.clientTimestamp=+new Date,s.data.customProxyAndRelayUsage=this.getCustomProxyAndRelayTag();const l=e.tenant;let c=this._eventsBufferMap.get(l);c||(c=this._eventsBufferMap.set(l,[]).get(l));let d=this._telemetryLoggers.get(l);if(d||(d=new fE(l,this._logger,c,this._acsProxy),this._telemetryLoggers.set(l,d),this._logger.log(`Created telemetry logger for ${l}`)),this._initialized){if(!d.isInitialized())try{d.initialize(this._caConfigBag),this._logger.log(`Created and initialized telemetry logger for ${l}`)}catch(e){throw this._telemetryLoggers.delete(l),c?.push(s),this._logger.error(`Failed to create and initialize telemetry logger for ${l}`),new le({defaultError:ee.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE,defaultErrorMessageArgs:[l]})}t&&d.getAppInsightsCore()?.addNotificationListener(t),d.sendEvent(s);const n=e.properties?.correlationId;if(void 0!==n&&void 0!==i){const e=this._sentEventsMap.get(n)??new Map;e.set(i,(e.get(i)??0)+1),this._sentEventsMap.set(n,e)}}else c?.push(s)}catch(t){this._logger.warn(`Failed to send event ${e?.name}`)}}deleteEventMapByCorrelationId(e){this._sentEventsMap.delete(e)}async flushAllEvents(e){if(this._logger.debug(`flushing events: ${this._telemetryLoggers.size}`),-1!==vy().telemetry.telemetryFlushTimeout){const t=(t,i)=>{try{const n=jT();n.promise.catch(My);const r=WT((async()=>(i===Uv&&await this.getMediaEventReportedPromise(e),n.promise)),vy().telemetry.telemetryFlushTimeout);return t.flushEvents((()=>{this._logger.debug("events flushed"),n.resolve()})),r.then(My)}catch(e){throw new le({defaultError:ee.INTERNAL.TELEMETRY_FAILED_TO_FLUSH})}},i=[];return this._telemetryLoggers.forEach(((e,n)=>{i.push(t(e,n).catch((()=>{this._logger.warn("Failed to flush telemetry")})))})),Promise.all(i)}this._telemetryLoggers.forEach((e=>{try{e.flushEvents()}catch(e){this._logger.warn("Failed to flush telemetry")}}))}checkIfEventIsBlocked(e){const t=e.name,i=e.properties?.kindOfEvent,n=vy().telemetry.blockedEvents,r=vy().telemetry.blockedKindOfEvents;return n.includes(t)||void 0!==r.find((e=>e.name==t&&e.kindOfEvents.includes(i)))}shouldLimitSendingTelemetry(e){return vy().telemetry.limit.outSideCall.enabled&&(0===vy().telemetry.limit.outSideCall.includedEvents.length||vy().telemetry.limit.outSideCall.includedEvents.includes(e))&&!vy().telemetry.limit.outSideCall.excludedEvents.includes(e)&&mE.callEndTimestamp!==Number.MAX_SAFE_INTEGER&&mE.callEndTimestamp+vy().telemetry.limit.outSideCall.deltaTimeInMs-Date.now()<0}isRateLimitExceeded(e){const t=this._telemetryRateLimit.get(e);if(t){const i=Date.now();if(i-t.windowStartTime>t.windowSizeInMs&&(t.windowStartTime=i,t.eventCount=0),t.eventCount++,t.eventCount>t.maxEventPerWindow)return this._logger.info(`Telemetry event ${e} is rate limited`),!0}return!1}getCustomProxyAndRelayTag(){const e=this._acsProxy?.proxyInUse??!1,t=this._acsCustomRelayManager?.hasRelayConfig??!1;return e&&t?TS.usedProxyAndNonMsftTurn:e?TS.onlyUsedProxy:t?TS.onlyUsedNonMsftTurn:TS.noCustomProxyAndTurnUsed}}mE.telemetryPayloadBytesOriginal=0,mE.telemetryPayloadBytesCompressed=0,mE.callEndTimestamp=0;class fE{constructor(e,t,i,n){this._tenantId=e,this._eventsBuffer=i,this._initialized=!1,this._networkOnline=!0,this._telemetryRetryIntervalRunning=!1,this._logger=t.createChild(`TelemetryLogger[${e}]`),this._acsProxy=n,window.addEventListener("online",(e=>{this._networkOnline=e.detail,this._networkOnline&&this._initialized&&!this._telemetryRetryIntervalRunning&&(this._logger.log("browser network back online starting telemetry send retry"),this.scheduleDiscardedTelemetryRetry())}))}initialize(e){if(this._initialized)this._logger.warn(`Telemetry logger for tenant: ${this._tenantId}, already initialized`);else try{const t=new Rf;this._appInsightsCore=new ld,this._postChannel=new cm;const i={instrumentationKey:this._tenantId,extensions:[this._postChannel,t],disableCookiesUsage:!0},n={populateBrowserInfo:!0,populateOperatingSystemInfo:!0};void 0===i.extensionConfig&&(i.extensionConfig={}),i.extensionConfig[t.identifier]=n;const r={overrideEndpointUrl:this.getAriaCollectorUrl(e),payloadPreprocessor:vy().telemetry.gzipTelemetryPayload?(e,t)=>{this.gzipPayload(e,t)}:void 0};if(i.extensionConfig[this._postChannel.identifier]=r,Object.keys(vy().calling?.eudb?.acsCompliantEvents).length>0&&(vE={...vE,...vy().calling.eudb.acsCompliantEvents}),vy().telemetry.localStorageEnable){const e=new dg;i.extensions?.push(e);const t={storageKey:"WebSdkTelemetry"};i.extensionConfig[e.identifier]=t}this._NotificationManager=new pE(this._tenantId,this._logger),this._appInsightsCore.initialize(i,[],void 0,this._NotificationManager),this._caConfigBag=e,this.scheduleDiscardedTelemetryRetry(),this._initialized=!0,this._eventsBuffer.forEach((e=>{this.sendEvent(e)})),this._eventsBuffer.splice(0,this._eventsBuffer.length)}catch(e){throw this._logger.error(`Failed to initialize telemetry logger for tenant: ${this._tenantId}`),new le({defaultError:ee.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(e){this._initialized&&(e?.name in vE&&this.appendEudbComplianceRegionToEvent(e),e?.data&&(e.data.clientId=this._caConfigBag?.clientId||"",0===e?.name?.indexOf("mdsc_webrtc")?e.data.metrics_AcsResourceId=this._caConfigBag?.acsResourceId||"":e.data.AcsResourceId=this._caConfigBag?.acsResourceId||"",e.data.cloudType=this._caConfigBag?.cloudType||"",e.data.identityType=this._caConfigBag?.identityType||""),this.sendAppInsightsCoreEvent(e))}scheduleDiscardedTelemetryRetry(){const e=vy().telemetry.discardedTelemetryRetryTimeout,t=setInterval((async()=>{this._networkOnline?(this._NotificationManager?.getDiscardedEvents().forEach((e=>{this.sendEvent(e)})),this._telemetryRetryIntervalRunning=!0):(this._logger.log("browser lost network access stopping telemetry send retry"),clearInterval(t),this._telemetryRetryIntervalRunning=!1)}),e)}sendAppInsightsCoreEvent(e){this._appInsightsCore?.track(e)}flushEvents(e){if(this._initialized&&this._postChannel){const t=vy().telemetry.asyncTelemetryFlush;this._postChannel.flush(t,e)}}getAriaCollectorUrl(e){const t=Dy(e.identityType,e.region);let i;if(e.identityType===wv.Enterprise)i=t?"https://eu-teams.events.data.microsoft.com/OneCollector/1.0":"https://teams.events.data.microsoft.com/OneCollector/1.0";else switch(e.cloudType){case Of.Public:i=t?"https://eu-ic3.events.data.microsoft.com/OneCollector/1.0/":kf;break;case Of.GccHigh:i="https://tb.events.data.microsoft.com/OneCollector/1.0/";break;case Of.Dod:i="https://pf.events.data.microsoft.com/OneCollector/1.0/";break;case Of.AirGap08:i="https://collector.azure.eaglex.ic.gov/OneCollector/1.0/";break;case Of.AirGap09:i="https://collector.azure.microsoft.scloud/OneCollector/1.0/";break;default:i=kf}return this._acsProxy?this._acsProxy.proxyfyUrl(i):i}gzipPayload(e,t){try{mE.telemetryPayloadBytesOriginal+=by(e.data,this._logger),e.data=$T.gzip(e.data),e.urlString+="&content-encoding=gzip",mE.telemetryPayloadBytesCompressed+=by(e.data,this._logger)}catch(e){this._logger.warn("Failed to gzip with pako: ",e)}t(e)}getRegion(e){if(this._caConfigBag&&ky(this._caConfigBag.identityType))switch(e){case"emea":case"de":return Ov.EMEA;case"apac":return Ov.APAC;case"noam":case"amer":return Ov.NOAM;default:return this._logger.log(`Unable to map region \`${e}\`, to EudbTenantRegion`),Ov.UNKNOWN}return e&&Rv.includes(e)?Ov.EMEA:e&&Mv.includes(e)?Ov.APAC:e&&Dv.includes(e)?Ov.NOAM:(this._logger.log(`Unable to map region \`${e}\`, to EudbTenantRegion`),Ov.UNKNOWN)}appendEudbComplianceRegionToEvent(e){const t=this.getTenantComplianceRegion(),i=this.getRegion(this._caConfigBag?.region);if(e.data){const n={};n[SE]=t,n[CE]=i,e.data[yE]=n}}getTenantComplianceRegion(){return this._caConfigBag&&Dy(this._caConfigBag.identityType,this._caConfigBag.region)?kv.EU:kv.RoW}}!function(e){e.remote_view="remote_view",e.remote_stream="remote_stream",e.network_quality="network_quality",e.video_device_issue="video_device_issue",e.other_diagnostic="other_diagnostic",e.logger_event="logger_event",e.number_of_participants="number_of_participants",e.media_metrics_device_events="media_metrics_device_events",e.sdk_active_in_another_tab="sdk_active_in_another_tab",e.network_changed="network_changed",e.video_max_capabilities="video_max_capabilities"}(sE||(sE={})),function(e){e.acs_calling_call_attempt="acs_calling_call_attempt",e.acs_calling_call_connected="acs_calling_call_connected",e.acs_calling_call_failed="acs_calling_call_failed",e.acs_calling_call_accept_attempt="acs_calling_call_accept_attempt",e.acs_calling_call_accept_connected="acs_calling_call_accept_connected",e.acs_calling_call_accept_failed="acs_calling_call_accept_failed",e.acs_calling_call_reject_attempt="acs_calling_call_reject_attempt",e.acs_calling_call_reject_success="acs_calling_call_reject_success",e.acs_calling_call_reject_failed="acs_calling_call_reject_failed",e.acs_calling_call_hangup_attempt="acs_calling_call_hangup_attempt",e.acs_calling_call_hangup_success="acs_calling_call_hangup_success",e.acs_calling_call_hangup_failure="acs_calling_call_hangup_failure",e.acs_calling_call_progress="acs_calling_call_progress",e.acs_calling_stack_init="acs_calling_stack_init",e.acs_calling_get_device_manager="acs_calling_get_device_manager",e.acs_calling_config_fetched_attempt="acs_calling_config_fetched_attempt",e.acs_calling_config_fetched_success="acs_calling_config_fetched_success",e.acs_calling_config_fetched_failure="acs_calling_config_fetched_failure",e.acs_calling_signaling_init="acs_calling_signaling_init",e.acs_calling_call_agent="acs_calling_call_agent",e.acs_calling_call_agent_init_attempt="acs_calling_call_agent_init_attempt",e.acs_calling_call_agent_init_success="acs_calling_call_agent_init_success",e.acs_calling_call_agent_init_failure="acs_calling_call_agent_init_failure",e.acs_calling_create_view_attempt="acs_calling_create_view_attempt",e.acs_calling_create_view_success="acs_calling_create_view_success",e.acs_calling_create_view_failure="acs_calling_create_view_failure",e.acs_calling_dispose_view_attempt="acs_calling_dispose_view_attempt",e.acs_calling_dispose_view_success="acs_calling_dispose_view_success",e.acs_calling_dispose_view_failure="acs_calling_dispose_view_failure",e.acs_calling_start_video_attempt="acs_calling_start_video_attempt",e.acs_calling_start_video_success="acs_calling_start_video_success",e.acs_calling_start_video_failure="acs_calling_start_video_failure",e.acs_calling_stop_video_on_ufd_attempt="acs_calling_stop_video_on_ufd_attempt",e.acs_calling_stop_video_attempt="acs_calling_stop_video_attempt",e.acs_calling_stop_video_success="acs_calling_stop_video_success",e.acs_calling_stop_video_failure="acs_calling_stop_video_failure",e.acs_calling_call_hold_and_resume="acs_calling_call_hold_and_resume",e.acs_calling_start_screen_share="acs_calling_start_screen_share",e.acs_calling_stop_screen_share="acs_calling_stop_screen_share",e.acs_calling_audio_stream_volume="acs_calling_audio_stream_volume",e.acs_calling_call_stats="acs_calling_call_stats",e.acs_calling_call_stats_and_ufds="acs_calling_call_stats_and_ufds",e.acs_calling_participant_added_or_removed="acs_calling_participant_added_or_removed",e.acs_calling_adp_attempt="acs_calling_adp_attempt",e.acs_calling_adp_success="acs_calling_adp_success",e.acs_calling_adp_failure="acs_calling_adp_failure",e.acs_calling_client_operations="acs_calling_client_operations",e.acs_calling_device_permission_changed="acs_calling_device_permission_changed",e.acs_calling_local_audio_source_changed="acs_calling_local_audio_source_changed",e.acs_calling_start_audio_stream_track="acs_calling_start_audio_stream_track",e.acs_calling_stop_audio_stream_track="acs_calling_stop_audio_stream_track",e.acs_calling_get_remote_audio_stream_track="acs_calling_get_remote_audio_stream_track",e.acs_calling_get_raw_device_media_stream="acs_calling_get_raw_device_media_stream",e.acs_calling_media_stream="acs_calling_media_stream",e.acs_calling_page_hidden="acs_calling_page_hidden",e.acs_calling_orientation_changed="acs_calling_orientation_changed",e.acs_calling_token_expiration_changed="acs_calling_token_expiration_changed",e.acs_calling_token_expiration_changed_failure="acs_calling_token_expiration_changed_failure",e.acs_calling_token_has_no_data_location="acs_calling_token_has_no_data_location",e.acs_calling_mute_on_ufd_attempt="acs_calling_mute_on_ufd_attempt",e.acs_calling_mute_attempt="acs_calling_mute_attempt",e.acs_calling_mute_success="acs_calling_mute_success",e.acs_calling_mute_failure="acs_calling_mute_failure",e.acs_calling_unmute_attempt="acs_calling_unmute_attempt",e.acs_calling_unmute_success="acs_calling_unmute_success",e.acs_calling_unmute_failure="acs_calling_unmute_failure",e.acs_calling_start_audio_attempt="acs_calling_start_audio_attempt",e.acs_calling_start_audio_success="acs_calling_start_audio_success",e.acs_calling_start_audio_failure="acs_calling_start_audio_failure",e.acs_calling_unmute_speaker_attempt="acs_calling_unmute_speaker_attempt",e.acs_calling_unmute_speaker_success="acs_calling_unmute_speaker_success",e.acs_calling_unmute_speaker_failure="acs_calling_unmute_speaker_failure",e.acs_calling_stop_audio_attempt="acs_calling_stop_audio_attempt",e.acs_calling_stop_audio_success="acs_calling_stop_audio_success",e.acs_calling_stop_audio_failure="acs_calling_stop_audio_failure",e.acs_calling_prevent_stop_audio="acs_calling_prevent_stop_audio",e.acs_calling_captions="acs_calling_captions",e.acs_calling_mid_call_media_stats="acs_calling_mid_call_media_stats",e.acs_calling_mid_call_new_media_stats="acs_calling_mid_call_new_media_stats",e.acs_calling_mid_call_raw_media_stats="acs_calling_mid_call_raw_media_stats",e.acs_calling_datachannel="acs_calling_datachannel",e.acs_calling_datachannel_stats="acs_calling_datachannel_stats",e.acs_calling_unmixed_audio="acs_calling_unmixed_audio",e.acs_calling_livestream_stats="acs_calling_livestream_stats",e.acs_calling_livestream_raw_stats="acs_calling_livestream_raw_stats",e.acs_calling_survey="acs_calling_survey",e.mdsc_call_quality_feedback="mdsc_call_quality_feedback",e.acs_calling_switch_video_source_attempt="acs_calling_switch_video_source_attempt",e.acs_calling_switch_video_source_success="acs_calling_switch_video_source_success",e.acs_calling_switch_video_source_failure="acs_calling_switch_video_source_failure",e.acs_calling_diagnostics_attempt="acs_calling_diagnostics_attempt",e.acs_calling_diagnostics_result="acs_calling_diagnostics_result",e.acs_calling_feature_usage="acs_calling_feature_usage",e.acs_calling_middletier_gateway_fetch_policy="acs_calling_middletier_gateway_fetch_policy",e.acs_calling_middletier_gateway_emergency_content="acs_calling_middletier_gateway_emergency_content",e.acs_calling_middletier_gateway_fetch_user_policies_for_captions="acs_calling_middletier_gateway_fetch_user_policies_for_captions",e.acs_calling_middletier_gateway_api="acs_calling_middletier_gateway_api",e.acs_calling_call_client_init="acs_calling_call_client_init",e.acs_calling_tab_events="acs_calling_tab_events",e.acs_calling_lobby_events="acs_calling_lobby_events",e.acs_calling_handle_push_notification="acs_calling_handle_push_notification"}(aE||(aE={})),function(e){e.attempt="attempt",e.success="success",e.failure="failure",e.getter="getter",e.setter="setter",e.subscribe="subscribe",e.unsubscribe="unsubscribe",e.initialize="initialize",e.event="event"}(oE||(oE={})),function(e){e.lobbyAdmit="lobbyAdmit",e.lobbyAdmitAll="lobbyAdmitAll",e.lobbyReject="lobbyReject"}(lE||(lE={})),function(e){e.MuteMicrophone="MuteMicrophone",e.MuteAllRemoteParticipants="MuteAllRemoteParticipants",e.MuteSpecificParticipant="MuteSpecificParticipant",e.UnmuteMicrophone="UnmuteMicrophone",e.MuteIncomingAudio="MuteIncomingAudio",e.UnmuteIncomingAudio="UnmuteIncomingAudio"}(cE||(cE={})),function(e){e.Expected="expected",e.Unexpected="unexpected",e.Unknown="unknown"}(dE||(dE={})),function(e){e.CaptionsKindChanged="CaptionsKindChanged",e.FirstCaptionReceived="FirstCaptionReceived",e.FirstCaptionParsingError="FirstCaptionParsingError",e.InitializeCaptions="InitializeCaptions",e.LanguageChanged="LanguageChanged",e.SetSpokenLanguage="SetSpokenLanguage",e.SetCaptionLanguage="SetCaptionLanguage",e.SpokenLanguageChanged="SpokenLanguageChanged",e.StartCaptions="StartCaptions",e.StopCaptions="StopCaptions",e.UpdateEndpointMetadata="UpdateEndpointMetadata",e.UpdateIsActive="UpdateIsActive",e.StartDataChannel="StartDataChannel"}(uE||(uE={}));let vE={...aE,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 SE="tenantComplianceRegion",yE="acsCompliancePayload",CE="tenantRegion";var TE,EE,bE,_E,IE,wE,AE;!function(e){e.mdsc_webrtc_session="mdsc_webrtc_session",e.mdsc_webrtc_session_initial="mdsc_webrtc_session_initial"}(TE||(TE={})),function(e){e.AudioRaw="AudioRaw",e.VideoRaw="VideoRaw",e.ScreenSharingRaw="ScreenSharingRaw",e.VideoRawOrScreenSharingRaw="VideoRawOrScreenSharingRaw",e.Audio="Audio",e.Video="Video"}(EE||(EE={})),function(e){e.Local="Local",e.Remote="Remote"}(bE||(bE={})),function(e){e.getMediaStream="getMediaStream",e.setMediaStream="setMediaStream",e.startEffects="startEffects",e.stopEffects="stopEffects",e.effectConfigureUpdate="effectConfigureUpdate",e.isSupported="isSupported",e.subscribe="subscribe",e.fpsWarningThresholdReached="fpsWarningThresholdReached",e.timeForEffectsWarningReached="timeForEffectsWarningReached",e.effectsError="effectsError",e.switchSource="switchSource",e.render="render",e.watermark="watermark"}(_E||(_E={})),function(e){e.stun="stun",e.turn="turn",e.turns="turns"}(IE||(IE={})),function(e){e.tcp="tcp",e.tls="tls",e.udp="udp"}(wE||(wE={})),function(e){e.Public_App="Public_App",e.Internal_LargeMeetingVideoRendering="Internal_LargeMeetingVideoRendering",e.Internal_RemoteVideoStreamDisposed="Internal_RemoteVideoStreamDisposed"}(AE||(AE={}));var PE,RE="object"==typeof Reflect?Reflect:null,ME=RE&&"function"==typeof RE.apply?RE.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};PE=RE&&"function"==typeof RE.ownKeys?RE.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var DE=Number.isNaN||function(e){return e!=e};function kE(){kE.init.call(this)}var OE=kE;kE.EventEmitter=kE,kE.prototype._events=void 0,kE.prototype._eventsCount=0,kE.prototype._maxListeners=void 0;var NE=10;function LE(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function xE(e){return void 0===e._maxListeners?kE.defaultMaxListeners:e._maxListeners}function FE(e,t,i,n){var r,s,a;if(LE(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=xE(e))>0&&a.length>r&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=a.length,function(e){console&&console.warn&&console.warn(e)}(o)}return e}function UE(){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 BE(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=UE.bind(n);return r.listener=i,n.wrapFn=r,r}function VE(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):$E(r,r.length)}function HE(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function $E(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}Object.defineProperty(kE,"defaultMaxListeners",{enumerable:!0,get:function(){return NE},set:function(e){if("number"!=typeof e||e<0||DE(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");NE=e}}),kE.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},kE.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||DE(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},kE.prototype.getMaxListeners=function(){return xE(this)},kE.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var o=r[e];if(void 0===o)return!1;if("function"==typeof o)ME(o,this,t);else{var l=o.length,c=$E(o,l);for(i=0;i<l;++i)ME(c[i],this,t)}return!0},kE.prototype.addListener=function(e,t){return FE(this,e,t,!1)},kE.prototype.on=kE.prototype.addListener,kE.prototype.prependListener=function(e,t){return FE(this,e,t,!0)},kE.prototype.once=function(e,t){return LE(t),this.on(e,BE(this,e,t)),this},kE.prototype.prependOnceListener=function(e,t){return LE(t),this.prependListener(e,BE(this,e,t)),this},kE.prototype.removeListener=function(e,t){var i,n,r,s,a;if(LE(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},kE.prototype.off=kE.prototype.removeListener,kE.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},kE.prototype.listeners=function(e){return VE(this,e,!0)},kE.prototype.rawListeners=function(e){return VE(this,e,!1)},kE.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):HE.call(e,t)},kE.prototype.listenerCount=HE,kE.prototype.eventNames=function(){return this._eventsCount>0?PE(this._events):[]},OE.once=function(e,t){return new Promise((function(i,n){function r(){void 0!==s&&e.removeListener("error",s),i([].slice.call(arguments))}var s;"error"!==t&&(s=function(i){e.removeListener(t,r),n(i)},e.once("error",s)),e.once(t,r)}))};class jE{constructor(e){this.disposed=!1,this.callAgent=e.callAgent,this.callClient=e.callClient,this.eventEmitter=new OE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class GE{constructor(e){this.disposed=!1,this.callClient=e.callClient,this.eventEmitter=new OE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class qE{constructor(e){this.disposed=!1,this.call=e.call,this.callAgent=e.callAgent,this.callInfo=e.callInfo,this.eventEmitter=new OE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class zE{constructor(e){this._logger=e,this._queue=Promise.resolve()}add(e){this._queue||(this._queue=Promise.resolve());let t=e;const i=this._queue?.then(t);return i&&(this._queue=i?.catch((e=>{throw e instanceof le?(this._logger?.error(`Error from promiseQueue! ${JSON.stringify(e)}`),e):new Error(`Error from promiseQueue! ${JSON.stringify(e)}`)}))),i}dispose(){this._queue=null}}const WE=()=>(e,t,i)=>{const n=i.value;return i.value=function(...e){return this.serialQueue.add(n.bind(this,...e))},i};class KE{constructor(e){this.disposed=!1,this.streamInstance=e.streamInstance,this.eventEmitter=new OE.EventEmitter,this.serialQueue=new zE(this.streamInstance.logger)}}class JE{constructor(e){this.disposed=!1,this.streamInstance=e.streamInstance,this.eventEmitter=new OE.EventEmitter,this.serialQueue=new zE(this.streamInstance.logger)}}var YE,QE;!function(e){e[e.CallClientFeature=0]="CallClientFeature",e[e.CallAgentFeature=1]="CallAgentFeature",e[e.CallFeature=2]="CallFeature"}(YE||(YE={}));class ZE extends qE{}class XE extends jE{}class eb extends GE{}class tb extends KE{}class ib extends JE{}!function(e){e.Transfer="Transfer",e.StartCaptions="StartCaptions",e.StopCaptions="StopCaptions",e.SetSpokenLanguage="SetSpokenLanguage",e.SetCaptionLanguage="SetCaptionLanguage",e.getMediaStatsCollector="getMediaStatsCollector",e.disposeAllCollectors="disposeAllCollectors"}(QE||(QE={}));class nb{constructor(e,t,i){this._logger=e,this._featureCtorContext=t,this._featureInitContext=i,this._apiObjInstances=new Map}getApiObjectInstance(e){if(!this._apiObjInstances.has(e)){const t=new e(this._featureCtorContext);return(t instanceof ZE||t instanceof XE||t instanceof eb||t instanceof tb||t instanceof ib)&&t.initialize(this._featureInitContext,this._logger),this._apiObjInstances.set(e,t),t}return this._apiObjInstances.get(e)}dispose(){for(const[,e]of this._apiObjInstances)e.dispose()}}const rb={commandUrl:"",processingModes:{closedCaptions:{state:"Inactive"},realTimeTranscript:{state:"Inactive"}},spokenLanguage:""};var sb,ab;!function(e){e.Acs="acs",e.Teams="teams",e.Unknown="unknown"}(sb||(sb={})),function(e){e.Captions="captions",e.TeamsCaptions="teams_captions"}(ab||(ab={}));class ob{constructor(e){this._eventEmitter=e,this._dataChannelId=vy().captions.dataChannelId,this._isCaptionsBot=e=>e.id===this._captionsBotMri||e.id===this._captionsLegacyBotMri,this._getBotMetadata=e=>e?.endpoints?.endpointDetails[0]?.endpointMetadata??void 0,this._getBotDataMediaStreamSourceId=e=>{if(e?.endpoints?.endpointDetails[0]?.mediaStreams){let t=e?.endpoints?.endpointDetails[0]?.mediaStreams;if(t.length>0)for(let e in t)if("data"===t[e].type)return t[e].sourceId}},this._isCaptionsEnabled=e=>"Active"===e?.processingModes?.closedCaptions?.state,this._copyBotMetaData=e=>{const t=this._getBotMetadata(e)||rb;return JSON.parse(JSON.stringify(t))}}dispose(){this._acsMetadata=void 0}}function lb(e,t={activationEvent:"OnFeatureAccess"}){return{get callApiCtor(){return e},activationOptions:t,isCallFeature:!0}}function cb(e,t={activationEvent:"OnFeatureAccess"}){return{get callClientApiCtor(){return e},activationOptions:t,isCallClientFeature:!0}}function db(e,t={activationEvent:"OnFeatureAccess"}){return{get videoStreamApiCtor(){return e},activationOptions:t,isVideoStreamFeature:!0}}function ub(e,t={activationEvent:"OnFeatureAccess"}){return{get audioStreamApiCtor(){return e},activationOptions:t,isAudioStreamFeature:!0}}function hb(e,t,i){try{const i={correlationId:e.correlationId||"",callId:e.callId,localParticipantId:e.localParticipantId,featureName:e.featureName,featureType:e.featureType,initializationType:e.initializationType,featureDetails:e.featureDetails,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};t.sendEvent({name:aE.acs_calling_feature_usage,tenant:xv,properties:i})}catch(t){i.debug(`Unable to send ${e.featureName} feature usage telemtery`)}}function gb(e,t,i){try{const i={featureName:e.featureName,featureType:e.featureType,initializationType:e.initializationType,featureDetails:e.featureDetails};t.sendEvent({name:aE.acs_calling_feature_usage,tenant:xv,properties:i})}catch(t){i.debug(`Unable to send ${e.featureName} feature usage telemetry`)}}const pb={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"},mb=e=>"number"==typeof e&&pb[e]||"UnknownError",fb={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"},vb=e=>"number"==typeof e&&fb[e]||"UnknownError",Sb={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"},yb={0:"None",1:"RealTime",2:"Streaming"};function Cb(e,t){let i=0,n=0,r=sS,s=[];return i=e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.callControllerCode||0,n=e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.callControllerSubCode||0,s=te[i]?.[n]?.resultCategories||e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.resultCategories||["Success"],r=te[i]?.[n]?.message||mb(t||e.tsCall?.terminatedReason||0),e.logger.error(`Call end reason=${r}, code=${i}, subCode=${n}, resultCategories=${s.toString()}`),{callEndReason:{message:r,code:i,subCode:n,resultCategories:s},callingCommunicationError:new le({defaultError:{message:r,code:i,subCode:n,resultCategories:s}})}}function Tb(e,t,i){let n=0,r=0,s=sS,a=[];if(t?.callEndDiagnosticsInfo)n=t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.callControllerCode||0,r=t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.callControllerSubCode||0,s=te[n]?.[r]?.message||vb(i||t.stateReason||0),a=te[n]?.[r]?.resultCategories||t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.resultCategories||["Success"];else{const t=Cb(e,i);n=t.callEndReason.code,r=t.callEndReason.subCode||0,a=t.callEndReason.resultCategories,s=t.callEndReason.message}return e.logger[0===n?"info":"error"](`Participant call end reason=${s}, code=${n}, subCode=${r}, resultCategories=${a.toString()}`),{callEndReason:{message:s,code:n,subCode:r,resultCategories:a},callingCommunicationError:new le({defaultError:{message:s,code:n,subCode:r,resultCategories:a}})}}function Eb(e,t,i){let n;switch(t?.type?t.type:ly.UnknownFailureForVideoOperation){case ly.DevicesNotFoundError:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.DEVICES_NOT_FOUND});break;case ly.MediaStreamRequestError:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_ERROR});break;case ly.MediaStreamRequestTimedout:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_TIMEDOUT});break;case ly.PermissionsDeniedBySystem:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.PERMISSION_DENIED_BY_SYSTEM});break;case ly.UnsupportedStream:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.UNSUPPORTED_STREAM});break;case ly.ConstraintNotSatisfiedError:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.CONSTRAINT_NOT_SATISFIED});break;case ly.noDeviceSelected:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.NO_DEVICE_SELECTED});break;case ly.SourceUnavailableError:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.SOURCE_UNAVAILABLE});break;case ly.PermissionDeniedError:case ly.permissionDeniedError:n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.PERMISSION_DENIED});break;default:n=new le(i?{defaultError:ee.CALL.STOP_VIDEO_FAILED}:{defaultError:ee.LOCAL_VIDEO_STREAM.UNKNOWN})}return n}function bb(e,t){return new le({defaultError:{message:t.message,code:e?.response?.status||t.code,subCode:t.subCode,resultCategories:t.resultCategories},originalError:e})}function _b(e){return{communicationServicesError:{message:e.message||"Unknown error",code:void 0===e.code?ne:e.code,subCode:e.subCode||0,resultCategories:void 0===e.resultCategories||0===e.resultCategories.length?["UnexpectedClientError"]:e.resultCategories,originalErrorMessage:e[ae]||""}}}function Ib(e){return{callEndReason:{message:e.message,code:void 0===e.code?ne:e.code,subCode:e.subCode||0,resultCategories:void 0===e.resultCategories||0===e.resultCategories.length?["UnexpectedClientError"]:e.resultCategories}}}var wb=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},Ab=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const Pb=Date.UTC(1900,0,1);class Rb{constructor(e,t){this._eventEmitter=t,this._impl=e}async startCaptions(e){await this._impl.startCaptions(e)}async stopCaptions(){await this._impl.stopCaptions()}async setSpokenLanguage(e){await this._impl.setSpokenLanguage(e)}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 Mb extends Rb{constructor(e,t){super(e,t)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}}class Db extends Rb{constructor(e,t){super(e,t)}get supportedCaptionLanguages(){return this._impl.supportedCaptionLanguages}get activeCaptionLanguage(){return this._impl.activeCaptionLanguage}async setCaptionLanguage(e){await this._impl.setCaptionLanguage(e)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}}class kb extends ob{constructor(e,t,i,n){super(e),this._botParticipantId="",this._isCteUser=!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=e=>{e.newValue.startLiveMeetingCaptions&&(this._participantCapability.startLiveMeetingCaptions=this._call.getParticipantCapabilities().startLiveMeetingCaptions,this._logger.log(`participant capabilitity to startLiveMeetingCaptions feature is ${this._participantCapability}`)),e.newValue.startLiveCallingCaptions&&(this._participantCapability.startLiveCallingCaptions=this._call.getParticipantCapabilities().startLiveCallingCaptions,this._logger.log(`participant capabilitity to startLiveCallingCaptions feature is ${this._participantCapability}`)),e.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(e,t)=>{},onStopped:async e=>{},onDataReceived:async(e,t,i)=>{let n;try{n=JSON.parse(t.toString())}catch(e){try{if(void 0===this._textDecoder)throw new Error("TextDecoder undefined.");n=JSON.parse(this._textDecoder.decode(t))}catch(e){return this._logger.error("Failed to parse Captions result",e),void(this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(uE.FirstCaptionParsingError,oE.failure,"",0,dE.Unexpected,"Could not decode data packet.")))}}if(n){let e=[];n.textTracks&&this._isCaptionInTextTracks(n)?e=n.textTracks:n.recognitionResults&&(e=n.recognitionResults),e.forEach((e=>{try{if("mt"!==e.source.toLowerCase()&&"ai"!==e.source.toLowerCase())return;const[t,n]=e.id.split("/");let r=parseInt(n,10);if(this._participantSequenceIdMap[e.userId]&&this._botParticipantId==t&&this._participantSequenceIdMap[e.userId]>r)return;this._botParticipantId=t,this._participantSequenceIdMap[e.userId]=r;const s=this._tsCall.participants.find((t=>t.id===e.userId))?.displayName||(this._internalCallAgent.getUserMri()===e.userId?this._internalCallAgent?.displayName:void 0),a={resultType:e.isFinal?"Final":"Partial",captionText:e.text,spokenText:e.originalText??e.text,timestamp:new Date(new Date(e.timestampAudioSent/1e4).getTime()+Pb),speaker:{identifier:kS(e.userId),displayName:s},spokenLanguage:e.spokenLanguage,captionLanguage:e.trackLanguage};if(this._currentLanguage!=e.spokenLanguage&&(this._currentLanguage=e.spokenLanguage,this._eventEmitter.emit("SpokenLanguageChanged")),!this.isCaptionsFeatureActive||this._mediaStreamSourceId!==i)return;this._hasReceivedFirstCaption||(this._hasReceivedFirstCaption=!0,this._sendCaptionsEvent(uE.FirstCaptionReceived,oE.success,"",0)),this._eventEmitter.emit("CaptionsReceived",a)}catch(e){this._logger.error("Failed to parse Captions result",e),this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(uE.FirstCaptionParsingError,oE.failure,"",0,dE.Unexpected,"Error thrown during incoming caption result mapping."))}}))}}},this._isCaptionInTextTracks=e=>{let t=!1;return e.textTracks&&e.textTracks.forEach((e=>{"Mt"===e.source&&(t=!0)})),t},this._handleBotRemoved=e=>{this._acsMetadata&&this._isCaptionsBot(e)&&(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===ab.TeamsCaptions?"TeamsCaptions":"Captions"}get activeSpokenLanguage(){return this._currentLanguage}get activeCaptionLanguage(){return this._currentCaptionLanguage}get isTeamsConversationType(){return Jv.indexOf(this._tsCall.conversationType)>-1}get isTeamsUserInCall(){for(let e of this._tsCall.participants)if("microsoftTeamsUser"===kS(e.id).kind)return!0;return!1}get isTeamsCallKind(){return this._call.kind===ue.TeamsCall}get isTeamsCaptionsBotInCall(){for(let e of this._tsCall.participants){if("gcc"===this._tsCall.region&&e.id===vy().captions.teams.gccBotMri)return!0;if("gcc"!==this._tsCall.region&&(e.id===vy().captions.teams.botMri||e.id===vy().captions.teams.legacyBotMri))return!0}return!1}async updateParticipantTranscriptionPrefsMetadata(e,t){let i;for(let e in this._tsCall.endpoints?.endpointDetails)if(this._tsCall.endpoints?.endpointDetails[e].participantId===this._tsCall.participantId){i=this._tsCall.endpoints?.endpointDetails[e];break}const n=i?.endpointMetadata??{transcriptionPrefs:{}};e?n.transcriptionPrefs?.closedCaptions?n.transcriptionPrefs.closedCaptions=e:n.transcriptionPrefs={closedCaptions:e}:n.transcriptionPrefs?.closedCaptions&&delete n.transcriptionPrefs.closedCaptions;try{await this._tsCall.updateEndpointMetadata(JSON.stringify(n))}catch(e){this._addParticipantPromise=null;const i=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_ENDPOINT_METADATA});throw this._sendCaptionsEvent(uE.UpdateEndpointMetadata,oE.failure,t,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("updateEndpointMetadata",oE.failure),this._logger.warn(i.message),i}}initialize(e,t,i,n,r,s,a,o){this._logger=s.createChild((()=>`CaptionsFeature::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._call=t,this._internalCallAgent=i,this._httpRequestHelper=n,this._telemetryLogManager=r,this._telemetryStartTime=a,this._isCteUser=i.isCteUser(),this._ecsCaptionsEnabled=vy().captions.enabled,this._ecsACSCaptionsEnabled=vy().captions.acs.enabled,this._ecsTeamsCaptionsEnabled=vy().captions.teams.enabled,this._ecsSetBotMetadataWhenEmptyFixEnabled=vy().captions.setBotMetadataWhenEmptyFix,this._name=this.isTeamsConversationType||this._isCteUser||this.isTeamsUserInCall||this.isTeamsCaptionsBotInCall||this.isTeamsCallKind?ab.TeamsCaptions:ab.Captions,this.updateCaptionsData(this._name),this._sendCaptionsEvent(uE.InitializeCaptions,oE.initialize,o,this._telemetryStartTime),this._initializationPromise=new Promise(((e,t)=>{this._initializeAsync(o).then((t=>e())).catch((e=>t(e)))}))}async _initializeAsync(e){try{this._textDecoder=new TextDecoder,this._tsCall.on("callStateChanged",(()=>{3===this._tsCall.state&&this._name===ab.TeamsCaptions&&"gcc"===this._tsCall.region&&(this._captionsBotMri=vy().captions.teams.gccBotMri)})),this._tsCall.on("participantAdded",(async t=>{if(this._captions&&"Captions"===this._captions.kind&&"microsoftTeamsUser"===kS(t.id).kind){if(this._captionsBotMri)try{await this._tsCall.removeParticipant(this._captionsBotMri),this._acsMetadata&&(this._acsMetadata=void 0)}catch(i){const n=new le({defaultError:{message:vb(i),code:t.callEndDiagnosticsInfo?.callControllerCode||0,subCode:t.callEndDiagnosticsInfo?.callControllerSubCode||0,resultCategories:t.callEndDiagnosticsInfo?.resultCategories||["UnexpectedClientError"]},originalError:i});this._sendCaptionsEvent(uE.CaptionsKindChanged,oE.failure,e,this._telemetryStartTime,dE.Unexpected,n.message,n.code,n.subCode,_b(n))}if(this.updateCaptionsData(ab.TeamsCaptions),this._ecsSetBotMetadataWhenEmptyFixEnabled){const i=this._tsCall.participants.find((e=>e.id===this._captionsBotMri));if(i){this._acsMetadata=this._copyBotMetaData(i),this._mediaStreamSourceId=i.getSourceIdForMediaType(3);try{await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)}catch(t){const i=new le({defaultError:ee.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(uE.StartDataChannel,oE.failure,e,this._telemetryStartTime,dE.Expected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("startDataChannel",oE.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(uE.CaptionsKindChanged,oE.success,e,this._telemetryStartTime)}})),this._tsCall.on("participantAdded",(async e=>{this._isCaptionsBot(e)&&(this._acsMetadata||(this._acsMetadata=this._copyBotMetaData(e),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(e),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)))})),this._tsCall.on("participantRemoved",(async e=>{this._isCaptionsBot(e)&&this._handleBotRemoved(e)})),this._tsCall.on("participantUpdated",(async e=>{this._getBotMetadata(e)&&this._isCaptionsBot(e)&&this._acsMetadata&&(this._acsMetadata=this._copyBotMetaData(e),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(e),!this._firstTimeActive&&this.isCaptionsFeatureActive&&(this._firstTimeActive=!0,this._eventEmitter.emit("CaptionsActiveChanged")))}));const t=this._tsCall.participants.find((e=>e.id===this._captionsBotMri||e.id===this._captionsLegacyBotMri));t&&(this._acsMetadata=this._copyBotMetaData(t),this._mediaStreamSourceId=t.getSourceIdForMediaType(3),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler))}catch(t){const i=new le({defaultError:ee.FEATURES.CAPTIONS.INITIALIZE});throw this._sendCaptionsEvent(uE.InitializeCaptions,oE.failure,e,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._logger.error(i.message),i}}updateCaptionsData(e){e===ab.Captions?(this._name=ab.Captions,this._captionsBotMri=vy().captions.acs.botMri,this._captionsLegacyBotMri=void 0,this._modeKey=vy().captions.acs.modeKey,this._modeVal=vy().captions.acs.modeVal,this._modesKey=vy().captions.acs.modesKey,this._modesVal=vy().captions.acs.modesVal,this._clientInfo=vy().captions.acs.clientInfo.ring,this._ecsACSCaptionsEnabled=vy().captions.acs.enabled,this._ecsSpokenLanguagesEnabled=vy().captions.acs.spokenLanguages.enabled,this._ecsSpokenLanguages=vy().captions.acs.spokenLanguages.languages,this._ecsCapabilitiesEnabled=vy().captions.useCapabilities,this._ecsSetBotMetadataWhenEmptyFixEnabled=vy().captions.setBotMetadataWhenEmptyFix,this._call.offParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler),this._logger.log("participant capabilities change event listener unregistered"),this._captions=new Mb(this,this._eventEmitter)):e===ab.TeamsCaptions&&(this._name=ab.TeamsCaptions,"gcc"===this._tsCall.region?this._captionsBotMri=vy().captions.teams.gccBotMri:this._captionsBotMri=vy().captions.teams.botMri,this._captionsLegacyBotMri=vy().captions.teams.legacyBotMri,this._modeKey=vy().captions.teams.modeKey,this._modeVal=vy().captions.teams.modeVal,this._modesKey=vy().captions.teams.modesKey,this._modesVal=vy().captions.teams.modesVal,this._clientInfo=vy().captions.teams.clientInfo.ring,this._ecsTeamsCaptionsEnabled=vy().captions.teams.enabled,this._ecsSpokenLanguagesEnabled=vy().captions.teams.spokenLanguages.enabled,this._ecsSpokenLanguages=vy().captions.teams.spokenLanguages.languages,this._ecsCaptionLanguagesEnabled=vy().captions.teams.captionLanguages.enabled,this._ecsCaptionLanguages=vy().captions.teams.captionLanguages.languages,this._ecsAmtPolicyUrlSuffix=vy().MiddleTier.policyUrlSuffixV2,this._ecsCapabilitiesEnabled=vy().captions.useCapabilities,this._ecsSetBotMetadataWhenEmptyFixEnabled=vy().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 Db(this,this._eventEmitter))}async startCaptions(e){this._telemetryStartTime=+Date.now();const t=Mf(),i=e?.spokenLanguage||"en-us";if(this._sendFeatureUsage("startCaptions",oE.attempt),this._sendCaptionsEvent(uE.StartCaptions,oE.attempt,t,0),this._addParticipantPromise){const e=new le({defaultError:ee.FEATURES.CAPTIONS.ALREADY_STARTING});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),void this._sendFeatureUsage("startCaptions",oE.failure)}if(await this._initializationPromise,!this._ecsCaptionsEnabled){const e=new le({defaultError:ee.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),void this._logger.error("Feature is not enabled.")}if(3!==this._tsCall.state){const e=new le({defaultError:ee.FEATURES.CAPTIONS.START_FAILED_CALL_NOT_CONNECTED});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),void this._logger.error("Captions unable to start as call state is not connected.")}if(!this._tsCall.endpoints){const e=new le({defaultError:ee.FEATURES.CAPTIONS.START_FAILED_CALL_ENDPOINTS_NOT_AVAILABLE});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),void this._logger.error("Captions unable to start as call endpoints are not available.")}if(!this._ecsSpokenLanguages.includes(i)){const e=new le({defaultError:ee.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),this._logger.error("Spoken language requested is not supported."),e}if(this._name===ab.Captions&&!this._ecsACSCaptionsEnabled){const e=new le({defaultError:ee.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),void this._logger.error("Captions Feature is not enabled.")}if(this._name===ab.TeamsCaptions){if("gcc"===this._tsCall.region&&(this._captionsBotMri=vy().captions.teams.gccBotMri),!this._ecsTeamsCaptionsEnabled){const e=new le({defaultError:ee.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),void this._logger.error("Teams Captinons Feature is not enabled.")}if(this._ecsCapabilitiesEnabled){if(this._isCteUser)if(this._call.callInfo.context===uy.TeamsMeeting||this.isTeamsConversationType){if(this._participantCapability)if(this.isTeamsConversationType){if(!this._participantCapability?.startLiveMeetingCaptions.isPresent){const e=new le({defaultError:ee.FEATURES.CAPTIONS.MEETING_POLICY_DISABLED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(e.message),e}}else if(!this._participantCapability?.startLiveCallingCaptions.isPresent){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(e.message),e}}else{const e=this._internalCallAgent.getUserPolicy();if("DisabledUserOverride"!==e?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(e.message),e}}}else if(this._mtPolicy=this._internalCallAgent.mtPolicyService,this._isCteUser){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(e){const i=new le({defaultError:ee.FEATURES.CAPTIONS.CTE_POLICY_FETCH_FAIL,originalError:e});this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._logger.error("Unable to fetch policies")}if(this._mtCaptionsPolicyResult)if(this.isTeamsConversationType){if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForMeeting){const e=new le({defaultError:ee.FEATURES.CAPTIONS.MEETING_POLICY_DISABLED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(e.message),e}}else if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForCalling){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(e.message),e}}}if(this._ecsSetBotMetadataWhenEmptyFixEnabled){const i=this._tsCall.participants.find((e=>e.id===this._captionsBotMri||e.id===this._captionsLegacyBotMri));if(i&&!this._acsMetadata){this._acsMetadata=this._copyBotMetaData(i),this._mediaStreamSourceId=i.getSourceIdForMediaType(3);try{await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)}catch(e){const i=new le({defaultError:ee.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(uE.StartDataChannel,oE.failure,t,this._telemetryStartTime,dE.Expected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("startDataChannel",oE.failure)}}}if(this._acsMetadata){if(this._isCaptionsEnabled(this._acsMetadata))if(this._isCaptionsActive){const e=new le({defaultError:ee.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure)}else this._isCaptionsActive=!0,"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!0,t),this._sendCaptionsEvent(uE.StartCaptions,oE.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",oE.success),this._eventEmitter.emit("CaptionsActiveChanged");else if("Captions"===this._captions.kind)if(this._isCaptionsActive){const e=new le({defaultError:ee.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("startCaptions",oE.failure)}else this._isCaptionsActive=!0,await this.updateParticipantTranscriptionPrefsMetadata(!0,t),this._sendCaptionsEvent(uE.StartCaptions,oE.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",oE.success),this._eventEmitter.emit("CaptionsActiveChanged")}else try{const e={participantInvitationData:{botData:{clientInfo:this._clientInfo,consumerType:"ACS",initiatorUserToken:this._name===ab.TeamsCaptions?"":await this._internalCallAgent.tokenProvider(),spokenLanguage:i,[this._modeKey]:this._modeVal,[this._modesKey]:this._modesVal}}};"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!0,t),this._addParticipantPromise=this._tsCall.addParticipant(this._captionsBotMri,e),await this._addParticipantPromise,this._addParticipantPromise=null,this._currentLanguage!==i&&(this._currentLanguage=i,this._eventEmitter.emit("SpokenLanguageChanged")),this._isCaptionsActive=!0,this._sendCaptionsEvent(uE.StartCaptions,oE.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",oE.success)}catch(e){this._addParticipantPromise=null;const i=new le({defaultError:ee.FEATURES.CAPTIONS.START_FAILED});throw this._sendCaptionsEvent(uE.StartCaptions,oE.failure,t,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("startCaptions",oE.failure),this._logger.error(i.message),i}}async stopCaptions(){this._telemetryStartTime=+Date.now();const e=Mf();if(this._sendFeatureUsage("stopCaptions",oE.attempt),this._sendCaptionsEvent(uE.StopCaptions,oE.attempt,e,0),this.isCaptionsFeatureActive)"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!1,e),this._isCaptionsActive=!1,this._sendCaptionsEvent(uE.StopCaptions,oE.success,e,this._telemetryStartTime),this._sendFeatureUsage("stopCaptions",oE.success),this._eventEmitter.emit("CaptionsActiveChanged");else{const t=new le({defaultError:ee.FEATURES.CAPTIONS.STOP_NOT_ACTIVE});this._sendCaptionsEvent(uE.StopCaptions,oE.failure,e,this._telemetryStartTime,dE.Expected,t.message,t.code,t.subCode,_b(t)),this._logger.warn(t.message)}this._isCaptionsActive=!1}async setSpokenLanguage(e){this._telemetryStartTime=+Date.now();const t=Mf();if(this._sendFeatureUsage("setSpokenLanguage",oE.attempt),this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.attempt,t,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),this._logger.error(e.message),e}if(!this._isCaptionsActive){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});return this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),void this._logger.warn(e.message)}if(!this._ecsSpokenLanguagesEnabled){const e=new le({defaultError:ee.FEATURES.CAPTIONS.SPOKEN_LANG_DISABLED});return this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),void this._logger.error(e.message)}if(e==this._currentLanguage){const e=new le({defaultError:ee.FEATURES.CAPTIONS.SPOKEN_LANGUAGE_ALREADY_SET});return this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),void this._sendFeatureUsage("setSpokenLanguage",oE.failure)}if(!this._ecsSpokenLanguages.includes(e)){const e=new le({defaultError:ee.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),this._logger.error(e.message),e}try{const i=await this._internalCallAgent.tokenProvider();if(!i){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_LANGUAGE_GET_TOKEN});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Unexpected,e.message,e.code,e.subCode,_b(e)),e}await this._sendSetLanguageRequest(e,"",i,this._acsMetadata.commandUrl),this._currentLanguage!==e&&(this._currentLanguage=e,this._eventEmitter.emit("SpokenLanguageChanged")),this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.success,t,this._telemetryStartTime),this._sendFeatureUsage("setSpokenLanguage",oE.success)}catch(e){const i=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_LANGUAGE_FAILED,originalError:e});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("setSpokenLanguage",oE.failure),this._logger.error(i.message),i}}async setCaptionLanguage(e){this._telemetryStartTime=+Date.now();const t=Mf();if(this._sendFeatureUsage("setCaptionLanguage",oE.attempt),this._sendCaptionsEvent(uE.SetCaptionLanguage,oE.attempt,t,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_STARTED});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(e.message),e}if(!this._isCaptionsActive){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_ACTIVE});return this._sendCaptionsEvent(uE.SetCaptionLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),void this._logger.warn(e.message)}if(!this._ecsCaptionLanguagesEnabled){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_DISABLED});return this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),void this._logger.error(e.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!==uy.TeamsMeeting){const e=this._internalCallAgent.getUserProperties();if(!e?.featureTypes?.includes(AS.TeamsProMgmt)){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(e.message),e}}else if(!this._participantCapability?.setCaptionLanguage.isPresent){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(e.message),e}}else if(!this._mtCaptionsPolicyResult?.isTeamsProMgmtSkuAvailable){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(e.message),e}if(e==this._currentCaptionLanguage){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_ALREADY_SET});return this._sendCaptionsEvent(uE.SetCaptionLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),void this._sendFeatureUsage("setCaptionLanguage",oE.failure)}if(!this._ecsCaptionLanguages.includes(e)){const e=new le({defaultError:ee.FEATURES.CAPTIONS.CAPTIONS_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Expected,e.message,e.code,e.subCode,_b(e)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(e.message),e}try{const i=await this._internalCallAgent.tokenProvider();if(!i){const e=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_CAPTIONS_GET_TOKEN});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Unexpected,e.message,e.code,e.subCode,_b(e)),e}await this._sendSetLanguageRequest("",e,i,this._acsMetadata.commandUrl),this._currentCaptionLanguage!==e&&(this._currentCaptionLanguage=e,this._eventEmitter.emit("CaptionLanguageChanged")),this._sendCaptionsEvent(uE.SetCaptionLanguage,oE.success,t,this._telemetryStartTime),this._sendFeatureUsage("setCaptionLanguage",oE.success)}catch(e){const i=new le({defaultError:ee.FEATURES.CAPTIONS.UPDATE_CAPTIONS_FAILED,originalError:e});throw this._sendCaptionsEvent(uE.SetSpokenLanguage,oE.failure,t,this._telemetryStartTime,dE.Unexpected,i.message,i.code,i.subCode,_b(i)),this._sendFeatureUsage("setCaptionLanguage",oE.failure),this._logger.error(i.message),i}}dispose(){this._acsMetadata=void 0,this._textDecoder=void 0}_sendCaptionsEvent(e,t,i,n,r,s,a,o,l){let c={eventName:aE.acs_calling_captions,callId:this._call.id,correlationId:i,isExpected:r??"",localParticipantId:this._call.tsCall.participantId,featureType:this._name,featureDetails:{step:e},kindOfEvent:t,timestampInfo:n?{deltaTimeInMs:+Date.now()-n}:"",additionalDetails:{failureReason:s,code:a,subCode:o,...l}};try{this._telemetryLogManager.sendEvent({name:aE.acs_calling_captions,tenant:xv,properties:c})}catch(e){this._logger.debug(`Unable to send ${this._name} feature usage telemtery`)}}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this._name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}async _sendSetLanguageRequest(e,t,i,n){const r=e?{type:qv,spokenLanguage:e}:{type:qv,subtitleLanguages:[t]},s={timestamp:(new Date).toISOString(),participantMri:this._internalCallAgent.getUserMri(),participantLegId:this._tsCall.participantId,action:qv,mode:Wv,actionParameters:r},a={headers:{"X-Microsoft-Skype-Chain-ID":this._tsCall.callId,Authorization:`Bearer ${i}`,"x-skypetoken":i},withCredentials:!0};return this._httpRequestHelper.sendRequestWithRetry("post",n,s,a,3)}}wb([pe(QE.StartCaptions),Ab("design:type",Function),Ab("design:paramtypes",[Object]),Ab("design:returntype",Promise)],kb.prototype,"startCaptions",null),wb([pe(QE.StopCaptions),Ab("design:type",Function),Ab("design:paramtypes",[]),Ab("design:returntype",Promise)],kb.prototype,"stopCaptions",null),wb([pe(QE.SetSpokenLanguage),Ab("design:type",Function),Ab("design:paramtypes",[String]),Ab("design:returntype",Promise)],kb.prototype,"setSpokenLanguage",null),wb([pe(QE.SetCaptionLanguage),Ab("design:type",Function),Ab("design:paramtypes",[String]),Ab("design:returntype",Promise)],kb.prototype,"setCaptionLanguage",null);class Ob{constructor(e){this.typeRankComparator=(e,t)=>void 0===e.publishedState?-1:void 0===t.publishedState?1:e.publishedState.typeRank-t.publishedState.typeRank,this._eventEmitter=e,this._currentRaiseHandStates=new Map}initialize(e,t,i,n,r){this._logger=n.createChild((()=>`RaiseHandFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._callInfo=r,this._telemetryLogManager=i,this._internalCallAgent=t,this._sendFeatureUsage("initialize",oE.initialize);try{let e=e=>new Map(this.getPublishedState(e).sort(this.typeRankComparator).map((e=>[e.id,e])));this._tsCall.on("publishedStatesChanged",(async t=>{let i=e(t),n=this._currentRaiseHandStates;this._currentRaiseHandStates=i,this._currentRaiseHandStates.forEach(((e,t)=>{n.has(t)||this._eventEmitter.emit("raisedHandEvent",{identifier:kS(t)})})),n.forEach(((e,t)=>{this._currentRaiseHandStates.has(t)||this._eventEmitter.emit("loweredHandEvent",{identifier:kS(t)})}))})),this._tsCall.publishedStates&&(this._currentRaiseHandStates=e(this._tsCall.publishedStates)),this._sendFeatureUsage("initialize",oE.success)}catch(e){throw this._logger.error("Could not initialize raise hand feature.",e),this._sendFeatureUsage("initialize",oE.failure),new le({defaultError:ee.FEATURES.RAISE_HAND.INITIALIZE,originalError:e})}}async raiseHand(){if(this._sendFeatureUsage("raiseHand",oE.attempt),this._callInfo.context===uy.TwoParty)throw this._logger.warn("Raise hand not supported for 1:1 calls"),this._sendFeatureUsage("raiseHand",oE.failure),new le({defaultError:ee.FEATURES.RAISE_HAND.NOT_SUPPORTED_1TO1});try{if(void 0!==this.getLocalRaiseHandState())return void this._sendFeatureUsage("raiseHand",oE.failure);const e={level:"user",type:"raiseHands",content:"{}"};if(!await this._tsCall.publishState(e,X.generateCauseId()))throw new le({defaultError:ee.FEATURES.RAISE_HAND.RAISE_HAND_PUBLISH_STATE});this._sendFeatureUsage("raiseHand",oE.success)}catch(e){throw this._logger.error("Could not change a participant state. Code: ",e?.response?.status),this._sendFeatureUsage("raiseHand",oE.failure),bb(e,ee.FEATURES.RAISE_HAND.RAISE_HAND_FAIL)}}async lowerHand(){this._sendFeatureUsage("lowerHand",oE.attempt);try{const e=this.getLocalRaiseHandState();if(void 0===e)return void this._sendFeatureUsage("lowerHand",oE.failure);const t={stateIds:[e]};await this._tsCall.removeState(t,X.generateCauseId()),this._sendFeatureUsage("lowerHand",oE.success)}catch(e){throw this._logger.error("Could not change a participant state. Code: ",e?.response?.status),this._sendFeatureUsage("lowerHand",oE.failure),bb(e,ee.FEATURES.RAISE_HAND.LOWER_HAND_FAIL)}}async lowerHands(e){this._sendFeatureUsage("lowerHands",oE.attempt);try{if(0===e.length)return void this._sendFeatureUsage("lowerHands",oE.failure);if(0===this._currentRaiseHandStates.size)return void this._sendFeatureUsage("lowerHands",oE.failure);const t=e.map((e=>DS(e))),i=this.findStateIdsForParticipantIds(t);await this._tsCall.removeState({stateIds:i},X.generateCauseId()),this._sendFeatureUsage("lowerHands",oE.success)}catch(e){throw this._logger.error("Could not change a participant state.",e),this._sendFeatureUsage("lowerHands",oE.failure),bb(e,ee.FEATURES.RAISE_HAND.LOWER_REMOTEPARTICIPANTS_HANDS_FAIL)}}async lowerAllHands(){this._sendFeatureUsage("lowerAllHands",oE.attempt);try{await this._tsCall.removeStatesForEveryone({type:"raiseHands"},X.generateCauseId()),this._sendFeatureUsage("lowerAllHands",oE.success)}catch(e){throw this._logger.error("Could not change a participant state.",e),this._sendFeatureUsage("lowerAllHands",oE.failure),bb(e,ee.FEATURES.RAISE_HAND.LOWER_ALL_HANDS_FAIL)}}get raisedHands(){return 0===this._currentRaiseHandStates.size?[]:Array.from(this._currentRaiseHandStates.keys()).map(((e,t)=>({identifier:kS(e),order:t+1})))}getLocalRaiseHandState(){const e=this.findStateIdsForParticipantIds([this._internalCallAgent.getUserMri()]);if(e&&e.length>0)return e[0]}findStateIdsForParticipantIds(e){return e&&0!==this._currentRaiseHandStates.size?Array.from(this._currentRaiseHandStates.entries()).filter((t=>e.includes(t[0]))).map((e=>e[1]?.publishedState?.stateId)).filter((e=>!!e)):[]}getPublishedState(e){return e.typeStates.filter((e=>"raiseHands"===e.type)).map((e=>e.participantStates)).flat()}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}var Nb;!function(e){e.turnVideoOn="turnVideoOn",e.unmuteMic="unmuteMic",e.shareScreen="shareScreen",e.removeParticipant="removeParticipant",e.hangUpForEveryOne="hangUpForEveryOne",e.addCommunicationUser="addCommunicationUser",e.addTeamsUser="addTeamsUser",e.addPhoneNumber="addPhoneNumber",e.manageLobby="manageLobby",e.spotlightParticipant="spotlightParticipant",e.removeParticipantsSpotlight="removeParticipantsSpotlight",e.blurBackground="blurBackground",e.startLiveMeetingCaptions="startLiveMeetingCaptions",e.startLiveCallingCaptions="startLiveCallingCaptions",e.setCaptionLanguage="setCaptionLanguage",e.raiseHand="raiseHand",e.pstnDialOut="pstnDialOut",e.muteOthers="muteOthers",e.useReactions="useReactions",e.viewAttendeeNames="viewAttendeeNames",e.startTogetherMode="startTogetherMode",e.joinBreakoutRooms="joinBreakoutRooms",e.forbidOthersAudio="forbidOthersAudio",e.forbidOthersVideo="forbidOthersVideo"}(Nb||(Nb={}));class Lb{constructor(e){this._logger=e,this._ecsConfig=vy()}getResolvedCapabilitiesBasedOnRole(e,t){let i={...t},n=e.toLocaleLowerCase();return n!==yS.Attendee.toLocaleLowerCase()&&n!==yS.Presenter.toLocaleLowerCase()&&n!==yS.Consumer.toLocaleLowerCase()&&n!==yS.Organizer.toLocaleLowerCase()||(this._ecsConfig[bS][n][Nb.turnVideoOn]?i.turnVideoOn={isPresent:this._ecsConfig[bS][n][Nb.turnVideoOn],reason:ES.Capable}:i.turnVideoOn={isPresent:this._ecsConfig[bS][n][Nb.turnVideoOn],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.unmuteMic]?i.unmuteMic={isPresent:this._ecsConfig[bS][n][Nb.unmuteMic],reason:ES.Capable}:i.unmuteMic={isPresent:this._ecsConfig[bS][n][Nb.unmuteMic],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.shareScreen]?i.shareScreen={isPresent:this._ecsConfig[bS][n][Nb.shareScreen],reason:ES.Capable}:i.shareScreen={isPresent:this._ecsConfig[bS][n][Nb.shareScreen],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.removeParticipant]?i.removeParticipant={isPresent:this._ecsConfig[bS][n][Nb.removeParticipant],reason:ES.Capable}:i.removeParticipant={isPresent:this._ecsConfig[bS][n][Nb.removeParticipant],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.muteOthers]?i.muteOthers={isPresent:this._ecsConfig[bS][n][Nb.muteOthers],reason:ES.Capable}:i.muteOthers={isPresent:this._ecsConfig[bS][n][Nb.muteOthers],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.pstnDialOut]?i.pstnDialOut={isPresent:this._ecsConfig[bS][n][Nb.pstnDialOut],reason:ES.Capable}:i.pstnDialOut={isPresent:this._ecsConfig[bS][n][Nb.pstnDialOut],reason:ES.RoleRestricted},this._ecsConfig[bS][n][Nb.addPhoneNumber]?i.addPhoneNumber={isPresent:this._ecsConfig[bS][n][Nb.addPhoneNumber],reason:ES.Capable}:i.addPhoneNumber={isPresent:this._ecsConfig[bS][n][Nb.addPhoneNumber],reason:ES.RoleRestricted}),i.removeParticipant={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.hangUpForEveryOne={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.addCommunicationUser={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.addTeamsUser={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.manageLobby={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.spotlightParticipant={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.removeParticipantsSpotlight={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.blurBackground={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.startLiveMeetingCaptions={isPresent:!0,reason:ES.Capable},i.startLiveCallingCaptions={isPresent:!0,reason:ES.Capable},i.setCaptionLanguage={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.raiseHand={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.useReactions={isPresent:!0,reason:ES.Capable},i.viewAttendeeNames={isPresent:!0,reason:ES.Capable},i.startTogetherMode={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.joinBreakoutRooms={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.forbidOthersAudio={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},i.forbidOthersVideo={isPresent:!1,reason:ES.CapabilityNotApplicableForTheCallType},this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on role change to ${e}`),i}}const xb="DisableAv",Fb="DisableVideo",Ub="DisableAudio",Bb="attendee";class Vb extends ZE{constructor(e){super(e),this.getLocalParticipantMediaAccess=()=>this._impl.getLocalParticipantMediaAccess(),this._impl=new Hb(this.eventEmitter)}get name(){return"MediaAccess"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}getAllOthersMediaAccess(){return this._impl.getAllOthersMediaAccess()}getMeetingMediaAccess(){return this._impl.getMeetingMediaAccess()}async permitAudio(e){return this._impl.permitAudio(e)}async permitOthersAudio(){return this._impl.permitOthersAudio()}async forbidAudio(e){return this._impl.forbidAudio(e)}async forbidOthersAudio(){return this._impl.forbidOthersAudio()}async permitVideo(e){return this._impl.permitVideo(e)}async permitOthersVideo(){return this._impl.permitOthersVideo()}async forbidVideo(e){return this._impl.forbidVideo(e)}async forbidOthersVideo(){return this._impl.forbidOthersVideo()}on(e,t){if(this._sendFeatureUsage(e,oE.subscribe),"mediaAccessChanged"!==e&&"meetingMediaAccessChanged"!==e&&"localParticipantMediaAccessChanged"!==e)throw new le({defaultError:ee.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(this._sendFeatureUsage(e,oE.unsubscribe),"mediaAccessChanged"!==e&&"meetingMediaAccessChanged"!==e&&"localParticipantMediaAccessChanged"!==e)throw new le({defaultError:ee.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"MediaAccess",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class Hb{constructor(e){this._ecsTeamsMediaAccessEnabled=!1,this._remoteParticipantsMediaAccess=[],this.getAllOthersMediaAccess=()=>(this._remoteParticipantsMediaAccess=this._tsCall.participants.reduce(((e,t)=>{const i=this._publishedStatesMediaAccessMap.get(t.id),n=t.advancedMeetingRole===Bb,r=kS(t.id);return i&&n?e.push(i):!i&&n?e.push({participant:r,isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}):e.push({participant:r,isAudioPermitted:!0,isVideoPermitted:!0}),e}),[]),this._remoteParticipantsMediaAccess),this.getLocalParticipantMediaAccess=()=>{const e=this._internalCallAgent.getUserMri(),t=this._publishedStatesMediaAccessMap.get(e),i="Attendee"===this._call.role;if(t&&i)return t;const n=kS(e);return!t&&i?{participant:n,isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}:{participant:n,isAudioPermitted:!0,isVideoPermitted:!0}},this.isMeetingCapabilityAudioRestricted=()=>[xb,Ub].includes(this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions),this.isMeetingCapabilityVideoRestricted=()=>[xb,Fb].includes(this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions),this.getMediaAccessMap=e=>{if(Z.isEmpty(e?.typeStates))return new Map;const t=new Map;return e&&this.getPublishedState(e).forEach((e=>{e.participantStates.forEach((i=>{let n=t.get(i.id);n||(n={participantId:i.id},t.set(i.id,n)),["attendeeAudioRestricted","attendeeModalitiesUnrestricted"].includes(e.type)&&(n.isAudioPermitted=this.isAudioPermitted(e.type)),["attendeeVideoRestricted","attendeeVideoUnrestricted"].includes(e.type)&&(n.isVideoPermitted=this.isVideoPermitted(e.type))}))})),t.forEach((e=>{void 0===e.isAudioPermitted&&(e.isAudioPermitted=!this.isMeetingCapabilityAudioRestricted()),void 0===e.isVideoPermitted&&(e.isVideoPermitted=!this.isMeetingCapabilityVideoRestricted())})),new Map(Array.from(t).map((([e,t])=>[e,{participant:kS(e),isAudioPermitted:!!t?.isAudioPermitted,isVideoPermitted:!!t?.isVideoPermitted}])))},this.isAudioPermitted=e=>this.isMeetingCapabilityAudioRestricted()?"attendeeModalitiesUnrestricted"===e:"attendeeAudioRestricted"!==e,this.isVideoPermitted=e=>this.isMeetingCapabilityVideoRestricted()?"attendeeVideoUnrestricted"===e:"attendeeVideoRestricted"!==e,this.checkRemoteParticipantsMediaAccessAndEmitEvent=()=>{const e=this._remoteParticipantsMediaAccess;this._publishedStatesMediaAccessMap=this.getMediaAccessMap(this._tsCall.publishedStates),this.getAllOthersMediaAccess(),Z.isEqual(e,this._remoteParticipantsMediaAccess)||this._eventEmitter.emit("mediaAccessChanged",{mediaAccesses:this._remoteParticipantsMediaAccess})},this.checkLocalMediaAccessAndEmitEvent=()=>{const e=this.getLocalParticipantMediaAccess();Z.isEqual(this._localMediaAccess,e)||(this._localMediaAccess=e,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 t=vy().calling.mediaAccess;this._ecsTeamsMediaAccessEnabled=t.enabled,this._supportedUserRoles=t.supportedRoles,this._supportedConversationTypes=t.supportedConversationTypes,this._supportedConversationTypesForMuteAll=t.supportedConversationTypesForMuteAll,this._eventEmitter=e,this._publishedStatesMediaAccessMap=new Map,this._attendeeRestrictions="",this._localMediaAccess=void 0}initialize(e,t,i,n,r){this._logger=r.createChild((()=>`MediaAccessCallFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._call=i,this._telemetryLogManager=n,this._internalCallAgent=t,this._sendFeatureUsage("initialize",oE.initialize);try{if(!this._ecsTeamsMediaAccessEnabled)throw"feature not supported or call context is not teams meeting join";this._tsCall.on("publishedStatesChanged",(async e=>{this._logger.info("publishedStatesChanged event received");const t=this._publishedStatesMediaAccessMap;this._publishedStatesMediaAccessMap=this.getMediaAccessMap(e),Z.isEqual(t,this._publishedStatesMediaAccessMap)||this._eventEmitter.emit("mediaAccessChanged",{mediaAccesses:this.getAllOthersMediaAccess()}),this.checkLocalMediaAccessAndEmitEvent()})),this._tsCall.changed((()=>{const e=this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions;Z.isEqual(this._attendeeRestrictions,e)||(this._logger.info(`Attendee restrictions change from ${this._attendeeRestrictions} to ${e}`),this._attendeeRestrictions=e,this._eventEmitter.emit("meetingMediaAccessChanged",{meetingMediaAccess:this.getMeetingMediaAccess()}),this.checkRemoteParticipantsMediaAccessAndEmitEvent(),this.checkLocalMediaAccessAndEmitEvent())})),this._tsCall.on("participantCountsUpdated",(e=>{this._logger.info("participantCountsUpdated changed event received, totalParticipants: ",e?.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",oE.success)}catch(e){throw this._logger.error("Could not initialize media access feature.",e),this._sendFeatureUsage("initialize",oE.failure),new le({defaultError:ee.FEATURES.MEDIA_ACCESS.INITIALIZE_FAILED,originalError:e})}}async permitAudio(e){const t=Mf();this._sendFeatureUsage("permitAudio",oE.attempt,t),this.validateMediaAccessConditions("permitAudio",t,!1,!0,e.map((e=>DS(e))));try{const i=e.map((e=>DS(e)));this.isMeetingCapabilityAudioRestricted()?await this.addModalityState(i,"attendeeModalitiesUnrestricted",t):await this.removeModalityState(i,"attendeeAudioRestricted",t),this._sendFeatureUsage("permitAudio",oE.success,t)}catch(e){throw this._logger.error(`Could not change a participant state. Code: ${e?.response?.status} correlationId: ${t}`),this._sendFeatureUsage("permitAudio",oE.failure),bb(e,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidAudio(e){const t=Mf();this._sendFeatureUsage("forbidAudio",oE.attempt,t),this.validateMediaAccessConditions("forbidAudio",t,!1,!0,e.map((e=>DS(e))));try{const i=e.map((e=>DS(e)));this.isMeetingCapabilityAudioRestricted()?await this.removeModalityState(i,"attendeeModalitiesUnrestricted",t):await this.addModalityState(i,"attendeeAudioRestricted",t),this._sendFeatureUsage("forbidAudio",oE.success,t)}catch(e){throw this._logger.error(`Could not change a participant state. Code: ${e?.response?.status} correlationId: ${t}`),this._sendFeatureUsage("forbidAudio",oE.failure),bb(e,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitOthersAudio(){const e=Mf();this._sendFeatureUsage("permitOthersAudio",oE.attempt,e),this.validateMediaAccessConditions("permitOthersAudio",e,!0);try{let t;t=this.isMeetingCapabilityVideoRestricted()?2:0,await this.updateAttendeeRestrictions(t,e),this._sendFeatureUsage("permitOthersAudio",oE.success,e)}catch(t){throw this._logger.error(`Could not change a participant state. Code: ${t?.response?.status} correlationId: ${e}`),this._sendFeatureUsage("permitOthersAudio",oE.failure),bb(t,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidOthersAudio(){const e=Mf();this._sendFeatureUsage("forbidOthersAudio",oE.attempt,e),this.validateMediaAccessConditions("forbidOthersAudio",e,!0);try{let t;t=this.isMeetingCapabilityVideoRestricted()?3:1,await this.updateAttendeeRestrictions(t,e),this._sendFeatureUsage("forbidOthersAudio",oE.success,e)}catch(t){throw this._logger.error(`Could not change a participant state. Code: ${t?.response?.status} correlationId: ${e}`),this._sendFeatureUsage("forbidOthersAudio",oE.failure),bb(t,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitVideo(e){const t=Mf();this._sendFeatureUsage("permitVideo",oE.attempt,t),this.validateMediaAccessConditions("permitVideo",t,!1,!0,e.map((e=>DS(e))));try{const i=e.map((e=>DS(e)));this.isMeetingCapabilityVideoRestricted()?await this.addModalityState(i,"attendeeVideoUnrestricted",t):await this.removeModalityState(i,"attendeeVideoRestricted",t),this._sendFeatureUsage("permitVideo",oE.success,t)}catch(e){throw this._logger.error(`Could not change a participant state. Code: ${e?.response?.status} correlationId: ${t}`),this._sendFeatureUsage("permitVideo",oE.failure),bb(e,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidVideo(e){const t=Mf();this._sendFeatureUsage("forbidVideo",oE.attempt,t),this.validateMediaAccessConditions("forbidVideo",t,!1,!0,e.map((e=>DS(e))));try{const i=e.map((e=>DS(e)));this.isMeetingCapabilityVideoRestricted()?await this.removeModalityState(i,"attendeeVideoUnrestricted",t):await this.addModalityState(i,"attendeeVideoRestricted",t),this._sendFeatureUsage("forbidVideo",oE.success,t)}catch(e){throw this._logger.error(`Could not change a participant state. Code: ${e?.response?.status} correlationId: ${t}`),this._sendFeatureUsage("forbidVideo",oE.failure),bb(e,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitOthersVideo(){const e=Mf();this._sendFeatureUsage("permitOthersVideo",oE.attempt,e),this.validateMediaAccessConditions("permitOthersVideo",e,!0);try{let t;t=this.isMeetingCapabilityAudioRestricted()?1:0,await this.updateAttendeeRestrictions(t,e),this._sendFeatureUsage("permitOthersVideo",oE.success,e)}catch(t){throw this._logger.error(`Could not change a participant state. Code: ${t?.response?.status} correlationId: ${e}`),this._sendFeatureUsage("permitOthersVideo",oE.failure),bb(t,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidOthersVideo(){const e=Mf();this._sendFeatureUsage("forbidOthersVideo",oE.attempt,e),this.validateMediaAccessConditions("forbidOthersVideo",e,!0);try{let t;t=this.isMeetingCapabilityAudioRestricted()?3:2,await this.updateAttendeeRestrictions(t,e),this._sendFeatureUsage("forbidOthersVideo",oE.success,e)}catch(t){throw this._logger.error(`Could not change a participant state. Code: ${t?.response?.status} correlationId: ${e}`),this._sendFeatureUsage("forbidOthersVideo",oE.failure),bb(t,ee.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}getMeetingMediaAccess(){return{isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}}updateAttendeeRestrictions(e,t){const i={attendeeRestrictions:e};return this._tsCall.updateMeetingSettings(i,t).catch((e=>{this._logger.error(`updateAttendeeRestrictions: failed with correlationId: ${t}, error: ${JSON.stringify(e)}`)}))}getPublishedState(e){return e.typeStates.filter((e=>["attendeeVideoRestricted","attendeeAudioRestricted","attendeeVideoUnrestricted","attendeeModalitiesUnrestricted"].includes(e.type)))}addModalityState(e,t,i){return new Promise(((n,r)=>{const s={type:t,level:"user",content:"{}",participantIds:e};this._tsCall.publishState(s,i).then((()=>{n()})).catch((t=>{const n=`addModalityState: failed with error: ${JSON.stringify({...t,correlationId:i,participantIds:e})}`;this._logger.error(n),r(n)}))}))}removeModalityState(e,t,i){const n=this._tsCall.publishedStates?this.getStateIdForParticipants(this._tsCall.publishedStates,e,t):[];if(Z.isEmpty(n)){const n=`removeModalityState: no valid stateIds found for participants: ${e}, publishStateType: ${t} correlationId: ${i}`;return this._logger.error(n),Promise.reject(n)}return new Promise(((e,t)=>{const r={stateIds:n};this._tsCall.removeState(r,i).then((()=>{e()})).catch((e=>{const r=`removeModalityState: failed with error: ${JSON.stringify({...e,correlationId:i,stateIds:n})}`;this._logger.error(r),t(r)}))}))}getStateIdForParticipants(e,t,i){const n=[],r=e&&e.typeStates&&e.typeStates.find((e=>e.type===i));return Z.isEmpty(r?.participantStates)?(this._logger.error(`getStateIdForParticipants: no valid typeState or participantStates found for participants: ${t}`),n):(t.forEach((e=>{const t=r?.participantStates.find((t=>t&&t.id===e));Z.isEmpty(t)?this._logger.error(`getStateIdForParticipants: participant: ${e} not found.`):Z.isEmpty(t?.publishedState)?this._logger.error(`getStateIdForParticipants: no published state for participant: ${e}`):t?.publishedState&&n.push(t.publishedState.stateId)})),n)}validateMediaAccessConditions(e,t,i,n,r){let s;if(this._ecsTeamsMediaAccessEnabled)if(this.isUserRoleEligible())if(i||this.isSupportedConversationType())if(i&&!this._supportedConversationTypesForMuteAll.includes(this._tsCall.conversationType))this._logger.error(`Conversation type is not supported for media access all feature, conversation type: ${this._tsCall.conversationType}`),s=new le({defaultError:ee.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."),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.CALL_NOT_CONNECTED,defaultErrorMessageArgs:["call state: ",this._tsCall.state]});else if(Z.isEmpty(r))n&&Z.isEmpty(r)?(this._logger.error("Participants array is empty."),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.INVALID_PARTICIPANTS_LIST})):this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions||(this._logger.error("Meeting capability attendee restrictions is empty."),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.INVALID_MEETING_CAPABILITY_ATTENDEE_RESTRICTIONS,defaultErrorMessageArgs:["Meeting capability attendeerestrictions is empty."]}));else{const e=this._tsCall.participants.find((e=>r?.includes(e.id)&&e.advancedMeetingRole!==Bb));e&&(this._logger.error(`Participant is not an attendee. id: ${e.id}`),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.ROLE_RESTRICTED,defaultErrorMessageArgs:["Participant role: ",e.advancedMeetingRole||""]}))}else this._logger.error(`Conversation type is not supported for media access feature, conversation type: ${this._tsCall.conversationType}`),s=new le({defaultError:ee.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."),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.UNSUPPORTED_ROLE,defaultErrorMessageArgs:["User role: ",this._tsCall.advancedMeetingRole||""]});else this._logger.error("Media access feature is not enabled."),s=new le({defaultError:ee.FEATURES.MEDIA_ACCESS.FEATURE_DISABLED,defaultErrorMessageArgs:["Media access feature is not enabled."]});if(s)throw this._sendFeatureUsage(e,oE.failure,t),s}_sendFeatureUsage(e,t,i){hb({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"MediaAccess",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}class $b{constructor(e,t){this._logger=e,this._ecsConfig=vy(),this._call=t}getResolvedCapabilitiesBasedOnRole(e,t){let i={...t},n=e.toLocaleLowerCase();return n!==yS.Attendee.toLocaleLowerCase()&&n!==yS.Presenter.toLocaleLowerCase()&&n!==yS.Consumer.toLocaleLowerCase()&&n!==yS.Organizer.toLocaleLowerCase()&&n!==yS.Coorganizer.toLocaleLowerCase()||(n=n.replace("-",""),t.shareScreen.reason!=ES.UserPolicyRestricted&&(this._ecsConfig[_S][n][Nb.shareScreen]?i.shareScreen={isPresent:!0,reason:ES.Capable}:i.shareScreen={isPresent:!1,reason:ES.RoleRestricted}),this._ecsConfig[_S][n][Nb.removeParticipant]?i.removeParticipant={isPresent:!0,reason:ES.Capable}:i.removeParticipant={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.hangUpForEveryOne]?i.hangUpForEveryOne={isPresent:!0,reason:ES.Capable}:i.hangUpForEveryOne={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.addCommunicationUser]?i.addCommunicationUser={isPresent:!0,reason:ES.Capable}:i.addCommunicationUser={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.addTeamsUser]?i.addTeamsUser={isPresent:!0,reason:ES.Capable}:i.addTeamsUser={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.addPhoneNumber]?i.addPhoneNumber={isPresent:!0,reason:ES.Capable}:i.addPhoneNumber={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.manageLobby]?i.manageLobby={isPresent:!0,reason:ES.Capable}:i.manageLobby={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.spotlightParticipant]?i.spotlightParticipant={isPresent:!0,reason:ES.Capable}:i.spotlightParticipant={isPresent:!1,reason:ES.RoleRestricted},this._ecsConfig[_S][n][Nb.removeParticipantsSpotlight]?i.removeParticipantsSpotlight={isPresent:!0,reason:ES.Capable}:i.removeParticipantsSpotlight={isPresent:!1,reason:ES.RoleRestricted},t.blurBackground.reason!=ES.UserPolicyRestricted&&(this._ecsConfig[_S][n][Nb.blurBackground]?i.blurBackground={isPresent:!0,reason:ES.Capable}:i.blurBackground={isPresent:!1,reason:ES.RoleRestricted}),t.startLiveMeetingCaptions.reason!=ES.UserPolicyRestricted&&(this._ecsConfig[_S][n][Nb.startLiveMeetingCaptions]?i.startLiveMeetingCaptions={isPresent:!0,reason:ES.Capable}:i.startLiveMeetingCaptions={isPresent:!1,reason:ES.RoleRestricted}),t.startLiveCallingCaptions.reason!=ES.UserPolicyRestricted&&(this._ecsConfig[_S][n][Nb.startLiveCallingCaptions]?i.startLiveCallingCaptions={isPresent:!0,reason:ES.Capable}:i.startLiveCallingCaptions={isPresent:!1,reason:ES.RoleRestricted}),t.setCaptionLanguage.reason!=ES.TeamsPremiumLicenseRestricted&&(this._ecsConfig[_S][n][Nb.setCaptionLanguage]?i.setCaptionLanguage={isPresent:!0,reason:ES.Capable}:i.setCaptionLanguage={isPresent:!1,reason:ES.RoleRestricted}),t.raiseHand.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.raiseHand]?i.raiseHand={isPresent:!0,reason:ES.Capable}:i.raiseHand={isPresent:!1,reason:ES.RoleRestricted}),t.pstnDialOut.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.pstnDialOut]?i.pstnDialOut={isPresent:!0,reason:ES.Capable}:i.pstnDialOut={isPresent:!1,reason:ES.RoleRestricted}),t.muteOthers.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.muteOthers]?i.muteOthers={isPresent:!0,reason:ES.Capable}:i.muteOthers={isPresent:!1,reason:ES.RoleRestricted}),t.forbidOthersAudio.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.forbidOthersAudio]?i.forbidOthersAudio={isPresent:!0,reason:ES.Capable}:i.forbidOthersAudio={isPresent:!1,reason:ES.RoleRestricted}),t.forbidOthersVideo.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.forbidOthersVideo]?i.forbidOthersVideo={isPresent:!0,reason:ES.Capable}:i.forbidOthersVideo={isPresent:!1,reason:ES.RoleRestricted}),t.useReactions.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.useReactions]?i.useReactions={isPresent:!0,reason:ES.Capable}:i.useReactions={isPresent:!1,reason:ES.RoleRestricted}),t.viewAttendeeNames.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.viewAttendeeNames]?i.viewAttendeeNames={isPresent:!0,reason:ES.Capable}:i.viewAttendeeNames={isPresent:!1,reason:ES.RoleRestricted}),t.startTogetherMode.reason!=ES.MeetingRestricted&&(this._ecsConfig[_S][n][Nb.startTogetherMode]?i.startTogetherMode={isPresent:!0,reason:ES.Capable}:i.startTogetherMode={isPresent:!1,reason:ES.RoleRestricted}),t.joinBreakoutRooms.reason!=ES.UserPolicyRestricted&&(this._ecsConfig[_S][n][Nb.joinBreakoutRooms]?i.joinBreakoutRooms={isPresent:!0,reason:ES.Capable}:i.joinBreakoutRooms={isPresent:!1,reason:ES.RoleRestricted})),this.resolveMicVideoAndScreenShareCapabilities(i),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on role change to ${e}`),i}getResolvedCapabilitiesBasedOnMeetingCapabilities(e,t){let i={...t};return this.resolveMicVideoAndScreenShareCapabilities(i),null!=e.allowRaiseHands&&(e.allowRaiseHands?i.raiseHand={isPresent:!0,reason:ES.Capable}:i.raiseHand={isPresent:!1,reason:ES.MeetingRestricted}),null!=e.allowPstnConferencing&&(e.allowPstnConferencing?i.pstnDialOut={isPresent:!0,reason:ES.Capable}:i.pstnDialOut={isPresent:!1,reason:ES.MeetingRestricted}),null!=e.allowTeamsMeetingReactions&&(e.allowTeamsMeetingReactions?i.useReactions={isPresent:!0,reason:ES.Capable}:i.useReactions={isPresent:!1,reason:ES.MeetingRestricted}),null!=e.maskIdentitiesForRole&&(e.maskIdentitiesForRole?i.viewAttendeeNames={isPresent:!1,reason:ES.MeetingRestricted}:i.viewAttendeeNames={isPresent:!0,reason:ES.Capable}),null!=e.allowTranslatedCaptions&&(e.allowTranslatedCaptions?i.setCaptionLanguage={isPresent:!0,reason:ES.Capable}:i.setCaptionLanguage={isPresent:!1,reason:ES.TeamsPremiumLicenseRestricted}),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on meeting details change to ${e}`),i}getResolvedCapabilitiesBasedOnUserPolicy(e,t){let i={...t};return null!=e.teamsMeetingPolicy?.screenSharingMode&&("Disabled"==e.teamsMeetingPolicy?.screenSharingMode?i.shareScreen={isPresent:!1,reason:ES.UserPolicyRestricted}:i.shareScreen={isPresent:!0,reason:ES.Capable}),null!=e.teamsMeetingPolicy?.liveCaptionsEnabledType&&("Disabled"==e.teamsMeetingPolicy?.liveCaptionsEnabledType?i.startLiveMeetingCaptions={isPresent:!1,reason:ES.UserPolicyRestricted}:i.startLiveMeetingCaptions={isPresent:!0,reason:ES.Capable}),null!=e.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling&&("Disabled"==e.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling?i.startLiveCallingCaptions={isPresent:!1,reason:ES.UserPolicyRestricted}:i.startLiveCallingCaptions={isPresent:!0,reason:ES.Capable}),null!=e.teamsMeetingPolicy?.videoFiltersMode&&("NoFilters"==e.teamsMeetingPolicy?.videoFiltersMode?i.blurBackground={isPresent:!1,reason:ES.UserPolicyRestricted}:i.blurBackground={isPresent:!0,reason:ES.Capable}),null!=e.teamsMeetingPolicy?.allowBreakoutRooms&&(e.teamsMeetingPolicy?.allowBreakoutRooms?i.joinBreakoutRooms={isPresent:!0,reason:ES.Capable}:i.joinBreakoutRooms={isPresent:!1,reason:ES.UserPolicyRestricted}),null!=e.teamsMeetingPolicy?.ipAudioMode&&("Disabled"===e.teamsMeetingPolicy?.ipAudioMode?i.unmuteMic={isPresent:!1,reason:ES.IpModeUserPolicyRestricted}:i.unmuteMic={isPresent:!0,reason:ES.Capable}),null!=e.teamsMeetingPolicy?.ipVideoMode&&("Disabled"===e.teamsMeetingPolicy?.ipVideoMode?i.turnVideoOn={isPresent:!1,reason:ES.IpModeUserPolicyRestricted}:i.turnVideoOn={isPresent:!0,reason:ES.Capable}),this.resolveMicVideoAndScreenShareCapabilities(i),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on user policy update to ${e}`),i}getResolvedCapabilitiesBasedOnUserProperties(e,t){let i={...t};return this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on user properties update to ${e}`),i}getResolvedCapabilitiesBasedOnCallPublishedStates(e){const t={...e};return this.resolveMicVideoAndScreenShareCapabilities(t),this._logger.log(`Capabilities resolved to : ${JSON.stringify(t)}`),t}resolveMicVideoAndScreenShareCapabilities(e){const t=e.unmuteMic.reason===ES.IpModeUserPolicyRestricted,i=e.turnVideoOn.reason===ES.IpModeUserPolicyRestricted;if(!t||!i){const n=this._call.feature(lb(Vb)).getLocalParticipantMediaAccess();t||(e.unmuteMic=n.isAudioPermitted?{isPresent:!0,reason:ES.Capable}:{isPresent:!1,reason:ES.MeetingRestricted}),i||(e.turnVideoOn=n.isVideoPermitted?{isPresent:!0,reason:ES.Capable}:{isPresent:!1,reason:ES.MeetingRestricted})}e.shareScreen.reason===ES.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?e.shareScreen={isPresent:!1,reason:ES.ExplicitConsentRequired}:e.shareScreen.reason!==ES.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(e.shareScreen={isPresent:!0,reason:ES.Capable}),e.unmuteMic.reason===ES.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?e.unmuteMic={isPresent:!1,reason:ES.ExplicitConsentRequired}:e.unmuteMic.reason!==ES.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(e.unmuteMic={isPresent:!0,reason:ES.Capable}),e.turnVideoOn.reason===ES.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?e.turnVideoOn={isPresent:!1,reason:ES.ExplicitConsentRequired}:e.turnVideoOn.reason!==ES.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(e.turnVideoOn={isPresent:!0,reason:ES.Capable})}}class jb{constructor(e,t,i,n,r,s){this._meetingCapabilities={},this._eventEmitter=e,this._logger=t,this._callInfo=n,this._tsCall=s,this._call=i,this._callAgent=r,this._capabilities=this.initializeCapabilities(),(this._callInfo.context==uy.Rooms||this._callInfo.context==uy.TeamsMeeting)&&this.doInitialCapabilityResolutionBasedOnRole(),this._callInfo.context==uy.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnUserPolicy(),this._callInfo.context==uy.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnMeetingCapabilities(),this._callInfo.context==uy.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnCallPublishedStates()}initializeCapabilities(){return this._logger.info("initializing capabilities"),this._callInfo.context!=uy.Rooms&&this._callInfo.context!=uy.TeamsMeeting?{turnVideoOn:{isPresent:!1,reason:ES.FeatureNotSupported},unmuteMic:{isPresent:!1,reason:ES.FeatureNotSupported},shareScreen:{isPresent:!1,reason:ES.FeatureNotSupported},removeParticipant:{isPresent:!1,reason:ES.FeatureNotSupported},hangUpForEveryOne:{isPresent:!1,reason:ES.FeatureNotSupported},addCommunicationUser:{isPresent:!1,reason:ES.FeatureNotSupported},addTeamsUser:{isPresent:!1,reason:ES.FeatureNotSupported},addPhoneNumber:{isPresent:!1,reason:ES.FeatureNotSupported},manageLobby:{isPresent:!1,reason:ES.FeatureNotSupported},spotlightParticipant:{isPresent:!1,reason:ES.FeatureNotSupported},removeParticipantsSpotlight:{isPresent:!1,reason:ES.FeatureNotSupported},blurBackground:{isPresent:!1,reason:ES.FeatureNotSupported},startLiveMeetingCaptions:{isPresent:!1,reason:ES.FeatureNotSupported},startLiveCallingCaptions:{isPresent:!1,reason:ES.FeatureNotSupported},setCaptionLanguage:{isPresent:!1,reason:ES.FeatureNotSupported},raiseHand:{isPresent:!1,reason:ES.FeatureNotSupported},pstnDialOut:{isPresent:!1,reason:ES.FeatureNotSupported},muteOthers:{isPresent:!1,reason:ES.FeatureNotSupported},useReactions:{isPresent:!1,reason:ES.FeatureNotSupported},viewAttendeeNames:{isPresent:!1,reason:ES.FeatureNotSupported},startTogetherMode:{isPresent:!1,reason:ES.FeatureNotSupported},joinBreakoutRooms:{isPresent:!1,reason:ES.FeatureNotSupported},forbidOthersAudio:{isPresent:!1,reason:ES.FeatureNotSupported},forbidOthersVideo:{isPresent:!1,reason:ES.FeatureNotSupported}}:{turnVideoOn:{isPresent:!1,reason:ES.NotInitialized},unmuteMic:{isPresent:!1,reason:ES.NotInitialized},shareScreen:{isPresent:!1,reason:ES.NotInitialized},removeParticipant:{isPresent:!1,reason:ES.NotInitialized},hangUpForEveryOne:{isPresent:!1,reason:ES.NotInitialized},addCommunicationUser:{isPresent:!1,reason:ES.NotInitialized},addTeamsUser:{isPresent:!1,reason:ES.NotInitialized},addPhoneNumber:{isPresent:!1,reason:ES.NotInitialized},manageLobby:{isPresent:!1,reason:ES.NotInitialized},spotlightParticipant:{isPresent:!1,reason:ES.NotInitialized},removeParticipantsSpotlight:{isPresent:!1,reason:ES.NotInitialized},blurBackground:{isPresent:!1,reason:ES.NotInitialized},startLiveMeetingCaptions:{isPresent:!1,reason:ES.FeatureNotSupported},startLiveCallingCaptions:{isPresent:!1,reason:ES.FeatureNotSupported},setCaptionLanguage:{isPresent:!1,reason:ES.FeatureNotSupported},raiseHand:{isPresent:!1,reason:ES.NotInitialized},pstnDialOut:{isPresent:!1,reason:ES.NotInitialized},muteOthers:{isPresent:!1,reason:ES.NotInitialized},useReactions:{isPresent:!1,reason:ES.NotInitialized},joinBreakoutRooms:{isPresent:!1,reason:ES.NotInitialized},viewAttendeeNames:{isPresent:!1,reason:ES.NotInitialized},startTogetherMode:{isPresent:!1,reason:ES.NotInitialized},forbidOthersAudio:{isPresent:!1,reason:ES.NotInitialized},forbidOthersVideo:{isPresent:!1,reason:ES.NotInitialized}}}doInitialCapabilityResolutionBasedOnRole(){this.resolveCapabilitiesBasedOnRole()}doInitialCapabilityResolutionBasedOnUserPolicy(){this.getCapabilityResolver()instanceof $b&&this._callInfo.context!=uy.Rooms&&this.resolveCapabilitiesBasedOnUserPolicy()}doInitialCapabilityResolutionBasedOnMeetingCapabilities(){this.resolveCapabilitiesBasedOnMeetingCapabilities()}doInitialCapabilityResolutionBasedOnCallPublishedStates(){this.resolveCapabilitiesBasedOnCallPublishedStates()}getCapabilityResolver(){return this._callInfo.context?.match(uy.Rooms)?new Lb(this._logger):(this._callInfo.context?.match(uy.TeamsMeeting),new $b(this._logger,this._call))}getCapabilities(){return this._capabilities}resolveCapabilitiesBasedOnRole(){if(this._callInfo.context!=uy.Rooms&&this._callInfo.context!=uy.TeamsMeeting)return;let e=this._call.role;e==yS.Unknown&&(e=this._callInfo.context==uy.Rooms?yS.Consumer:yS.Attendee);let t=this.getCapabilityResolver();if(t){let i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnRole(e,this._capabilities),!Z.isEqual(i,this._capabilities)){const t=this.getChangedCapabilitiesInfo(i,this._capabilities,"RoleChanged");this._logger.info(`Capabilities has changed based on role update to ${e}, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(t)}`),this._eventEmitter.emit("capabilitiesChanged",t)}}}resolveCapabilitiesBasedOnMeetingCapabilities(){if(this._callInfo.context!=uy.TeamsMeeting)return;let e={};e={...this._tsCall.meetingDetails?.capabilities,...this._tsCall.meetingDetails?.meetingCapability,...this._tsCall.meetingDetails?.recordingConsentDetails},this._meetingCapabilities={...e};let t=this.getCapabilityResolver();if(t&&t){const i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnMeetingCapabilities(e,this._capabilities),!Z.isEqual(i,this._capabilities)){const e=this.getChangedCapabilitiesInfo(i,this._capabilities,"MeetingOptionOrOrganizerPolicyChanged");this._logger.info(`Capabilities has changed due to meeting capabilities, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}resolveCapabilitiesBasedOnCallPublishedStates(){if(this._callInfo.context!==uy.TeamsMeeting)return;const e=this.getCapabilityResolver();if(e&&e){const t=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=e.getResolvedCapabilitiesBasedOnCallPublishedStates(this._capabilities),!Z.isEqual(t,this._capabilities)){const e=this.getChangedCapabilitiesInfo(t,this._capabilities,"MeetingOptionOrOrganizerPolicyChanged");this._logger.info(`Capabilities has changed due to call published states, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}resolveCapabilitiesBasedOnUserPolicy(){if(this._callInfo.context!=uy.TeamsMeeting)return;let e=this._callAgent.getUserPolicy(),t=this.getCapabilityResolver();if(t&&t&&e){let i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnUserPolicy(e,this._capabilities),!Z.isEqual(i,this._capabilities)){const e=this.getChangedCapabilitiesInfo(i,this._capabilities,"UserPolicyChanged");this._logger.info(`Capabilities has changed due to user policy, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}resolveCapabilitiesBasedOnUserProperties(){if(this._callInfo.context!=uy.TeamsMeeting)return;let e=this._callAgent.getUserProperties(),t=this.getCapabilityResolver();if(t&&t&&e){let i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnUserProperties(e,this._capabilities),!Z.isEqual(i,this._capabilities)){const e=this.getChangedCapabilitiesInfo(i,this._capabilities,"TeamsPremiumLicenseChanged");this._logger.info(`Capabilities has changed due to Teams Premium License, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}getMeetingsCapabilitiesInternal(){return this._meetingCapabilities}getChangedCapabilitiesInfo(e,t,i){let n={},r={};return Object.keys(e).forEach((i=>{e[i].isPresent!=t[i].isPresent&&(n[i]=e[i],r[i]=t[i])})),{oldValue:n,newValue:r,reason:i}}}class Gb{constructor(e){this._eventEmitter=e}get capabilities(){return this._capabilityResolver.getCapabilities()}initialize(e,t,i,n,r,s){this._logger=s.createChild((()=>`CapabilitiesFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._call=i,this._callInfo=n,this._internalCallAgent=t,this._timeToInitialize=new Date,this._capabilityResolver=new jb(this._eventEmitter,this._logger,this._call,this._callInfo,this._internalCallAgent,this._tsCall),this._call.on("roleChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnRole();let e=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after role set is "+e)})),this._call.onMeetingCapabilitiesChanged("meetingCapabilitiesChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities();let e=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after meeting set up is"+e)})),this._call.feature(lb(Vb)).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 e=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after published state change is"+e)}))}}var qb,zb;!function(e){e.ping="ping",e.pong="pong"}(qb||(qb={}));class Wb{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(e,t){this._logger=t,this._callAgent=e?.callClient?.callAgent,this._sdkDiagnosticInformation=e?.callClient.sdkDiagnosticInformation,this._logger.info("waiting for call agent to be created"),e?.callClient.on("callAgentCreated",(()=>{this._callAgent=e?.callClient.callAgent,this.subscribeToCallAgentEvents()}))}dispose(){}subscribeToCallAgentEvents(){try{this._callAgent?.on("callsUpdated",(e=>{[...e.added,...e.removed].forEach((e=>{this.updateLocalParticipantIdMap(e),e.on("idChanged",(()=>{this.updateLocalParticipantIdMap(e)}))}))})),this._callAgent?.on("incomingCall",(e=>{let t=e.incomingCall;t.on("callEnded",(e=>{try{this._incommingCallIdMap[t.id]=JSON.stringify(e.callEndReason)}catch(e){this._incommingCallIdMap[t.id]="callEnd reason unknown"}}));try{this._incommingCallIdMap[t.id]=JSON.stringify(e.incomingCall.callerInfo.identifier?.kind)}catch(e){this._incommingCallIdMap[t.id]="identifier kind unknown"}}))}catch(e){this._logger.info("failed to subscribe to call agent events, due to non initialized call agent")}}updateLocalParticipantIdMap(e){try{let t=this._localParticipantIdMap[e.tsCall.participantId]?.callIds.filter((t=>t!==e.tsCall.callId)).concat([e.tsCall.callId])??[e.tsCall.callId],i=[],n=[],r=e.callEndReason?JSON.stringify(e.callEndReason):e.state,s=e.state;this._localParticipantIdMap[e.tsCall.participantId]?.callEndReasons?(this._localParticipantIdMap[e.tsCall.participantId].callEndReasons.slice(-1)[0]!==r?(this._localParticipantIdMap[e.tsCall.participantId].callEndReasons.push(r),i=this._localParticipantIdMap[e.tsCall.participantId].callEndReasons):i=this._localParticipantIdMap[e.tsCall.participantId].callEndReasons,this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.slice(-1)[0]!==s?(this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.push(s),n=this._localParticipantIdMap[e.tsCall.participantId].stateTransitions):n=this._localParticipantIdMap[e.tsCall.participantId].stateTransitions):(i=[r],n=[e.state]),this._localParticipantIdMap[e.tsCall.participantId]={callIds:t,callEndReasons:i,stateTransitions:n},this._logger.info(`localParticipantIdMap: ${JSON.stringify(this._localParticipantIdMap)}`),e.on("stateChanged",(()=>{"Connected"===e.state&&(this._lastLocalParticipantId=e.tsCall.participantId,this._logger.info(`last patricipant id: ${this._lastLocalParticipantId}`)),this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.slice(-1)[0]!==e.state&&this.localParticipantIdMap[e.tsCall.participantId].stateTransitions.push(e.state)}))}catch(e){this._logger.error(`exception occured while updating localParticipantId map: ${e}`)}}}class Kb{get isCallClientActiveInAnotherTab(){return this._isCallClientActiveInAnotherTab}get isAnotherCallClientActiveInSameTab(){return this._isAnotherCallClientActiveInSameTab}constructor(e){this._eventEmitter=e,this._tabGroupId=Kb.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(vy().debugInfo.broadcastChannelName)}initialize(e,t,i){this._callClient=e,this._logger=t,this._telemetryLogManager=i;const n=vy().debugInfo.tabsBroadcastDelay,r=vy().debugInfo.tabsUpdateDelay;this.tabsCheck(),this._channel.postMessage({action:qb.ping,tabId:Kb.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:qb.ping,tabId:Kb.tabId,groupId:this._tabGroupId}),setTimeout((()=>{null===this._areThereMultipleTabs&&(this._areThereMultipleTabs=!1),null===this._manyCallClientInSameTab&&(this._manyCallClientInSameTab=!1),this.tabsUpdate()}),r)}),n)}tabsCheck(){this._channel.addEventListener("message",(e=>{e.data?.action!==qb.ping&&e.data?.action!==qb.pong||(e.data?.action===qb.ping&&(Kb.tabId===e.data.tabId?this._manyCallClientInSameTab=!0:Kb.tabId!==e.data.tabId&&(this._areThereMultipleTabs=!0),this._channel.postMessage({action:qb.pong,tabId:Kb.tabId,groupId:this._tabGroupId})),e.data?.action===qb.pong&&(Kb.tabId===e.data.tabId?this._manyCallClientInSameTab=!0:Kb.tabId!==e.data.tabId&&(this._areThereMultipleTabs=!0),this._tabGroupId!==e.data.groupId&&(this._tabGroupId=e.data.groupId)),this.tabsUpdate())}))}sendTabUpdateToCallEvent(){this._callClient.callAgent?._calls?.forEach((e=>e?.stats?.recordEvent({name:sE.sdk_active_in_another_tab,callId:e.id,localParticipantId:e.tsCall.participantId,data:{tabId:Kb.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab}})))}sendTabUpdateEvent(){const e={tabId:Kb.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab};this._telemetryLogManager.sendEvent({name:aE.acs_calling_tab_events,tenant:xv,properties:e})}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)}}Kb.tabId=Mf(),function(e){e[e.Good=1]="Good",e[e.Poor=2]="Poor",e[e.Bad=3]="Bad"}(zb||(zb={}));const Jb="networkReconnect",Yb="networkReceiveQuality",Qb="networkSendQuality",Zb="networkRelaysNotReachable",Xb="noNetwork",e_="noSpeakerDevicesEnumerated",t_="noMicrophoneDevicesEnumerated",i_="microphoneNotFunctioning",n_="microphoneMuteUnexpectedly",r_="cameraStoppedUnexpectedly",s_="capturerStoppedUnexpectedly",a_="speakingWhileMicrophoneIsMuted",o_="cameraFreeze",l_="cameraStartFailed",c_="capturerStartFailed",d_="cameraStartTimedOut",u_="screenshareRecordingDisabled",h_="microphonePermissionDenied",g_="cameraPermissionDenied";function p_(e,t){return"serverConnection"==t?e?"Good":"Bad":"boolean"==typeof e?e?"Bad":"Good":zb[e]}class m_{get network(){return void 0===this._network&&(this._network=new v_(this._internalApi,this._logger),this._network.bindToTsCallQualityChangedEvent()),this._network}get media(){return void 0===this._media&&(this._media=new S_(this._internalApi,this._logger),this._media.bindToTsCallQualityChangedEvent()),this._media}get remote(){return void 0===this._remote&&(this._remote=new y_(this._internalApi,this._logger),this._remote.bindToTsCallPublishedStatesChangedEvent()),this._remote}initialize(e,t){this._internalApi=e,this._logger=t}dispose(){}}class f_{constructor(e,t,i){this._name=e,this.internalApi=t,this.logger=i,this._tsUfdUnknownValue=0,this.tsToAcsNetworkQualityEventTypeMap={5:Jb,2:Yb,1:Qb,32:Zb,37:Xb},this.tsToAcsMediaQualityEventTypeMap={44:e_,43:t_,9:i_,25:n_,27:a_,45:o_,33:l_,34:d_,55:u_,26:h_,47:g_},this.tsQualityToAcsQualityMap={1:zb.Good,2:zb.Poor,3:zb.Bad},this.tsQualityToAcsBooleanMap={3:!0,1:!1},this.eventEmitter=new OE.EventEmitter}bindToTsCallQualityChangedEvent(){this.internalApi.tsCall.on("callQualityChanged",(e=>{try{let t;if("NetworkDiagnostics"===this._name?t=this.mapTsNetworkQualityEventType(e.type):"MediaDiagnostics"===this._name&&(t=this.mapTsMediaQualityEventType(e.type,e.mediaType)),t){if(e.value===this._tsUfdUnknownValue)return;let i,n;if("NetworkDiagnostics"===this._name){const{mappedQualityLevel:n,valueType:r}=this.mapTsNetworkQualityLevel(t,e.value);i=n,this.setLatestDiagnostic(t,{value:i,valueType:r})}else if("MediaDiagnostics"===this._name){const{mappedQualityLevel:n,valueType:r}=this.mapTsMediaQualityLevel(t,e.value);i=n,this.setLatestDiagnostic(t,{value:i,valueType:r})}if("number"!=typeof i||i!==zb.Good&&i!==zb.Poor&&i!==zb.Bad){if("boolean"!=typeof i)throw this.logger.error(`Incorrect valueType mapped for diagnostic='${t}', value='${i}'`),new le({defaultError:ee.FEATURES.DIAGNOSTICS.INCORRECT_VALUETYPE_MAPPED});n="DiagnosticFlag"}else n="DiagnosticQuality";const r={diagnostic:t,value:i,valueType:n};this.logger.log(`Call diagnostic changed, diagnostic='${r.diagnostic}', value='${r.value}'`);const s="DiagnosticFlag"===r.valueType&&!0===r.value,a="DiagnosticQuality"===r.valueType&&(r.value===zb.Bad||r.value===zb.Poor);(s||a)&&this.logger.warn(`Call diagnostic error raised!, diagnostic='${r.diagnostic}', value='${r.value}', value type='${r.valueType}'`),this.sendDiagnosticEvent({name:"UserFacingDiagnostics",callId:this.internalApi.tsCall.callId,localParticipantId:this.internalApi.tsCall.participantId,remoteParticipantId:"",diagnostic:r.diagnostic,valueText:p_(r.value),valueType:r.valueType,correlationId:""}),this.eventEmitter.emit("diagnosticChanged",r)}}catch(e){this.logger.error(`${e?.message})`)}}))}mapTsNetworkQualityEventType(e){return this.tsToAcsNetworkQualityEventTypeMap[e]}mapTsNetworkQualityLevel(e,t){let i,n;switch(e){case Jb:case Yb:case Qb:n="DiagnosticQuality",i=this.tsQualityToAcsQualityMap[t];break;case Zb:case Xb:n="DiagnosticFlag",i=this.tsQualityToAcsBooleanMap[t]}return{mappedQualityLevel:i,valueType:n}}mapTsMediaQualityEventType(e,t){const i=this.tsToAcsMediaQualityEventTypeMap[e];if(i===n_)switch(t){case 1:return r_;case 2:return s_}return i===l_&&2===t?c_:i}mapTsMediaQualityLevel(e,t){let i,n;switch(e){case e_:case t_:case i_:case n_:case a_:case o_:case l_:case d_:case u_:case h_:case g_:case r_:case s_:case c_:n="DiagnosticFlag",i=this.tsQualityToAcsBooleanMap[t]}return{mappedQualityLevel:i,valueType:n}}sendDiagnosticEvent(e){this.internalApi.telemetryLogManager.sendEvent({name:aE.acs_calling_call_stats_and_ufds,tenant:xv,properties:{name:e.name,callId:e.callId,localParticipantId:e.localParticipantId,remoteParticipantId:e.remoteParticipantId,diagnostic:e.diagnostic,valueText:e.valueText,valueType:e.valueType,correlationId:e.correlationId}})}}class v_ extends f_{constructor(e,t){super("NetworkDiagnostics",e,t.createChild((()=>`[UserFacingDiagnosticsFeature:NetworkDiagnostics:Call(id='${e.tsCall.callId}', state='${e.tsCall.state}')]`))),this.latestNetworkDiagnostics=new Map}setLatestDiagnostic(e,t){this.latestNetworkDiagnostics.set(e,t)}on(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getLatest(){try{return _y(this.latestNetworkDiagnostics)}catch(e){return this.logger.error("Failed to get latest network diagnostics"),{}}}}class S_ extends f_{constructor(e,t){super("MediaDiagnostics",e,t.createChild((()=>`[UserFacingDiagnosticsFeature:MediaDiagnostics:Call(id='${e.tsCall.callId}', state='${e.tsCall.state}')]`))),this.latestMediaDiagnostics=new Map}setLatestDiagnostic(e,t){this.latestMediaDiagnostics.set(e,t)}on(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getLatest(){try{return _y(this.latestMediaDiagnostics)}catch(e){return this.logger.error("Failed to get latest media diagnostics"),{}}}}class y_ extends f_{constructor(e,t){super("RemoteDiagnostics",e,t.createChild((()=>`[UserFacingDiagnosticsFeature:RemoteDiagnosticsiagnostics:Call(id='${e.tsCall.callId}', state='${e.tsCall.state}')]`))),this._remoteDiagnosticCorrelationIdMap=new Map,this._isSendingRemoteDiagnostics=!1,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,HighSystemMemoryUsage:81},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 e=>{const t=[],i=new Set;e.typeStates.forEach((e=>{const n=(e,i)=>{const n=this.getRemoteDiagnosticIndex(e);n>-1&&this._latestRemoteDiagnostics.diagnostics[n].value!==e.value?(e={...e,remoteParticipant:this._latestRemoteDiagnostics.diagnostics[n].remoteParticipant},this._latestRemoteDiagnostics.diagnostics[n]=e,t.push(e)):-1!==n||this.isGoodServerRemoteDiagnostic(e)||(e={...e,remoteParticipant:this.internalApi.call.remoteParticipants.find((e=>DS(e.identifier)===i))},this._latestRemoteDiagnostics.diagnostics.push(e),t.push(e))},r=(e,t)=>{const i=this.createClientRemoteDiagnostic(t.id,e);for(const e of i)n(e,t.id)};"serverMediaUfd"===e.type&&(this.logger.debug(`Remote diagnostics changed, typeState='${JSON.stringify(e)}'`),e.participantStates.forEach((e=>{try{if(e.id!==this.internalApi.callAgent.getUserMri()){const t=this.createServerRemoteDiagnostic(e.id,e.publishedState?.content);n(t,e.id),i.add(e.id)}}catch(t){this.logger.error(`Error processing remote diagnostic: ${JSON.stringify(e)}, error: ${t?.message}`)}}))),"clientMediaUfd"===e.type&&(this.logger.debug(`Client remote diagnostics changed, typeState='${JSON.stringify(e)}'`),e.participantStates.forEach((e=>{try{if(e.id!==this.internalApi.callAgent.getUserMri()&&e.endpoints)for(const t of e.endpoints)r(t,e)}catch(t){this.logger.error(`Error processing client remote diagnostic: ${JSON.stringify(e)}, error: ${t?.message}`)}})))})),this.removeRemoteUserDiagnostics(i),t.length>0&&(this.sendRemoteDiagnosticsTelemetry(t),this.eventEmitter.emit("diagnosticChanged",{diagnostics:t}))})),this.internalApi.tsCall.on("participantCountsUpdated",(()=>{this._isSendingRemoteDiagnostics&&this.enableSendingRemoteDiagnosticsBasedOnRemoteAcsUserCount()}))}setLatestDiagnostic(e,t){}get isSendingDiagnosticsEnabled(){return this._isSendingRemoteDiagnostics}startSendingDiagnostics(){this._isSendingRemoteDiagnostics=!0,this.enableSendingRemoteDiagnosticsBasedOnRemoteAcsUserCount()}stopSendingDiagnostics(){this._isSendingRemoteDiagnostics=!1,this.internalApi.tsCall.enableRemoteUFDs?.(!1),this.logger.debug("Disabled client remote diagnostics")}getLatest(){return this._latestRemoteDiagnostics}on(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("diagnosticChanged"!==e)throw new le({defaultError:ee.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}enableSendingRemoteDiagnosticsBasedOnRemoteAcsUserCount(){const e=this.internalApi.call.remoteParticipants.filter((e=>"communicationUser"===e.identifier.kind)).length;e>0&&this._isSendingRemoteDiagnostics?(this.logger.debug(`Enabling remote client UFDs, totalRemoteAcsParticipants=${e}`),this.internalApi.tsCall.enableRemoteUFDs?.(!0)):0===e&&(this.logger.debug(`Disabling remote client UFDs, totalRemoteAcsParticipants=${e}`),this.internalApi.tsCall.enableRemoteUFDs?.(!1))}isGoodServerRemoteDiagnostic(e){return"serverConnection"===e.diagnostic&&!0===e.value}createServerRemoteDiagnostic(e,t){if(!t)throw new Error("Content is missing in remote diagnostic");return"string"==typeof t&&(t=JSON.parse(t)),{participantId:t.participantId,rawId:e,diagnostic:t.type,value:"string"==typeof t.value&&"good"===t.value.toLowerCase(),valueType:"DiagnosticFlag"}}mergeOrIgnoreClientDiagnostics(e){const t=vy().calling.remoteDiagnostic.sourceEvents.indexOf(e);if(t>-1){const e=vy().calling.remoteDiagnostic.exposedEvents[t];return this.logger.debug(`Merging ${vy().calling.remoteDiagnostic.sourceEvents[t]} to ${e}`),e}return e}createClientRemoteDiagnostic(e,t){if(!t.publishedState.content)throw new Error("Content is missing in client remote diagnostic");const i=[],n=t.publishedState.content;for(const r of n){const n=r.type;let s=this.mapTsNetworkQualityEventType(this.tsQualityStringToEnumMap[n]);const a=r.value;let o;if(s)o=this.mapTsNetworkQualityLevel(s,this.tsQualityLevelStringToEnumMap[a]);else{const e=r.mediaType;s=this.mapTsMediaQualityEventType(this.tsQualityStringToEnumMap[n],this.tsMediaStringToEnumMap[e]),o=this.mapTsMediaQualityLevel(s,this.tsQualityLevelStringToEnumMap[a])}const l=this.mergeOrIgnoreClientDiagnostics(s);if(""===l)continue;l!==s&&(s=l);const c={participantId:t.id,rawId:e,diagnostic:s,value:o.mappedQualityLevel,valueType:o.valueType};i.push(c)}return i}getRemoteDiagnosticIndex(e){return this._latestRemoteDiagnostics.diagnostics.findIndex((t=>t.participantId===e.participantId&&t.diagnostic===e.diagnostic))}removeRemoteUserDiagnostics(e){this._latestRemoteDiagnostics.diagnostics=this._latestRemoteDiagnostics.diagnostics.filter((t=>{const i=e.has(t.rawId);return i||this._remoteDiagnosticCorrelationIdMap.forEach(((e,i)=>{i.endsWith(`_${t.participantId}`)&&this._remoteDiagnosticCorrelationIdMap.delete(i)})),i}))}sendRemoteDiagnosticsTelemetry(e){this.logger.debug(`Sending remote diagnostics telemetry, number of diagnostics=${e.length}`),e.forEach((e=>{const t=`${e.diagnostic}_${e.participantId}`;this._remoteDiagnosticCorrelationIdMap.has(t)||this._remoteDiagnosticCorrelationIdMap.set(t,Mf()),this.sendDiagnosticEvent({name:"RemoteClientDiagnostics",callId:this.internalApi.tsCall.callId,localParticipantId:this.internalApi.tsCall.participantId,remoteParticipantId:e.participantId,diagnostic:e.diagnostic,valueText:p_(e.value,e.diagnostic),valueType:e.valueType,correlationId:this._remoteDiagnosticCorrelationIdMap.get(t)??""}),("DiagnosticFlag"===e.valueType&&!0===e.value||"DiagnosticQuality"===e.valueType&&e.value===zb.Good)&&this._remoteDiagnosticCorrelationIdMap.set(t,Mf())}))}}class C_{constructor(e){this._eventEmitter=e,this.localDominantList=[]}initialize(e,t,i,n,r=!1){this._logger=n.createChild((()=>`DominantSpeakersFeature${r?"Internal":""}::Call(id='${e.callId}')`)),this._tsCall=e,this.localDominantList=this._tsCall.dominantSpeakerInfo?.speakerList||[],this._tsCallChangedListener=this._tsCall.changed((()=>{let e=!1;if(this.localDominantList.length!=this._tsCall.dominantSpeakerInfo.speakerList.length)e=!0;else for(let t in this._tsCall.dominantSpeakerInfo.speakerList)if(this._tsCall.dominantSpeakerInfo.speakerList[t]!==this.localDominantList[t]){e=!0;break}e&&(this._logger.info("Dominant speakers list change detected"),this.localDominantList=this._tsCall.dominantSpeakerInfo.speakerList,this._eventEmitter.emit("dominantSpeakersChanged"))}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get dominantSpeakers(){let e=Array();return this._tsCall.dominantSpeakerInfo.speakerList.map((t=>{e.push(kS(t))})),{speakersList:e,timestamp:this._tsCall.dominantSpeakerInfo.timestamp||new Date}}dispose(){this._eventEmitter.removeAllListeners(),this._tsCallChangedListener?.dispose()}}class T_ extends OE.EventEmitter{constructor(e,t){super(),this._options={enableLogOn:!0,enableLogOff:!0,enableLogOnce:!0,enableLogEmit:!0},this._logger=e.createChild("CallingEventEmitter"),t&&(this._options=t)}on(e,t){return!1!==this._options.enableLogOn&&this._logger.info(`event:subscribe to ${e.toString()}`),super.on(e,t)}once(e,t){return!1!==this._options.enableLogOnce&&this._logger.info(`event:subscribe once to ${e.toString()}`),super.once(e,t)}off(e,t){return!1!==this._options.enableLogOff&&this._logger.info(`event:unsubscribed ${e.toString()}`),super.off(e,t)}emit(e,...t){try{return!1!==this._options.enableLogEmit&&this._logger.info(`event:emit ${e.toString()}`),super.emit(e,...t)}catch(t){return this._logger.warn(`Application threw an error while it handled the ${e.toString()} event`),!1}}}function E_(e){let t=e.length>0?e[0]:0;return e.forEach((e=>{e>t&&(t=e)})),t}function b_(e){let t=e.length>0?e[0]:0;return e.forEach((e=>{e<t&&(t=e)})),t}function __(e){let t=0,i=0;return e.forEach((e=>{const n=e-i,r=t+n;i=r-t-n,t=r})),t}const I_=function(){return{audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{},info:{}}};class w_{constructor(e){this._metricsProperties=e,this._originalValues={},this._aggregateValues={},this._events=[],this._currentValues={}}addStats(e,t){const i=this._metricsProperties[e];if(void 0!==i&&!0!==i.skip){if(i.events){const n=i.output_key??e;t!==this._currentValues[n]&&(this._currentValues[n]=t,this._events.push({name:n,value:t,timestamp:Date.now()}))}else{let i=this._originalValues[e];void 0===i&&(i={raw:[],beginTime:Date.now()},this._originalValues[e]=i),i.raw.push(t)}return t}}aggregate(){for(const[e,t]of Object.entries(this._originalValues)){const i=this._metricsProperties[e],n=i.output_key??e;let r=this._aggregateValues[n];void 0===r&&(r={raw:[],timestamp:new Date(t.beginTime)},i.aggregable&&(r.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[n]=r);const s=t.raw;let a=s;if(i.aggregable&&r.aggregation){const e=s.filter((e=>"number"==typeof e&&!isNaN(e)));r.aggregation.count.push(e.length),r.aggregation.sum.push(__(e)),r.aggregation.max.push(E_(e)),r.aggregation.min.push(b_(e)),a=e}i.raw_data_reduction&&a.length>0&&(r.reduced=r.reduced||[],r.reduced.push(a[a.length-1])),a.forEach((e=>r.raw.push(e)))}this._originalValues={}}popAggregates(){const e=this._aggregateValues;return this._aggregateValues={},e}popEvents(){const e=this._events;return this._events=[],e}}class A_{constructor(e,t){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=I_(),this._isActive=!1,t.aggregationInterval<1)throw new Error("invalid aggregationInterval value range");if(t.dataPointsPerAggregation<1)throw new Error("invalid dataPointsPerAggregation value range");this._metricsProperties=t.metricsPropertics,this._logger=e.createChild("TelemetryCollector"),this._eventEmitter=new T_(this._logger,{enableLogEmit:!1}),this._callStateChanged=jT(),this._aggregationInterval=t.aggregationInterval,this._dataPointsPerAggregation=t.dataPointsPerAggregation,this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}onReport(e){this._processMediaStatsReport(e)}onAdded(e){this._isActive!==e&&(this._isActive=e,this._callStateChanged.resolve(e))}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(e){try{const t=[[e.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send,"send"],[e.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive,"recv"],[e.video.send,this._calculators.video.send,this._metricsProperties.video.send,"send"],[e.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive,"recv"],[e.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send,"send"],[e.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive,"recv"],[e.dataChannel,this._calculators.dataChannel,this._metricsProperties.dataChannel,""],[e.transports,this._calculators.transports,this._metricsProperties.transports,""],[e.info,this._calculators.info,this._metricsProperties.info,""]];for(const[i,n,r,s]of t){const t=[],a=Object.keys(n);Object.keys(i).forEach((a=>{const o=i[a],l=o.id;t.push(l),void 0===n[l]&&(n[l]=new w_(r));const c=(e,t)=>n[l].addStats(e,t);if(Object.keys(o).forEach((e=>c(e,o[e]))),"send"==s||"recv"==s){const t=o.transportId;if(void 0!==t){const i=e.transports[t];void 0!==i.rtt&&c("pairRttInMs",i.rttInMs),void 0!==i.availableIncomingBitrate&&"recv"==s&&c("availableBitrate",i.availableIncomingBitrate),void 0!==i.availableOutgoingBitrate&&"send"==s&&c("availableBitrate",i.availableOutgoingBitrate)}}})),a.filter((e=>!t.includes(e))).forEach((e=>{delete n[e]}))}}catch(e){this._logger.error(e)}}async _run(){let e=0;const t=()=>{if(0===e)return;const t={audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{},info:{}},i=[[t.audio.send,this._calculators.audio.send],[t.audio.receive,this._calculators.audio.receive],[t.video.send,this._calculators.video.send],[t.video.receive,this._calculators.video.receive],[t.screenShare.send,this._calculators.screenShare.send],[t.screenShare.receive,this._calculators.screenShare.receive],[t.dataChannel,this._calculators.dataChannel],[t.transports,this._calculators.transports],[t.info,this._calculators.info]];for(const[e,t]of i)for(const[i,n]of Object.entries(t))e[i]={id:i,...n.popAggregates(),events:n.popEvents()};this._eventEmitter.emit("data",t),e=0};let i=1e3*this._aggregationInterval;for(;!this._disposed;){const n=[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){i>0&&await WT((()=>this._callStateChanged.promise),i).catch((e=>{}));const r=Date.now();for(const e of n)for(const[,t]of Object.entries(e))t.aggregate();e++,e===this._dataPointsPerAggregation&&t();const s=Date.now();i=r+1e3*this._aggregationInterval-s}else t(),this._calculators=I_(),await this._callStateChanged.promise.catch((e=>{})),i=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=jT())}t()}}function P_(e){const t=[];return e.sort(((e,t)=>e.id>t.id?1:e.id<t.id?-1:0)),e.forEach((e=>{const i=/^([^.]+)\.?([^.]+)?$/.exec(e.id);if(i&&i[2]){e.id=Z.toString(i[2]);const n=Z.toString(i[1]);if(t.length>0&&t[t.length-1].id===n){const i=t[t.length-1].altLayouts??[];i.push(e),t[t.length-1].altLayouts=i}else t.push(e)}else t.push(e)})),t}class R_{constructor(e,t){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=I_(),this._isActive=!1,t.aggregationInterval<1)throw new le({defaultError:ee.FEATURES.MEDIA_STATS.INVALID_AGGREGATION_INTERVAL_RANGE});if(t.dataPointsPerAggregation<1)throw new le({defaultError:ee.FEATURES.MEDIA_STATS.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._metricsProperties=t.metricsPropertics,this._logger=e.createChild("MediaStatsCollector"),this._eventEmitter=new T_(this._logger,{enableLogEmit:!1}),this._callStateChanged=jT(),this._aggregationInterval=t.aggregationInterval,this._dataPointsPerAggregation=t.dataPointsPerAggregation,this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}onReport(e){this._processMediaStatsReport(e)}onAdded(e){this._isActive!==e&&(this._isActive=e,this._callStateChanged.resolve(e))}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(e){const t={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};try{const i=[[e.audio.send,t.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send],[e.audio.receive,t.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive],[e.video.send,t.video.send,this._calculators.video.send,this._metricsProperties.video.send],[e.video.receive,t.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive],[e.screenShare.send,t.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send],[e.screenShare.receive,t.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive],[e.transports,t.transports,this._calculators.transports,this._metricsProperties.transports]];let n=!1;for(const[e,t,r,s]of i){const i=[],a=Object.keys(r);Object.keys(e).forEach((a=>{const o=e[a];let l=o.id;o.groupId&&(l=`${o.groupId}.${l}`,n=!0);const c={id:l};i.push(l),void 0===r[l]&&(r[l]=new w_(s)),Object.keys(o).forEach((e=>{const t=s[e];if(t&&!0!==t.skip){const i=r[l].addStats(e,o[e]),n=t.output_key??e;c[n]=i}})),t.push(c)})),a.filter((e=>!i.includes(e))).forEach((e=>{delete r[e]}))}n&&(t.video.send=P_(t.video.send),t.screenShare.send=P_(t.screenShare.send))}catch(e){this._logger.error(e)}this._eventEmitter.emit("sampleReported",t)}async _run(){let e=0;const t=()=>{if(0===e)return;const t={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};for(const[e,i]of Object.entries(this._calculators.audio.send))t.audio.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.audio.receive))t.audio.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.video.send))t.video.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.video.receive))t.video.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.screenShare.send))t.screenShare.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.screenShare.receive))t.screenShare.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.transports))t.transports.push({id:e,...i.popAggregates()});t.video.send=P_(t.video.send),t.screenShare.send=P_(t.screenShare.send),this._eventEmitter.emit("summaryReported",t),e=0};let i=1e3*this._aggregationInterval;for(;!this._disposed;){const n=[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){i>0&&await WT((()=>this._callStateChanged.promise),i).catch((e=>{}));const r=Date.now();for(const e of n)for(const[,t]of Object.entries(e))t.aggregate();e++,e===this._dataPointsPerAggregation&&t();const s=Date.now();i=r+1e3*this._aggregationInterval-s}else t(),this._calculators=I_(),await this._callStateChanged.promise.catch((e=>{})),i=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=jT())}t()}}class M_{constructor(){this._eventEmitter=new OE.EventEmitter,this._getCurrentTime=globalThis.performance&&"function"==typeof globalThis.performance.now?()=>globalThis.performance.now():()=>Date.now()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners()}}class D_ extends M_{constructor(e){super(),this._intervalInMs=e,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 k_ extends M_{constructor(e){super(),this._intervalInMs=e,this._callQueue=Promise.resolve(),this._state={isRunning:!1}}start(){if(this._state.isRunning)return;const e={isRunning:!0};this._state=e;const t=async()=>{for(;e.isRunning;){const e=this._getCurrentTime();this._eventEmitter.emit("tick");const t=this._getCurrentTime()-e;t<this._intervalInMs&&await GT(this._intervalInMs-t)}};this._callQueue=this._callQueue.then((()=>t())).catch((()=>{}))}stop(){this._state.isRunning&&(this._state.isRunning=!1)}dispose(){this._state.isRunning=!1,super.dispose()}}class O_{static createTicker(e,t){if("interval"===e)return new D_(t);if("timeout"===e)return new k_(t);throw new Error(`Invalid tickerType: ${e}`)}}class N_{constructor(e,t,i,n,r){this._call=e,this._logger=t,this._dataEventRefCount=0,this._lastFetchTime=0,this._timerDelayRatio=0,this._pendingStats=!1,this._tsCall=this._call.tsCall,this._fetchInterval=i,this._eventEmitter=new T_(this._logger,{enableLogEmit:!1});const s=1e3*i;this._ticker=O_.createTicker(n,s),this._ticker.on("tick",(()=>{const e=Date.now();this._lastFetchTime>0&&(this._timerDelayRatio=(e-this._lastFetchTime)/s),this._lastFetchTime=e,this._dataEventRefCount>0&&!1===this._pendingStats&&(this._pendingStats=!0,this.getStats().then((e=>{e&&this._eventEmitter.emit("data",e)})).catch((e=>{this._logger.error(e)})).finally((()=>{this._pendingStats=!1})))}));const a=()=>{r.includes(this._tsCall.state)?this._start():this._stop()};this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{a()})),a()}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(e,t){this._dataEventRefCount++,this._eventEmitter.on(e,t)}off(e,t){this._dataEventRefCount--,this._eventEmitter.off(e,t)}}class L_ extends N_{constructor(e,t,i){super(e,t.createChild("MediaStatsPoller"),i.mediaStats.fetchInterval,i.mediaStats.pollingMethod,i.mediaStats.activeState),this._memoryInformationV2PendingTask=!1,this._lastCap=new Map,this._lastCpuPressureLevel=-1,this._telemetryConfig=i.telemetry.mediaStatsConfig}_recordSendMaxCapabilities(e,t){if(t)try{const i=JSON.parse(t);Z.each(i,(t=>{const i=t.events,n=this._lastCap.get(e)??0,r=Z.filter(Z.flatten(i),(e=>"req"===e?.eventType&&e?.timestamp>n));r.length>0&&this._lastCap.set(e,Z.last(r).timestamp),r.forEach((t=>{this._call.stats.recordEvent({name:sE.video_max_capabilities,callId:this._call.id,localParticipantId:this._tsCall.participantId,timestamp:t.timestamp,data:{streamType:e,eventType:t.eventType??"",capabilities:t.capabilities??{},isSimulcast:t.isSimulcast??!1}})}))}))}catch(t){this._logger.warn(`Failed to process max capabilities for streamType ${e}: ${t}`)}}async getStats(){const e=await(this._tsCall.getMediaSessionStatsAsync?.());this._telemetryConfig.enableVideoMaxCapCallStats&&e?.extensions&&(this._recordSendMaxCapabilities("Video",e.extensions.Video_send_MaxCapabilities),this._recordSendMaxCapabilities("ScreenSharing",e.extensions.Sharing_send_MaxCapabilities));const t={report:e,delayRatio:this.timerDelayRatio};if(this._telemetryConfig.enableNetworkInformation&&window.navigator.connection){const e=window.navigator.connection,i=Z.get(e,"downlink"),n=Z.get(e,"rtt");void 0===i&&void 0===n||(t.networkInformation={downlink:i,rtt:n})}if(this._telemetryConfig.enableMemoryInformationV1&&window.performance?.memory){const e=window.performance.memory,i=Z.get(e,"jsHeapSizeLimit"),n=Z.get(e,"totalJSHeapSize"),r=Z.get(e,"usedJSHeapSize");void 0===i&&void 0===n&&void 0===r||(t.memoryInformationV1={jsHeapSizeLimit:i,totalJSHeapSize:n,usedJSHeapSize:r})}if(this._telemetryConfig.enableMemoryInformationV2&&window.crossOriginIsolated&&window.performance?.measureUserAgentSpecificMemory&&(this._memoryInformationV2&&(t.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((e=>{let t,i,n;Z.get(e,"breakdown",[]).forEach((e=>{e.bytes>0&&(Z.indexOf(e.types,"DOM")>=0&&(n=void 0===n?e.bytes:n+e.bytes),Z.indexOf(e.types,"Shared")>=0&&(i=void 0===i?e.bytes:i+e.bytes),Z.indexOf(e.types,"JavaScript")>=0&&(t=void 0===t?e.bytes:t+e.bytes))})),this._memoryInformationV2={jsSize:t,sharedSize:i,domSize:n}})).catch((e=>{this._memoryInformationV2=void 0})).finally((()=>{this._memoryInformationV2PendingTask=!1})))),this._telemetryConfig.enableBatteryInformation&&navigator.getBattery)try{const e=await navigator.getBattery();e&&(t.batteryInformation={charging:e.charging,level:e.level})}catch(e){}if(this._telemetryConfig.enablePressureInformation&&window.PressureObserver){if(!this._pressureObserver)try{this._pressureObserver=new window.PressureObserver((e=>{const t=e[e.length-1];this._lastCpuPressureLevel=["nominal","fair","serious","critical"].indexOf(t.state)})),await this._pressureObserver.observe("cpu",{sampleInterval:1e3})}catch(e){this._logger.error(`Failed to observe cpu pressure ${e}`)}-1!==this._lastCpuPressureLevel&&(t.pressureInformation={cpuPressureLevel:this._lastCpuPressureLevel})}if(this._telemetryConfig.enableAudioLeakInformation)try{const i=this._tsCall.isMuted||this._tsCall.isServerMuted;t.callInformation?t.callInformation.audioLeak=0:t.callInformation={audioLeak:0},i&&e?.audio.send.length&&void 0!==e.audio.send[0].audioLevel&&e.audio.send[0].audioLevel>this._telemetryConfig.audioLeakThreshold&&(navigator.mediaDevices.isRemote&&!navigator.mediaDevices.tsCallingChannel?.createdRemoteObject||(t.callInformation.audioLeak=1))}catch(e){}if(this._telemetryConfig.enableVideoLeakInformation)try{t.callInformation?t.callInformation.videoLeak=0:t.callInformation={videoLeak:0},!this._tsCall.isVideoOn&&e?.video.send.length&&(t.callInformation.videoLeak=1)}catch(e){}return t}dispose(){try{this._pressureObserver&&(this._pressureObserver.disconnect(),this._pressureObserver=void 0)}catch(e){this._logger.error(`dispose error: ${e}`)}}}var x_;!function(e){e[e.Running=0]="Running",e[e.Paused=1]="Paused",e[e.Stopped=2]="Stopped"}(x_||(x_={}));class F_{constructor(){this._sinks=[],this._transformers=[],this._state=x_.Running}_setTransformers(e){this._transformers=e.slice()}addSink(e){e.source=this,this._sinks.push(e),e.onAdded(this._state===x_.Running)}removeSink(e){e.source===this&&(Z.pull(this._sinks,e),e.source=void 0,e.onRemoved())}removeAllSinks(){const e=this._sinks;this._sinks=[],e.forEach((e=>{e.source=void 0,e.onRemoved()}))}send(e){if(this._state!==x_.Running)return;let t=e;this._transformers.length&&(t=this._transformers.reduce(((e,t)=>t.transform(e)),e)),this._sinks.forEach((e=>e.onReport(t)))}pause(){this._state===x_.Running&&(this._state=x_.Paused,this._sinks.forEach((e=>e.pause())))}resume(){this._state===x_.Paused&&(this._state=x_.Running,this._sinks.forEach((e=>e.resume())))}stop(){this._state!==x_.Stopped&&this._sinks.forEach((e=>e.stop()))}}class U_ extends F_{constructor(e){super(),this._setTransformers(e)}onReport(e){if(void 0===e.report)return;const t={audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{},info:{}};t.metadata=t.metadata??{},t.metadata.delayRatio=e.delayRatio;const i=[],n={id:"0"};e.networkInformation&&(void 0!==e.networkInformation.downlink&&(n.networkInfoDownlink=e.networkInformation.downlink),void 0!==e.networkInformation.rtt&&(n.networkInfoRttInMs=e.networkInformation.rtt)),e.memoryInformationV1&&(void 0!==e.memoryInformationV1.jsHeapSizeLimit&&(n.jsHeapSizeLimit=e.memoryInformationV1.jsHeapSizeLimit),void 0!==e.memoryInformationV1.totalJSHeapSize&&(n.totalJSHeapSize=e.memoryInformationV1.totalJSHeapSize),void 0!==e.memoryInformationV1.usedJSHeapSize&&(n.usedJSHeapSize=e.memoryInformationV1.usedJSHeapSize)),e.memoryInformationV2&&(void 0!==e.memoryInformationV2.jsSize&&(n.jsSize=e.memoryInformationV2.jsSize),void 0!==e.memoryInformationV2.sharedSize&&(n.sharedSize=e.memoryInformationV2.sharedSize),void 0!==e.memoryInformationV2.domSize&&(n.domSize=e.memoryInformationV2.domSize)),e.batteryInformation&&(void 0!==e.batteryInformation.charging&&(n.batteryCharging=e.batteryInformation.charging?1:0),void 0!==e.batteryInformation.level&&(n.batteryLevel=e.batteryInformation.level)),e.pressureInformation&&void 0!==e.pressureInformation.cpuPressureLevel&&(n.cpuPressureLevel=e.pressureInformation.cpuPressureLevel),e.callInformation&&(void 0!==e.callInformation.audioLeak&&(n.audioLeak=e.callInformation.audioLeak),void 0!==e.callInformation.videoLeak&&(n.videoLeak=e.callInformation.videoLeak)),Z.keys(n).length>1&&i.push(n);const r=[[e.report.audio.send,t.audio.send],[e.report.audio.recv,t.audio.receive],[e.report.video.send,t.video.send],[e.report.video.recv,t.video.receive],[e.report.screenShare.send,t.screenShare.send],[e.report.screenShare.recv,t.screenShare.receive],[e.report.data,t.dataChannel],[e.report.transports,t.transports],[i,t.info]],s=e=>{const t={};return Object.entries(e).forEach((e=>{const i=e[0],n=e[1];"altLayouts"!==i&&null!=n&&(t[i]=n)})),t};r.forEach((e=>{const t=e[0];if(void 0!==t){const i=e[1];t.forEach((e=>{const t=Z.toString(e.id);i[t]=s(e),void 0!==e.altLayouts&&e.altLayouts.forEach((e=>{const n=e.id,r=s(e);r.groupId=t,i[n]=r}))}))}})),this.send(t)}}class B_ extends F_{constructor(e){super(),this._setTransformers(e)}onAdded(e){}onRemoved(){}onReport(e){this.send(e)}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}}class V_{constructor(e){this._tsCall=e,this._activeParticipantMris=new Set,this._sourceIdToParticipantInfo=new Map,this._listenerHandles=[],this._config=vy(),this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._activeParticipantMris.has(e.id)&&this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._activeParticipantMris.delete(e.id),this._removeMapping(e)}))),this._tsCall.participants?.forEach((e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))}_updateMapping(e){const t=e.id,i=[],n=this._config.calling.composedStreamBotIds;e.endpoints?.endpointDetails?.forEach((e=>{e.mediaStreams?.forEach((r=>{i.push(r.sourceId),this._sourceIdToParticipantInfo.set(r.sourceId,{mri:t,participantId:e.participantId,isComposedStream:n.includes(t)})}))}))}_removeMapping(e){e.endpoints?.endpointDetails?.forEach((e=>{e.mediaStreams?.forEach((e=>{this._sourceIdToParticipantInfo.delete(e.sourceId)}))}))}findParticipantInfo(e){let t=this._sourceIdToParticipantInfo.get(e);if(void 0===t&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const e=this._tsCall.participants[0],i=e.endpoints?.endpointDetails[0];t={mri:e.id,participantId:i?.participantId??"",isComposedStream:!1}}return t}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._sourceIdToParticipantInfo.clear(),this._listenerHandles.forEach((e=>e.dispose()))}}class H_{constructor(e,t,i,n){this._tsCall=e,this._call=t,this._telemetryLogManager=i,this._config=n,this._participantMappingManager=new V_(this._tsCall)}dispose(){this._participantMappingManager.dispose()}log(e){const t=this._config.telemetry.mediaStatsConfig;[{type:"audio",direction:"send",value:e.audio.send},{type:"audio",direction:"recv",value:e.audio.receive},{type:"video",direction:"send",value:e.video.send},{type:"video",direction:"recv",value:e.video.receive},{type:"screen",direction:"send",value:e.screenShare.send},{type:"screen",direction:"recv",value:e.screenShare.receive},{type:"data",direction:"",value:e.dataChannel},{type:"transport",direction:"",value:e.transports},{type:"info",direction:"",value:e.info}].forEach((e=>{const i=Object.values(e.value);i.forEach((n=>{const r={id:n.id},s={id:n.id};Object.keys(n).forEach((e=>{const i=e;if("id"===e)return;if("events"===e){const e=n[i];return void(e.length>0&&(r.events=JSON.stringify(e)))}const a=n[i];if(t.dataToSend.raw){const e={};a?.timestamp&&(e.timestamp=a?.timestamp),t.dataToSend.raw&&(e.raw=a?.raw),s[i]=e}const o={};void 0!==a.aggregation?(a.timestamp&&(o.timestamp=a.timestamp),t.dataToSend.min&&(o.min=a.aggregation.min),t.dataToSend.max&&(o.max=a.aggregation.max),t.dataToSend.sum&&(o.sum=a.aggregation.sum),t.dataToSend.count&&(o.count=a.aggregation.count)):(a.timestamp&&(o.timestamp=a.timestamp),a.reduced?o.raw=a.reduced:a.raw&&(o.raw=a.raw)),r[i]=o}));let a="",o="";if(("video"===e.type||"screen"===e.type)&&"recv"===e.direction){const e=n;if(void 0!==e.streamId&&e.streamId.raw?.length){const t=e.streamId.raw[0],i=this._participantMappingManager.findParticipantInfo(t);a=i?.participantId??"",o=i?.isComposedStream?"ComposedVideoStream":"RemoteVideoStream"}}if(Object.keys(r).length>1){const t={mediaType:e.type,mediaDirection:e.direction,stats:r,callId:this._tsCall.callId,remoteParticipantId:a,localParticipantId:this._tsCall.participantId,videoStreamKind:o,streamCount:i.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(t)}if(t.dataToSend.raw&&Object.keys(s).length>1){const t={mediaType:e.type,mediaDirection:e.direction,stats:s,callId:this._tsCall.callId,remoteParticipantId:a,localParticipantId:this._tsCall.participantId,videoStreamKind:o,streamCount:i.length};this._sendMidCallRawMediaStats(t)}}))}))}_sendMidCallNewMediaStats(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_mid_call_new_media_stats,tenant:xv,properties:e})}_sendMidCallRawMediaStats(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_mid_call_raw_media_stats,tenant:xv,properties:e})}}function $_(e){return{transform:t=>([[t.audio.send,e.audio.send],[t.audio.receive,e.audio.receive],[t.video.send,e.video.send],[t.video.receive,e.video.receive],[t.screenShare.send,e.screenShare.send],[t.screenShare.receive,e.screenShare.receive],[t.dataChannel,e.dataChannel],[t.transports,e.transports],[t.info,e.info]].forEach((e=>{const t=e[0],i=e[1];Z.forEach(i,((e,i)=>{!0!==e.disabled&&Z.forEach(t,(t=>{let n=t[e.source];void 0!==n&&(void 0!==e.multiplier&&"number"==typeof n&&(n*=e.multiplier),e.integer&&(n=Z.toInteger(n)),t[i]=n)}))}))})),t)}}function j_(e){const t=["audio.send","audio.receive","video.send","video.receive","screenShare.send","screenShare.receive","dataChannel","transports","info"];return{transform:i=>(Z.forEach(t,(t=>{const n=Z.get(i,t),r=Z.get(e,t,[]);Z.forEach(n,(e=>{r.forEach((t=>{"id"!==t&&delete e[t]}))}))})),i)}}const G_={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:{}},q_={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:{}},z_={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:G_,receive:q_},screenShare:{send:G_,receive:q_},dataChannel:{incomingBitrate:{aggregable:!0},outgoingBitrate:{aggregable:!0},messagesSentPerSecond:{aggregable:!0},messagesReceivedPerSecond:{aggregable:!0}},transports:{rttInMs:{aggregable:!0},availableIncomingBitrate:{aggregable:!0},availableOutgoingBitrate:{aggregable:!0}},info:{}},W_={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},fsOvershoot:{aggregable:!0},fpsOvershoot:{aggregable:!0},brOvershoot:{aggregable:!0}},K_={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}},J_={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:W_,receive:K_},screenShare:{send:W_,receive:K_},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}}},Y_={multiplier:1e3,integer:!0,source:"jitter"},Q_={multiplier:1e3,integer:!0,source:"rtt"},Z_={integer:!0,source:"jitterBufferMs"},X_={jitterInMs:Y_,rttInMs:Q_,fsOvershoot:{integer:!0,source:"isFsOvershooting"},fpsOvershoot:{integer:!0,source:"isFpsOvershooting"},brOvershoot:{integer:!0,source:"isBrOvershooting"}},eI={jitterInMs:Y_,rttInMs:Q_,jitterBufferDelayInMs:Z_,streamId:{source:"msi"},longestFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"longestFreezeDuration"},totalFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"totalFreezeDuration"}},tI={audio:{send:{jitterInMs:Y_,rttInMs:Q_,audioInputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}},receive:{jitterInMs:Y_,rttInMs:Q_,jitterBufferDelayInMs:Z_,audioOutputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}}},video:{send:X_,receive:eI},screenShare:{send:X_,receive:eI},dataChannel:{incomingBitrate:{source:"recvBitrate"},outgoingBitrate:{source:"sendBitrate"}},transports:{rttInMs:Q_},info:{networkInfoDownlink:{multiplier:1e3,integer:!0,source:"networkInfoDownlink"}}};class iI{constructor(e,t,i,n){this._tsCall=e,this._call=t,this._logger=i,this._disposed=!1;const r=vy();this._config=r.mediaStats,this._statsPoller=new L_(t,this._logger,r);const s=[$_(Z.merge(Z.cloneDeep(tI),this._config.transformMetrics))];this._config.timerThrottlingFilter.enabled&&s.push(function(e,t){return{transform:i=>{const n=i.metadata?.delayRatio,r=e>0&&void 0!==n&&n>e;return Z.forEach(t,((e,t)=>{const n=Z.get(i,t);Z.forEach(n,(t=>{Z.forEach(e,((e,i)=>{if(r)delete t[i];else{const n=t[i];(void 0!==e.max&&n>e.max||void 0!==e.min&&n<e.min||Z.isNaN(n))&&delete t[i]}}))}))})),i}}}(this._config.timerThrottlingFilter.delayRatio,this._config.timerThrottlingFilter.filterRange)),this._mediaStatsSourceNode=new U_(s);const a=this._config.activeState;this._isCallActive=a.includes(this._tsCall.state),this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{const e=a.includes(this._tsCall.state);this._isCallActive!==e&&(this._isCallActive=e,e?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause())}));const o=this._config.blockMetrics;if(Object.keys(o).length>0){const e=new B_([{transform:e=>Z.cloneDeep(e)},j_(o)]);this._mediaStatsSourceNode.addSink(e),this._collectorsSourceNode=e}else this._collectorsSourceNode=this._mediaStatsSourceNode;const l=r.telemetry.mediaStatsConfig;if(l.enabled){const e=new H_(this._tsCall,this._call,n,r),t=Z.merge(Z.cloneDeep(z_),J_,l.metricsProperties),i=new A_(this._logger,{aggregationInterval:l.aggregationInterval,dataPointsPerAggregation:l.dataPointsPerAggregation,metricsPropertics:t});i.on("data",(t=>e.log(t))),this._mediaStatsSourceNode.addSink(i)}this._isCallActive?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause(),this._dataEventListener=e=>{this._mediaStatsSourceNode.onReport(e)},this._statsPoller.on("data",this._dataEventListener)}createCollector(e){if(this._disposed)throw new le({defaultError:ee.FEATURES.MEDIA_STATS.DISPOSED});const t=this._config,i=new R_(this._logger,{aggregationInterval:e?.aggregationInterval??t.aggregationInterval,dataPointsPerAggregation:e?.dataPointsPerAggregation??t.dataPointsPerAggregation,metricsPropertics:z_});return this._collectorsSourceNode.addSink(i),i}dispose(){this._disposed||(this._disposed=!0,this._statsPoller.off("data",this._dataEventListener),this._statsPoller.dispose(),this._mediaStatsSourceNode.stop(),this._callStateChangedHandle.dispose())}}class nI extends ZE{constructor(e){super(e)}get name(){return this._sendFeatureUsage("name",oE.getter),"MediaStats"}createCollector(e){this._sendFeatureUsage("createCollector",oE.attempt);const t=this._statsManager.createCollector(e);return this._sendFeatureUsage("creaetCollector",oE.success),t}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._statsManager=new iI(e.tsCall,this._call,this._logger,this._telemetryLogManager),this._sendFeatureUsage("initialize",oE.initialize)}_sendFeatureUsage(e,t){hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"MediaStats",featureType:"Call",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._statsManager.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}var rI,sI;!function(e){e[e.None=0]="None",e[e.Started=1]="Started",e[e.Paused=2]="Paused",e[e.Ended=3]="Ended"}(rI||(rI={}));class aI{constructor(e){this._eventEmitter=e,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((e=>{throw this._logger.error("Consent failure to set publish state for user"),bb(e,ee.FEATURES.RECORDING.RECORDING_CONSENT_FAILURE)}))),this._updateIsCallRecorded=e=>this._isRecordingActive!==e&&(this._isRecordingActive=e,this._logger.info(`Updating isCallRecorded to ${e}`),!0),this._handleRecordingBotAdded=e=>{const t=()=>{let t,i=!1,n=!1;if(this._hasRecordingState(e)){if(this._recordingBots.has(e.id)){let i=this._getRecordingBotEndpoint(e);if(t=this._recordingBots.get(e.id),i&&t){t.endpoint=i;let e=i.userId?this._recordingInitiatorMap.get(i.userId):void 0;n=t.recordingInfo?.update(i,e)??!1}}else t=this._getRecordingBotInfo(e),t&&(this._logger.info("Adding recording bot"),this._recordingBots.set(e.id,t),i=!0);this._sendEvents(n?[t]:void 0,i?[t]:void 0,void 0,this._updateIsCallRecorded(this._isRecordingEnabled()))}};t(),this._recordingBotChangedSubs.set(e,e.changed(t))},this._handleRecordingBotRemoved=e=>{let t=this._recordingBots.get(e.id);this._recordingBots.delete(e.id),this._recordingBotChangedSubs.get(e)?.dispose(),this._recordingBotChangedSubs.delete(e),this._logger.info(`Updating recordingState to ${t?.endpoint?.state}`),t?.recordingInfo?.dispose(),this._sendEvents([t],void 0,[t],this._updateIsCallRecorded(this._isRecordingEnabled()))},this._sendEvents=(e,t,i,n)=>{e&&e.forEach((e=>e?.recordingInfo?.sendRecordingStateChanged()));let r=!!t&&t.length>0,s=!!i&&i.length>0;(r||s)&&this._eventEmitter.emit("recordingsUpdated",{added:this._getRecordingInfos(t),removed:this._getRecordingInfos(i)}),n&&this._eventEmitter.emit("isRecordingActiveChanged")},this._hasRecordingState=e=>e?.endpoints?.endpointDetails?.some((e=>!!e?.endpointMetadata?.__platform?.recording?.compliance?.state||!!e?.endpointMetadata?.processingModes?.recording?.state))??!1,this._getRecordingInfos=e=>{if(e)return e.map((e=>e?.recordingInfo)).filter((e=>!!e))},this._isRecordingEnabled=()=>{let e=!1;try{this._recordingBots.forEach((t=>{e||(e="Active"===t?.endpoint?.state)}))}catch(e){this._logger.info("Unable to read recording state: ",e)}return e},this._getRecordingInfoImpl=e=>{if(null==e)return;if("Active"!==e.state&&"Inactive"!==e.state)return;let t;return void 0!==e.userId&&(t=this._recordingInitiatorMap.get(e.userId)),new oI(e.state,this._eventEmitter,t)},this._getRecordingBotInfo=e=>{let t=this._getRecordingBotEndpoint(e);return t?{endpoint:t,recordingInfo:this._getRecordingInfoImpl(t)}:void 0},this._getRecordingBotEndpoint=e=>{let t=e.endpoints?.endpointDetails.map((e=>{let t=e?.endpointMetadata?.__platform?.recording?.compliance?.state,i=e?.endpointMetadata?.__platform?.recording?.compliance?.userId,n=e?.endpointMetadata?.processingModes?.recording?.state,r=e?.endpointMetadata?.processingModes?.recording?.userId;if(t||n)return{state:t??n,userId:i??r}})).filter((e=>null!=e));if(t&&0!=t.length)return t.length>1&&this._logger.log(`Unexpected: multiple recording endpoints: ${t?.map((e=>e?.state??"undefined")).join(", ")}`),t[0]}}get isRecordingActive(){return this._isRecordingActive}get recordings(){return Array.from(this._recordingBots.values()).map((e=>e?.recordingInfo)).filter((e=>!!e))}initialize(e,t,i,n){this._logger=t.createChild((()=>`RecordingFeature::Call(id='${e.callId}', state='${e.state}')`)),this._callInfo=i,this._call=n,e.on("callStateChanged",(async()=>{3===e.state&&this._initInitiatorMap(e)})),e.participants.forEach((e=>{OS(e.id)&&this._handleRecordingBotAdded(e)})),e.on("participantAdded",(async e=>{OS(e.id)?this._handleRecordingBotAdded(e):void 0===e||this._recordingInitiatorMap.has(e.id)||this._recordingInitiatorMap.set(e.id,e.displayName)})),e.on("participantRemoved",(async e=>{OS(e.id)?this._handleRecordingBotRemoved(e):void 0!==e&&this._recordingInitiatorMap.has(e.id)&&this._recordingInitiatorMap.delete(e.id)})),e.on("participantUpdated",(async e=>{void 0!==e&&this._recordingInitiatorMap.has(e.id)&&this._recordingInitiatorMap.set(e.id,e.displayName)}))}get isTeamsConsentRequired(){return this._call.explicitConsentStateImp.isConsentRequiredInCall()}dispose(){let e=this._updateIsCallRecorded(!1),t=Array.from(this._recordingBots.values());t.forEach((e=>e?.recordingInfo?.dispose())),this._sendEvents(void 0,void 0,t,e)}_initInitiatorMap(e){const{participants:t}=e;[...t].forEach((e=>{OS(e.id)||this._recordingInitiatorMap.set(e.id,e.displayName)}))}}class oI{constructor(e,t,i){this.state=this.getRecordingState(e),this._eventEmitter=t,this.displayName=i}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}update(e,t){if(null==e)return!1;let i=this.getRecordingState(e.state);return i!=this.state&&(this.state=i,void 0!==t&&(this.displayName=t),!0)}dispose(){this.state=rI.Ended}sendRecordingStateChanged(){this._eventEmitter.emit("recordingStateChanged")}getRecordingState(e){let t=rI.None;switch(e?.toLocaleLowerCase()){case"active":t=rI.Started;break;case"inactive":t=rI.Paused;break;default:t=rI.None}return t}}!function(e){e[e.None=0]="None",e[e.Started=1]="Started",e[e.Ended=2]="Ended"}(sI||(sI={}));const lI="active";class cI{constructor(e){this._eventEmitter=e,this._localRecordingInitiators=new Map,this._sendEvents=(e,t,i)=>{let n=!!e&&e.length>0,r=!!t&&t.length>0;(n||r)&&this._eventEmitter.emit("localRecordingsUpdated",{added:e,removed:t}),i&&this._eventEmitter.emit("isLocalRecordingActiveChanged")},this._isEnabled=vy().calling.localRecording.enabled,this._supportedConversationTypes=vy().calling.localRecording.supportedConversationTypes}get isRecordingActive(){return this._localRecordingInitiators.size>0}get recordings(){return Array.from(this._localRecordingInitiators.values())}initialize(e,t,i){if(this._logger=i.createChild((()=>`LocalRecordingFeature::Call(id='${e.callId}', state='${e.state}')`)),!this._isEnabled){const e="Local Recording feature is is disabled",t=new le({defaultError:ee.FEATURES.LOCAL_RECORDING.DISABLED});throw this._logger.error(e),t}e.on("callStateChanged",(async()=>{if(3===e.state){if(!this._supportedConversationTypes.includes(e.conversationType)){const e="Local Recording feature is only available in meetings",t=new le({defaultError:ee.FEATURES.LOCAL_RECORDING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(e),t}this.initLocalRecordingStatus(e)}})),e.on("participantUpdated",(t=>this._onParticipantUpdatedEvent(e,t,t.endpoints?.endpointDetails)))}dispose(){let e=this._localRecordingInitiators.size>0,t=Array.from(this._localRecordingInitiators.values());t.forEach((e=>e?.dispose())),e&&(e=0==this._localRecordingInitiators.size),this._sendEvents(void 0,t,e)}hasOngoingLocalRecording(e){return e?.some((e=>(e.propertyBag?.localRecording?.value?.state||"")===lI))||!1}initLocalRecordingStatus(e){const{participants:t}=e,i=[...t];this._localRecordingInitiators=new Map(i.filter((e=>this.hasOngoingLocalRecording(e.endpoints?.endpointDetails))).map((e=>[e.id,this._getLocalRecordingInfo(e)])))}_onParticipantUpdatedEvent(e,t,i){t?OS(t.id)||(this.hasOngoingLocalRecording(i)?this._tryAddLocalRecordingInitiator(e,t):this._tryRemoveLocalRecordingInitiator(e,t)):this._logger.error(`Empty participant, skip update event processing. CallId: ${e.callId}`)}_tryAddLocalRecordingInitiator(e,t){const{callId:i}=e;if(!this._localRecordingInitiators.has(t.id)){this._logger.info(`Add local recording participant: ${t.id}, callId: ${i}`);let e=this._getLocalRecordingInfo(t);this._localRecordingInitiators.set(t.id,e),this._sendEvents([e],void 0,1==this._localRecordingInitiators.size)}}_tryRemoveLocalRecordingInitiator(e,t){const{callId:i}=e;if(this._localRecordingInitiators.has(t.id)){this._logger.info(`Remove local recording participant: ${t.id}, callId: ${i}`);let e=this._localRecordingInitiators.get(t.id);e.update("inactive"),this._localRecordingInitiators.delete(t.id),this._sendEvents(void 0,[e],0==this._localRecordingInitiators.size)}}_getLocalRecordingInfo(e){let t=e.displayName;return new dI(lI,t)}}class dI{constructor(e,t){this.state=this.getRecordingState(e),this.displayName=t}update(e){let t=this.getRecordingState(e);return t!=this.state&&(this.state=t,!0)}dispose(){this.state=sI.Ended}getRecordingState(e){let t=sI.None;switch(e?.toLocaleLowerCase()){case"active":t=sI.Started;break;case"inactive":t=sI.Ended;break;default:t=sI.None}return t}}class uI{constructor(e){this._eventEmitter=e,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((e=>{throw this._logger.error("Consent failure to set publish state for user"),bb(e,ee.FEATURES.TRANSCRIPTION.TRANSCRIPTION_CONSENT_FAILURE)}))),this._updateIsTranscriptionActive=e=>{this._isTranscriptionActive!==e&&(this._isTranscriptionActive=e,this._logger.info(`Updating isTranscriptionActive to ${e}`),this._eventEmitter.emit("isTranscriptionActiveChanged"))},this._isCallingApplication=e=>OS(e.id),this._handleBotRemoved=e=>{this._botChangedSubs.get(e)?.dispose(),this._botChangedSubs.delete(e),this._checkIfAbotIsTranscribing()},this._handleBotAdded=e=>{this._botChangedSubs.set(e,e.changed(this._checkIfAbotIsTranscribing)),this._checkIfAbotIsTranscribing()},this._checkIfAbotIsTranscribing=()=>{try{Array.from(this._botChangedSubs.keys()).find((e=>e.endpoints?.endpointDetails?.find((e=>"Active"===e?.endpointMetadata?.processingModes?.realTimeTranscript?.state))))?this._updateIsTranscriptionActive(!0):this._updateIsTranscriptionActive(!1)}catch(e){this._logger.warn("Unable to read transcription state: ",e)}}}get isTranscriptionActive(){return this._isTranscriptionActive}initialize(e,t,i,n){this._logger=t.createChild((()=>`TranscriptionFeature::Call(id='${e.callId}', state='${e.state}')`)),this._callInfo=i,this._call=n,e.on("participantAdded",(e=>{this._isCallingApplication(e)&&this._handleBotAdded(e)})),e.participants.forEach((e=>{this._isCallingApplication(e)&&this._handleBotAdded(e)})),e.on("participantRemoved",(e=>{this._isCallingApplication(e)&&this._handleBotRemoved(e)}))}get isTeamsConsentRequired(){return this._call.explicitConsentStateImp.isConsentRequiredInCall()}dispose(){this._updateIsTranscriptionActive(!1),this._botChangedSubs.forEach(((e,t)=>e.dispose())),this._botChangedSubs.clear()}}class hI{get state(){return this._state}get error(){return this._error}constructor(e,t,i=!0){return this._eventEmitter=new OE.EventEmitter,this._lastTsTransferState=0,this._getTransferEndReason=(e,t=0)=>{let i=t,n=0,r=e||"Unknown";this._tsCall&&(i=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo.callControllerCode||t,n=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo?.callControllerSubCode||0,r=mb(this._tsCall.terminatedReason));const s={code:i,subCode:n};return this._logger[0===i?"info":"error"](`Transfer end reason=${r}, code=${i}, subCode=${n}`),s},this._state="None",this._logger=t.createChild((()=>"Transfer")),this._logger.log("created"),this._tsCall=e,i?4!==e.state?(this._logger.error("Transfer end reason= call must be on hold before transfer"),this._error={code:412},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:412},void this.setTransferState(4))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}setTransferState(e){let t,i;const n={0:"None",1:"Transferring",2:"Transferring",3:"Transferred",4:"Failed"};n[e]?(t=n[e],"Failed"===t&&(i=this._getTransferEndReason(),this._error=i),this._logger.log(`Mapped ts transfer state:[${e}] to [${t}]`),this._setTransferState(t)):this._logger.warn(`unable to map tsCall state=[${e}] to transfer state`)}_setTransferState(e){e!==this._state&&(this._logger.log(`transfer state changed [${this._state}]=>[${this.state}]`),this._state=e,this._eventEmitter.emit("stateChanged"))}}class gI{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||(this.instance=new gI),this.instance}deleteNetworkInfo(e){delete this.CAUSE_ID_TO_NETWORK_INFO[e]}ifCauseIdExistsRemoveNetworkInfo(e){return this.CAUSE_ID_TO_NETWORK_INFO[e]&&0===this.CAUSE_ID_TO_NETWORK_INFO[e].length?!!this.getRemoveCauseIdToNetworkInfo(e):!!this.CAUSE_ID_TO_NETWORK_INFO[e]}getRemoveCauseIdToNetworkInfo(e){if(!vy().telemetry.sendNetworkInfo)return;const t=this.CAUSE_ID_TO_NETWORK_INFO[e];return t&&this.deleteNetworkInfo(e),t}setCauseIdToNetworkInfo(e,t){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),t?this.CAUSE_ID_TO_NETWORK_INFO[e]?this.CAUSE_ID_TO_NETWORK_INFO[e].push({url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[e]=[{url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[e]=[]}}gI.instance=null;const pI=gI.getInstance();var mI=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class fI{constructor(e){this._eventEmitter=e,this._autoAccept=vy().calling.transfer.autoAccept}initialize(e,t,i,n){this._logger=n.createChild((()=>`TransferFeature::Call(id='${e.callId}', state='${e.state}')`)),this._telemetryLogManager=i,this._tsCall=e,this._callAgent=t,e.on("transferRequested",(async e=>{try{const t=this.getTransferRequestPayload(e);if(this._autoAccept){const e=await t.accept();this._eventEmitter.emit("transferAccepted",{targetCall:e})}}catch(e){this._logger.error(`Failed to handle transferRequested event: ${e?.message??"unknown error"}`)}}))}transfer(e,t){let i="safe";if(e.targetCallId?i="consultative":e.targetParticipantVoicemail&&(i="voicemail"),this._sendFeatureUsage(i,oE.attempt,t),!this.isTransferable(this._tsCall))throw this._sendFeatureUsage(i,oE.failure,t),new le({defaultError:ee.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});const n=X.generateCauseId();pI.setCauseIdToNetworkInfo(n);try{let r;switch(i){case"safe":return r=this.transferToParticipant(e.targetParticipant,n,t),this._sendFeatureUsage(i,oE.success,t,pI.getRemoveCauseIdToNetworkInfo(n)),r;case"consultative":return r=this.transferToCall(e.targetCallId,n,t),this._sendFeatureUsage(i,oE.success,t,pI.getRemoveCauseIdToNetworkInfo(n)),r;case"voicemail":return r=this.transferToParticipantVoicemail(e.targetParticipantVoicemail,t),this._sendFeatureUsage(i,oE.success,t),r}}catch(e){if(this._sendFeatureUsage(i,oE.failure,t,pI.getRemoveCauseIdToNetworkInfo(n)),e instanceof le)throw e}throw this._sendFeatureUsage(i,oE.failure,t),new le({defaultError:ee.FEATURES.TRANSFER.TARGET_NOT_RECOGNIZED})}getTransferRequestPayload(e){const t=kS(e.transferContext.targetMri);if("communicationUser"===t.kind||"phoneNumber"===t.kind||"microsoftTeamsUser"===t.kind||"unknown"===t.kind||"microsoftTeamsApp"===t.kind){let t=!1;return{accept:async()=>{let i;try{if(i=await this._callAgent.createTransferTargetCall(e.transferContext),t)return this._logger.info("Transfer accept was called when transfer action is already in progress."),i;t=!0;const n={threadId:"",messageId:void 0,transferContext:e.transferContext,mediaPeerType:0};i.startCallInternal(void 0,!1,void 0,n).catch((i=>{t=!1,e.onCompleted(7),this._logger.error("Transfer to target failed at call start")}));const r=()=>{if(t)switch(i.state){case"Connected":t=!1,e.onCompleted(1),this._logger.info("Transfer Completed"),i.off("stateChanged",(()=>{}));break;case"Disconnected":t=!1,e.onCompleted(7),this._logger.info(`Transfer call disconnected. \n code = ${i.callEndReason?.code} \n subcode = ${i.callEndReason?.subCode} \n message = ${i.callEndReason?.message} \n result categories = ${i.callEndReason?.resultCategories}`),i.off("stateChanged",(()=>{}))}};return i.on("stateChanged",r),i}catch(i){throw t=!1,e.onCompleted(7),this._logger.error("Transfer to target failed at call create"),new le({defaultError:ee.FEATURES.TRANSFER.TRANSFER_TO_TARGET_FAILED,originalError:i})}}}}throw new le({defaultError:ee.FEATURES.TRANSFER.INVALID_TARGET_TYPE,defaultErrorMessageArgs:[t]})}isTransferable(e){return 1===e.callType||e.participants.filter((e=>!OS(e.id))).length<=2}transferToParticipant(e,t,i){const n=DS(e);let r;return i&&(r={disableForwardingAndUnanswered:i.disableForwardingAndUnanswered,clientTransferContext:{customContext:$y(i)}}),4===this._tsCall.state&&this._tsCall.callSafeTransfer(n,t,r),new hI(this._tsCall,this._logger)}transferToCall(e,t,i){const n=this._callAgent.getCallByCallId(e);if(n&&!this.isTransferable(n))throw new le({defaultError:ee.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});let r;return i&&(r={clientTransferContext:{customContext:$y(i)}}),n&&4===this._tsCall.state&&this._tsCall.callConsultativeTransfer(n,t,void 0,r),new hI(this._tsCall,this._logger,!!n)}transferToParticipantVoicemail(e,t){const i=DS(e);if(4===this._tsCall.state){const e={transferTargetMri:i};this._tsCall.transferCallToVoicemail(e)}return new hI(this._tsCall,this._logger)}_sendFeatureUsage(e,t,i,n){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:{transferConstraint:{userToUserPresent:!!i?.customContext?.userToUser,xHeadersPresent:!!i?.customContext?.xHeaders&&i.customContext.xHeaders.length>0,type:"safe"===e?"participant":"consultative"===e?"call":"voicemail"}},networkInfo:n||[]},this._telemetryLogManager,this._logger)}dispose(){}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([ge(QE.Transfer),mI("design:type",Function),mI("design:paramtypes",[Object,Object]),mI("design:returntype",Object)],fI.prototype,"transfer",null);class vI{constructor(e,t,i,n){this._name=e,this._id=t,this._deviceType=i,this._deviceManager=n}get name(){return this._name}setName(e){this._name=e}get id(){return this._id}setId(e){this._id=e}get deviceType(){return this._deviceType}setDeviceType(e){this._deviceType=e}get deviceManager(){return this._deviceManager}}function SI(e,t){Reflect.defineMetadata(ce,t,e)}function yI(e){if(this._capacity=TI(e),this._length=0,this._front=0,CI(e)){for(var t=e.length,i=0;i<t;++i)this[i]=e[i];this._length=t}}yI.prototype.toArray=function(){for(var e=this._length,t=new Array(e),i=this._front,n=this._capacity,r=0;r<e;++r)t[r]=this[i+r&n-1];return t},yI.prototype.push=function(e){var t=arguments.length,i=this._length;if(t>1){var n=this._capacity;if(i+t>n){for(var r=0;r<t;++r)this._checkCapacity(i+1),this[s=this._front+i&this._capacity-1]=arguments[r],i++,this._length=i;return i}var s=this._front;for(r=0;r<t;++r)this[s+i&n-1]=arguments[r],s++;return this._length=i+t,i+t}return 0===t?i:(this._checkCapacity(i+1),this[r=this._front+i&this._capacity-1]=e,this._length=i+1,i+1)},yI.prototype.pop=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1,i=this[t];return this[t]=void 0,this._length=e-1,i}},yI.prototype.shift=function(){var e=this._length;if(0!==e){var t=this._front,i=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,i}},yI.prototype.unshift=function(e){var t=this._length,i=arguments.length;if(i>1){if(t+i>(r=this._capacity)){for(var n=i-1;n>=0;n--){this._checkCapacity(t+1);var r=this._capacity;this[a=(this._front-1&r-1^r)-r]=arguments[n],t++,this._length=t,this._front=a}return t}var s=this._front;for(n=i-1;n>=0;n--){var a;this[a=(s-1&r-1^r)-r]=arguments[n],s=a}return this._front=s,this._length=t+i,t+i}return 0===i?t:(this._checkCapacity(t+1),r=this._capacity,this[n=(this._front-1&r-1^r)-r]=e,this._length=t+1,this._front=n,t+1)},yI.prototype.peekBack=function(){var e=this._length;if(0!==e)return this[this._front+e-1&this._capacity-1]},yI.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},yI.prototype.get=function(e){var t=e;if(t===(0|t)){var i=this._length;if(t<0&&(t+=i),!(t<0||t>=i))return this[this._front+t&this._capacity-1]}},yI.prototype.isEmpty=function(){return 0===this._length},yI.prototype.clear=function(){for(var e=this._length,t=this._front,i=this._capacity,n=0;n<e;++n)this[t+n&i-1]=void 0;this._length=0,this._front=0},yI.prototype.toString=function(){return this.toArray().toString()},yI.prototype.valueOf=yI.prototype.toString,yI.prototype.removeFront=yI.prototype.shift,yI.prototype.removeBack=yI.prototype.pop,yI.prototype.insertFront=yI.prototype.unshift,yI.prototype.insertBack=yI.prototype.push,yI.prototype.enqueue=yI.prototype.push,yI.prototype.dequeue=yI.prototype.shift,yI.prototype.toJSON=yI.prototype.toArray,Object.defineProperty(yI.prototype,"length",{get:function(){return this._length},set:function(){throw new RangeError("")}}),yI.prototype._checkCapacity=function(e){this._capacity<e&&this._resizeTo(TI(1.5*this._capacity+16))},yI.prototype._resizeTo=function(e){var t=this._capacity;this._capacity=e;var i=this._front,n=this._length;i+n>t&&function(e,t,i,n,r){for(var s=0;s<r;++s)i[s+n]=e[s+0],e[s+0]=void 0}(this,0,this,t,i+n&t-1)};var CI=Array.isArray;function TI(e){if("number"!=typeof e){if(!CI(e))return 16;e=e.length}return function(e){return e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,1+((e|=e>>8)|e>>16)}(Math.min(Math.max(16,e),1073741824))}var EI,bI=yI;class _I{static overrideDefaultLogDump(){if(_I.logDump.isEmpty())_I.logDump=new bI(vy()?.debugInfo?.maxLogDumpLength);else{let e=new bI(vy()?.debugInfo?.maxLogDumpLength);for(;_I.logDump.length>0;){const t=_I.logDump.shift();t&&e.push(t)}_I.logDump=e}}constructor(e,t=[],i=_I.defaultLogRedirect){this._azureLogger=e,this._namespace=t,this._logRedirectCallback=i}createChild(e){return new _I(this._azureLogger,[...this._namespace,"string"==typeof e?()=>e:e])}createFnLogger(e,t,...i){return this.createChild(this.getPrefix(e,t)+i.join(""))}log(...e){const t=this.getMessage(e);this._azureLogger.verbose(t),this._logRedirectCallback(`log:${t}`)}debug(...e){const t=this.getMessage(e);this._azureLogger.verbose(t),this._logRedirectCallback(`debug:${t}`)}info(...e){const t=this.getMessage(e);this._azureLogger.info(t),this._logRedirectCallback(`info:${t}`)}warn(...e){const t=this.getMessage(e);this._azureLogger.warning(t),this._logRedirectCallback(`warn:${t}`)}error(...e){const t=this.getMessage(e);this._azureLogger.error(this.getMessage(e)),this._logRedirectCallback(`error::${t}`)}getMessage(...e){return`${(new Date).toISOString()} ${this.getNamespace()} ${e.join(" ")}`}getNamespace(){return this._namespace.map((e=>e())).join(":")}getPrefix(e,t){let i="";return t&&(i+=t),e&&(i+=e),i}redirectLog(e){this._logRedirectCallback=t=>{_I.defaultLogRedirect(t),e(t)}}dumpAllLogs(){return[..._I.logDump.toArray()]}}_I.logDump=new bI(500),_I.defaultLogRedirect=e=>{if(vy()?.debugInfo?.enableLogDump){const t=()=>{_I.logDump.length>vy()?.debugInfo?.maxLogDumpLength&&_I.logDump.shift()};if(vy()?.debugInfo?.includeList.some((t=>Z.includes(e,t))))return _I.logDump.push(e),void t();if(!vy()?.debugInfo?.excludeList.some((t=>Z.includes(e,t))))return _I.logDump.push(e),void t()}};class II{constructor(e){this._telemetryLogManager=e}sendMediaStreamEvent(e){this._telemetryLogManager?.sendEvent({name:aE.acs_calling_media_stream,tenant:xv,properties:{correlationId:e.correlationId,mediaType:e.mediaType,operation:e.operation,timestampInfo:e.timestampInfo,streamType:e.streamType||bE.Local,additionalDetails:e.additionalDetails||"",kindOfEvent:e.kindOfEvent||"",callId:e.callId||"",localPaticipantId:e.localParticipantId||"",createViewResolvedOnPlayEvent:e.createViewResolvedOnPlayEvent||""}})}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([SI,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata("design:type",t)}(0,Object)],II.prototype,"logger",void 0);class wI{constructor(e,t,i){this._logger=e,this._environmentInfo=t,this._isVdi3Enabled=i,this._videoEffectsEnabled=!1,this._audioEffectsEnabled=!1,this._videoEffectsSupported=!1,this._audioEffectsSupported=!1,this._config=vy(),this._mediaConfig=Sy(),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 e=this._mediaConfig?.webcv?.useWasmEffects?this._isWasmVideoEffectSupported():this._isWebgl2EffectSupported();this._videoEffectsSupported=e&&this._isCurrentEnvironmentSDKSupported()}else this._logger.info("Video effects are disabled."),this._videoEffectsSupported=!1;return this._videoEffectsSupported}async audioEffectsSupported(e){return this._audioEffectsEnabled?this._audioEffectsSupported=this._isBrowserEffect(e)?this._isBrowserEffectSupported(e):await this._isWasmAudioEffectSupported():(this._logger.info("Audio effects are disabled."),this._audioEffectsSupported=!1),this._audioEffectsSupported}_isBrowserEffect(e){if("string"==typeof e)switch(e){case"BrowserEchoCancellation":case"BrowserNoiseSuppression":case"BrowserAutoGainControl":return!0;default:return!1}return!1}_isBrowserEffectSupported(e){if(this._isVdi3Enabled)return!0;const t=window.navigator?.mediaDevices?.getSupportedConstraints?.();if(t)switch(e){case"BrowserEchoCancellation":return!!t.echoCancellation;case"BrowserNoiseSuppression":return!!t.noiseSuppression;case"BrowserAutoGainControl":return!!t.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 e=this._mediaConfig?.webcv?.webGLUnsupportedRenderers??[];let t=!1;try{const i=document.createElement("canvas").getContext("webgl"),n=i?.getExtension("WEBGL_debug_renderer_info"),r=n&&i?.getParameter(n.UNMASKED_RENDERER_WEBGL);return r&&!e.some((e=>e===r))?t=!0:this._logger.info(`Unsupported renderer: ${Ey(r)}`),t}catch(e){return this._logger.warn(`Error trying to check compatibility: ${JSON.stringify(e)}`),!1}}_isWebGL2Supported(){try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return this._logger.info("WebGL2 context is not supported"),!1;const t=e.getSupportedExtensions(),i=this._mediaConfig?.webcv?.webGLRequiredExtensions.filter((e=>!t?.includes(e)));if(i.length>0)return this._logger.info(`Unsupported WebGL2 extensions: ${Ey(i)}`),!1}catch(e){return this._logger.error(`isWebGL2Supported: ${Ey(e)}`),!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)}}function AI(e){if("object"==typeof e){if("initializeMediaAgent"in e)return EI.IPluginlessCallingStack;if("setConfiguration"in e)return EI.ICallRegistry;if("joinCallWithoutCallModality"in e)return EI.ICall;if("getSourceIdForMediaType"in e)return EI.ICallParticipant;if("getDiagnosticData"in e&&"start"in e)return EI.ICallParticipantStream;if("askDevicePermission"in e)return EI.IDeviceManager}return EI.None}function PI(e){if("object"!=typeof e)return!1;if(e===Object.prototype)return!1;for(const[,t]of Object.entries(Object.getOwnPropertyDescriptors(e))){if(void 0!==t.get)return!0;if(void 0!==t.value&&"function"==typeof t.value)return!0}return PI(Object.getPrototypeOf(e))}!function(e){e[e.None=0]="None",e[e.IPluginlessCallingStack=1]="IPluginlessCallingStack",e[e.ICallRegistry=2]="ICallRegistry",e[e.ICall=3]="ICall",e[e.ICallParticipant=4]="ICallParticipant",e[e.ICallParticipantStream=5]="ICallParticipantStream",e[e.IDeviceManager=6]="IDeviceManager"}(EI||(EI={}));const RI=Symbol();function MI(e){return"object"==typeof e&&RI in e}var DI=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},kI=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const OI=[{acsEffect:"Off",tsCallingEffect:0},{acsEffect:"BackgroundBlur",tsCallingEffect:1},{acsEffect:"BackgroundReplacement",tsCallingEffect:16}];class NI extends tb{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 e=>{const t=Mf(),i=this.getUsageDetailsForTelemetry("Configure method",e),n=+new Date;try{this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.effectConfigureUpdate,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:i,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}});const r=this._internalDeviceManager.getTsDeviceManager();if("BackgroundReplacement"===e){const e=(this._effect?._internalHandle?.effectConfig).backgroundImageUrl;e&&await r.setBackgroundImageAsync("",e),this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.effectConfigureUpdate,timestampInfo:{deltaTimeInMs:+new Date-n},kindOfEvent:oE.success,additionalDetails:{usageDetails:i,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}})}this._logger.info("effect config was updated")}catch(e){const r=new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EFFECT_CONFIG_UPDATE_CALLBACK_FAILED,originalError:e});this._logger.error(r.message),this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.effectConfigureUpdate,timestampInfo:{deltaTimeInMs:+new Date-n},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:i}})}},this.processingErrorCallback=async e=>{const t=Mf();this.eventEmitter.emit("effectsError",e);const i=this.getEffectNameForTelemetry(this._effect?.name),n=this.getUsageDetailsForTelemetry("Internal handle error",i);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.effectsError,kindOfEvent:oE.failure,additionalDetails:{failureReason:e.message,code:e.code,..._b(e),usageDetails:n}}),await this.stopEffects()},this.effectStatusChangedCallback=(e,t)=>{if(t.length>0){const e=this._effect?.name?[this._effect.name]:t;this.eventEmitter.emit("effectsStarted",e)}else{const t=this._effect?.name?[this._effect.name]:e;this.eventEmitter.emit("effectsStopped",t)}}}initialize(e,t){this._logger=t.createChild(" - VideoEffects:"),this._telemetryLogManager=e.telemetryLogManager,this.updateEffectStatusManager()}get name(){return"VideoEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"fpsWarningThresholdReached"!==e&&"timeForEffectsWarningReached"!==e)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t);const i=Mf();this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:i,operation:_E.subscribe,additionalDetails:{usageDetails:`Subscribed to ${e}`}})}off(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"fpsWarningThresholdReached"!==e&&"timeForEffectsWarningReached"!==e)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}async isSupported(e){const t=Mf(),i=+new Date,n=this.getEffectNameForTelemetry(e?.name),r=this.getUsageDetailsForTelemetry("",n);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:r}});try{this._logger.info(`isSupported attempted with input ${this.getEffectNameForTelemetry(e?.name)}`);const n=this.getEffectInternalCast(e);if(this.disposed)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const r=this._internalDeviceManager.getEnvironmentInfoInternal(),s=MI(this._internalDeviceManager.getTsDeviceManager());this._supportChecker||(this._supportChecker=new wI(this._logger,r,s));const a=await this._supportChecker.videoEffectsSupported();this._logger.info(`Support check for ${n.name} resulted in: ${a}`);const o=this.getUsageDetailsForTelemetry("",n.name);return this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.success,additionalDetails:{usageDetails:o}}),this._logger.info("isSupported success"),a}catch(n){const r=new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:n});this._logger.error(r.message);const s=this.getEffectNameForTelemetry(e?.name),a=this.getUsageDetailsForTelemetry("",s);throw this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:a}}),r}}async startEffects(e){const t=Mf(),i=+new Date,n=this.getEffectNameForTelemetry(e?.name),r=this.getUsageDetailsForTelemetry("",n);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:r}});try{if(this._logger.info(`startEffects attempted with input ${this.getEffectNameForTelemetry(e?.name)}`),!vy().videoEffects.enableVideoEffects)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.DISABLED});if(this.disposed)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this.updateEffectStatusManager(),this.subscribeToStreamInstanceEvents();const n=window.performance.now();if(this._effect=this.getEffectInternalCast(e),!await this.isSupported(e))throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});const r=this._internalDeviceManager.getTsDeviceManager();if(!r)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.START_DEVICE_MANAGER});this.setConfigForEffects(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();const s=await this._effect._internalHandle.getEffectProvider();if(!s)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.PROVIDER_UNAVAILABLE});const a=await s.getVideoEffectProvider(),o=this.streamInstance.callStackWebCVProvider;if(!o)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.WEBCV_PROVIDER_FAILED});o.videoEffectProviderDeferredPromise.resolve(a),0===this._tsCallingEffectCapability&&(this._tsCallingEffectCapability=await(r?.getDeviceEffectsCapabilityAsync(""))),this._tsCallingSupportedEffects=this.getTsCallingSupportedEffects();const l=this._tsCallingSupportedEffects.find((e=>e.acsEffect===this._effect?.name));if(!l)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await(r?.setDeviceEffectsAsync("",l.tsCallingEffect)),this._effectsStatusManager.setActiveEffects([this._effect.name]),this._logger.info(`Video effects started: ${this._effect.name}`);const c=window.performance.now();this.handleEffectsInitTimeEvent(n,c),this.handleFpsWarningEvent();const d=this.getUsageDetailsForTelemetry("",this._effect.name);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.success,additionalDetails:{usageDetails:d,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}}),this._logger.info("startEffects success")}catch(n){const r=new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.START_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r),this.clearFpsCheckInterval();const s=this.getEffectNameForTelemetry(e?.name),a=this.getUsageDetailsForTelemetry("",s);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:a,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}})}}async stopEffects(){const e=Mf(),t=+new Date;this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:e,operation:_E.stopEffects,kindOfEvent:oE.attempt});try{if(this._logger.info("stopEffects attempted"),this.clearFpsCheckInterval(),this.disposed)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const i=this._internalDeviceManager.getTsDeviceManager();if(!i)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.STOP_DEVICE_MANAGER});this.updateEffectStatusManager();const n=this._tsCallingSupportedEffects.find((e=>"Off"===e.acsEffect));if(!n)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await i.setDeviceEffectsAsync("",n.tsCallingEffect),this._effectsStatusManager?.setActiveEffects([]),this.unsubscribeFromStreamInstanceEvents();const r=this.getEffectNameForTelemetry(this._effect?.name);this._logger.info(`Video effects stopped: ${r}`),this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:e,operation:_E.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.success}),this._logger.info("stopEffects success")}catch(i){const n=new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.STOP_FAILED,originalError:i});this._logger?.error(n.message),this.eventEmitter.emit("effectsError",n),this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:e,operation:_E.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,additionalDetails:{failureReason:n.message,code:n.code,..._b(n)}})}}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(e){const t=new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.DISPOSE_FAILED,originalError:e});this._logger?.error(t.message),this.eventEmitter.emit("effectsError",t)}}getEffectsSdkVersion(){let e=this._stringForUnknownInput;return this.activeEffects.length>0&&this._effect&&this._effect._internalHandle?.getVersion&&(e=this._effect._internalHandle?.getVersion()),this.truncateToMax(e)}getActiveEffectsForTelemetry(){return this.truncateToMax(JSON.stringify(this.activeEffects))}getEffectInternalCast(e){if("BackgroundBlur"===e?.name&&this.isValidEffectInstance(e))return e;if("BackgroundReplacement"===e?.name&&this.isValidEffectInstance(e))return e;throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(e){let t;return("BackgroundBlur"===e.name&&void 0!==e._internalHandle||"BackgroundReplacement"===e.name&&void 0!==e._internalHandle)&&(t=e,this.hasValidInternalHandle(t._internalHandle))}hasValidInternalHandle(e){return void 0!==e.effectConfig&&void 0!==e.getEffectProvider&&void 0!==e.dispose&&void 0!==e.getStats&&void 0!==e.setConfig}getTsCallingSupportedEffects(){const e=[];return Object.values(OI).forEach((t=>{(this._tsCallingEffectCapability&t.tsCallingEffect)===t.tsCallingEffect&&e.push(t)})),e}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 e=>{e.source&&"Video"!==e.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(e,t){if(!this._effect)return void this._logger.debug("No effect active");const i=Mf(),n=t-e,r=this._effect._internalHandle.effectConfig.effectInitTimeThresholdInMs;if(this._logger.info(`Time for effects to start: ${n}ms`),r&&n>r){this.eventEmitter.emit("timeForEffectsWarningReached",this._effect.name);const e=this.getUsageDetailsForTelemetry(`Threshold value: ${r}ms`,this._effect.name);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:i,operation:_E.timeForEffectsWarningReached,additionalDetails:{usageDetails:e}})}}handleFpsWarningEvent(){if(!this._effect)return void this._logger.debug("No effect active");this.clearFpsCheckInterval();const e=vy(),t=Mf(),i=e.videoEffects.waitTimeToInitiateFpsChecksInMs,n=e.videoEffects.fpsCheckIntervalTimeInMs;this._fpsWarningThresholdValue=this._effect._internalHandle.effectConfig.fpsWarningThreshold??e.videoEffects.fpsWarningThreshold;const r=window.setTimeout((()=>{const e=window.setInterval((()=>{const i=this._effect?._internalHandle.getStats(),n=i?.processor.fpsAvg;if(this._logger.info(`Effects avg fps check interval poll. Current Avg - ${n}`),n&&n<this._fpsWarningThresholdValue){this.eventEmitter.emit("fpsWarningThresholdReached",this._effect?.name),window.clearInterval(e),this._logger.info(`Effects fps warning threshold hit at ${n}fps`);const i=this.getUsageDetailsForTelemetry(`Fps reported: ${n}, Fps warning threshold value: ${this._fpsWarningThresholdValue}`,this._effect?.name);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.fpsWarningThresholdReached,additionalDetails:{usageDetails:i}})}}),n);this._fpsWarningEventIntervalIds.push(e)}),i);this._fpsWarningEventTimeoutIds.push(r)}setConfigForEffects(){if(!this._effect)return void this._logger.debug("No effect active");const e=this._effect._internalHandle.configProvider.config.videoEffects??this._effect._internalHandle.configProvider.config,t=Sy(),i=vy();if(t?.enableVideoEffects&&i?.videoEffects?.enableVideoEffects&&(e.enableVideoEffects=t.enableVideoEffects&&i.videoEffects.enableVideoEffects),e.effectConfig={...e.effectConfig,effectInitTimeThresholdInMs:i.videoEffects.effectInitTimeThresholdInMs,fpsWarningThreshold:i.videoEffects.fpsWarningThreshold},t.webcv){const i=t.webcv;e.webcvConfig={...e.webcvConfig,...i}}this._effect._internalHandle.setConfig(e),this._logger.info(`Config for effects set: ${Ey(e)}`)}sendFeatureUsageTelemetry(e){if(this._telemetryLogManager){e.additionalDetails={...e.additionalDetails,callState:this.streamInstance.getCall()?.state,activeEffects:JSON.stringify(this.activeEffects),effectsSdk:{...e.additionalDetails?.effectsSdk,version:this.getEffectsSdkVersion()}};try{const t={correlationId:e.correlationId,mediaType:EE.VideoRaw,streamType:bE.Local,operation:e.operation,timestampInfo:e.timestampInfo||{},kindOfEvent:e.kindOfEvent||"",additionalDetails:e.additionalDetails||"",callId:this.streamInstance.getCall()?.id||"",localParticipantId:this.streamInstance.getLocalParticipantId()||""};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:t})}catch(t){this._logger.debug(`Unable to send ${e.operation} telemetry`)}}else this._logger.debug("Telemetry error. Instance is undefined.")}getEffectNameForTelemetry(e){let t=this._stringForUnknownInput;return e?t="string"==typeof e?e:JSON.stringify(e):this._effect?.name?t=this._effect.name:this._activeEffects?.[0]&&(t=JSON.stringify(this._activeEffects[0])),this.truncateToMax(t)}getUsageDetailsForTelemetry(e,t=""){return this.truncateToMax(`${t?`[${t}] `:""}${e}`)}clearFpsCheckInterval(){this._fpsWarningEventIntervalIds.forEach((e=>{window.clearInterval(e)})),this._fpsWarningEventTimeoutIds.forEach((e=>{window.clearTimeout(e)})),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(e){const t=vy().videoEffects.maxStringLengthForTelemetry;return e.length>t?(this._logger?.info("Truncating video effects info for telemetry"),e.substring(0,t-2)+".."):e}getBackgroundImageHasTransparentPixel(){try{if("BackgroundReplacement"===this._effect?.name&&void 0!==this._effect._internalHandle?.imageLoader?.loadedImageHasTransparentPixels)return this._effect._internalHandle.imageLoader?.loadedImageHasTransparentPixels}catch(e){return null}return null}}DI([WE(),kI("design:type",Function),kI("design:paramtypes",[Object]),kI("design:returntype",Promise)],NI.prototype,"startEffects",null),DI([WE(),kI("design:type",Function),kI("design:paramtypes",[]),kI("design:returntype",Promise)],NI.prototype,"stopEffects",null);var LI,xI=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},FI=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class UI{constructor(e){if(this._disposed=!1,this._call=new Set,this._canStartEffects=!1,this.kind="LocalVideoStream",this._renderers=[],this._rawStreamCloneCache=new Set,this._disposeRenderer=e=>{this.logger.log("disposing renderer");try{e.dispose(),this.logger.log("renderer disposed")}catch(e){this.logger.log("failed to dispose renderer")}},!(e instanceof vI||e instanceof MediaStream))throw new le({defaultError:ee.LOCAL_VIDEO_STREAM.WRONG_STREAM_TYPE});const t=R("ACS-calling");this.logger=new _I(t,[()=>`LocalVideoStream:${e.id}`]),this.logger.info("created"),this._eventEmitter=new T_(this.logger),this.setSource(e,!0),this._localStreamTelemetryEventSender=new II(this._telemetryLogManager)}on(e,t){if("videoSourceChanged"!==e)throw new le({defaultError:ee.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("videoSourceChanged"!==e)throw new le({defaultError:ee.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}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(e){this.logger.createFnLogger(iy.SwitchSource);const t=+new Date,i=Mf(),n={timestampInfo:{attemptTimestamp:t},correlationId:i,operation:_E.switchSource,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",kindOfEvent:oE.attempt,mediaType:EE.Video,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),!(e instanceof vI)){const e=new le({defaultError:ee.LOCAL_VIDEO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.switchSource,additionalDetails:{failureReason:e.message,code:ie,..._b(e)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,mediaType:EE.Video,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}if(this._source===e){const e=new le({defaultError:ee.LOCAL_VIDEO_STREAM.SWITCH_SAME_SOURCE}),n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.switchSource,additionalDetails:{failureReason:e.message,code:e.code,..._b(e)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,mediaType:EE.Video,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}try{"RawMedia"===this._mediaStreamType&&Array.from(this._call.values()).some((e=>e.localVideoStream===this))&&e.deviceManager.getTsDeviceManager().unsetRawMediaStream?.(1),e.deviceManager.getTsDeviceManager().selectDevices({camera:e.id}),this.setSource(e);const n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:EE.Video,operation:_E.switchSource,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n)}catch(e){const n=Eb(0,e),r={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.switchSource,additionalDetails:{failureReason:n.message,code:ie,..._b(n)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,mediaType:EE.Video,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}dispose(){this.logger.log("Disposing LocalVideoStream."),this._disposed?this.logger.log("already disposed"):(this.disposeRawStream(),this._renderers.forEach((e=>this._disposeRenderer(e))),this._renderers=[],this._extensibleApi?.dispose(),this._eventEmitter.removeAllListeners(),this._disposed=!0)}async getMediaStream(){const e=Mf();let t=+new Date;const i={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",timestampInfo:{attemptTimestamp:t},operation:_E.getMediaStream,kindOfEvent:oE.attempt,mediaType:EE.VideoRaw,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const i={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:EE.VideoRaw,operation:_E.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(i);const n=this._mediaStreamSource.clone();return this._cacheCloneStream(n),n}try{let i;if("ScreenSharing"===this._source.deviceType?i=2:"UsbCamera"!==this._source.deviceType&&"CaptureAdapter"!==this._source.deviceType&&"Virtual"!==this._source.deviceType||(i=1),!i)throw new le({defaultError:ee.LOCAL_VIDEO_STREAM.CANT_GET_DEVICE_TYPE});this._rawStream||(this._rawStream=this.source.deviceManager.getRawDeviceMediaStream(i));const n={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:EE.VideoRaw,operation:_E.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n);const r=(await(this._rawStream?.getMediaStream())).clone();return this._cacheCloneStream(r),r}catch(i){let n;n="ScreenSharing"===this._source.deviceType?new le({defaultError:ee.CALL.SS_RAW_STREAM_GET,originalError:i}):new le({defaultError:ee.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:i});const r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.getMediaStream,additionalDetails:{failureReason:n.message,code:n.code,..._b(n)},kindOfEvent:oE.failure,mediaType:EE.VideoRaw,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}async setMediaStream(e){const t=Mf();let i,n=+new Date,r=!1,s=!1,a=EE.VideoRawOrScreenSharingRaw;for(let e of this._call){const t=e;if(t.localScreenSharingStream===this||t.localVideoStream===this){i=t.deviceManager,s=!0,t.localVideoStream===this?(r=!0,a=EE.VideoRaw):t.localScreenSharingStream===this&&(r=!1,a=EE.ScreenSharingRaw);break}}const o={timestampInfo:{attemptTimestamp:n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.setMediaStream,kindOfEvent:oE.attempt,mediaType:a,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(o),!(e instanceof MediaStream)){const e=new le({defaultError:ee.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),i={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.setMediaStream,additionalDetails:{failureReason:e.message,code:e.code,..._b(e)},kindOfEvent:oE.failure,mediaType:a,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),e}if(this.setSource(e),vy()?.calling?.allowAccessRawMediaStream)try{if(s){const t=i?.getTsDeviceManager();if(!t?.setRawMediaStream)throw new le({defaultError:ee.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_UNDEFINED_FUNC});r?t.setRawMediaStream(e,1):t.setRawMediaStream(e,2)}this._renderers.forEach((t=>{t.setSourceObject(e)}));const o={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.setMediaStream,kindOfEvent:oE.success,mediaType:a,streamType:bE.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(o)}catch(e){const i=new le({defaultError:ee.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM,originalError:e}),r={correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:_E.setMediaStream,additionalDetails:{failureReason:i.message,code:i.code,..._b(i)},timestampInfo:{deltaTimeInMs:+new Date-n},kindOfEvent:oE.failure,mediaType:a,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),i}}addCall(e){this._call.add(e)}removeCall(e){this._call.delete(e)}feature(e){return this._extensibleApi||(this._extensibleApi=new nb(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(e.videoStreamApiCtor)}registerRenderer(e){this._renderers.push(e)}unregisterRenderer(e){const t=this._renderers.indexOf(e);-1!==t&&this._renderers.splice(t,1)}getStreamMetadata(){let e,t,i=this.getCall();this._source instanceof vI?(e=this.source.deviceManager,t=this.source.deviceType):this._mediaStreamSource instanceof MediaStream&&i&&(e=i.deviceManager);let n=-1;return i&&("Video"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&i.localVideoStream===this?n=i.tsCall.mediaStreams[0][0]?.id||-1:("ScreenSharing"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&i.localScreenSharingStream===this)&&(n=i.tsCall.mediaStreams[1][0]?.id||-1)),{source:"local",sourceId:n,streamType:this.mediaStreamType,deviceType:t||"",callId:i?.id||"",localParticipantId:i?.tsCall.participantId||"",deviceManagerPermissionState:e?JSON.stringify({cameraPermission:e.getVideoDevicePermission(),microphonePermission:e.getAudioDevicePermission()}):"",acsResourceId:e?.getAcsResourceId()||"",clientId:e?.getClientId()||""}}getLocalParticipantId(){let e="";const t=this.getCall();return t&&(e=t.tsCall.participantId),e}getCall(){for(const e of this._call)if(e.localVideoStreams.includes(this))return e}getEffectsCurrentStateRecord(){try{const e=this.feature(db(NI)),t=e.getEffectsSdkVersion();return{activeEffects:e.getActiveEffectsForTelemetry(),effectsSdk:{version:t}}}catch(e){return void this.logger.warn(`Error while getting current effect state on LocalAudioStream for telemetry: ${e}`)}}setSource(e,t=!1){if(e instanceof vI)this._telemetryLogManager=e.deviceManager.telemetryLogManager,this._source=e,this._mediaStreamType="ScreenSharing"===e.deviceType?"ScreenSharing":"Video",this._mediaStreamSource=void 0,this._rawStream=void 0,this._canStartEffects=!0;else{try{1===globalThis[Xv]&&(this._telemetryLogManager=globalThis[Zv])}catch(e){this.logger.error("Failed to retrive telemetry logger for localVideoStream")}this._source={name:"CustomMediaStream",id:Mf(),deviceType:"Virtual"},this._mediaStreamSource=e,this._mediaStreamType="RawMedia",this._canStartEffects=!1}t||this._eventEmitter.emit("videoSourceChanged",{source:this})}subscribeToRawStreamChangedIfNeeded(){this._source instanceof vI&&!this._videoSourceChangedSub&&(this._videoSourceChangedSub=this._rawStream?.changed((()=>{this._eventEmitter.emit("videoSourceChanged",{source:this})})))}_cacheCloneStream(e){this._rawStreamCloneCache.add(e)}disposeRawStream(){this._rawStream&&this._rawStream.dispose();for(const e of Array.from(this._rawStreamCloneCache))e?.getTracks?.().forEach((e=>e.stop()));this._rawStreamCloneCache.clear(),this._videoSourceChangedSub?.dispose(),this._videoSourceChangedSub=void 0}}xI([SI,FI("design:type",Object)],UI.prototype,"logger",void 0),xI([pe(iy.SwitchSource),FI("design:type",Function),FI("design:paramtypes",[Object]),FI("design:returntype",Promise)],UI.prototype,"switchSource",null),xI([pe(iy.GetMediaStream),FI("design:type",Function),FI("design:paramtypes",[]),FI("design:returntype",Promise)],UI.prototype,"getMediaStream",null),xI([pe(iy.SetMediaStream),FI("design:type",Function),FI("design:paramtypes",[MediaStream]),FI("design:returntype",Promise)],UI.prototype,"setMediaStream",null),xI([ge(iy.Feature),FI("design:type",Function),FI("design:paramtypes",[Object]),FI("design:returntype","function"==typeof(LI="undefined"!=typeof TFeature&&TFeature)?LI:Object)],UI.prototype,"feature",null);class BI{constructor(e,t,i,n,r){this._name=e,this._id=t,this._isSystemDefault=i,this._deviceType=n,this._deviceManager=r}get name(){return this._name}setName(e){this._name=e}get id(){return this._id}setId(e){this._id=e}get isSystemDefault(){return this._isSystemDefault}setIsSystemDefault(e){this._isSystemDefault=e}get deviceType(){return this._deviceType}setDeviceType(e){this._deviceType=e}get deviceManager(){return this._deviceManager}}class VI{constructor(e,t,i,n,r){this._workQueue=Promise.resolve(),this.logger=e.createChild("volume indicator"),this._eventEmitter=new T_(this.logger,{enableLogEmit:!1}),this._isInitialized=!1,this._level=0,this._streamType=t,this._callId=n,this._localParticipantId=r,this._telemetryLogManager=i}get isInitialized(){return this._isInitialized}initialize(e){if(void 0===e)throw this.logger.error("failed to getMediaStreamTrack"),new le({defaultError:ee.CALL.VOLUME_TRACK});const t=Mf(),i=+new Date;try{this.sendVolumeEvent({eventName:aE.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),this.bindToAudioStreamVolume(e),this.sendVolumeEvent({eventName:aE.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:""})}catch(e){const n=new le({defaultError:ee.CALL.VOLUME_INIT,originalError:e});throw this.logger.error(n.message),this.sendVolumeEvent({eventName:aE.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,..._b(n)}}),n}}bindToAudioStreamVolume(e){let[t,i]=this.setupVolumeCalculator(e);this._level=t();let n=setInterval((()=>{let e=t();e!==this._level&&(this._level=e,this._eventEmitter.emit("levelChanged"))}),vy()?.volumeIndicator?.microphoneVolumeSampleIntervalMs);this._volumeCallBackInterval=n,this._audioContext=i}setupVolumeCalculator(e){const t=new MediaStream(e),i=new AudioContext,n=i.createMediaStreamSource(t),r=i.createAnalyser();n.connect(r),r.fftSize=vy().volumeIndicator.fftSize,r.minDecibels=vy().volumeIndicator.minDecibels,r.maxDecibels=vy().volumeIndicator.maxDecibels,r.smoothingTimeConstant=vy().volumeIndicator.smoothingConstant;const s=new Uint8Array(r.frequencyBinCount);return[()=>{try{r.getByteFrequencyData(s);let e=0;for(const t of s)e+=t;return e/s.length*vy().volumeIndicator.normalisedMaxVolume/vy().volumeIndicator.maxAvailableVolume}catch(e){return this.logger.error("error in calculating audio stream volume"),0}},i]}dispose(){this._isInitialized=!1,this._level=0,this._eventEmitter.removeAllListeners();try{this._audioContext?.close().catch((e=>{this.logger.error("unable to close AudioContext")}))}catch(e){this.logger.error("unable to close MicrophoneAudioContext")}this._volumeCallBackInterval&&clearInterval(this._volumeCallBackInterval)}on(e,t){if("levelChanged"!==e)throw new le({defaultError:ee.CALL.VOLUME_EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("levelChanged"!==e)throw new le({defaultError:ee.CALL.VOLUME_EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get level(){return this._level}getVolumeIndicator(e){const t=()=>{if(!this.isInitialized)try{this.initialize(e),this._isInitialized=!0}catch(e){const t=new le({defaultError:ee.CALL.VOLUME_GET,originalError:e});throw this.logger.error(t.message),t}return this},i=this._workQueue.then((()=>t()));return this._workQueue=i.then(My,My),i}sendVolumeEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send screen share telemetry")}}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([SI,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata("design:type",t)}(0,Object)],VI.prototype,"logger",void 0);class HI{constructor(e,t,i){this._effectsStatusManager=e,this._logger=t,this._localAudioStream=i,this._currentActiveBrowserEffects={};const n=this._localAudioStream.source.deviceManager;this._isVdi3Enabled=MI(n.getTsDeviceManager()),this._updateCurrentActive()}async setBrowserAudioEffects(e,t,i){try{await this._updateCurrentActive(t);const n={autoGainControl:void 0!==i.autoGainControl?i.autoGainControl:this._currentActiveBrowserEffects.autoGainControl,echoCancellation:void 0!==i.echoCancellation?i.echoCancellation:this._currentActiveBrowserEffects.echoCancellation,noiseSuppression:void 0!==i.noiseSuppression?i.noiseSuppression:this._currentActiveBrowserEffects.noiseSuppression},r=this._calculateFlags(n);this._logger.info(`Setting browser audio processing flags to ${r}`),await e.setAudioProcessingFlags(r)}catch(e){throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.AUDIO_FLAGS,originalError:e})}}async _updateCurrentActive(e){try{const t=e??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 i=this._isVdi3Enabled?{autoGainControl:!0,noiseSuppression:!0,echoCancellation:!0}:await(async()=>{const e=await this._localAudioStream.getMediaStream(),t=e?.getAudioTracks()?.[0];if(!t)throw new Error("Could not get MediaStreamTrack from the LocalAudioStream");return t.getSettings()})();let n=!!i?.autoGainControl,r=!!i?.noiseSuppression,s=!!i?.echoCancellation;this._currentActiveBrowserEffects={},("BrowserAutoGainControl"===t?.autoGainControl?.[0]||n)&&(this._currentActiveBrowserEffects.autoGainControl=!0),("BrowserEchoCancellation"===t?.echoCancellation?.[0]||s)&&(this._currentActiveBrowserEffects.echoCancellation=!0),("BrowserNoiseSuppression"===t?.noiseSuppression?.[0]||r)&&(this._currentActiveBrowserEffects.noiseSuppression=!0)}catch(e){throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.AUDIO_FLAGS,originalError:e})}}_calculateFlags(e){let t=0;return e.autoGainControl&&(t+=1),e.echoCancellation&&(t+=2),e.noiseSuppression&&(t+=4),t}}var $I=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},jI=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class GI extends ib{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=(e,t,i)=>{this._logger?.debug(`Effects status changed from ${JSON.stringify(e)} to ${JSON.stringify(t)} with operationType: ${i}`),"start"!==i&&"initialize"!==i||this.eventEmitter.emit("effectsStarted",t),"stop"===i&&this.eventEmitter.emit("effectsStopped",t)},this.configUpdatedCallback=async e=>{this._logger?.info("configUpdated callback, no-op.")},this.processingErrorCallback=async e=>{const t=Mf();this._logger?.info("processingError callback"),this.eventEmitter.emit("effectsError",e);const i=this.getEffectsNameForTelemetry(this.activeEffects),n=this.getUsageDetailsForTelemetry("Internal handle error",i);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.stopEffects,kindOfEvent:oE.failure,additionalDetails:{failureReason:e.message,..._b(e),usageDetails:n}}),await this.stopEffects({echoCancellation:!0,noiseSuppression:!0})},this.subscribeToStatUpdates=async()=>{const e=this.getAnyActiveWasmEffect();if(!e)return;const t=await e._internalHandle.getEffectProvider(),i=await(t?.getAudioEffectProvider());let n=null;i&&(this._audioEffectProviderSub=i?.on?.("onMetricsUpdated",(()=>{try{n=i?.getStats&&i.getStats(),n&&(this._audioEffectsProcessorStats={activeAudioEffects:JSON.stringify(this.activeEffects),audioEffectsSpeechProcessingStats:{localAudioInputSpeechRMS_dBFS:n?.speechLevels?.nearEndInputRMS_dBFS,localAudioOutputSpeechRMS_dBFS:n?.speechLevels?.nearEndOutputRMS_dBFS,localAudioInputNoiseRMS_dBFS:n?.noiseLevels?.nearEndInputRMS_dBFS,localAudioOutputNoiseRMS_dBFS:n?.noiseLevels?.nearEndOutputRMS_dBFS,remoteAudioInputSpeechRMS_dBFS:n?.speechLevels?.farEndInputRMS_dBFS,remoteAudioOutputSpeechRMS_dBFS:n?.speechLevels?.farEndOutputRMS_dBFS},rawStats:JSON.stringify(n)}),this.eventEmitter.emit("effectsProcessorStatsUpdated",this._audioEffectsProcessorStats)}catch(e){this._logger?.warn(`Could not emit audio effect processor stat event: ${e}`)}})),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(e,t){this._logger=t.createChild(" - AudioEffects:"),this._telemetryLogManager=e.telemetryLogManager,this.updateAudioEffectsStatusManager()}get name(){return"AudioEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"effectsProcessorStatsUpdated"!==e)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"effectsProcessorStatsUpdated"!==e)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}async isSupported(e){const t=Mf(),i=+new Date,n=this.getUsageDetailsForTelemetry("",this.getEffectsNameForTelemetry(e));this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:n}});try{if(this._logger?.info(`isSupported attempted with input ${e}`),this.disposed)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const n=this._internalDeviceManager.getEnvironmentInfoInternal(),r=MI(this._internalDeviceManager.getTsDeviceManager());this._supportChecker||(this._supportChecker=new wI(this._logger,n,r));let s=!1;if("object"==typeof e){const t=this.getEffectInternalCast(e);s=await this._supportChecker.audioEffectsSupported(t),this._logger?.info(`Support check for ${t.name} resulted in: ${s}`)}else"string"==typeof e&&(s=await this._supportChecker.audioEffectsSupported(e),this._logger?.info(`Support check for ${e} resulted in: ${s}`));const a=this.getEffectsNameForTelemetry(e),o=this.getUsageDetailsForTelemetry("",a);return this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.success,additionalDetails:{usageDetails:o}}),this._logger?.info("isSupported success"),s}catch(n){const r=new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:n});this._logger?.error(r.message);const s=this.getEffectsNameForTelemetry(e),a=this.getUsageDetailsForTelemetry("",s);throw this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:a}}),r}}async startEffects(e){const t=Mf(),i=+new Date,n=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(e)));this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:n}});try{this._logger?.info(`startEffects attempted with input ${JSON.stringify(this.getEffectsConfigForTelemetry(e))}`);const n=vy();if(!n?.audioEffects?.enableAudioEffects)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.DISABLED});if(this.disposed)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const r=this._internalDeviceManager.getTsDeviceManager();if(!r)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.START_DEVICE_MANAGER});await this.updateAudioEffectsStatusManager(),this.subscribeToStreamInstanceEvents(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();let s=this.activeEffects;e?.autoGainControl&&(s=await this.startStopAutoGainControl(r,s,!0,e.autoGainControl)),e?.echoCancellation&&(s=await this.startStopEchoCancellation(r,s,!0,e.echoCancellation)),e?.noiseSuppression&&(s=await this.startStopNoiseSuppression(r,s,!0,e.noiseSuppression)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&(this._logger?.info(`Setting tsDeviceManager setAudioEffectsAsync API with ${this._currentTsWasmEffectType}`),await r.setAudioEffectsAsync("",this._currentTsWasmEffectType)),this._effectsStatusManager?.setActiveEffects(s,"start"),await this.subscribeToStatUpdates();const a=JSON.stringify(s),o=this.getUsageDetailsForTelemetry("",a);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.success,additionalDetails:{usageDetails:o}}),this._logger?.info("startEffects success")}catch(n){const r=new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.START_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r);const s=JSON.stringify(this.getEffectsConfigForTelemetry(e)),a=this.getUsageDetailsForTelemetry("",s);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:a}})}}async stopEffects(e){const t=Mf(),i=+new Date,n=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(e)));this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.stopEffects,kindOfEvent:oE.attempt,additionalDetails:{usageDetails:n}});try{if(this._logger?.info(`stopEffects attempted with input ${JSON.stringify(this.getEffectsConfigForTelemetry(e))}`),this.disposed)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const n=this._internalDeviceManager.getTsDeviceManager();if(!n)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.STOP_DEVICE_MANAGER});await this.updateAudioEffectsStatusManager();let r=this.activeEffects;e?.autoGainControl&&(r=await this.startStopAutoGainControl(n,r,!1)),e?.echoCancellation&&(r=await this.startStopEchoCancellation(n,r,!1)),e?.noiseSuppression&&(r=await this.startStopNoiseSuppression(n,r,!1)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&(this._logger?.info(`Setting tsDeviceManager setAudioEffectsAsync API with ${this._currentTsWasmEffectType}`),await n.setAudioEffectsAsync("",this._currentTsWasmEffectType)),this._effectsStatusManager?.setActiveEffects(r,"stop"),this.unsubscribeFromStatUpdates(),this.unsubscribeFromStreamInstanceEvents();const s=JSON.stringify(r),a=this.getUsageDetailsForTelemetry("",s);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.success,additionalDetails:{usageDetails:a}}),this._logger?.info("stopEffects success")}catch(n){const r=new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.STOP_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r);const s=JSON.stringify(this.getEffectsConfigForTelemetry(e)),a=this.getUsageDetailsForTelemetry("",s);this.sendFeatureUsageTelemetry({eventName:aE.acs_calling_media_stream,correlationId:t,operation:_E.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:oE.failure,additionalDetails:{failureReason:r.message,code:r.code,..._b(r),usageDetails:a}})}}async dispose(){const e=async()=>{try{const e=this._internalDeviceManager?.getTsDeviceManager();if(e){let t=await this.startStopAutoGainControl(e,this._activeEffects,!1);t=await this.startStopEchoCancellation(e,t,!1),await this.startStopNoiseSuppression(e,t,!1)}}catch(e){this._logger?.info(`Error stopping effects before disposing: ${e.message}`)}};try{if(this._logger?.info("dispose attempt"),this.disposed)return void this._logger?.info("AudioEffects feature already disposed");await e(),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(e){const t=new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.DISPOSE_FAILED,originalError:e});this._logger?.error(t.message),this.eventEmitter.emit("effectsError",t)}}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}getEffectsSdkVersion(){let e=this._stringForUnknownInput;const t=this.getAnyActiveWasmEffect();return t&&t._internalHandle?.getVersion&&(e=t._internalHandle.getVersion()),this.truncateToMax(e)}getActiveEffectsForTelemetry(){return this.truncateToMax(JSON.stringify(this.activeEffects))}async updateAudioEffectsStatusManager(){if(!this.streamInstance.canStartEffects)return void this._logger?.warn("Cannot update status manager, current source is not supported.");this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const e=MI(this._internalDeviceManager.getTsDeviceManager());if(!this._effectsStatusManager)if(this._effectsStatusManager=this._internalDeviceManager.callStackAudioEffectsStatusManager,this._effectsStatusManager.on("statusChanged",this.effectStatusChangedCallback),this.streamInstance.canStartEffects){const t=e?{autoGainControl:!0,noiseSuppression:!0,echoCancellation:!0}:await(async()=>{const e=await this.streamInstance.getMediaStream(),t=e?.getAudioTracks()?.[0],i=t?.getSettings();return i})();this._effectsStatusManager?.setActiveEffects({autoGainControl:t.autoGainControl?["BrowserAutoGainControl"]:[],echoCancellation:t.echoCancellation?["BrowserEchoCancellation"]:[],noiseSuppression:t.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 HI(this._effectsStatusManager,this._logger,this.streamInstance))}async initializeWasmVqeInStack(e){if(this._wasmVqeInitialized)return void this._logger?.info("WasmVqe initialized already");if(!this._internalDeviceManager)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.FAILED_TO_GET_DM});const t=await e._internalHandle.getEffectProvider();if(!t)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.PROVIDER_UNAVAILABLE});const i=await t.getAudioEffectProvider(),n=this.streamInstance.callStackWasmVqeProvider;if(!n)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.AEC_PROVIDER_MISSING});n.providerValue=i,this._wasmVqeInitialized=!0}getEffectInternalCast(e){if("EchoCancellation"===e?.name&&this.isValidEffectInstance(e))return e;if("DeepNoiseSuppression"===e?.name&&this.isValidEffectInstance(e))return e;throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(e){let t;return("EchoCancellation"===e.name&&e._internalHandle||!("DeepNoiseSuppression"!==e.name||!e._internalHandle))&&(t=e,this.hasValidInternalHandle(t._internalHandle))}hasValidInternalHandle(e){return!!(e.getEffectProvider&&e.dispose&&e.setConfig&&e.handleProcessingError)}updateCurrentTsWasmAudioEffectType(e,t,i){const n=i??this._effectsStatusManager?.getActiveEffects();let r=!!n?.echoCancellation?.includes("EchoCancellation"),s=!!n?.noiseSuppression?.includes("DeepNoiseSuppression");switch(e){case"EchoCancellation":r=t;break;case"DeepNoiseSuppression":s=t}this._previousTsWasmEffectType=this._currentTsWasmEffectType,this._currentTsWasmEffectType=r&&s?16:r?4:s?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 e=>{e.source&&"Audio"!==e.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(e){const t=e._internalHandle.configProvider.config.audioEffects,i=Sy(),n=vy();i?.wasmvqe?.enableVqe&&n?.audioEffects?.enableAudioEffects&&(t.enableAudioEffects=i?.wasmvqe?.enableVqe&&n.audioEffects.enableAudioEffects),e._internalHandle.setConfig(t),this._logger?.info(`Config for audio effects set: ${Ey(t)}`)}async startStopAutoGainControl(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("BrowserAutoGainControl"!==n)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_GAINCONTROL});return await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{autoGainControl:!0})),this._logger?.info("Browser auto gain control started"),this._currentEffects.autoGainControl=n,t.autoGainControl=[n],t}switch(t?.autoGainControl?.[0]??""){case"":case"BrowserAutoGainControl":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{autoGainControl:!1})),this._logger?.info("Browser auto gain control stopped")}return t.autoGainControl=[],this._currentEffects.autoGainControl=void 0,t}catch(e){throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SET_AUTO_GAIN_CONTROL,defaultErrorMessageArgs:[i],originalError:e})}}async startStopEchoCancellation(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("string"==typeof n&&"BrowserEchoCancellation"===n)"EchoCancellation"===t.echoCancellation[0]&&(await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("EchoCancellation",!1,t),t.echoCancellation=[]),await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{echoCancellation:!0})),this._logger?.info("Browser echo cancellation started"),this._currentEffects.echoCancellation=n,t.echoCancellation=[n];else{if("object"!=typeof n)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_ECHO});this._currentEffects.echoCancellation=this.getEffectInternalCast(n),this.setConfigForEffects(this._currentEffects.echoCancellation),await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.echoCancellation.name,!0,t),t.echoCancellation=[this._currentEffects.echoCancellation.name]}return t}switch(t?.echoCancellation?.[0]??""){case"":case"BrowserEchoCancellation":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{echoCancellation:!1})),this._logger?.info("Browser echo cancellation stopped");break;case"EchoCancellation":await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType("EchoCancellation",!1,t)}return t.echoCancellation=[],this._currentEffects.echoCancellation=void 0,t}catch(e){throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SET_ECHO_CANCELLATION,defaultErrorMessageArgs:[i],originalError:e})}}async startStopNoiseSuppression(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("string"==typeof n&&"BrowserNoiseSuppression"===n)"DeepNoiseSuppression"===t.noiseSuppression[0]&&(await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("DeepNoiseSuppression",!1,t),t.noiseSuppression=[]),await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{noiseSuppression:!0})),this._logger?.info("Browser noise cancellation started"),t.noiseSuppression=[n],this._currentEffects.noiseSuppression=n;else{if("object"!=typeof n)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_NOISE_SUPP});this._currentEffects.noiseSuppression=this.getEffectInternalCast(n),this.setConfigForEffects(this._currentEffects.noiseSuppression),await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.noiseSuppression.name,!0,t),t.noiseSuppression=[this._currentEffects.noiseSuppression.name]}return t}switch(t?.noiseSuppression?.[0]??""){case"":case"BrowserNoiseSuppression":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{noiseSuppression:!1})),this._logger?.info("Browser noise suppression stopped");break;case"DeepNoiseSuppression":await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("DeepNoiseSuppression",!1,t)}return t.noiseSuppression=[],this._currentEffects.noiseSuppression=void 0,t}catch(e){throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.SET_NOISE_SUPPRESSION,defaultErrorMessageArgs:[i],originalError:e})}}sendFeatureUsageTelemetry(e){if(this._telemetryLogManager){e.additionalDetails={...e.additionalDetails,callState:this.streamInstance.getCall()?.state,activeEffects:JSON.stringify(this.activeEffects),effectsSdk:{version:this.getEffectsSdkVersion()}};try{const t={correlationId:e.correlationId,mediaType:EE.AudioRaw,streamType:bE.Local,operation:e.operation,timestampInfo:e.timestampInfo||{},kindOfEvent:e.kindOfEvent||"",additionalDetails:e.additionalDetails||"",callId:this.streamInstance.getCall()?.id||"",localParticipantId:this.streamInstance.getLocalParticipantId()||""};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:t})}catch(t){this._logger?.debug(`Unable to send ${e.operation} telemetry`)}}else this._logger?.debug("Telemetry error. Instance is undefined.")}getAnyActiveWasmEffect(){let e=null;for(const t of Object.values(this._currentEffects))t&&"object"==typeof t&&(e=t);return e}getEffectsConfigForTelemetry(e){let t=!1;"boolean"!=typeof e?.autoGainControl&&"boolean"!=typeof e?.echoCancellation&&"boolean"!=typeof e?.noiseSuppression||(t=!0);let i={};return i=t?{autoGainControl:e?.autoGainControl&&"boolean"==typeof e?.autoGainControl?e?.autoGainControl:void 0,echoCancellation:e?.echoCancellation&&"boolean"==typeof e?.echoCancellation?e?.echoCancellation:void 0,noiseSuppression:e?.noiseSuppression&&"boolean"==typeof e?.noiseSuppression?e?.noiseSuppression:void 0}:{autoGainControl:this.getEffectsNameForTelemetry(e?.autoGainControl),echoCancellation:this.getEffectsNameForTelemetry(e?.echoCancellation),noiseSuppression:this.getEffectsNameForTelemetry(e?.noiseSuppression)},Object.keys(i).forEach((e=>{""!==i[e]&&void 0!==i[e]||delete i[e]})),i}getEffectsNameForTelemetry(e){return e?"string"==typeof e?this.truncateToMax(e):e?.name&&"string"==typeof e?.name?this.truncateToMax(e.name):(this._logger?.warn("Invalid effect object found"),this._stringForUnknownInput):""}getUsageDetailsForTelemetry(e,t){const i=`${t?`[${t}]`:""}:${e??""}`;return this.truncateToMax(i)}truncateToMax(e){const t=vy().audioEffects.maxStringLengthForTelemetry;return e.length>t?(this._logger?.info("Truncating audio effects info for telemetry"),e.substring(0,t-2)+".."):e}}$I([WE(),jI("design:type",Function),jI("design:paramtypes",[Object]),jI("design:returntype",Promise)],GI.prototype,"startEffects",null),$I([WE(),jI("design:type",Function),jI("design:paramtypes",[Object]),jI("design:returntype",Promise)],GI.prototype,"stopEffects",null);var qI,zI,WI,KI=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},JI=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class YI{constructor(e){this._calls=new Set,this.canStartEffects=!1;const t=R("ACS-calling");if(this.logger=new _I(t,[()=>`LocalAudioStream for default device with source: ${!!e}`]),this._eventEmitter=new T_(this.logger),this._disposed=!1,!(e instanceof BI||e instanceof MediaStream))throw new le({defaultError:ee.LOCAL_AUDIO_STREAM.WRONG_STREAM_TYPE});if(e instanceof BI&&"Microphone"!==e.deviceType)throw new le({defaultError:ee.LOCAL_AUDIO_STREAM.SOURCE_WRONG_TYPE});this.setSource(e,!0),this._localStreamTelemetryEventSender=new II(this._telemetryLogManager),this._volumeIndicator=new VI(this.logger,"LocalAudioStream",this._telemetryLogManager),this.logger.info("created")}on(e,t){if("audioSourceChanged"!==e)throw new le({defaultError:ee.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("audioSourceChanged"!==e)throw new le({defaultError:ee.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}feature(e){return this._extensibleApi||(this._extensibleApi=new nb(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(e.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(e){this._calls.add(e)}removeCall(e){this._calls.delete(e)}getCall(){for(const e of this._calls)if(e.localAudioStreams.includes(this))return e}getLocalParticipantId(){let e="";const t=this.getCall();return t&&(e=t.tsCall.participantId),e}async getMediaStream(){const e=Mf(),t=+new Date,i={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:_E.getMediaStream,kindOfEvent:oE.attempt,mediaType:EE.AudioRaw,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const i={correlationId:e,mediaType:EE.AudioRaw,operation:_E.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this._mediaStreamSource}if(this._source instanceof BI)try{this._rawStream||(this._rawStream=this._source.deviceManager.getRawDeviceMediaStream(0));const i=await(this._rawStream?.getMediaStream()),n={correlationId:e,mediaType:EE.AudioRaw,operation:_E.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),i}catch(n){const i=new le({defaultError:ee.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM,originalError:n}),r={correlationId:e,operation:_E.getMediaStream,additionalDetails:{failureReason:i.message,code:i.code,..._b(i)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,mediaType:EE.AudioRaw,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),i}const n=new le({defaultError:ee.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM}),r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_E.getMediaStream,additionalDetails:{failureReason:n.message,code:ie,..._b(n)},kindOfEvent:oE.failure,mediaType:EE.AudioRaw,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}async setMediaStream(e){const t=Mf();let i=+new Date;const n={timestampInfo:{attemptTimestamp:i},correlationId:t,operation:_E.setMediaStream,kindOfEvent:oE.attempt,mediaType:EE.AudioRaw,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),!(e instanceof MediaStream)){const e=new le({defaultError:ee.LOCAL_AUDIO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),n={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:t,operation:_E.setMediaStream,additionalDetails:{failureReason:e.message,code:e.code,..._b(e)},kindOfEvent:oE.failure,mediaType:EE.AudioRaw,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}this._mediaStreamSource=new MediaStream(e.getAudioTracks()),this.setSource(this._mediaStreamSource),this._volumeIndicator.dispose();const r={correlationId:t,mediaType:EE.AudioRaw,operation:_E.setMediaStream,timestampInfo:{deltaTimeInMs:+new Date-i},streamType:bE.Local,kindOfEvent:oE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r)}async switchSource(e){const t=+new Date,i=Mf(),n={timestampInfo:{attemptTimestamp:t},correlationId:i,operation:_E.switchSource,kindOfEvent:oE.attempt,mediaType:EE.Audio,streamType:bE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e instanceof BI&&"Microphone"!==e.deviceType){const e=new le({defaultError:ee.LOCAL_AUDIO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:_E.switchSource,additionalDetails:{failureReason:e.message,code:e.code,..._b(e)},kindOfEvent:oE.failure,mediaType:EE.Audio,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}if(this._source===e){const e=new le({defaultError:ee.LOCAL_AUDIO_STREAM.SWITCH_SAME_SOURCE}),n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:_E.switchSource,additionalDetails:{failureReason:e.message,code:e.code,..._b(e)},kindOfEvent:oE.failure,mediaType:EE.Audio,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}try{this._source.deviceManager.selectMicrophone(e),this.setSource(e),this._volumeIndicator.dispose();const n={correlationId:i,mediaType:EE.Audio,operation:_E.switchSource,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:bE.Local,kindOfEvent:oE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n)}catch(e){const n=new le({defaultError:ee.LOCAL_AUDIO_STREAM.UNKNOWN,originalError:e}),r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:_E.switchSource,additionalDetails:{failureReason:n.message,code:n.code,..._b(n)},kindOfEvent:oE.failure,mediaType:EE.Audio,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}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 BI&&!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 e=this.source.deviceManager;return{source:"local",streamType:this.mediaStreamType,deviceType:this.source.deviceType,deviceManagerPermissionState:JSON.stringify({cameraPermission:e.getVideoDevicePermission(),microphonePermission:e.getAudioDevicePermission()}),acsResourceId:e.getAcsResourceId()||"",clientId:e.getClientId()}}getEffectsCurrentStateRecord(){try{const e=this.feature(ub(GI)),t=e.getEffectsSdkVersion();return{activeEffects:e.getActiveEffectsForTelemetry(),effectsSdk:{version:t}}}catch(e){return void this.logger.warn(`Error while getting current effect state on LocalAudioStream for telemetry: ${e}`)}}setSource(e,t=!1){if(e instanceof BI)this._telemetryLogManager=e.deviceManager.telemetryLogManager,this._source=e,this._mediaStreamType="Audio",this._mediaStreamSource=void 0,this._rawStream=void 0,this.canStartEffects=!0;else{try{1===globalThis[Xv]&&(this._telemetryLogManager=globalThis[Zv])}catch(e){this.logger.error("Failed to retrive telemetry logger for localAudioStream")}this._source={name:"CustomMediaStream",id:Mf(),deviceType:"Virtual",isSystemDefault:!1},this._mediaStreamSource=e,this._mediaStreamType="RawMedia",this.canStartEffects=!1}t||this._eventEmitter.emit("audioSourceChanged",{source:this})}}KI([SI,JI("design:type",Object)],YI.prototype,"logger",void 0),KI([ge(ny.Feature),JI("design:type",Function),JI("design:paramtypes",[Object]),JI("design:returntype","function"==typeof(qI="undefined"!=typeof TFeature&&TFeature)?qI:Object)],YI.prototype,"feature",null),KI([pe(ny.GetMediaStream),JI("design:type",Function),JI("design:paramtypes",[]),JI("design:returntype",Promise)],YI.prototype,"getMediaStream",null),KI([pe(ny.SetMediaStream),JI("design:type",Function),JI("design:paramtypes",[MediaStream]),JI("design:returntype",Promise)],YI.prototype,"setMediaStream",null),KI([pe(ny.SwitchSource),JI("design:type",Function),JI("design:paramtypes",[Object]),JI("design:returntype",Promise)],YI.prototype,"switchSource",null),function(e){e[e.JITTER=0]="JITTER",e[e.RTT=1]="RTT",e[e.PACKETS_LOSS=2]="PACKETS_LOSS",e[e.BIT_RATE=3]="BIT_RATE",e[e.BANDWIDTH=4]="BANDWIDTH"}(zI||(zI={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO"}(WI||(WI={}));const QI="Unknown";var ZI,XI;function ew(e){return e?.count.length&&e?.count[0]?function(e,t,i=100){return Math.round((e/t+Number.EPSILON)*i)/i}(e.sum[0],e.count[0]):NaN}function tw(e){return e?.count.length&&e?.count[0]?e.sum[0]:NaN}!function(e){e.Supported="Supported",e.NotSupported="NotSupported",e.Unknown="Unknown"}(ZI||(ZI={})),function(e){e.CompleteTest="CompleteTest",e.StartTest="StartTest",e.DeviceAccess="DeviceAccess",e.DeviceEnumerations="DeviceEnumerations",e.InCallDiagnostics="InCallDiagnostics",e.BrowserSupport="BrowserSupport"}(XI||(XI={}));class iw{constructor(){this._printableObjectAll=!0,this._completeTestInfo={name:"",succeeded:!0},this._diagnosticsTestRunIds=[],this._callMediaStatistics=jT(),this._inCallDiagnostics={connected:!1,diagnostics:{audio:{jitter:QI,packetLoss:QI,rtt:QI},video:{jitter:QI,packetLoss:QI,rtt:QI}},bandWidth:QI},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(e,t,i,n){this._internalCallClient=t,this._mainCallClient=e,this._logger=i,this._telemetryLogManager=n}async getDevices(e,t){let i=[];try{switch(t){case"Speaker":i=await e.getSpeakers();break;case"Microphone":i=await e.getMicrophones();break;default:i=await e.getCameras()}}catch(e){this._logger.warn("Failed to get speakers")}return i}async startTest(e,t){this._sendFeatureUsage("startTest",oE.attempt),this._currentTestRunId=Mf(),this._diagnosticsTestRunIds.push(this._currentTestRunId),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.CompleteTest}}),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.StartTest}});try{this._internalDeviceManager=await this._internalCallClient.getDeviceManager();const e=this._internalCallClient.callAgent,t=await this._mainCallClient.getDeviceManager(),i=await(e?.tsStack?.getDeviceManagerAsync?.());await(i?.selectDevicesAsync?.({speaker:t.selectedSpeaker?.id,microphone:t.selectedMicrophone?.id}));const n=await this._internalCallClient.getDeviceManager(),r={mic:(await this.getDevices(n,"Microphone")).length,speaker:(await this.getDevices(n,"Speaker")).length};this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.StartTest,!0,`Device selection successful. Result: ${Ny(r,this._printableObjectAll)}`)})}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.SET_DEVICE_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.StartTest,!1,"Device selection failed."),additionalDetails:{..._b(t)}}),this._logger.warn(e),this._sendFeatureUsage("startTest",oE.failure),t}try{return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.StartTest,!0,"StartTest succeeded")}),this._sendFeatureUsage("startTest",oE.success),t?{deviceAccess:t.deviceAccess?this.deviceAccess():void 0,deviceEnumeration:t.deviceEnumeration?this.deviceEnumeration():void 0,inCallDiagnostics:t.inCallDiagnostics?this.getInCallDiagnostics(e):void 0,browserSupport:t.browserSupport?this.getBrowserSupport():void 0,callMediaStatistics:t.callMediaStatistics?this.getcallMediaStatistics():void 0,id:this._currentTestRunId}:{deviceAccess:this.deviceAccess(),deviceEnumeration:this.deviceEnumeration(),inCallDiagnostics:this.getInCallDiagnostics(e),browserSupport:this.getBrowserSupport(),callMediaStatistics:this.getcallMediaStatistics(),id:this._currentTestRunId}}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.GET_DIAGNOSTICS_INFO,originalError:e});throw this._logger.error(t.message),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.StartTest,!1,"StartTest failed."),additionalDetails:{..._b(t)}}),this._sendFeatureUsage("startTest",oE.failure),t}}async getBrowserSupport(){let e;this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.BrowserSupport}});try{const t=await this._mainCallClient.getEnvironmentInfoInternal();e={browser:t.isSupportedBrowser?ZI.Supported:ZI.NotSupported,os:t.isSupportedPlatform?ZI.Supported:ZI.NotSupported},this.updateTestInfo(XI.BrowserSupport,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Browser support successful. Result: ${Ny(e,this._printableObjectAll)}`,name:XI.BrowserSupport}})}catch(t){e={browser:ZI.Unknown,os:ZI.Unknown},this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.BrowserSupport,!1,`Browser support failed. Error: ${Ny(t)}`)}),this._logger.error(`Browser support failed: ${t}`)}return new Promise((t=>t(e)))}async renderHiddenVideoElement(e,t){let i,n=e.tsCall,r=n.mediaStreams;try{await new Promise(((e,t)=>{i=n.changed((()=>{void 0!==r[0]&&r[0].length>0&&r[0][0].isAvailable&&(e(),i?.dispose(),this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call mediaStreams successful.",name:XI.InCallDiagnostics}}))})),setTimeout((()=>{this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,"Call mediaStreams failed. Error: Timeout")}),t(new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_STREAM_TIMEOUT}))}),1e3*this._diagnosticsEcsConfig.CALL.MEDIASTREAM_TIMEOUT_IN_SEC)}));let s=n.mediaStreams[0][0],a=document.getElementById("_hiddenSelfRemoteStream");a&&a.remove(),a=document.createElement("div"),a.id="_hiddenSelfRemoteStream",a.style.position="relative",a.style.height="0px",a.style.width="0px";const o=document.createElement("div");o.style.position="absolute",o.style.height=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.heigth+"px",o.style.width=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.width+"px",o.style.bottom="0px",o.style.left="-2000px",a.appendChild(o),document.getElementsByTagName("body")[0].appendChild(a),this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Video element rendering successful. CallId: ${e.id}, localParticipantId: ${t}`,name:XI.InCallDiagnostics}}),await s.start(o)}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,`Call mediaStreams failed. Error: ${Ny(e)}`)}),this._logger.warn("Failed to render hidden video element")}}sineWaveAudioStream(){const e=new window.AudioContext,t=e.createMediaStreamDestination(),i=e.createOscillator();i.type="sine",i.frequency.value=500,i.connect(t),i.start();const{stream:n}=t;return new YI(n)}async receiveAndPlayCallAudio(e,t){try{const i=new window.AudioContext,n=new MediaStream;i.createMediaStreamSource(n).connect(i.destination),this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call mediaStreams audio track succeeded. CallId: ${e.id}, localParticipantId: ${t}`,name:XI.InCallDiagnostics}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,`Call mediaStreams audio track failed. Error: ${Ny(e)}`)}),this._logger.warn("Failed to send audio to call.")}}async getcallMediaStatistics(){return this._callMediaStatistics.promise}setEcsConfig(){this._diagnosticsEcsConfig=vy()?.calling?.callDiagnostics}async getInCallDiagnostics(e){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.InCallDiagnostics}}),this.setEcsConfig();const t={groupId:this._diagnosticsEcsConfig.CALL.GROUP_ID},i=await this.getDevices(this._internalDeviceManager,"Camera");let n,r="";0!==i.length&&(n=[new UI(i[0])]);const s={videoOptions:{localVideoStreams:n},audioOptions:{muted:!1,localAudioStreams:[this.sineWaveAudioStream()]}};let a;try{a=await(this._mainCallClient.callAgent?.getExistingCallAgentWithToken(e)),a?this._internalCallClient.setCallAgent(a):(this._isCreatingNewCallAgent=!0,await this._internalCallClient.createCallAgent(e)),this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Create CallAgent successful.",name:XI.InCallDiagnostics}})}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.GET_CALL_AGENT,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,t.message),additionalDetails:{..._b(t)}}),this._logger.error(t.message),t}const o=this._internalCallClient.callAgent?.join(t,s);if(o){try{await this.waitCallConnected(o),r=o.tsCall.participantId,this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call connected successfully",name:XI.InCallDiagnostics}})}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.CONNECT_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,t.message),additionalDetails:{..._b(t)}}),this._logger.error(t.message),t}try{this.updateTestInfo(XI.InCallDiagnostics,!0),await this.renderHiddenVideoElement(o,r)}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.RENDER_VIDEO,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,t.message),additionalDetails:{..._b(t)}}),t}this.receiveAndPlayCallAudio(o,r);const t=o.feature(lb(nI,{activationEvent:"OnExtendedObjectConstructor"}));this._callMediaStatistics.resolve(t),t.createCollector({aggregationInterval:this._diagnosticsEcsConfig.CALL.AGGREGATION.INTERVAL,dataPointsPerAggregation:this._diagnosticsEcsConfig.CALL.AGGREGATION.DATAPOINTS}).on("summaryReported",(e=>this.gatherCallStatistics(e)));try{await GT(1e3*this._diagnosticsEcsConfig.CALL.DURATION_IN_SEC),await o.hangUp({forEveryone:!0}),this.updateTestInfo(XI.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call hangup successful. Result: ${Ny(this._inCallDiagnostics,this._printableObjectAll)}`,name:XI.InCallDiagnostics}})}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.HANGUP_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.InCallDiagnostics,!1,t.message),additionalDetails:{..._b(t)}}),this._logger.error(t.message),t}this.dispose()}return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:this._completeTestInfo.succeeded,result:this._completeTestInfo.result||"InCallDiagnostics succeeded.",name:XI.CompleteTest}}),this._inCallDiagnostics}async waitCallConnected(e){await new Promise((async(t,i)=>{e.on("stateChanged",(()=>{"Connected"==e.state&&(this._inCallDiagnostics.connected=!0,t()),"Disconnected"==e.state&&i("Call disconnected")}));const n=this._diagnosticsEcsConfig.CALL.CONNECT_TIMEOUT_IN_SEC;await GT(1e3*n),i(new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.CALL_CONNECT_TIMEOUT,defaultErrorMessageArgs:[n]}))}))}qualityGrade(e,t,i){return e<=t?"Good":e>=i?"Bad":"Average"}bandwidthQualityGrade(e,t,i){return e>=t?"Good":e<=i?"Bad":"Average"}getQualityGradeForMetric(e,t,i){switch(e){case zI.JITTER:return i===WI.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.JITTER.GOOD,this._diagnosticsEcsConfig.AUDIO.JITTER.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.JITTER.GOOD,this._diagnosticsEcsConfig.VIDEO.JITTER.AVERAGE);case zI.RTT:return i===WI.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.RTT.GOOD,this._diagnosticsEcsConfig.AUDIO.RTT.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.RTT.GOOD,this._diagnosticsEcsConfig.VIDEO.RTT.AVERAGE);case zI.PACKETS_LOSS:return i===WI.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.AVERAGE);case zI.BANDWIDTH:return this.bandwidthQualityGrade(t,this._diagnosticsEcsConfig.BANDWIDTH.GOOD,this._diagnosticsEcsConfig.BANDWIDTH.AVERAGE);default:return QI}}gatherCallStatistics(e){try{const t=e.audio.receive.length?e.audio.receive[0]:void 0,i=e.audio.send.length?e.audio.send[0]:void 0,n=e.video.receive.length?e.video.receive[0]:void 0,r=e.video.send.length?e.video.send[0]:void 0,s=e.transports.length?e.transports[0]:void 0;this._diagnosticsMediaTelemetry.jitter.audio.inbound=ew(t?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.audio.outbound=ew(i?.jitterInMs?.aggregation);const a=Math.max(this._diagnosticsMediaTelemetry.jitter.audio?.inbound,this._diagnosticsMediaTelemetry.jitter.audio?.outbound);this._inCallDiagnostics.diagnostics.audio.jitter=this.getQualityGradeForMetric(zI.JITTER,a,WI.AUDIO),this._diagnosticsMediaTelemetry.rtt.audio=ew(i?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.audio.rtt=this.getQualityGradeForMetric(zI.JITTER,this._diagnosticsMediaTelemetry.rtt.audio,WI.AUDIO),this._diagnosticsMediaTelemetry.packets.audioSent=tw(i?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioSentLost=tw(i?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceived=tw(t?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceivedLost=tw(t?.packetsLostPerSecond?.aggregation);const o=this._diagnosticsMediaTelemetry.packets.audioSent-this._diagnosticsMediaTelemetry.packets.audioSentLost,l=this._diagnosticsMediaTelemetry.packets.audioReceived-this._diagnosticsMediaTelemetry.packets.audioReceivedLost,c=Math.max(o,l)/this._diagnosticsMediaTelemetry.packets.audioSent*100;this._inCallDiagnostics.diagnostics.audio.packetLoss=this.getQualityGradeForMetric(zI.PACKETS_LOSS,c,WI.AUDIO),this._diagnosticsMediaTelemetry.jitter.video.inbound=ew(n?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.video.outbound=ew(r?.jitterInMs?.aggregation);const d=Math.max(this._diagnosticsMediaTelemetry.jitter.video.inbound,this._diagnosticsMediaTelemetry.jitter.video.outbound);this._inCallDiagnostics.diagnostics.video.jitter=this.getQualityGradeForMetric(zI.JITTER,d,WI.VIDEO),this._diagnosticsMediaTelemetry.rtt.video=ew(r?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.video.rtt=this.getQualityGradeForMetric(zI.RTT,this._diagnosticsMediaTelemetry.rtt.video,WI.VIDEO),this._diagnosticsMediaTelemetry.packets.videoSent=tw(r?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoSentLost=tw(r?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceived=tw(n?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceivedLost=tw(n?.packetsLostPerSecond?.aggregation);const u=this._diagnosticsMediaTelemetry.packets.videoSent-this._diagnosticsMediaTelemetry.packets.videoSentLost,h=this._diagnosticsMediaTelemetry.packets.videoReceived-this._diagnosticsMediaTelemetry.packets.videoReceivedLost,g=Math.max(u,h)/this._diagnosticsMediaTelemetry.packets.videoSent*100;this._inCallDiagnostics.diagnostics.video.packetLoss=this.getQualityGradeForMetric(zI.PACKETS_LOSS,g,WI.VIDEO),this._diagnosticsMediaTelemetry.bandWidth=ew(s?.availableOutgoingBitrate?.aggregation),this._inCallDiagnostics.bandWidth=this.getQualityGradeForMetric(zI.BANDWIDTH,this._diagnosticsMediaTelemetry.bandWidth,WI.AUDIO)}catch(e){const t=new le({defaultError:ee.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_MEDIASTATS,originalError:e});this._logger.error("Failed to get audio call media stats:",t.message),this._callMediaStatistics.reject(t)}}async deviceAccess(){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.DeviceAccess}});const e=this._internalDeviceManager.askDevicePermission({audio:!0,video:!0});try{const t=await e;this.updateTestInfo(XI.DeviceAccess,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Access successful. Result: ${Ny(t,this._printableObjectAll)}`,name:XI.DeviceAccess}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.DeviceAccess,!1,"Device Access failed.")})}return e}async deviceEnumeration(){const e={microphone:QI,camera:QI,speaker:QI};this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:XI.DeviceEnumerations}});try{const t=0!==(await this.getDevices(this._internalDeviceManager,"Microphone")).length,i=0!==(await this.getDevices(this._internalDeviceManager,"Camera")).length,n=0!==(await this.getDevices(this._internalDeviceManager,"Speaker")).length;e.microphone=t?"Available":"NotAvailable",e.camera=i?"Available":"NotAvailable",e.speaker=n?"Available":"NotAvailable",this.updateTestInfo(XI.DeviceEnumerations,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Enumeration successful. Result: ${Ny(e,this._printableObjectAll)}`,name:XI.DeviceEnumerations}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(XI.DeviceEnumerations,!1,"Device Enumeration failed.")}),this._logger.error(`Couldn't find mic, camera, or speaker: ${e}`)}return e}telemetryLogAttemptEvents(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_diagnostics_attempt,tenant:xv,properties:{name:e.testAttemptDetails.name,diagnosticsTestRunId:e.diagnosticsTestRunId}})}telemetryLogResultEvents(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_diagnostics_result,tenant:xv,properties:{name:e.testResultDetails.name,diagnosticsTestRunId:e.diagnosticsTestRunId,succeeded:e.testResultDetails.succeeded,result:e.testResultDetails.result,additionalDetails:e.additionalDetails||{}}})}updateTestInfo(e,t,i){return this._completeTestInfo.succeeded&&(this._completeTestInfo={succeeded:t,name:e,result:i}),{succeeded:t,name:e,result:i||""}}_sendFeatureUsage(e,t){gb({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._isCreatingNewCallAgent&&this._internalCallClient.callAgent?.dispose()}}class nw{constructor(e,t){this._debounce=void 0,this._updateFunction=e,this._timeout=t}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 rw{constructor(e,t,i,n,r,s){this._isReceiving=!1,this._mediaStreamType="Video",this._renderers=[],this._disposed=!1,this._size={height:0,width:0},this._setType=e=>{0===e.type?this._mediaStreamType="Video":1===e.type?this._mediaStreamType="ScreenSharing":2===e.type&&(this._mediaStreamType="LiveStream")},this._disposeRenderer=e=>{this.logger.log("disposing renderer");try{e.dispose(AE.Internal_RemoteVideoStreamDisposed),this.logger.log("renderer disposed")}catch(e){this.logger.log("failed to dispose renderer")}},this.tsStream=e,this._setType(this.tsStream),this.logger=t.createChild((()=>`Stream:{id=${this.tsStream.id}}:{type=${this._mediaStreamType}}`)),this.telemetryLogManager=r,this.kind=s,this._eventEmitter=new T_(this.logger),this.call=i,this._tsParticipantId=n,this.sendRemoteVideoStreamTelemetry(),this._debounceSize=this.createDebounceSize(),this._debounceIsReceiving=new nw((()=>{const e=this._renderers?.filter((e=>!!e?.isRendering)).length>0;this._isReceiving!==e&&(this._isReceiving=e,this.logger.info(`isReceiving changed to ${this._isReceiving}`),this._eventEmitter.emit("isReceivingChanged"),this.sendRemoteVideoStreamTelemetry())}),vy().rendering.remoteVideo.debounceTimeout),this._registeredViewIdsMaxLength=vy().rendering.remoteVideo.registeredViewIdsMaxLength,this.logger.info("created")}on(e,t){if("sizeChanged"!==e&&"isReceivingChanged"!==e)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("sizeChanged"!==e&&"isReceivingChanged"!==e)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}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(e){this._renderers.push(e),this.logger.info(`Renderer registered, view id: ${e.viewId}`)}unregisterRenderer(e){const t=this._renderers.indexOf(e);-1!==t&&(this._renderers.splice(t,1),this.logger.info(`Renderer un-registered, view id: ${e.viewId}`))}dispose(){this.logger.log("dispose"),this._disposed?this.logger.log("already disposed"):(this._disposed=!0,this._streamChangedHandler&&this._streamChangedHandler.dispose(),this._renderers.forEach((e=>this._disposeRenderer(e))),this._renderers=[],this._eventEmitter.removeAllListeners())}getRegisteredViewIds(){let e=this._renderers.map((e=>e.viewId));return this._registeredViewIdsMaxLength&&(e=e.slice(0,this._registeredViewIdsMaxLength)),e.join(", ")}sendRemoteVideoStreamTelemetry(){this.call.stats.recordEvent({name:sE.remote_stream,callId:this.call.id,localParticipantId:this.call.tsCall.participantId,data:{...this.getStreamMetadata()}})}createDebounceSize(){return new nw((()=>{let e={height:0,width:0};this._renderers?.forEach((t=>{t?.isRendering&&t.size.height>e.height&&t.size.width>e.width&&(e.height=t.size.height,e.width=t.size.width)}),vy().rendering.remoteVideo.debounceTimeout),this._size.height===e.height&&this._size.width===e.width||(this._size.height=e.height,this._size.width=e.width,this.logger.info(`stream size changed to { height: ${this._size.height}, width: ${this._size.width} }`),this._eventEmitter.emit("sizeChanged"),this.sendRemoteVideoStreamTelemetry())}),vy().rendering.remoteVideo.debounceTimeout)}}class sw{constructor(e){this._statsInfo=e,this._originalValues={},this._aggregateValues={}}isDiffMethod(e){return"diff"==e||"last2"==e||"rate"===e}addStats(e,t){const i=this._statsInfo[e];let n=this._originalValues[e];if(void 0===n&&(n={raw:[],calc:[],lastTime:Date.now(),beginTime:Date.now()},this._originalValues[e]=n),this.isDiffMethod(i.calculation_method)){n.raw.push(t);const e=Date.now(),r=n.lastTime;n.lastTime=e,n.raw.length>1?(t=n.raw[n.raw.length-1]-n.raw[n.raw.length-2],"rate"===i.calculation_method&&(t=t/(e-r)*1e3),void 0!==i.multiplier&&(t*=i.multiplier),!0===i.integer&&(t|=0),n.calc.push(t)):"rate"===i.calculation_method&&(t=0)}else void 0!==i.multiplier&&"number"==typeof t&&(t*=i.multiplier),!0===i.integer&&(t|=0),n.raw.push(t);return t}aggregate(){const e={};for(const[t,i]of Object.entries(this._originalValues)){const n=this._statsInfo[t];if(void 0===n||!1===n.show)continue;this.isDiffMethod(n.calculation_method)&&i.raw.length>0&&(e[t]={raw:[i.raw[i.raw.length-1]],calc:[],lastTime:i.lastTime,beginTime:0});let r=this._aggregateValues[t];void 0===r&&(r={raw:[],timestamp:new Date(i.beginTime)},n.aggregation_needed&&(r.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[t]=r);const s=i.calc?.length?i.calc:i.raw;let a=s;if(n.aggregation_needed&&r.aggregation){const e=s.filter((e=>"number"==typeof e&&!isNaN(e)));r.aggregation.count.push(e.length),r.aggregation.sum.push(__(e)),r.aggregation.max.push(E_(e)),r.aggregation.min.push(b_(e)),a=e}n.raw_data_reduction&&a.length>0&&(r.reduced=r.reduced||[],r.reduced.push(a[a.length-1])),a.forEach((e=>r.raw.push(e)))}this._originalValues=e}popAggregates(){const e={};for(const[t,i]of Object.entries(this._aggregateValues))e[this._statsInfo[t].name??t]=i;return this._aggregateValues={},e}}class aw{constructor(e,t,i){if(this._tsCall=e,this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=new Map,i.aggregationInterval<1)throw new le({defaultError:ee.FEATURES.LIVE_STREAM.INVALID_AGGREGATION_INTERVAL_RANGE});if(i.dataPointsPerAggregation<1)throw new le({defaultError:ee.FEATURES.LIVE_STREAM.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._logger=t.createChild("LiveStreamStatsCollector"),this._eventEmitter=new T_(this._logger,{enableLogEmit:!1}),this._callStateChanged=jT(),this._statsPoller=i.statsPoller,this._statsInfo=i.statsInfo,this._aggregationInterval=i.aggregationInterval,this._dataPointsPerAggregation=i.dataPointsPerAggregation,this._isInternal=i.isInternal,this._dataEventListener=e=>{void 0!==e&&this._processData(e)},this._statsPoller.on("data",this._dataEventListener);const n=[3,10];let r=n.includes(this._tsCall.state);this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{r!==n.includes(this._tsCall.state)&&(r=!r,this._callStateChanged.resolve(r))})),this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}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(e){const t={},i=Object.keys(e);0!==i.length&&(i.forEach((i=>{const n=e[i],r={};let s=this._calculators.get(i);s||(s=new sw(this._statsInfo),this._calculators.set(i,s));for(const[e,t]of Object.entries(n)){const i=this._statsInfo[e];if(i&&!1!==i.show&&(this._isInternal||!i.is_internal)){const n=s.addStats(e,t);r[i.name??e]=n}}t[i]=r})),Object.keys(t).length>0&&this._eventEmitter.emit("sampleReported",t))}async _run(){let e=0;const t=e=>(Object.keys(e).forEach((t=>{e[t].reduced&&!this._isInternal&&delete e[t].reduced})),e),i=()=>{if(0===this._calculators.size||0===e)return;const i=[],n={};this._calculators.forEach(((e,r)=>{const s=t(e.popAggregates());0===Object.keys(s).length?i.push(r):(s.reduced&&!this._isInternal&&delete s.reduced,n[r]=s)}));try{this._eventEmitter.emit("summaryReported",n)}catch(e){this._logger.error(`summary event: ${e}`)}i.forEach((e=>{this._calculators.delete(e)})),e=0},n=[3,10];let r=1e3*this._aggregationInterval;for(;!this._disposed;){if(n.includes(this._tsCall.state)){r>0&&await WT((()=>this._callStateChanged.promise),r).catch((e=>{}));const t=Date.now();this._calculators.size>0&&(this._calculators.forEach((e=>{e.aggregate()})),e++,e===this._dataPointsPerAggregation&&i());const n=Date.now();r=t+1e3*this._aggregationInterval-n}else i(),this._calculators.clear(),await this._callStateChanged.promise.catch((e=>{})),r=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=jT())}i()}}class ow extends N_{constructor(e,t,i,n){super(e,t.createChild("LiveStreamStatsPoller"),i.liveStreamStats.fetchInterval,i.liveStreamStats.pollingMethod,i.liveStreamStats.activeState),this._liveStreams=n}async getStats(){const e={};return this._liveStreams.forEach(((t,i)=>{try{const i=t.tsStream.getStats();if(i){const t=i.id.toString(),n={id:t};"number"==typeof i.player_downloadBitrate&&(n.videoBitrate=i.player_downloadBitrate),"number"==typeof i.player_audioDownloadBitrate&&(n.audioBitrate=i.player_audioDownloadBitrate),"number"==typeof i.player_totalDownloadedBytes&&(n.downloadBitrate=i.player_totalDownloadedBytes,n.totalDownloadBytes=i.player_totalDownloadedBytes),"number"==typeof i.player_videoBufferLength&&(n.bufferLengthInMs=Math.round(1e3*i.player_videoBufferLength)),void 0!==i.player_mediaHeight&&(n.videoHeight=i.player_mediaHeight),void 0!==i.player_mediaWidth&&(n.videoWidth=i.player_mediaWidth),void 0!==i.player_playerHeight&&(n.playerHeight=i.player_playerHeight),void 0!==i.player_playerWidth&&(n.playerWidth=i.player_playerWidth),"number"==typeof i.player_mediaDelay&&(n.mediaDelayInMs=Math.round(1e3*i.player_mediaDelay)),"number"==typeof i.player_currentPlayPosition&&(n.currentPlayPosition=Math.round(1e3*i.player_currentPlayPosition)/1e3),e[t]=n}}catch(e){this._logger.error(`fetch live stream stats failed: ${e}`)}})),Object.keys(e).length>0?e:void 0}}class lw{constructor(e,t,i){this._tsCall=e,this._telemetryLogManager=t,this._config=i}log(e){Object.entries(e).forEach((([e,t])=>{const i={id:e},n={id:e};if(Object.entries(t).forEach((([e,t])=>{const r=e,s={};if(this._config.dataToSend.raw){const e={};t?.timestamp&&(e.timestamp=t.timestamp),t?.raw&&(e.raw=t?.raw),void 0===e.raw&&delete n[r],n[r]=e}void 0!==t?.aggregation?(t?.timestamp&&(s.timestamp=t?.timestamp),this._config.dataToSend.min&&(s.min=t?.aggregation.min),this._config.dataToSend.max&&(s.max=t?.aggregation.max),this._config.dataToSend.sum&&(s.sum=t?.aggregation.sum),this._config.dataToSend.count&&(s.count=t?.aggregation.count),t?.aggregation.sum&&t?.aggregation.count&&(s.average=__(t?.aggregation.sum)/__(t?.aggregation.count))):(t?.timestamp&&(s.timestamp=t.timestamp),t?.reduced?s.raw=t?.reduced:void 0!==t?.raw&&(s.raw=t?.raw)),i[r]=s})),Object.keys(i).length>1){const e={stats:i,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamStatsEvent(e)}if(this._config.dataToSend.raw&&Object.keys(n).length>1){const e={stats:n,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamRawStatsEvent(e)}}))}_sendLiveStreamStatsEvent(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_livestream_stats,tenant:xv,properties:e})}_sendLiveStreamRawStatsEvent(e){this._telemetryLogManager.sendEvent({name:aE.acs_calling_livestream_raw_stats,tenant:xv,properties:e})}}class cw{constructor(e,t,i,n){this._logger=t,this._collectors=[],this._disposed=!1,this._externalStatsInfo={};const r=vy(),s=r.telemetry.liveStreamStatsConfig;this._config=r.liveStreamStats,this._tsCall=e.tsCall,this._statsPoller=new ow(e,this._logger,r,n);const a={...vS,...s.additionalStats};if(Object.entries(a).filter((([,e])=>!e.is_internal)).forEach((([e,t])=>{this._externalStatsInfo[e]=t})),s.enabled){const e=new aw(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:s.aggregationInterval,dataPointsPerAggregation:s.dataPointsPerAggregation,statsInfo:a,isInternal:!0}),t=new lw(this._tsCall,i,s);e.on("summaryReported",(e=>{t.log(e)})),this._collectors.push(e)}}createStatsCollector(e){if(this._disposed)throw new le({defaultError:ee.FEATURES.LIVE_STREAM.DISPOSED});const t=this._config,i=new aw(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:e?.aggregationInterval??t.aggregationInterval,dataPointsPerAggregation:e?.dataPointsPerAggregation??t.dataPointsPerAggregation,statsInfo:this._externalStatsInfo,isInternal:!1});return i.on("dispose",(()=>{this._collectors=this._collectors.filter((e=>e!==i))})),this._collectors.push(i),i}dispose(){this._disposed||(this._disposed=!0,this._collectors.forEach((e=>{e.dispose()})))}}class dw{constructor(e,t){this._featureName=e,this._targetBotIds=t,this._streamIdToStreamMap=new Map}initialize(e,t,i,n,r){this._logger=r.createChild((()=>`${this._featureName}::Call(id='${e.callId}')`)),this._telemetryLogManager=n,this._call=i,this._tsCall=e,this._callAgent=t,this.observeBotParticipantsAlreadyInCall(),this._tsCall.on("participantAdded",(async e=>{this.observeBotParticipantJustJoinedCall(e)})),this._tsCall.on("participantRemoved",(async e=>{this.removeStreamOfTheBotJustRemovedFromCall(e)}))}disposeAllBotStreams(){this._streamIdToStreamMap.forEach((e=>e.dispose())),this._streamIdToStreamMap.clear()}updateBotIds(e){this._targetBotIds=e}observeBotParticipantsAlreadyInCall(){this._tsCall.participants.forEach((e=>{this.isExpectedBotParticipant(e)&&(this._logger.info(`${this._featureName} Bot already in the call`),this.observeBotParticipant(e))}))}observeBotParticipantJustJoinedCall(e){this.isExpectedBotParticipant(e)&&(this._logger.info(`${this._featureName} Bot added`),this.observeBotParticipant(e))}removeStreamOfTheBotJustRemovedFromCall(e){if(this.isExpectedBotParticipant(e)){this._logger.info(`${this._featureName} Bot removed`);const t=[];this.removeAllStreams(e,t),this.checkVideoStreamAddedOrRemoved([],t)}}observeBotParticipant(e){e.changed((()=>{this._logger.info(`${this._featureName} Bot - changed event triggered. state: ${e.state}`),this._mapStreams(e)})),this._logger.info(`Composition Bot state: ${e.state}`),this._mapStreams(e)}_mapStreams(e){const t=[],i=[],n=n=>{if(e)if(HS(e.streams&&e.streams[n])){let r=e.streams[n];this._logger.log(`Stream Type: ${n}`),r.forEach((i=>{if(void 0===i.id&&(i.id=-1),!this._streamIdToStreamMap.get(i.id)){const n=this.createConcreteVideoStream(i,e.id);this._logger.log(`${this._featureName} stream created, type==${n.mediaStreamType} id=${i.id}`),t.push(n)}})),this._streamIdToStreamMap.forEach((t=>{t.tsParticipantId!==e.id||r.some((e=>e.id===t.id))||i.push(t)}))}else this.removeAllStreams(e,i)};this.getStreamTypes().forEach((e=>n(e))),this.checkVideoStreamAddedOrRemoved(t,i)}removeAllStreams(e,t){this._streamIdToStreamMap.forEach((i=>{i.tsParticipantId===e.id&&t.push(i)}))}checkVideoStreamAddedOrRemoved(e,t){if(e.length>0||t.length>0){const i=e=>{this._streamIdToStreamMap.set(e.id,e)},n=e=>{const t=this._streamIdToStreamMap.get(e.id);t&&(this._logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._streamIdToStreamMap.delete(e.id),t.dispose())};e.forEach(i),t.forEach(n),this.emitVideoStreamsUpdatedEvent({added:e,removed:t})}}isExpectedBotParticipant(e){return this._targetBotIds.includes(e.id)}}class uw extends dw{constructor(e,t){super(t,vy().calling.liveStreamingBotIds),this._eventEmitter=e}initialize(e,t,i,n,r){super.initialize(e,t,i,n,r),this._statsManager=new cw(i,r,n,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 e=this._participantCount;this._participantCount=this._tsCall.participantCounts.streamingClients,this._logger.log(`tsCall participantCount changed from ${e} to ${this._participantCount}`),this._eventEmitter.emit("participantCountChanged")}}))}dispose(){super.disposeAllBotStreams(),this._statsManager.dispose()}createStatsCollector(e){return this._statsManager.createStatsCollector(e)}get liveStreams(){return[...this._streamIdToStreamMap.values()].map((e=>e))}get streamingClientCount(){return this._participantCount??0}createConcreteVideoStream(e,t){return new hw(e,this._logger,this._call,this._callAgent,t,this._telemetryLogManager)}getStreamTypes(){return[2]}emitVideoStreamsUpdatedEvent(e){return this._eventEmitter.emit("liveStreamsUpdated",e)}}class hw extends rw{constructor(e,t,i,n,r,s){super(e,t,i,r,s,"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 gw extends dw{constructor(e,t){super(t,vy().calling.composedStreamBotIds),this._eventEmitter=e}initialize(e,t,i,n,r){super.initialize(e,t,i,n,r)}dispose(){super.disposeAllBotStreams()}get composedStreams(){return[...this._streamIdToStreamMap.values()].map((e=>e))}createConcreteVideoStream(e,t){return new pw(e,this._logger,this._call,this._callAgent,t,this._telemetryLogManager)}getStreamTypes(){return[0]}emitVideoStreamsUpdatedEvent(e){return this._eventEmitter.emit("composedStreamsUpdated",e)}}class pw extends rw{constructor(e,t,i,n,r,s){super(e,t,i,r,s,"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 mw{constructor(e){this._tsCall=e,this._activeParticipantMris=new Set,this._participantMriToSourceId=new Map,this._sourceIdToParticipantMri=new Map,this._sourceIdToParticipantId=new Map,this._listenerHandles=[],this._eventEmitter=new OE.EventEmitter,this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e),this._eventEmitter.emit("participantAdded",e.id)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._activeParticipantMris.has(e.id)&&this._updateMapping(e)&&this._eventEmitter.emit("participantUpdated",e.id)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._activeParticipantMris.delete(e.id),this._removeMapping(e),this._eventEmitter.emit("participantRemoved",e.id)}))),this._tsCall.participants.forEach((e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))}_updateMapping(e){const t=e.id,i=[];e.endpoints?.endpointDetails?.forEach((e=>{const t=e.mediaStreams?.find((e=>"data"===e.type));t&&(i.push(t.sourceId),this._sourceIdToParticipantId.set(t.sourceId,e.participantId))}));const n=this._participantMriToSourceId.get(t);return i.sort(),!Z.isEqual(i,n)&&(this._participantMriToSourceId.set(t,i),i.forEach((e=>{this._sourceIdToParticipantMri.set(e,t)})),!0)}_removeMapping(e){const t=e.id,i=this._participantMriToSourceId.get(t)||[];this._participantMriToSourceId.delete(t),i.forEach((e=>{this._sourceIdToParticipantMri.delete(e),this._sourceIdToParticipantId.delete(e)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}findParticipantMri(e){let t=this._sourceIdToParticipantMri.get(e);return void 0===t&&this.isP2P()&&this._tsCall.participants.length&&(t=this._tsCall.participants[0].id),t}findParticipantId(e){let t=this._sourceIdToParticipantId.get(e);if(void 0===t&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const e=this._tsCall.participants[0].endpoints?.endpointDetails[0];t=e.participantId}return t}findSourceIds(e){return this._participantMriToSourceId.get(e)??[]}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._participantMriToSourceId.clear(),this._sourceIdToParticipantMri.clear(),this._sourceIdToParticipantId.clear(),this._listenerHandles.forEach((e=>e.dispose())),this._eventEmitter.removeAllListeners()}}const fw=2147483648,vw=65535,Sw=4294967295;function yw(e,t){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[t,e]})}function Cw(e,t){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_TYPE,defaultErrorMessageArgs:[e,t]})}function Tw(e,t){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_VALUE,defaultErrorMessageArgs:[e,t]})}function Ew(){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.NO_AVAILABLE_CHANNEL_ID})}function bw(){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.INVALID_CHANNEL_ID})}function _w(){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.TOO_MANY_PARTICIPANTS})}function Iw(){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.NO_AVAILABLE_UNRELIABLE_CHANNEL})}function ww(){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.TRAFFIC_LIMITED})}function Aw(e){return e?.message??"Unknown"}function Pw(e,t,i){const n=i.value;return i.value=function(...e){try{return n?.apply(this,e)}catch(e){throw this?._logger?.error(`${t}: ${Aw(e)}`),e}},i}class Rw{constructor(){this._firstByte=0,this._channelVersion=0,this._channelId=0,this._sequenceNumber=0}static parse(e){if(e.length<Rw.headerLength)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.INVALID_MSG_LENGTH});const t=new DataView(e.buffer),i=t.getUint8(0),n=t.getUint8(1),r=t.getUint16(2),s=t.getUint32(4),a=e.slice(Rw.headerLength),o=new Rw;return o._firstByte=i,o._channelVersion=n,o._channelId=r,o._sequenceNumber=s,o._data=a,o._serializedData=e,o}static create(e,t,i,n){const r=new Rw,s=new Uint8Array(Rw.headerLength+n.length),a=new DataView(s.buffer);return t&=255,e&=65535,i>>>=0,a.setUint8(0,0),a.setUint8(1,t),a.setUint16(2,e),a.setUint32(4,i),s.set(n,Rw.headerLength),r._channelVersion=t,r._channelId=e,r._sequenceNumber=i,r._data=n,r._serializedData=s,r}get channelId(){return this._channelId}set channelId(e){this._channelId=e}get channelVersion(){return this._channelVersion}get sequenceNumber(){return this._sequenceNumber}get data(){return this._data}get serializedData(){return this._serializedData}isInternal(){return!!(128&this._firstByte)}isEmpty(){return 0===this._data.length}}var Mw;Rw.headerLength=8,function(e){e[e.Initializing=0]="Initializing",e[e.Initialized=1]="Initialized",e[e.Started=2]="Started",e[e.Stopped=3]="Stopped",e[e.Destroyed=4]="Destroyed"}(Mw||(Mw={}));class Dw{constructor(e,t){this._eventEmitter=new OE.EventEmitter,this._state=Mw.Initializing,this._tsCall=e,this._dataId=t}async initialize(){const e={onStarted:async(e,t,i)=>{this._dataSendFunction=t,this._getStats=i,this._state=Mw.Started,this._eventEmitter.emit("stateChanged",this._state)},onStopped:async e=>{this._dataSendFunction=void 0,this._getStats=void 0,this._state=Mw.Stopped,this._eventEmitter.emit("stateChanged",this._state)},onDataReceived:async(e,t,i)=>{const n={sourceId:i,data:t};this._eventEmitter.emit("message",n)}};await(this._tsCall.dataChannelAdapter?.addHandler(this._dataId,e)),this._state<Mw.Initialized&&(this._state=Mw.Initialized)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}send(e,t){return this._dataSendFunction?this._dataSendFunction(e,t):Promise.reject(new le({defaultError:ee.FEATURES.DATA_CHANNEL.SENDER_NOT_READY}))}getStats(){return this._getStats?this._getStats():Promise.resolve({bufferSize:0,remainingBytes:0,remainingPackets:0})}get state(){return this._state}dispose(){if(this._state===Mw.Destroyed)return;const e=this._state;this._state=Mw.Destroyed,this._dataSendFunction=void 0,this._getStats=void 0,e!==Mw.Initializing&&this._tsCall.dataChannelAdapter?.removeHandler(this._dataId).catch(My),this._eventEmitter.emit("stateChanged",this._state),this._eventEmitter.removeAllListeners()}}class kw{constructor(e,t,i){const n=e.dataId;this._logger=i.createChild(`DataChannelProcessor(${n})`),this._eventEmitter=new T_(this._logger,{enableLogOn:!1,enableLogOff:!1,enableLogOnce:!1,enableLogEmit:!1}),this._bufferFullErrorMessage=`dataId ${n} send queue is full`,this._dataChannelAdapter=new Dw(t,n),this._dataChannelAdapter.on("message",(e=>{try{const t=e.sourceId,i=Rw.parse(e.data),n={sourceId:t,message:i};i.isInternal()?this._eventEmitter.emit("internalMessage",n):this._eventEmitter.emit("message",n)}catch(e){this._logger.error(`process message error: ${Aw(e)}`)}}))}async initialize(){await this._dataChannelAdapter.initialize()}async send(e){try{if(void 0===e.recipients)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.NO_VALID_PARTICIPANT});if(e.recipients.length>64)throw _w();await this._dataChannelAdapter.send(e.data,e.recipients)}catch(e){throw e?.message===this._bufferFullErrorMessage?new le({defaultError:ee.FEATURES.DATA_CHANNEL.BUFFER_FULL}):new le({defaultError:ee.FEATURES.DATA_CHANNEL.SEND_FAIL,originalError:e})}}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._dataChannelAdapter.dispose()}}class Ow{constructor(e){this._sourceIds=[],this._participantMappingManager=e,this._participantMapping=new Map,e.on("participantAdded",(e=>{if(this._participantMapping.has(e)){const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t),this._updateSourceIds()}})),e.on("participantUpdated",(e=>{if(this._participantMapping.has(e)){const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t),this._updateSourceIds()}})),e.on("participantRemoved",(e=>{this._participantMapping.has(e)&&(this._participantMapping.set(e,[]),this._updateSourceIds())}))}get sourceIds(){if(this._participantMappingManager.isP2P()||!(this._participantMapping.size>0)||0!==this._sourceIds.length)return this._sourceIds}setParticipants(e){const t=[];e.forEach((e=>{NS(e),t.push(DS(e))})),this._participantMapping.clear(),t.forEach((e=>{const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t)})),this._updateSourceIds()}_updateSourceIds(){this._sourceIds=Array.from(this._participantMapping.values()).flat()}}var Nw,Lw=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},xw=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};!function(e){e[e.Open=0]="Open",e[e.Closed=1]="Closed",e[e.Destroyed=2]="Destroyed"}(Nw||(Nw={}));class Fw{constructor(e,t,i,n,r,s){this._state=Nw.Open;const a=vy().dataChannel;this._eventEmitter=new OE.EventEmitter,this._channelId=e,this._channelVersion=t,this._sequenceNumber=Math.floor(Math.random()*(Sw+1)),this._recipientsManager=new Ow(n),this._dataChannelMonitor=r,this._sendMessageFunction=i,this._maxMessageSize=a.maxMessageSize,this._logger=s.createChild(`DataChannelSender(${e},${t})`),this._logger.info("opened")}get channelId(){return this._channelId}get maxMessageSize(){return this._maxMessageSize}setParticipants(e){if(!Array.isArray(e))throw Cw("participants","CommunicationIdentifier[]");if(e.length>64)throw _w();this._recipientsManager.setParticipants(e),this._logger.info(`participant size: ${e.length}`)}async sendMessage(e){if(this._dataChannelMonitor.updateAttemptStats(e.length),!(e instanceof Uint8Array))throw Cw("data","Uint8Array");if(this._state===Nw.Closed)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.SENDER_CLOSED});if(0===e.length)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.MSG_DATA_EMPTY});if(e.length>this._maxMessageSize)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.MSG_DATA_TOO_LARGE});const t=this._recipientsManager.sourceIds;await this._sendMessage(e,t),this._dataChannelMonitor.updateCommitStats(e.length)}close(){this._state<Nw.Closed&&(this._sendMessage(new Uint8Array,[]).catch(My),this._state=Nw.Closed,this._eventEmitter.emit("close"),this._logger.info("closed"),this._dataChannelMonitor.close())}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this.close(),this._state!==Nw.Destroyed&&(this._eventEmitter.removeAllListeners(),this._state=Nw.Destroyed,this._logger.info("disposed"))}get channelVersion(){return this._channelVersion}get state(){return this._state}async _sendMessage(e,t){const i=Rw.create(this._channelId,this._channelVersion,this._sequenceNumber,e);this._sequenceNumber=(this._sequenceNumber+1)%(Sw+1);const n={channelId:this._channelId,channelVersion:this._channelVersion,recipients:t,data:i.serializedData};await this._sendMessageFunction(n)}}Lw([Pw,xw("design:type",Function),xw("design:paramtypes",[Array]),xw("design:returntype",void 0)],Fw.prototype,"setParticipants",null),Lw([function(e,t,i){const n=i.value;return i.value=async function(...e){try{return await(n?.apply(this,e))}catch(e){throw this?._logger?.error(`${t}: ${Aw(e)}`),e}},i},xw("design:type",Function),xw("design:paramtypes",[Uint8Array]),xw("design:returntype",Promise)],Fw.prototype,"sendMessage",null),Lw([Pw,xw("design:type",Function),xw("design:paramtypes",[]),xw("design:returntype",void 0)],Fw.prototype,"close",null),Lw([Pw,xw("design:type",Function),xw("design:paramtypes",[]),xw("design:returntype",void 0)],Fw.prototype,"dispose",null);class Uw{constructor(e){this.value=e,this.next=void 0}}class Bw{constructor(){this.length=0,this.front=void 0,this.rear=void 0}enqueue(e){const t=new Uw(e);this.front?(this.rear.next=t,this.rear=t):(this.front=t,this.rear=t),this.length++}dequeue(){if(!this.front)return;const e=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,e.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 Vw,Hw=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},$w=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};!function(e){e[e.Open=0]="Open",e[e.Closed=1]="Closed",e[e.Destroyed=2]="Destroyed"}(Vw||(Vw={}));class jw{constructor(e,t,i,n,r,s){this._receiveBuffers=new Bw,this._remainingBytes=0,this._state=Vw.Open,this._channelVersion=0;const a=vy().dataChannel;this._logger=s.createChild(`DataChannelReceiver(${e},${n},${i})`),this._eventEmitter=new T_(this._logger,{enableLogEmit:!1}),this._maxBufferSize=a.maxReceiveBufferSize,this._dataChannelMonitor=r,this._channelId=e,this._senderParticipantIdentifier=kS(t),this._channelVersion=n,this._lastMessageTimestamp=Date.now(),this._logger.info("created.")}get channelId(){return this._channelId}get senderParticipantIdentifier(){return this._senderParticipantIdentifier}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}readMessage(){const e=this._receiveBuffers.dequeue();return e?.data&&(this._remainingBytes-=e.data.length),e}dispose(){this._state!==Vw.Destroyed&&(this.close(),this._state=Vw.Destroyed,this._receiveBuffers.clear(),this._eventEmitter.removeAllListeners())}close(){this._state===Vw.Open&&(this._state=Vw.Closed,this._eventEmitter.emit("close"),this._dataChannelMonitor.close())}get channelVersion(){return this._channelVersion}get lastMessageTimestamp(){return this._lastMessageTimestamp}get state(){return this._state}appendMessage(e){if(this._dataChannelMonitor.updateAttemptStats(e.data.length),this._state!==Vw.Open)return;if(0===e.data.length)return void this.close();if(this._lastMessageTimestamp=Date.now(),this._remainingBytes+e.data.length>this._maxBufferSize)return;const t={sequenceNumber:e.sequenceNumber,data:e.data};this._receiveBuffers.enqueue(t),this._remainingBytes+=e.data.length,this._eventEmitter.emit("messageReady"),this._dataChannelMonitor.updateCommitStats(e.data.length)}}Hw([Pw,$w("design:type",Function),$w("design:paramtypes",[]),$w("design:returntype",Object)],jw.prototype,"readMessage",null),Hw([Pw,$w("design:type",Function),$w("design:paramtypes",[Rw]),$w("design:returntype",void 0)],jw.prototype,"appendMessage",null);class Gw{constructor(e,t,i){this._timeoutHandle=0;const n=vy().dataChannel;this._eventEmitter=new OE.EventEmitter,this._participantMappingManager=e,this._dataChannelMonitor=t,this._logger=i,this._receivers=new Map,this._lastestVersion=new Map,this._receiveTimeoutInMs=n.receiveTimeoutInMs}_checkTimeoutReceivers(){Array.from(this._receivers.keys()).forEach((e=>{const t=this._receivers.get(e);void 0!==t&&Date.now()-t.lastMessageTimestamp>=this._receiveTimeoutInMs&&t.close()})),this._receivers.size>0&&(this._timeoutHandle=window.setTimeout((()=>{this._timeoutHandle=0,this._checkTimeoutReceivers()}),Math.ceil(this._receiveTimeoutInMs/2)))}appendMessage(e){const t=`${e.sourceId},${e.message.channelId}`,i=`${e.sourceId},${e.message.channelId},${e.message.channelVersion}`;let n=this._lastestVersion.get(t),r=this._receivers.get(i);const s=e.message;if(void 0===r){if(void 0!==n&&-1===function(e,t){if(e===t)return 0;if(-1===t)return 1;const i=e-t;return i>0?i<127.5?1:-1:-i>127.5?1:-1}(s.channelVersion,n))return;if(this._lastestVersion.set(t,s.channelVersion),s.isEmpty())return;if(0===this._eventEmitter.listenerCount("dataChannelReceiverCreated"))return;const a=this._participantMappingManager.findParticipantMri(e.sourceId)??"",o=this._participantMappingManager.findParticipantId(e.sourceId)??"",l=this._dataChannelMonitor.createReceiverMonitor(s.channelId,s.channelVersion,o);if(""===a)return void this._logger.info(`Unable to find corresponding sender mri, ignoring the message. channelId:${s.channelId}, sourceId:${e.sourceId}`);this._logger.info(`channelId:${s.channelId} message from ${o}, sourceId:${e.sourceId}, channelVersion:${s.channelVersion}`),r=new jw(s.channelId,a,e.sourceId,s.channelVersion,l,this._logger),r.on("close",(()=>{this._receivers.delete(i)})),this._receivers.set(i,r),this._eventEmitter.emit("dataChannelReceiverCreated",r),0===this._timeoutHandle&&this._checkTimeoutReceivers()}r.appendMessage(s),s.isEmpty()&&this._receivers.delete(i)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){window.clearTimeout(this._timeoutHandle),this._timeoutHandle=0,this._receivers.forEach(((e,t)=>{e.dispose()})),this._lastestVersion.clear(),this._receivers.clear(),this._eventEmitter.removeAllListeners()}}const qw=64512;class zw{constructor(e){this._channelIdsInUse=e}findAvailableChannelId(){if(this._channelIdsInUse.size>=qw)throw Ew();let e;for(;(e=Math.floor(Math.random()*qw)+1024)&&this._channelIdsInUse.has(e););return e}}class Ww{constructor(e){this._availableChannelIds=[],this._channelIdsInUse=e,this._initArray()}findAvailableChannelId(){if(0===this._availableChannelIds.length){if(this._channelIdsInUse.size>=qw)throw Ew();this._initArray()}return this._availableChannelIds.pop()}_initArray(){const e=Array.from(this._channelIdsInUse,(e=>e)).sort();let t=0,i=0;for(;t<=vw&&i<e.length;)t<e[i]?(this._availableChannelIds.push(t),t++):(t>e[i]||t++,i++);for(;t<=vw;)this._availableChannelIds.push(t),t++;this._availableChannelIds=Z.shuffle(this._availableChannelIds)}}class Kw{constructor(){this._channelIdsInUse=new Set,this._highWaterMark=Math.ceil(.8*qw),this._lowWaterMark=Math.floor(.4*qw),this._strategy=new zw(this._channelIdsInUse)}addChannelId(e){e>=1024&&e<=vw&&(this._channelIdsInUse.add(e),this._channelIdsInUse.size>=this._highWaterMark&&this._strategy instanceof zw&&(this._strategy=new Ww(this._channelIdsInUse)))}removeChannelId(e){this._channelIdsInUse.delete(e),this._channelIdsInUse.size<this._lowWaterMark&&this._strategy instanceof Ww&&(this._strategy=new zw(this._channelIdsInUse))}findAvailableChannelId(){return this._strategy.findAvailableChannelId()}}class Jw{constructor(e){this._dataIds=[],this._channelIds=new Map,e.forEach((e=>{this._dataIds.push({dataId:e.dataId,bandwidth:e.bandwidth,allocatedBandwidth:0})}))}allocate(e){const t=Z.maxBy(this._dataIds,(t=>1-(t.allocatedBandwidth+e.bitrate)/t.bandwidth));if(void 0===t)throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.NO_AVAILABLE_RELIABLE_CHANNEL});return t.allocatedBandwidth+=e.bitrate,this._channelIds.set(e.channelId,{dataId:t.dataId,allocatedBandwidth:e.bitrate}),t.dataId}deallocate(e){const t=this._channelIds.get(e);if(void 0!==t){const i=this._dataIds.find((e=>e.dataId===t.dataId));void 0!==i&&(i.allocatedBandwidth-=t.allocatedBandwidth),this._channelIds.delete(e)}}getDataIds(e){const t=this._channelIds.get(e);return void 0!==t?[t.dataId]:[]}}class Yw{getDataIds(e){throw Iw()}getAllSum(){return 0}}class Qw{constructor(e){this._acsDataIdConfigs=[],this._bandwidthList=[],this._acsDataIdConfigs=e,e.forEach((e=>{this._bandwidthList.push(e.bandwidth/1e3)})),this._allSum=Z.sumBy(e,(e=>e.bandwidth))}getDataIds(e){let t=[];const i=Math.ceil(e/1e3);if(i>=this._allSum)t=this._acsDataIdConfigs.map((e=>e.dataId));else{const e=this._bandwidthList[0]-1;let n=0;i&e&&(n=this._bandwidthList.findIndex((e=>!(e&i))),-1!==n&&(t.push(this._acsDataIdConfigs[n].dataId),n++));for(let e=n;e<this._bandwidthList.length;e++)this._bandwidthList[e]&i&&t.push(this._acsDataIdConfigs[e].dataId)}return t}getAllSum(){return this._allSum}}class Zw{constructor(e){this._bandwidthMap=new Map,this._bandwidthMap.set(0,[]),function(e){const t=[[]];return e.forEach((e=>{const i=[];t.forEach((t=>{i.push([...t,e])})),t.push(...i)})),t}(e).forEach((e=>{const t=Z.sumBy(e,(e=>e.bandwidth)),i=this._bandwidthMap.get(t);(void 0===i||e.length<i.length)&&this._bandwidthMap.set(t,e.map((e=>e.dataId)))})),this._bandwidthList=Array.from(this._bandwidthMap.keys()).sort(((e,t)=>e-t))}getDataIds(e){const t=Z.sortedIndex(this._bandwidthList,e),i=this._bandwidthList[t]??this._bandwidthList[this._bandwidthList.length-1];return this._bandwidthMap.get(i)||[]}getAllSum(){return Z.last(this._bandwidthList)||0}}class Xw{constructor(e){(e=Z.sortBy(e,(e=>e.bandwidth))).length?function(e){if(e.find((e=>!Number.isInteger(Math.log2(e)))))return!1;for(let t=1;t<e.length;t++)if(e[t]!==2*e[t-1])return!1;return!0}(e.map((e=>e.bandwidth/1e3)))?this._dataIdSelectionStrategy=new Qw(e):this._dataIdSelectionStrategy=new Zw(e):this._dataIdSelectionStrategy=new Yw}getDataIds(e){return this._dataIdSelectionStrategy.getDataIds(e)}getAllSum(){return this._dataIdSelectionStrategy.getAllSum()}}class eA{constructor(e){this._totalNormalPriorityBandwidth=0,this._totalHighPriorityBandwidth=0,this._configs=new Map,this._currentNormalPriorityDataIds=[],this._currentHighPriorityDataIds=[],this._normalPriorityTable=new Xw(e.filter((e=>"normal"===e.priority))),this._highPriorityTable=new Xw(e.filter((e=>"high"===e.priority)))}allocate(e){this._configs.set(e.channelId,e),"Normal"===e.priority?this._totalNormalPriorityBandwidth+=e.bitrate:"High"===e.priority&&(this._totalHighPriorityBandwidth+=e.bitrate),this._updateDataIds()}deallocate(e){const t=this._configs.get(e);void 0!==t&&(this._configs.delete(e),"Normal"===t.priority?this._totalNormalPriorityBandwidth-=t.bitrate:"High"===t.priority&&(this._totalHighPriorityBandwidth-=t.bitrate),this._updateDataIds())}getDataIds(e){const t=this._configs.get(e);if(void 0!==t){if("Normal"===t.priority)return this._currentNormalPriorityDataIds;if("High"===t.priority)return this._currentHighPriorityDataIds}return[]}_updateDataIds(){const e=this._highPriorityTable.getAllSum(),t=this._totalHighPriorityBandwidth-e;if(t>0){const e=this._totalNormalPriorityBandwidth+t;this._currentNormalPriorityDataIds=this._normalPriorityTable.getDataIds(e),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 tA{constructor(e){const t=e.filter((e=>"reliable"===e.category)),i=e.filter((e=>"unicast"===e.category)),n=e.filter((e=>"broadcast"===e.category));this._reliableDataIdManager=new Jw(t),this._unicastDataIdManager=new eA(i),this._broadcastDataIdManager=new eA(n),this._configs=new Map}allocate(e){let t=-1;if(this._configs.has(e.channelId))throw new le({defaultError:ee.FEATURES.DATA_CHANNEL.CHANNEL_ALREADY_ALLOCATED});try{"Durable"===e.reliability?t=this._reliableDataIdManager.allocate(e):(this._unicastDataIdManager.allocate(e),this._broadcastDataIdManager.allocate(e)),this._configs.set(e.channelId,e)}catch(t){throw"Durable"===e.reliability?this._reliableDataIdManager.deallocate(e.channelId):(this._unicastDataIdManager.deallocate(e.channelId),this._broadcastDataIdManager.deallocate(e.channelId)),t}return t}deallocate(e){const t=this._configs.get(e);void 0!==t&&("Durable"===t.reliability?this._reliableDataIdManager.deallocate(e):(this._unicastDataIdManager.deallocate(e),this._broadcastDataIdManager.deallocate(e)),this._configs.delete(e))}getDataIdToSend(e,t,i){const n=this._configs.get(e);if(void 0!==n)return"Durable"===n.reliability?this._reliableDataIdManager.getDataIds(e):i?this._broadcastDataIdManager.getDataIds(e):this._unicastDataIdManager.getDataIds(e);throw function(e){return new le({defaultError:ee.FEATURES.DATA_CHANNEL.CANT_FIND_CHANNEL_ID,defaultErrorMessageArgs:[e]})}(e)}}class iA{constructor(e){this._attemptCount=0,this._attemptBytes=0,this._commitCount=0,this._commitBytes=0,this._dataChannelTelemetryLogger=e,this._openTime=new Date,this._closeTime=this._openTime}updateAttemptStats(e){this._attemptCount++,this._attemptBytes+=e}updateCommitStats(e){this._commitCount++,this._commitBytes+=e}close(){this._closeTime=new Date}}class nA extends iA{constructor(e,t,i,n){super(n),this._channelId=e,this._channelVersion=t,this._correlationId=i}close(){super.close();const e={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(e)}}class rA extends iA{constructor(e,t,i,n){super(n),this._channelId=e,this._channelVersion=t,this._remoteParticipantId=i}close(){super.close();const e={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(e)}}class sA{constructor(e){this._dataChannelTelemetryLogger=e}createSenderMonitor(e,t,i){return new nA(e,t,i,this._dataChannelTelemetryLogger)}createReceiverMonitor(e,t,i){return new rA(e,t,i,this._dataChannelTelemetryLogger)}}class aA{constructor(e){this._timeBucket=0,this._maxPacketRate=0,this._packetCount=0,this._maxPacketRate=e}canSend(e){let t=Math.ceil(e/1200);const i=window.performance.now();return Math.floor(i/1e3)==this._timeBucket&&(t+=this._packetCount),t<=this._maxPacketRate}update(e){let t=Math.ceil(e/1200);const i=window.performance.now(),n=Math.floor(i/1e3);n!==this._timeBucket&&(this._timeBucket=n,this._packetCount=0),this._packetCount+=t}}class oA{constructor(e){this._endTime=0,this._maxDataRate=0,this._maxDataRate=e/8}canSend(e){if(0===this._maxDataRate)return!0;const t=window.performance.now(),i=(this._endTime-t)/1e3;return!(i>0)||i+e/this._maxDataRate<=1}update(e){const t=window.performance.now(),i=this._maxDataRate?e/this._maxDataRate*1e3:0;this._endTime<t?this._endTime=t+i:this._endTime+=i}changeBitrate(e){this._maxDataRate=e/8}}class lA{constructor(){this._totalBytes=0,this._lastUpdateTime=window.performance.now(),this._lastUpdateBytes=0,this._currentBitrate=0}getBitrate(){return this._currentBitrate}update(e){this._totalBytes+=e}calculateBitrate(){const e=window.performance.now();e-this._lastUpdateTime>0&&(this._currentBitrate=8*(this._totalBytes-this._lastUpdateBytes)/(e-this._lastUpdateTime)),this._lastUpdateTime=e,this._lastUpdateBytes=this._totalBytes}}class cA{constructor(e,t){this._availableBytes=0,this._reducedBytes=0,this._lastUpdateTime=window.performance.now(),this._packetRateLimiter=new aA(t),this._receiveBitrate=new lA,this._bitrateTimer=window.setInterval((()=>{this._receiveBitrate.calculateBitrate();const t=window.performance.now(),i=(t-this._lastUpdateTime)/1e3;this._availableBytes=e/8*i,this._reducedBytes=.8*this._receiveBitrate.getBitrate()/8*i,this._lastUpdateTime=t}),1e3)}canSend(e,t){return t?!!this._packetRateLimiter.canSend(e)&&this._availableBytes-this._reducedBytes>=e:this._availableBytes>=e}updateSendBytes(e,t){t&&this._packetRateLimiter.update(e),this._availableBytes-=e}updateReceiveBytes(e){this._receiveBitrate.update(e)}dispose(){window.clearInterval(this._bitrateTimer)}}var dA,uA;!function(e){e[e.Initializing=0]="Initializing",e[e.Initialized=1]="Initialized",e[e.Destroyed=2]="Destroyed"}(dA||(dA={}));class hA{constructor(e,t,i){this._state=dA.Initializing,this._initializedDefer=jT();const n=vy();this._logger=t,this._tsCall=e,this._dataChannelTelemtryLogger=i,this._participantMappingManager=new mw(e),this._dataChannelMonitor=new sA(i),this._senders=new Map,this._receiversManager=new Gw(this._participantMappingManager,this._dataChannelMonitor,t),this._processors=new Map,this._channelVersions=new Map,this._randomChannelIdManager=new Kw,this._dataIds=new Map,n.dataChannel.dataIdConfigs.forEach((e=>{const t=this._dataIds.get(e.dataId)??[];t.push(e.raw?{dataId:e.dataId,raw:e.raw}:{dataId:e.dataId,raw:e.raw,bandwidth:e.bandwidth??0,priority:e.priority??"normal",category:e.category??"reliable"}),this._dataIds.set(e.dataId,t)})),this._rateLimiters=new Map,this._sendTrafficLimiter=new cA(n.dataChannel.maxSendBandwidth,n.dataChannel.maxBroadcastPacketRate),this._enableBroadcastLimitOnReliableChannel=n.dataChannel.enableBroadcastLimitOnReliableChannel}async initialize(){const e=async e=>{const t=new kw(e,this._tsCall,this._logger);return t.on("message",(t=>{const i=t.message;e.raw?i.channelId=e.dataId+fw:this._sendTrafficLimiter.updateReceiveBytes(i.data.length);try{this._receiversManager.appendMessage(t)}catch(t){this._logger.error(`Failed to appendMessage on dataId ${e.dataId}: ${Aw(t)}`)}})),await t.initialize(),t},t=[],i=new Map,n=Array.from(this._dataIds.keys());for(let r=0;r<n.length;r++){const s=n[r],a=this._dataIds.get(s)[0];try{const t=await e(a);i.set(s,t)}catch(i){t.push(s),this._dataIds.delete(s)}}const r=Z.flatten(Array.from(this._dataIds.values())).filter((e=>!e.raw));this._dataIdMappingManager=new tA(r),this._state===dA.Initializing?(this._processors=i,r.forEach((e=>{this._rateLimiters.has(e.dataId)||this._rateLimiters.set(e.dataId,new oA(e.bandwidth))})),t.length&&this._dataChannelTelemtryLogger.sendCreateProcessorEvent({kindOfEvent:"failure",dataIds:t}),this._state=dA.Initialized,this._initializedDefer.resolve()):i.forEach((e=>{e.dispose()}))}createSender(e,t){let i=e.channelId,n=!1;if(i>=fw){if(!0!==this._dataIds.get(i-fw)?.[0].raw)throw bw();n=!0}else{if(i<0||i>vw)throw bw();0===i&&(i=this._randomChannelIdManager.findAvailableChannelId())}this._senders.get(i)?.close();const r=function(e){return 255===e?0:e+1}(this._channelVersions.get(i)??-1);let s=i>=fw?i-fw:-1,a=!1;-1===s&&this._state===dA.Initialized&&(s=this._dataIdMappingManager.allocate({channelId:i,reliability:e.reliability,priority:e.priority,bitrate:1e3*e.bitrateInKbps}),a=!0);const o=this._dataChannelMonitor.createSenderMonitor(i,r,t),l=new Fw(i,r,(async t=>{const r=t.data.length;if(-1===s&&!a){if(8===r)return;await this._initializedDefer.promise,a||(s=this._dataIdMappingManager.allocate({channelId:i,reliability:e.reliability,priority:e.priority,bitrate:1e3*e.bitrateInKbps}),a=!0)}const o=0===t.recipients?.length&&!this._participantMappingManager.isP2P();if(-1!==s)if(this._enableBroadcastLimitOnReliableChannel&&o&&!n){if(!this._sendTrafficLimiter.canSend(r,o))throw ww();const e=this._processors.get(s);await(e?.send(t)),this._sendTrafficLimiter.updateSendBytes(r,o)}else{const e=this._processors.get(s);await(e?.send(t))}else{const n=this._dataIdMappingManager.getDataIdToSend(i,r,o);try{const i=!this._sendTrafficLimiter.canSend(r,o);if(i&&"High"!==e.priority)throw ww();if(0===n.length)throw Iw();for(let e=0;e<n.length;e++)try{const s=n[e],a=this._dataIds.get(s)[0];if(i&&"normal"===a.priority)continue;const l=this._rateLimiters.get(s);if(l?.canSend(r)??1){const e=this._processors.get(s);return await(e?.send(t)),l?.update(r),void this._sendTrafficLimiter.updateSendBytes(r,o)}}catch(e){}throw ww()}catch(e){this._logger.error(`Failed to send channelId ${i} message: ${Aw(e)}`)}}}),this._participantMappingManager,o,this._logger);return l.on("close",(()=>{a&&this._dataIdMappingManager.deallocate(i),this._randomChannelIdManager.removeChannelId(i),this._senders.delete(i),setTimeout((()=>l.dispose()),0)})),void 0!==e.participants&&l.setParticipants(e.participants),this._senders.set(i,l),this._randomChannelIdManager.addChannelId(i),this._channelVersions.set(i,r),l}getDataStreamIdsFromParticipant(e){return this._participantMappingManager.findSourceIds(e.id)}on(e,t){"dataChannelReceiverCreated"===e&&this._receiversManager.on("dataChannelReceiverCreated",t)}off(e,t){"dataChannelReceiverCreated"===e&&this._receiversManager.off("dataChannelReceiverCreated",t)}dispose(){this._state!==dA.Destroyed&&(this._state=dA.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(new le({defaultError:ee.FEATURES.DATA_CHANNEL.DISPOSED})),this._senders.forEach((e=>{e.dispose()})),this._receiversManager.dispose(),this._processors.forEach((e=>{e.dispose()})),this._sendTrafficLimiter.dispose(),this._participantMappingManager.dispose())}}class gA{constructor(e,t){this._tsCall=e,this._telemetryLogManager=t}sendStatsEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,...e};this._telemetryLogManager.sendEvent({name:aE.acs_calling_datachannel_stats,tenant:xv,properties:t})}sendCreateSenderEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createSender",...e};this._telemetryLogManager.sendEvent({name:aE.acs_calling_datachannel,tenant:xv,properties:t})}sendCreateProcessorEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createProcessor",...e};this._telemetryLogManager.sendEvent({name:aE.acs_calling_datachannel,tenant:xv,properties:t})}}class pA{constructor(e){this.typeRankComparator=(e,t)=>void 0===e.publishedState?-1:void 0===t.publishedState?1:e.publishedState.typeRank-t.publishedState.typeRank,this._eventEmitter=e,this._currentSpotlightStates=new Map;const t=vy().calling.spotlight;this._maxSpotlightStateSupported=t.maxSpotlightParticipants,this._supportedUserRoles=t.supportedRoles,this._meetingTypes=t.meetingTypes}initialize(e,t,i,n,r){this._logger=n.createChild((()=>`SpotlightFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._callInfo=r,this._telemetryLogManager=i,this._internalCallAgent=t;const s="initialize";this._sendFeatureUsage(s,oE.initialize);try{let e=e=>new Map(this.getPublishedState(e).sort(this.typeRankComparator).map(((e,t)=>[e.id,{spotlightStateId:e.publishedState?.stateId,index:t+1}])));this._tsCall.on("publishedStatesChanged",(async t=>{let i=e(t),n=[];i.forEach(((e,t)=>{this._currentSpotlightStates.has(t)||n.push({identifier:kS(t),order:e?.index})}));let r=[];this._currentSpotlightStates.forEach(((e,t)=>{i.has(t)||r.push({identifier:kS(t)})})),this._currentSpotlightStates=i,(n.length||r.length)&&this._eventEmitter.emit("spotlightChanged",{added:n,removed:r})})),this._tsCall.publishedStates&&(this._currentSpotlightStates=e(this._tsCall.publishedStates)),this._sendFeatureUsage(s,oE.success)}catch(e){this.handleSpotlightFailure(s,e)}}async startSpotlight(e){const t="startSpotlight";try{this._sendFeatureUsage(t,oE.attempt);let i=this.getIdentifiersMri(e).filter((e=>!this._currentSpotlightStates.has(e)));if(!i.length)throw new le({defaultError:ee.FEATURES.SPOTLIGHT.ALREADY_SPOTLIGHTED});this.validateStartSpotlightConditions(i);const n={level:"user",type:"spotlight",content:"{}",participantIds:i};if(!await this._tsCall.publishState(n,X.generateCauseId()))throw new le({defaultError:ee.FEATURES.SPOTLIGHT.START_SPOTLIGHT_FAILED});this._sendFeatureUsage(t,oE.success)}catch(e){this.handleSpotlightFailure(t,e)}}async stopSpotlight(e){const t="stopSpotlight";this._tsCall.publishedStates||this._logger.warn(`${t}: no participants is currently Spotlighted`);try{this._sendFeatureUsage(t,oE.attempt);let i=this.getIdentifiersMri(e);this.validateStopSpotlightConditions(i);const n=this.findStateIdsForParticipantIds(i);await this._tsCall.removeState({stateIds:n},X.generateCauseId()),this._sendFeatureUsage(t,oE.success)}catch(e){this.handleSpotlightFailure(t,e)}}async stopAllSpotlight(){const e="stopAllSpotlight";try{this._sendFeatureUsage(e,oE.attempt),this.validateStopSpotlightConditions([]),await this._tsCall.removeStatesForEveryone({type:"spotlight"},X.generateCauseId()),this._sendFeatureUsage(e,oE.success)}catch(t){this.handleSpotlightFailure(e,t)}}get spotlightedParticipants(){return this._tsCall.publishedStates?Array.from(this._currentSpotlightStates.keys()).map((e=>({identifier:kS(e),order:this._currentSpotlightStates.get(e)?.index}))):[]}get maxSpotlightStateSupported(){return this._maxSpotlightStateSupported}findStateIdsForParticipantIds(e){return e.length&&this._tsCall.publishedStates?e.map((e=>this._currentSpotlightStates.get(e)?.spotlightStateId||"")).filter((e=>e.length)):[]}getPublishedState(e){return e.typeStates.filter((e=>"spotlight"===e.type)).map((e=>e.participantStates)).flat()}isUserRoleEligible(){const e=this._tsCall.advancedMeetingRole;return!!e&&!!this._supportedUserRoles.find((t=>t===e))}isRoleBasedConversationType(){const e=this._tsCall.conversationType;return!!e&&!!this._meetingTypes.find((t=>t===e))}getIdentifiersMri(e){return e&&e?.length?e.map((e=>DS(e))):[this._internalCallAgent.getUserMri()]}validateStartSpotlightConditions(e){if(this._callInfo.context===uy.TwoParty)throw this._logger.warn("Spotlight not supported for 1:1 calls"),this._sendFeatureUsage("startSpotlight",oE.failure),new le({defaultError:ee.FEATURES.SPOTLIGHT.NOT_SUPPORTED_1TO1});if(this.spotlightedParticipants.length+e.length>this._maxSpotlightStateSupported)throw new le({defaultError:ee.FEATURES.SPOTLIGHT.SPOTLIGHT_LIGHT_MAX_REACHED,defaultErrorMessageArgs:[this._maxSpotlightStateSupported]});if(this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new le({defaultError:ee.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Start",this._tsCall.conversationType]})}validateStopSpotlightConditions(e){if((1!==e.length||e[0]!==this._internalCallAgent.getUserMri())&&this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new le({defaultError:ee.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Stop",this._tsCall.conversationType]})}handleSpotlightFailure(e,t){throw this._logger.error(JSON.stringify(t)),this._sendFeatureUsage(e,oE.failure,t),t}_sendFeatureUsage(e,t,i){let n=i?{code:i?.code||ne,subCode:i?.subCode||0,failureReason:i?.message||"",..._b(i)}:void 0;hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Spotlight",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}class mA{initialize(e,t,i,n,r){this._tsCall=e,this._call=i,this._telemetryLogManager=n,this._logger=r,this.updateCallSurveyInfo(),this._tsCall.on("callStateChanged",(()=>{7===this._tsCall?.state&&(this._logger.debug("Call disconnected. Releasing call and tsCall references."),this.updateCallSurveyInfo(),this._tsCall=void 0,this._call=void 0)}))}async submitSurvey(e){const t=+new Date,i=Mf();this.updateCallSurveyInfo(),this.sendEndOfCallEvent("attempt",i);const n=this.validateSurvey(e);if(n){const e=new le({defaultError:ee.FEATURES.CALL_SURVEY.INVALID_SURVEY,defaultErrorMessageArgs:[n]});throw this.sendEndOfCallEvent("failure",i,t,{failureReason:n,code:400,..._b(e),isExpected:!0}),e}return new Promise(((n,r)=>{const s=this.createCallSurveyInternal(e);this.registerNotificationEventListener(s,i,t,n,r),this.sendEndOfCallEvent("success",i,t,void 0,s)}))}registerNotificationEventListener(e,t,i,n,r){const s={id:t,callId:e.callId,localParticipantId:e.localParticipantId,overallRating:e.overallRating,audioRating:e.audioRating,videoRating:e.videoRating,screenshareRating:e.screenshareRating};mA.NOTIFICATION_LISTENER.eventsSent=e=>{e.find((e=>e.name===aE.acs_calling_survey&&e.data?.correlationId===t&&"success"===e.data?.kindOfEvent))&&n(s)},mA.NOTIFICATION_LISTENER.eventsDiscarded=(e,n)=>{if(e.find((e=>e.name===aE.acs_calling_survey&&e.data?.correlationId===t&&"success"===e.data?.kindOfEvent))){const e=new le({defaultError:ee.FEATURES.CALL_SURVEY.SUBMIT_TIMEOUT});this.sendEndOfCallEvent("failure",t,i,{failureReason:e.message,code:e.code,..._b(e)}),r(e)}}}updateCallSurveyInfo(){const e=this.createCallSurveyInfo();e&&(this._callSurveyInfo=e)}createCallSurveyInfo(){return this._call&&this._tsCall?{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,callMode:this._tsCall.callMode,isCteTeamsCall:this._call.isCteTeamsCall}:void this._logger.warn(`Call: ${this._call} or tsCall: ${this._tsCall} is not available to create call survey info.`)}sendEndOfCallEvent(e,t,i,n,r){try{const s={eventName:aE.acs_calling_survey,callId:this._callSurveyInfo?.callId,localParticipantId:this._callSurveyInfo?.localParticipantId,correlationId:t,kindOfEvent:e,timestampInfo:{deltaTimeInMs:0},additionalDetails:n};if(i){const e=+new Date;s.timestampInfo.deltaTimeInMs=e-i}"success"===e&&r?(s.overallRating=r.overallRating,s.audioRating=r.audioRating,s.videoRating=r.videoRating,s.screenshareRating=r.screenshareRating,this._telemetryLogManager.sendEvent({name:aE.acs_calling_survey,tenant:xv,priority:cd.Immediate,properties:s},mA.NOTIFICATION_LISTENER),vy().calling.teamsCallQualityFeedback.enabled&&this._callSurveyInfo?.isCteTeamsCall&&this.acsCallSurveyToMediaCallQualityFeedback(r,t)):this._telemetryLogManager.sendEvent({name:s.eventName,tenant:xv,properties:s})}catch(e){this._logger.debug("Unable to send call survey telemetry")}}acsCallSurveyToMediaCallQualityFeedback(e,t){const i=this.getFiveStarRating(e.overallRating);if(void 0===i)return void this._logger.info("Call survey has no valid overall rating. Skipping media call quality feedback.");const n=this.getAllCallIssues(e),r={acs_correlation_id:t,call_mos_score_questionary_id:105,clientType:"ACSWebSDK",call_id:e.callId,participant_id:e.localParticipantId,call_mos_score:i-1,call_mos_score_tracking_reason:"random",call_mos_score_problem_tokens:n,call_mos_score_never_expires:!1};void 0!==this._callSurveyInfo?.callMode&&(r.call_mode=this._callSurveyInfo.callMode),this._telemetryLogManager.sendEvent({name:aE.mdsc_call_quality_feedback,tenant:vy().calling.teamsCallQualityFeedback.tenantId,priority:cd.Immediate,properties:r})}getAllCallIssues(e){const t=[];return e.overallRating?.issues?.forEach((e=>t.push(mA.ACS_OVERALL_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[e]))),e.audioRating?.issues?.forEach((e=>t.push(mA.ACS_AUDIO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[e]))),e.videoRating?.issues?.forEach((e=>t.push(mA.ACS_VIDEO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[e]))),e.screenshareRating?.issues?.forEach((e=>t.push(mA.ACS_SCREENSHARE_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[e]))),t.length>0?"checks="+t.join("%20"):""}getFiveStarRating(e){if(e?.scale){const t=e.score-e.scale.lowerBound+1,i=e.scale.upperBound-e.scale.lowerBound+1,n=Math.round(5*t/i);return n<1?1:n}return e?.score}createCallSurveyInternal(e){const t={callId:this._callSurveyInfo?.callId,localParticipantId:this._callSurveyInfo?.localParticipantId};return e&&(t.overallRating=e.overallRating,t.audioRating=e.audioRating,t.videoRating=e.videoRating,t.screenshareRating=e.screenshareRating),t}validateSurvey(e){let t="";return t=this.validateOverallRating(e.overallRating),t+=this.validateAudioRating(e.audioRating),t+=this.validateVideoRating(e.videoRating),t+=this.validateScreenshareRating(e.screenshareRating),""!==t||e.overallRating||e.audioRating||e.videoRating||e.screenshareRating||(t="At least one survey rating is required."),""===t&&(t=this.validateCallSurveyTypes(e)),t.trim()}validateOverallRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(mA.OVERALL_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("overallRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("overallRating.scale",e)):t=this.defaultRatingScaleMessage(mA.OVERALL_RATING_SCORE),t}validateAudioRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(mA.AUDIO_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("audioRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("audioRating.scale",e)):t=this.defaultRatingScaleMessage(mA.AUDIO_RATING_SCORE),t}validateVideoRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(mA.VIDEO_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("videoRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("videoRating.scale",e)):t=this.defaultRatingScaleMessage(mA.VIDEO_RATING_SCORE),t}validateScreenshareRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(mA.SCREEN_SHARE_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("screenshareRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("screenshareRating.scale",e)):t=this.defaultRatingScaleMessage(mA.SCREEN_SHARE_RATING_SCORE),t}validateCallSurveyTypes(e){let t="";return e.overallRating&&(t=this.valueShouldBeNumber(mA.OVERALL_RATING_SCORE,e.overallRating.score),e.overallRating.issues&&(this.isArray(e.overallRating.issues)?e.overallRating.issues.some((e=>mA.OVERALL_ISSUES[e]!==e))&&(t+="overallRating.issues array should be of type OverallIssue. "):t+="overallRating.issues should be of type Array<OverallIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("overallRating.scale",e.overallRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("overallRating",e.overallRating)),e.audioRating&&(t+=this.valueShouldBeNumber(mA.AUDIO_RATING_SCORE,e.audioRating.score),e.audioRating.issues&&(this.isArray(e.audioRating.issues)?e.audioRating.issues.some((e=>mA.AUDIO_ISSUES[e]!==e))&&(t+="audioRating.issues array should be of type AudioIssue. "):t+="audioRating.issues should be of type Array<AudioIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("audioRating.scale",e.audioRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("audioRating",e.audioRating)),e.videoRating&&(t+=this.valueShouldBeNumber(mA.VIDEO_RATING_SCORE,e.videoRating.score),e.videoRating.issues&&(this.isArray(e.videoRating.issues)?e.videoRating.issues.some((e=>mA.VIDEO_ISSUES[e]!==e))&&(t+="videoRating.issues array should be of type VideoIssue. "):t+="videoRating.issues should be of type Array<VideoIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("videoRating.scale",e.videoRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("videoRating",e.videoRating)),e.screenshareRating&&(t+=this.valueShouldBeNumber(mA.SCREEN_SHARE_RATING_SCORE,e.screenshareRating.score),e.screenshareRating.issues&&(this.isArray(e.screenshareRating.issues)?e.screenshareRating.issues.some((e=>mA.SCREENSHARE_ISSUES[e]!==e))&&(t+="screenshareRating.issues array should be of type ScreenshareIssue. "):t+="screenshareRating.issues should be of type Array<ScreenshareIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("screenshareRating.scale",e.screenshareRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("screenshareRating",e.screenshareRating)),t}isNumber(e){return null!==e&&"number"==typeof e}isArray(e){return null!==e&&Array.isArray(e)}isValidFiveStarRating(e){return null==e||void 0!==e.scale||e.score>=1&&e.score<=5}isRatingValueMatchesRatingScale(e,t){return e>=t.lowerBound&&e<=t.upperBound}isValidQualityThreshold(e){return e.lowScoreThreshold>=e.lowerBound&&e.lowScoreThreshold<=e.upperBound}isValidRatingScale(e){return e.lowerBound>=0&&e.upperBound<=100}valueShouldBeNumber(e,t){return this.isNumber(t)?"":`${e} should be of type number. `}ratingScaleShouldNotHaveUnexpectedProperties(e,t){let i="";if(!t)return i;for(const n in t)void 0===mA.RATING_SCALE_KEYS[n]&&(i+=`${e} should not have ${n}. `);return i}ratingShouldNotHaveUnexpectedProperties(e,t){let i="";if(!t)return i;for(const n in t)void 0===mA.CALL_RATING_KEYS[n]&&(i+=`${e} should not have ${n}. `);return i}defaultRatingScaleMessage(e){return`In default scale ${e} should be 1 to 5. `}ratingOutOfRangeMessage(e,t){return`${e}: ${t.score} should be between ${t.scale?.lowerBound} and ${t.scale?.upperBound}. `}thresholdOutOfRangeMessage(e,t){return`${e}: ${t.scale?.lowScoreThreshold} should be between ${t.scale?.lowerBound} and ${t.scale?.upperBound}. `}ratingScaleOutOfRangeMessage(e,t){return`${e} lowerBound: ${t.scale?.lowerBound} and upperBound: ${t.scale?.upperBound} should be between 0 and 100. `}}mA.OVERALL_RATING_SCORE="overallRating.score",mA.AUDIO_RATING_SCORE="audioRating.score",mA.VIDEO_RATING_SCORE="videoRating.score",mA.SCREEN_SHARE_RATING_SCORE="screenshareRating.score",mA.NOTIFICATION_LISTENER={},mA.OVERALL_ISSUES={CallCannotInvite:"CallCannotInvite",CallCannotJoin:"CallCannotJoin",CallEndedUnexpectedly:"CallEndedUnexpectedly",HadToRejoin:"HadToRejoin",OtherIssues:"OtherIssues"},mA.AUDIO_ISSUES={AudioInterruption:"AudioInterruption",AudioNoise:"AudioNoise",AudioStoppedUnexpectedly:"AudioStoppedUnexpectedly",DistortedSpeech:"DistortedSpeech",Echo:"Echo",LowVolume:"LowVolume",NoLocalAudio:"NoLocalAudio",NoRemoteAudio:"NoRemoteAudio",OtherIssues:"OtherIssues"},mA.VIDEO_ISSUES={AudioVideoOutOfSync:"AudioVideoOutOfSync",DarkVideoReceived:"DarkVideoReceived",Freezes:"Freezes",LowQuality:"LowQuality",NoVideoReceived:"NoVideoReceived",NoVideoSent:"NoVideoSent",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},mA.SCREENSHARE_ISSUES={CannotPresent:"CannotPresent",Freezes:"Freezes",LargeDelay:"LargeDelay",LowQuality:"LowQuality",NoContentLocal:"NoContentLocal",NoContentRemote:"NoContentRemote",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},mA.CALL_RATING_KEYS={score:"score",issues:"issues",scale:"scale"},mA.RATING_SCALE_KEYS={lowerBound:"lowerBound",upperBound:"upperBound",lowScoreThreshold:"lowScoreThreshold"},mA.ACS_OVERALL_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE={CallCannotInvite:502,CallCannotJoin:501,CallEndedUnexpectedly:501,HadToRejoin:501,OtherIssues:501},mA.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},mA.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},mA.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 fA{constructor(e,t){this._eventEmitter=e,this._featureName=t}initialize(e,t,i,n,r){this._logger=r.createChild((()=>`${this._featureName}::Call(id='${e.callId}')`)),this._tsCall=e,this.updateMeetingGroupDetails(),this._tsCall.changed((()=>{this._logger.log("tsCall changed"),this.updateMeetingGroupDetails()}))}updateAudioZone(e,t){const i=Mf();return this._logger.log(`updateAudioZone toGroup=${e}, fromGroup=${t}, causeId=${i}`),this._tsCall.updateMeetingGroups(i,{scope:4,toGroup:e,fromGroup:t})}dispose(){this._meetingGroupDetails=void 0}get meetingGroupDetails(){return this._meetingGroupDetails}updateMeetingGroupDetails(){const e=this._tsCall.meetingDetails?.meetingGroups??void 0;Z.isEqual(e,this._meetingGroupDetails)||(this._meetingGroupDetails=e,this._eventEmitter.emit("meetingGroupDetailsChanged"))}}class vA{constructor(e,t,i){this._featureName=e,this._eventEmitter=t,this._optimalVideoCount=i}initialize(e,t,i,n,r){this._tsCall=e,this._logger=r,this._logger?.createChild((()=>`${this._featureName}::Call(id='${this._tsCall?.callId}')`)),this._tsCall.changed((()=>this.ovcChanged(e)))}ovcChanged(e){e?.optimalVideoCount&&e.optimalVideoCount!==this._optimalVideoCount&&(this._logger.log(`tsCall optimalVideoCount changed from ${this._optimalVideoCount} to ${e?.optimalVideoCount}`),this._eventEmitter.emit("optimalVideoCountChanged"))}}function SA(e,t){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.EVENT_SUBSCIBE_UNSUBSCRIBE,defaultErrorMessageArgs:[t,e]})}function yA(){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.UNAVAILABLE})}function CA(e){return Z.isString(e)?e:e?.message??"Unknown"}function TA(e){throw e instanceof le?e:new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.UNKNOWN_ERROR})}function EA(){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.PENDING_OPERATION})}function bA(){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.UNSUPPORTED_OPERATION})}function _A(e){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.INVALID_STATE,defaultErrorMessageArgs:[e]})}function IA(e){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.FAILED_TO_INITIALIZE,originalError:e})}class wA{constructor(e){this._tsCall=e,this._sourceIdMapping=new Map,this._participantIdMapping=new Map,this._listenerHandles=[],this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._removeMapping(e)}))),this._tsCall.participants.forEach((e=>{this._updateMapping(e)}))}_updateMapping(e){e.endpoints?.endpointDetails?.forEach((t=>{const i=t.mediaStreams?.find((e=>"audio"===e.type));if(i){const n={sourceId:i.sourceId,participantId:t.participantId,mri:e.id};this._sourceIdMapping.set(i.sourceId,n),this._participantIdMapping.set(t.participantId,n)}}))}_removeMapping(e){e.endpoints?.endpointDetails?.forEach((e=>{const t=e.mediaStreams?.find((e=>"audio"===e.type));t&&(this._sourceIdMapping.delete(t.sourceId),this._participantIdMapping.delete(e.participantId))}))}findParticipantInfoBySourceId(e){return this._sourceIdMapping.get(e)}findParticipantInfoByParticipantId(e){return this._participantIdMapping.get(e)}dispose(){this._sourceIdMapping.clear(),this._participantIdMapping.clear(),this._listenerHandles.forEach((e=>e.dispose()))}}class AA{constructor(e,t){this._tsCall=e,this._telemetryLogManager=t}sendActionEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,...e};this._telemetryLogManager.sendEvent({name:aE.acs_calling_unmixed_audio,tenant:xv,properties:t})}}class PA{constructor(e,t){this._unmixedAudioTelemetryLogger=e,this._action=t,this._correlationId=Mf()}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(e,t){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"failure",correlationId:this._correlationId,failureReason:e.message,...t,additionalDetails:{..._b(e)}})}}class RA{constructor(e,t){this._waitTimeoutInMs=e,this._expectedState=t,this._result=jT(),this._wait=WT((()=>this._result.promise),this._waitTimeoutInMs)}updateState(e){this._result.isPending()&&(e===this._expectedState?this._result.resolve():this._result.reject(new Error(`Unexpected active state: ${e}`)))}get waitState(){return this._expectedState}async wait(){await this._wait}cancel(){this._result.isPending()&&this._result.reject(new Error("Operation cancelled"))}}class MA{constructor(e,t){this._logger=e.createChild(`AudioContext:${t}`),this._eventEmitter=new OE.EventEmitter;const i=new AudioContext,n=()=>{this._logger.info(`The AudioContext:${t} state changed to ${i.state}`),this._eventEmitter.emit("stateChanged"),"closed"===i.state&&(i.removeEventListener("statechange",n),this._eventEmitter.removeAllListeners())};i.addEventListener("statechange",n),this._audioContext=i}async resume(e=0){if("closed"===this._audioContext.state)throw _A(this._audioContext.state);if("running"===this._audioContext.state)return;const t=new RA(e,!0);return this._audioContext.resume().then((()=>{t.updateState(!0),this._logger.info("resumed")})).catch((e=>{this._logger.info(`Failed to resume: ${CA(e)}`),t.updateState(!1)})),t.wait()}async close(){"closed"!==this._audioContext.state&&await this._audioContext.close().then((()=>{this._logger.info("closed")})).catch((e=>{this._logger.info(`Failed to close: ${CA(e)}`)}))}get state(){return this._audioContext.state}get value(){return this._audioContext}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}}function DA(e){switch(e){case uA.Uninitialized:return"Uninitialized";case uA.Initializing:return"Initializing";case uA.Initialized:return"Initialized";case uA.Destroyed:return"Destroyed";case uA.Aborted:return"Aborted"}}!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized",e[e.Destroyed=3]="Destroyed",e[e.Aborted=4]="Aborted"}(uA||(uA={}));class kA{constructor(e,t,i,n){this._state=uA.Uninitialized,this._listenerHandles=[],this._audioContextSeq=0,this._activeState=!1,this._pendingOperation=!1,this._initializedDefer=jT();try{this._tsCall=e,this._logger=t.createChild("UnmixedAudioManager"),this._eventEmitter=new T_(this._logger,{enableLogEmit:!1}),this._unmixedAudioTelemetryLogger=i,this._participantManager=new wA(e),this._destinationStreamInfoMap=new Map,this._destinationStreamInfoList=new Array(n.maxStreamSize),this._sourceStreamInfoList=new Array(n.maxStreamSize),this._maxStreamSize=n.maxStreamSize,this._operationTimeoutInMs=n.operationTimeoutInMs,this._skipProviderStateCheck=n.skipProviderStateCheck}catch(e){throw this._state=uA.Aborted,t.info(`Failed to create UnmixedAudioManager: ${CA(e)}`),IA(e)}}async initialize(){if(this._state!==uA.Uninitialized)throw _A(DA(this._state));this._initializedDefer.isPending()||(this._initializedDefer=jT());const e=new PA(this._unmixedAudioTelemetryLogger,"initialize");this._state=uA.Initializing;try{if(e.logAttempt(),!this._tsCall.getUnmixedAudioProvider)throw yA();if(this._tsUnmixedAudioProvider=this._tsUnmixedAudioProvider??await this._tsCall.getUnmixedAudioProvider(),!this._tsUnmixedAudioProvider)throw yA();this._audioContext||(this._audioContext=new MA(this._logger,this._audioContextSeq++),this._audioContext.on("stateChanged",(()=>{this._updateActiveState()}))),0===this._listenerHandles.length&&(this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onStreamSourcesUpdated",(e=>{this._state===uA.Initialized?this._onStreamSourcesUpdatedHandler(e):this._logger.error(`Cannot attach _onStreamSourcesUpdatedHandler listener - this._state:${this._state}`)}))),this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onActiveStateChanged",(()=>{this._state===uA.Initialized?this._updateActiveState():this._logger.error(`Cannot attach _updateActiveState listener - this._state:${this._state}`)})))),e.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=uA.Initialized,this._initializedDefer.resolve(),this._updateActiveState()}catch(t){this._state=uA.Uninitialized;const i=CA(t);this._logger.error(`Failed to initialize: ${i}`);const n=IA(t);e.logFailure(n),this._initializedDefer.reject(n)}return this._initializedDefer.promise}async enableUnmixedAudio(){const e=new PA(this._unmixedAudioTelemetryLogger,"enable");try{if(![uA.Uninitialized,uA.Initializing,uA.Initialized].includes(this._state))throw _A(DA(this._state));if(1===this._tsCall.callType)throw bA();if(this._pendingOperation)throw EA();if(this.isUnmixedAudioEnabled&&(this._skipProviderStateCheck||"active"===this._getUnmixedAudioProviderState())&&"running"===this._getAudioContextState())throw new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.ENABLED});this._pendingOperation=!0,e.logAttempt(),this._state===uA.Uninitialized?await this.initialize():this._state===uA.Initializing&&await this._initializedDefer.promise,void 0!==this._audioContext&&"closed"!==this._getAudioContextState()||(this._cleaupAudioNodes(),this._audioContext=new MA(this._logger,this._audioContextSeq++),this._audioContext.on("stateChanged",(()=>{this._updateActiveState()})));const t=[["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(t),this._pendingOperation=!1,e.logSuccess(),this._logger.info(`UnmixedAudio is enabled. The AudioContext state is ${this._getAudioContextState()}.`),this._updateActiveState()}catch(t){const i=this._getAudioContextState(),n=this._getUnmixedAudioProviderState(),r=CA(t);this._logger.error(`Failed to enable unmixed audio: ${r}. isEnabled=${this.isUnmixedAudioEnabled}, AudioContext=${i}, UnmixedAudio=${n}`);const s={audioContextState:i,unmixedAudioState:n},a=function(e,t){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.FAILED_TO_ENABLE,defaultErrorMessageArgs:[t.audioContextState||"undefined",t.unmixedAudioState||"undefined"],originalError:e})}(t,s);!1===this._pendingOperation&&TA(a),e.logFailure(a,s),this._pendingOperation=!1,TA(a)}}async disableUnmixedAudio(){const e=new PA(this._unmixedAudioTelemetryLogger,"disable");try{if(![uA.Initializing,uA.Initialized].includes(this._state))throw _A(DA(this._state));if(1===this._tsCall.callType)throw bA();if(this._pendingOperation)throw EA();if(!this.isUnmixedAudioEnabled)throw new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.DISABLED});this._pendingOperation=!0,e.logAttempt(),this._state===uA.Initializing&&await this._initializedDefer.promise;const t=[["disable spatial audio config",this._enableSpatialAudio(!1)]];await this._runTasks(t),this._pendingOperation=!1,e.logSuccess(),this._logger.info("UnmixedAudio is disabled")}catch(t){const i=this._getAudioContextState(),n=this._getUnmixedAudioProviderState(),r=CA(t);this._logger.info(`Failed to disable unmixed audio: ${r}. isEnabled=${this.isUnmixedAudioEnabled}, AudioContext=${i}, UnmixedAudio=${n}`);const s={audioContextState:i,unmixedAudioState:n},a=function(e,t){return new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.FAILED_TO_DISABLE,defaultErrorMessageArgs:[t.audioContextState||"undefined",t.unmixedAudioState||"undefined"],originalError:e})}(t,s);!1===this._pendingOperation&&TA(a),e.logFailure(a,s),this._pendingOperation=!1,TA(a)}}get isUnmixedAudioActive(){return this._state===uA.Initialized&&"active"===this._getUnmixedAudioProviderState()&&"running"===this._getAudioContextState()}get isUnmixedAudioEnabled(){return this._state===uA.Initialized&&(this._tsUnmixedAudioProvider?.configured??!1)}getAudioSourceIdsFromParticipantIds(e){return e.map((e=>this._participantManager.findParticipantInfoByParticipantId(e.participantId)?.sourceId)).filter((e=>void 0!==e))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._state!==uA.Destroyed&&(this._state=uA.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(new le({defaultError:ee.FEATURES.UNMIXED_AUDIO.DISPOSED})),this._listenerHandles.forEach((e=>e.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(((e,t)=>{const i=this._destinationStreamInfoList[t];void 0!==e&&void 0!==i&&e.audioNode.disconnect(i.audioNode),this._sourceStreamInfoList[t]=void 0,this._destinationStreamInfoList[t]=void 0})),this._destinationStreamInfoMap.clear()}_onStreamSourcesUpdatedHandler(e){const t=this._audioContext?.value;if(void 0===t||"running"!==t.state)return void this._logger.warn(`Dropping onStreamSourcesUpdated event because audioContext.state is ${t?.state}`);const i=[];for(let n=0;n<this._maxStreamSize;n++){const r=n<e.length?e[n]:0,s=r?this._participantManager.findParticipantInfoBySourceId(r):void 0;let a=this._destinationStreamInfoList[n],o=this._sourceStreamInfoList[n];if(void 0===s)void 0!==a&&void 0!==o&&(o.audioNode.disconnect(a.audioNode),this._destinationStreamInfoList[n]=void 0);else{const e=this._tsUnmixedAudioProvider?.streams[n]??void 0;if(void 0!==o&&o.mediaStream!==e&&(void 0!==a&&o.audioNode.disconnect(a.audioNode),o=void 0,this._sourceStreamInfoList[n]=void 0),!e)continue;let r=!1;void 0!==o&&void 0!==a&&s.participantId!==a.participantId&&(o.audioNode.disconnect(a.audioNode),a=void 0,this._destinationStreamInfoList[n]=void 0),void 0===a&&(a=this._destinationStreamInfoMap.get(s.participantId),void 0===a&&(a={participantId:s.participantId,identifier:kS(s.mri),audioNode:t.createMediaStreamDestination()},this._destinationStreamInfoMap.set(s.participantId,a)),this._destinationStreamInfoList[n]=a,r=!0),void 0===o&&(o={mediaStream:e,audioNode:t.createMediaStreamSource(e)},this._sourceStreamInfoList[n]=o,r=!0),r&&o.audioNode.connect(a.audioNode),i.push({id:s.sourceId,stream:a.audioNode.stream,participantId:s.participantId,identifier:a.identifier})}}this._eventEmitter.emit("participantSpeaking",{speakers:i})}async _enableSpatialAudio(e){await this._tsCall.setAudioMidcallConfigJson({enableSpatialAudio:e})}async _runTasks(e){let t;if((await Promise.allSettled(e.map((e=>e[1])))).forEach(((i,n)=>{"rejected"===i.status&&(this._logger.info(`Failed to ${e[n][0]}: ${CA(i.reason)}}`),t=i)})),void 0!==t)throw t.reason}_updateActiveState(){const e=this.isUnmixedAudioActive;e!==this._activeState&&(this._activeState=e,this._eventEmitter.emit("activeStateChanged"))}}class OA{constructor(){this._isEnabled=vy().calling.teamsMeetingAudioConferencing.enabled,this._supportedConversationTypes=vy().calling.teamsMeetingAudioConferencing.supportedConversationTypes}initialize(e,t,i,n){this._logger=n.createChild((()=>`teamsMeetingAudioConferencing::Call(id='${e.callId}')`)),this._tsCall=e,this._telemetryLogManager=i,this._internalCallAgent=t;const r="initialize";if(this.sendFeatureUsage(r,oE.initialize),!this.isSupportedConversationType()){const e=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(e.message),this.sendFeatureUsage(r,oE.failure,e),e}this.sendFeatureUsage(r,oE.success)}getTeamsMeetingAudioConferencingDetails(){const e="getTeamsMeetingAudioConferencingDetails";if(this.sendFeatureUsage(e,oE.attempt),!this._isEnabled){const t=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.DISABLED});return this._logger.error(t.message),this.sendFeatureUsage(e,oE.failure,t),Promise.reject(t)}if(!this.isSupportedConversationType()){const t=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});return this._logger.error(t.message),this.sendFeatureUsage(e,oE.failure,t),Promise.reject(t)}let t;if(3!==this._tsCall.state)return t=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNAVAILABLE_BEFORE_JOINING}),10===this._tsCall.state&&(t=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNVAILABLE_IN_LOBBY})),this.sendFeatureUsage(e,oE.failure,t),this._logger.error(t.message),Promise.reject(t);let i={phoneConferenceId:"",phoneNumbers:[]};try{const t=this._tsCall?.meetingDetails?.pstnDetails?.acpMcuInfo?.settings,n=this._tsCall?.meetingDetails?.pstnDetails?.meetingInvitePhoneNumbers;if(t||n){const e=t?.participantPasscode||"",r=n?.flatMap((e=>e.number?(()=>{const t=e.isTollFree?void 0:kS(nS+e.number),i=e.isTollFree?kS(nS+e.number):void 0;return{cityName:e?.cityName,countryName:e?.countryName,tollPhoneNumber:t,tollFreePhoneNumber:i}})():[]))||[];if(null===r||0===r.length){const e={cityName:void 0,countryName:void 0,tollPhoneNumber:t?.tollNumber&&kS(nS+t?.tollNumber),tollFreePhoneNumber:t?.tollFreeNumber&&kS(nS+t?.tollFreeNumber)};r.push(e)}i={phoneConferenceId:e,phoneNumbers:r},this._logger.info("Teams meeting audio conferencing details was retrieved successfully")}return this.sendFeatureUsage(e,oE.success),Promise.resolve(i)}catch(t){const i=new le({defaultError:ee.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.GET_DETAILS_FAILED,originalError:t});throw this.sendFeatureUsage(e,oE.failure,i),i}}isSupportedConversationType(){const e=this._tsCall.conversationType;let t=this._supportedConversationTypes.find((t=>t===e));return this._logger.info(`TeamsMeetingAudioConferencingDetails::ConversationType = \n ${e}. ConversationType is supported = ${t}`),t}sendFeatureUsage(e,t,i){let n=i?{code:i?.code||ne,subCode:i?.subCode||0,failureReason:i?.message||"",..._b(i)}:void 0;hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"TeamsMeetingAudioConferencing",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}var NA,LA=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.TraceLevel=void 0,function(e){e[e.Error=10]="Error",e[e.Warning=15]="Warning",e[e.Info=50]="Info"}(t.TraceLevel||(t.TraceLevel={}))})),xA=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MessageTrackingOption=t.ConnectionState=t.ServiceGeneratedClientIdName=t.SystemCommandsStateName=t.ConfigurationName=t.SystemSessionStateName=t.StateSubscriptionsName=void 0,t.StateSubscriptionsName="ConfigStateSubscriptions",t.SystemSessionStateName="systemSessionState",t.ConfigurationName="config",t.SystemCommandsStateName="systemCommands",t.ServiceGeneratedClientIdName="serviceGeneratedClientId",function(e){e[e.Disconnected=0]="Disconnected",e[e.Connected=1]="Connected",e[e.Connecting=2]="Connecting"}(t.ConnectionState||(t.ConnectionState={})),function(e){e[e.All=0]="All",e[e.Last=1]="Last",e[e.None=2]="None"}(t.MessageTrackingOption||(t.MessageTrackingOption={}))})),FA=function(e,t){return function(){return e.apply(t,arguments)}},UA=Object.prototype.toString,BA=(NA=Object.create(null),function(e){var t=UA.call(e);return NA[t]||(NA[t]=t.slice(8,-1).toLowerCase())});function VA(e){return e=e.toLowerCase(),function(t){return BA(t)===e}}function HA(e){return Array.isArray(e)}function $A(e){return void 0===e}var jA=VA("ArrayBuffer");function GA(e){return"number"==typeof e}function qA(e){return null!==e&&"object"==typeof e}function zA(e){if("object"!==BA(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var WA=VA("Date"),KA=VA("File"),JA=VA("Blob"),YA=VA("FileList");function QA(e){return"[object Function]"===UA.call(e)}var ZA=VA("URLSearchParams");function XA(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),HA(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.call(null,e[r],r,e)}var eP,tP=(eP="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return eP&&e instanceof eP}),iP=VA("HTMLFormElement"),nP=function(e){return function(t,i){return e.call(t,i)}}(Object.prototype.hasOwnProperty),rP={isArray:HA,isArrayBuffer:jA,isBuffer:function(e){return null!==e&&!$A(e)&&null!==e.constructor&&!$A(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||UA.call(e)===t||QA(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&jA(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:GA,isObject:qA,isPlainObject:zA,isEmptyObject:function(e){return e&&0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype},isUndefined:$A,isDate:WA,isFile:KA,isBlob:JA,isFunction:QA,isStream:function(e){return qA(e)&&QA(e.pipe)},isURLSearchParams:ZA,isStandardBrowserEnv:function(){var e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:XA,merge:function e(){var t={};function i(i,n){zA(t[n])&&zA(i)?t[n]=e(t[n],i):zA(i)?t[n]=e({},i):HA(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)XA(arguments[n],i);return t},extend:function(e,t,i){return XA(t,(function(t,n){e[n]=i&&"function"==typeof t?FA(t,i):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,i,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,i&&Object.assign(e.prototype,i)},toFlatObject:function(e,t,i,n){var r,s,a,o={};if(t=t||{},null==e)return t;do{for(s=(r=Object.getOwnPropertyNames(e)).length;s-- >0;)a=r[s],n&&!n(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==i&&Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:BA,kindOfTest:VA,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var n=e.indexOf(t,i);return-1!==n&&n===i},toArray:function(e){if(!e)return null;if(HA(e))return e;var t=e.length;if(!GA(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:tP,isFileList:YA,forEachEntry:function(e,t){for(var i,n=(e&&e[Symbol.iterator]).call(e);(i=n.next())&&!i.done;){var r=i.value;t.call(e,r[0],r[1])}},matchAll:function(e,t){for(var i,n=[];null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:iP,hasOwnProperty:nP};function sP(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}rP.inherits(sP,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var aP=sP.prototype,oP={};["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(e){oP[e]={value:e}})),Object.defineProperties(sP,oP),Object.defineProperty(aP,"isAxiosError",{value:!0}),sP.from=function(e,t,i,n,r,s){var a=Object.create(aP);return rP.toFlatObject(e,a,(function(e){return e!==Error.prototype})),sP.call(a,e.message,t,i,n,r),a.cause=e,a.name=e.name,s&&Object.assign(a,s),a};var lP=sP,cP="object"==typeof self?self.FormData:window.FormData;function dP(e){return rP.isPlainObject(e)||rP.isArray(e)}function uP(e){return rP.endsWith(e,"[]")?e.slice(0,-2):e}function hP(e,t,i){return e?e.concat(t).map((function(e,t){return e=uP(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}var gP=rP.toFlatObject(rP,{},null,(function(e){return/^is[A-Z]/.test(e)})),pP=function(e,t,i){if(!rP.isObject(e))throw new TypeError("target must be an object");t=t||new(cP||FormData);var n=(i=rP.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!rP.isUndefined(t[e])}))).metaTokens,r=i.visitor||c,s=i.dots,a=i.indexes,o=(i.Blob||"undefined"!=typeof Blob&&Blob)&&function(e){return e&&rP.isFunction(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator]}(t);if(!rP.isFunction(r))throw new TypeError("visitor must be a function");function l(e){if(null===e)return"";if(rP.isDate(e))return e.toISOString();if(!o&&rP.isBlob(e))throw new lP("Blob is not supported. Use a Buffer instead.");return rP.isArrayBuffer(e)||rP.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function c(e,i,r){var o=e;if(e&&!r&&"object"==typeof e)if(rP.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(rP.isArray(e)&&function(e){return rP.isArray(e)&&!e.some(dP)}(e)||rP.isFileList(e)||rP.endsWith(i,"[]")&&(o=rP.toArray(e)))return i=uP(i),o.forEach((function(e,n){!rP.isUndefined(e)&&t.append(!0===a?hP([i],n,s):null===a?i:i+"[]",l(e))})),!1;return!!dP(e)||(t.append(hP(r,i,s),l(e)),!1)}var d=[],u=Object.assign(gP,{defaultVisitor:c,convertValue:l,isVisitable:dP});if(!rP.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!rP.isUndefined(i)){if(-1!==d.indexOf(i))throw Error("Circular reference detected in "+n.join("."));d.push(i),rP.forEach(i,(function(i,s){!0===(!rP.isUndefined(i)&&r.call(t,i,rP.isString(s)?s.trim():s,n,u))&&e(i,n?n.concat(s):[s])})),d.pop()}}(e),t};function mP(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'\(\)~]|%20|%00/g,(function(e){return t[e]}))}function fP(e,t){this._pairs=[],e&&pP(e,this,t)}var vP=fP.prototype;vP.append=function(e,t){this._pairs.push([e,t])},vP.toString=function(e){var t=e?function(t){return e.call(this,t,mP)}:mP;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var SP=fP;function yP(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var CP=function(e,t,i){if(!t)return e;var n=e.indexOf("#");-1!==n&&(e=e.slice(0,n));var r,s=i&&i.encode||yP,a=i&&i.serialize;return(r=a?a(t,i):rP.isURLSearchParams(t)?t.toString():new SP(t,i).toString(s))&&(e+=(-1===e.indexOf("?")?"?":"&")+r),e};function TP(){this.handlers=[]}TP.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1},TP.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},TP.prototype.clear=function(){this.handlers&&(this.handlers=[])},TP.prototype.forEach=function(e){rP.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var EP=TP,bP=function(e,t){rP.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))},_P={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},IP={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:SP,FormData,Blob},protocols:["http","https","file","blob","url","data"]},wP=function(e){function t(e,i,n,r){var s=e[r++],a=Number.isFinite(+s),o=r>=e.length;return s=!s&&rP.isArray(n)?n.length:s,o?(rP.hasOwnProperty(n,s)?n[s]=[n[s],i]:n[s]=i,!a):(n[s]&&rP.isObject(n[s])||(n[s]=[]),t(e,i,n[s],r)&&rP.isArray(n[s])&&(n[s]=function(e){var t,i,n={},r=Object.keys(e),s=r.length;for(t=0;t<s;t++)n[i=r[t]]=e[i];return n}(n[s])),!a)}if(rP.isFormData(e)&&rP.isFunction(e.entries)){var i={};return rP.forEachEntry(e,(function(e,n){t(function(e){return rP.matchAll(/\w+|\[(\w*)]/g,e).map((function(e){return"[]"===e[0]?"":e[1]||e[0]}))}(e),n,i,0)})),i}return null},AP=rP.isStandardBrowserEnv()?{write:function(e,t,i,n,r,s){var a=[];a.push(e+"="+encodeURIComponent(t)),rP.isNumber(i)&&a.push("expires="+new Date(i).toGMTString()),rP.isString(n)&&a.push("path="+n),rP.isString(r)&&a.push("domain="+r),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},PP=function(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t},RP=["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"],MP=rP.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");function n(e){var n=e;return t&&(i.setAttribute("href",n),n=i.href),i.setAttribute("href",n),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}return e=n(window.location.href),function(t){var i=rP.isString(t)?n(t):t;return i.protocol===e.protocol&&i.host===e.host}}():function(){return!0};function DP(e,t,i){lP.call(this,null==e?"canceled":e,lP.ERR_CANCELED,t,i),this.name="CanceledError"}rP.inherits(DP,lP,{__CANCEL__:!0});var kP=DP,OP=function(e){return new Promise((function(t,i){var n,r=e.data,s=e.headers,a=e.responseType,o=e.withXSRFToken;function l(){e.cancelToken&&e.cancelToken.unsubscribe(n),e.signal&&e.signal.removeEventListener("abort",n)}rP.isFormData(r)&&rP.isStandardBrowserEnv()&&delete s["Content-Type"];var c=new XMLHttpRequest;if(e.auth){var d=e.auth.username||"",u=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.Authorization="Basic "+btoa(d+":"+u)}var h=PP(e.baseURL,e.url);function g(){if(c){var n="getAllResponseHeaders"in c?function(e){var t,i,n,r={};return e?(rP.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=rP.trim(e.slice(0,n)).toLowerCase(),i=rP.trim(e.slice(n+1)),t){if(r[t]&&RP.indexOf(t)>=0)return;r[t]="set-cookie"===t?(r[t]?r[t]:[]).concat([i]):r[t]?r[t]+", "+i:i}})),r):r}(c.getAllResponseHeaders()):null;(function(e,t,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new lP("Request failed with status code "+i.status,[lP.ERR_BAD_REQUEST,lP.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)})((function(e){t(e),l()}),(function(e){i(e),l()}),{data:a&&"text"!==a&&"json"!==a?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:e,request:c}),c=null}}if(c.open(e.method.toUpperCase(),CP(h,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=g:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(g)},c.onabort=function(){c&&(i(new lP("Request aborted",lP.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new lP("Network Error",lP.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",n=e.transitional||_P;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new lP(t,n.clarifyTimeoutError?lP.ETIMEDOUT:lP.ECONNABORTED,e,c)),c=null},rP.isStandardBrowserEnv()&&(o&&rP.isFunction(o)&&(o=o(e)),o||!1!==o&&MP(h))){var p=e.xsrfHeaderName&&e.xsrfCookieName&&AP.read(e.xsrfCookieName);p&&(s[e.xsrfHeaderName]=p)}"setRequestHeader"in c&&rP.forEach(s,(function(e,t){void 0===r&&"content-type"===t.toLowerCase()?delete s[t]:c.setRequestHeader(t,e)})),rP.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),a&&"json"!==a&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(n=function(t){c&&(i(!t||t.type?new kP(null,e,c):t),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(n),e.signal&&(e.signal.aborted?n():e.signal.addEventListener("abort",n))),r||!1===r||0===r||""===r||(r=null);var m=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(h);m&&-1===IP.protocols.indexOf(m)?i(new lP("Unsupported protocol "+m+":",lP.ERR_BAD_REQUEST,e)):c.send(r)}))},NP={"Content-Type":"application/x-www-form-urlencoded"};function LP(e,t){!rP.isUndefined(e)&&rP.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var xP={transitional:_P,adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=OP),e}(),transformRequest:[function(e,t){bP(t,"Accept"),bP(t,"Content-Type");var i,n=t&&t["Content-Type"]||"",r=n.indexOf("application/json")>-1,s=rP.isObject(e);if(s&&rP.isHTMLForm(e)&&(e=new FormData(e)),rP.isFormData(e))return r?JSON.stringify(wP(e)):e;if(rP.isArrayBuffer(e)||rP.isBuffer(e)||rP.isStream(e)||rP.isFile(e)||rP.isBlob(e))return e;if(rP.isArrayBufferView(e))return e.buffer;if(rP.isURLSearchParams(e))return LP(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();if(s){if(-1!==n.indexOf("application/x-www-form-urlencoded"))return function(e,t){return pP(e,new IP.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=rP.isFileList(e))||n.indexOf("multipart/form-data")>-1){var a=this.env&&this.env.FormData;return pP(i?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||r?(LP(t,"application/json"),function(e){if(rP.isString(e))try{return(0,JSON.parse)(e),rP.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||xP.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&rP.isString(e)&&(i&&!this.responseType||n)){var r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw lP.from(e,lP.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:IP.classes.FormData,Blob:IP.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};rP.forEach(["delete","get","head"],(function(e){xP.headers[e]={}})),rP.forEach(["post","put","patch"],(function(e){xP.headers[e]=rP.merge(NP)}));var FP=xP,UP=function(e,t,i,n){var r=this||FP;return rP.forEach(n,(function(n){e=n.call(r,e,t,i)})),e},BP=function(e){return!(!e||!e.__CANCEL__)};function VP(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new kP}var HP=function(e){return VP(e),e.headers=e.headers||{},e.data=UP.call(e,e.data,e.headers,null,e.transformRequest),bP(e.headers,"Accept"),bP(e.headers,"Content-Type"),e.headers=rP.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),rP.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||FP.adapter)(e).then((function(t){return VP(e),t.data=UP.call(e,t.data,t.headers,t.status,e.transformResponse),t}),(function(t){return BP(t)||(VP(e),t&&t.response&&(t.response.data=UP.call(e,t.response.data,t.response.headers,t.response.status,e.transformResponse))),Promise.reject(t)}))},$P=function(e,t){t=t||{};var i={};function n(e,t){return rP.isPlainObject(e)&&rP.isPlainObject(t)?rP.merge(e,t):rP.isEmptyObject(t)?rP.merge({},e):rP.isPlainObject(t)?rP.merge({},t):rP.isArray(t)?t.slice():t}function r(i){return rP.isUndefined(t[i])?rP.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function s(e){if(!rP.isUndefined(t[e]))return n(void 0,t[e])}function a(i){return rP.isUndefined(t[i])?rP.isUndefined(e[i])?void 0:n(void 0,e[i]):n(void 0,t[i])}function o(i){return i in t?n(e[i],t[i]):i in e?n(void 0,e[i]):void 0}var l={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o};return rP.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||r,n=t(e);rP.isUndefined(n)&&t!==o||(i[e]=n)})),i},jP="0.28.1",GP=jP,qP={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){qP[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var zP={};qP.transitional=function(e,t,i){function n(e,t){return"[Axios v"+GP+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,s){if(!1===e)throw new lP(n(r," has been removed"+(t?" in "+t:"")),lP.ERR_DEPRECATED);return t&&!zP[r]&&(zP[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s)}};var WP={assertOptions:function(e,t,i){if("object"!=typeof e)throw new lP("options must be an object",lP.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),r=n.length;r-- >0;){var s=n[r],a=t[s];if(a){var o=e[s],l=void 0===o||a(o,s,e);if(!0!==l)throw new lP("option "+s+" must be "+l,lP.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new lP("Unknown option "+s,lP.ERR_BAD_OPTION)}},validators:qP},KP=WP.validators;function JP(e){this.defaults=e,this.interceptors={request:new EP,response:new EP}}JP.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=$P(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;void 0!==i&&WP.assertOptions(i,{silentJSONParsing:KP.transitional(KP.boolean),forcedJSONParsing:KP.transitional(KP.boolean),clarifyTimeoutError:KP.transitional(KP.boolean)},!1);var n=t.paramsSerializer;void 0!==n&&WP.assertOptions(n,{encode:KP.function,serialize:KP.function},!0),rP.isFunction(n)&&(t.paramsSerializer={serialize:n});var r=[],s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var a,o=[];if(this.interceptors.response.forEach((function(e){o.push(e.fulfilled,e.rejected)})),!s){var l=[HP,void 0];for(Array.prototype.unshift.apply(l,r),l=l.concat(o),a=Promise.resolve(t);l.length;)a=a.then(l.shift(),l.shift());return a}for(var c=t;r.length;){var d=r.shift(),u=r.shift();try{c=d(c)}catch(e){u(e);break}}try{a=HP(c)}catch(e){return Promise.reject(e)}for(;o.length;)a=a.then(o.shift(),o.shift());return a},JP.prototype.getUri=function(e){e=$P(this.defaults,e);var t=PP(e.baseURL,e.url);return CP(t,e.params,e.paramsSerializer)},rP.forEach(["delete","get","head","options"],(function(e){JP.prototype[e]=function(t,i){return this.request($P(i||{},{method:e,url:t,data:(i||{}).data}))}})),rP.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request($P(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}JP.prototype[e]=t(),JP.prototype[e+"Form"]=t(!0)}));var YP=JP;function QP(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var i=this;this.promise.then((function(e){if(i._listeners){for(var t=i._listeners.length;t-- >0;)i._listeners[t](e);i._listeners=null}})),this.promise.then=function(e){var t,n=new Promise((function(e){i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new kP(e,n,r),t(i.reason))}))}QP.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},QP.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},QP.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},QP.source=function(){var e;return{token:new QP((function(t){e=t})),cancel:e}};var ZP=QP,XP=function e(t){var i=new YP(t),n=FA(YP.prototype.request,i);return rP.extend(n,YP.prototype,i),rP.extend(n,i),n.create=function(i){return e($P(t,i))},n}(FP);XP.Axios=YP,XP.CanceledError=kP,XP.CancelToken=ZP,XP.isCancel=BP,XP.VERSION=jP,XP.toFormData=pP,XP.AxiosError=lP,XP.Cancel=XP.CanceledError,XP.all=function(e){return Promise.all(e)},XP.spread=function(e){return function(t){return e.apply(null,t)}},XP.isAxiosError=function(e){return rP.isObject(e)&&!0===e.isAxiosError},XP.formToJSON=function(e){return wP(rP.isHTMLForm(e)?new FormData(e):e)};var eR=XP,tR=XP;eR.default=tR;for(var iR=eR,nR=G((function(e){var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(t){var i=new Uint8Array(16);e.exports=function(){return t(i),i}}else{var n=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)3&t||(e=4294967296*Math.random()),n[t]=e>>>((3&t)<<3)&255;return n}}})),rR=[],sR=0;sR<256;++sR)rR[sR]=(sR+256).toString(16).substr(1);var aR,oR,lR=function(e,t){var i=t||0,n=rR;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")},cR=0,dR=0,uR=function(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||nR)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var s=0;s<16;++s)t[n+s]=r[s];return t||lR(r)},hR=uR;hR.v1=function(e,t,i){var n=t&&i||0,r=t||[],s=(e=e||{}).node||aR,a=void 0!==e.clockseq?e.clockseq:oR;if(null==s||null==a){var o=nR();null==s&&(s=aR=[1|o[0],o[1],o[2],o[3],o[4],o[5]]),null==a&&(a=oR=16383&(o[6]<<8|o[7]))}var l=void 0!==e.msecs?e.msecs:(new Date).getTime(),c=void 0!==e.nsecs?e.nsecs:dR+1,d=l-cR+(c-dR)/1e4;if(d<0&&void 0===e.clockseq&&(a=a+1&16383),(d<0||l>cR)&&void 0===e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");cR=l,dR=c,oR=a;var u=(1e4*(268435455&(l+=122192928e5))+c)%4294967296;r[n++]=u>>>24&255,r[n++]=u>>>16&255,r[n++]=u>>>8&255,r[n++]=255&u;var h=l/4294967296*1e4&268435455;r[n++]=h>>>8&255,r[n++]=255&h,r[n++]=h>>>24&15|16,r[n++]=h>>>16&255,r[n++]=a>>>8|128,r[n++]=255&a;for(var g=0;g<6;++g)r[n+g]=s[g];return t||lR(r)},hR.v4=uR;for(var gR=hR,pR=G((function(e,t){var i=j&&j.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.errorToString=void 0,t.errorToString=function(e,t){if(void 0===t&&(t=!0),null==e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,r(n(t)))}catch(e){return"Stringifying error failed"}};var n=function(e){return void 0===e&&(e=!1),function(t,n){return n instanceof Error?i({name:n.name,message:n.message,stack:e?[]:("string"==typeof n.stack?n.stack:"").split("\n").map((function(e){return e.trim()})).filter((function(e){return!!e}))},n):n}},r=function(e){var t=new WeakSet;return function(i,n){if("object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return e(i,n)}}})),mR=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.EvictingQueue=void 0;var i=function(){function e(e){this.maxSize=e,this._store=[]}return Object.defineProperty(e.prototype,"store",{get:function(){return this._store},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._store.length},enumerable:!1,configurable:!0}),e.prototype.enqueue=function(e){this._store.length>=this.maxSize&&this._store.shift(),this._store.push(e)},e.prototype.dequeue=function(){return this._store.shift()},e.prototype.clear=function(){this._store=[]},e.prototype.forEach=function(e){this._store.forEach(e)},e}();t.EvictingQueue=i})),fR=G((function(e,t){var i=j&&j.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?i(e.value):r(e.value).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=j&&j.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(e){return function(t){return l([e,t])}}function l(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleSyncCell=void 0;var r=function(){function e(e,t,i,n,r){this.m_id=e,this.m_sender=t,this.m_shouldEmitEventForAllMessages=i,this.aggregation=r,this.m_events=new OE.EventEmitter,this.m_emitUnacknowledgedEventFor=null!=n?n:xA.MessageTrackingOption.None}return e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.off=function(e,t){return this.m_events.off(e,t),this},e.prototype.removeAllListeners=function(e){return this.m_events.removeAllListeners(e),this},e.prototype.id=function(){return this.m_id},e.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},e.prototype.getAsync=function(){return i(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.m_value]}))}))},e.prototype.setAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return this.m_value=e,t={messageId:(0,gR.v4)(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"set",value:JSON.stringify(this.m_value)},this.m_sender.sendStateMessage(t),[2]}))}))},e.prototype.delete=function(){this.m_value=void 0;var e={messageId:(0,gR.v4)(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"delete",value:""};this.m_sender.sendStateMessage(e)},e.prototype.handleStateMessage=function(e){switch(e.operation){case"set":return void((JSON.stringify(this.m_value)!==e.value||this.m_shouldEmitEventForAllMessages)&&(this.m_value=JSON.parse(e.value),this.m_events.emit("valueChanged",this.m_value,e)));case"delete":return this.m_value=void 0,void this.m_events.emit("valueDeleted",this.m_value,e);default:return}},e.prototype.handleUnacknowledgedMessage=function(e){this.m_events.emit("valueUnacknowledged",e)},e.prototype.beginAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.beginAggregatedStateUpdating()},e.prototype.endAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.endAggregatedStateUpdating()},e}();t.SimpleSyncCell=r})),vR=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isPrefixDeleteMessage=void 0,t.isPrefixDeleteMessage=function(e){return"delete"===e.operation&&"prefix"===e.value}})),SR=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleSyncMap=void 0;var i=function(){function e(e,t,i,n,r){this.m_id=e,this.m_sender=t,this.m_shouldEmitEventForAllMessages=i,this.aggregation=r,this.m_events=new OE.EventEmitter,this.m_map=new Map,this.m_emitUnacknowledgedEventFor=null!=n?n:xA.MessageTrackingOption.None}return e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.off=function(e,t){return this.m_events.off(e,t),this},e.prototype.removeAllListeners=function(e){return this.m_events.removeAllListeners(e),this},e.prototype.id=function(){return this.m_id},e.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},e.prototype.get=function(e){return this.m_map.get(e)},e.prototype.set=function(e,t){this.m_map.set(e,t);var i={messageId:(0,gR.v4)(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"set",property:e,value:JSON.stringify(t)};this.m_sender.sendStateMessage(i)},e.prototype.delete=function(e){var t={messageId:(0,gR.v4)(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:e,value:""};this.performLocalDelete(t),this.m_sender.sendStateMessage(t)},e.prototype.deleteWithPrefix=function(e){var t={messageId:(0,gR.v4)(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:e,value:"prefix"};this.performLocalDelete(t),this.m_sender.sendStateMessage(t)},e.prototype.forEach=function(e){this.m_map.forEach(e)},e.prototype.handleStateMessage=function(e){switch(e.operation){case"set":return void this.handleSet(e);case"delete":return void this.handleDelete(e);default:return}},e.prototype.handleSet=function(e){if(!e.property)throw new Error("property is missing for a map.");(JSON.stringify(this.m_map.get(e.property))!==e.value||this.m_shouldEmitEventForAllMessages)&&(this.m_map.set(e.property,JSON.parse(e.value)),this.m_events.emit("valueChanged",e.property,e))},e.prototype.handleDelete=function(e){this.performLocalDelete(e),(0,vR.isPrefixDeleteMessage)(e)?this.m_events.emit("valuesDeletedWithPrefix",e.property,e):this.m_events.emit("valueDeleted",e.property||"",e)},e.prototype.handleUnacknowledgedMessage=function(e){this.m_events.emit("valueUnacknowledged",e)},e.prototype.beginAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.beginAggregatedStateUpdating()},e.prototype.endAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.endAggregatedStateUpdating()},e.prototype.performLocalDelete=function(e){var t=this;if(e.property){var i=e.property;(0,vR.isPrefixDeleteMessage)(e)?this.m_map.forEach((function(e,n){n.startsWith(i)&&t.m_map.delete(n)})):this.m_map.delete(e.property)}else this.m_map.clear()},e}();t.SimpleSyncMap=i})),yR=G((function(e){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}}})),CR=[],TR=[],ER="undefined"!=typeof Uint8Array?Uint8Array:Array,bR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_R=0;_R<64;++_R)CR[_R]=bR[_R],TR[bR.charCodeAt(_R)]=_R;function IR(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function wR(e){return CR[e>>18&63]+CR[e>>12&63]+CR[e>>6&63]+CR[63&e]}function AR(e,t,i){for(var n,r=[],s=t;s<i;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),r.push(wR(n));return r.join("")}TR["-".charCodeAt(0)]=62,TR["_".charCodeAt(0)]=63;var PR=function(e){var t,i,n=IR(e),r=n[0],s=n[1],a=new ER(function(e,t,i){return 3*(t+i)/4-i}(0,r,s)),o=0,l=s>0?r-4:r;for(i=0;i<l;i+=4)t=TR[e.charCodeAt(i)]<<18|TR[e.charCodeAt(i+1)]<<12|TR[e.charCodeAt(i+2)]<<6|TR[e.charCodeAt(i+3)],a[o++]=t>>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===s&&(t=TR[e.charCodeAt(i)]<<2|TR[e.charCodeAt(i+1)]>>4,a[o++]=255&t),1===s&&(t=TR[e.charCodeAt(i)]<<10|TR[e.charCodeAt(i+1)]<<4|TR[e.charCodeAt(i+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},RR=function(e){for(var t,i=e.length,n=i%3,r=[],s=16383,a=0,o=i-n;a<o;a+=s)r.push(AR(e,a,a+s>o?o:a+s));return 1===n?(t=e[i-1],r.push(CR[t>>2]+CR[t<<4&63]+"==")):2===n&&(t=(e[i-2]<<8)+e[i-1],r.push(CR[t>>10]+CR[t>>4&63]+CR[t<<2&63]+"=")),r.join("")},MR=function(e,t,i,n,r){var s,a,o=8*r-n-1,l=(1<<o)-1,c=l>>1,d=-7,u=i?r-1:0,h=i?-1:1,g=e[t+u];for(u+=h,s=g&(1<<-d)-1,g>>=-d,d+=o;d>0;s=256*s+e[t+u],u+=h,d-=8);for(a=s&(1<<-d)-1,s>>=-d,d+=n;d>0;a=256*a+e[t+u],u+=h,d-=8);if(0===s)s=1-c;else{if(s===l)return a?NaN:1/0*(g?-1:1);a+=Math.pow(2,n),s-=c}return(g?-1:1)*a*Math.pow(2,s-n)},DR=function(e,t,i,n,r,s){var a,o,l,c=8*s-r-1,d=(1<<c)-1,u=d>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:s-1,p=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=d):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),(t+=a+u>=1?h/l:h*Math.pow(2,1-u))*l>=2&&(a++,l/=2),a+u>=d?(o=0,a=d):a+u>=1?(o=(t*l-1)*Math.pow(2,r),a+=u):(o=t*Math.pow(2,u-1)*Math.pow(2,r),a=0));r>=8;e[i+g]=255&o,g+=p,o/=256,r-=8);for(a=a<<r|o,c+=r;c>0;e[i+g]=255&a,g+=p,a/=256,c-=8);e[i+g-p]|=128*m},kR=G((function(e,t){const i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},t.INSPECT_MAX_BYTES=50;const n=2147483647;function r(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,i)}function a(e,t,i){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const i=0|h(e,t);let n=r(i);const a=n.write(e,t);return a!==i&&(n=n.slice(0,a)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(W(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return c(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(W(e,ArrayBuffer)||e&&W(e.buffer,ArrayBuffer))return d(e,t,i);if("undefined"!=typeof SharedArrayBuffer&&(W(e,SharedArrayBuffer)||e&&W(e.buffer,SharedArrayBuffer)))return d(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,i);const a=function(e){if(s.isBuffer(e)){const t=0|u(e.length),i=r(t);return 0===i.length||e.copy(i,0,0,t),i}return void 0!==e.length?"number"!=typeof e.length||K(e.length)?r(0):c(e):"Buffer"===e.type&&Array.isArray(e.data)?c(e.data):void 0}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return o(e),r(e<0?0:0|u(e))}function c(e){const t=e.length<0?0:0|u(e.length),i=r(t);for(let n=0;n<t;n+=1)i[n]=255&e[n];return i}function d(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i),Object.setPrototypeOf(n,s.prototype),n}function u(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||W(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const i=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===i)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return q(e).length;default:if(r)return n?-1:G(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,i){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,i);case"utf8":case"utf-8":return b(this,t,i);case"ascii":return w(this,t,i);case"latin1":case"binary":return A(this,t,i);case"base64":return E(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,i);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function p(e,t,i){const n=e[t];e[t]=e[i],e[i]=n}function m(e,t,i,n,r){if(0===e.length)return-1;if("string"==typeof i?(n=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),K(i=+i)&&(i=r?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(r)return-1;i=e.length-1}else if(i<0){if(!r)return-1;i=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:f(e,t,i,n,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):f(e,[t],i,n,r);throw new TypeError("val must be string, number or Buffer")}function f(e,t,i,n,r){let s,a=1,o=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,o/=2,l/=2,i/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(r){let n=-1;for(s=i;s<o;s++)if(c(e,s)===c(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===l)return n*a}else-1!==n&&(s-=s-n),n=-1}else for(i+l>o&&(i=o-l),s=i;s>=0;s--){let i=!0;for(let n=0;n<l;n++)if(c(e,s+n)!==c(t,n)){i=!1;break}if(i)return s}return-1}function v(e,t,i,n){i=Number(i)||0;const r=e.length-i;n?(n=Number(n))>r&&(n=r):n=r;const s=t.length;let a;for(n>s/2&&(n=s/2),a=0;a<n;++a){const n=parseInt(t.substr(2*a,2),16);if(K(n))return a;e[i+a]=n}return a}function S(e,t,i,n){return z(G(t,e.length-i),e,i,n)}function y(e,t,i,n){return z(function(e){const t=[];for(let i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,n)}function C(e,t,i,n){return z(q(t),e,i,n)}function T(e,t,i,n){return z(function(e,t){let i,n,r;const s=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)i=e.charCodeAt(a),n=i>>8,r=i%256,s.push(r),s.push(n);return s}(t,e.length-i),e,i,n)}function E(e,t,i){return 0===t&&i===e.length?RR(e):RR(e.slice(t,i))}function b(e,t,i){i=Math.min(e.length,i);const n=[];let r=t;for(;r<i;){const t=e[r];let s=null,a=t>239?4:t>223?3:t>191?2:1;if(r+a<=i){let i,n,o,l;switch(a){case 1:t<128&&(s=t);break;case 2:i=e[r+1],128==(192&i)&&(l=(31&t)<<6|63&i,l>127&&(s=l));break;case 3:i=e[r+1],n=e[r+2],128==(192&i)&&128==(192&n)&&(l=(15&t)<<12|(63&i)<<6|63&n,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:i=e[r+1],n=e[r+2],o=e[r+3],128==(192&i)&&128==(192&n)&&128==(192&o)&&(l=(15&t)<<18|(63&i)<<12|(63&n)<<6|63&o,l>65535&&l<1114112&&(s=l))}}null===s?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),r+=a}return I(n)}t.kMaxLength=n,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),s.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(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,i){return a(e,t,i)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,i){return function(e,t,i){return o(e),e<=0?r(e):void 0!==t?"string"==typeof i?r(e).fill(t,i):r(e).fill(t):r(e)}(e,t,i)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(W(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),W(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let i=e.length,n=t.length;for(let r=0,s=Math.min(i,n);r<s;++r)if(e[r]!==t[r]){i=e[r],n=t[r];break}return i<n?-1:n<i?1:0},s.isEncoding=function(e){switch(String(e).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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;const n=s.allocUnsafe(t);let r=0;for(i=0;i<e.length;++i){let t=e[i];if(W(t,Uint8Array))r+t.length>n.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(n,r)):Uint8Array.prototype.set.call(n,t,r);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,r)}r+=t.length}return n},s.byteLength=h,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?b(this,0,e):g.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let e="";const i=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,i).replace(/(.{2})/g,"$1 ").trim(),this.length>i&&(e+=" ... "),"<Buffer "+e+">"},i&&(s.prototype[i]=s.prototype.inspect),s.prototype.compare=function(e,t,i,n,r){if(W(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===r&&(r=this.length),t<0||i>e.length||n<0||r>this.length)throw new RangeError("out of range index");if(n>=r&&t>=i)return 0;if(n>=r)return-1;if(t>=i)return 1;if(this===e)return 0;let a=(r>>>=0)-(n>>>=0),o=(i>>>=0)-(t>>>=0);const l=Math.min(a,o),c=this.slice(n,r),d=e.slice(t,i);for(let e=0;e<l;++e)if(c[e]!==d[e]){a=c[e],o=d[e];break}return a<o?-1:o<a?1:0},s.prototype.includes=function(e,t,i){return-1!==this.indexOf(e,t,i)},s.prototype.indexOf=function(e,t,i){return m(this,e,t,i,!0)},s.prototype.lastIndexOf=function(e,t,i){return m(this,e,t,i,!1)},s.prototype.write=function(e,t,i,n){if(void 0===t)n="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)n=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}const r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return v(this,e,t,i);case"utf8":case"utf-8":return S(this,e,t,i);case"ascii":case"latin1":case"binary":return y(this,e,t,i);case"base64":return C(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const _=4096;function I(e){const t=e.length;if(t<=_)return String.fromCharCode.apply(String,e);let i="",n=0;for(;n<t;)i+=String.fromCharCode.apply(String,e.slice(n,n+=_));return i}function w(e,t,i){let n="";i=Math.min(e.length,i);for(let r=t;r<i;++r)n+=String.fromCharCode(127&e[r]);return n}function A(e,t,i){let n="";i=Math.min(e.length,i);for(let r=t;r<i;++r)n+=String.fromCharCode(e[r]);return n}function P(e,t,i){const n=e.length;(!t||t<0)&&(t=0),(!i||i<0||i>n)&&(i=n);let r="";for(let n=t;n<i;++n)r+=J[e[n]];return r}function R(e,t,i){const n=e.slice(t,i);let r="";for(let e=0;e<n.length-1;e+=2)r+=String.fromCharCode(n[e]+256*n[e+1]);return r}function M(e,t,i){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>i)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,i,n,r,a){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<a)throw new RangeError('"value" argument is out of bounds');if(i+n>e.length)throw new RangeError("Index out of range")}function k(e,t,i,n,r){V(t,n,r,e,i,7);let s=Number(t&BigInt(4294967295));e[i++]=s,s>>=8,e[i++]=s,s>>=8,e[i++]=s,s>>=8,e[i++]=s;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[i++]=a,a>>=8,e[i++]=a,a>>=8,e[i++]=a,a>>=8,e[i++]=a,i}function O(e,t,i,n,r){V(t,n,r,e,i,7);let s=Number(t&BigInt(4294967295));e[i+7]=s,s>>=8,e[i+6]=s,s>>=8,e[i+5]=s,s>>=8,e[i+4]=s;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[i+3]=a,a>>=8,e[i+2]=a,a>>=8,e[i+1]=a,a>>=8,e[i]=a,i+8}function N(e,t,i,n,r,s){if(i+n>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function L(e,t,i,n,r){return t=+t,i>>>=0,r||N(e,0,i,4),DR(e,t,i,n,23,4),i+4}function x(e,t,i,n,r){return t=+t,i>>>=0,r||N(e,0,i,8),DR(e,t,i,n,52,8),i+8}s.prototype.slice=function(e,t){const i=this.length;(e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);let n=this[e],r=1,s=0;for(;++s<t&&(r*=256);)n+=this[e+s]*r;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);let n=this[e+--t],r=1;for(;t>0&&(r*=256);)n+=this[e+--t]*r;return n},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Y((function(e){H(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+i*2**24;return BigInt(n)+(BigInt(r)<<BigInt(32))})),s.prototype.readBigUInt64BE=Y((function(e){H(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+i;return(BigInt(n)<<BigInt(32))+BigInt(r)})),s.prototype.readIntLE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);let n=this[e],r=1,s=0;for(;++s<t&&(r*=256);)n+=this[e+s]*r;return r*=128,n>=r&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);let n=t,r=1,s=this[e+--n];for(;n>0&&(r*=256);)s+=this[e+--n]*r;return r*=128,s>=r&&(s-=Math.pow(2,8*t)),s},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);const i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);const i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Y((function(e){H(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(i<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),s.prototype.readBigInt64BE=Y((function(e){H(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+i)})),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),MR(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),MR(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),MR(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),MR(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,i,n){e=+e,t>>>=0,i>>>=0,n||D(this,e,t,i,Math.pow(2,8*i)-1,0);let r=1,s=0;for(this[t]=255&e;++s<i&&(r*=256);)this[t+s]=e/r&255;return t+i},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,i,n){e=+e,t>>>=0,i>>>=0,n||D(this,e,t,i,Math.pow(2,8*i)-1,0);let r=i-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&255;return t+i},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Y((function(e,t=0){return k(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeBigUInt64BE=Y((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeIntLE=function(e,t,i,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*i-1);D(this,e,t,i,n-1,-n)}let r=0,s=1,a=0;for(this[t]=255&e;++r<i&&(s*=256);)e<0&&0===a&&0!==this[t+r-1]&&(a=1),this[t+r]=(e/s|0)-a&255;return t+i},s.prototype.writeIntBE=function(e,t,i,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*i-1);D(this,e,t,i,n-1,-n)}let r=i-1,s=1,a=0;for(this[t+r]=255&e;--r>=0&&(s*=256);)e<0&&0===a&&0!==this[t+r+1]&&(a=1),this[t+r]=(e/s|0)-a&255;return t+i},s.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Y((function(e,t=0){return k(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeBigInt64BE=Y((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeFloatLE=function(e,t,i){return L(this,e,t,!0,i)},s.prototype.writeFloatBE=function(e,t,i){return L(this,e,t,!1,i)},s.prototype.writeDoubleLE=function(e,t,i){return x(this,e,t,!0,i)},s.prototype.writeDoubleBE=function(e,t,i){return x(this,e,t,!1,i)},s.prototype.copy=function(e,t,i,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-i&&(n=e.length-t+i);const r=n-i;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,i,n):Uint8Array.prototype.set.call(e,this.subarray(i,n),t),r},s.prototype.fill=function(e,t,i,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;let r;if(t>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(r=t;r<i;++r)this[r]=e;else{const a=s.isBuffer(e)?e:s.from(e,n),o=a.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(r=0;r<i-t;++r)this[r+t]=a[r%o]}return this};const F={};function U(e,t,i){F[e]=class extends i{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function B(e){let t="",i=e.length;const n="-"===e[0]?1:0;for(;i>=n+4;i-=3)t=`_${e.slice(i-3,i)}${t}`;return`${e.slice(0,i)}${t}`}function V(e,t,i,n,r,s){if(e>i||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${i}${n}`,new F.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,i){H(t,"offset"),void 0!==e[t]&&void 0!==e[t+i]||$(t,e.length-(i+1))}(n,r,s)}function H(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,i){if(Math.floor(e)!==e)throw H(e,i),new F.ERR_OUT_OF_RANGE(i||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${t}`,e)}U("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),U("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),U("ERR_OUT_OF_RANGE",(function(e,t,i){let n=`The value of "${e}" is out of range.`,r=i;return Number.isInteger(i)&&Math.abs(i)>2**32?r=B(String(i)):"bigint"==typeof i&&(r=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(r=B(r)),r+="n"),n+=` It must be ${t}. Received ${r}`,n}),RangeError);const j=/[^+/0-9A-Za-z-_]/g;function G(e,t){let i;t=t||1/0;const n=e.length;let r=null;const s=[];for(let a=0;a<n;++a){if(i=e.charCodeAt(a),i>55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&s.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;s.push(i)}else if(i<2048){if((t-=2)<0)break;s.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;s.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return s}function q(e){return PR(function(e){if((e=(e=e.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,i,n){let r;for(r=0;r<n&&!(r+i>=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function W(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function K(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let i=0;i<16;++i){const n=16*i;for(let r=0;r<16;++r)t[n+r]=e[i]+e[r]}return t}();function Y(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}})),OR=G((function(e,t){var i=kR.Buffer;function n(e,t){for(var i in e)t[i]=e[i]}function r(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=kR:(n(kR,t),t.Buffer=r),r.prototype=Object.create(i.prototype),n(i,r),r.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},r.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},r.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},r.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return kR.SlowBuffer(e)}})),NR=OR.Buffer;function LR(e,t){this._block=NR.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}LR.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=NR.from(e,t));for(var i=this._block,n=this._blockSize,r=e.length,s=this._len,a=0;a<r;){for(var o=s%n,l=Math.min(r-a,n-o),c=0;c<l;c++)i[o+c]=e[a+c];a+=l,(s+=l)%n==0&&this._update(i)}return this._len+=r,this},LR.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var i=8*this._len;if(i<=4294967295)this._block.writeUInt32BE(i,this._blockSize-4);else{var n=(4294967295&i)>>>0,r=(i-n)/4294967296;this._block.writeUInt32BE(r,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var s=this._hash();return e?s.toString(e):s},LR.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var xR=LR,FR=OR.Buffer,UR=[1518500249,1859775393,-1894007588,-899497514],BR=new Array(80);function VR(){this.init(),this._w=BR,xR.call(this,64,56)}function HR(e){return e<<5|e>>>27}function $R(e){return e<<30|e>>>2}function jR(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}yR(VR,xR),VR.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},VR.prototype._update=function(e){for(var t=this._w,i=0|this._a,n=0|this._b,r=0|this._c,s=0|this._d,a=0|this._e,o=0;o<16;++o)t[o]=e.readInt32BE(4*o);for(;o<80;++o)t[o]=t[o-3]^t[o-8]^t[o-14]^t[o-16];for(var l=0;l<80;++l){var c=~~(l/20),d=HR(i)+jR(c,n,r,s)+a+t[l]+UR[c]|0;a=s,s=r,r=$R(n),n=i,i=d}this._a=i+this._a|0,this._b=n+this._b|0,this._c=r+this._c|0,this._d=s+this._d|0,this._e=a+this._e|0},VR.prototype._hash=function(){var e=FR.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e};var GR=VR,qR=OR.Buffer,zR=[1518500249,1859775393,-1894007588,-899497514],WR=new Array(80);function KR(){this.init(),this._w=WR,xR.call(this,64,56)}function JR(e){return e<<1|e>>>31}function YR(e){return e<<5|e>>>27}function QR(e){return e<<30|e>>>2}function ZR(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}yR(KR,xR),KR.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},KR.prototype._update=function(e){for(var t=this._w,i=0|this._a,n=0|this._b,r=0|this._c,s=0|this._d,a=0|this._e,o=0;o<16;++o)t[o]=e.readInt32BE(4*o);for(;o<80;++o)t[o]=JR(t[o-3]^t[o-8]^t[o-14]^t[o-16]);for(var l=0;l<80;++l){var c=~~(l/20),d=YR(i)+ZR(c,n,r,s)+a+t[l]+zR[c]|0;a=s,s=r,r=QR(n),n=i,i=d}this._a=i+this._a|0,this._b=n+this._b|0,this._c=r+this._c|0,this._d=s+this._d|0,this._e=a+this._e|0},KR.prototype._hash=function(){var e=qR.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e};var XR=KR,eM=OR.Buffer,tM=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],iM=new Array(64);function nM(){this.init(),this._w=iM,xR.call(this,64,56)}function rM(e,t,i){return i^e&(t^i)}function sM(e,t,i){return e&t|i&(e|t)}function aM(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function oM(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function lM(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function cM(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}yR(nM,xR),nM.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},nM.prototype._update=function(e){for(var t=this._w,i=0|this._a,n=0|this._b,r=0|this._c,s=0|this._d,a=0|this._e,o=0|this._f,l=0|this._g,c=0|this._h,d=0;d<16;++d)t[d]=e.readInt32BE(4*d);for(;d<64;++d)t[d]=cM(t[d-2])+t[d-7]+lM(t[d-15])+t[d-16]|0;for(var u=0;u<64;++u){var h=c+oM(a)+rM(a,o,l)+tM[u]+t[u]|0,g=aM(i)+sM(i,n,r)|0;c=l,l=o,o=a,a=s+h|0,s=r,r=n,n=i,i=h+g|0}this._a=i+this._a|0,this._b=n+this._b|0,this._c=r+this._c|0,this._d=s+this._d|0,this._e=a+this._e|0,this._f=o+this._f|0,this._g=l+this._g|0,this._h=c+this._h|0},nM.prototype._hash=function(){var e=eM.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var dM=nM,uM=OR.Buffer,hM=new Array(64);function gM(){this.init(),this._w=hM,xR.call(this,64,56)}yR(gM,dM),gM.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},gM.prototype._hash=function(){var e=uM.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var pM=gM,mM=OR.Buffer,fM=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],vM=new Array(160);function SM(){this.init(),this._w=vM,xR.call(this,128,112)}function yM(e,t,i){return i^e&(t^i)}function CM(e,t,i){return e&t|i&(e|t)}function TM(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function EM(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function bM(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function _M(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function IM(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function wM(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function AM(e,t){return e>>>0<t>>>0?1:0}yR(SM,xR),SM.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},SM.prototype._update=function(e){for(var t=this._w,i=0|this._ah,n=0|this._bh,r=0|this._ch,s=0|this._dh,a=0|this._eh,o=0|this._fh,l=0|this._gh,c=0|this._hh,d=0|this._al,u=0|this._bl,h=0|this._cl,g=0|this._dl,p=0|this._el,m=0|this._fl,f=0|this._gl,v=0|this._hl,S=0;S<32;S+=2)t[S]=e.readInt32BE(4*S),t[S+1]=e.readInt32BE(4*S+4);for(;S<160;S+=2){var y=t[S-30],C=t[S-30+1],T=bM(y,C),E=_M(C,y),b=IM(y=t[S-4],C=t[S-4+1]),_=wM(C,y),I=t[S-14],w=t[S-14+1],A=t[S-32],P=t[S-32+1],R=E+w|0,M=T+I+AM(R,E)|0;M=(M=M+b+AM(R=R+_|0,_)|0)+A+AM(R=R+P|0,P)|0,t[S]=M,t[S+1]=R}for(var D=0;D<160;D+=2){M=t[D],R=t[D+1];var k=CM(i,n,r),O=CM(d,u,h),N=TM(i,d),L=TM(d,i),x=EM(a,p),F=EM(p,a),U=fM[D],B=fM[D+1],V=yM(a,o,l),H=yM(p,m,f),$=v+F|0,j=c+x+AM($,v)|0;j=(j=(j=j+V+AM($=$+H|0,H)|0)+U+AM($=$+B|0,B)|0)+M+AM($=$+R|0,R)|0;var G=L+O|0,q=N+k+AM(G,L)|0;c=l,v=f,l=o,f=m,o=a,m=p,a=s+j+AM(p=g+$|0,g)|0,s=r,g=h,r=n,h=u,n=i,u=d,i=j+q+AM(d=$+G|0,$)|0}this._al=this._al+d|0,this._bl=this._bl+u|0,this._cl=this._cl+h|0,this._dl=this._dl+g|0,this._el=this._el+p|0,this._fl=this._fl+m|0,this._gl=this._gl+f|0,this._hl=this._hl+v|0,this._ah=this._ah+i+AM(this._al,d)|0,this._bh=this._bh+n+AM(this._bl,u)|0,this._ch=this._ch+r+AM(this._cl,h)|0,this._dh=this._dh+s+AM(this._dl,g)|0,this._eh=this._eh+a+AM(this._el,p)|0,this._fh=this._fh+o+AM(this._fl,m)|0,this._gh=this._gh+l+AM(this._gl,f)|0,this._hh=this._hh+c+AM(this._hl,v)|0},SM.prototype._hash=function(){var e=mM.allocUnsafe(64);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var PM=SM,RM=OR.Buffer,MM=new Array(160);function DM(){this.init(),this._w=MM,xR.call(this,128,112)}yR(DM,PM),DM.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},DM.prototype._hash=function(){var e=RM.allocUnsafe(48);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var kM=DM,OM=G((function(e){var t=e.exports=function(e){e=e.toLowerCase();var i=t[e];if(!i)throw new Error(e+" is not supported (we accept pull requests)");return new i};t.sha=GR,t.sha1=XR,t.sha224=pM,t.sha256=dM,t.sha384=kM,t.sha512=PM})),NM=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleServicePerformanceTelemetry=t.SimpleServiceTelemetry=void 0;var i=function(){function e(e,t,i){this.backendService="SimpleService",this.clientId=e,this.sessionId=this.calculateHash(t),this.wsReconnectCount=0,this.wsState=xA.ConnectionState[xA.ConnectionState.Disconnected],this.maxRoundtripRaw=i||0,this.roundtripTelemetry=new n,this.messageHandleTelemetry=new n,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 e.prototype.addRoundtripLatency=function(e){this.roundtripRaw&&this.roundtripRaw.length<this.maxRoundtripRaw&&this.roundtripRaw.push(e),this.roundtripTelemetry.addLatency(e)},e.prototype.addMessageHandleLatency=function(e){this.messageHandleTelemetry.addLatency(e)},e.prototype.incrementAcknowledgedCount=function(e){this.incrementMessageCount(this.messageAcknowledged,e)},e.prototype.incrementRequestedCount=function(e){this.incrementMessageCount(this.messageRequested,e)},e.prototype.incrementReceivedCount=function(e){this.incrementMessageCount(this.messageReceived,e)},e.prototype.incrementMessageCount=function(e,t){var i=e[t],n=void 0===i?1:i+1;e[t]=n},e.prototype.calculateHash=function(e){return e?"".concat((new OM.sha256).update(e).digest("hex")):""},e}();t.SimpleServiceTelemetry=i;var n=function(){function e(){this.count=0,this.minValue=0,this.maxValue=0,this.avgValue=0}return e.prototype.addLatency=function(e){this.count+=1,this.avgValue=this.avgValue+(e-this.avgValue)/this.count,this.minValue=this.count>1?Math.min(e,this.minValue):e,this.maxValue=Math.max(this.maxValue,e)},e}();t.SimpleServicePerformanceTelemetry=n})),LM=G((function(e,t){var i=j&&j.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?i(e.value):r(e.value).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=j&&j.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(e){return function(t){return l([e,t])}}function l(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.StateServiceWebSocketConnection=void 0;var r=function(){function e(e,t){var r=this;this.onopen=null,this.onclose=null,this.onerror=null,this.onmessage=null,this.onlog=null,this.ws=new WebSocket(e),this.settings=t,this.ws.onopen=function(e){return i(r,void 0,void 0,(function(){return n(this,(function(t){switch(t.label){case 0:return this.onopen&&this.onopen(e),[4,this.sendSetupMessages()];case 1:return t.sent(),[2]}}))}))},this.ws.onclose=function(e){r.onclose&&r.onclose(e)},this.ws.onerror=function(e){r.onerror&&r.onerror(e)},this.ws.onmessage=function(e){r.onmessage&&r.onmessage(e)}}return e.CreateAsync=function(t,r){return i(this,void 0,void 0,(function(){return n(this,(function(i){return[2,new e(t,r)]}))}))},Object.defineProperty(e.prototype,"name",{get:function(){return"WebSocket"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this.ws.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isOpen",{get:function(){return this.ws.readyState===WebSocket.OPEN},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shouldSendPings",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.close=function(){this.ws.close()},e.prototype.send=function(e){this.ws.send(e)},e.prototype.sendSetupMessages=function(){return i(this,void 0,void 0,(function(){var e,t,i,r,s,a,o=this;return n(this,(function(n){switch(n.label){case 0:return(t=this.settings.getAuthTokenAsync)?[4,this.settings.getAuthTokenAsync()]:[3,2];case 1:t=n.sent(),n.label=2;case 2:return e=t,i=this.settings,r=i.metadata,s=i.subscriptions,a={authToken:e,metadata:r,subscriptions:s},this.settings.createSetupMessage(a).forEach((function(e){return o.send(e)})),[2]}}))}))},e}();t.StateServiceWebSocketConnection=r})),xM=G((function(e,t){var i=j&&j.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?i(e.value):r(e.value).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=j&&j.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(e){return function(t){return l([e,t])}}function l(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},r=j&&j.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},s=j&&j.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleStateServiceProxy=void 0;var a=s(iR),o=[2e3,2e3,3e3,3e3,5e3],l=function(){function e(e,t,i,n,r,s){var a;this.m_events=new OE.EventEmitter,this.m_clientId="",this.m_connectionState=xA.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=e,this.m_hashedSessionId=this.calculateHash(e),this.m_logger=n,this.m_connectionAliveTimeAfterLoseFocusInMS=r.websocketAliveTimeAfterLoseFocusInMS,this.m_useServiceGeneratedClientId=r.useServiceGeneratedClientId||!1,this.m_wsUrl="".concat(i,"?docId=").concat(this.m_sessionId,"&clientType=").concat(t),r.correlationId&&(this.m_wsUrl+="&cid=".concat(r.correlationId)),r.isAutomation&&(this.m_wsUrl+="&automation=true"),r.autoRoutingEnabled&&(this.m_wsUrl+="&routing=true"),this.m_useServiceGeneratedClientId||(this.m_clientId=r.customClientId||(0,gR.v4)(),this.m_wsUrl+="&clientId=".concat(this.m_clientId)),this.m_deltasBaseUrl=i.replace("wss://","https://").replace("ws://","http://"),this.setupSystemClientsCell(),this.setUpSystemCommandsCell(),this.setupServiceGeneratedClientIdCell(),this.m_useServiceGeneratedClientId&&(this.m_clientIdEvictingQueue=new mR.EvictingQueue(20)),this.m_telemetry=new NM.SimpleServiceTelemetry(this.m_clientId,this.m_sessionId,r.maxRoundtripRaw),this.m_verbose=r.verbose||!1,this.m_batchedRequestsEnabled=r.batchedRequestsEnabled,this.m_initTimeoutDurationInMS=r.initTimeoutDurationInMs||0,this.m_pingTimeoutInMs=r.pingTimeoutInMs,this.m_pongTimeoutInMs=r.pongTimeoutInMs,this.m_user=s,this.m_metadata=r.metadata,this.m_retryIntervalsInMs=r.retryIntervalsInMs||o,this.m_maxSessionRetries=r.maxSessionRetries,this.m_offlineMessageCacheEnabled=r.offlineMessageCacheEnabled,this.m_maxOfflineMessageCacheTimeInMs=r.maxOfflineMessageCacheTimeInMs,this.m_maxOfflineMessageCacheLength=r.maxOfflineMessageCacheLength,this.m_allowReconnectOnMessageSend=r.allowReconnectOnSendMessage||!1,this.m_unacknowledgedMaxTimeInMs=null!==(a=r.unacknowledgeMessageTimeoutInMs)&&void 0!==a?a:0,this.m_subscriptions=r.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(e.prototype,"lastCloseReason",{get:function(){return this.m_lastCloseReason},enumerable:!1,configurable:!0}),e.prototype.senderId=function(){return this.m_clientId},e.prototype.countOfOutboundMessagesNotRoundTrippedYet=function(){return this.m_outboundMessageInfo.size},e.prototype.canRetry=function(){return this.m_connectionState===xA.ConnectionState.Disconnected&&4321!==this.m_lastCloseCode},e.prototype.getServiceTelemetry=function(){return this.m_telemetry.wsState=xA.ConnectionState[this.getConnectionState()],this.m_telemetry.messagePendingAckCount=this.m_outboundMessageInfo.size,this.m_telemetry},e.prototype.activeClientCount=function(){return this.m_clientIds.size},e.prototype.activeClientIds=function(){return this.m_clientIds},e.prototype.clientId=function(){return this.m_clientId},e.prototype.getConnectionState=function(){return this.m_connectionState},e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.connectAsync=function(){return i(this,void 0,void 0,(function(){var e=this;return n(this,(function(t){return this.m_initPromise.promise=new Promise((function(t,i){e.m_initPromise.resolve=t,e.m_initPromise.reject=i})),this.setConnectionState(xA.ConnectionState.Connecting),[2,new Promise((function(t,r){return i(e,void 0,void 0,(function(){var e,i=this;return n(this,(function(n){switch(n.label){case 0:return e=this,[4,LM.StateServiceWebSocketConnection.CreateAsync(this.m_wsUrl,this.m_connectionSettings)];case 1:return e.m_connection=n.sent(),this.m_connection.onopen=function(){i.handleConnectionOpen(),i.startInitTimeoutTimerWithRetry(i.m_initTimeoutDurationInMS,i.m_initPromise.reject),t()},this.m_connection.onerror=function(e){var n;i.m_logger.sendTraceTag(590213388,LA.TraceLevel.Error,"SimpleStateServiceProxy::connect - ".concat(null===(n=i.m_connection)||void 0===n?void 0:n.name," onerror. {hashedSessionId: ").concat(i.m_hashedSessionId,", ClientId: ").concat(i.m_clientId,", Error: ").concat(JSON.stringify(e),"}")),i.retryConnection((function(e){var t,n="failed to reconnect after ".concat(null===(t=i.m_connection)||void 0===t?void 0:t.name," error: ").concat((0,pR.errorToString)(e));i.m_logger.sendTraceTag(579463185,LA.TraceLevel.Error,n),r(n)}),!1,(function(){return t()}))},this.m_connection.onlog=function(e){var t;i.m_logger.sendTraceTag(556909603,e.detail.level,"SimpleStateServiceProxy::log - ".concat(null===(t=i.m_connection)||void 0===t?void 0:t.name," {hashedSessionId: ").concat(i.m_hashedSessionId,", ClientId: ").concat(i.m_clientId,", Message: ").concat(e.detail.message,"}"))},this.m_connection.onclose=function(e){var n,s;i.m_logger.sendTraceTag(590213389,LA.TraceLevel.Error,"SimpleStateServiceProxy::connect - ".concat(null===(n=i.m_connection)||void 0===n?void 0:n.name," onclose. {hashedSessionId: ").concat(i.m_hashedSessionId,", ClientId: ").concat(i.m_clientId,", Code: ").concat(e.code,", Reason: ").concat(e.reason,"}")),i.m_lastCloseCode=e.code,i.m_lastCloseReason=e.reason,4321!==e.code?i.retryConnection((function(e){var t="failed to reconnect after service side disconnect: ".concat((0,pR.errorToString)(e));i.m_logger.sendTraceTag(579463186,LA.TraceLevel.Error,t),r(t)}),!1,(function(){return t()})):(i.setConnectionState(xA.ConnectionState.Disconnected),i.m_logger.sendTraceTag(588009741,LA.TraceLevel.Error,"SimpleStateServiceProxy::connect - ".concat(null===(s=i.m_connection)||void 0===s?void 0:s.name," onclose. Not retryable close code. {hashedSessionId: ").concat(i.m_hashedSessionId,", ClientId: ").concat(i.m_clientId,"}")))},this.m_connection.onmessage=function(e){var t;try{i.handleConnectionMessage(e)}catch(e){i.m_logger.sendTraceTag(590213390,LA.TraceLevel.Error,"SimpleStateServiceProxy::onmessage - ".concat(null===(t=i.m_connection)||void 0===t?void 0:t.name," error. {hashedSessionId: ").concat(i.m_hashedSessionId,", ClientId: ").concat(i.m_clientId,", Error: ").concat((0,pR.errorToString)(e),"}"))}},[2]}}))}))}))]}))}))},e.prototype.close=function(){var e;this.m_logger.sendTraceTag(590213400,LA.TraceLevel.Info,"SimpleStateServiceProxy::close. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(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===(e=this.m_clientIdEvictingQueue)||void 0===e||e.clear(),0!==this.countOfOutboundMessagesNotRoundTrippedYet()&&(this.m_events.emit("messageFailedToRoundTripOnClose",this.m_outboundMessageInfo.size),this.m_outboundMessageInfo.clear())},e.prototype.sendStateMessage=function(e){this.sendStateMessageImpl(e)},e.prototype.createMapAsync=function(e,t,r,s){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){return i=new SR.SimpleSyncMap(e,this,t,r,s),this.m_handlers.set(e,i),[2,i]}))}))},e.prototype.getMapAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return(t=this.m_handlers.get(e))?[2,t]:[2,null]}))}))},e.prototype.waitMapAsync=function(e,t,r,s){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return[4,this.m_initPromise.promise];case 1:return n.sent(),[4,this.getMapAsync(e)];case 2:return(i=n.sent())?[3,4]:[4,this.createMapAsync(e,t,r,s)];case 3:i=n.sent(),n.label=4;case 4:return[2,i]}}))}))},e.prototype.createCellAsync=function(e,t,r,s){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){return i=new fR.SimpleSyncCell(e,this,t,r,s),this.m_handlers.set(e,i),[2,i]}))}))},e.prototype.getCellAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return(t=this.m_handlers.get(e))?[2,t]:[2,null]}))}))},e.prototype.waitCellAsync=function(e,t,r,s){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return this.m_logger.sendTraceTag(520161040,LA.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - awaiting initPromise ".concat(e)),[4,this.m_initPromise.promise];case 1:return n.sent(),this.m_logger.sendTraceTag(520161039,LA.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - getCellAsync ".concat(e)),[4,this.getCellAsync(e)];case 2:return(i=n.sent())?[3,4]:(this.m_logger.sendTraceTag(520161038,LA.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - createCellAsync ".concat(e)),[4,this.createCellAsync(e,t,r,s)]);case 3:i=n.sent(),n.label=4;case 4:return[2,i]}}))}))},e.prototype.onFocusChanged=function(e){var t=this;e?(window.clearTimeout(this.m_closeConnectionTimer),this.m_connection||(this.m_logger.sendTraceTag(590213392,LA.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - retryConnection due to getting focus again. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}")),this.retryConnection((function(e){t.m_logger.sendTraceTag(579463187,LA.TraceLevel.Error,"failed to reconnect after regaining focus: ".concat((0,pR.errorToString)(e)))}),!0))):this.m_closeConnectionTimer=window.setTimeout((function(){var e;t.m_connection&&(t.m_logger.sendTraceTag(590213391,LA.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - ".concat(null===(e=t.m_connection)||void 0===e?void 0:e.name," close due to losing focus. {hashedSessionId: ").concat(t.m_hashedSessionId,", ClientId: ").concat(t.m_clientId,"}")),t.m_connection.onclose=function(){},t.m_connection.close(),t.m_connection=null)}),this.m_connectionAliveTimeAfterLoseFocusInMS)},e.prototype.getHistoryAsync=function(e,t){return i(this,void 0,void 0,(function(){var i,r;return n(this,(function(n){switch(n.label){case 0:return(i=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),i.searchParams.append("docId",this.m_sessionId),i.searchParams.append("cid",this.m_clientId),i.searchParams.append("objectId",e),t&&i.searchParams.append("property",t),[4,a.default.get(i.toString())];case 1:return(r=n.sent().data).forEach((function(e){return e.value=JSON.parse(e.value)})),[2,r]}}))}))},e.prototype.getHistoryWithPaginationAsync=function(e,t,r){return i(this,void 0,void 0,(function(){var i,s;return n(this,(function(n){switch(n.label){case 0:return(i=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),i.searchParams.append("docId",this.m_sessionId),i.searchParams.append("cid",this.m_clientId),i.searchParams.append("objectId",e),i.searchParams.append("pagination","true"),r&&i.searchParams.append("cursor",r),t&&i.searchParams.append("property",t),[4,a.default.get(i.toString())];case 1:return(s=n.sent().data).messages.forEach((function(e){return e.value=JSON.parse(e.value)})),[2,s]}}))}))},e.prototype.setupSystemClientsCell=function(){var e=this;this.m_clientsCell=new fR.SimpleSyncCell("systemClients",this),this.m_handlers.set(this.m_clientsCell.id(),this.m_clientsCell),this.m_clientsCell.on("valueChanged",(function(t){e.m_clientIds=new Set(t),e.m_events.emit("activeClientCountChanged")}))},e.prototype.setUpSystemCommandsCell=function(){var e=this;this.m_systemCommandsCell=new fR.SimpleSyncCell(xA.SystemCommandsStateName,this),this.m_handlers.set(this.m_systemCommandsCell.id(),this.m_systemCommandsCell),this.m_systemCommandsCell.on("valueChanged",(function(t){return i(e,void 0,void 0,(function(){var e,i,r;return n(this,(function(n){switch(n.label){case 0:return"refreshToken"===t?[3,1]:[3,6];case 1:if(!this.m_user||!this.m_user.getForceRefreshedTokenAsync)return[3,5];n.label=2;case 2:return n.trys.push([2,4,,5]),[4,this.m_user.getForceRefreshedTokenAsync()];case 3:return e=n.sent(),i={},e&&(i.authorization=e.token,i.authProvider=e.authProvider,i.mri=e.mri||"",i.huid=e.hashedUserEmail||""),this.sendConfigMessage(i),[3,5];case 4:return r=n.sent(),this.m_logger.sendTraceTag(574107847,LA.TraceLevel.Error,"Error getting force refreshed auth token: ".concat((0,pR.errorToString)(r))),[3,5];case 5:return[3,7];case 6:return this.m_logger.sendTraceTag(574107848,LA.TraceLevel.Error,"Unknown system command cell value: ".concat(t)),[3,7];case 7:return[2]}}))}))}))},e.prototype.setupServiceGeneratedClientIdCell=function(){var e=this;this.m_serviceGeneratedClientIdCell=new fR.SimpleSyncCell(xA.ServiceGeneratedClientIdName,this),this.m_handlers.set(this.m_serviceGeneratedClientIdCell.id(),this.m_serviceGeneratedClientIdCell),this.m_serviceGeneratedClientIdCell.on("valueChanged",(function(t){e.m_logger.sendTraceTag(520161037,LA.TraceLevel.Info,"SimpleStateServiceProxy::serviceGeneratedClientId changed to ".concat(t,"}")),e.setClientId(t,!0),e.processClientIdQueue(),e.m_useServiceGeneratedClientId&&(e.processOfflineMessageCache(!0),e.clearOfflineMessageCacheTimer())})),this.m_logger.sendTraceTag(509743689,LA.TraceLevel.Info,"SimpleStateServiceProxy::setupServiceGeneratedClientIdCell completed.")},e.prototype.handleConnectionOpen=function(){var e;this.m_logger.sendTraceTag(590213387,LA.TraceLevel.Info,"SimpleStateServiceProxy::connect - ".concat(null===(e=this.m_connection)||void 0===e?void 0:e.name," onopen. {hashedSessionId: ").concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}")),this.m_retryAttempts=0,this.setConnectionState(xA.ConnectionState.Connected),this.startPingTimer(),this.m_useServiceGeneratedClientId||(this.processOfflineMessageCache(!1),this.clearOfflineMessageCacheTimer())},e.prototype.setConnectionState=function(e){this.m_connectionState!==e&&(this.m_connectionState=e,e===xA.ConnectionState.Disconnected&&this.m_useServiceGeneratedClientId&&this.setClientId("",!1),this.m_events.emit("connectionStateChanged"))},e.prototype.setClientId=function(e,t){this.m_clientId!==e&&(this.m_clientId=e,t&&this.m_events.emit("clientIdChanged"))},e.prototype.processClientIdQueue=function(){var e=this;this.m_clientIdEvictingQueue&&this.m_clientIdEvictingQueue.forEach((function(t){t.senderId=e.m_clientId,e.sendConnectionMessage(t,!0)}))},e.prototype.sendGetInitialSystemStateMessages=function(){try{var e={messageId:(0,gR.v4)(),senderId:this.senderId(),objectId:xA.SystemSessionStateName,type:"",operation:"get",value:""};this.sendStateMessage(e);var t={messageId:(0,gR.v4)(),senderId:this.senderId(),objectId:xA.ServiceGeneratedClientIdName,type:"",operation:"get",value:""};this.sendStateMessage(t),this.m_logger.sendTraceTag(509141838,LA.TraceLevel.Info,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - sent messages.")}catch(e){this.m_logger.sendTraceTag(509141837,LA.TraceLevel.Error,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - caught error ".concat(e))}},e.prototype.createSetupMessage=function(e){var t=e.authToken,i=e.metadata,n=e.subscriptions,r=[];if(t||i){var s={};t&&(s.authorization=t.token,s.authProvider=t.authProvider,s.mri=t.mri||"",s.huid=t.hashedUserEmail||""),i&&(s.metadata=JSON.stringify(i));var a={messageId:(0,gR.v4)(),senderId:this.senderId(),objectId:xA.ConfigurationName,type:"",operation:"",value:JSON.stringify(s)};r.push(JSON.stringify(a))}return n&&(a={messageId:(0,gR.v4)(),senderId:this.senderId(),objectId:xA.StateSubscriptionsName,type:"",operation:"",value:JSON.stringify(n)},r.push(JSON.stringify(a))),r},e.prototype.sendConfigMessage=function(e){var t={messageId:(0,gR.v4)(),senderId:this.senderId(),objectId:xA.ConfigurationName,type:"",operation:"",value:JSON.stringify(e)};this.sendStateMessage(t)},e.prototype.retryConnection=function(e,t,r){var s=this;if(this.clearPingPongTimer(),this.clearInitTimeoutTimer(),this.m_retryAttempts>=this.m_retryIntervalsInMs.length||this.m_sessionRetryAttempts>=this.m_maxSessionRetries)return this.setConnectionState(xA.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213393,LA.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection reached max retry attempts. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}")),void(e&&e(new Error("reached max retry attempts")));if(this.setConnectionState(xA.ConnectionState.Connecting),t||this.m_connection&&!this.m_retryTimer){var a=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 i(s,void 0,void 0,(function(){var t;return n(this,(function(i){switch(i.label){case 0:this.m_logger.sendTraceTag(590213395,LA.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}")),this.m_retryTimer=null,i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.connectAsync()];case 2:return i.sent(),r&&r(),[3,4];case 3:return t=i.sent(),this.setConnectionState(xA.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213396,LA.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection failed. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}, ").concat((0,pR.errorToString)(t))),this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&e(t),[3,4];case 4:return[2]}}))}))}),a)}else this.m_logger.sendTraceTag(590213394,LA.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection skipped. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", NullConnection: ").concat(null===this.m_connection,", NullRetryTimer: ").concat(null===this.m_retryTimer,"}"))},e.prototype.startPingTimer=function(){var e=this;this.m_connection&&this.m_connection.shouldSendPings&&(this.m_pingTimeoutInMs<=0||this.m_pongTimeoutInMs<=0||(this.clearPingPongTimer(),this.m_pingTimer=setTimeout((function(){return i(e,void 0,void 0,(function(){return n(this,(function(e){return this.sendPingMessage(),this.m_pingTimer=null,[2]}))}))}),this.m_pingTimeoutInMs)))},e.prototype.sendPingMessage=function(){var e=this;this.m_connection&&(this.m_connection.isOpen?(this.m_verbose&&this.m_logger.sendTraceTag(559952470,LA.TraceLevel.Info,"SimpleStateServiceProxy::sendPingMessage. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", __ping__")),this.m_connection.send("__ping__"),this.clearPongTimer(),this.m_pongTimer=setTimeout((function(){return i(e,void 0,void 0,(function(){var e=this;return n(this,(function(t){return this.retryConnection((function(t){e.m_logger.sendTraceTag(579463188,LA.TraceLevel.Error,"failed to reconnect after missing ping: ".concat((0,pR.errorToString)(t)))}),!1),this.m_pongTimer=null,[2]}))}))}),this.m_pongTimeoutInMs)):(this.retryConnection((function(t){e.m_logger.sendTraceTag(579463189,LA.TraceLevel.Error,"failed to reconnect after closed connection: ".concat((0,pR.errorToString)(t)))}),!1),this.clearPongTimer()))},e.prototype.clearPingPongTimer=function(){this.clearPingTimer(),this.clearPongTimer()},e.prototype.clearPingTimer=function(){this.m_pingTimer&&(clearTimeout(this.m_pingTimer),this.m_pingTimer=null)},e.prototype.clearPongTimer=function(){this.m_pongTimer&&(clearTimeout(this.m_pongTimer),this.m_pongTimer=null)},e.prototype.handleConnectionMessage=function(e){if("string"==typeof e.data){if(this.startPingTimer(),"__pong__"===e.data)return void(this.m_verbose&&this.m_logger.sendTraceTag(559952471,LA.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", __pong__")));var t=Date.now();try{var i=JSON.parse(e.data);Array.isArray(i)&&i.length>0?this.handleAggregatedStateMessages(i):this.handleStateMessage(i),this.m_telemetry.addMessageHandleLatency(Date.now()-t),i.objectId===xA.SystemSessionStateName?(this.m_logger.sendTraceTag(520161036,LA.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - systemSessionState - initPromise resolved."),this.m_initPromise.resolve(),this.clearInitTimeoutTimer()):i.objectId===xA.ServiceGeneratedClientIdName&&this.m_logger.sendTraceTag(509743688,LA.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - serviceGeneratedClientId received.")}catch(e){this.m_logger.sendTraceTag(578102302,LA.TraceLevel.Error,"handleConnectionMessage: ".concat((0,pR.errorToString)(e)))}}else this.m_logger.sendTraceTag(590213397,LA.TraceLevel.Error,"SimpleStateServiceProxy::handleConnectionMessage - Unknown data type. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", Type: ").concat(typeof e.data,"}"))},e.prototype.handleAggregatedStateMessages=function(e){var t,i,n=this;if(e&&0!==e.length){var s=e.map((function(e){return JSON.parse(e)})),a={};s.forEach((function(e){return a[e.objectId]=1+(a[e.objectId]||0)})),Object.keys(a).forEach((function(e){if(a[e]>1){var t=n.m_handlers.get(e);t&&t.beginAggregatedStateUpdating&&t.beginAggregatedStateUpdating()}}));try{for(var o=r(s),l=o.next();!l.done;l=o.next()){var c=l.value;this.handleStateMessage(c)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}Object.keys(a).forEach((function(e){if(a[e]>1){var t=n.m_handlers.get(e);t&&t.endAggregatedStateUpdating&&t.endAggregatedStateUpdating()}}))}},e.prototype.handleStateMessage=function(e){var t=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213398,LA.TraceLevel.Info,"SimpleStateServiceProxy::handleStateMessage. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", ObjectId: ").concat(e.objectId,", MessageId: ").concat(e.messageId,"}")),"list"===e.type)JSON.parse(e.value).forEach((function(e){t.handleStateMessage(e)}));else{if(this.m_user&&this.m_user.validateMessage&&!this.m_user.validateMessage(e))return void this.m_logger.sendTraceTag(588009742,LA.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage rejected message: {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", ObjectId: ").concat(e.objectId,", MessageId: ").concat(e.messageId,"}"));var i=this.getHandlerForMessage(e);if(e.senderId===this.senderId()&&(this.acknowledgeMessage(e,i),this.m_telemetry.incrementAcknowledgedCount(e.objectId)),this.measureMessageRoundTripLatency(e),this.m_telemetry.incrementReceivedCount(e.objectId),i)return void i.handleStateMessage(e)}},e.prototype.getAuthToken=function(){return i(this,void 0,void 0,(function(){var e,t;return n(this,(function(i){switch(i.label){case 0:if(!this.m_user||!this.m_user.getAuthTokenAsync)return[3,4];i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.m_user.getAuthTokenAsync()];case 2:return e=i.sent(),[3,4];case 3:return t=i.sent(),this.m_logger.sendTraceTag(578102469,LA.TraceLevel.Error,"Error getting auth token: ".concat((0,pR.errorToString)(t))),[3,4];case 4:return[2,e]}}))}))},e.prototype.getHandlerForMessage=function(e){var t=this.m_handlers.get(e.objectId);return t||("cell"===e.type?t=new fR.SimpleSyncCell(e.objectId,this):"map"===e.type?t=new SR.SimpleSyncMap(e.objectId,this):this.m_logger.sendTraceTag(559204164,LA.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage - Unknown message type. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", Type: ").concat(e.type,"}")),t&&this.m_handlers.set(e.objectId,t),t)},e.prototype.sendStateMessageImpl=function(e){var t,i=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213403,LA.TraceLevel.Info,"SimpleStateServiceProxy::sendStateMessageImpl. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", ObjectId: ").concat(e.objectId,", MessageId: ").concat(e.messageId,"}")),e.objectId!==xA.StateSubscriptionsName&&e.objectId!==xA.ConfigurationName){if(this.m_outboundMessageInfo.set(e.messageId,Date.now()),this.m_telemetry.incrementRequestedCount(e.objectId),this.m_unacknowledgedMaxTimeInMs>0){var n=null===(t=this.getHandlerForMessage(e))||void 0===t?void 0:t.messageTrackingOption();if(n&&n!==xA.MessageTrackingOption.None){var r=this.getUnacknowledgedMessagesMapKey(e,n);this.m_unacknowledgedMessages.set(r,{message:e,timestamp:Date.now()}),this.startUnacknowledgeMessageTimer()}}if(this.m_useServiceGeneratedClientId&&this.m_clientIdEvictingQueue&&!this.m_clientId&&"get"!==e.operation)return this.m_logger.sendTraceTag(508348254,LA.TraceLevel.Info,"SimpleStateServiceProxy::enqueueMessage ".concat(JSON.stringify(e))),void this.m_clientIdEvictingQueue.enqueue(e)}this.m_user&&this.m_user.patchMessage&&this.m_user.patchMessage(e),this.m_batchedRequestsEnabled?(this.m_messageBuffer.push(e),this.m_processBufferTimer||(this.m_processBufferTimer=setTimeout((function(){i.processMessageBuffer()}),this.m_batchWaitTimeMS))):this.sendConnectionMessage(e,!0)},e.prototype.createListMessage=function(e){if(0!==e.length)return 1===e.length?e[0]:{value:JSON.stringify(e),type:this.m_batchMessageTypeName,operation:"",messageId:(0,gR.v4)(),objectId:"batch",senderId:this.senderId()}},e.prototype.processMessageBuffer=function(){var e=this.m_messageBuffer.length,t=this.m_messageBuffer.splice(0,e),i=this.createListMessage(t);this.m_processBufferTimer&&clearTimeout(this.m_processBufferTimer),this.m_processBufferTimer=null,i&&this.sendConnectionMessage(i,!0)},e.prototype.processOfflineMessageCache=function(e){var t=this;this.m_offlineMessageCacheEnabled&&(this.m_offlineMessageCache.forEach((function(i){e&&(i.message.senderId=t.m_clientId),t.sendConnectionMessage(i.message,!1),t.m_telemetry.offlineCacheTelemetry.resentCount+=1})),this.m_offlineMessageCache=[])},e.prototype.purgeOfflineMessageCache=function(){var e=this;if(this.m_offlineMessageCacheEnabled&&this.m_maxOfflineMessageCacheTimeInMs){var t=Date.now(),i=this.m_offlineMessageCache.filter((function(i){return e.m_maxOfflineMessageCacheTimeInMs&&i.timestamp+e.m_maxOfflineMessageCacheTimeInMs>=t}));this.m_telemetry.offlineCacheTelemetry.expiredCount+=this.m_offlineMessageCache.length-i.length,this.m_offlineMessageCache=i,0===this.m_offlineMessageCache.length&&this.clearOfflineMessageCacheTimer()}},e.prototype.clearOfflineMessageCacheTimer=function(){this.m_offlineMessageCacheEnabled&&this.m_offlineMessageCacheTimer&&(clearInterval(this.m_offlineMessageCacheTimer),this.m_offlineMessageCacheTimer=null)},e.prototype.getUnacknowledgedMessagesMapKey=function(e,t){return t===xA.MessageTrackingOption.None?"":t===xA.MessageTrackingOption.All?e.messageId:e.objectId},e.prototype.startUnacknowledgeMessageTimer=function(){var e=this;this.m_unacknowledgedMaxTimeInMs>0&&!this.m_unacknowledgedTimer&&(this.m_unacknowledgedTimer=setInterval((function(){e.notifyUnacknowledgedMessages(),e.m_unacknowledgedMessages.size<=0&&e.clearUnacknowledgedTimer()}),this.m_unacknowledgedMaxTimeInMs/2))},e.prototype.acknowledgeMessage=function(e,t){if(e.senderId===this.senderId()&&t&&!(this.m_unacknowledgedMessages.size<=0)){var i=this.getUnacknowledgedMessagesMapKey(e,t.messageTrackingOption()),n=this.m_unacknowledgedMessages.get(i);n&&e.messageId===n.message.messageId&&this.m_unacknowledgedMessages.delete(i)}},e.prototype.notifyUnacknowledgedMessages=function(){var e=this,t=Date.now();this.m_unacknowledgedMessages.forEach((function(i,n){if(i.timestamp+e.m_unacknowledgedMaxTimeInMs<t){var r=e.getHandlerForMessage(i.message);null==r||r.handleUnacknowledgedMessage(i.message),e.m_unacknowledgedMessages.delete(n),e.m_telemetry.unacknowledgedMessagesCount+=1}}))},e.prototype.clearUnacknowledgedTimer=function(){this.m_unacknowledgedTimer&&(clearInterval(this.m_unacknowledgedTimer),this.m_unacknowledgedTimer=null)},e.prototype.startInitTimeoutTimerWithRetry=function(e,t){var i=this;this.startInitTimeoutTimer(e,(function(){i.m_logger.sendTraceTag(509141836,LA.TraceLevel.Error,"SimpleStateServiceProxy::startInitTimeoutTimer - failed to init after ".concat(e," ms; requesting get messages and retrying")),i.sendGetInitialSystemStateMessages(),i.startInitTimeoutTimer(e,t)}))},e.prototype.startInitTimeoutTimer=function(e,t){e>0&&(this.clearInitTimeoutTimer(),this.m_initTimeoutTimer=setTimeout((function(){t("Initialization timed out after ".concat(e," ms"))}),e))},e.prototype.clearInitTimeoutTimer=function(){this.m_initTimeoutTimer&&clearTimeout(this.m_initTimeoutTimer)},e.prototype.sendConnectionMessage=function(e,t){var i,n,r=this;if(this.m_allowReconnectOnMessageSend&&this.m_connectionState===xA.ConnectionState.Disconnected&&(this.updateRetryAttempts(),this.retryConnection((function(e){r.m_logger.sendTraceTag(559428289,LA.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - failed to reconnect with error: ".concat((0,pR.errorToString)(e)," "))}),!1)),this.m_offlineMessageCacheEnabled&&t){if(!this.m_connection||this.m_connectionState!==xA.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,LA.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - Dropping message because offline cache is full. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", Status: ").concat(null===(i=this.m_connection)||void 0===i?void 0:i.readyState,"}"))):(!this.m_offlineMessageCacheTimer&&this.m_maxOfflineMessageCacheTimeInMs&&(this.m_offlineMessageCacheTimer=setInterval((function(){r.purgeOfflineMessageCache()}),this.m_maxOfflineMessageCacheTimeInMs/2)),this.m_offlineMessageCache.push({message:e,timestamp:Date.now()}),void(this.m_telemetry.offlineCacheTelemetry.cachedCount+=1))}else{if(!this.m_connection)return void this.m_logger.sendTraceTag(590213401,LA.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - connection is not set. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,"}"));if(!this.m_connection.isOpen)return void this.m_logger.sendTraceTag(590213402,LA.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - ".concat(this.m_connection.name," status is not open. {hashedSessionId: ").concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", Status: ").concat(this.m_connection.readyState,"}"))}null===(n=this.m_connection)||void 0===n||n.send(JSON.stringify(e))},e.prototype.closeAndClearConnection=function(){if(this.m_connection){if(this.m_connection.onclose=function(){},this.m_connection.isOpen)this.m_connection.close();else{var e=this.m_connection;e.onopen=function(){return e.close()}}this.m_connection=null}},e.prototype.updateRetryAttempts=function(){this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&(this.m_retryAttempts=0),this.m_sessionRetryAttempts>=this.m_maxSessionRetries&&(this.m_sessionRetryAttempts=0)},e.prototype.measureMessageRoundTripLatency=function(e){if(e.senderId===this.senderId())try{var t=this.m_outboundMessageInfo.get(e.messageId);if(void 0!==t){this.m_outboundMessageInfo.delete(e.messageId);var i=Date.now()-t;this.m_events.emit("messageRoundTripped",{clientId:this.m_clientId,sessionId:this.m_sessionId,messageId:e.messageId,objectId:e.objectId,operation:e.operation,latencyInMs:i}),this.m_telemetry.addRoundtripLatency(i)}else this.m_verbose&&this.m_logger.sendTraceTag(590213404,LA.TraceLevel.Info,"SimpleStateServiceProxy::measureMessageRoundTripLatency. Failed to find outbound message info for {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", ObjectId: ").concat(e.objectId,", MessageId: ").concat(e.messageId,"}"))}catch(t){this.m_logger.sendTraceTag(590213405,LA.TraceLevel.Error,"SimpleStateServiceProxy::measureMessageRoundTripLatency - Exception thrown error. {hashedSessionId: ".concat(this.m_hashedSessionId,", ClientId: ").concat(this.m_clientId,", MessageId: ").concat(e.messageId,", Error: ").concat(t.message,"}"))}},e.prototype.calculateHash=function(e){return e?"".concat((new OM.sha256).update(e).digest("hex")):""},e}();t.SimpleStateServiceProxy=l})),FM=G((function(e,t){var i=j&&j.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?i(e.value):r(e.value).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=j&&j.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(e){return function(t){return l([e,t])}}function l(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createStateServiceProxyAsync=void 0,t.createStateServiceProxyAsync=function(e,t,r,s,a,o){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return[4,(i=new xM.SimpleStateServiceProxy(e,t,r,s,a,o)).connectAsync()];case 1:return n.sent(),[2,i]}}))}))}})),UM=G((function(e,t){var i=j&&j.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),n=j&&j.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),n(LA,t),n(xA,t),n(FM,t)}));class BM{constructor(e){this.enableConsoleLog=vy().calling.reaction.enableStateServiceConsoleLogs,this._logger=e}sendTraceTag(e,t,i){this.enableConsoleLog&&this._logger.info(`Tag: ${e}, Leve: ${t}, Message: ${i}`)}}class VM{constructor(e){this._wsUrl="",this.name="Reaction",this.capabilityChangeHandler=e=>{e.newValue.useReactions&&(this._participantCapability=this._call.getParticipantCapabilities().useReactions,this._logger.log(`participant capabilitity to useReactions feature is ${this._participantCapability}`))},this._eventEmitter=e,this._participantCapability={isPresent:!0,reason:"Capable"},this._isReactionFeatureEnabled=vy().calling.reaction.enabled}initialize(e,t,i,n,r,s){void 0===this._proxy||this._proxy?.getConnectionState()===UM.ConnectionState.Disconnected?(this._logger=r.createChild((()=>`ReactionImplOverStateService::Call(id='${this._tsCall.callId}')`)),this._internalCallAgent=t,this._tsCall=e,this._call=i,this._callInfo=s,this._docId=this._tsCall.callId,this._wsUrl=this.getEndpointUrl(),this._telemetryLogManager=n,this._sendAttempOrFailureFeatureUsage("initialize",oE.attempt),this.start()):r.info("State Service Proxy already has an active connection."),this._callInfo.context==uy.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 e=vy().calling.reaction.StateServiceProxySettings,t={getAuthTokenAsync:this.getAuthToken.bind(this)};try{this._proxy=await UM.createStateServiceProxyAsync(this._docId,"ACSWeb",this._wsUrl,new BM(this._logger),e,t)}catch(e){return this._logger.error("Could not create state service proxy",e),void this._sendAttempOrFailureFeatureUsage("initialize",oE.failure,new le({defaultError:ee.FEATURES.REACTION.STATE_SERVICE_CONNECT_FAIL,originalError:e}))}try{this._reactionsMap=await this._proxy.createMapAsync("reactions",!0)}catch(e){return this._logger.error("Could not create state service proxy reaction map",e),void this._sendAttempOrFailureFeatureUsage("initialize",oE.failure,new le({defaultError:ee.FEATURES.REACTION.MAP_CREATE_FAIL,originalError:e}))}this._sendSuccessFeatureUsage("initialize",oE.success),this._reactionsMap?.on("valueChanged",this.onReactionsReceived.bind(this))}async getAuthToken(){const e={token:await this._internalCallAgent.tokenProvider(),authProvider:"SKYPE",mri:this._internalCallAgent.getUserMri()};return Promise.resolve(e)}async sendReaction(e,t){if(!this._isReactionFeatureEnabled||!this._participantCapability.isPresent){const e=new le({defaultError:ee.FEATURES.REACTION.SEND_FAIL_POLICY});throw this._sendAttempOrFailureFeatureUsage("sendReaction",oE.failure,e,t),e}if(!this._reactionsMap){this._logger.error("Reaction Map has not yet been initialized.");const e=new le({defaultError:ee.FEATURES.REACTION.NOT_INIT_YET});throw this._sendAttempOrFailureFeatureUsage("sendReaction",oE.failure,e,t),e}try{return this._reactionsMap?.set(this._internalCallAgent.getUserMri(),{name:e.reactionType}),void this._sendSuccessFeatureUsage("sendReaction",oE.success,t,e.reactionType)}catch(e){this._logger.error("Unable to send reaction",e);const i=new le({defaultError:ee.FEATURES.REACTION.SEND_REACTION_FAIL,originalError:e});throw this._sendAttempOrFailureFeatureUsage("sendReaction",oE.failure,i,t),i}}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async onReactionsReceived(e){if(3===this._tsCall.state&&this._participantCapability.isPresent){const t=Mf();this._sendAttempOrFailureFeatureUsage("receiveReaction",oE.attempt,void 0,t);try{const i={reactionType:(await(this._reactionsMap?.get(e))).name};this._eventEmitter.emit("reaction",{identifier:e,reactionMessage:i}),this._sendSuccessFeatureUsage("receiveReaction",oE.success,t,i.reactionType)}catch(e){this._logger.error("Unable to parse reaction",e);let i=new le({defaultError:ee.FEATURES.REACTION.RECEIVE_REACTION_FAIL,originalError:e});this._sendAttempOrFailureFeatureUsage("receiveReaction",oE.failure,i,t)}}}dispose(){void 0!==this._telemetryLogManager&&(this._proxy?.getConnectionState()===UM.ConnectionState.Connected?(this._reactionsMap?.removeAllListeners("valueChanged"),this._proxy.close(),this._sendSuccessFeatureUsage("dispose",oE.success),this._call.offParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler)):this._sendSuccessFeatureUsage("dispose",oE.failure))}_sendAttempOrFailureFeatureUsage(e,t,i,n){let r=i?{code:i?.code||ne,subCode:i?.subCode||0,failureReason:i?.message||"",..._b(i)}:void 0;hb({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}_sendSuccessFeatureUsage(e,t,i,n){let r;r="initialize"===e||"dispose"==e?void 0:{reactionConstraint:{reactionType:n}},hb({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}getEndpointUrl(){const e=this._internalCallAgent._caConfigBag,t=e&&Dy(e.identityType,e.region);var i=vy().PowerPointStateServiceUrl.public.amer;switch(e?.cloudType){case Of.Public:t&&(i=vy().PowerPointStateServiceUrl.public.eu);break;case Of.GccHigh:i=vy().PowerPointStateServiceUrl.gcch;break;case Of.AirGap08:i=vy().PowerPointStateServiceUrl.ag08;break;case Of.AirGap09:i=vy().PowerPointStateServiceUrl.ag09;break;case Of.Dod:i=vy().PowerPointStateServiceUrl.dod;break;default:i=vy().PowerPointStateServiceUrl.public.amer}return`wss://${new URL(i).hostname}/StateServiceHandler.ashx`}}class HM{get contentSharingSession(){return this._contentSharingSession}constructor(e){this._contentSharingSession=e}getFileDetails(){if(this.contentSharingSession)return JSON.parse(atob(this.contentSharingSession.contentSharingIdentity))}}const $M="azure_communication_calling_pptLive";class jM{constructor(e){this._isActive=!1,this._isInitializingPPTLive=!1,this._updateIsActive=e=>this._isActive!==e&&(this._isActive=e,this._logger.info(`Updating isActive to ${e}`),!0),this._eventEmitter=e,this._target=document.createElement("div"),this._target.id=$M,this._target.style.width="100%",this._target.style.height="100%"}initialize(e,t,i,n){this._logger=n.createChild((()=>`PPTLive::Call(id='${e.callId}')`)),this._tsCall=e,this._internalCallAgent=t,this._telemetryLogManager=i,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(e){if(this._contentSharing&&0===e.length)this._updateIsActive(!1),this._contentSharing=void 0,this._target.innerHTML="",this._isInitializingPPTLive=!1,this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("endedPPTLive",oE.success);else if(!this._contentSharing&&0!==e.length){if(!vy().calling.pptlive.enabled)return;this._contentSharing=new HM(e[0]),this._updatePPTLive(this._tsCall.state),this._sendFeatureUsage("startedPPTLive",oE.attempt,this._contentSharing?.contentSharingSession?.contentSharingGuid)}}async _updatePPTLive(e){this._fileDetails=this._contentSharing?.getFileDetails(),this._fileDetails&&"ppt"===this._fileDetails.type&&3===e&&await this._startPPTLive(this._target)}_updateActivePresenter(){this._tsCall.participants.forEach((e=>{const t=kS(e.id);2===e.contentSharingRole&&(this._activePresenterId=t)}))}_sendFeatureUsage(e,t,i){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"PPTLive",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:{pptLiveConstraint:{contentId:i}}},this._telemetryLogManager,this._logger)}_observeDivMount(){const e=new MutationObserver((async t=>{if(this._isActive&&!this._isInitializingPPTLive)for(const i of t)for(let t=0;t<i.addedNodes.length;t++){const n=i.addedNodes[t];if(n.nodeType===Node.ELEMENT_NODE&&n.matches(`#${$M}`)){await this._startPPTLive(this._target),e.disconnect();break}}else e.disconnect()}));e.observe(document.body,{childList:!0,subtree:!0})}_initViewerWithExperiment(e,t,i,n,r,s,a,o,l,c,d,u,h,g,p){const m=window.Microsoft,f=vy().calling.pptlive,v={Container:e,SessionInformation:{DocumentClickTime:new Date,HostInitTime:new Date,UiLocale:u,DataLocale:u,IsPresenter:!1,WdParams:{wdModernSlideShowInTeams:f.wdParams.wdModernSlideShowInTeams,wdPresenterViewInTeams:f.wdParams.wdPresenterViewInTeams,wdForceModernSlideShowInTeams:f.wdParams.wdForceModernSlideShowInTeams,isMovePrivateViewingToPPTEnabled:f.wdParams.isMovePrivateViewingToPPTEnabled},PptFeatureGates:f.featureGates,ParticipantId:o,EnableStateServiceInPreviewerFeatures:JSON.parse(f.enableStateServiceInPreviewerFeatures),StateServiceSettings:{stateServiceProxySettings:f.stateServiceProxySettings,regionalEndpointUrl:this._getEndpointUrl(),authEnabled:!1,rosterCheckEnabled:!1,stateServiceUser:{getAuthTokenAsync:!1,getForceRefreshedTokenAsync:!1}},ContentId:h,EndpointId:a,CallId:g,HostName:"ACSWeb",HostSessionId:l},WopiPrecheckInfo:{FileName:n,FileGetUrl:s,FileSize:r,CustomFontCatalogUrl:p,BundleInfo:{MajorVersion:i,Url:c},CreateNewInfo:null},ApplicationCustomSettings:{TakeFocusOnBoot:f.appSettings.takeFocusOnBoot,EnableAdvanceOnClick:f.appSettings.enableAdvanceOnClick,EnableAdvanceOnTap:f.appSettings.enableAdvanceOnTap},Diagnostics:{entryPoint:"null"},FnOnInitializeSuccess:e=>{this._isInitializingPPTLive=!1,this._observeDivMount(),this._sendFeatureUsage("startedPPTLive",oE.success,this._contentSharing?.contentSharingSession?.contentSharingGuid)},FnOnInitializeFailure:e=>{this._isInitializingPPTLive=!1;var t="Category: "+e.Category+"\nMessage: "+e.Message+"\nExtraInfo: "+e.ExtraInfo;this._sendFeatureUsage("startedPPTLive",oE.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid),this._logger.error(t)}};d&&(v.ApplicationCustomSettings.EnableWacFallback=!1,v.ApplicationUrl=d),m.Office.PowerPoint.Bootstrap.Prefetch(),m.Office.PowerPoint.Bootstrap.InitializeWopiPending(v),this._updateActivePresenter(),this._updateIsActive(!0),this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("startedPPTLive",oE.initialize,this._contentSharing?.contentSharingSession?.contentSharingGuid)}async _startPPTLive(e){this._fileDetails?.bootstrapperUrl&&(this._isInitializingPPTLive=!0,e.innerHTML="",await this._loadDynamicModule(this._fileDetails.bootstrapperUrl).then((()=>{this._fileDetails&&this._initViewerWithExperiment(e,Number(this._contentSharing?.contentSharingSession?.contentSharingState),this._fileDetails.majorVersion,this._fileDetails.name,this._fileDetails.fileSize,this._fileDetails.fileGetUrl,this._tsCall.endpointId,this._tsCall.participantId,Mf(),this._fileDetails.contentBundleUrl,this._fileDetails.wacUrl,navigator.language,this._fileDetails.id,this._tsCall.callId,this._fileDetails.customFontCatalogUrl)})).catch((()=>{this._sendFeatureUsage("startedPPTLive",oE.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid)})))}_getEndpointUrl(){const e=this._internalCallAgent._caConfigBag,t=e&&Dy(e.identityType,e.region);let i=vy().PowerPointStateServiceUrl.public.amer;switch(e?.cloudType){case Of.Public:t&&(i=vy().PowerPointStateServiceUrl.public.eu);break;case Of.GccHigh:i=vy().PowerPointStateServiceUrl.gcch;break;case Of.AirGap08:i=vy().PowerPointStateServiceUrl.ag08;break;case Of.AirGap09:i=vy().PowerPointStateServiceUrl.ag09;break;case Of.Dod:i=vy().PowerPointStateServiceUrl.dod;break;default:i=vy().PowerPointStateServiceUrl.public.amer}return i}async _loadDynamicModule(e){const t=document.querySelectorAll(`head > script[src="${e}"]`);return t.length>0&&t[0]?Promise.resolve():new Promise(((t,i)=>{const n=document.createElement("script"),r=document.getElementsByTagName("head")[0];n.onload=()=>t(),n.onerror=e=>{r.removeChild(n),i(e)},n.src=e,r.appendChild(n)}))}}const GM=255;var qM;!function(e){e.sceneChanged="sceneChanged",e.seatingChanged="seatingChanged"}(qM||(qM={}));const zM=e=>{const t=e.width,i=e.height,n=Math.max(t-1.778*i,0)/2,r=Math.max(i-t/1.778,0)/2;return{sceneX:n,sceneY:r,sceneWidth:t-2*n,sceneHeight:i-2*r}},WM=(e,t,i,n,r,s)=>({x:e/GM*r,y:t/GM*s,w:i/GM*r,h:n/GM*s});class KM extends dw{constructor(e,t,i){super(t,[i]),this._eventEmitter=e,this._togetherModeBotId=i,this._lastSeatingMapData="",this._seatingCoordinates=new Map,this._dataChannelId=vy().calling.togetherMode.dataChannelId,this._supportedConversationTypes=vy().calling.togetherMode.supportedConversationTypes,this._lastdataChannelMessage={},this._botSceneSize={width:1280,height:720}}initialize(e,t,i,n,r){"gcc"===e.region&&this.updateTogethermodeBotId(vy().calling.togetherMode.gccBotId),super.initialize(e,t,i,n,r),e.on("callStateChanged",(()=>{if(3===e.state){const t=this.isGccBotInCall();("gcc"===e.region||t)&&(this.updateTogethermodeBotId(vy().calling.togetherMode.gccBotId),t&&this.observeBotParticipantsAlreadyInCall())}})),this._dataChannelAdapter=new Dw(e,this._dataChannelId),this._dataChannelAdapter.on("message",(e=>{this.handleDataChannelMessageReceived(e)})),this._dataChannelAdapter.on("stateChanged",(e=>{this.handleDataChannelStateChanged(e)})),this._dataChannelAdapter.initialize(),this._sendFeatureUsage("initialize",oE.initialize)}dispose(){this._dataChannelAdapter?.off("message",(()=>{})),this._dataChannelAdapter?.off("stateChanged",(()=>{})),super.disposeAllBotStreams(),this._dataChannelAdapter?.dispose()}get togetherModeStream(){return[...this._streamIdToStreamMap.values()].map((e=>e))}get seatingCooridnates(){return this._seatingCoordinates}set sceneSize(e){this._botSceneSize=e;const t=this.decodeMessageData(this._lastdataChannelMessage?.data);this.updateSeatingCoordinatesAndEmitEvent(t?.payload,t?.eventType)}get sceneSize(){return this._botSceneSize}async start(){const e="start";try{this.validateCanStartTogetherMode()}catch(t){return this._sendFeatureUsage(e,oE.failure,t),void this._logger.error(`[${this._featureName}]: Validation failed. ${JSON.stringify(t)}`)}if(this.isTogetherModeBotInCall())this._logger.warn("Together mode is already active");else{this._sendFeatureUsage(e,oE.attempt),this._logger.info(`[${this._featureName}]: Adding together mode bot to call`);try{await this._tsCall.addParticipant(this._togetherModeBotId)}catch(t){const i=new le({defaultError:ee.FEATURES.TOGETHER_MODE.ADD_TOGETHER_MODE_BOT_FAILED,originalError:t});throw this._sendFeatureUsage(e,oE.failure,i),i}const t={level:"user",type:"togetherMode",content:"{}",participantIds:[this._togetherModeBotId]};try{await this._tsCall.publishState(t,X.generateCauseId())}catch(t){const i=bb(t,ee.FEATURES.TOGETHER_MODE.PUBLISH_TOGETHER_MODE_STATE_FAILED);throw this._sendFeatureUsage(e,oE.failure,i),i}this._sendFeatureUsage(e,oE.success)}}createConcreteVideoStream(e,t){return new JM(e,this._logger,this._call,t,this._telemetryLogManager)}getStreamTypes(){return[0]}emitVideoStreamsUpdatedEvent(e){return this._eventEmitter.emit("togetherModeStreamsUpdated",e)}handleDataChannelMessageReceived(e){if(!e?.data)return;const t="messageReceived";try{this._sendFeatureUsage(t,oE.attempt),this._lastdataChannelMessage=e;const i=this.decodeMessageData(e.data);if(!i?.payload?.seating)return this._logger.info("Received data does not contain seating information. Ignoring the event"),void this._sendFeatureUsage(t,oE.success);if(i.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(t,oE.success);this._lastSeatingMapData=i.payload.seating,this.updateSeatingCoordinatesAndEmitEvent(i.payload,i.eventType),this._sendFeatureUsage(t,oE.success)}catch(e){const i=new le({defaultError:ee.FEATURES.TOGETHER_MODE.SEAT_MAP_CALCULATION_FAILED,originalError:e});this._sendFeatureUsage(t,oE.failure,i)}}decodeMessageData(e){return e?JSON.parse((new TextDecoder).decode(e)):null}updateSeatingCoordinatesAndEmitEvent(e,t){if(t===qM.sceneChanged||t===qM.seatingChanged){const i=t===qM.sceneChanged?"togetherModeSceneUpdated":"togetherModeSeatingUpdated";this._seatingCoordinates=((e,t)=>{const i=new Map,n=JSON.parse((e=>{try{const t=$T.ungzip(kR.Buffer.from(e,"base64"));return(new TextDecoder).decode(t)}catch(e){throw e}})(e))?.seating;return n.forEach((e=>{const n=e?.mri,r=((e,t)=>{const{sceneX:i,sceneY:n,sceneWidth:r,sceneHeight:s}=zM(t),a=WM(e.x,e.y,e.w,e.h,r,s),o=vy().calling.togetherMode.mainVideo.scaledHeightRatio,l=vy().calling.togetherMode.mainVideo.scaledWidthRatio;return{top:n+a.y+a.h*(1-o),left:i+a.x+a.w*(1-l)/2,width:a.w*l,height:a.h*o}})({x:e?.x,y:e?.y,w:e?.w,h:e?.h},t);i.set(n,r)})),i})(e?.seating,this._botSceneSize),vy().calling.togetherMode.forceSeatMapRequest&&this.requestSeatMap(),"togetherModeSceneUpdated"===i&&this._eventEmitter.emit("togetherModeSeatingUpdated",this._seatingCoordinates),this._eventEmitter.emit(i,this._seatingCoordinates)}}validateCanStartTogetherMode(){if(!this._callAgent.isCteUser())throw new le({defaultError:ee.FEATURES.TOGETHER_MODE.UNSUPPORTED_USER_KIND});if(!this.isSupportedConversationType())throw new le({defaultError:ee.FEATURES.TOGETHER_MODE.UNSUPPORTED_CONVERSATION_TYPE})}handleDataChannelStateChanged(e){e===Mw.Started&&this.requestSeatMap()}requestSeatMap(){try{const e={eventType:"seatMapping",payload:{seqId:1}};this._dataChannelAdapter?.send((new TextEncoder).encode(JSON.stringify(e)))}catch(e){throw new le({defaultError:ee.FEATURES.TOGETHER_MODE.REQUEST_INITIAL_SEAT_MAPPING_FAILED,originalError:e})}}updateTogethermodeBotId(e){this._togetherModeBotId=e,super.updateBotIds([e])}isGccBotInCall(){for(let e of this._tsCall.participants)if(e.id===vy().calling.togetherMode.gccBotId)return!0;return!1}isTogetherModeBotInCall(){for(let e of this._tsCall.participants)if(e.id===this._togetherModeBotId)return!0;return!1}isSupportedConversationType(){const e=this._tsCall.conversationType;return!!e&&!!this._supportedConversationTypes.find((t=>t===e))}_sendFeatureUsage(e,t,i){const n=i&&_b(i);hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"TogetherMode",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}class JM extends rw{constructor(e,t,i,n,r){super(e,t,i,n,r,"TogetherModeVideoStream"),this._isAvailable=!1;const s=()=>{this.setIsAvailable(this.tsStream.isAvailable)};this._streamChangedHandler=this.tsStream.changed((()=>{s()})),s()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}setIsAvailable(e){e!==this._isAvailable&&(this._isAvailable=!!e,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 YM{constructor(e,t,i,n,r,s,a,o){this._logger=n.createChild((()=>"BreakoutRooms")),this._logger.log("created"),this._tsCall=e,this._mainMeeting=i,this._callAgent=t,this._telemetryLogManager=s,this.state="closed",this._eventEmitter=r,this.threadId="",this._breakoutRoomsCallFeature=a,this._breakoutRoomsService=o,this._hangUpCallDelayInMilliSeconds=vy().calling.breakoutRooms.hangUpCallDelayInMilliSeconds}async join(){try{if("open"!==this.state)throw this._logger.error("Breakout room is not open."),new le({defaultError:ee.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(e){throw this._logger.error("Breakout Room join failed",e),this._sendFeatureUsage("BreakoutRoomJoinError",oE.failure),this._logger?.error(e),e}}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 GT(this._hangUpCallDelayInMilliSeconds)),this.isBreakoutRoomManager()?(this._logger?.info("Resuming main meeting."),await this.resumeMainMeeting()):await this.rejoinMainMeeting()}catch(e){throw this._logger.error("Rejoin main meeting failed.",e),this._sendFeatureUsage("RejoinMainMeetingError",oE.failure),new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.RETURN_TO_MAINMEETING_FAILED,originalError:e})}}async hangUp(e){null!=e&&setTimeout((()=>{this.handleBreakoutRoomCallHangUp(e)}),this._hangUpCallDelayInMilliSeconds)}async handleBreakoutRoomCallHangUp(e){"Connected"===e?.state&&await(e?.hangUp().then((()=>{this._logger.info("Breakout room call hang up success.")})).catch((e=>{throw this._logger.error("Error in hanging up the breakout room call.",e),new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.HANGUP_EXISTING_BREAKOUT_ROOM_FAILED,originalError:e})})))}getBreakoutRoomCall(e){return this._callAgent.calls.find((t=>t.id==e))}async rejoinMainMeeting(){let e;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 le({defaultError:ee.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&&(e=this._callAgent.join({meetingLink:this._breakoutRoomsService.mainMeetingjoinLink}),this._logger.info("joined mainmeeting , callId :",e.id),this._sendFeatureUsage("RejoinMainMeetingSuccess",oE.success)),Promise.resolve(e)}async joinBreakoutRoomCall(){try{if(null==this.url)throw new le({defaultError:ee.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 e={type:"join",data:this.call};this.emitBreakoutRoomsUpdated(e),this._logger.info("Joined breakout room. callId :",this.call.id),this._sendFeatureUsage("BreakoutRoomJoin",oE.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(e){throw this._logger.error("Breakout room join failed",e),new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.JOIN_FAILED,originalError:e})}return Promise.resolve(this.call)}emitBreakoutRoomsUpdated(e){!this._mainMeeting.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdated",e),this._mainMeeting.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",e)}async holdMainMeetingCall(){this._mainMeeting.isSubscribedCall||"Connected"!=this._mainMeeting.state||this._mainMeeting.hold().catch((e=>{throw this._logger.error("Main meeting hold failed",e),new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.MAINMEETING_HOLD_FAILED,originalError:e})}))}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",oE.success);let e=this._callAgent.calls.find((e=>e.id==this._mainMeeting.id));if(e)return e;throw new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.MAINMEETING_RESUME_FAILED,originalError:"Main meeting call not found."})})).catch((e=>{const t=new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.MAINMEETING_RESUME_FAILED,originalError:e});throw this._logger?.error("Error in resuming main meeting",t),this._sendFeatureUsage("MainMeetingResumeError",oE.failure),t}))}catch(e){throw e}throw new le({defaultError:ee.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",oE.success)})).catch((e=>{this._logger?.error("Not able to disconnect subscribed call",e),this._sendFeatureUsage("SubscribedCallHangupError",oE.failure)})))}async hangUpMainMeeting(){try{if(!this.isBreakoutRoomManager()){let e=this._callAgent.getCallByCallId(this._mainMeeting.id);const t=e&&JSON.parse(await e.getJoinBlob()),i=t?.conversationUrl;if(!i)throw new le({defaultError:ee.CALL.GET_SERVER_CALL_ID});if(e){const t={meetingUrl:i,threadId:e.threadId,callId:e.callId,participantId:e.participantId,messageId:e.messageId};this._mainMeeting.on("stateChanged",(async()=>{if("Disconnected"===this._mainMeeting.state)return this._mainMeeting.dispose(),await this.joinMainMeetingWithoutModalities(t)})),await this._mainMeeting.hangUp()}}}catch(e){this._sendFeatureUsage("MainMeetingHangupError",oE.failure),this._logger?.error("Error in hangingup main meeting ",e)}}isBreakoutRoomManager(){if(this._callAgent.isCteUser()){if(this._mainMeeting?.role==yS.Organizer||this._mainMeeting?.role==yS.Coorganizer)return!0;const e=this._callAgent.getUserMri(),t=this._tsCall.meetingDetails?.breakoutDetails?.mainMeetingProperties?.breakoutRoomManagers||this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties?.breakoutRoomManagers;return null!=t&&0!=t?.length&&!!t.find((t=>t.id===e))}return!1}async joinMainMeetingWithoutModalities(e){this._callAgent.subscribeCallWithoutModality(e).then((e=>{if(e.isSubscribedCall=!0,this._mainMeeting=e,e){let t=this._callAgent.getCallByCallId(e.id);t&&(this._breakoutRoomsCallFeature.initialize({tsCall:t,call:e,callAgent:this._callAgent,telemetryLogManager:this._telemetryLogManager},this._logger),this._breakoutRoomsCallFeature.on("breakoutRoomsUpdatedInternal",(e=>{this._breakoutRoomsService.breakoutRoomsCallFeatureImpl?.emitBreakoutRoomsEvents(e)})))}this._logger?.info("Joined main meeting without modalities successfully"),this._sendFeatureUsage("SubscribedCallJoinSuccess",oE.success)})).catch((e=>{throw this._logger?.error("Error in joining the main meeting without modalities",e),this._sendFeatureUsage("SubscribedCallJoinFailed",oE.failure),e}))}_sendFeatureUsage(e,t,i){let n=i?_b(i):void 0;hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}function QM(e){const t=new URL(e),i=t.pathname.split("/"),n=decodeURIComponent(i[3]);return!!t.searchParams.get("context")&&!!n}function ZM(e,t){let i=!0;try{const t=new URL(e);if(vy().teamsMeetingShortUrlJoin.validatePattern){const e=new RegExp(vy().teamsMeetingShortUrlJoin.regexPattern);i=!!t.toString().trim().match(e)}}catch(e){t.error(`Teams Meeting url validation failed with error= ${JSON.stringify(e)}`),i=!1}return i}function XM(e,t){return t.some((t=>e.includes(t.trim().toLocaleLowerCase())))}function eD(e){try{const t=new URL(e),i=t.pathname.split("/"),n=decodeURIComponent(i[3]),r=i[4],s=JSON.parse(decodeURIComponent(t.search.replace("?context=","")));return{threadId:n,messageId:r,organizerId:s.Oid,tenantId:s.Tid}}catch(e){throw new le({defaultError:ee.CALL_AGENT.INVALID_MEETING_LINK,originalError:e})}}class tD{constructor(e,t,i,n,r,s,a,o){this._autoMoveInMs=vy().calling.breakoutRooms.autoMoveInMilliSeconds,this._eventEmitter=a,this._tsCall=e,this._currentCall=i,this._telemetryLogManager=n,this._callAgent=t,this._logger=r,this._breakoutRoomsCallFeature=s,this.breakoutRoomsService=o,this.breakoutRoom=new YM(this._tsCall,this._callAgent,this._currentCall,this._logger,a,this._telemetryLogManager,this._breakoutRoomsCallFeature,this.breakoutRoomsService)}initialize(e){e.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(e){this._eventEmitter.emit("breakoutRoomsUpdated",e)}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 e=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!=e?.meetingJoinUrl,this.breakoutRoomsService.isNewBreakoutRoomAssigned&&(this.breakoutRoomsService.breakoutRoomCallId=this._breakoutRoomAssignedInternal?.call?.id)),e){this._breakoutRoomAssignedInternal=this.updateAssignedBreakoutRoomDetails(e);const t={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(t)}this.canJoinBreakoutRoom()&&this.joinBreakoutRoom(),this._currentCall.isSubscribedCall&&this._breakoutRoomAssignedInternal&&!this.breakoutRoomsService.isNewBreakoutRoomAssigned&&this.breakoutRoomsService.breakoutRoomCallId&&(this._breakoutRoomAssignedInternal.call=this._callAgent.calls.find((e=>e.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 e={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(e)}if(this.hasAllBreakoutRoomsAvailable(this._tsCall.breakoutDetails?.mainMeetingProperties?.allBreakoutRooms)){this._logger?.info("all breakoutrooms available"),this.parseBreakoutRooms(this._tsCall.breakoutDetails?.mainMeetingProperties?.allBreakoutRooms);const e={type:"breakoutRooms",data:this.breakoutRooms};this._eventEmitter.emit("breakoutRoomsUpdated",e)}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 e={type:"breakoutRoomsSettings",data:this.breakoutRoomSettings};this._currentCall.isBreakoutRoomCall=!0,this._eventEmitter.emit("breakoutRoomsUpdated",e)}}catch(e){throw this._logger.error("Could not Update Breakout details.",e),this._sendFeatureUsage("UpdateBreakoutDetails",oE.failure),new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.BREAKOUT_ROOMS_UPDATEFAILED,originalError:e})}}updateAssignedBreakoutRoomDetails(e){let t=this.breakoutRoom;return this.assignBreakoutRoomProperties(e,t),t}assignBreakoutRoomProperties(e,t){t.autoMoveParticipantToBreakoutRoom=e?.allowMoveParticipantsAutomatically,t.displayName=e?.name,t.url=e?.meetingJoinUrl,t.threadId=e?.meetingJoinUrl&&eD(e?.meetingJoinUrl)?.threadId||"",t.state=e?.isOpen?"open":"closed"}emitBreakoutRoomsUpdated(e){!this._currentCall.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdated",e),this._currentCall.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",e)}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 e={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(e),"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((e=>{this._breakoutRoomAssignedInternal&&(this._breakoutRoomAssignedInternal.call=e),this._logger?.info("Breakout room call joined successfully")}))}),this._autoMoveInMs)}catch(e){throw this._logger?.error(e),e}}hasbreakoutRoomSettingsAvailable(e){return null!=e&&void 0===this._breakoutRoomSettingsInternal}hasbreakoutRoomSettingsUpdated(e){return null!=e&&null==this._breakoutRoomSettingsInternal||e?.roomEndTime!=this._breakoutRoomSettingsInternal?.roomEndTime||e?.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(e){this._breakoutRoomsInternal=e.map((e=>{let t=new YM(this._tsCall,this._callAgent,this._currentCall,this._logger,this._eventEmitter,this._telemetryLogManager,this._breakoutRoomsCallFeature,this.breakoutRoomsService);return this.assignBreakoutRoomProperties(e,t),t.invitees=e.invitees.map((e=>kS(e.id))),t}))}hasAllBreakoutRoomsAvailable(e){return!!(e?.length>0&&0==this._breakoutRoomsInternal?.length||e?.length!=this._breakoutRooms?.length||this.hasAllBreakoutRoomsPropertiesChanged(e)||this._breakoutRoomsInternal&&this._breakoutRoomsInternal?.length>0&&0==e?.length)}hasAllBreakoutRoomsPropertiesChanged(e){return!!(e&&e.length>0&&this._breakoutRooms&&this._breakoutRooms.length>0)&&e.some((e=>{const t=this._breakoutRoomsInternal?.find((t=>e.displayName===t.displayName));return!t||e.isOpen!==("open"===t.state)}))}hasBreakoutRooomsAssigned(e){return(null==this._breakoutRoomAssignedInternal?.url||""==this._breakoutRoomAssignedInternal?.url)&&void 0!==e?.meetingJoinUrl||this._breakoutRoomAssignedInternal?.displayName!=e?.name}hasBreakoutRooomsAssignmentChanged(e){return!!(this._breakoutRoomAssignedInternal?.url&&e&&void 0!==e?.meetingJoinUrl&&this._breakoutRoomAssignedInternal?.url!=e?.meetingJoinUrl||this._breakoutRoomAssignedInternal?.autoMoveParticipantToBreakoutRoom!=e?.allowMoveParticipantsAutomatically)}hasBreakoutRoomsStateChanged(e){return!(!this._breakoutRoomAssignedInternal||this.isBreakoutRoomOpen()==e.isOpen)}isBreakoutRoomOpen(){return"open"===this._breakoutRoomAssignedInternal?.state}_sendFeatureUsage(e,t,i){let n=i?_b(i):void 0;hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}class iD{constructor(e){this._eventEmitter=e}emit(e,t){!e&&this._eventEmitter.emit("breakoutRoomsUpdated",t),e&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",t)}subscribe(e){this._eventEmitter.on("breakoutRoomsUpdatedInternal",e)}static getInstance(e){return iD.instance||(iD.instance=new iD(e)),iD.instance}dispose(){iD.instance=void 0}}class nD{constructor(e,t){this._isEnabled=vy().calling.breakoutRooms.enabled,this._supportedConversationTypes=vy().calling.breakoutRooms.supportedConversationTypes,this._eventEmitter=e,this._breakoutRoomsCallFeature=t}initialize(e,t,i,n,r,s){this._logger=r.createChild((()=>`BreakoutRoomsFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._internalCallAgent=t;const a="initialize";if(this._breakoutRoomsImpl=new tD(e,t,i,n,r,this._breakoutRoomsCallFeature,this._eventEmitter,s),this._breakoutRoomsImpl._sendFeatureUsage(a,oE.attempt),!this._isEnabled){const e="Breakoutrooms feature is is disabled",t=new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.DISABLED});throw this._breakoutRoomsImpl._sendFeatureUsage(a,oE.failure,t),this._logger.error(e),t}if(3===this._tsCall.state&&!this._supportedConversationTypes.includes(e.conversationType)){const e="Breakout rooms feature is only available in meetings",t=new le({defaultError:ee.FEATURES.BREAKOUT_ROOMS.ONLY_AVAILABLE_IN_MEETINGS});throw this._breakoutRoomsImpl._sendFeatureUsage(a,oE.failure,t),this._logger.error(e),t}this._breakoutRoomsImpl.initialize(this._tsCall),this._breakoutRoomsImpl._sendFeatureUsage(a,oE.success)}get breakoutRoomAssigned(){return this._breakoutRoomsImpl.breakoutRoomAssigned}get breakoutRooms(){return this._breakoutRoomsImpl.breakoutRooms}get breakoutRoomSettings(){return this._breakoutRoomsImpl.breakoutRoomSettings}emitBreakoutRoomsEvents(e){return this._breakoutRoomsImpl.emitBreakoutRoomsEvents(e)}}var rD;!function(e){e.Initialize="initialize",e.Dispose="dispose",e.RealTimeTextReceived="realTimeTextReceived",e.SendRealTimeText="sendRealTimeText",e.StartDataChannel="startDataChannel",e.LockTimerToDataChannel="lockTimerToDataChannel",e.SendTimerToDataChannel="sendTimerToDataChannel",e.FinalizedSendRealTimeText="finalizedSendRealTimeText",e.RealTimeTextStarted="realTimeTextStarted"}(rD||(rD={}));class sD{constructor(e){this._eventEmitter=e,this._dataChannelInitialized=!1,this._firstMessageReceivedOrSent=!1,this._entries=new Map,this.sequenceId=0,this._userMri="",this._nextMessage="",this._rttSendTimerToDataChannel=()=>{const e=Mf();this._sendTimer=setTimeout((async()=>{this._sendFeatureUsage(rD.SendTimerToDataChannel,oE.attempt,e),this._nextMessage.includes("\n")&&this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),await this._purgeMessage(e,rD.SendTimerToDataChannel)}),300)},this._rttLockTimerToDataChannel=()=>{const e=Mf();this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),this._lockTimer=setTimeout((async()=>{this._sendFeatureUsage(rD.LockTimerToDataChannel,oE.attempt,e);let t=this._entries.get(this._userMri)?.text??"";(""!==t.trim()||this._entries.get(this._userMri)&&"Final"!==this._entries.get(this._userMri)?.resultType)&&(this._nextMessage=t+"\n",await this._purgeMessage(e,rD.LockTimerToDataChannel))}),3e3)},this._dataChannelHandler=e=>{let t,{sourceId:i,data:n}=e;const r=Mf();try{this._sendFeatureUsage(rD.RealTimeTextReceived,oE.attempt,r),t=JSON.parse(n.toString())}catch(e){try{if(void 0===this._textDecoder)throw new Error("TextDecoder undefined.");t=JSON.parse(this._textDecoder.decode(n))}catch(e){throw this._logger.error("Failed to parse RealTimeText message"),new le({defaultError:ee.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_PARSE_FAILED})}try{if(t&&i){let e=t.s,n=this._participantMappingManager?.findParticipantMri(i);if(!n)throw new le({defaultError:ee.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_CONTAINS_NO_SPEAKER});this._updateEntries(n,e),this._sendFirstMessageReceivedOrSentTelemetry(),this._sendFeatureUsage(rD.RealTimeTextReceived,oE.success,r)}}catch(e){const t=new le({originalError:e,defaultError:ee.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_HANDLER_FAILED});throw this._sendFeatureUsage(rD.RealTimeTextReceived,oE.failure,r,t),t}}},this._updateEntries=(e,t)=>{try{let i,n=this._entries.get(e),{composedText:r,isFinal:s}=this._generateRealTimeTextMessage(t,n&&"Final"!==n.resultType?n.text:"");const a=new Date,o=s?"Final":"Partial";if(n)i={...n,sequenceId:"Final"===n.resultType?this.sequenceId++:n.sequenceId,text:r,updatedTimestamp:a,resultType:o};else{const t=this._tsCall.participants.find((t=>t.id===e))?.displayName||(this._internalCallAgent.getUserMri()===e?this._internalCallAgent?.displayName:void 0);i={sequenceId:this.sequenceId++,text:r,sender:{identifier:kS(e),displayName:t,endpointDetails:[]},receivedTimestamp:a,updatedTimestamp:a,resultType:o,isLocal:this._internalCallAgent.getUserMri()===e}}this._entries.set(e,i),this._eventEmitter.emit("realTimeTextReceived",this._entries.get(e)),"Final"===this._entries.get(e)?.resultType&&this._entries.delete(e)}catch(e){throw new le({originalError:e,defaultError:ee.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_ENTRY_UPDATE_FAILED})}},this._generateRealTimeTextMessage=(e,t)=>{let i=t;for(const t of e)switch(t){case"\b":i=i.slice(0,-1);break;case"\n":return{composedText:i,isFinal:!0};default:i+=t}return{composedText:i,isFinal:!1}}}initialize(e,t,i,n,r,s){this._logger=r,this._tsCall=e,this._call=t,this._internalCallAgent=i,this._telemetryLogManager=n;try{this._userMri=this._internalCallAgent.getUserMri(),this._rttDataChannelAdapter=new Dw(e,24),this._participantMappingManager=new mw(e),this._textDecoder=new TextDecoder,this._textEncoder=new TextEncoder,this.startDataChannel(s)}catch(e){const t=new le({originalError:e,defaultError:ee.FEATURES.REAL_TIME_TEXT.INITIALIZE_FAILED});throw this._sendFeatureUsage(rD.Initialize,oE.failure,s,t),t}}startDataChannel(e){try{this._rttDataChannelAdapter||(this._rttDataChannelAdapter=new Dw(this._tsCall,24)),this._dataChannelInitialized||(this._rttDataChannelAdapter.initialize().then((()=>{this._dataChannelInitialized=!0})),this._rttDataChannelAdapter.off("message",this._dataChannelHandler),this._rttDataChannelAdapter.on("message",this._dataChannelHandler))}catch(t){const i=new le({originalError:t,defaultError:ee.FEATURES.REAL_TIME_TEXT.START_REAL_TIME_TEXT_FAILED});throw this._sendFeatureUsage(rD.StartDataChannel,oE.failure,e,i),i}}async sendRealTimeText(e,t){const i=Mf();this.startDataChannel(i);let n=rD.SendRealTimeText;t&&(n=rD.FinalizedSendRealTimeText),this._sendFeatureUsage(n,oE.attempt,i);try{if(""===e&&(!this._entries.get(this._userMri)||"Final"===this._entries.get(this._userMri)?.resultType))return;if(!t&&e===this._entries.get(this._userMri)?.text)return;if(e.length>2e3)throw new le({defaultError:ee.FEATURES.REAL_TIME_TEXT.MESSAGE_LENGTH_EXCEEDS_MAX_INPUT_LENGTH});this._nextMessage=t?e+="\n":e,t?(this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),this._sendTimer&&(clearTimeout(this._sendTimer),this._sendTimer=null),await this._purgeMessage(i,n)):(this._rttLockTimerToDataChannel(),this._sendTimer||this._rttSendTimerToDataChannel()),this._sendFeatureUsage(n,oE.success,i)}catch(e){const t=new le({originalError:e,defaultError:ee.FEATURES.REAL_TIME_TEXT.SEND_REAL_TIME_TEXT_MESSAGE_FAILED});throw this._sendFeatureUsage(n,oE.failure,i,t),t}}async _purgeMessage(e,t){const i=aD(this._entries.get(this._userMri)?.text??"",this._nextMessage);if(""!==i){if(void 0===this._textEncoder)throw new Error("TextEncoder undefined.");let n=this._textEncoder.encode(JSON.stringify({s:i}));this._updateEntries(this._internalCallAgent.getUserMri(),i);try{await(this._rttDataChannelAdapter?.send(n)),this._sendFirstMessageReceivedOrSentTelemetry()}catch(i){const n=new le({defaultError:ee.FEATURES.REAL_TIME_TEXT.SEND_DATA_CHANNEL_MESSAGE_FAILED});throw this._sendFeatureUsage(t,oE.failure,e),n}this._nextMessage="",i.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(t,oE.success,e)}}dispose(){this._textDecoder=void 0}_sendFeatureUsage(e,t,i,n){const r=n&&_b(n);hb({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RealTimeText",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}_sendFirstMessageReceivedOrSentTelemetry(){this._firstMessageReceivedOrSent||(this._sendFeatureUsage(rD.RealTimeTextStarted,oE.event),this._firstMessageReceivedOrSent=!0)}}const aD=(e,t)=>{let i="";const n=Math.min(e?.length,t.length);let r=-1;for(let s=0;s<n;s++)e[s]!==t[s]&&-1===r&&(r=s),-1!==r&&(i+="\b");for(let t=n;t<e.length;t++)i+="\b";return i+=-1===r?t.substring(n):t.substring(r),i},oD={Recording:lb(class extends ZE{constructor(e){super(e),this._callInfo=e.callInfo,this._impl=new aI(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",oE.getter),"Recording"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,t,this._callInfo,this._call),this._sendFeatureUsage("initialize",oE.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",oE.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",oE.getter),this._impl.recordings}on(e,t){if("isRecordingActiveChanged"!==e&&"recordingsUpdated"!==e)throw new le({defaultError:ee.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("isRecordingActiveChanged"!==e&&"recordingsUpdated"!==e)throw new le({defaultError:ee.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}get isTeamsConsentRequired(){return this._sendFeatureUsage("isTeamsConsentRequired",oE.getter),this._impl.isTeamsConsentRequired}grantTeamsConsent(){return this._sendFeatureUsage("ConsentForRecording",oE.attempt),this._impl.grantTeamsConsent().then((()=>{this._sendFeatureUsage("ConsentForRecording",oE.success)})).catch((e=>{throw this._sendFeatureUsage("ConsentForRecording",oE.failure,e),e}))}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}_sendFeatureUsage(e,t,i){let n=i?_b(i):void 0;hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Recording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}),Transfer:lb(class extends ZE{constructor(e){super(e),this._impl=new fI(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",oE.getter),"Transfer"}transfer(e,t){return this._impl.transfer(e,t)}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",oE.initialize)}on(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}_sendFeatureUsage(e,t){hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}),Transcription:lb(class extends ZE{constructor(e){super(e),this._impl=new uI(this.eventEmitter),this._callInfo=e.callInfo}get name(){return this._sendFeatureUsage("name",oE.getter),"Transcription"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,t,this._callInfo,this._call),this._sendFeatureUsage("initialize",oE.initialize)}get isTranscriptionActive(){return this._sendFeatureUsage("isTranscriptionActive",oE.getter),this._impl.isTranscriptionActive}get isTeamsConsentRequired(){return this._sendFeatureUsage("isTeamsConsentRequired",oE.getter),this._impl.isTeamsConsentRequired}grantTeamsConsent(){return this._sendFeatureUsage("ConsentForTranscription",oE.attempt),this._impl.grantTeamsConsent().then((()=>{this._sendFeatureUsage("ConsentForTranscription",oE.success)})).catch((e=>{throw this._sendFeatureUsage("ConsentForTranscription",oE.failure,e),e}))}on(e,t){this._sendFeatureUsage("isTranscriptionActiveChanged",oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage("isTranscriptionActiveChanged",oE.unsubscribe),this.eventEmitter.off(e,t)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}_sendFeatureUsage(e,t,i){let n=i?_b(i):void 0;hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transcription",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}),Captions:lb(class extends ZE{constructor(e){super(e),this._impl=new kb(this.eventEmitter)}initialize(e,t){const i=Mf();this._impl.initialize(e.tsCall,e.call,e.callAgent,e.callAgent.getHttpRequestHelper(),e.telemetryLogManager,t,this._telemetryStartTime,i),this._logger=t,this._telemetryStartTime=+Date.now(),this._telemetryLogManager=e.telemetryLogManager,this._call=e.call}get name(){return this._sendFeatureUsage("name",oE.getter),this._captionsTelemetryType.toString()}get _captionsTelemetryType(){return"TeamsCaptions"===this._impl.kind?ab.TeamsCaptions:ab.Captions}get captions(){return this._impl.captions}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}_sendFeatureUsage(e,t){hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:this._captionsTelemetryType,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),RaiseHand:lb(class extends ZE{constructor(e){super(e),this._impl=new Ob(this.eventEmitter),this._callInfo=e.callInfo}get name(){return"RaiseHand"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t,this._callInfo)}async raiseHand(){return this._impl.raiseHand()}async lowerHand(){return this._impl.lowerHand()}async lowerHands(e){return this._impl.lowerHands(e)}lowerAllHands(){return this._impl.lowerAllHands()}getRaisedHands(){return this._sendFeatureUsage("getRaisedHands",oE.getter),this._impl.raisedHands}on(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),LocalRecording:lb(class extends ZE{constructor(e){super(e),this._impl=new cI(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",oE.getter),"LocalRecording"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",oE.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",oE.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",oE.getter),this._impl.recordings}on(e,t){if("isLocalRecordingActiveChanged"!==e&&"localRecordingsUpdated"!==e)throw new le({defaultError:ee.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("isLocalRecordingActiveChanged"!==e&&"localRecordingsUpdated"!==e)throw new le({defaultError:ee.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t,i){let n=i?{code:i?.code||ne,subCode:i?.subCode||0,failureReason:i?.message||""}:void 0;hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"LocalRecording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}),Reaction:lb(class extends ZE{constructor(e){super(e),this._impl=new VM(this.eventEmitter),this._isReactionFeatureEnabled=vy().calling.reaction.enabled,this._callInfo=e.callInfo}get name(){return"Reaction"}initialize(e,t){this._tsCall=e.tsCall,this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._logger.info(`Meeting Reaction feature enable flag: ${this._isReactionFeatureEnabled}`),this._isReactionFeatureEnabled&&3===e.tsCall.state?this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t,this._callInfo):e.tsCall.on("callStateChanged",(()=>{this._isReactionFeatureEnabled&&3===e.tsCall.state?this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t,this._callInfo):this._logger.warn("Calls to reaction APIs will perform no action or return default values where applicable")}))}async sendReaction(e){let t=Mf();if(this._sendFeatureUsage("sendReaction",oE.attempt,void 0,t),3!=this._tsCall.state||this.callInfo.context===uy.TwoParty){const e=new le({defaultError:3!=this._tsCall.state?ee.FEATURES.REACTION.CALL_NOT_CONNECTED:ee.FEATURES.REACTION.NOT_SUPPORTED_1TO1_CTE});throw this._sendFeatureUsage("sendReaction",oE.failure,e,t),e}await this._impl.sendReaction(e,t)}on(e,t){if("reaction"!==e)throw new le({defaultError:ee.FEATURES.REACTION.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});if(!this._isReactionFeatureEnabled){const e=new le({defaultError:ee.FEATURES.REACTION.EVENT_SUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",oE.failure,e),e}this._sendFeatureUsage("receiveReaction",oE.subscribe),this._impl.on(e,t)}off(e,t){if("reaction"!==e)throw new le({defaultError:ee.FEATURES.REACTION.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});if(!this._isReactionFeatureEnabled){const e=new le({defaultError:ee.FEATURES.REACTION.EVENT_UNSUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",oE.failure,e),e}this._sendFeatureUsage("receiveReaction",oE.unsubscribe),this._impl.off(e,t)}dispose(){this.disposed||(this._impl.dispose(),super.dispose())}_sendFeatureUsage(e,t,i,n){let r=i?{code:i?.code||ne,subCode:i?.subCode||0,failureReason:i?.message||"",..._b(i)}:void 0;hb({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}}),Spotlight:lb(class extends ZE{constructor(e){super(e),this._impl=new pA(this.eventEmitter),this._isSpotlightFeatureEnabled=vy().calling.spotlight.enabled,this._callInfo=e.callInfo}get name(){return"Spotlight"}initialize(e,t){this._logger=t,this._logger.info(`Spotlight feature enable flag: ${this._isSpotlightFeatureEnabled}`),this._isSpotlightFeatureEnabled?(this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t,this._callInfo)):this._logger.warn("Calls to spotlight APIs will perform no action or return default values where applicable")}async startSpotlight(e){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(e)&&await this._impl.startSpotlight(e)}async stopSpotlight(e){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(e)&&await this._impl.stopSpotlight(e)}async stopAllSpotlight(){this._isSpotlightFeatureEnabled&&await this._impl.stopAllSpotlight()}getSpotlightedParticipants(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("getSpotlightedParticipants",oE.getter),this._impl.spotlightedParticipants):[]}get maxParticipantsToSpotlight(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("maxSpotlightSupportedState",oE.getter),this._impl.maxSpotlightStateSupported):0}on(e,t){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t))}off(e,t){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t))}validateIdentifierParam(e=[]){try{return e.forEach((e=>NS(e))),!0}catch(e){return!1}}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),PPTLive:lb(class extends ZE{constructor(e){super(e),this._impl=new jM(this.eventEmitter)}on(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}get isActive(){return this._impl.isActive}get target(){return this._impl.target}get activePresenterId(){return this._impl.activePresenterId}get name(){return"PPTLive"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:e,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),BreakoutRooms:lb(class extends ZE{constructor(e){super(e),this._impl=new nD(this.eventEmitter,this),this.breakoutRoomsService=iD.getInstance(this.eventEmitter)}get name(){return"BreakoutRooms"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(this._tsCall,e.callAgent,e.call,e.telemetryLogManager,t,this.breakoutRoomsService)}get assignedBreakoutRooms(){return this._impl.breakoutRoomAssigned}get breakoutRooms(){return this._impl.breakoutRooms}get breakoutRoomsSettings(){return this._impl.breakoutRoomSettings}emitBreakoutRoomsEvents(e){this._impl.emitBreakoutRoomsEvents(e)}on(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),Capabilities:lb(class extends ZE{constructor(e){super(e),this._callInfo=e.callInfo,this._impl=new Gb(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",oE.getter),"Capabilities"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.call,this._callInfo,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",oE.initialize)}get capabilities(){return this._sendFeatureUsage("getCapabilities",oE.getter),this._impl.capabilities}on(e,t){this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Capabilities",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),DominantSpeakers:lb(class extends ZE{constructor(e){super(e),this._impl=new C_(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",oE.getter),"DominantSpeakers"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",oE.initialize)}get dominantSpeakers(){return this._sendFeatureUsage("dominantSpeakers",oE.getter),this._impl.dominantSpeakers}on(e,t){this._sendFeatureUsage("dominantSpeakersChanged",oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage("dominantSpeakersChanged",oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"DominantSpeakers",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}),LiveStream:lb(class extends ZE{constructor(e){super(e),this._impl=new uw(this.eventEmitter,this.name)}get name(){return"LiveStream"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}dispose(){this._impl.dispose(),super.dispose()}get liveStreams(){return this._impl.liveStreams}get participantCount(){return this._impl.streamingClientCount}on(e,t){if("liveStreamsUpdated"!==e&&"participantCountChanged"!==e)throw new le({defaultError:ee.FEATURES.LIVE_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("liveStreamsUpdated"!==e&&"participantCount"!==e)throw new le({defaultError:ee.FEATURES.LIVE_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}createStatsCollector(e){return this._impl.createStatsCollector(e)}}),ComposedStream:lb(class extends ZE{constructor(e){super(e),this._impl=new gw(this.eventEmitter,this.name)}get name(){return"ComposedStream"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}dispose(){this._impl.dispose(),super.dispose()}get composedStreams(){return this._impl.composedStreams}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}),CallSurvey:lb(class extends ZE{constructor(e){super(e),this._impl=new mA}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}get name(){return"CallSurvey"}dispose(){super.dispose()}submitSurvey(e){return this._impl.submitSurvey(e)}}),UserFacingDiagnostics:lb(class extends ZE{constructor(e){super(e),this._impl=new m_}get name(){return this._sendFeatureUsage("name",oE.getter),"Diagnostics"}get network(){return this._sendFeatureUsage("network",oE.getter),this._impl.network}get media(){return this._sendFeatureUsage("media",oE.getter),this._impl.media}get remote(){return this._sendFeatureUsage("remote",oE.getter),this._impl.remote}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e,t),this._sendFeatureUsage("initialize",oE.initialize)}_sendFeatureUsage(e,t){hb({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Diagnostics",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}),MediaStats:lb(nI,{activationEvent:"OnExtendedObjectConstructor"}),DebugInfo:cb(class extends eb{constructor(e){super(e),this._impl=new Wb;try{US().includes("stable")||(this._browserTabInfoImpl=new Kb(this.eventEmitter))}catch(t){e.callClient.logger.error("Feature to detect multiple tabs is not supported on the current environment.")}}get name(){return this._sendFeatureUsage("name",oE.getter),"DebugInfo"}get lastLocalParticipantId(){return this._sendFeatureUsage("lastLocalParticipantId",oE.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",oE.getter),this.lastLocalParticipantId)return this._impl.localParticipantIdMap[this.lastLocalParticipantId].callIds.slice(-1)[0]}get diagnosticInformation(){return this._impl.diagnosticInformation}get sdkVersion(){return US()}get acsResourceId(){return this._impl.AcsResourceId}get clientId(){return this._impl.clientId}dumpDebugInfoAsJSONString(){try{return JSON.stringify(this.toZip())}catch(e){return`JSON.stringify threw: ${e}`}}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",oE.attempt);try{const e=$T.deflate(this.dumpDebugInfoAsJSONString(),{to:"string"}),t=function(e){var t=typeof e;if("string"===t||"number"===t)return function(e,t){var i="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";t=t||62;var n,r=[],s="",a=e<0?"-":"";for(e=Math.abs(e);e>=t;)n=e%t,e=Math.floor(e/t),r.push(i[n]);e>0&&r.push(i[e]);for(var o=r.length-1;o>=0;o--)s+=r[o];return a+s}(function(e){var t=0;if(0==e.length)return t;for(var i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}(String(e)),61).replace("-","Z");throw new Error("Unexpected input type")}(e);return this._sendFeatureUsage("dumpDebugInfo",oE.success),{dump:e,dumpId:`${Mf()}-${t}`}}catch(e){const t=`failed to deflate, error: ${e}`;return this.logger.error(t),this._sendFeatureUsage("dumpDebugInfo",oE.failure),{dump:$T.deflate(t,{to:"string"}),dumpId:Mf()}}}initialize(e,t){this._impl.initialize(e,t),this.logger=t,this._telemetryLogManager=e.telemetryLogManager,this._callClient=e.callClient,this._browserTabInfoImpl&&this._browserTabInfoImpl.initialize(e.callClient,t,e.telemetryLogManager),this._sendFeatureUsage("initialize",oE.initialize)}async getEnvironmentInfo(){return this._sendFeatureUsage("getEnvironmentInfo",oE.getter),await this._callClient.getEnvironmentInfoInternal()}get isAnotherCallClientActiveInSameTab(){return this._sendFeatureUsage("isAnotherCallClientActiveInSameTab",oE.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isAnotherCallClientActiveInSameTab}get isCallClientActiveInAnotherTab(){return this._sendFeatureUsage("isCallClientActiveInAnotherTab",oE.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isCallClientActiveInAnotherTab}on(e,t){"isCallClientActiveInAnotherTabChanged"!==e&&"isAnotherCallClientActiveInSameTabChanged"!==e&&this.logger.error(`Not able to subscribe to event ${e}, unknown event name`),this._sendFeatureUsage(e,oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){"isCallClientActiveInAnotherTabChanged"!==e&&"isAnotherCallClientActiveInSameTabChanged"!==e&&this.logger.error(`Not able to unsubscribe to event ${e}, unknown event name`),this._sendFeatureUsage(e,oE.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){gb({featureName:"DebugInfo",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this.logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}},{activationEvent:"OnExtendedObjectConstructor"}),PreCallDiagnostics:cb(class extends eb{constructor(e){super(e),this._impl=new iw}initialize(e,t){const i=e.callClient;this._logger=t;const n=i.createInstance({diagnostics:{tags:["diagnostics"]}});this._telemetryLogManager=n.telemetryLogManager,this._impl.intialize(i,n,t,this._telemetryLogManager),this._sendFeatureUsage("initialize",oE.initialize)}get name(){return this._sendFeatureUsage("name",oE.getter),"PreCallDiagnostics"}startTest(e,t){return this._impl.startTest(e,t)}_sendFeatureUsage(e,t){gb({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",oE.attempt),this.disposed?this._sendFeatureUsage("dispose",oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",oE.success))}}),VideoEffects:db(NI),AudioEffects:ub(GI),DataChannel:lb(class extends ZE{constructor(e){super(e)}createDataChannelSender(e){const t=Mf(),i=vy();try{if(void 0!==e.bitrateInKbps&&"number"!=typeof e.bitrateInKbps)throw Cw("bitrateInKbps","number");if(void 0!==e.channelId&&"number"!=typeof e.channelId)throw Cw("channelId","number");if(void 0!==e.participants&&!Array.isArray(e.participants))throw Cw("participants","CommunicationIdentifier[]");if(void 0!==e.priority&&-1===["High","Normal"].indexOf(e.priority))throw Tw("priority","High,Normal");if(void 0!==e.reliability&&-1===["Durable","Lossy"].indexOf(e.reliability))throw Tw("reliability","Durable,Lossy");const n={bitrateInKbps:Math.ceil(e.bitrateInKbps??i.dataChannel.defaultBitrate/1e3),channelId:e.channelId??0,participants:e.participants??[],priority:e.priority??"Normal",reliability:e.reliability??"Durable"};this._logger.info(`createDataChannelSender: ${function(e){const t=[];return void 0!==e.bitrateInKbps&&t.push(`bitrateInKbps=${e.bitrateInKbps}`),void 0!==e.channelId&&t.push(`channelId=${e.channelId}`),void 0!==e.participants&&t.push(`participants size=${e.participants.length}`),void 0!==e.priority&&t.push(`priority=${e.priority}`),void 0!==e.reliability&&t.push(`reliability=${e.reliability}`),t.join(",")}(e)}`),this._sendFeatureUsage("createDataChannelSender",oE.attempt),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"attempt",correlationId:t,senderOptions:{channelId:e.channelId,bitrateInKbps:e.bitrateInKbps,participantsSize:e.participants?.length,priority:e.priority,reliability:e.reliability}});const r=this._dataChannelManager.createSender(n,t);return this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"success",correlationId:t,senderOptions:{channelId:r.channelId,bitrateInKbps:n.bitrateInKbps,participantsSize:n.participants?.length,priority:n.priority,reliability:n.reliability}}),this._logger.info(`The sender is created. channel id=${r.channelId}`),this._sendFeatureUsage("createDataChannelSender",oE.success),r}catch(e){const i=new le({defaultError:ee.FEATURES.DATA_CHANNEL.FAILED_TO_CREATE_SENDER,originalError:e});throw this._logger.info(`Failed to create the sender: ${i.message}`),this._sendFeatureUsage("createDataChannelSender",oE.failure),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"failure",correlationId:t,failureReason:i.message,additionalDetails:{..._b(i)}}),i}}async createDataChannelAdapter(e){const t=new Dw(this._tsCall,e);return await t.initialize(),t}initialize(e,t){this._tsCall=e.tsCall,this._logger=t.createChild("DataChannelCallFeature"),this._telemetryLogManager=e.telemetryLogManager,this._dataChannelTelemetryLogger=new gA(this._tsCall,this._telemetryLogManager);const i=new hA(this._tsCall,this._logger,this._dataChannelTelemetryLogger);this._dataChannelManager=i,this._dataChannelManager.initialize().then((()=>{this._sendFeatureUsage("initialize",oE.initialize)})).catch((e=>{this._logger.error(`initialize:${Aw(e)}`)}))}get name(){return this._sendFeatureUsage("name",oE.getter),"DataChannel"}dispose(){this.disposed||(this._dataChannelManager?.dispose(),super.dispose())}getDataStreamIdsFromParticipant(e){return e.tsRemoteParticipant?this._dataChannelManager.getDataStreamIdsFromParticipant(e.tsRemoteParticipant):[]}on(e,t){if("dataChannelReceiverCreated"!==e)throw yw(e,"subscribe");this._sendFeatureUsage(e,oE.subscribe),"dataChannelReceiverCreated"===e&&this._dataChannelManager?.on("dataChannelReceiverCreated",t)}off(e,t){if("dataChannelReceiverCreated"!==e)throw yw(e,"unsubscribe");this._sendFeatureUsage(e,oE.unsubscribe),"dataChannelReceiverCreated"===e&&this._dataChannelManager?.off("dataChannelReceiverCreated",t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"DataChannel",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),OptimalVideoCount:lb(class extends ZE{_sendOVCTelemetryEvent(e){if(!this._telemetryLogManager)return;const t={callId:this._call?.id||"",localParticipantId:this._tsCall?.participantId||"",featureName:"OptimalVideoCount",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{step:e}};this._telemetryLogManager.sendEvent({name:aE.acs_calling_feature_usage,tenant:xv,properties:t})}get optimalVideoCount(){return this._sendOVCTelemetryEvent(oE.getter),this._tsCall?.optimalVideoCount?this._tsCall.optimalVideoCount:1}constructor(e){super(e),this.name="OptimalVideoCount",this._impl=new vA(this.name,this.eventEmitter,this.optimalVideoCount)}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t),this._tsCall=e.tsCall,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call}on(e,t){if("optimalVideoCountChanged"!==e)throw new le({defaultError:ee.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendOVCTelemetryEvent(oE.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("optimalVideoCountChanged"!==e)throw new le({defaultError:ee.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendOVCTelemetryEvent(oE.unsubscribe),this.eventEmitter.off(e,t)}}),UnmixedAudio:lb(class extends ZE{constructor(e){super(e)}initialize(e,t){const i=vy().unmixedAudio;this._tsCall=e.tsCall,this._logger=t.createChild("UnmixedAudioCallFeature"),this._telemetryLogManager=e.telemetryLogManager;const n=new AA(this._tsCall,this._telemetryLogManager);this._unmixedAudioManager=new kA(this._tsCall,this._logger,n,i),this._unmixedAudioManager.initialize().then((()=>{this._sendFeatureUsage("initialize",oE.initialize)})).catch((e=>{}))}get name(){return this._sendFeatureUsage("name",oE.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(e){return this._unmixedAudioManager.getAudioSourceIdsFromParticipantIds(e.endpointDetails)}on(e,t){if("participantSpeaking"!==e&&"activeStateChanged"!==e)throw SA(e,"subscribe");this._sendFeatureUsage(e,oE.subscribe),this._unmixedAudioManager.on(e,t)}off(e,t){if("participantSpeaking"!==e&&"activeStateChanged"!==e)throw SA(e,"unsubscribe");this._sendFeatureUsage(e,oE.unsubscribe),this._unmixedAudioManager.off(e,t)}_sendFeatureUsage(e,t){hb({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"UnmixedAudio",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),AudioZones:lb(class extends ZE{constructor(e){super(e),this._impl=new fA(this.eventEmitter,this.name)}get name(){return"AudioZones"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}updateAudioZone(e,t){return this._impl.updateAudioZone(e,t)}dispose(){this._impl.dispose(),super.dispose()}get meetingGroupDetails(){return this._impl.meetingGroupDetails}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}),TeamsMeetingAudioConferencing:lb(class extends ZE{constructor(e){super(e),this._impl=new OA}get name(){return"TeamsMeetingAudioConferencing"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)}async getTeamsMeetingAudioConferencingDetails(){return this._impl.getTeamsMeetingAudioConferencingDetails()}dispose(){this.disposed||super.dispose()}}),TogetherMode:lb(class extends ZE{constructor(e){super(e),this._impl=new KM(this.eventEmitter,this.name,vy().calling.togetherMode.botId)}get name(){return"TeamsMeetingTogetherMode"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}dispose(){this._impl.dispose(),super.dispose()}on(e,t){if("togetherModeStreamsUpdated"!==e&&"togetherModeSceneUpdated"!==e&&"togetherModeSeatingUpdated"!==e)throw new le({defaultError:ee.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("togetherModeStreamsUpdated"!==e&&"togetherModeSceneUpdated"!==e&&"togetherModeSeatingUpdated"!==e)throw new le({defaultError:ee.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}get togetherModeStream(){return this._impl.togetherModeStream}get togetherModeSeatingMap(){return this._impl.seatingCooridnates}set sceneSize(e){this._impl.sceneSize=e}get sceneSize(){return this._impl.sceneSize}async start(){await this._impl.start()}}),MediaAccess:lb(Vb),RealTimeText:lb(class extends ZE{constructor(e){super(e),this._impl=new sD(this.eventEmitter)}initialize(e,t){const i=Mf();this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._sendFeatureUsage(rD.Initialize,oE.initialize,i),this._impl.initialize(e.tsCall,e.call,e.callAgent,e.telemetryLogManager,t,i)}get name(){return"RealTimeText"}async sendRealTimeText(e,t){await this._impl.sendRealTimeText(e,t)}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}dispose(){this._sendFeatureUsage(rD.Dispose,oE.attempt),this.disposed?this._sendFeatureUsage(rD.Dispose,oE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage(rD.Dispose,oE.success))}_sendFeatureUsage(e,t,i){hb({correlationId:i,callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}})};function lD(e){switch(e){case YE.CallClientFeature:return Object.entries(oD).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case YE.CallAgentFeature:return Object.entries(oD).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case YE.CallFeature:return Object.entries(oD).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]))}}class cD{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild("CallStats"),this._telemetryLogManager=t}recordEvent(e){try{if(vy()?.telemetry?.callStatsFlushTimeout<0)return;if(vy()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;const t={timestamp:+new Date,...e};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemetryFlush()}catch(e){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 e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:aE.acs_calling_call_stats,tenant:xv,properties:{...e[t]}})})),this.resetEventBag()}catch(e){this._logger.debug("Failed to send call stats")}}scheduleTelemetryFlush(){this._callStatSendTimeout||(this._callStatSendTimeout=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),vy().telemetry.callStatsFlushTimeout))}}function dD(e,t){if("Connected"===t)return;let i;if(e==JS.MuteAllRemoteParticipants)i=ee.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(e==JS.StopAudio)i=ee.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(e==JS.AddParticipant)i=ee.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(e!=JS.RemoveParticipant)return;i=ee.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new le({defaultError:i})}class uD{constructor(e){this._volumeIndicator=e,this._eventEmitter=new OE}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on("levelChanged",(()=>{this._eventEmitter.emit("levelChanged")}))))}dispose(){this._eventEmitter.removeAllListeners()}}class hD{constructor(e,t,i,n){this._workQueue=Promise.resolve();const r=R("ACS-calling");this.logger=new _I(r,[()=>"RemoteAudioStream for media stream"]),this._source=e,this._disposed=!1,this._volumeIndicator=new VI(this.logger,"RemoteAudioStream",t,i,n),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await(this._volumeProxy?.setSource(await this._source.getMediaStream()))})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.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 e=new uD(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(My),await t,this._volumeProxy=e}return this._volumeProxy}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([SI,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata("design:type",t)}(0,Object)],hD.prototype,"logger",void 0);var gD=G((function(e,t){!function(i,n){var r="function",s="undefined",a="object",o="string",l="major",c="model",d="name",u="type",h="vendor",g="version",p="architecture",m="console",f="mobile",v="tablet",S="smarttv",y="wearable",C="embedded",T="Amazon",E="Apple",b="ASUS",_="BlackBerry",I="Browser",w="Chrome",A="Firefox",P="Google",R="Huawei",M="LG",D="Microsoft",k="Motorola",O="Opera",N="Samsung",L="Sharp",x="Sony",F="Xiaomi",U="Zebra",B="Facebook",V="Chromium OS",H="Mac OS",$=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},j=function(e,t){return typeof e===o&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},q=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},z=function(e,t){for(var i,s,o,l,c,d,u=0;u<t.length&&!c;){var h=t[u],g=t[u+1];for(i=s=0;i<h.length&&!c&&h[i];)if(c=h[i++].exec(e))for(o=0;o<g.length;o++)d=c[++s],typeof(l=g[o])===a&&l.length>0?2===l.length?typeof l[1]==r?this[l[0]]=l[1].call(this,d):this[l[0]]=l[1]:3===l.length?typeof l[1]!==r||l[1].exec&&l[1].test?this[l[0]]=d?d.replace(l[1],l[2]):n:this[l[0]]=d?l[1].call(this,d,l[2]):n:4===l.length&&(this[l[0]]=d?l[3].call(this,d.replace(l[1],l[2])):n):this[l]=d||n;u+=2}},W=function(e,t){for(var i in t)if(typeof t[i]===a&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(j(t[i][r],e))return"?"===i?n:i}else if(j(t[i],e))return"?"===i?n:i;return e},K={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"},J={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,g],[/opios[\/ ]+([\w\.]+)/i],[g,[d,O+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[g,[d,O+" GX"]],[/\bopr\/([\w\.]+)/i],[g,[d,O]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[g,[d,"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],[d,g],[/\bddg\/([\w\.]+)/i],[g,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[g,[d,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[g,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[g,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[g,[d,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+I],g],[/\bfocus\/([\w\.]+)/i],[g,[d,A+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[d,O+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[d,O+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[d,"MIUI "+I]],[/fxios\/([-\w\.]+)/i],[g,[d,A]],[/\bqihu|(qi?ho?o?|360)browser/i],[[d,"360 "+I]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1 "+I],g],[/samsungbrowser\/([\w\.]+)/i],[g,[d,N+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[d,/_/g," "],g],[/metasr[\/ ]?([\d\.]+)/i],[g,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[d,g],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,B],g],[/(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],[d,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[g,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[d,w+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,w+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[d,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,g],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[g,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[g,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[g,W,{"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],[d,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[d,A+" 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],[d,g],[/(cobalt)\/([\w\.]+)/i],[d,[g,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,G]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,G]]],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],[c,[h,N],[u,v]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[c,[h,N],[u,f]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[c,[h,E],[u,f]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[c,[h,E],[u,v]],[/(macintosh);/i],[c,[h,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[c,[h,L],[u,f]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[c,[h,R],[u,v]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[c,[h,R],[u,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],[[c,/_/g," "],[h,F],[u,f]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[c,/_/g," "],[h,F],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[c,[h,"OPPO"],[u,f]],[/\b(opd2\d{3}a?) bui/i],[c,[h,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[c,[h,"Vivo"],[u,f]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[c,[h,"Realme"],[u,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],[c,[h,k],[u,f]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[c,[h,k],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[c,[h,M],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[c,[h,M],[u,f]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[c,[h,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[c,/_/g," "],[h,"Nokia"],[u,f]],[/(pixel c)\b/i],[c,[h,P],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[c,[h,P],[u,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],[c,[h,x],[u,f]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[c,"Xperia Tablet"],[h,x],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[c,[h,"OnePlus"],[u,f]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[c,[h,T],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[c,/(.+)/g,"Fire Phone $1"],[h,T],[u,f]],[/(playbook);[-\w\),; ]+(rim)/i],[c,h,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[c,[h,_],[u,f]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[c,[h,b],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[c,[h,b],[u,f]],[/(nexus 9)/i],[c,[h,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[c,/_/g," "],[u,f]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[c,[h,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[c,[h,"Meizu"],[u,f]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[c,[h,"Ulefone"],[u,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],[h,c,[u,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],[h,c,[u,v]],[/(surface duo)/i],[c,[h,D],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[c,[h,"Fairphone"],[u,f]],[/(u304aa)/i],[c,[h,"AT&T"],[u,f]],[/\bsie-(\w*)/i],[c,[h,"Siemens"],[u,f]],[/\b(rct\w+) b/i],[c,[h,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[c,[h,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[c,[h,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[c,[h,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[c,[h,"NuVision"],[u,v]],[/\b(k88) b/i],[c,[h,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[c,[h,"ZTE"],[u,f]],[/\b(gen\d{3}) b.+49h/i],[c,[h,"Swiss"],[u,f]],[/\b(zur\d{3}) b/i],[c,[h,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[c,[h,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],c,[u,v]],[/\b(ns-?\w{0,9}) b/i],[c,[h,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[c,[h,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],c,[u,f]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],c,[u,f]],[/\b(ph-1) /i],[c,[h,"Essential"],[u,f]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[c,[h,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[c,[h,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[c,[h,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[c,[h,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[h,c,[u,f]],[/(kin\.[onetw]{3})/i],[[c,/\./g," "],[h,D],[u,f]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[c,[h,U],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[c,[h,U],[u,f]],[/smart-tv.+(samsung)/i],[h,[u,S]],[/hbbtv.+maple;(\d+)/i],[[c,/^/,"SmartTV"],[h,N],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,M],[u,S]],[/(apple) ?tv/i],[h,[c,E+" TV"],[u,S]],[/crkey/i],[[c,w+"cast"],[h,P],[u,S]],[/droid.+aft(\w+)( bui|\))/i],[c,[h,T],[u,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[c,[h,L],[u,S]],[/(bravia[\w ]+)( bui|\))/i],[c,[h,x],[u,S]],[/(mitv-\w{5}) bui/i],[c,[h,F],[u,S]],[/Hbbtv.*(technisat) (.*);/i],[h,c,[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,q],[c,q],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,c,[u,m]],[/droid.+; (shield) bui/i],[c,[h,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[c,[h,x],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[c,[h,D],[u,m]],[/((pebble))app/i],[h,c,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[c,[h,E],[u,y]],[/droid.+; (glass) \d/i],[c,[h,P],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[c,[h,U],[u,y]],[/(quest( \d| pro)?)/i],[c,[h,B],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,C]],[/(aeobc)\b/i],[c,[h,T],[u,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[c,[u,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[c,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,f]],[/(android[-\w\. ]{0,9});.+buil/i],[c,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[d,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[d,"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],[d,g],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,g],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[g,W,K]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,W,K],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,H],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[g,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,g],[/\(bb(10);/i],[g,[d,_]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[g,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[g,[d,A+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[g,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[g,[d,w+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,V],g],[/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],[d,g],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],g],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,g]]},Y=function(e,t){if(typeof e===a&&(t=e,e=n),!(this instanceof Y))return new Y(e,t).getResult();var m=typeof i!==s&&i.navigator?i.navigator:n,S=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:n,C=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(J,t):J,T=m&&m.userAgent==S;return this.getBrowser=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.browser),e[l]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[g]),T&&m&&m.brave&&typeof m.brave.isBrave==r&&(e[d]="Brave"),e},this.getCPU=function(){var e={};return e[p]=n,z.call(e,S,C.cpu),e},this.getDevice=function(){var e={};return e[h]=n,e[c]=n,e[u]=n,z.call(e,S,C.device),T&&!e[u]&&y&&y.mobile&&(e[u]=f),T&&"Macintosh"==e[c]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[c]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.engine),e},this.getOS=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.os),T&&!e[d]&&y&&y.platform&&"Unknown"!=y.platform&&(e[d]=y.platform.replace(/chrome os/i,V).replace(/macos/i,H)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=typeof e===o&&e.length>500?q(e,500):e,this},this.setUA(S),this};Y.VERSION="1.0.38",Y.BROWSER=$([d,g,l]),Y.CPU=$([p]),Y.DEVICE=$([c,h,u,m,f,S,v,y,C]),Y.ENGINE=Y.OS=$([d,g]),e.exports&&(t=e.exports=Y),t.UAParser=Y;var Q=typeof i!==s&&(i.jQuery||i.Zepto);if(Q&&!Q.ua){var Z=new Y;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:j)}));const pD=[{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"}],mD="0.0",fD="unknown";function vD(e){return/iPhone|iPad|iPod|Android|Mobi/i.test(e)?"Mobile":"Desktop"}let SD=new gD.UAParser;function yD(){return SD||(SD=new gD.UAParser),SD.getResult()}function CD(){const e=yD().ua;return-1!==e.indexOf("Edge")?"edge":-1!==e.indexOf("Electron")?"electron":-1!==e.indexOf("Chrome")?"chrome":-1!==e.indexOf("Firefox")?"firefox":-1!==e.indexOf("Safari")?"safari":-1!==e.indexOf("Mac OS X")?"applewebview":-1!==e.indexOf("Trident")?"ie":"unknown"}function TD(e,t){const i=t.find((({name:t})=>t===e));if(!i)return fD;let n=i.engine;return n=function(e,t){return"ios"===_D()&&(t="Safari"),t}(0,n),n}function ED(){const e=yD();return"WebKit"===e.browser.name&&-1!==e.ua.indexOf("Mac OS X")?e.os.version??mD:void 0!==e.browser.version?e.browser.version:mD}function bD(){const e=yD(),t=e.ua,i=function(e,t){const i=t.find((({key:t})=>e.includes(t)));if(!i)return fD;let n=i.name;return n=function(e,t){return"edge"!==e&&"edgeanaheim"!==e||((t.includes("Edg/")||t.includes("EdgA/")||t.includes("EdgiOS/"))&&(e="edgeanaheim"),t.includes("Edge/")&&(e="edge")),e}(n,yD().ua),n}(e.browser.name,pD);return{name:i,engine:TD(i,pD),version:ED(),formFactor:vD(t)}}function _D(){const e=yD().ua;return/windows phone/i.test(e)?"windowsphone":/windows /i.test(e)?"windows":/macintosh/i.test(e)?"mac":/(ipod|iphone|ipad)/i.test(e)?"ios":function(e){const t=!/like android/i.test(e),i=/android/i.test(e);return t&&i}(e)?"android":/(web|hpw)[o0]s/i.test(e)?"webos":/tizen/i.test(e)?"tizen":/headlesschrome(?:\/([\w\.]+)| )/i.test(e)?"headlesschrome":/linux/i.test(e)?"linux":/CrOS/.test(e)?"chrome":"other"}function ID(){const e=yD();return void 0!==e.os.version?e.os.version:mD}function wD(e){return/^\d+$/.test(e)}function AD(e){let t=vy()?.environments;return!!t.hasOwnProperty(e)}function PD(){let e,t,i=!1;const n=yD(),r=_D(),s=bD().name,a=bD().version,o=AD(r),l=function(e,t){let i=vy()?.environments;return!(!AD(e)||!i[e].hasOwnProperty(t))&&i[e][t].isSupportedOnSdkVersion}(r,s);return l&&function(e,t){e=e.replace(/,/g,".").trim(),t=t.replace(/,/g,".").trim();let i=e.split("."),n=t.split(".");try{if(!i.every(wD)||!n.every(wD))return-2;for(;i.length<n.length;)i.push("0");for(;n.length<i.length;)n.push("0");let e=i.map(Number),t=n.map(Number);for(var r=0;r<e.length;r++)if(e[r]!==t[r]){if(e[r]>t[r])return 1;if(e[r]<t[r])return-1}}catch(e){w.log(`Error in browser check version support: ${e}`)}return 0}(a,function(e,t){let i=vy()?.environments;return i.hasOwnProperty(e)&&i[e].hasOwnProperty(t)?i[e][t].minVersion:mD}(r,s))>=0&&(i=!0),t={platform:n.os.name,browser:n.browser.name,browserVersion:n.browser.version},e={environment:t,isSupportedPlatform:o,isSupportedBrowser:l,isSupportedBrowserVersion:i,isSupportedEnvironment:o&&l&&i},e}class RD{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,i){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild("MediaConstraintsManager"),this._telemetryLogManager=i}async setVideoConstraints(e,t,i,n){const r=this.getTelemetryPayload({video:e}),s=e=>{let r=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,..._b(e)}:void 0;hb({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:{deltaTimeInMs:+new Date-n},featureDetails:{name:"setConstraints",step:e?oE.failure:oE.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...r}},this._telemetryLogManager,this._logger)};try{if(hb({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:"",featureDetails:{name:"setConstraints",step:oE.attempt,stage:t},additionalDetails:{constraints:r}},this._telemetryLogManager,this._logger),!vy().calling.constraints.enabled)throw this._logger.error("Setting call constraints is disabled"),new le({defaultError:ee.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);const n={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},a=this._tsCall.setCallConstraints?.(n);if("mid-call"!==t)a?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),s()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`);const i=new le({defaultError:ee.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e});s(i)}));else try{await a,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),s()}catch(e){throw new le({defaultError:ee.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){const i=new le({defaultError:ee.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw s(i),i}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){const t=vy(),i=t.calling.constraints.maxOutgoingResolution,n=t.calling.constraints.maxOutgoingFrameRate,r=t.calling.constraints.maxOutgoingVideoBitrate,s=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,a=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,o=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(i,"maxOutgoingResolution",s)},frameRate:{max:this._getConstraintValue(n,"maxOutgoingFrameRate",a)},bitrate:{max:this._getConstraintValue(r,"maxOutgoingBitrate",o)}}}}_getConstraintValue(e,t,i){return"number"==typeof i?i<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&i>e&&(this._logger.info(`${t} value ${i} is larger than ${e}, resetting to ${e}`),i=e),i):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([SI,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata("design:type",t)}(0,Object)],RD.prototype,"_logger",void 0);var MD=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},DD=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class kD{constructor(e,t,i,n){this.logger=i.createChild("Lobby"),this._tsCall=e,this._eventEmitter=new T_(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=n,this._lobbySupportedConversationTypes=vy().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=vy().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(0!==e.added.length&&e.added.forEach((e=>{"InLobby"===e.state&&this.addLobbyParticipant(e),e.on("stateChanged",(()=>{"InLobby"===e.state?this.addLobbyParticipant(e):"Connected"===e.state&&this.removeLobbyParticipant(e)}))})),0!==e.removed.length){if(0===this._call.remoteParticipants.length)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on("remoteParticipantsUpdated",this._remoteParticipantUpdatedListener))}on(e,t){if("lobbyParticipantsUpdated"!==e)throw new le({defaultError:ee.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("lobbyParticipantsUpdated"!==e)throw new le({defaultError:ee.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const i=Mf(),n=+new Date;this._sendLobbyAdmitAndRejectUsage("Start admit participant",lE.lobbyAdmit,i,oE.attempt,void 0);try{NS(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(DS(e));const t=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant admitted successfully",lE.lobbyAdmit,i,oE.success,t-n)}catch(e){let t=dE.Unexpected;this._hasExpectedError&&(t=dE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit participant from lobby",e,i,n,lE.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const i=Mf(),n=+new Date;this._sendLobbyAdmitAndRejectUsage("Start reject participant",lE.lobbyReject,i,oE.attempt,void 0);try{NS(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(DS(e));const t=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant rejected successfully",lE.lobbyReject,i,oE.success,t-n)}catch(e){let t=dE.Unexpected;this._hasExpectedError&&(t=dE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to reject participant from lobby",e,i,n,lE.lobbyReject,t)}}async admitAll(e){const t=Mf(),i=+new Date;let n,r=0,s=0;if(!this._isLobbyEnabled)return this.logger.warn("Lobby is not enabled"),{successCount:r,failureCount:s};this._sendLobbyAdmitAndRejectUsage("Start admit all participants",lE.lobbyAdmitAll,t,oE.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:"all"},X.generateCauseId()).then((e=>{if(n=e,e.result){const t=JSON.parse(e.result);r=t.successCount,s=t.failureCount}}));const e=+new Date;if(0!==s)return this._sendLobbyAdmitAndRejectUsage(`${r} participants are admitted successfully, ${s} participants admit failed. TransactionEnd: ${n}`,lE.lobbyAdmitAll,t,oE.success,e-i),{successCount:r,failureCount:s};this._sendLobbyAdmitAndRejectUsage("All participants are admitted successfully",lE.lobbyAdmitAll,t,oE.success,e-i)}catch(e){let n=dE.Unexpected;this._hasExpectedError&&(n=dE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit all participants from lobby",e,t,i,lE.lobbyAdmitAll,n)}return{successCount:r,failureCount:s}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn("Lobby is not enabled"),[])}getInLobbyParticipants(e){e.forEach((e=>{if("InLobby"===e.state){const t=DS(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(0===this._participants.size)return;const e=Array.from(this._participants.values());this._participants.clear(),this.logger.info("All participants are removed from lobby"),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:e})}removeLobbyParticipant(e){const t=DS(e.identifier);this._participants.has(t)&&(this.logger.info(`${B(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:[e]}))}addLobbyParticipant(e){const t=DS(e.identifier);this._participants.has(t)||(this.logger.info(`${B(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[e],removed:[]}))}validateLobbyOperation(e){const t=this._tsCall.conversationType?this._tsCall.conversationType:"oneToOneCall";if(this.logger.info("Current conversation type is: ",t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new le({defaultError:ee.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>DS(t.identifier)===DS(e)));if(t&&"Connected"===t.state)throw this._hasExpectedError=!0,new le({defaultError:ee.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[B(e).kind]});if(t&&"InLobby"!==t.state||!t)throw this._hasExpectedError=!0,new le({defaultError:ee.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[B(e).kind]})}if(this._call.role!==yS.Presenter&&this._call.role!==yS.Organizer&&this._call.role!==yS.Coorganizer)throw this._hasExpectedError=!0,new le({defaultError:ee.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,i,n,r,s){const a=+new Date,o=function(e,t,i){const n=void 0===t?.code?500:t?._code,r=t?.subCode||t?._subCode||0;return new le({defaultError:{message:i+", reason: "+(t?.phrase||t?.message||"unknown error"),code:n,subCode:r,resultCategories:t?.resultCategories||[]}})}(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(o.message,r,i,oE.failure,a-n,s,t),o}_sendLobbyAdmitAndRejectUsage(e,t,i,n,r,s,a){n===oE.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:aE.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:i,kindOfEvent:n,operation:t,isExpected:s??"",timestampInfo:r?{deltaTimeInMs:r}:"",additionalDetails:a?{failureReason:a.message,code:a.code,subCode:a.subCode,..._b(a)}:""})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send lobby admit and reject telemetry")}}}function OD(){const e=window.navigator.mediaDevices;if(e?.isRemote){const t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return"connected";if(!1===t)return"disconnected"}return""}function ND(e){const t=window.navigator.mediaDevices,i={isMMREnabled:t?.isRemote??!1,isVdi3Enabled:e};return i.isMMREnabled&&(t?.mmrClientVersion&&(i.mmrClientVersion=t.mmrClientVersion),t?.mmrExtensionVersion&&(i.mmrExtensionVersion=t.mmrExtensionVersion),t?.mmrHostVersion&&(i.mmrHostVersion=t.mmrHostVersion),t?.activityId&&(i.mmrActivityId=t.activityId),t?.connectionId&&(i.mmrConnectionId=t.connectionId),i.mmrRdpState=OD()),i}MD([SI,DD("design:type",Object)],kD.prototype,"logger",void 0),MD([pe(JS.LobbyAdmitParticipant),DD("design:type",Function),DD("design:paramtypes",[Object,Object]),DD("design:returntype",Promise)],kD.prototype,"admit",null),MD([pe(JS.LobbyRejectParticipant),DD("design:type",Function),DD("design:paramtypes",[Object,Object]),DD("design:returntype",Promise)],kD.prototype,"reject",null),MD([pe(JS.LobbyAdmitAll),DD("design:type",Function),DD("design:paramtypes",[Object]),DD("design:returntype",Promise)],kD.prototype,"admitAll",null);class LD{constructor(e){this._lastState="",this._callback=e=>{const t=e?.detail?.state??"";t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit("stateChange",t),this._lastState=t):this._logger.info("connection state is unknown")},this._logger=e.createChild("MmrRdpConnectionManager"),this._eventEmitter=new OE.EventEmitter;const t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("listener registered"))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return OD()}dispose(){const e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("event listener unregistered")),this._eventEmitter.removeAllListeners()}}var xD=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class FD extends rw{constructor(e,t,i,n,r,s,a){super(e,t,i,r,s,"RemoteVideoStream"),this._remoteParticipantIdentifier=a,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit("isAvailableChanged",this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};const o=()=>{if("Video"===this.mediaStreamType&&i.isHandlingLargeMeetingVideoRendering){for(const e of i.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&DS(e.identifier)===DS(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else this.setIsAvailable(this.tsStream.isAvailable)};this._streamChangedHandler=this.tsStream.changed((()=>{o()})),o()}on(e,t){if("isAvailableChanged"!==e&&"sizeChanged"!==e&&"isReceivingChanged"!==e)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("isAvailableChanged"!==e&&"sizeChanged"!==e&&"isReceivingChanged"!==e)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){const e=Mf(),t=+new Date,i={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:_E.getMediaStream,mediaType:this.getMediaType(),streamType:bE.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:oE.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(i);try{if(!this.tsStream.getRawStream)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});const i=this.tsStream.getRawStream(),n=new Promise((async(e,t)=>{const n=setTimeout((()=>{r.dispose(),t(new le({defaultError:ee.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),vy().rendering.remoteVideo.getMediaStreamTimeout),r=i.changed((()=>{s()})),s=async()=>{try{const t=await i.getMediaStream();if(!t)return void this.logger.warn("MediaStream is not yet ready.");clearTimeout(n),r.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||"unknown"}`)}};s()})),r=await n,s=r.getVideoTracks()[0];if(!s)throw new le({defaultError:ee.REMOTE_VIDEO_STREAM.GET_TRACK});const a=new Promise(((e,t)=>{const i=()=>{s.removeEventListener("unmute",i,!1),e()};s.addEventListener("unmute",i,!1),s.muted?setTimeout((()=>{s.removeEventListener("unmute",i,!1),t(new le({defaultError:ee.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),vy().rendering.remoteVideo.getMediaStreamTimeout):i()}));await a;const o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:_E.getMediaStream,mediaType:this.getMediaType(),streamType:bE.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),r}catch(i){const n={correlationId:e,operation:_E.getMediaStream,mediaType:this.getMediaType(),streamType:bE.Remote,additionalDetails:{failureReason:i?.message||"",code:i.code||ne,..._b(i),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:oE.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(n),new le({defaultError:ee.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:i})}}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((e=>e.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?EE.ScreenSharingRaw:EE.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:aE.acs_calling_media_stream,tenant:xv,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||"",kindOfEvent:e.kindOfEvent||"",mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||"",callId:e.callId||""}})}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([pe(sy.GetMediaStream),xD("design:type",Function),xD("design:paramtypes",[]),xD("design:returntype",Promise)],FD.prototype,"getMediaStream",null);const UD="#242424",BD="#424242",VD="#616161",HD="#bdbdbd",$D="#e0e0e0",jD="#e6e6e6",GD="#ebebeb",qD="#f0f0f0",zD="#f5f5f5",WD="#fafafa",KD="rgba(255, 255, 255, 0.4)",JD="rgba(255, 255, 255, 0.5)",YD="rgba(0, 0, 0, 0.05)",QD="rgba(0, 0, 0, 0.1)",ZD="#ffffff",XD={shade50:"#200205",shade40:"#3b0509",shade30:"#6e0811",shade20:"#960b18",shade10:"#b10e1c",primary:"#c50f1f",tint10:"#cc2635",tint20:"#d33f4c",tint30:"#dc626d",tint40:"#eeacb2",tint50:"#f6d1d5",tint60:"#fdf3f4"},ek={shade50:"#031403",shade40:"#052505",shade30:"#094509",shade20:"#0c5e0c",shade10:"#0e700e",primary:"#107c10",tint10:"#218c21",tint20:"#359b35",tint30:"#54b054",tint40:"#9fd89f",tint50:"#c9eac9",tint60:"#f1faf1"},tk={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:ek,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"}},ik={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:XD,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"}},nk={cranberry:XD,green:ek,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"}},rk={success:"green",warning:"orange",danger:"cranberry"},sk=["red","green","darkOrange","yellow","berry","lightGreen","marigold"].reduce(((e,t)=>{const i=t.slice(0,1).toUpperCase()+t.slice(1),n={[`colorPalette${i}Background1`]:tk[t].tint60,[`colorPalette${i}Background2`]:tk[t].tint40,[`colorPalette${i}Background3`]:tk[t].primary,[`colorPalette${i}Foreground1`]:tk[t].shade10,[`colorPalette${i}Foreground2`]:tk[t].shade30,[`colorPalette${i}Foreground3`]:tk[t].primary,[`colorPalette${i}BorderActive`]:tk[t].primary,[`colorPalette${i}Border1`]:tk[t].tint40,[`colorPalette${i}Border2`]:tk[t].primary};return Object.assign(e,n)}),{});sk.colorPaletteYellowForeground1=tk.yellow.shade30,sk.colorPaletteRedForegroundInverted=tk.red.tint20,sk.colorPaletteGreenForegroundInverted=tk.green.tint20,sk.colorPaletteYellowForegroundInverted=tk.yellow.tint40;const ak=["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"].reduce(((e,t)=>{const i=t.slice(0,1).toUpperCase()+t.slice(1),n={[`colorPalette${i}Background2`]:ik[t].tint40,[`colorPalette${i}Foreground2`]:ik[t].shade30,[`colorPalette${i}BorderActive`]:ik[t].primary};return Object.assign(e,n)}),{}),ok={...sk,...ak},lk=Object.entries(rk).reduce(((e,[t,i])=>{const n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorStatus${n}Background1`]:nk[i].tint60,[`colorStatus${n}Background2`]:nk[i].tint40,[`colorStatus${n}Background3`]:nk[i].primary,[`colorStatus${n}Foreground1`]:nk[i].shade10,[`colorStatus${n}Foreground2`]:nk[i].shade30,[`colorStatus${n}Foreground3`]:nk[i].primary,[`colorStatus${n}ForegroundInverted`]:nk[i].tint30,[`colorStatus${n}BorderActive`]:nk[i].primary,[`colorStatus${n}Border1`]:nk[i].tint40,[`colorStatus${n}Border2`]:nk[i].primary};return Object.assign(e,r)}),{});lk.colorStatusDangerBackground3Hover=nk[rk.danger].shade10,lk.colorStatusDangerBackground3Pressed=nk[rk.danger].shade20,lk.colorStatusWarningForeground1=nk[rk.warning].shade20,lk.colorStatusWarningForeground3=nk[rk.warning].shade20,lk.colorStatusWarningBorder2=nk[rk.warning].shade20;const ck={borderRadiusNone:"0",borderRadiusSmall:"2px",borderRadiusMedium:"4px",borderRadiusLarge:"6px",borderRadiusXLarge:"8px",borderRadiusCircular:"10000px"},dk={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)"},uk={durationUltraFast:"50ms",durationFaster:"100ms",durationFast:"150ms",durationNormal:"200ms",durationGentle:"250ms",durationSlow:"300ms",durationSlower:"400ms",durationUltraSlow:"500ms"},hk={fontSizeBase100:"10px",fontSizeBase200:"12px",fontSizeBase300:"14px",fontSizeBase400:"16px",fontSizeBase500:"20px",fontSizeBase600:"24px",fontSizeHero700:"28px",fontSizeHero800:"32px",fontSizeHero900:"40px",fontSizeHero1000:"68px"},gk={lineHeightBase100:"14px",lineHeightBase200:"16px",lineHeightBase300:"20px",lineHeightBase400:"22px",lineHeightBase500:"28px",lineHeightBase600:"32px",lineHeightHero700:"36px",lineHeightHero800:"40px",lineHeightHero900:"52px",lineHeightHero1000:"92px"},pk={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},mk={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"},fk="10px",vk="12px",Sk="16px",yk="20px",Ck="24px",Tk="32px",Ek={spacingHorizontalNone:"0",spacingHorizontalXXS:"2px",spacingHorizontalXS:"4px",spacingHorizontalSNudge:"6px",spacingHorizontalS:"8px",spacingHorizontalMNudge:fk,spacingHorizontalM:vk,spacingHorizontalL:Sk,spacingHorizontalXL:yk,spacingHorizontalXXL:Ck,spacingHorizontalXXXL:Tk},bk={spacingVerticalNone:"0",spacingVerticalXXS:"2px",spacingVerticalXS:"4px",spacingVerticalSNudge:"6px",spacingVerticalS:"8px",spacingVerticalMNudge:fk,spacingVerticalM:vk,spacingVerticalL:Sk,spacingVerticalXL:yk,spacingVerticalXXL:Ck,spacingVerticalXXXL:Tk},_k={strokeWidthThin:"1px",strokeWidthThick:"2px",strokeWidthThicker:"3px",strokeWidthThickest:"4px"};function Ik(e,t,i=""){return{[`shadow2${i}`]:`0 0 2px ${e}, 0 1px 2px ${t}`,[`shadow4${i}`]:`0 0 2px ${e}, 0 2px 4px ${t}`,[`shadow8${i}`]:`0 0 2px ${e}, 0 4px 8px ${t}`,[`shadow16${i}`]:`0 0 2px ${e}, 0 8px 16px ${t}`,[`shadow28${i}`]:`0 0 8px ${e}, 0 14px 28px ${t}`,[`shadow64${i}`]:`0 0 8px ${e}, 0 32px 64px ${t}`}}const wk=(()=>{const e=(e=>({colorNeutralForeground1:UD,colorNeutralForeground1Hover:UD,colorNeutralForeground1Pressed:UD,colorNeutralForeground1Selected:UD,colorNeutralForeground2:BD,colorNeutralForeground2Hover:UD,colorNeutralForeground2Pressed:UD,colorNeutralForeground2Selected:UD,colorNeutralForeground2BrandHover:e[80],colorNeutralForeground2BrandPressed:e[70],colorNeutralForeground2BrandSelected:e[80],colorNeutralForeground3:VD,colorNeutralForeground3Hover:BD,colorNeutralForeground3Pressed:BD,colorNeutralForeground3Selected:BD,colorNeutralForeground3BrandHover:e[80],colorNeutralForeground3BrandPressed:e[70],colorNeutralForeground3BrandSelected:e[80],colorNeutralForeground4:"#707070",colorNeutralForegroundDisabled:HD,colorNeutralForegroundInvertedDisabled:KD,colorBrandForegroundLink:e[70],colorBrandForegroundLinkHover:e[60],colorBrandForegroundLinkPressed:e[40],colorBrandForegroundLinkSelected:e[70],colorNeutralForeground2Link:BD,colorNeutralForeground2LinkHover:UD,colorNeutralForeground2LinkPressed:UD,colorNeutralForeground2LinkSelected:UD,colorCompoundBrandForeground1:e[80],colorCompoundBrandForeground1Hover:e[70],colorCompoundBrandForeground1Pressed:e[60],colorBrandForeground1:e[80],colorBrandForeground2:e[70],colorBrandForeground2Hover:e[60],colorBrandForeground2Pressed:e[30],colorNeutralForeground1Static:UD,colorNeutralForegroundStaticInverted:ZD,colorNeutralForegroundInverted:ZD,colorNeutralForegroundInvertedHover:ZD,colorNeutralForegroundInvertedPressed:ZD,colorNeutralForegroundInvertedSelected:ZD,colorNeutralForegroundInverted2:ZD,colorNeutralForegroundOnBrand:ZD,colorNeutralForegroundInvertedLink:ZD,colorNeutralForegroundInvertedLinkHover:ZD,colorNeutralForegroundInvertedLinkPressed:ZD,colorNeutralForegroundInvertedLinkSelected:ZD,colorBrandForegroundInverted:e[100],colorBrandForegroundInvertedHover:e[110],colorBrandForegroundInvertedPressed:e[100],colorBrandForegroundOnLight:e[80],colorBrandForegroundOnLightHover:e[70],colorBrandForegroundOnLightPressed:e[50],colorBrandForegroundOnLightSelected:e[60],colorNeutralBackground1:ZD,colorNeutralBackground1Hover:zD,colorNeutralBackground1Pressed:$D,colorNeutralBackground1Selected:GD,colorNeutralBackground2:WD,colorNeutralBackground2Hover:qD,colorNeutralBackground2Pressed:"#dbdbdb",colorNeutralBackground2Selected:jD,colorNeutralBackground3:zD,colorNeutralBackground3Hover:GD,colorNeutralBackground3Pressed:"#d6d6d6",colorNeutralBackground3Selected:$D,colorNeutralBackground4:qD,colorNeutralBackground4Hover:WD,colorNeutralBackground4Pressed:zD,colorNeutralBackground4Selected:ZD,colorNeutralBackground5:GD,colorNeutralBackground5Hover:zD,colorNeutralBackground5Pressed:qD,colorNeutralBackground5Selected:WD,colorNeutralBackground6:jD,colorNeutralBackgroundInverted:"#292929",colorNeutralBackgroundStatic:"#333333",colorNeutralBackgroundAlpha:JD,colorNeutralBackgroundAlpha2:"rgba(255, 255, 255, 0.8)",colorSubtleBackground:"transparent",colorSubtleBackgroundHover:zD,colorSubtleBackgroundPressed:$D,colorSubtleBackgroundSelected:GD,colorSubtleBackgroundLightAlphaHover:"rgba(255, 255, 255, 0.7)",colorSubtleBackgroundLightAlphaPressed:JD,colorSubtleBackgroundLightAlphaSelected:"transparent",colorSubtleBackgroundInverted:"transparent",colorSubtleBackgroundInvertedHover:QD,colorSubtleBackgroundInvertedPressed:"rgba(0, 0, 0, 0.3)",colorSubtleBackgroundInvertedSelected:"rgba(0, 0, 0, 0.2)",colorTransparentBackground:"transparent",colorTransparentBackgroundHover:"transparent",colorTransparentBackgroundPressed:"transparent",colorTransparentBackgroundSelected:"transparent",colorNeutralBackgroundDisabled:qD,colorNeutralBackgroundInvertedDisabled:"rgba(255, 255, 255, 0.1)",colorNeutralStencil1:jD,colorNeutralStencil2:WD,colorNeutralStencil1Alpha:QD,colorNeutralStencil2Alpha:YD,colorBackgroundOverlay:"rgba(0, 0, 0, 0.4)",colorScrollbarOverlay:"rgba(0, 0, 0, 0.5)",colorBrandBackground:e[80],colorBrandBackgroundHover:e[70],colorBrandBackgroundPressed:e[40],colorBrandBackgroundSelected:e[60],colorCompoundBrandBackground:e[80],colorCompoundBrandBackgroundHover:e[70],colorCompoundBrandBackgroundPressed:e[60],colorBrandBackgroundStatic:e[80],colorBrandBackground2:e[160],colorBrandBackground2Hover:e[150],colorBrandBackground2Pressed:e[130],colorBrandBackground3Static:e[60],colorBrandBackground4Static:e[40],colorBrandBackgroundInverted:ZD,colorBrandBackgroundInvertedHover:e[160],colorBrandBackgroundInvertedPressed:e[140],colorBrandBackgroundInvertedSelected:e[150],colorNeutralCardBackground:WD,colorNeutralCardBackgroundHover:ZD,colorNeutralCardBackgroundPressed:zD,colorNeutralCardBackgroundSelected:GD,colorNeutralCardBackgroundDisabled:qD,colorNeutralStrokeAccessible:VD,colorNeutralStrokeAccessibleHover:"#575757",colorNeutralStrokeAccessiblePressed:"#4d4d4d",colorNeutralStrokeAccessibleSelected:e[80],colorNeutralStroke1:"#d1d1d1",colorNeutralStroke1Hover:"#c7c7c7",colorNeutralStroke1Pressed:"#b3b3b3",colorNeutralStroke1Selected:HD,colorNeutralStroke2:$D,colorNeutralStroke3:qD,colorNeutralStrokeSubtle:$D,colorNeutralStrokeOnBrand:ZD,colorNeutralStrokeOnBrand2:ZD,colorNeutralStrokeOnBrand2Hover:ZD,colorNeutralStrokeOnBrand2Pressed:ZD,colorNeutralStrokeOnBrand2Selected:ZD,colorBrandStroke1:e[80],colorBrandStroke2:e[140],colorBrandStroke2Hover:e[120],colorBrandStroke2Pressed:e[80],colorBrandStroke2Contrast:e[140],colorCompoundBrandStroke:e[80],colorCompoundBrandStrokeHover:e[70],colorCompoundBrandStrokePressed:e[60],colorNeutralStrokeDisabled:$D,colorNeutralStrokeInvertedDisabled:KD,colorTransparentStroke:"transparent",colorTransparentStrokeInteractive:"transparent",colorTransparentStrokeDisabled:"transparent",colorNeutralStrokeAlpha:YD,colorNeutralStrokeAlpha2:"rgba(255, 255, 255, 0.2)",colorStrokeFocus1:ZD,colorStrokeFocus2:"#000000",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)"}))({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"});return{...ck,...hk,...gk,...mk,...pk,..._k,...Ek,...bk,...uk,...dk,...e,...ok,...lk,...Ik(e.colorNeutralShadowAmbient,e.colorNeutralShadowKey),...Ik(e.colorBrandShadowAmbient,e.colorBrandShadowKey,"Brand")}})();let Ak=1;class Pk{constructor(e,t,i,n,r){this._container=e,this._videoStream=t,this._viewId=i,this._streamTelemetryEventSender=r,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:wk.fontFamilyBase,fontWeight:"bold",stroke:"black",strokeOpacity:"0.1",fill:wk.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=(e=>{const t=qS(90-e),i=1/Math.cos(qS(e)),n=1/Math.cos(t),r=Math.tan(t);return(e,t)=>e<r*t?e*i:t*n})(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(e,t,i,n)=>({width:e*(i+1.1),height:t*(n+1.1)}),this._call=this._videoStream.call,this._logger=n.createChild("WatermarkOverlayProvider"+Ak++);const s=this._call.getMeetingCapabilitiesInternal();if(!s){this._logger.warn("No watermark capabilities found. Likely not received from service.");const e=new le({defaultError:ee.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),t=Mf();return void this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_E.watermark,kindOfEvent:oE.failure,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{failureReason:e.message,code:e.code,..._b(e),watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}this._watermarkCapability=s.waterMarkCapability;const a=this._call.deviceManager.getOSNameInternal();this._isApple="ios"===a||"mac"===a,this._resizeObserver=new ResizeObserver((e=>{for(const t of e)if(t.contentRect?.width>1){const e=t.contentRect.width,i=t.contentRect.height;this._updateWatermarkScalingValues(e,i)}})),this._resizeObserver.observe(this._container)}attach(){const e=Mf(),t=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,e),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on("isReceivingChanged",this._watermarkIsReceivingSub)}catch(i){const n=new le({defaultError:ee.VIEW.WATERMARK_ATTACH_FAIL,originalError:i});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:e,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-t},operation:_E.watermark,kindOfEvent:oE.failure,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{failureReason:n.message,code:n.code,..._b(n),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),n}}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(e,t){"Single"===this._getSelectedWatermarkPattern()?this._updateWatermarkUseTextScalingSingle(e,t):"Tiled"===this._getSelectedWatermarkPattern()&&this._updateWatermarkPatternScalingTiled(e,t)}_generateWatermark(e,t){const i=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 n;if("Video"===e&&this._watermarkCapability.enabledForVideo)n=this._watermarkCapability.videoSettings;else{if("ScreenSharing"!==e||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);n=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:i},operation:_E.watermark,kindOfEvent:oE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!n||!n.opacity||!n.pattern||"number"!=typeof n.opacity||"string"!=typeof n.pattern)throw this._logger.debug("Unexpected watermark settings"),new le({defaultError:ee.VIEW.WATERMARK_UNEXPECTED_VALUES});const r=this._getClampedUsername();let s;if("Single"===n.pattern)s=this._generateSinglePatternWatermark(r,n);else{if("Tiled"!==n.pattern)throw this._logger.debug("Unexpected watermark pattern setting"),new le({defaultError:ee.VIEW.WATERMARK_UNEXPECTED_VALUES});s=this._generateTiledPatternWatermark(r,n)}this._svgContainerHidden=s.outerHTML,this._container.appendChild(s),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:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_E.watermark,kindOfEvent:oE.event,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged("watermarkAudioOnlyFallbackTriggeredChanged",this._audioOnlyCallback),this._mutationObserver=new MutationObserver((e=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug("watermark mutation detected, falling back to audio only!"),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_E.watermark,kindOfEvent:oE.event,mediaType:this._videoStream.mediaStreamType,streamType:bE.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:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-i},operation:_E.watermark,kindOfEvent:oE.success,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(e){const n=new le({defaultError:ee.VIEW.WATERMARK_ATTACH_FAIL,originalError:e});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-i},operation:_E.watermark,kindOfEvent:oE.failure,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,additionalDetails:{failureReason:n.message,code:n.code,..._b(n),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),n}}_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(e,t){for(const[i,n]of Object.entries(t))e.style[`${i}`]=n}_generateSinglePatternWatermark(e,t){const i=this._getWatermarkContainer(t);this._svgContainer=i;const n=t.opacity/this.RANGE_MAX,r=n/this.SHADOW_OPACITY_RATIO,s=Mf(),a=`url(#${s})`,o=document.createElementNS("http://www.w3.org/2000/svg","defs"),l=this._getSvgFilter(s,r),c=document.createElementNS("http://www.w3.org/2000/svg","text");c.id=Mf(),this._addStyleAttributesToSvgElement(c,this.WATERMARK_TEXT_COMMON_STYLES),c.setAttribute("filter",a),c.setAttribute("text-anchor","middle"),c.setAttribute("dominant-baseline","middle"),c.setAttribute("fill-opacity",`${n}`),c.style.transform="rotate(-30deg)";const d=document.createTextNode(e);c.appendChild(d),this._svgTextDefElement=c,o.appendChild(l),o.appendChild(c);const u=document.createElementNS("http://www.w3.org/2000/svg","use");return u.id=Mf(),this._svgWatermarkUseTagSinglePattern=u,u.setAttribute("href",`#${this._svgTextDefElement.id}`),u.setAttribute("x","50%"),u.setAttribute("y","50%"),u.setAttribute("width","100%"),u.setAttribute("height","100%"),u.setAttribute("font-size",`${this._svgWatermarkUseTextScale}`),u.setAttribute("stroke-width",`${this._svgWatermarkUseTextBorderSize}`),i.appendChild(o),i.appendChild(u),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),i}_updateWatermarkUseTextScalingSingle(e,t){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){const i=this._computeTextDiagonal(e,t);return this._svgWatermarkUseTextScale=this.SPACE_USE*i*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(e,t){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){const i=((e,t)=>{const i=document.documentElement.clientWidth/document.documentElement.clientHeight,n=Math.max(i,1),r=1/n,s=.001*Math.min(e,t)*n;return{scaledFontSize:24*Math.max(.75,s)*r,scaledBorderSize:1*Math.max(1,s)*r,scaledHorizontalGap:.5*Math.max(.5,Math.min(1,s)),scaledVerticalGap:Math.max(11.5*Math.min(1,s),4.5*n)}})(e,t,this._isApple);this._svgTextTiledScaledSize=i.scaledFontSize,this._svgTextTiledScaledStrokeWidth=i.scaledBorderSize,this._svgTextDefElement.setAttribute("font-size",`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute("stroke-width",`${this._svgTextTiledScaledStrokeWidth}`);const n=this._svgTextDefElement.getBoundingClientRect().width,r=this._svgTextDefElement.getBoundingClientRect().height,{width:s,height:a}=this._getScaledPatternDimensions(n,r,i.scaledHorizontalGap,i.scaledVerticalGap),o=.5*s,l=.5*a;return this._svgFirstPatternWidth=s,this._svgFirstPatternHeight=a,this._svgSecondPatternWidth=s,this._svgSecondPatternHeight=a,this._svgSecondPatternOffsetX=o,this._svgSecondPatternOffsetY=l,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(e,t){const i=this._getWatermarkContainer(t);this._svgContainer=i;const n=t.opacity/this.RANGE_MAX,r=n/this.SHADOW_OPACITY_RATIO,s=Mf(),a=Mf(),o=Mf(),l=`url(#${s})`,c=document.createElementNS("http://www.w3.org/2000/svg","defs"),d=this._getSvgFilter(s,r),u=document.createElementNS("http://www.w3.org/2000/svg","text");this._svgTextDefElement=u,u.id=Mf(),this._addStyleAttributesToSvgElement(u,this.WATERMARK_TEXT_COMMON_STYLES),u.setAttribute("filter",l),u.setAttribute("dominant-baseline","hanging"),u.setAttribute("fill-opacity",`${n}`),u.setAttribute("font-size",`${this._svgTextTiledScaledSize}`),u.setAttribute("stroke-width",`${this._svgTextTiledScaledStrokeWidth}`);const h=document.createTextNode(e);u.appendChild(h);const g=document.createElementNS("http://www.w3.org/2000/svg","pattern");this._svgFirstPattern=g,g.id=a,g.setAttribute("patternUnits","userSpaceOnUse"),g.setAttribute("patternTransform","rotate(-30)"),g.setAttribute("width",`${this._svgFirstPatternWidth}`),g.setAttribute("height",`${this._svgFirstPatternHeight}`);const p=document.createElementNS("http://www.w3.org/2000/svg","use");p.setAttribute("href",`#${this._svgTextDefElement.id}`),g.appendChild(p);const m=document.createElementNS("http://www.w3.org/2000/svg","pattern");this._svgSecondPattern=m,m.id=o,m.setAttribute("patternUnits","userSpaceOnUse"),m.setAttribute("patternTransform","rotate(-30)"),m.setAttribute("width",`${this._svgSecondPatternWidth}`),m.setAttribute("height",`${this._svgSecondPatternHeight}`),m.setAttribute("x",`${this._svgSecondPatternOffsetX}`),m.setAttribute("y",`${this._svgSecondPatternOffsetY}`);const f=p.cloneNode(!0);m.appendChild(f),c.appendChild(d),c.appendChild(u),c.appendChild(g),c.appendChild(m);const v=this._getRect(0,0,100,100,a),S=this._getRect(0,0,100,100,o);return i.appendChild(c),i.appendChild(v),i.appendChild(S),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),i}_getWatermarkContainer(e){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");return this._addStyleAttributesToSvgElement(t,this.WATERMARK_CONTAINER_STYLES),t.setAttribute("xmlns","http://www.w3.org/2000/svg"),t}_getSvgFilter(e,t){const i=document.createElementNS("http://www.w3.org/2000/svg","filter");i.id=e;const n=document.createElementNS("http://www.w3.org/2000/svg","feDropShadow");return n.setAttribute("dx","0.5"),n.setAttribute("dy","0.5"),n.setAttribute("stdDeviation","1"),n.setAttribute("flood-color","black"),n.setAttribute("flood-opacity",`${t}`),i.appendChild(n),i}_getRect(e,t,i,n,r){const s=document.createElementNS("http://www.w3.org/2000/svg","rect");return s.setAttribute("x",`${e}%`),s.setAttribute("y",`${t}%`),s.setAttribute("width",`${i}%`),s.setAttribute("height",`${n}%`),s.setAttribute("fill",`url(#${r})`),s}_getClampedUsername(){let e="";const t=this._call.callAgent,i=vy().calling.watermark,n=i.watermarkMaxUsernameLength,r=i.watermarkEmptyDisplayNamePlaceholder;if(t?.isCteUser()){let i=t.getUserProperties()?.sipUri;i&&"string"==typeof i&&(e=i.replace("sip:",""))}else e=t?.displayName??"",e||(e=r);return function(e,t){const i=e.match(/^(.+)@([^@]+)$/),n=i?.[2],r=3===i?.length?i[1]:e,s=r.length>t?`${r.substring(0,t)}***`:r;return n?`${s}@${n}`:s}(e,n)}_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(e=""){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:e,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 Rk=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},Mk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let Dk=1;class kk{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 isDisposed(){return this._disposed}get retryErrorEvents(){return this._retryErrorEvents}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,i,n,r,s,a){this._target=e,this._viewId=t,this._videoStream=i,this._onDisposedCallback=r,this._createViewSteps=s,this._eventEmitter=new OE.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=(e=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),e&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),e?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=e=>{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(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){const e=this._tsRenderer.streamSize?.height||0,t=this._tsRenderer.streamSize?.width||0;e===this._size.height&&t===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 e={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(function(e,t){const i=Object.keys(e);for(let n of i)if(e[n]!==t[n])return!1;return!0}(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;const t=this._videoStream.getStreamMetadata(),{callId:i,localParticipantId:n,isDisposed:r,viewIdsRegistered:s,height:a,width:o,...l}=t,c={...e,...l,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:sE.remote_view,callId:i,localParticipantId:n,data:c})}catch(e){}},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(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new le({defaultError:ee.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=n.createChild("RemoteStreamRenderer"+Dk++),this.logger.log("created"),void 0!==a?.scalingMode&&(this._scalingMode=a.scalingMode),void 0!==a?.isMirrored&&(this._isMirrored=a.isMirrored),this._remoteStreamTelemetryEventSender=new II(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new Pk(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach(),this._retryErrorEvents=new Set([ee.VIEW.TIMEOUT.subCode,ee.VIEW.SUBSCRIBE.subCode])}async start(){const e=Mf(),t=+new Date,i=this.logger.createFnLogger(ay.Start),n={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:_E.render,kindOfEvent:oE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n),this._disposed)throw this.logger.warn("already disposed"),new le({defaultError:ee.VIEW.START_ALREADY_DISPOSED});this._createViewTimeout&&(clearTimeout(this._createViewTimeout),this._createViewTimeout=void 0);try{i.info(`scalingMode=${Ty(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=jT(),this._renderingDeferred.promise.catch(My),"RemoteVideoStream"===this._videoStream.kind&&(this._availableCallback=()=>{this._videoStream.isAvailable||(i.warn("stream isAvailable changed to false, attempting to reject operation"),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new le({defaultError:ee.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:Ty(this._scalingMode),transparent:!1}).then((e=>{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=e,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 le({defaultError:ee.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),-1!==vy().rendering.remoteVideo.createViewTimeout&&(this._createViewTimeout=setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new le({defaultError:ee.VIEW.TIMEOUT})),this._createViewTimeout&&(clearTimeout(this._createViewTimeout),this._createViewTimeout=void 0)}catch(e){}}),vy().rendering.remoteVideo.createViewTimeout)),vy().rendering.remoteVideo.speedupCreateViewWithPlayEvent){const e=this._target&&this._target.children.length>0&&this._target.children[0];e?e.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(i))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((e=>{if(this.logger.info("Failed to subscribe to video"),this._renderingDeferred?.isPending()){const t=new le({defaultError:ee.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),vy().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();const n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_E.render,kindOfEvent:oE.success,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n),this}catch(i){this.logger.warn(`Failed to render, message=${i}`);try{this._retryErrorEvents.has(i?.subCode)||this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}const n=new le({defaultError:ee.VIEW.START,originalError:i});if(n.message!==ee.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&n.message!==ee.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const i={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_E.render,additionalDetails:{failureReason:n.message,code:ie,..._b(n)},kindOfEvent:oE.failure,mediaType:this._videoStream.mediaStreamType,streamType:bE.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(i)}throw n}}videoPlayEventListener(){this.logger.log("video element play event was fired"),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||0,this._size.height=this._tsRenderer?.streamSize.height||0,this._videoStream.updateSize()}catch(e){this.logger.error(`Failed to update video stream size with error ${e}`)}}async setScalingMode(e){if(!this._tsRenderer)throw new le({defaultError:ee.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(Ty(e)),this._scalingMode=e}_clearTimeouts(){this._checkIfVideoWasAttachedToDomTimeout&&(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),this._checkIfVideoWasAttachedToDomTimeout=void 0),this._createViewTimeout&&(clearTimeout(this._createViewTimeout),this._createViewTimeout=void 0)}dispose(e=AE.Public_App){if(this._disposed)throw new le({defaultError:ee.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case AE.Internal_LargeMeetingVideoRendering:t=ee.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case AE.Internal_RemoteVideoStreamDisposed:t=ee.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=ee.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new le({defaultError:t}))}if(this._target){const e=this._target.children&&this._target.children.length>0&&this._target.children[0];e&&e.removeEventListener("play",this.videoPlayEventListener),this._target.remove()}try{e!==AE.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.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,this._clearTimeouts()}_checkIfVideoWasAttachedToDom(){if(this._checkIfVideoWasAttachedToDomTimeout&&(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),this._checkIfVideoWasAttachedToDomTimeout=void 0),vy().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=vy().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries;const t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&(this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>t()),vy().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime)))};t()}else this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),vy().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}}Rk([SI,Mk("design:type",Object)],kk.prototype,"logger",void 0),Rk([pe(ay.Start),Mk("design:type",Function),Mk("design:paramtypes",[]),Mk("design:returntype",Promise)],kk.prototype,"start",null),Rk([ge(ay.Dispose),Mk("design:type",Function),Mk("design:paramtypes",[String]),Mk("design:returntype",void 0)],kk.prototype,"dispose",null);var Ok=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},Nk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Lk{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get isDisposed(){return this._disposed}constructor(e,t,i,n,r){this._target=e,this._videoStream=t,this._onDisposed=n,this._eventEmitter=new OE.EventEmitter,this._isRendering=!1,this._scalingMode="Stretch",this._isMirrored=!0,this._disposed=!1,this.logger=i.createChild("LocalStreamRenderer"),this.logger.log("created"),void 0!==r?.scalingMode&&(this._scalingMode=r.scalingMode),void 0!==r?.isMirrored?this._isMirrored=r.isMirrored:"ScreenSharing"===this._videoStream.mediaStreamType&&(this._isMirrored=!1),this._localStreamTelemetryEventSender=new II(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){const e=Mf(),t=this.logger.createFnLogger(ay.Start),i=+new Date,n={timestampInfo:{attemptTimestamp:i},correlationId:e,operation:_E.render,kindOfEvent:oE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:bE.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n);try{if(t.info("attempting to select new device as a source"),this._videoStream.source instanceof vI&&"Video"===this._videoStream.mediaStreamType){const e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info("device selected"),t.info("creating preview"),this._tsRenderer=await e.createPreview(this._target,{kind:"camera"},{scalingMode:Ty(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if("RawMedia"!==this._videoStream.mediaStreamType&&"ScreenSharing"!==this._videoStream.mediaStreamType)throw new le({defaultError:ee.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;const e=await this._videoStream.getMediaStream(),t=new MediaStream(e.getVideoTracks());this._rawMediaOrSS_previewVideo.srcObject=t,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 n={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:e,operation:_E.render,kindOfEvent:oE.success,mediaType:this._videoStream.mediaStreamType,streamType:bE.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),this}catch(n){this.dispose();const t=Eb(0,n),r={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:e,operation:_E.render,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)},kindOfEvent:oE.failure,mediaType:this._videoStream.mediaStreamType,streamType:bE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),t}}setScalingMode(e){if(this._tsRenderer)this._tsRenderer.setScalingMode(Ty(e)),this._scalingMode=e;else{if(!this._rawMediaOrSS_previewVideo)throw new le({defaultError:ee.VIEW.SCALING_MODE});switch(e){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(e){this.disposeScreenSharingMediaStream();const t=this._target.querySelector("video");t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log("disposing underlying local renderer"),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new le({defaultError:ee.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 e=this._target.querySelector("video"),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info("disposed of ScreenSharing MediaStream"))}}}Ok([SI,Nk("design:type",Object)],Lk.prototype,"logger",void 0),Ok([pe(oy.Start),Nk("design:type",Function),Nk("design:paramtypes",[]),Nk("design:returntype",Promise)],Lk.prototype,"start",null),Ok([ge(oy.SetScalingMode),Nk("design:type",Function),Nk("design:paramtypes",[String]),Nk("design:returntype",void 0)],Lk.prototype,"setScalingMode",null),Ok([ge(oy.SetSourceObject),Nk("design:type",Function),Nk("design:paramtypes",[MediaStream]),Nk("design:returntype",void 0)],Lk.prototype,"setSourceObject",null),Ok([ge(oy.Dispose),Nk("design:type",Function),Nk("design:paramtypes",[]),Nk("design:returntype",void 0)],Lk.prototype,"dispose",null);var xk=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},Fk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let Uk=1;class Bk{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,i,n,r){if(this._videoStream=e,this._viewId=i,this._options=r,this._disposed=!1,this._isRetryErrorSubCode=e=>"retryErrorEvents"in this._streamRenderer&&this._streamRenderer.retryErrorEvents.has(e.subCode),this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let i=e.call.activeRemoteVideoStreamViews?.get(e.id);i?.delete(t),0==i?.size&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild("VideoStreamRendererView"+Uk++),this.target=document.createElement("div"),this.target.style.width="100%",this.target.style.height="100%",this._videoStream instanceof rw)this._streamRenderer=new kk(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),n,this._options);else{if(!(this._videoStream instanceof UI))throw new le({defaultError:ee.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new Lk(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info("created")}async render(){const e=this.logger.createFnLogger(this._videoStream instanceof rw?ey.RenderRemoteStream:ey.RenderLocalStream);if(this._disposed)throw e.log("failed, stream disposed!"),new le({defaultError:ee.VIEW.RENDER_FAIL_STREAM_DISPOSED});const t=vy().rendering.remoteVideo.maxRendererRetries;let i=1;const n=(e,t)=>e().catch((r=>{if(t>0&&this._isRetryErrorSubCode(r))return i+=1,n(e,t-1);throw this._streamRenderer.isDisposed||this._streamRenderer.dispose(),r})),r=()=>this._streamRenderer.start();try{await n(r,t-1)}catch(t){throw e.error(`Failed to render stream ${this._viewId} after ${i} retries.`),this._isRetryErrorSubCode(t)&&i>1&&(t.message+=`\nFailed to render stream ${this._viewId} after ${i} retries.`),t}return i}async updateScalingMode(e){if(this._disposed)throw new le({defaultError:ee.VIEW.SCALING_MODE_DISPOSED});if("Crop"!==e&&"Fit"!==e&&"Stretch"!==e)throw new le({defaultError:ee.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new le({defaultError:ee.VIEW.SCALING_MODE,originalError:e})}}dispose(e=AE.Public_App){if(this._disposed)throw new le({defaultError:ee.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;const t=+new Date,i=Mf();try{e===AE.Public_App&&this.sendDisposeViewEvent({eventName:aE.acs_calling_dispose_view_attempt,correlationId:i,timestampInfo:{attemptTimestamp:t}}),this._videoStream instanceof FD&&this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),this.logger.debug("attempt to dispose stream renderer"),this._streamRenderer.dispose(e),this.target?.remove();const n=+new Date;e===AE.Public_App&&this.sendDisposeViewEvent({eventName:aE.acs_calling_dispose_view_success,correlationId:i,timestampInfo:{deltaTimeInMs:n-t}})}catch(n){const r=new le({defaultError:ee.VIEW.DISPOSE_FAIL,originalError:n});if(e===AE.Public_App){const e=+new Date;this.sendDisposeViewEvent({eventName:aE.acs_calling_dispose_view_failure,correlationId:i,timestampInfo:{deltaTimeInMS:e-t}},r)}throw r}}sendDisposeViewEvent(e,t){try{let i,n;t&&(i="string"==typeof t?.message?t?.message:"",n={..._b(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:i,additionalDetails:n}})}catch(e){this.logger.debug("Unable to send telemtery")}}}xk([SI,Fk("design:type",Object)],Bk.prototype,"logger",void 0),xk([pe(ey.Render),Fk("design:type",Function),Fk("design:paramtypes",[]),Fk("design:returntype",Promise)],Bk.prototype,"render",null),xk([pe(ey.UpdateScalingMode),Fk("design:type",Function),Fk("design:paramtypes",[String]),Fk("design:returntype",Promise)],Bk.prototype,"updateScalingMode",null),xk([ge(ey.Dispose),Fk("design:type",Function),Fk("design:paramtypes",[String]),Fk("design:returntype",void 0)],Bk.prototype,"dispose",null);class Vk{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,i,n,r){this._statsCollector=e,this._streamId=t,this._logger=i,this._call=n,this._attemptTimestamp=r,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on("sampleReported",(e=>{!function(e,t,i,n){const r=vy()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength,s=vy()?.rendering.remoteVideo.createViewSendMediaStatsInitialMaxLength,a=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","healedRatio","lossRate"],o=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","frameRateDecoded","frameRateReceived","frameWidthReceived","frameHeightReceived","longestFreezeDurationInMs","totalFreezeDurationInMs","framesReceived","framesDropped","framesDecoded","keyFramesDecoded"],l=o;if(i.audio.receive.length>0){const n=i.audio.receive[0];e.audio=e.audio??{},t.audio=t.audio??{},a.forEach((i=>{const a=i;if(void 0!==n[a]&&e.audio){const t=n[a];if(void 0===e.audio[a])e.audio[a]=[t];else{const i=e.audio[a]?.length;i>=r&&e.audio[a]?.shift(),e.audio[a]?.push(t)}}if(void 0!==n[a]&&t.audio){const e=n[a];if(void 0===t.audio[a])t.audio[a]=[e];else{const i=t.audio[a]?.length;i<s&&t.audio[a]?.push(e)}}}))}if(i.video.receive.length>0){const a=i.video.receive.find((e=>e.streamId===n));void 0!==a&&(e.video=e.video??{},t.video=t.video??{},o.forEach((i=>{const n=i;if(void 0!==a[n]&&e.video){const t=a[n];if(void 0===e.video[n])e.video[n]=[t];else{const i=e.video[n]?.length;i>=r&&e.video[n]?.shift(),e.video[n]?.push(t)}}if(void 0!==a[n]&&t.video){const e=a[n];if(void 0===t.video[n])t.video[n]=[e];else{const i=t.video[n]?.length;i<s&&t.video[n]?.push(e)}}})))}if(i.screenShare.receive.length>0){const a=i.screenShare.receive.find((e=>e.streamId===n));void 0!==a&&(e.screenShare=e.screenShare??{},t.screenShare=t.screenShare??{},l.forEach((i=>{const n=i;if(void 0!==a[n]&&e.screenShare){const t=a[n];if(void 0===e.screenShare[n])e.screenShare[n]=[t];else{const i=e.screenShare[n]?.length;i>=r&&e.screenShare[n]?.shift(),e.screenShare[n]?.push(t)}}if(void 0!==a[n]&&t.screenShare){const e=a[n];if(void 0===t.screenShare[n])t.screenShare[n]=[e];else{const i=t.screenShare[n]?.length;i<s&&t.screenShare[n]?.push(e)}}})))}}(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;void 0!==this.createViewStats.video?.framesDropped&&void 0!==this.initialCreateViewStats.video?.framesDropped&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let i=NaN;void 0!==this.createViewStats.video?.framesReceived&&void 0!==this.initialCreateViewStats.video?.framesReceived&&(e=this.createViewStats.video.framesReceived.length,i=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0]);let n=NaN;void 0!==this.createViewStats.video?.framesDecoded&&void 0!==this.initialCreateViewStats.video?.framesDecoded&&(e=this.createViewStats.video.framesDecoded.length,n=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let r=NaN;void 0!==this.createViewStats.video?.keyFramesDecoded&&void 0!==this.initialCreateViewStats.video?.keyFramesDecoded&&(e=this.createViewStats.video.keyFramesDecoded.length,r=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let s=0;!isNaN(t)&&i>0&&(s=Number((t/i*100).toFixed(7)));let a=!1;i>0&&0===n&&(a=!0);let o=!1;!isNaN(n)&&!isNaN(r)&&n>0&&n===r&&(o=!0);const l=[],c=this._call.networkQualityUfdEventDetails,d=vy().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;c.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=d&&l.push(e)}));const u=0===i;this._createViewFailureStats.video={framesDroppedPercentage:s,framesReceivedButNothingDecoded:a,onlyKeyFramesDecoded:o,networkQualityEventsDuringAttempt:l,zeroFramesReceived:u}}catch(e){this._logger.debug("Error calculating create view failure stats!")}return this._createViewFailureStats}}class Hk{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};const i=vy()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on("sampleReported",(e=>{(function(e,t,i,n){const r=t[i.toString()];void 0!==r&&["audioBitrate","videoBitrate","downloadBitrate","bufferLengthInMs","videoHeight","videoWidth","currentPlayPosition"].forEach((t=>{const i=t,s=t;if(void 0!==r[i]){const t=r[i];if(void 0===e[s])e[s]=[t];else{const i=e[s]?.length;i>=n&&e[s]?.shift(),e[s]?.push(t)}}}))})(this._liveStreamStats,e,this._streamId,i),Z.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}}var $k=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},jk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Gk{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(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||"Failed to dispose, unknown error")}},this._addActiveRemoteVideoStreamView=(e,t,i)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n&&n.set(t,i)}else{let n=new Map;n.set(t,i),e.call.activeRemoteVideoStreamViews?.set(e.id,n)}},!(e instanceof UI||e instanceof rw||e instanceof FD))throw new le({defaultError:ee.VIEW.RENDERER_WRONG_STREAM_TYPE});const t=R("ACS");this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new _I(t,e instanceof UI?[()=>`VideoStreamRenderer:LocalVideoStream:${Q.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info("created")}async createView(e){if(this.disposed)throw new le({defaultError:ee.VIEW.RENDERER_DISPOSED});const t={},i=+new Date,n=Mf(),r=Mf();let s,a;try{let o=1;if(t.attemptTimestamp=i,this.sendCreateViewEvent({eventName:aE.acs_calling_create_view_attempt,viewId:n,correlationId:r,timestampInfo:{attemptTimestamp:i},isMirrored:e?.isMirrored,scalingMode:e?.scalingMode,stepsInfo:t}),"RemoteVideoStream"===this._videoStream.kind&&!this._videoStream.isAvailable)throw new le({defaultError:ee.VIEW.ISAVAILABLE_FALSE});if("RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&vy()?.calling.applyViewLimit&&Sy()?.numVideoChannelsGvc){const e=Sy().numVideoChannelsGvc,t=this._videoStream;if(!t.call.activeRemoteVideoStreamViews?.has(t.id)&&t.call.activeRemoteVideoStreamViews?.size>=e)throw new le({defaultError:ee.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]})}if(vy()?.rendering.remoteVideo.createViewSendMediaStats)if("RemoteVideoStream"===this._videoStream.kind||"ComposedVideoStream"===this._videoStream.kind){const e=this._videoStream,t=e.call;a=e.call.feature(oD.MediaStats).createCollector();const n=e.id;this._createViewTelemetryHelper=new Vk(a,n,this.logger,t,i)}else if("LiveVideoStream"===this._videoStream.kind){const e=this._videoStream;a=e.call.feature(oD.LiveStream).createStatsCollector();const t=e.id;this._createViewLiveStreamTelemetryHelper=new Hk(a,t)}s=new Bk(this._videoStream,this.logger,n,t,e),this.views.set(n,s),o=await s.render(),"RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&this._addActiveRemoteVideoStreamView(this._videoStream,n,s);const l=+new Date;return this.sendCreateViewEvent({eventName:aE.acs_calling_create_view_success,viewId:n,correlationId:r,timestampInfo:{deltaTimeInMs:l-i},additionalProperties:{isRetry:!!o&&o>1,attemptNumber:o},stepsInfo:t}),s}catch(e){const a=new le({defaultError:ee.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(n),this._attemptToDisposeView(s),a.message!==ee.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&a.message!==ee.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const e=Date.now();this.sendCreateViewEvent({eventName:aE.acs_calling_create_view_failure,viewId:n,correlationId:r,timestampInfo:{deltaTimeInMs:e-i},stepsInfo:t},a)}throw a}finally{a?.dispose()}}async sendCreateViewEvent(e,t){try{let i={},n={},r={};if(vy()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===aE.acs_calling_create_view_failure||e.eventName===aE.acs_calling_create_view_success)){if("RemoteVideoStream"===this._videoStream.kind){const t=this._videoStream.call,n=await(t.tsCall.getMediaSessionStatsAsync?.());i={isRetry:e.additionalProperties?.isRetry??!1,attemptNumber:e.additionalProperties?.attemptNumber??1,videoSubscriptionEvents:n?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:n?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:n?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:n?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:n?.metrics?.IceConnectedStateTime,relayCandidate:n?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:n?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:n?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:t.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:t.activeRemoteVideoStreamViews?.size||0}}e.eventName===aE.acs_calling_create_view_failure&&(r=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},n=this._createViewStats)}i.visibilityState=document.visibilityState,void 0!==e.isMirrored&&(i.isMirrored=e.isMirrored),void 0!==e.scalingMode&&(i.scalingMode=e.scalingMode),e.eventName!==aE.acs_calling_create_view_failure&&e.eventName!==aE.acs_calling_create_view_success||"RemoteVideoStream"!==this._videoStream.kind&&"ComposedVideoStream"!==this._videoStream.kind||Z.forOwn(e.stepsInfo,((e,t)=>{void 0!==e&&(i[t]=e)}));let s="",a={};t&&(s="string"==typeof t?.message?t?.message:"",a={..._b(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:s,additionalProperties:i,additionalDetails:a,stats:n,createViewFailureDebugStats:r,videoStreamKind:this._videoStream.kind}})}catch(e){this.logger.debug("Unable to send telemtery")}}dispose(){if(this.disposed)throw new le({defaultError:ee.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}}$k([SI,jk("design:type",Object)],Gk.prototype,"logger",void 0),$k([pe(ty.CreateView),jk("design:type",Function),jk("design:paramtypes",[Object]),jk("design:returntype",Promise)],Gk.prototype,"createView",null),$k([ge(ty.Dispose),jk("design:type",Function),jk("design:paramtypes",[]),jk("design:returntype",void 0)],Gk.prototype,"dispose",null);var qk=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},zk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Wk{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId,deviceType:e.deviceType,clientEndpointCapabilities:e.clientEndpointCapabilities,endpointMetadata:e.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(e,t,i,n,r){this._mappedStreams=new Map,this._state="Idle",this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName="",this._role="Unknown",this.acsToTsStreamType=e=>"Video"===e?0:"ScreenSharing"===e?1:void 0,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=r,this._eventEmitter=new T_(this.logger),this._callAgent=n,this._call=i,this.logger.log("created"),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if("stateChanged"!==e&&"isMutedChanged"!==e&&"isSpeakingChanged"!==e&&"displayNameChanged"!==e&&"roleChanged"!==e&&"videoStreamsUpdated"!==e)throw new le({defaultError:ee.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("stateChanged"!==e&&"isMutedChanged"!==e&&"isSpeakingChanged"!==e&&"displayNameChanged"!==e&&"roleChanged"!==e&&"videoStreamsUpdated"!==e)throw new le({defaultError:ee.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){const e=vy();if(!e.calling.enableMuteOthers)throw new le({defaultError:ee.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===uy.TwoParty)throw new le({defaultError:ee.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(!["Connected","Hold"].some((e=>e===this._state)))throw new le({defaultError:ee.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});const t=this.logger.createFnLogger(YS.Mute),i=+new Date,n=Mf();if(this.sendAudioEvent({eventName:aE.acs_calling_mute_attempt,eventType:cE.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:i},correlationId:n,step:"mid-call"}),!e.calling.allowMutePstnRemoteParticipant&&"phoneNumber"===this._identifier.kind){const e=+new Date,r=ee.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;t.warn(r.message);const s=new le({defaultError:r});throw this.sendAudioEvent({eventName:aE.acs_calling_mute_failure,eventType:cE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-i},correlationId:n,step:"mid-call"},s),s}try{t.info("remote mute specific"),void 0!==this._tsParticipant?await this._call.tsCall.muteParticipants(1,[this._tsParticipant]):t.warn("no participant to mute in attempt to mute specific remote participant"),t.info("remote mute specific success");const e=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_mute_success,eventType:cE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-i},correlationId:n,step:"mid-call"})}catch(e){const r=new le({defaultError:ee.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:e});t.error(r.message);const s=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_mute_failure,eventType:cE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:s-i},correlationId:n,step:"mid-call"},r),r}}_dispose(){this.logger.log("dispose"),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.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(e){this._callEndReason=e}observeParticipant(e){this._tsParticipant||(this._tsParticipant=e,this._displayName=e.displayName,this._isMuted=e.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=e.displayName,this._eventEmitter.emit("displayNameChanged")),this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){const e=0!==this._tsParticipant.voiceLevel;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit("isSpeakingChanged"))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!U(this._identifier)&&!F(this._identifier)||this.getRemoteParticipantProperties().then((e=>{e?.displayName&&(this._displayName=e.displayName,this._eventEmitter.emit("displayNameChanged"))})).catch((e=>{this.logger.error(`Failed to get remote participant properties: ${e}`)})))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,"Disconnected"==this._state?this._dispose():this._eventEmitter.emit("stateChanged",this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return"function"==typeof e?this._updateRenderingState(e,"Video",t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,i){if("function"==typeof e){let n;const r="Video"===t?0:1;this._tsParticipant&&(n=i?.stream?i.stream:new FD(this._tsParticipant.streams[r][0],this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier),n.on("isReceivingChanged",(()=>{this._renderers[t].renderingState.isFrozen=!n.isReceiving,e(this._renderers[t].renderingState)})),n.on("isAvailableChanged",(async()=>{this._renderers[t].renderingState.isStreaming!==n?.isAvailable&&(this._renderers[t].renderingState.isStreaming=n.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new Gk(n),this._renderers[t].view||(this._renderers[t].view=await(this._renderers[t].renderer?.createView(i?.viewOptions))),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return"function"==typeof e?this._updateRenderingState(e,"ScreenSharing",t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,i){if(this._tsParticipant){const n=0===t?"Video":"ScreenSharing",r=i?.stream?i.stream:new FD(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier);return r.isAvailable&&(this._renderers[n].view=await this._appendVideo(e,t,r,i?.viewOptions)),r.on("isAvailableChanged",(async()=>{r.isAvailable?this._renderers[n].view=await this._appendVideo(e,t,r,i?.viewOptions):this._renderers[n]?.view&&this._renderers[n].view?.target&&this._renderers[n].view?.target.parentNode?.removeChild(this._renderers[n].view?.target)})),Promise.resolve({stream:r,view:this._renderers[n]?.view})}return Promise.reject()}async _appendVideo(e,t,i,n){try{const r=0===t?"Video":"ScreenSharing";if(0===t&&(this._renderers[r]?.renderer||(this._renderers[r].renderer=this._renderers[r]?.renderer?this._renderers[r].renderer:new Gk(i),this._renderers[r].view=await(this._renderers[r].renderer?.createView(n))),this._renderers[r].view))return e.appendChild(this._renderers[r].view?.target||document.createElement("emptyNode")),Promise.resolve(this._renderers[r].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){const t=0===e?"Video":"ScreenSharing";this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=Fy(vy(),e);"Unknown"===t?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit("roleChanged"))}_mapTsParticipantState(e){let t;const i={0:"Idle",1:"Connecting",2:"Ringing",3:"Connected",4:"Disconnected",5:"Hold",7:"InLobby",6:"EarlyMedia"};i[e]?(t=i[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){const e=[],t=[],i=i=>{if(this._tsParticipant)if(this._tsParticipant.streams&&HS(this._tsParticipant.streams[i])){let n=[];this._tsParticipant&&(n=this._tsParticipant.streams[i]),n.forEach((t=>{if(!this._mappedStreams.get(t.id)){const i=new FD(t,this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${i.mediaStreamType} id=${t.id}`),e.push(i)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===i&&(n.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===i&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach((e=>{this._mappedStreams.set(e.id,e)})),t.forEach((e=>{const t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())})),this._eventEmitter.emit("videoStreamsUpdated",{added:e,removed:t}))}sendAudioEvent(e,t){try{let i,n;t&&(i=t.message,n=_b(t));const r={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:i||"",additionalDetails:{...n}};void 0!==e.eventType&&(r.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:r})}catch(e){this.logger.debug("Unable to send mute others audio telemetry")}}getRemoteParticipantProperties(){return new Promise((e=>{const t={policyUrlSuffix:vy().MiddleTier.policyUrlSuffixV2,userPolicies:["TeamsMeetingPolicy"],userProperties:["displayName"]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,DS(this.identifier),t,this._callAgent.getUserMri()).then((t=>{e(t.userAggregatedPolicySettingData?.userProperties)}))}))}}qk([SI,zk("design:type",Object)],Wk.prototype,"logger",void 0),qk([pe(YS.Mute),zk("design:type",Function),zk("design:paramtypes",[]),zk("design:returntype",Promise)],Wk.prototype,"mute",null);class Kk{constructor(e){this._deviceManager=e,this._eventEmitter=new OE.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;const t=e=>()=>{const t=this._selectedDevices.get(e),i=(()=>"Speaker"===e?this._deviceManager.selectedSpeaker:"Microphone"===e?this._deviceManager.selectedMicrophone:void 0)(),n=void 0===i?void 0:{id:this._deviceInfoMapper.getDeviceId(i.id),name:this._deviceInfoMapper.scrubDeviceLabel(i.name)};this._selectedDevices.set(e,n),this._eventEmitter.emit("selectedDeviceChanged",{selectedDeviceType:e,oldDevice:t,newDevice:n})},i=t("Speaker");this._selectedDeviceListeners.set("Speaker",i),this._deviceManager.on("selectedSpeakerChanged",i),i();const n=t("Microphone");this._selectedDeviceListeners.set("Microphone",n),this._deviceManager.on("selectedMicrophoneChanged",n),n()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){const e=this._selectedDeviceListeners.get("Speaker");e&&this._deviceManager.off("selectedSpeakerChanged",e);const t=this._selectedDeviceListeners.get("Microphone");t&&this._deviceManager.off("selectedMicrophoneChanged",t),this._eventEmitter.removeAllListeners()}}function Jk(e,t,i,n){const r=n===SS.RoomCall||e.kind===ue.Call&&"Incoming"==e.direction&&!e.tsCall.groupId&&!!e.tsCall.meetingData?.meetingCode&&!e.tsCall.threadId,s=!r&&n===SS.TeamsMeetingLink||n===SS.TeamsMeetingId||n===SS.TeamsCoordinates||"Incoming"==e.direction&&!e.tsCall.groupId&&!!e.tsCall.meetingData&&!!e.tsCall.threadId,a={audio:"",video:""},o=e.localAudioStreams?.[0];o&&(a.audio=o.getEffectsCurrentStateRecord()??"");const l=e.localVideoStreams?.[0];return l&&(a.video=l.getEffectsCurrentStateRecord()??""),{timestampInfo:{attemptTimestamp:+new Date},correlationId:i,localParticipantId:e.tsCall.participantId||"",isAcsTeamsCall:e.isAcsTeamsCall,callId:e.tsCall.callId||"",callType:e.tsCall.callType||"",callDirection:e.direction,state:"Ringing"===e.state?"Ringing":Sb[e.tsCall.state],groupJoin:!!e.tsCall.groupId,roomJoin:r,meetingJoin:s,callEndDiagnosticsInfo:e.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:t?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:a,hostRegion:e.tsCall.region||"",diagnosticInfo:{...e.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:mE.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:mE.telemetryPayloadBytesCompressed}}}function Yk(e,t,i){try{"state-changed"===i.step&&"Connecting"===i.newState&&(mE.telemetryPayloadBytesOriginal=0,mE.telemetryPayloadBytesCompressed=0),e.sendEvent({name:aE.acs_calling_call_progress,tenant:xv,properties:i})}catch(e){t.error(`Failed to send event: ${aE.acs_calling_call_progress} step: ${i.step}`)}}var Qk=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Zk{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 dy.CallQueue;if("unknown"!==this.transferorKind){if("transfer"===this._tsCall.incomingCallType)return dy.TransferToParticipant;if("replaces"===this._tsCall.incomingCallType)return dy.TransferToCall}return"Incoming"===this.direction?"AcceptCall":"Outgoing"===this.direction&&"Rooms"==this.context?dy.JoinRoom:"Outgoing"===this.direction&&"TeamsMeeting"==this.context?dy.JoinTeamMeeting:"Outgoing"===this.direction&&"GroupIdCall"==this.context?dy.JoinWithGroupId:dy.PlaceCall}get context(){return 1==this._tsCall.callType||this._currentCallContext==uy.TwoParty?uy.TwoParty:this._tsCall.groupId?uy.GroupIdCall:"groupCall"==this._tsCall.conversationType||this._currentCallContext==uy.MultiParty?uy.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith("994")||this._tsCall.meetingData?.meetingCode?.startsWith("995")||this._tsCall.meetingData?.meetingCode?.startsWith("996")?uy.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||"scheduledMeeting"==this._tsCall.conversationType?uy.TeamsMeeting:(this._tsCall.callType,uy.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?kS(this._tsCall.transferorMri||"").kind:""}get direction(){return this._config?.isIncoming?zS.Incoming:zS.Outgoing}get initiatorKind(){return kS(this._tsCall.callerMri?this._tsCall.callerMri:"").kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?"TeamsMeetingJoinLink":this._tsCall.transferorMri?"Transferee":1===this._tsCall.participants.length?kS(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>kS(e.id).kind)).toString()}constructor(e,t={}){this._tsCall=e,this._threadId=this._tsCall.threadId;const i=this._tsCall.groupId;this._groupId=!i||i.startsWith("19:")||i.startsWith("99:")?void 0:i,this._roomId=t?.config?.roomId,this._config=t.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(e){this._threadId=e}initialize(e,t,i){this._logger=t,this._eventEmitter=e,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 e=JSON.parse(await this._tsCall.getJoinBlob()),t=e?.conversationUrl;if(!t)throw new le({defaultError:ee.CALL.GET_SERVER_CALL_ID});return function(e){let t=btoa(e).replace(/=/g,"");t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_");for(const e of t)if(e.match(/[^A-Za-z0-9-_]/))throw new le({defaultError:ee.CALL.SERVER_CALL_ID});return t}(t)}p2pCallHandler(){null==this._currentCallContext&&1==this._tsCall.callType&&(this._currentCallContext=uy.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==uy.TwoParty&&Uy(this._tsCall)>2&&(this._currentCallContext=uy.MultiParty,this._eventEmitter.emit("callInfoChanged"),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(const e of this._tsCall.participants)if("microsoftTeamsUser"===kS(e.id).kind)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(const e of this._tsCall.participants)if("phoneNumber"===kS(e.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(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit("threadIdChanged"))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}onCallInfoChanged(e,t){this._eventEmitter.on(e,t)}offCallInfoChanged(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([pe(QS.GetServerCallId),Qk("design:type",Function),Qk("design:paramtypes",[]),Qk("design:returntype",Promise)],Zk.prototype,"getServerCallId",null);class Xk{constructor(e,t,i,n,r){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=vy().calling.explicitConsentFeatureEnabled.enabled,this.initialize(e,t,i,n,r)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,Xk.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let e=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: "+e),e}async consent(e){if(this._isExplicitConsentEnabled){if(e.context===uy.TwoParty)throw this._logger.warn("Consent for recording is not supported for 1:1 calls"),new le({defaultError:ee.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new le({defaultError:ee.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{const e={level:"user",type:"consentToRecording",content:"{}"};if(!await this._tsCall.publishState(e,X.generateCauseId()))throw this._logger.error("Consent failure to set publish state for user"),new le({defaultError:ee.CALL.FAILED_TO_SET_CONSENT});this._logger.log("ExplicitConsentCallStateManager: Consent for the call provided successfully")}catch(e){throw this._logger.error("Consent failure to set publish state for user on service side"),e}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let e=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: "+e),e}offConsentRestrictionChanged(e,t){if("consentRestrictionChanged"!==e)throw new Error("ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event");this._logger.log("ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event"),this._eventEmitter.off(e,t)}onConsentRestrictionChanged(e,t){if("consentRestrictionChanged"!==e)throw new Error("ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event");this._logger.log("ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event"),this._eventEmitter.on(e,t)}handleConsentCapabilitiesChanges(){this._eventEmitter.emit("consentRestrictionChanged"),this.areCoreCapabilitiesConsentRestricted()&&(!this._call.isMuted&&this._tsCall.mute().catch((e=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic",e)})),this._call.isLocalVideoStarted&&this._tsCall.stopVideo().catch((e=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video",e)})),this._call.isScreenSharingOn&&this._tsCall.stopScreenSharing().catch((e=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screen sharing",e)})),this._logger.log("ExplicitConsentCallStateManager: Handle Capabilities changes: Core capabilities are turned off"))}initialize(e,t,i,n,r){this._isExplicitConsentEnabled&&(this._isInitialized||(this._logger=r.createChild((()=>`Explicit Consent::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._callAgent=i,this._eventEmitter=n,this._call=t,e.changed((()=>{if(!0===e.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;const t=!0===e.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;t!==this._consentActivelyRequired&&(this._consentActivelyRequired=t,this.handleConsentCapabilitiesChanges())}})),e.on("publishedStatesChanged",(async e=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(e)})),this._isInitialized=!0))}_handleConsentStateChange(e){if(!0!==this._localParticipantConsentPublishState){const i=this._callAgent.getUserMri();var t=!1;e&&this._getPublishedState(e).forEach((e=>{e.participantStates.forEach((e=>{if(e.id===i)return this._logger.log("ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent"),void(t=!0)}))})),this._localParticipantConsentPublishState=t,t&&this._eventEmitter.emit("consentRestrictionChanged")}}_getPublishedState(e){return e.typeStates.filter((e=>["consentToRecording"].includes(e.type)))}}Xk.instance=null;var eO,tO=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},iO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class nO{constructor(e){this._lastRecovered=new Date,this._shouldNotifyError=!0,this._shouldNotifyRecovery=!0,this._interval=0,this._interval=e}updateLastRecoveredTime(e){this._lastRecovered=new Date(e.getTime()+this._interval),this._shouldNotifyError=!0,this._shouldNotifyRecovery=!1}shouldNotifyError(e){const t=this._lastRecovered<e&&this._shouldNotifyError;return t&&(this._shouldNotifyError=!1,this._shouldNotifyRecovery=!0),t}shouldNotifyRecovery(e){const t=this._shouldNotifyRecovery;return t&&this.updateLastRecoveredTime(e),t}}class rO{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===uy.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===uy.TwoParty||this._allowIPVideo}get isCteTeamsCall(){return this._isCteTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{const e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(0===this._remoteAudioStreams.length){if(!await e.getMediaStream())throw new le({defaultError:ee.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new hD(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[]});else{const e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[e]})}}catch(e){throw new le({defaultError:ee.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(My)})),t().catch((()=>{this.logger.info("Failed to update remote audio stream collection, retrying on changed")}))}catch(e){this.logger.info("Failed to get raw audio stream from the stack")}}get remoteAudioStreams(){if(!vy().calling.allowAccessRawMediaStream)throw new le({defaultError:ee.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(e){this._watermarkAudioOnlyFallbackTriggered=e,this._eventEmitter.emit("watermarkAudioOnlyFallbackTriggeredChanged")}constructor(e,t,i,n,r,s){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=Mf(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=Mf(),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=sS,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=SS.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._setOrUpdateDeviceEventsTask=Promise.resolve(),this._isAcsTeamsCall=!1,this._isCteTeamsCall=this._callAgent.isCteUser(),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 e=[uy.Rooms,uy.GroupIdCall,uy.MultiParty,uy.TeamsMeeting].some((e=>e===this._callInfo.context)),t=this.tsCall.conversationType||e?!!(this.tsCall.isMuted||10!==this.tsCall.state&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);const e=[];this.tsCall.isMuted&&e.push("isMicrophoneMuted"),this.tsCall.isServerMuted&&(e.push("isServerMuted"),[3,4,5].some((e=>e===this.tsCall.state))&&this._eventEmitter.emit("mutedByOthers"),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.explicitConsentStateImp.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&e.push("isDeviceNotFunctioningMuted");let i="";e.length>=1&&(i=e.join(", ")),t&&(this._isMuted_correlationIdCache=Mf()),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:"isMuted-changed",oldIsMuted:this._isMuted,newIsMuted:t,reason:i}),this._isMuted=t,this._eventEmitter.emit("isMutedChanged")}},this.audioSourceChanged=async e=>{if(this._telemetryLogManager.sendEvent({name:aE.acs_calling_local_audio_source_changed,tenant:xv,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:Mf(),localAudioStream:e.source?.source instanceof MediaStream?"MediaStream":"Device"}}),e.source instanceof BI){this.localAudioStreams[0]&&"RawMedia"===this.localAudioStreams[0].mediaStreamType&&this.stopAudioInternal(!0);const t=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());await(t?.selectDevicesAsync?.({microphone:e.source.id}))}else await this.startAudioInternal(e.source,!0)},this._handleIncomingAudioMuteChanges=()=>{const e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=Mf()),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:"isIncomingAudioMuted-changed",oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:""}),this._isIncomingAudioMuted=e,this._eventEmitter.emit("isIncomingAudioMutedChanged"))},this._id=e.callId,this.tsCall=i,this._direction=e.isIncoming?"Incoming":"Outgoing",this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=n,this.stats=new cD(this.logger,this._telemetryLogManager),this._eventEmitter=new T_(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=r,this._optimalVideoCount=1,this._ufdsCorrelationIdCache={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},81:{0:void 0,1:void 0,2:void 0,3:void 0}},this._callInfo=new Zk(i,{config:e}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._speakingWhileMutedManager=new nO(vy().telemetry.speakingWhileMutedThrottleInterval),vy().calling.mediaMetricsDeviceEventsEnabled&&(async()=>{const e=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());e&&(this._dmDevicesChangedSub=e.on("devicesChanged",(()=>{this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(My)))})))})().catch((e=>{this.logger.error(`Failed to register devicesChanged event: ${e}`)})),this._extensibleApi=new nb(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new Xk(this.tsCall,this,t,this._eventEmitter,this.logger),this._capabilityResolver=new jb(this._eventEmitter,this.logger,this,this._callInfo,t,i),this._lobby=new kD(this.tsCall,this,this.logger,this._telemetryLogManager);const a=lD(YE.CallFeature);for(const e of a)"OnExtendedObjectConstructor"===e.activationOptions.activationEvent&&this.feature(e);this._mmrRdpConnectionManager=new LD(this.logger),vy().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),vy().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new Kk(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new RD(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=s??!1,this.feature(oD.MediaAccess).on("localParticipantMediaAccessChanged",(e=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${(new Date).getTime()}, isAudioPermitted=${e.mediaAccess.isAudioPermitted}, isVideoPermitted=${e.mediaAccess.isVideoPermitted}`),!1===e.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)}))}async accept(e={}){const t=e.audioOptions?.muted??!1,i=this.getLocalVideoStreamFromCallOptions(e),n=this.getLocalAudioStreamFromCallOptions(e),r=+new Date,s=Mf(),a=this._callAgent.getEcsConfigIds(),o=jy(this.tsCall),l=MI(this.tsCall),c={joinContextDescription:"",additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:this.isIPVideoEnabled&&!!i,withAudio:this.isIPAudioEnabled&&n?.mediaStreamType?n?.mediaStreamType:"",...ND(l),AcsCallingSDKWeb_ecsConfigId:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:a.SkypeWebMedia,customContext:{userToUserPresent:!!o?.userToUser,xHeadersPresent:!!o?.xHeaders&&o.xHeaders.length>0}},additionalDetails:{}},d=(e,t,a)=>{const o=+new Date,l={...c};let d;if(t){const{callEndReason:t,callingCommunicationError:i}=Cb(this,e);l.additionalDetails.callEndReason=t,d=i}else d=new le({defaultError:ee.CALL.ACCEPT_INCOMING_CALL,originalError:e}),l.additionalDetails.communicationServicesError=_b(d).communicationServicesError;if(this.sendCallStageEvent({eventName:aE.acs_calling_call_accept_failed,correlationId:s,timestampInfo:{deltaTimeInMs:o-r},additionalPayload:l},d,void 0,a?pI.getRemoveCauseIdToNetworkInfo(a):void 0),i){const e=+new Date;d=new le({defaultError:ee.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(d.message),this.sendVideoEvent({correlationId:s,eventName:aE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:e-r},localVideoStream:i,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn},d),this.removeLocalVideoStream(i)}return n&&this.removeLocalAudioStream(n),d};try{if(e?.videoOptions?.constraints){const t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});c.additionalProperties.constraints=t}this.sendCallStageEvent({eventName:aE.acs_calling_call_accept_attempt,correlationId:s,timestampInfo:{attemptTimestamp:r},additionalPayload:c});const a={...c};if(i&&this.setLocalVideoStream(i),this.setLocalAudioStream(n),i&&this.sendVideoEvent({eventName:aE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:r},correlationId:s,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn}),1!==this.tsCall.state)throw new le({defaultError:ee.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){const t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,"accept",s,r),i=this._mediaConstraintsManager.getTelemetryPayload({video:t});a.additionalProperties.constraints=i}}catch(e){const t=new le({defaultError:ee.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}const o={withVideo:!!i&&this.isIPVideoEnabled,muted:t};if(t&&(o.muteFlags=1),vy()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(o.mediaConfiguration={connectionType:"NoDirectConnection"}),n&&await this.startAudioInternal(n,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),"RawMedia"===i?.mediaStreamType)try{await this._setRawStream(i,1)}catch(e){const t=+new Date,n=new le({defaultError:ee.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:s,eventName:aE.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-r},localVideoStream:i,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn},n),this.removeLocalVideoStream(i)}const l=X.generateCauseId();return pI.setCauseIdToNetworkInfo(l),this.tsCall.accept(o,l).then((async()=>{const e=+new Date;i&&this.shallRemoveLvsAfterConnectedSuccessfully(i,"accept",s,e,r),n&&this.shallRemoveLasAfterConnectedSuccessfully(n,"accept",s,e,r),this.sendCallStageEvent({eventName:aE.acs_calling_call_accept_connected,correlationId:s,timestampInfo:{deltaTimeInMs:e-r},additionalPayload:a},void 0,void 0,pI.getRemoveCauseIdToNetworkInfo(l))})).catch((e=>{d(e,!0,l)})),this}catch(e){throw d(e,!1)}}async reject(){const e=+new Date,t=Mf();this.sendCallStageEvent({eventName:aE.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});const i=this._callAgent.getEcsConfigIds(),n={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:{}};if(1!==this.tsCall.state){const i=new le({defaultError:ee.CALL.REJECT_NOT_RINGING});n.additionalDetails.communicationServicesError=_b(i).communicationServicesError;const r=+new Date;throw this.sendCallStageEvent({eventName:aE.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:r-e},additionalPayload:n},i),i}const r=X.generateCauseId();return pI.setCauseIdToNetworkInfo(r),this.tsCall.reject(r).then((()=>{const i=+new Date;this.sendCallStageEvent({eventName:aE.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:i-e}},void 0,void 0,pI.getRemoveCauseIdToNetworkInfo(r))})).catch((i=>{const s=+new Date,{callEndReason:a,callingCommunicationError:o}=Cb(this,i);throw n.additionalDetails.callEndReason=a,this.sendCallStageEvent({eventName:aE.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:s-e},additionalPayload:n},o,void 0,pI.getRemoveCauseIdToNetworkInfo(r)),o}))}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(e,t=!1){const i=Mf(),n=+new Date,r=X.generateCauseId();pI.setCauseIdToNetworkInfo(r);try{if(this.isInternalApiCallWithoutRawMedia(e,t))return;this.sendRawMediaEvent({eventName:aE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:oE.attempt,isInternal:t,timestampInfo:"",additionalDetails:""}),this.validateRawMedia(e,ee.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=e;const s=await this.createMediaStream(e),a=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());if(!vy()?.calling?.allowAccessRawMediaStream||!a?.setRawMediaStream)throw new le({defaultError:ee.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});a?.setRawMediaStream(s,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);const o=+new Date;this.sendRawMediaEvent({eventName:aE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:oE.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)}})}catch(e){const s=new le({defaultError:ee.CALL.START_AUDIO_STREAM_FAILED,originalError:e});this.logger.error(`Failed to start raw media audio: ${s.message}`);const a=+new Date;throw this.sendRawMediaEvent({eventName:aE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,isInternal:t,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:a-n},additionalDetails:{failureReason:s.message||"",code:s.code,subCode:s.subCode,..._b(s),networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)}}),s}}isInternalApiCallWithoutRawMedia(e,t){return!("RawMedia"===e?.mediaStreamType||!t||(this.logger.info("startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal"),0))}validateRawMedia(e,t){if("RawMedia"!==e?.mediaStreamType)throw new le({defaultError:t})}async createMediaStream(e){let t;try{t=await e.getMediaStream()}catch(e){throw new le({defaultError:ee.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e})}return new MediaStream(t)}stopAudioInternal(e=!1){const t=Mf(),i=+new Date,n=X.generateCauseId();pI.setCauseIdToNetworkInfo(n);try{const r=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(r,e))return;this.sendRawMediaEvent({eventName:aE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.attempt,isInternal:e,timestampInfo:"",additionalDetails:""}),e||dD(JS.StopAudio,this.state),this.validateRawMedia(r,ee.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);const s=this._callAgent.tsStack?.getDeviceManager();if(!vy()?.calling?.allowAccessRawMediaStream||!s?.unsetRawMediaStream)throw new le({defaultError:ee.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});s.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();const a=+new Date;this.sendRawMediaEvent({eventName:aE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:a-i},additionalDetails:{networkInfo:pI.getRemoveCauseIdToNetworkInfo(n)}})}catch(r){const s=new le({defaultError:ee.CALL.STOP_AUDIO_STREAM_FAILED,originalError:r});this.logger.error(`Failed to stop raw media audio: ${s.message}`);const a=+new Date;throw this.sendRawMediaEvent({eventName:aE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:a-i},additionalDetails:{failureReason:s.message||"",code:s.code,subCode:s.subCode,..._b(s),networkInfo:pI.getRemoveCauseIdToNetworkInfo(n)}}),s}}bindTsCall(){const e=[];void 0!==this.tsCall.callerMri&&(this._callerIdentity=kS(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.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=kS(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=kS(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=kS(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),e.push(this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),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&&function(e,t){return null==t.meetingCapability&&null!=e.meetingCapability||null==t.capabilities&&null!=e.capabilities||!(Z.isEqual(t.capabilities,e.capabilities)&&Z.isEqual(t.meetingCapability,e.meetingCapability)&&Z.isEqual(t.recordingConsentDetails,e.recordingConsentDetails))}(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode(),this.optimalVideoCountChanged()}))),e.push(this.tsCall.on("serverMutedChanged",(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()}))),this._totalParticipantCount=Uy(this.tsCall),e.push(this.tsCall.on("participantCountsUpdated",(()=>{const e=Uy(this.tsCall);if(this._totalParticipantCount!==e){const t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),vy().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit("totalParticipantCountChanged");try{this.stats.recordEvent({name:sE.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch(e){this.logger.error("failed to send participant count change telemetry")}}})));const t=(e,t)=>{if(e!==t){this.logger.log(`transportState changed from ${this._transportState} to ${t}`);const i=void 0===this._transportStateTimestamp.get("Connected")?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(t);const n=Z.omitBy({connectedTimetamp:i,transportConnectedTimestamp:this._transportStateTimestamp.get("Connected"),transportDisconnectedTimestamp:this._transportStateTimestamp.get("Disconnected"),transportFailedTimestamp:this._transportStateTimestamp.get("Failed")},Z.isUndefined),r=Z.merge(Jk(this,this._callAgent,Mf(),this._joinContextDescription),{timestampInfo:n});Yk(this._telemetryLogManager,this.logger,{...r,step:"transportState-changed",oldState:e,newState:t}),this._transportStateTimestamp.set(t,Date.now()),this._transportState=t}};e.push(this.tsCall.on("transportConnected",(()=>{t(this._transportState,"Connected")}))),e.push(this.tsCall.on("transportDisconnected",(()=>{t(this._transportState,"Disconnected")}))),e.push(this.tsCall.on("transportFailed",(()=>{t(this._transportState,"Failed")}))),e.push(this.tsCall.on("callQualityChanged",(async e=>{try{let t,i;if(5===e.type||32===e.type||2===e.type||1===e.type||37===e.type?(t=sE.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):44===e.type||43===e.type||9===e.type||25===e.type||45===e.type||33===e.type||34===e.type||55===e.type||26===e.type||47===e.type?t=sE.video_device_issue:27===e.type?(i=!0,t=sE.video_device_issue):t=sE.other_diagnostic,3===e.value||2===e.value){if(i&&!this._speakingWhileMutedManager.shouldNotifyError(new Date))return;this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===sE.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!1}))}else{if(i&&!this._speakingWhileMutedManager.shouldNotifyRecovery(new Date))return;this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===sE.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!0}))}let n="";const r=this._ufdsCorrelationIdCache[e.type][e.mediaType];3==e.value||2==e.value?r?n=r:(n=Mf(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=n):(r&&(n=r),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);const s={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:n};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:s}),this.shallStopVideo(e)){const t=+new Date,i=Mf();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:aE.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch(t){const i=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(i)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){const t=new le({defaultError:ee.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});this.localVideoStream&&(this.sendVideoEvent({eventName:aE.acs_calling_start_video_failure,correlationId:Mf(),timestampInfo:{attemptTimestamp:+new Date},step:"start",additionalDetails:{..._b(t)},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)),this.logger.error(t.message)}if(this.shallStopAudio(e)){const t=+new Date,i=Mf();if(vy()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:aE.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.mute()}catch(t){const i=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(i)}}const n=vy()?.calling?.preventStopAudio;if(n)return this.sendAudioEvent({eventName:aE.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"}),void(!vy()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:aE.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.stopAudio(),this.markCallMuted();const e=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new le({defaultError:ee.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:n});this.logger.error(r.message);const s=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:s-t},correlationId:i,step:"mid-call"},r)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch(e){this.logger.error("Failed to send ufd telemetry")}}))),e.push(this.tsCall.on("participantAdded",(async e=>{this.logger.debug("tsCall participant added");const t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),0===t.length&&t.push("remoteParticipantId unavailable");const i=kS(e.id);if(this._isCteTeamsCall=this._isCteTeamsCall||"microsoftTeamsUser"===i.kind,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"added",kindOfEvent:oE.event}),By(e))this.logger.info("Add participant: Handle hidden calling application");else{this._handleLocalRingingCallState(e);try{const t=this.getOrCreateRemoteParticipant(i,e);this._eventEmitter.emit("remoteParticipantsUpdated",{added:[t],removed:[]})}catch(e){this.logger.log("unable to map call participant to ACS user")}}}))),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);const i=e=>{const t=kS(e.id);this._isCteTeamsCall=this._isCteTeamsCall||"microsoftTeamsUser"===t.kind;const i=this.getOrCreateRemoteParticipant(t,e);this._handleLocalRingingCallState(e),i.on("displayNameChanged",(()=>{this._callerIdentity&&DS(this._callerIdentity)===DS(i.identifier)&&(this._callerDisplayName=i.displayName,this._eventEmitter.emit("callerInfoChanged")),this._transferorIdentity&&DS(this._transferorIdentity)===DS(i.identifier)&&(this._transferorDisplayName=i.displayName,this._eventEmitter.emit("transferorInfoChanged"))}))},n=[];this.tsCall.participants.forEach((e=>{vy().calling.checkHiddenBotOnCallStart&&By(e)||i(e);try{e.endpoints?.endpointDetails.forEach((e=>n.push(e.participantId)))}catch(e){this.logger.error("Unable to get participantId from from remote participant")}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:n,participantAddedOrRemoved:"added",kindOfEvent:oE.initialize})}catch(e){this.logger.error("Unable to send participant added telemtery")}return e.push(this.tsCall.on("participantRemoved",(async e=>{this.logger.debug("tsCall participant removed");const t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),0===t.length&&t.push("remoteParticipantId unavailable"),By(e))return this.logger.info("Remove participant: Ignore calling application"),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"removed",kindOfEvent:oE.event});const i=e.id;if(i){const n=this._remoteParticipants.find((e=>DS(e.identifier)===i));if(n){const{callEndReason:i}=Tb(this,e);n.setCallEndReason(i),this.deleteRemoteParticipant(n),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[n]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"removed",kindOfEvent:oE.event,additionalDetails:{...Ib(i)}})}else this.logger.log("unable to find participant to remove")}}))),e}_trackNetworkQualityUfdEventDetails(e){const t=+new Date;let i="";switch(e){case 5:i=Jb;break;case 32:i=Zb;break;case 2:i=Yb;break;case 1:i=Qb;break;case 37:i=Xb}this._networkQualityUfdEventDetails.push({eventName:i,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{const t=vy().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||9!==e.type||3!==e.value)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await GT(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info("Unable to perform mute and unmute to recover microphoneNotFunctioning",e)}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}`),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"callMode-changed",oldState:yb[this._callMode],newState:yb[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}async startCallInternal(e,t,i,n,r,s){const a=!!e?.audioOptions?.muted,o=this.getLocalVideoStreamFromCallOptions(e),l=this.getLocalAudioStreamFromCallOptions(e);let c;const d=r?.attemptTimestamp??+new Date,u=r?.correlationId??Mf(),h=Mf();this._joinContextDescription=function(e){return e?e.groupId?SS.GroupCall:!e.threadId||e.organizerId||e.tenantId||e.messageId?e.threadId&&e.organizerId&&e.tenantId&&e.messageId?SS.TeamsCoordinates:e.meetingId?SS.TeamsMeetingId:e.meetingLink?SS.TeamsMeetingLink:e.roomId?SS.RoomCall:SS.Unknown:SS.GroupChatCall:SS.Unknown}(i);const g=this._callAgent.getEcsConfigIds(),p=1===this.tsCall.participants.length&&!this.tsCall.threadId&&!t,m=!!p||this._allowIPAudio,f=!!p||this._allowIPVideo,v=MI(this.tsCall),S={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:n?.isEmergency||!1,trouterState:this._callAgent.getTrouterState(),muted:a,withVideo:f&&!!o,withAudio:m&&l?.mediaStreamType?l.mediaStreamType:"",...ND(v),AcsCallingSDKWeb_ecsConfigId:g.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:g.SkypeWebMedia,customContext:{userToUserPresent:!!e?.customContext?.userToUser,xHeadersPresent:!!e?.customContext?.xHeaders&&e.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:vy().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode,accessToImmersiveEvents:e?.firstPartyOptions?.accessToImmersiveEvents}},additionalDetails:{}};e?.videoOptions?.constraints&&(S.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),n?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=n.meetingInfo.tenantId,S.additionalProperties.teamsMeetingTenantId=n.meetingInfo.tenantId),n?.threadId&&(this._teamsMeetingThreadId=n.threadId,S.additionalProperties.teamsMeetingThreadId=n.threadId),n?.onBehalfOf&&(S.additionalProperties.onBehalfOfProvided=!0,S.additionalProperties.onBehalfOfIdKind=kS(n.onBehalfOf).kind);const y={...S},C={...S};this.sendCallStageEvent({eventName:aE.acs_calling_call_attempt,correlationId:u,timestampInfo:{attemptTimestamp:d},additionalPayload:S},void 0,void 0,void 0,"attempt");try{this._isMicrophoneMuted=a,e?.alternateCallerId&&(c=DS(e.alternateCallerId)),o&&this.setLocalVideoStream(o),this.setLocalAudioStream(l)}catch(e){s?.reject(e);const t=+new Date,i=new le({defaultError:ee.CALL.INSTANTIATE_CALL,originalError:e});throw y.additionalDetails.communicationServicesError=_b(i).communicationServicesError,this.sendCallStageEvent({eventName:aE.acs_calling_call_failed,correlationId:u,timestampInfo:{deltaTimeInMs:t-d},additionalPayload:y},i,void 0,void 0,"failure"),this.logger.error(i.message),i}const T=X.generateCauseId();pI.setCauseIdToNetworkInfo(T);try{const i={...n};!vy().calling.setDeviceType||"mesh"!==this._callAgent.getDeviceType()&&"meshV2"!==this._callAgent.getDeviceType()||(i.endpointMetadata=JSON.stringify({meshapp:!0})),v?(await(this.tsCall.initAsync?.(i)),s?.resolve()):this.tsCall.init(i),o&&this.sendVideoEvent({correlationId:h,eventName:aE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:d},localVideoStream:o,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn});try{if(e?.videoOptions?.constraints){const t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,"start",h,d),i=this._mediaConstraintsManager.getTelemetryPayload({video:t});C.additionalProperties.constraints=i}}catch(e){const t=new le({defaultError:ee.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}const r=this.setClientEndpointCapabilities(e);if(vy()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(r.mediaConfiguration={connectionType:"NoDirectConnection"}),a&&(r.muteFlags=1),e?.firstPartyOptions?.disableAudioMixing&&(void 0===r.muteFlags?r.muteFlags=2:r.muteFlags|=2),void 0!==e?.firstPartyOptions?.enableSpatialAudio&&(r.mediaConfiguration=r.mediaConfiguration||{},r.mediaConfiguration.enableSpatialAudio=e.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:e.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${e.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),r.customHeaderContext=$y(e),l&&await this.startAudioInternal(l,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),"RawMedia"===o?.mediaStreamType)try{await this._setRawStream(o,1)}catch(e){const t=+new Date,i=new le({defaultError:ee.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:h,eventName:aE.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-d},localVideoStream:o,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn},i),this.removeLocalVideoStream(o)}t?await this.tsCall.startWithMeetingData(T,{withVideo:!!o&&this.isIPVideoEnabled,muted:a,ringOthers:!0,alternateId:c,shouldResurrect:"resurrect",...r}):await this.tsCall.start({withVideo:!!o&&this.isIPVideoEnabled,muted:a,ringOthers:!0,alternateId:c,...r},T);const g=+new Date;this.sendCallStageEvent({eventName:aE.acs_calling_call_connected,correlationId:u,timestampInfo:{deltaTimeInMs:g-d},additionalPayload:C},void 0,void 0,pI.getRemoveCauseIdToNetworkInfo(T),"success"),l&&this.shallRemoveLasAfterConnectedSuccessfully(l,"start",u,g,d),o&&this.shallRemoveLvsAfterConnectedSuccessfully(o,"start",u,g,d),this._handleAudioEffectsOperations()}catch(e){s?.reject(e);const t=+new Date,{callEndReason:i,callingCommunicationError:n}=Cb(this,e);if(o){const i=new le({defaultError:ee.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:e});this.sendVideoEvent({correlationId:h,eventName:aE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-d},localVideoStream:o,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn},i),this.removeLocalVideoStream(o)}throw l&&this.removeLocalAudioStream(l),y.additionalDetails.callEndReason=Ib(i).callEndReason,this.sendCallStageEvent({eventName:aE.acs_calling_call_failed,correlationId:u,timestampInfo:{deltaTimeInMs:t-d},additionalPayload:y},n,void 0,pI.getRemoveCauseIdToNetworkInfo(T),"failure"),this.logger.error(`Failed to start the call, message=${i?.message}, code=${i?.code}, subCode=${i?.subCode}, resultCategories=${i?.resultCategories}`),n}}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){const e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(DS(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${vy().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<vy().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){const t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{const i=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>"audio"===e.type)).map((e=>e.sourceId))??[],n=i.length>0?Math.min(...i):void 0,r=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>"audio"===e.type)).map((e=>e.sourceId))??[],s=r.length>0?Math.min(...r):void 0;return void 0!==n&&null!=s?n-s:0}));for(const i of t){if(e.length===vy().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(i)}}else e.splice(vy().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){const e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}getMeetingCapabilitiesInternal(){const e=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){const t=+new Date,i=Mf(),n=X.generateCauseId();return pI.setCauseIdToNetworkInfo(n),this.sendCallStageEvent({eventName:aE.acs_calling_call_hangup_attempt,correlationId:i,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone,n).then((()=>{const e=+new Date;this.sendCallStageEvent({eventName:aE.acs_calling_call_hangup_success,correlationId:i,timestampInfo:{deltaTimeInMs:e-t}},void 0,void 0,pI.getRemoveCauseIdToNetworkInfo(n))})).catch((e=>{const r=+new Date,{callEndReason:s,callingCommunicationError:a}=Cb(this,e),o=this._callAgent.getEcsConfigIds(),l={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:o.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:o.SkypeWebMedia},additionalDetails:{...Ib(s)}};throw this.sendCallStageEvent({eventName:aE.acs_calling_call_hangup_failure,correlationId:i,timestampInfo:{deltaTimeInMs:r-t},additionalPayload:l},a,void 0,pI.getRemoveCauseIdToNetworkInfo(n)),a}))}async mute(){const e=this.logger.createFnLogger(JS.Mute),t=+new Date,i=Mf(),n=X.generateCauseId();pI.setCauseIdToNetworkInfo(n),this.sendAudioEvent({eventName:aE.acs_calling_mute_attempt,eventType:cE.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info("mute"),await this.tsCall.mute(n),e.info("mute success");const r=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_mute_success,eventType:cE.MuteMicrophone,timestampInfo:{deltaTimeInMs:r-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:pI.getRemoveCauseIdToNetworkInfo(n)})}catch(r){const s=new le({defaultError:ee.CALL.MIC_MUTE,originalError:r});e.error("Failed to mute microphone");const a=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_mute_failure,eventType:cE.MuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:pI.getRemoveCauseIdToNetworkInfo(n)},s),s}}async unmute(){const e=this.logger.createFnLogger(JS.Unmute),t=+new Date,i=Mf();let n=!1;const r=X.generateCauseId();if(pI.setCauseIdToNetworkInfo(r),this.sendAudioEvent({eventName:aE.acs_calling_unmute_attempt,eventType:cE.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){const t="cannot unmute as microphone is disabled";throw e.error(t),new le({defaultError:ee.CALL.MIC_DISABLED,originalError:t})}if(!this.isIPAudioEnabled){const t="cannot unmute as IP audio in Teams Meeting Policy is disabled";throw e.error(t),new le({defaultError:ee.CALL.IP_AUDIO_NOT_ALLOWED,originalError:t})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const t="cannot unmute as consent is required to be recorded or transcribed";throw e.error(t),new le({defaultError:ee.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:t})}try{e.info("unmute"),await this.tsCall.unmute(r),e.info("unmute success");const s=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_unmute_success,eventType:cE.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:s-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)});const a=+new Date,o=vy()?.calling?.preventStopAudio;if(!o&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:aE.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:a},correlationId:i,step:"mid-call",networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)}),n=!0,e.info("start audio"),await this.tsCall.startAudio(),e.info("start audio success");const t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:aE.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-a},correlationId:i,step:"mid-call",networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)})}this.setLocalAudioStream()}catch(s){const a=n?ee.CALL.MIC_UNMUTE_AND_STARTAUDIO:ee.CALL.MIC_UNMUTE,o=new le({defaultError:a,originalError:s});e.error(a.message);const l=+new Date;throw this.sendAudioEvent({eventName:n?aE.acs_calling_start_audio_failure:aE.acs_calling_unmute_failure,eventType:n?void 0:cE.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:l-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!n,networkInfo:pI.getRemoveCauseIdToNetworkInfo(r)},o),o}}async muteAllRemoteParticipants(){const e=vy();if(!e.calling.enableMuteOthers)throw new le({defaultError:ee.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===uy.TwoParty)throw new le({defaultError:ee.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});const t=this.logger.createFnLogger(JS.MuteAllRemoteParticipants),i=+new Date,n=Mf();this.sendAudioEvent({eventName:aE.acs_calling_mute_attempt,eventType:cE.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:i},correlationId:n,step:"mid-call"});try{t.info("mute all others"),dD(JS.MuteAllRemoteParticipants,this.state);const r=[];if(0!==this._remoteParticipants.length){let i=!1,n=!1,s="";if(this._remoteParticipants.map((a=>{const o=a.tsRemoteParticipant;e.calling.allowMutePstnRemoteParticipant||"phoneNumber"!==a.identifier.kind?[3,5].some((e=>e===o?.state))?void 0!==o&&(r.push(o),s+=DS(a.identifier)+", "):(t.warn("non-connected participants cannot be muted by others"),n=!0):(t.warn("PSTN participants cannot be muted by others"),i=!0)})),0!==r.length?(await this.tsCall.muteParticipants(1,r),t.info(`called mute function on the following participants: ${s}`)):t.error("all remote participants are not supported to be muted by others"),i)throw new le({defaultError:ee.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});if(n)throw new le({defaultError:ee.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else t.info("no participants to mute in attempt to mute all remote participants");t.info("mute all others success");const s=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_mute_success,eventType:cE.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:s-i},correlationId:n,step:"mid-call"})}catch(e){const r=new le({defaultError:ee.CALL.MUTE_ALL_PARTICIPANTS,originalError:e});t.error(r.message);const s=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_mute_failure,eventType:cE.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:s-i},correlationId:n,step:"mid-call"},r),r}}async muteIncomingAudio(){const e=this.logger.createFnLogger(JS.MuteIncomingAudio),t=+new Date,i=Mf();this.sendAudioEvent({eventName:aE.acs_calling_mute_attempt,eventType:cE.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.muteSpeaker();const e=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_mute_success,eventType:cE.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new le({defaultError:ee.CALL.MUTE_INCOMING_AUDIO,originalError:n});e.error(r.message);const s=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_mute_failure,eventType:cE.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:s-t},correlationId:i,step:"mid-call"},r),r}}async unmuteIncomingAudio(){const e=this.logger.createFnLogger(JS.MuteIncomingAudio),t=+new Date,i=Mf();this.sendAudioEvent({eventName:aE.acs_calling_unmute_attempt,eventType:cE.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.unmuteSpeaker();const e=+new Date;this.sendAudioEvent({eventName:aE.acs_calling_unmute_success,eventType:cE.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new le({defaultError:ee.CALL.UNMUTE_INCOMING_AUDIO,originalError:n});e.error(r.message);const s=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_unmute_failure,eventType:cE.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:s-t},correlationId:i,step:"mid-call"},r),r}}async sendDtmf(e){const t=function(e){switch(e){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 le({defaultError:ee.CALL.INVALID_DTMF_TONE})}}(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error("Failed to send DTMF tone"),new le({defaultError:ee.CALL.DTMF_TONE})}))}async startVideo(e){const t=this.logger.createFnLogger(JS.StartVideo),i=+new Date,n=Mf(),r=vy()?.calling?.preventStopAudio;if(this.sendVideoEvent({eventName:aE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},localVideoStream:e,correlationId:n,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),!this.isVideoPermitted()){const e="cannot start video as camera is disabled by the Presenter or Organizer of the meeting";throw t.error(e),new le({defaultError:ee.CALL.CAMERA_DISABLED,originalError:e})}if(!this.isIPVideoEnabled){const e="cannot start video as IP video is not allowed";throw t.error(e),new le({defaultError:ee.CALL.IP_VIDEO_NOT_ALLOWED,originalError:e})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const e="cannot start video as consent is restricted";throw t.error(e),new le({defaultError:ee.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:e})}if(this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:aE.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:i},correlationId:n,step:"mid-call"});try{t.info("start audio before starting video"),await this.tsCall.startAudio(),t.info("start audio success before starting video");const e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:aE.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-i},correlationId:n,step:"mid-call"})}catch(e){const r="Failed to start audio before starting video",s=new le({defaultError:ee.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(r);const a=+new Date;throw this.sendAudioEvent({eventName:aE.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:a-i},correlationId:n,step:"mid-call"},s),s}}try{if(!e)throw new le({defaultError:ee.CALL.STREAM_NULL});if(!(e instanceof UI))throw new le({defaultError:ee.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new le({defaultError:ee.CALL.VIDEO_ALREADY_ON});"RawMedia"===e?.mediaStreamType&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){const r=new le({defaultError:ee.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},r),r}const s=X.generateCauseId();pI.setCauseIdToNetworkInfo(s);try{t.info("start video"),await this.tsCall.startVideo(void 0,s);const r=+new Date;this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:pI.getRemoveCauseIdToNetworkInfo(s)}),t.info("video started")}catch(r){const t=+new Date,a=Eb(0,r);throw this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:pI.getRemoveCauseIdToNetworkInfo(s)},a),this.removeLocalVideoStream(e),a}}async stopVideo(e){const t=this.logger.createFnLogger(JS.StopVideo),i=+new Date,n=Mf();this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn});const r=4===this.tsCall.state||5===this.tsCall.state;if(!r&&!this.tsCall.isVideoOn||r&&!this.localVideoStream){const t=new le({defaultError:ee.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},t),t}if(void 0!==this.localVideoStream&&this.localVideoStream!==e){const t=new le({defaultError:ee.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},t),t}const s=()=>{try{if(vy().calling.allowAccessRawMediaStream&&"RawMedia"===e.mediaStreamType){const e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??"Unkown error"}`)}},a=X.generateCauseId();pI.setCauseIdToNetworkInfo(a);try{t.info("stop video"),await this.tsCall.stopVideo(void 0,a),s();const r=+new Date;this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:pI.getRemoveCauseIdToNetworkInfo(a)}),t.info("video stopped"),this.removeLocalVideoStream(e)}catch(r){s();const t=+new Date,o=Eb(0,r,!0);throw this.sendVideoEvent({correlationId:n,eventName:aE.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:pI.getRemoveCauseIdToNetworkInfo(a)},o),o}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){const e=+new Date,t=Mf(),i=X.generateCauseId();pI.setCauseIdToNetworkInfo(i);try{this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:gy.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),vy().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,i),this.removeLocalAudioStream(this._localAudioStreams[0]);const n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:gy.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:pI.getRemoveCauseIdToNetworkInfo(i)})}catch(n){const r=+new Date,s=new le({defaultError:ee.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,holdType:gy.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,..._b(s)},networkInfo:pI.getRemoveCauseIdToNetworkInfo(i)}),s}}async resume(){const e=+new Date,t=Mf(),i=X.generateCauseId();pI.setCauseIdToNetworkInfo(i);try{this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:gy.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,i),this.setLocalAudioStream();const n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:gy.Standard},networkInfo:pI.getRemoveCauseIdToNetworkInfo(i)})}catch(n){const r=+new Date,s=new le({defaultError:ee.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,holdType:gy.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,..._b(s)},networkInfo:pI.getRemoveCauseIdToNetworkInfo(i)}),s}}async startScreenSharing(e){const t=this.logger.createFnLogger(JS.StartScreenShare),i=+new Date,n=Mf();try{if(this.sendScreenShareEvent({eventName:aE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:oE.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:e}),3!==this.tsCall.state)throw new le({defaultError:ee.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new le({defaultError:ee.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const e="screen sharing cannot be started as consent is required to be recorded or transcribed";throw t.error(e),new le({defaultError:ee.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:e})}if(e){if(!(e instanceof UI))throw new le({defaultError:ee.CALL.SS_RAW_STREAM_IS_NOT_LVS});if("RawMedia"!==e.mediaStreamType)throw new le({defaultError:ee.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new UI(new vI(RS,Mf(),RS,this._callAgent.deviceManager))}catch(e){const t=+new Date;this.removeScreenSharingStream();const r=new le({defaultError:ee.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:aE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:t-i},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,..._b(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}return this.tsCall.startScreenSharing().then((()=>{const e=+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:aE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:e-i},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream})})).catch((e=>{const t=+new Date;this.removeScreenSharingStream();const r=Eb(0,e);throw this.sendScreenShareEvent({eventName:aE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:t-i},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,..._b(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}))}async stopScreenSharing(){this.logger.createFnLogger(JS.StopScreenShare);const e=+new Date,t=Mf();if(this.sendScreenShareEvent({eventName:aE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),3!==this.tsCall.state)throw new le({defaultError:ee.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){const i=+new Date,n=new le({defaultError:ee.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:aE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,..._b(n)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),n}return this.tsCall.stopScreenSharing().then((()=>{const i=+new Date,n=Z.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:aE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:n})})).catch((i=>{const n=+new Date,r=Eb(0,i,!0),s="string"==typeof r?.message?r?.message:void 0;throw this.sendScreenShareEvent({eventName:aE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:s||"",code:r.code,subCode:r.subCode,..._b(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}))}async setConstraints(e){const t=+new Date,i=Mf();try{const n=await this._mediaConstraintsManager.setVideoConstraints(e?.video,"mid-call",i,t);this.logger.info(`Video constraints set - ${JSON.stringify(n)}`)}catch(e){throw new le({defaultError:ee.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if("stateChanged"!==e&&"idChanged"!==e&&"isMutedChanged"!==e&&"isIncomingAudioMutedChanged"!==e&&"isScreenSharingOnChanged"!==e&&"isLocalVideoStartedChanged"!==e&&"remoteParticipantsUpdated"!==e&&"localVideoStreamsUpdated"!==e&&"localAudioStreamsUpdated"!==e&&"remoteAudioStreamsUpdated"!==e&&"totalParticipantCountChanged"!==e&&"roleChanged"!=e&&"mutedByOthers"!==e&&"callerInfoChanged"!==e&&"transferorInfoChanged"!==e)throw new le({defaultError:ee.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("stateChanged"!==e&&"idChanged"!==e&&"isMutedChanged"!==e&&"isIncomingAudioMutedChanged"!=e&&"isScreenSharingOnChanged"!==e&&"isLocalVideoStartedChanged"!==e&&"remoteParticipantsUpdated"!==e&&"localVideoStreamsUpdated"!==e&&"localAudioStreamsUpdated"!==e&&"remoteAudioStreamsUpdated"!==e&&"totalParticipantCountChanged"!=e&&"roleChanged"!=e&&"mutedByOthers"!==e&&"callerInfoChanged"!==e&&"transferorInfoChanged"!==e)throw new le({defaultError:ee.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if("meetingCapabilitiesChanged"!==e)throw new le({defaultError:ee.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if("meetingCapabilitiesChanged"!=e)throw new le({defaultError:ee.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log("participant capabilities change event listener registered"),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log("participant capabilities change event listener unregistered"),this._eventEmitter.off(e,t)}onWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log("watermark audio only fallback triggered listener registered"),this._eventEmitter.on(e,t)}offWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log("watermark audio only fallback triggered listener unregistered"),this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let i=this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)));return i||(i=new Wk(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(i),this._mriToRemoteParticipantMap.set(DS(i.identifier),i)),t&&i.observeParticipant(t),i}deleteRemoteParticipant(e){let t=!0;return 1!==this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length&&(this.logger.warn("Deleted remote participant array is not 1"),t=!1),this._mriToRemoteParticipantMap.delete(DS(e.identifier))||(this.logger.warn("Deleted remote participant was not found in mri-to-remoteparticipant map"),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send call hold or resume telemetry")}}sendVideoEvent(e,t){try{let i,n;try{i=e.localVideoStream?.getStreamMetadata()}catch(e){this.logger.error("Unable to get stream meta data on send video event")}t&&(n="string"==typeof t?.message?t?.message:void 0,e.additionalDetails={..._b(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{...i,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:n||"",isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch(e){this.logger.debug("Unable to send video telemetry")}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch(e){this.logger.error("Unable to get stream meta data on send video event")}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch(e){this.logger.debug("Unable to send screen share telemetry")}}sendRawMediaEvent(e){const t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?"MediaStream":"Device";try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:t})}catch(e){this.logger.debug("Unable to send raw media telemetry")}}sendAudioEvent(e,t){try{let i;t&&(i="string"==typeof t?.message?t?.message:void 0,e.additionalDetails={..._b(t)});const n={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:i||"",additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};void 0!==e.eventType&&(n.eventType=e.eventType),e.initiatedBySdk&&(n.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:n})}catch(e){this.logger.debug("Unable to send audio telemetry")}}sendCallStageEvent(e,t,i,n,r){try{let s,a="";t&&(s=this?.tsCall?.callEndDiagnosticsInfo||i||{},a=t.message);const o=this._joinContextDescription===SS.RoomCall||this.kind===ue.Call&&"Incoming"===this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,l=!o&&this._joinContextDescription===SS.TeamsMeetingLink||this._joinContextDescription===SS.TeamsMeetingId||this._joinContextDescription===SS.TeamsCoordinates||"Incoming"==this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,c={localParticipantId:this?.tsCall?.participantId||"",callId:this?.tsCall?.callId||"",callType:this?.tsCall?.callType||"",callDirection:this._direction,failureReason:a,callEndDiagnosticsInfo:s,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:o,meetingJoin:l,hostRegion:this?.tsCall?.region||"",correlationId:e.correlationId,timestampInfo:e.timestampInfo,...e.additionalPayload,networkInfo:n||[]};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:c},void 0,r)}catch(e){}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return MS.group;if(0===this.tsCall?.participants.length)return MS.unknown;const e=this.tsCall?.participants[0];return kS(e.id).kind}optimalVideoCountChanged(){const e=this._optimalVideoCount,t=this.tsCall.optimalVideoCount;if(t&&e!==t)try{Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"optimalVideoCount-changed",previousOptimalVideoCount:e,newOptimalVideoCount:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch(e){this.logger.error("Failed to send optimal video count change telemetry")}finally{this._optimalVideoCount=this.tsCall.optimalVideoCount||1}}_sendNetworkChangedTelemetry(){try{const e=(e,t,i)=>{Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"network-changed",trouterState:e,onLine:t,rdpState:i})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener("online",this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener("offline",this._offlineListener),this._mmrRdpConnectionManager.on("stateChange",(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch(e){this.logger.warn("Failed to subscribe to network changed")}}_setupSelectedDeviceChangedTelemetry(){try{const e=e=>{Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"selectedDevice-changed",selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on("selectedDeviceChanged",e);const t=this._selectedDeviceManager.selectedDevice("Speaker"),i=this._selectedDeviceManager.selectedDevice("Microphone");e({selectedDeviceType:"Speaker",oldDevice:void 0,newDevice:t}),e({selectedDeviceType:"Microphone",oldDevice:void 0,newDevice:i})}}catch(e){this.logger.warn("Failed to subscribe to selectedDevice changed")}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new le({defaultError:ee.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){if(this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),"RawMedia"!==this.localVideoStream.mediaStreamType){const t=this._callAgent.tsStack.getDeviceManager();t?.selectDevices({camera:e.source.id})}this.localVideoStream.addCall(this);try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[this.localVideoStream],removed:[]})}catch(e){this.logger.warn("Application threw on emit localVideoStreamsUpdated added")}this.logger.log("isLocalVideoStarted changed=true"),this._isLocalVideoStarted=!0,this._eventEmitter.emit("isLocalVideoStartedChanged")}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log("Attempting to remove local video stream"),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 t=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[t]})}catch(e){this.logger.warn("Application threw on emit localVideoStreamsUpdated removed")}this.logger.log("isLocalVideoStarted changed=false"),this._isLocalVideoStarted=!1,this._eventEmitter.emit("isLocalVideoStartedChanged")}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new le({defaultError:ee.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],removed:[]});else if(0===this._localAudioStreams.length){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),void this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],removed:[]});const t=this.deviceManager?.selectedMicrophone;if(t){const e=new YI(t);e.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],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(e){if(e){if(this.logger.log("Attempting to remove local audio stream"),e.off("audioSourceChanged",this.audioSourceChanged),e.dispose(),0===this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length)return void this.logger.warn("Stream not found, failed to remove stream from localAudioStreams collection");e.removeCall(this),this.logger.log("Local audio stream removed successfully"),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{const e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug("No LocalAudioStream found in the call, cannot handle call audio effects operations");this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e};const t=e.feature(oD.AudioEffects);t?.on("effectsProcessorStatsUpdated",this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}isAudioPermitted(){return!!this.feature(oD.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature(oD.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(vy()?.calling?.allowAccessRawMediaStream&&"RawMedia"===this.localScreenSharingStream?.mediaStreamType){const e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);const e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);const t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[t]})}}mapTsCallState(e){const t=Sb[e];switch(t){case"Unknown":case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case"Disconnected":{this._callEndReason=Cb(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(Tb(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState("Disconnected")}));const i=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:i}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),vy().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log("Telemetry flushed")})).catch((e=>{this.logger.warn("Failed to flush telemetry log manager events")}));break}case"Connected":this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(My))),vy().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case"Incoming Call":{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);const e=new Zk(this.tsCall,{config:this._config});Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"state-changed",oldState:this._state,newState:"Incoming Call",callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.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:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){const t=vy()?.calling?.deviceNotFunctioningMuted,i=vy()?.calling?.deviceCaptureMutedVideo,n=vy()?.calling?.preventStopVideo,r=25===e.type&&3===e.value,s=r&&1===e.mediaType,a=33===e.type&&3===e.value,o=bD(),l="ios"===_D()&&"Safari"===o.engine,c="android"===_D(),d=3===this.tsCall.state;return n?d&&this.tsCall.isVideoOn&&a:t&&d&&this.tsCall.isVideoOn&&(a||l&&r||i&&c&&s)}shallRemoveLocalVideoStreamOnBadUfd(e){const t=this.tsCall.localMediaStreams.find((e=>1===e.mediaType)),i=1===e.mediaType&&3===e.value&&25===e.type,n=4==this.tsCall.state||5===this.tsCall.state;if("Mobile"===bD().formFactor&&(i||"hidden"==document.visibilityState)&&this.localVideoStream&&n&&!t)return!1;if(!vy()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;const r=3===this.tsCall.state;return!(1!==e.mediaType||3!==e.value||33!==e.type&&25!==e.type&&34!==e.type||!this.localVideoStream||r||t)}shallStopAudio(e){const t=vy()?.calling?.deviceNotFunctioningMuted,i=vy()?.calling?.osAutoRecoverAudio,n=25===e.type&&3===e.value&&0===e.mediaType,r=9===e.type&&3===e.value,s=bD(),a="ios"===_D()&&"Safari"===s.engine,o=3===this.tsCall.state;return i?t&&o&&r:t&&!this._isDeviceNotFunctioningMuted&&o&&(r||a&&n)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){const t=vy()?.calling?.deviceCaptureMuteRecover&&!vy()?.calling?.preventFakeMute,i=25===e.type&&1===e.value&&0===e.mediaType,n=3===this.tsCall.state,r=bD(),s="ios"===_D()&&"Safari"===r.engine,a=9===e.type&&1===e.value;return t&&this._isDeviceNotFunctioningMuted&&n&&(a||s&&i)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:aE.acs_calling_participant_added_or_removed,tenant:xv,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,vy().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||"",timestampInfo:e.timestampInfo||"",additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch(e){this.logger.debug("Unable to send participant added or removed telemtery")}}_handleLocalRingingCallState(e){"Connected"===this._state||"Outgoing"!==this._direction||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{2!==e.state||"Connected"===this._state||this._localRingingStateSet||(this._setCallState("Ringing"),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){const t=this._state,i=e,n=new Zk(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${i}`),this._state=i,"Connected"===i&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit("stateChanged"),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"state-changed",oldState:t,newState:i,callTypeInfo:{initiatorKind:n.initiatorKind,targetKind:n.targetKind,transferor:n.transferorKind,context:n.context,callScenario:n.callScenario,direction:n.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?{...Ib(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){const t=Fy(vy(),e);t===sS?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"role-changed",oldAcsRole:this._role,newAcsRole:t,serviceRole:e||""}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit("roleChanged"))}}_setMeetingCapabilities(e){(function(e,t){return!!(e.capabilities&&null!=e.capabilities.allowVideo&&(null==t.capabilities?.allowVideo||t.capabilities.allowVideo!=e.capabilities.allowVideo)||e.meetingCapability&&null!=e.meetingCapability.allowIPVideo&&(null==t.meetingCapability?.allowIPVideo||t.meetingCapability.allowIPVideo!=e.meetingCapability.allowIPVideo)||e.meetingCapability&&null!=e.meetingCapability.attendeeRestrictions&&(null==t.meetingCapability?.attendeeRestrictions||t.meetingCapability.attendeeRestrictions!=e.meetingCapability.attendeeRestrictions)||e.meetingCapability&&null!=e.meetingCapability.allowPstnConferencing&&(null==t.meetingCapability?.allowPstnConferencing||t.meetingCapability.allowPstnConferencing!=e.meetingCapability.allowPstnConferencing)||e.meetingCapability&&null!=e.meetingCapability.allowTranslatedCaptions&&(null==t.meetingCapability?.allowTranslatedCaptions||t.meetingCapability?.allowTranslatedCaptions!=e.meetingCapability.allowTranslatedCaptions)||e.meetingCapability&&null!=e.meetingCapability.allowTranslatedTranscriptions&&(null==t.meetingCapability?.allowTranslatedTranscriptions||t.meetingCapability?.allowTranslatedTranscriptions!=e.meetingCapability.allowTranslatedTranscriptions)||e.meetingCapability&&null!=e.meetingCapability.allowRaiseHands&&(null==t.meetingCapability?.allowRaiseHands||t.meetingCapability?.allowRaiseHands!=e.meetingCapability.allowRaiseHands)||e.meetingCapability&&null!=e.meetingCapability.allowTeamsMeetingReactions&&(null==t.meetingCapability?.allowTeamsMeetingReactions||t.meetingCapability?.allowTeamsMeetingReactions!=e.meetingCapability.allowTeamsMeetingReactions)||e.meetingCapability&&null!=e.meetingCapability.presenterOption&&(null==t.meetingCapability?.presenterOption||t.meetingCapability?.presenterOption!=e.meetingCapability.presenterOption)||e.capabilities&&null!=e.capabilities.maskIdentitiesForRole&&(null==t.capabilities?.maskIdentitiesForRole||t.capabilities?.maskIdentitiesForRole!=e.capabilities.maskIdentitiesForRole)||e.recordingConsentDetails&&null!=e.recordingConsentDetails.consentActivelyRequired&&(null==t.recordingConsentDetails?.consentActivelyRequired||t.recordingConsentDetails.consentActivelyRequired!=e.recordingConsentDetails.consentActivelyRequired))})(e,this._lastTsCallMeetingDetails)&&(Yk(this._telemetryLogManager,this.logger,{...Jk(this,this._callAgent,Mf(),this._joinContextDescription),step:"meetingCapabilities-changed",oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit("meetingCapabilitiesChanged")),Object.assign(this._lastTsCallMeetingDetails,e)}removeRemoteAudioStream(e){if(e){if(this.logger.log("Attempting to remove remote audio stream"),0===this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),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:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(vy().calling.mediaMetricsDeviceEventsEnabled)try{const e=await(this.tsCall.getMediaSessionStatsAsync?.());if(void 0!==e?.metrics?.DeviceEvents){const t=JSON.parse(e.metrics.DeviceEvents),i=xy(this._mediaMetricsDeviceEvents||{},t);i.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:sE.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:i||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.info("Failed to set media metrics device events telemetry: no valid events data")}catch(e){this.logger.error("Failed to set media metrics device events telemetry")}}setClientEndpointCapabilities(e){const t={};let i=0;return e?.firstPartyOptions?.isImmersiveMode&&(i|=32768),e?.firstPartyOptions?.accessToImmersiveEvents&&(i|=2097152),vy()?.calling?.supportLiveStreaming&&(i|=32),vy()?.calling.sharedLineAppearance.enabled&&(i|=128),this._allowBreakoutRoomJoin&&(i|=4098),i>0&&(t.clientEndpointCapabilities=i),t}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(1!==e?.videoOptions?.localVideoStreams.length)throw new le({defaultError:ee.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof UI))throw new le({defaultError:ee.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(1!==e?.audioOptions?.localAudioStreams.length)throw new le({defaultError:ee.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof YI))throw new le({defaultError:ee.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!vy().calling.allowAccessRawMediaStream)throw new le({defaultError:ee.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});const i=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());if(!i?.setRawMediaStream)throw new le({defaultError:ee.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{const n=await e.getMediaStream();if(!n)throw new le({defaultError:ee.CALL.SS_RAW_STREAM_UNDEFINED});i.setRawMediaStream(n,t)}catch(e){if(1===t)throw new le({defaultError:ee.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(2===t)throw new le({defaultError:ee.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,i,n,r){if(this.tsCall.localMediaStreams.find((e=>1===e.mediaType)))this.sendVideoEvent({correlationId:i,eventName:aE.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:n-r},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn});else{if(!vy()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);const n=+new Date,s=new le({defaultError:ee.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(s.message),this.sendVideoEvent({correlationId:i,eventName:aE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:n-r},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn},s)}}shallRemoveLasAfterConnectedSuccessfully(e,t,i,n,r){if(this.tsCall.localMediaStreams.find((e=>0===e.mediaType)))this.sendRawMediaEvent({eventName:aE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:oE.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:n-r},additionalDetails:""});else{if(!vy().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);const n=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);const s=new le({defaultError:ee.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:aE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,localAudioStream:e,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:n-r},additionalDetails:{failureReason:s.message||"",code:s.code,subCode:s.subCode,..._b(s)}})}}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=vy().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new C_(new T_(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>=vy().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((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info("All remote streams isAvailable flags were reset"),this.logger.info("Disposed large meeting video rendering handler")))}catch(e){this.logger.error("Failed to handle large meeting video rendering",e)}}handleDominantSpeakersVideos(){this.logger.info("Dominant speakers changed during large meeting");const e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){const t=new le({defaultError:ee.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}const t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(AE.Internal_LargeMeetingVideoRendering),this.logger.info("Successfully disposed of view during large meeting"))}catch(e){const t=new le({defaultError:ee.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}}tO([SI,iO("design:type",Object)],rO.prototype,"logger",void 0),tO([ge(JS.BindToCall),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Array)],rO.prototype,"bindTsCall",null),tO([ge(JS.Feature),iO("design:type",Function),iO("design:paramtypes",[Object]),iO("design:returntype","function"==typeof(eO="undefined"!=typeof TFeature&&TFeature)?eO:Object)],rO.prototype,"feature",null),tO([pe(JS.HangUp),iO("design:type",Function),iO("design:paramtypes",[Object]),iO("design:returntype",Promise)],rO.prototype,"hangUp",null),tO([pe(JS.Mute),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"mute",null),tO([pe(JS.Unmute),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"unmute",null),tO([pe(JS.MuteAllRemoteParticipants),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"muteAllRemoteParticipants",null),tO([pe(JS.MuteIncomingAudio),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"muteIncomingAudio",null),tO([pe(JS.UnmuteIncomingAudio),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"unmuteIncomingAudio",null),tO([pe(JS.SendDtmf),iO("design:type",Function),iO("design:paramtypes",[String]),iO("design:returntype",Promise)],rO.prototype,"sendDtmf",null),tO([pe(JS.StartVideo),iO("design:type",Function),iO("design:paramtypes",[UI]),iO("design:returntype",Promise)],rO.prototype,"startVideo",null),tO([pe(JS.StopVideo),iO("design:type",Function),iO("design:paramtypes",[UI]),iO("design:returntype",Promise)],rO.prototype,"stopVideo",null),tO([pe(JS.StartAudio),iO("design:type",Function),iO("design:paramtypes",[YI]),iO("design:returntype",Promise)],rO.prototype,"startAudio",null),tO([me(JS.Hold),pe(JS.Hold),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"hold",null),tO([me(JS.Resume),pe(JS.Resume),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"resume",null),tO([pe(JS.StartScreenShare),iO("design:type",Function),iO("design:paramtypes",[UI]),iO("design:returntype",Promise)],rO.prototype,"startScreenSharing",null),tO([pe(JS.StopScreenShare),iO("design:type",Function),iO("design:paramtypes",[]),iO("design:returntype",Promise)],rO.prototype,"stopScreenSharing",null),tO([pe(JS.SetConstraints),iO("design:type",Function),iO("design:paramtypes",[Object]),iO("design:returntype",Promise)],rO.prototype,"setConstraints",null);var sO=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},aO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class oO extends rO{get info(){return this._info}constructor(e,t,i,n,r){super(e,t,i,n,ue.Call,r),this._info=this.callInfo,this._allowBreakoutRoomJoin=vy().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let i,n;const r=t,s=t,a=t,o=+new Date,l=Mf();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.attempt,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{attemptTimestamp:o},additionalDetails:{customContext:{userToUserPresent:!!r?.customContext?.userToUser,xHeadersPresent:!!r?.customContext?.xHeaders&&r?.customContext.xHeaders.length>0}}}),this._callAgent.isCteUser())switch(this.validateThreadId(e,t),B(e).kind){case"communicationUser":n=r.threadId;break;case"microsoftTeamsUser":n=a.threadId;break;case"phoneNumber":n=s.threadId;break;default:{const e=new le({defaultError:ee.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{deltaTimeInMs:+new Date-o},additionalDetails:{code:e.code,failureReason:e.message,..._b(e)}}),e}}let c;s?.alternateCallerId&&(NS(s.alternateCallerId),i=DS(s.alternateCallerId));try{if(dD(JS.AddParticipant,this.state),c=NS(e),!Vy(this.acsProxy,this.acsCustomRelayManager,!1,c))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{deltaTimeInMs:+new Date-o},additionalDetails:{code:e.code,failureReason:e.message,..._b(e)}}),e}if(this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)))){const t=new le({defaultError:ee.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[B(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{deltaTimeInMs:+new Date-o},additionalDetails:{code:t.code,failureReason:t.message,..._b(t)}}),t}const d=[...this.remoteParticipants.values()].map((e=>e.identifier));this._isAcsTeamsCall=Hy([...d,e],this._callAgent.kind),vy().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!n&&(n=this.tsCall.threadId||`${re}${Mf()}`);const u=X.generateCauseId();pI.setCauseIdToNetworkInfo(u);const h=this.getOrCreateRemoteParticipant(kS(DS(e)));return this.tsCall.addParticipant(DS(e),{alternateId:i,threadId:n,customHeaderContext:$y(s)},u).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.success,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{deltaTimeInMs:+new Date-o},networkInfo:pI.getRemoveCauseIdToNetworkInfo(u)})})).catch((t=>{const{callEndReason:i}=Tb(this,h.tsRemoteParticipant,t);h.callEndReason||h.setCallEndReason(i);const n=Ib(i);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:l,timestampInfo:{deltaTimeInMs:+new Date-o},additionalDetails:{code:n?.callEndReason.code,subCode:n?.callEndReason.subCode,failureReason:n?.callEndReason.message,...n},networkInfo:pI.getRemoveCauseIdToNetworkInfo(u)}),this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)))&&(this.deleteRemoteParticipant(h),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[h]}))})),h}async removeParticipant(e,t){const i=+new Date,n=Mf();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.attempt,participantAddedOrRemoved:"remove",correlationId:n,timestampInfo:{attemptTimestamp:i}});try{dD(JS.RemoveParticipant,this.state),NS(e)}catch(e){const t=new le({defaultError:ee.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{code:e.code,failureReason:e.message,..._b(t)}}),t}let r=this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)));if(!r){const t=new le({defaultError:ee.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[B(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,..._b(t)}}),t}const s=X.generateCauseId();pI.setCauseIdToNetworkInfo(s);try{await this.tsCall.removeParticipant(DS(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.success,participantAddedOrRemoved:"remove",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},networkInfo:pI.getRemoveCauseIdToNetworkInfo(s)})}catch(e){const t=Tb(this,r.tsRemoteParticipant,e).callEndReason;r.callEndReason||r.setCallEndReason(t);const a=Ib(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a},networkInfo:pI.getRemoveCauseIdToNetworkInfo(s)}),new le({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new le({defaultError:ee.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}}sO([ge(JS.AddParticipant),aO("design:type",Function),aO("design:paramtypes",[Object,Object]),aO("design:returntype",Object)],oO.prototype,"addParticipant",null),sO([pe(JS.RemoveParticipant),aO("design:type",Function),aO("design:paramtypes",[Object,Object]),aO("design:returntype",Promise)],oO.prototype,"removeParticipant",null);var lO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class cO{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(e,t){this._callCommon=e,this._eventEmitter=new OE.EventEmitter,this._kind=t,this._callConnected="Connected"===this._callCommon.state,this._customContext=jy(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(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([pe(),lO("design:type",Function),lO("design:paramtypes",[]),lO("design:returntype",Promise)],cO.prototype,"reject",null);var dO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class uO extends cO{get info(){return this._call.info}constructor(e){super(e,he.IncomingCall),this._call=e}async accept(e){if("microsoftTeamsUser"===this.info?.initiatorKind&&!Vy(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([pe(JS.Accept),dO("design:type",Function),dO("design:paramtypes",[Object]),dO("design:returntype",Promise)],uO.prototype,"accept",null);class hO{constructor(e,t){this.logger=e,this.proxy=t}async sendRequestWithRetry(e,t,i,n,r,s=1,a){if(s>r)throw new Error("Max retry reached");n.timeout||(n.timeout=2e4),n.maxRedirects=0,this.proxy&&(t=this.proxy.proxyfyUrl(t));try{switch(e){case"post":default:return await iR.post(t,i,n);case"get":return await iR.get(t,n);case"put":return await iR.put(t,i,n);case"delete":return await iR.delete(t,n)}}catch(o){let l=o?.response?.status;this.logger.error(`Found error for request ${e} ${t} ${l||""}`);const c=s+1;if(c<=r){let s=t;if(o&&o.response)if(301===o.response.status||302===o.response.status||303===o.response.status||307===o.response.status||404===o.response.status)s=o.response.headers&&o.response.headers.location?o.response.headers.location:s;else if(o.response.status<500)throw o;return this.logger.error(`Retrying, attempt #${c} url=${s}`),await new Promise((e=>setTimeout(e,a))),this.sendRequestWithRetry(e,s,i,n,r,c,a)}throw o}}}class gO{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,i){if(this._callId="",this._localParticipantId="",this._logger=i.createChild("IncomingCallPushNotificationHandler"),!e.incomingCallContext)throw new le({defaultError:ee.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new le({defaultError:ee.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse($T.inflate(atob(this._incomingCallContext),{to:"string"})),!(this._gp.hasOwnProperty("callNotification")&&this._gp.hasOwnProperty("conversationInvitation")&&this._gp.hasOwnProperty("debugContent")&&this._gp.hasOwnProperty("groupContext")))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new le({defaultError:ee.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((e=>e.callId==this._callId)))throw new le({defaultError:ee.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});const e=jT(),t=t=>{const i=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&1===t.state&&e.resolve()};this._tsCallStateSub=t.on("callStateChanged",i),i()};this._tsCallRegistrySub=this._tsCallRegistry.on("callAdded",t);const i={eventId:107,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(i))throw new le({defaultError:ee.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new le({defaultError:ee.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}}class pO{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};const t=R("ACS");this._logger=new _I(t)}initialize(e){this._localParticipant=e.localParticipant,this._jwtTokenProvider=e.jwtTokenProvider,this._telemetryLogManager=e.telemetryLogManager}userDialedNumber(e){this._userDialedPstnNumber=e,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(e,t){this._callId=e;const i=+new Date,n=t?.createThreadIdSuffix??vy().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.attempt});const r=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),s=new URL(n,vy().MiddleTier.baseServiceUrl);t?.participants.push({id:this._localParticipant});const a={Participants:t?.participants};try{const e=await this._httpRequestHelper.sendRequestWithRetry("post",s.toString(),a,{headers:r},vy().MiddleTier.maxRetry);return this._logger.info("Successfully created chat thread using ACS MiddleTier Service."),this._threadIdData=e?.data,this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-i},additionalDetails:{phrase:"Thread Id was successfully created from ACS MiddleTier Service",code:0,subCode:220006}}),Promise.resolve(this._threadIdData.threadId)}catch(e){this._logger.error("Error creating thread Id from ACS MiddleTier Service");const t=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-i},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)}}),t}}async AddParticipantsToThread(e,t){this._callId=e;const i=+new Date,n=t?.addParticipantsSuffix??vy().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.attempt});const r=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),s=new URL(n,vy().MiddleTier.baseServiceUrl),a={threadId:t?.threadId,Participants:t?.participants};try{const e=await this._httpRequestHelper.sendRequestWithRetry("post",s.toString(),a,{headers:r},vy().MiddleTier.maxRetry);this._logger.info("Call to add participants to chat thread using ACS MiddleTier Service");const t=e?.data;if(null!==t){if(!t.isSuccess)throw new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&735==t.multipleStatus[0].statusCode&&this._logger.info("Trying to add the same participant to the thread id")}return this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-i},additionalDetails:{phrase:"Successfully add participants from ACS MiddleTier Service",code:0,subCode:220007}}),Promise.resolve(t.isSuccess)}catch(e){this._logger.error("Fail to add participant error from ACS MiddleTier Service");const t=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:aE.acs_calling_middletier_gateway_api,suffix:n,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-i},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)}}),t}}async fetchUserPoliciesFromAcsMiddleTier(e,t,i){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(e,t,i)}async requestUserPoliciesFromAcsMiddleTier(e,t,i,n){this._callId=e;const r=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:oE.attempt},t),!t){const e=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-r},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,..._b(e)}}),e}let s,a={};i?(s=new URL(i.policyUrlSuffix,vy().MiddleTier.baseServiceUrl),a={id:t,userPolicies:i.userPolicies,userProperties:i.userProperties}):(s=new URL(vy().MiddleTier.policyUrlSuffix,vy().MiddleTier.baseServiceUrl),a={id:t});const o=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(n);try{const e=await this._httpRequestHelper.sendRequestWithRetry("post",s.toString(),a,{headers:o},vy().MiddleTier.maxRetry);return this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-r},additionalDetails:{phrase:"Teams user policy was fetched successfully from ACS MiddleTier Service",code:0,subCode:220004}},t),e?.data}catch(e){const i=function(e,t){return new le({defaultError:{message:e?.response?.data?.operationFailure?.phrase||t.message,code:e?.response?.data?.operationFailure?.code||t.code,subCode:e?.response?.data?.operationFailure?.subCode||t.subCode,resultCategories:e?.response?.data?.operationFailure?.resultCategories||t.resultCategories},originalError:e})}(e,ee.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(i.message),this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-r},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,..._b(i)}},t),i}}isEvEnabled(){const e=this._policySettingData?.userAggregatedPolicySettingData?.userProperties;return e?.evEnabled||!1}isMoHEnabled(){const e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy,t=e?.musicOnHoldEnabledType;return this._logger.info("Checking Music on Hold Policy, Enabled Type is: "+t),t===(hy.Enabled||hy.UserOverride)}isBreakoutRoomsAllowed(){const e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy;let t=e?.allowBreakoutRooms;return this._logger.info("Allow Breakout rooms from Teams meeting policy is "+t),null==t&&(t=!0),t}isIPAudioAllowed(){if(!vy().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info("Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false"),!0;const e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy,t=e?.ipAudioMode!==py.Disabled;return this._logger.info("Allow IP audio from Teams meeting policy is "+t),t}isIPVideoAllowed(){if(!vy().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info("Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false"),!0;const e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy,t=e?.ipVideoMode!==py.Disabled;return this._logger.info("Allow IP video from Teams meeting policy is "+t),t}getTeamsUserCaptionsPoliciesData(){const e=+new Date;let t="";this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:oE.attempt});const i=this._policySettingData.userAggregatedPolicySettingData,n=i?.userPolicies,r=i?.userProperties;if(!n?.teamsCallingPolicy){const t=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)}})}if(!n?.teamsMeetingPolicy){const t=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)}})}if(!r?.featureTypes){const t=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,..._b(t)}})}return(n?.teamsCallingPolicy||n?.teamsMeetingPolicy||r?.featureTypes?.includes(AS.TeamsProMgmt))&&(t=JSON.stringify({isLiveCaptionsEnabledForCalling:n?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===PS.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:n?.teamsMeetingPolicy?.liveCaptionsEnabledType===PS.DisabledUserOverride,isTeamsProMgmtSkuAvailable:r?.featureTypes?.includes(AS.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{phrase:"Fetching Captions policy from ACS MiddleTier Service response was successful",code:0}}),this._logger.info(`Fetching user's captions policy content = ${t}`)),t}getEmergencyContent(){const e=+new Date;this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:oE.attempt});let t="";try{const i=this._policySettingData.userAggregatedPolicySettingData,n=i?.userPolicies;let r=!1,s="";if(n?.locationPolicy?.emergencyNumbers){const e=n.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(e)&&(r=!0,t=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:i?.userProperties.region,locationPolicyTag:n?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:n?.teamsEmergencyCallingPolicy?.policyDocument}),s="LocationPolicy")}if(!r&&n?.teamsEmergencyCallRoutingPolicy){const e=n?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(e)&&(r=!0,t=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:i?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:n?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:n?.teamsEmergencyCallingPolicy?.policyDocument}),s="TeamsEmergencyCallingRoutingPolicy")}const a=r?`Created Emergency policy using ${s}`:"This is NOT an emergency call";return this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{phrase:"Deriving Emergency policy from ACS MiddleTier Service response was successful",code:0,subCode:220005}}),this._logger.info(`Deriving emergency policy message = ${a}. Emergency Content = ${t}`),t}catch(t){const i=new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:aE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,..._b(i)}}),i}}isFetchUserPoliciesAndSettingsApplicable(e,t){return $S(e)||$S(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(e){if(!$S(e))for(const t of e)if(t.dialString===this._userDialedPstnNumber||!$S(t.dialMask?.split(";").find((e=>e===this._userDialedPstnNumber))))return this._emergencyNumber=t.dialString,!0;return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e){if(!$S(e))for(const t of e)if(t.emergencyDialString===this._userDialedPstnNumber||!$S(t.emergencyDialMask?.split(";").find((e=>e===this._userDialedPstnNumber))))return this._emergencyNumber=t.emergencyDialString,!0;return!1}verifyFetchUserPoliciesSettings(e,t){const i=vy().MiddleTier;return i.enabled?i.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!x(t[0]))?(this._logger.info("Target particpant (Callee) is not a PSTN Number"),!1):Array.isArray(t)||x(t)?(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"),i.userPolicySettingsApi):(this._logger.info("ACS MiddleTier service is disabled"),i.enabled)}isSecurityDeskEnabled(){const e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!($S(e?.notificationGroup)&&$S(e?.notificationDialOutNumber)||0==e?.notificationGroup?.trim().length&&0==e?.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(e){let t={};return t=await this.getAcsMiddletierServiceRequestHeader(),t.onbehalfOfUser=e??this._localParticipant,t}sendMiddleTierPolicyEvent(e,t){try{this.setDefaultEventData(e,t),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this._logger.debug("Unable to send AcsMiddleTierPolicyService telemetry")}}sendMiddleTierApiEvent(e){try{this.setDefaultEventData(e),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this._logger.debug("Unable to send MiddleTier Api telemetry")}}setDefaultEventData(e,t){e.callId=this._callId,e.localParticipantId=this._localParticipant,e.requestedParticipantMRI=t??this._localParticipant,e.timestampInfo=e.timestampInfo??"",e.additionalDetails=e.additionalDetails??""}}class mO{constructor(e){this._logger=e}get gpu(){const e={};try{const t=document.createElement("canvas"),i=t.getContext("webgl")||t.getContext("experimental-webgl");if(i){const t=i.getExtension("WEBGL_debug_renderer_info");t?(e.vendor=i.getParameter(t.UNMASKED_VENDOR_WEBGL),e.renderer=i.getParameter(t.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(e){this._logger?.info(`Unable to get GPU info: ${e}`)}return e}get hardwareConcurrency(){return navigator.hardwareConcurrency}}var fO;!function(e){e.deviceSelection="deviceSelection",e.handleIncomingCall="handleIncomingCall"}(fO||(fO={}));var vO,SO=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},yO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let CO=1;class TO{get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,i,n,r,s,a){this._callClient=e,this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async e=>{const t=+new Date;let i;try{if(this.sendTokenChangedEvent({kindOfEvent:"attempt",timestampInfo:{attemptTimestamp:t},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new le({defaultError:ee.CALL_AGENT.GET_TOKEN_BEFORE_INIT});i=await Oy(this._communicationTokenCredential,vy().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),i.acsResourceId===this._parsedTokenCredential?.acsResourceId&&i.identityMri===this._parsedTokenCredential?.identityMri||Ry(ee.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState("invalidToken"),this._disposed||await this.dispose(),Ry(ee.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));const n=+new Date;return this.sendTokenChangedEvent({kindOfEvent:"success",timestampInfo:{deltaTimeInMs:n-t},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:i.exp,isTokenChanged:this._oldToken!==i.jwtToken}),this._oldToken=i.jwtToken,this._oldTokenExpiration=i.exp,i.jwtToken}catch(e){const n={kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-t},oldTokenExpiration:this._oldTokenExpiration};throw i&&(n.newTokenExpiration=i.exp,n.isTokenChanged=this._oldToken!==i.jwtToken,this._oldToken=i.jwtToken,this._oldTokenExpiration=i.exp),this.sendTokenChangedEvent(n,e),e}},this.sendTokenChangedEvent=(e,t)=>{try{let i={kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,oldTokenExpiration:e.oldTokenExpiration};void 0!==e.newTokenExpiration&&(i.newTokenExpiration=e.newTokenExpiration),void 0!==e.isTokenChanged&&(i.isTokenChanged=e.isTokenChanged),t&&(i={...i,..._b(t)}),this._telemetryLogManager.sendEvent({name:aE.acs_calling_token_expiration_changed,tenant:xv,properties:i})}catch(e){this.logger.debug("Unable to send token change telemetry")}},this.pushHandlingStarted=e=>{const t=Mf();this._pushHandlingDeltaTimeInMs.set(e,{correlationId:t,timestamp:+new Date}),this.logger.log("Incoming call state started",e),pI.setCauseIdToNetworkInfo(e),this.sendIncomingNotificationEvent({eventName:aE.acs_calling_client_operations,operation:fO.handleIncomingCall,networkInfo:[],kindOfEvent:"attempt",timestampInfo:{deltaTimeInMs:void 0},correlationId:t,additionalDetails:{},callId:"",participantId:""})},this.pushHandlingEnded=(e,t)=>{const i=void 0!==t?.code&&[0,200].includes(t?.code);this.logger.log("Incoming call state ended",e,t);const n=pI.getRemoveCauseIdToNetworkInfo(e),r=this._pushHandlingDeltaTimeInMs.get(e)?.correlationId||"unknown",s=(e=>{if(i)return new le({defaultError:{code:e?.code??0,subCode:e?.subCode??0,message:"Success",resultCategories:["Success"]}});const t=[ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,ee.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS],n=Z.find(t,(t=>t.subCode===e?.subCode))??ee.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA;return new le({defaultError:n})})(t);this.sendIncomingNotificationEvent({eventName:aE.acs_calling_client_operations,operation:fO.handleIncomingCall,networkInfo:n||[],kindOfEvent:i?"success":"failure",timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(e)?+new Date-this._pushHandlingDeltaTimeInMs.get(e)?.timestamp:void 0},correlationId:r,additionalDetails:{..._b(s)},callId:t.callId||"",participantId:t.participantId||""}),this._pushHandlingDeltaTimeInMs.delete(e),this._eventEmitter.emit("handleIncomingCall",{callId:t.callId||"",participantId:t.participantId||"",...Ib({code:s.code,subCode:s.subCode,message:s.message,resultCategories:s.resultCategories})})},this.logger=t.createChild("CallAgent"+CO++),this._telemetryLogManager=n,this._kind=s,this._connectionState="Disconnected",this._eventEmitter=new T_(this.logger),this._internalEventEmitter=new OE.EventEmitter,this.clientId=i,this._abortController=new AbortController,this._maxDisplayNameLength=vy()?.calling?.maxDisplayNameLength||256,this._oldToken="",this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=vy()?.calling?.maxNumberOfTokenFetchRetries||10,this._callStack=r,this.acsProxy=this._callClient.acsProxy,this.acsCustomRelayManager=this._callClient.acsCustomRelayManager,this._httpRequestHelper=new hO(this.logger,this.acsProxy),this.mtPolicyService=new pO(this._httpRequestHelper),this._parsedTokenCredential={jwtToken:"",acsResourceId:void 0,identityMri:"",cloudType:Of.Public,isCte:!1,region:"",rgnClaimExists:!1,exp:0},this._caConfigBag={clientId:"",acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isCte?wv.Enterprise:wv.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1},this.deviceManager=a,this._extensibleApi=new nb(this.logger,{callClient:this._callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});const o=lD(YE.CallAgentFeature);for(const e of o)"OnExtendedObjectConstructor"===e.activationOptions.activationEvent&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState("trouterChanged")},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState("registrarChanged")}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():"Unknown"}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}onDisposed(e){this._internalEventEmitter.on("disposed",e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||""}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||""}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}async initialize(e,t){const i=+new Date,n=new mO(this.logger),r={gpu:n.gpu,hardwareConcurrency:n.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(aE.acs_calling_call_agent_init_attempt,{attemptTimestamp:i},r),this._communicationTokenCredential=e,this._parsedTokenCredential=await Oy(e,vy().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==de.TeamsCallAgent||this._parsedTokenCredential.isCte?this._kind===de.CallAgent&&this._parsedTokenCredential.isCte&&Ry(ee.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):Ry(ee.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),t?.displayName){if(this._parsedTokenCredential.isCte)throw new le({defaultError:ee.CALL_AGENT.CTE_DISPLAY_NAME});if(t?.displayName.length>this._maxDisplayNameLength)throw new le({defaultError:ee.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===Of.Public&&(!this._parsedTokenCredential.region||""===this._parsedTokenCredential.region)){try{const e=+new Date-i;this._telemetryLogManager.sendEvent({name:aE.acs_calling_token_has_no_data_location,tenant:xv,properties:{deltaTimeInMs:e}})}catch(e){this.logger.debug("Unable to send token has no data location assigned")}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?Pv[0]:Av[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.isCte?wv.Enterprise:wv.Consumer,emergencyCountryCode:t?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!t?.emergencyCallOptions?.countryCode},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this._callClient.getEnvironmentInfoInternal()}catch(e){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(e)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||""}`)}await this.setUserPoliciesOnAgentInitialization(),this.isCteUser()&&(t={...t,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,t),this.registerConnectionStateEventHandlers();const n=+new Date;this.sendCallAgentInitializiedEvent(aE.acs_calling_call_agent_init_success,{deltaTimeInMs:n-i},r)}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);const t=new le({defaultError:ee.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);const n=+new Date;throw this.sendCallAgentInitializiedEvent(aE.acs_calling_call_agent_init_failure,{deltaTimeInMs:n-i},r,t),this._telemetryLogManager.clearTelemetryLoggers(),t}}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isCteUser(){return void 0!==this._parsedTokenCredential?.isCte&&this._parsedTokenCredential?.isCte}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}async createTransferTargetCall(e){const t=X.generateCauseId(),i=Mf(),n=Mf(),r=await this._tsCallRegistry.createCallAsync({callId:i,localParticipantId:n,causeId:t,type:"ThreadId",threadId:""}),s=this.createNewCall(i,r);return this.addToCallArray(s),this.handleCallState(s),r.addParticipant(e.targetMri).catch((()=>{this.logger.error("Failed to add participant for transer call")})),MI(r)?await Promise.all(s.bindTsCall()):s.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[s],removed:[]}),s}async subscribeCallWithoutModality(e){const t=X.generateCauseId(),i=await this._tsCallRegistry.createCallAsync({callId:e.callId,localParticipantId:e.participantId,causeId:t,type:"ThreadId",threadId:e.threadId,messageId:e.messageId}),n=this.createNewCall(e.callId,i),r={conversationUrl:e.meetingUrl,conversationId:e.callId};return this.addToCallArray(n),this.handleCallState(n),i.joinCallWithoutCallModality(r,{},t).then((()=>{this.logger.info("Successfully joined call without modalities")})).catch((e=>{throw this.logger.error("Error while joining call without modalities",e),new le({defaultError:ee.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:e})})),MI(i)?await Promise.all(n.bindTsCall()):n.bindTsCall(),n}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){const t=Mf(),i=+new Date;let n;try{if(this.sendHandlePushNotificationEvent({eventName:aE.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:"",localParticipantId:"",kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),!e.incomingCallContext)throw new le({defaultError:ee.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});n=new gO(e,this._tsCallRegistry,this.logger),await n.process(),this.sendHandlePushNotificationEvent({eventName:aE.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:n.callId,localParticipantId:n.localParticipantId,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:""})}catch(e){const r=new le({defaultError:ee.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:aE.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:n?.callId||"",localParticipantId:n?.localParticipantId||"",kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{failureReason:r.message,code:r.code,..._b(r)}}),r}}getDeviceType(){const e=this._callClient?.firstPartyOptions?.acsDeviceType;return e?CS[e]:"default"}isWatermarkSupported(){return this.isCteUser()?vy().calling.watermark.watermarkEnabledForCteUsers:vy().calling.watermark.watermarkEnabledForAcsUsers}trackCallEndTimeToStopTelemetry(e){0===e.length?mE.callEndTimestamp=Date.now():mE.callEndTimestamp=Number.MAX_SAFE_INTEGER}updateConnectionState(e){const t=this.getCallAgentConnectionState(),i=this.getTrouterState(),n=this._callStack?.isRegistered()?"Connected":"Disconnected",r="Connected"===t?void 0:"invalidToken"==e?"invalidToken":"connectionIssue";if(this.sendCallAgentInfoEvent({eventName:aE.acs_calling_call_agent,additionalDetails:{step:"connectionState-changed",oldState:this._connectionState,newState:t,trouterState:i,registrarState:n,reason:r,connectionStateSource:e}}),t!==this._connectionState||r!==this._connectionStateReason){const e={oldValue:this._connectionState,newValue:t,reason:r};this._connectionState=t,this._connectionStateReason=r,this._eventEmitter.emit("connectionStateChanged",e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{...e.additionalDetails}})}catch(e){this.logger.debug("Failed to send connection state changed event",e)}}sendCallAgentInitializiedEvent(e,t,i,n){try{let r="string"==typeof n?.message?n?.message:void 0;e!==aE.acs_calling_call_agent_init_failure&&(r=void 0);const s=n?_b(n):void 0,a=this.getEcsConfigIds();this._telemetryLogManager.sendEvent({name:e,tenant:xv,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:r,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:a.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:i},additionalDetails:{...s,firstPartyOptions:{isDeviceTypeEnabled:vy().calling.setDeviceType,deviceTypeRawStrlen:this._callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists}}})}catch(e){this.logger.debug("Unable to send telemtery")}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send handle push notification telemetry")}}async initializeCallRegistry(e,t){const i=t?.displayName,n=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,i);return this.logger.info(`registry created for version number=${US()}`),n}async getCallRegistry(e,t,i,n){const r={id:t.identityMri,displayName:n||"",tokenProvider:i},s=await e.createCallRegistry(r);await s.login(r);const a=vy()?.tsCalling?.accountConfiguration?.ring||void 0,o=t.isCte?wv.Enterprise:wv.Consumer,l=t.acsResourceId,c=t.region;let d={acsResourceId:l,clientType:o,ring:a};if(vy().calling.setDeviceType)d.deviceType=this.getDeviceType();else if(this._callClient.firstPartyOptions?.acsDeviceType)throw new le({defaultError:ee.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});const u=vy().calling.eudb;return u.isEnabled&&u.sendRegionToNgc&&(u.isRgnClaimEnabledForACS||t.isCte)&&(d={...d,region:c}),vy()?.calling.supportLiveStreaming&&(d.clientSupportsUms=!0),d.clientSupportsWatermark=this.isWatermarkSupported(),await s.setConfiguration(d),s.on("callAdded",this.handleCallAdded),s.on("callRemoved",this.handleCallRemoved),s.on("pushHandlingStarted",this.pushHandlingStarted),s.on("pushHandlingEnded",this.pushHandlingEnded),n&&await s.updateDisplayName(n),s}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await Oy(e,vy().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(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send incoming call notification telemetry")}}}SO([SI,yO("design:type",Object)],TO.prototype,"logger",void 0),SO([pe(KS.Initialize),yO("design:type",Function),yO("design:paramtypes",[Object,Object]),yO("design:returntype",Promise)],TO.prototype,"initialize",null),SO([ge(KS.Feature),yO("design:type",Function),yO("design:paramtypes",[Object]),yO("design:returntype","function"==typeof(vO="undefined"!=typeof TFeature&&TFeature)?vO:Object)],TO.prototype,"feature",null),SO([pe(KS.HandlePushNotification),yO("design:type",Function),yO("design:paramtypes",[Object]),yO("design:returntype",Promise)],TO.prototype,"handlePushNotification",null);class EO{constructor(e){this._call=e}setTarget(e){this._call=e}getTarget(){return this._call}startVideo(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setConstraints(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}function bO(e){const t=new EO(e);return new Proxy({},{get:(e,i)=>{let n,r;const s=t.getTarget();if(i in t)n=t[i],r=t;else{if(void 0===s)throw new le({defaultError:ee.FEATURES.VDI3.CALL_INITIALIZING});if(!(i in s))return;n=s[i],r=s}return"function"==typeof n?function(...e){return n.apply(r,e)}:n},has:(e,i)=>{const n=t.getTarget();return i in t||void 0!==n&&i in n}})}var _O=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},IO=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class wO extends TO{get calls(){return this._calls}constructor(e,t,i,n,r,s,a){super(e,t,n,r,i,de.CallAgent,s),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);const t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){const e=vy().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit("callsUpdated",{added:[],removed:[t]}),this.logger.info("call removed")}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){const t=e.on("callStateChanged",(async()=>{if(1===e.state){const i=MI(e),n=e.callId;t.dispose();let r=new oO({callId:n,isIncoming:!0},this,e,this._telemetryLogManager);i&&(r=bO(r));const s=new uO(r);this.handleCallState(r),i?await Promise.all(r.bindTsCall()):r.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:s})}}))}},this.handleCallState=e=>{e.on("stateChanged",(async()=>{try{"Disconnected"===e.state?this.tsStack?(await(this._tsCallRegistry.deleteCallAsync?.(e.tsCall))||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry"):"Connecting"===e.state&&"Incoming"==e.direction&&(this.addToCallArray(e),this._eventEmitter.emit("callsUpdated",{added:[e],removed:[]}))}catch(e){this.logger.error("Failed to handle call state changed event")}}))},this.displayName=a?.displayName}addToCallAgentsMap(e){wO.callAgents.get(e?.identityMri)&&Ry(ee.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),wO.callAgents.set(e?.identityMri,this)}removeFromCallAgentsMap(e){e?.identityMri&&wO.callAgents.get(e?.identityMri)===this&&wO.callAgents.delete(e?.identityMri)}disposeCall(e){const t=this._calls.indexOf(e);-1!==t&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(e){try{const t=await Oy(e,vy().calling.eudb.isRgnClaimEnabledForACS);return wO.callAgents.get(t.identityMri)}catch(e){throw new le({defaultError:ee.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){const i=new oO({callId:e},this,t,this._telemetryLogManager);return MI(t)?bO(i):i}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}startCall(e,t){const i=Mf(),n=+new Date,r={correlationId:i,timestampInfo:{attemptTimestamp:n}};this._telemetryLogManager.sendEvent({name:aE.acs_calling_call_attempt,tenant:xv,properties:r},void 0,"attempt");try{if(this.assertCallUserIds(e),t?.alternateCallerId&&NS(t.alternateCallerId),e.find((e=>DS(e)===this.getUserMri())))throw new le({defaultError:ee.CALL_AGENT.CANT_CALL_YOURSELF});let r=t?.audioOptions?.muted;return void 0===r&&(r=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${r}`),this.createCall({participants:e,startCallOptions:t},{correlationId:i,attemptTimestamp:n})}catch(e){let t,r;throw e instanceof le&&(t="string"==typeof e?.message?e?.message:void 0,r={..._b(e)}),this._telemetryLogManager.sendEvent({name:aE.acs_calling_call_failed,tenant:xv,properties:{correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-n},failureReason:t||"",additionalDetails:r||{}}},void 0,"failure"),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(i)}}join(e,t){if(!Vy(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let i=t?.audioOptions?.muted;return void 0===i&&(i=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${i}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){if(this._disposed)throw new le({defaultError:ee.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&wO.callAgents.delete(this._parsedTokenCredential?.identityMri);try{const e=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(e))}catch(e){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(e,t){if("handleIncomingCall"!==e&&"incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new le({defaultError:ee.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("handleIncomingCall"!==e&&"incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new le({defaultError:ee.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&"meshV2"!==this.getDeviceType())throw new le({defaultError:ee.CALL_AGENT.MESH_DEVICETYPE_V2});if(!this.tsStack)throw new le({defaultError:ee.CALL_AGENT.STACK_NOT_INIT});let i,n,r,s=e?.callContext?.threadId||e?.startCallOptions?.threadId,a=!1,o=e?.callContext?.groupId;const l=e?.callContext?.roomId,c=e?.callContext?.meetingLink,d=e?.callContext?.meetingId,u=e?.callContext?.passcode||"";if(o&&o.startsWith("19:")&&(s=o,o=""),c)if(QM(c))n=eD(c);else{if(!ZM(c,this.logger))throw new le({defaultError:ee.CALL_AGENT.INVALID_MEETING_LINK});if(XM(c.trim().toLocaleLowerCase(),vy().calling.tfl.hosts)&&!vy().calling.tfl.isEnabled)throw new le({defaultError:ee.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});a=!0}e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(n={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():"0",organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),n&&(r={meetingType:"0"===n.messageId?1:2,tenantId:n.tenantId,organizerId:n.organizerId,replyChainMessageId:n.messageId}||void 0,s=n.threadId,i=n.messageId);const h=X.generateCauseId(),g=Mf(),p=Mf(),m={threadId:s||"",messageId:i||"",meetingInfo:r,mediaPeerType:2};let f=!1;if(MI(this._tsCallRegistry)){const n=bO();return(async()=>{let r;o?r=await this._tsCallRegistry.createCallAsync({type:"GroupId",groupId:o,callId:g,localParticipantId:p,causeId:h}):d?r=await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:p,causeId:h,type:"MeetingData",meetingData:{meetingCode:d,passcode:u,threadId:s}}):l?r=await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:p,causeId:h,type:"MeetingData",meetingData:{meetingCode:l}}):a?r=await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:p,causeId:h,type:"MeetingData",meetingData:{meetingUrl:c}}):(f=!!e?.participants&&e.participants.length>=2&&Hy(e.participants,this.kind),vy().calling.enableSmePassFakeConversation&&!s&&f&&(s=`${re}${Mf()}`),r=await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:p,causeId:h,type:"ThreadId",threadId:s||"",messageId:i}));const v=new oO({callId:g,roomId:l},this,r,this._telemetryLogManager,f);n.setTarget(v),this.addToCallArray(n),this.handleCallState(n),e?.participants&&e?.participants.forEach((e=>{r.addParticipant(DS(e)).catch((()=>{this.logger.error("Failed to add participant during call start")}))}));const S=jT();v.startCallInternal(e?.startCallOptions,!!d||!!l,e?.callContext,m,t,S).catch(My),await Promise.all(v.bindTsCall()),await S.promise,this._eventEmitter.emit("callsUpdated",{added:[n],removed:[]})})().catch((e=>{})),n}{let n,r=!1;o?n=this._tsCallRegistry.createCallWithGroupId(o,g,p,h):d?n=this._tsCallRegistry.createCallWithMeetingData({meetingCode:d,passcode:u,threadId:s},g,p,h):l?n=this._tsCallRegistry.createCallWithMeetingData({meetingCode:l},g,p,h):a?n=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:c},g,p,h):(r=!!e?.participants&&e.participants.length>=2&&Hy(e.participants,this.kind),vy().calling.enableSmePassFakeConversation&&!s&&r&&(s=`${re}${Mf()}`),n=this._tsCallRegistry.createCall(s||"",g,p,i,h));const f=new oO({callId:g,roomId:l},this,n,this._telemetryLogManager,r);return this.addToCallArray(f),this.handleCallState(f),e?.participants&&e?.participants.forEach((e=>{n.addParticipant(DS(e)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),f.startCallInternal(e?.startCallOptions,!!d||!!l,e?.callContext,m,t).catch(My),f.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[f],removed:[]}),f}}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new le({defaultError:ee.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}assertCallUserIds(e){Ay(e,ee.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),wy(e,ee.CALL_AGENT.USERIDS_CANNOT_BE_NULL),function(e){if(!(e instanceof Array))throw new le({defaultError:ee.IDENTIFIER.INVALID_IDENTIFIER_ARRAY})}(e),e.forEach((e=>{const t=NS(e);if(!Vy(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}}wO.callAgents=new Map,_O([ge(KS.StartCall),IO("design:type",Function),IO("design:paramtypes",[Array,Object]),IO("design:returntype",Object)],wO.prototype,"startCall",null),_O([ge(KS.Join),IO("design:type",Function),IO("design:paramtypes",[Object,Object]),IO("design:returntype",Object)],wO.prototype,"join",null),_O([pe(KS.Dispose),IO("design:type",Function),IO("design:paramtypes",[]),IO("design:returntype",Promise)],wO.prototype,"dispose",null);var AO=G((function(e,t){var i=window;!function(t,i){e.exports=i()}(0,((e,t)=>{var n={},r={exports:n},s=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,c=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[l(e)[0]])((t={exports:{}}).exports,t),t.exports},h=(e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of l(t))d.call(e,r)||r===i||a(e,r,{get:()=>t[r],enumerable:!(n=o(t,r))||n.enumerable});return e},g=(e,t,i)=>(i=null!=e?s(c(e)):{},h(!t&&e&&e.__esModule?i:a(i,"default",{value:e,enumerable:!0}),e)),p=u({"../node_modules/lodash.clonedeep/index.js"(e,t){var n="__lodash_hash_undefined__",r=9007199254740991,s="[object Arguments]",a="[object Boolean]",o="[object Date]",l="[object Function]",c="[object GeneratorFunction]",d="[object Map]",u="[object Number]",h="[object Object]",g="[object Promise]",p="[object RegExp]",m="[object Set]",f="[object String]",v="[object Symbol]",S="[object WeakMap]",y="[object ArrayBuffer]",C="[object DataView]",T="[object Float32Array]",E="[object Float64Array]",b="[object Int8Array]",_="[object Int16Array]",I="[object Int32Array]",w="[object Uint8Array]",A="[object Uint8ClampedArray]",P="[object Uint16Array]",R="[object Uint32Array]",M=/\w*$/,D=/^\[object .+?Constructor\]$/,k=/^(?:0|[1-9]\d*)$/,O={};O[s]=O["[object Array]"]=O[y]=O[C]=O[a]=O[o]=O[T]=O[E]=O[b]=O[_]=O[I]=O[d]=O[u]=O[h]=O[p]=O[m]=O[f]=O[v]=O[w]=O[A]=O[P]=O[R]=!0,O["[object Error]"]=O[l]=O[S]=!1;var N="object"==typeof i&&i&&i.Object===Object&&i,L="object"==typeof self&&self&&self.Object===Object&&self,x=N||L||Function("return this")(),F="object"==typeof e&&e&&!e.nodeType&&e,U=F&&"object"==typeof t&&t&&!t.nodeType&&t,B=U&&U.exports===F;function V(e,t){return e.set(t[0],t[1]),e}function H(e,t){return e.add(t),e}function $(e,t,i,n){var r=-1,s=e?e.length:0;for(n&&s&&(i=e[++r]);++r<s;)i=t(i,e[r],r,e);return i}function j(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function G(e){var t=-1,i=Array(e.size);return e.forEach((function(e,n){i[++t]=[n,e]})),i}function q(e,t){return function(i){return e(t(i))}}function z(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}var W,K=Array.prototype,J=Function.prototype,Y=Object.prototype,Q=x["__core-js_shared__"],Z=(W=/[^.]+$/.exec(Q&&Q.keys&&Q.keys.IE_PROTO||""))?"Symbol(src)_1."+W:"",X=J.toString,ee=Y.hasOwnProperty,te=Y.toString,ie=RegExp("^"+X.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=B?x.Buffer:void 0,re=x.Symbol,se=x.Uint8Array,ae=q(Object.getPrototypeOf,Object),oe=Object.create,le=Y.propertyIsEnumerable,ce=K.splice,de=Object.getOwnPropertySymbols,ue=ne?ne.isBuffer:void 0,he=q(Object.keys,Object),ge=xe(x,"DataView"),pe=xe(x,"Map"),me=xe(x,"Promise"),fe=xe(x,"Set"),ve=xe(x,"WeakMap"),Se=xe(Object,"create"),ye=$e(ge),Ce=$e(pe),Te=$e(me),Ee=$e(fe),be=$e(ve),_e=re?re.prototype:void 0,Ie=_e?_e.valueOf:void 0;function we(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Ae(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Pe(e){var t=-1,i=e?e.length:0;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Re(e){this.__data__=new Ae(e)}function Me(e,t,i){var n=e[t];ee.call(e,t)&&je(n,i)&&(void 0!==i||t in e)||(e[t]=i)}function De(e,t){for(var i=e.length;i--;)if(je(e[i][0],t))return i;return-1}function ke(e,t,i,n,r,a,o){var d;if(n&&(d=a?n(e,r,a,o):n(e)),void 0!==d)return d;if(!Ke(e))return e;var u=Ge(e);if(u){if(d=function(e){var t=e.length,i=e.constructor(t);return t&&"string"==typeof e[0]&&ee.call(e,"index")&&(i.index=e.index,i.input=e.input),i}(e),!t)return function(e,t){var i=-1,n=e.length;for(t||(t=Array(n));++i<n;)t[i]=e[i];return t}(e,d)}else{var g=Ue(e),p=g==l||g==c;if(ze(e))return function(e,t){if(t)return e.slice();var i=new e.constructor(e.length);return e.copy(i),i}(e,t);if(g==h||g==s||p&&!a){if(j(e))return a?e:{};if(d=function(e){return"function"!=typeof e.constructor||He(e)?{}:function(e){return Ke(e)?oe(e):{}}(ae(e))}(p?{}:e),!t)return function(e,t){return Ne(e,Fe(e),t)}(e,function(e,t){return e&&Ne(t,Je(t),e)}(d,e))}else{if(!O[g])return a?e:{};d=Be(e,g,ke,t)}}o||(o=new Re);var m=o.get(e);if(m)return m;if(o.set(e,d),!u)var f=i?function(e){return function(e,t,i){var n=t(e);return Ge(e)?n:function(e,t){for(var i=-1,n=t.length,r=e.length;++i<n;)e[r+i]=t[i];return e}(n,i(e))}(e,Je,Fe)}(e):Je(e);return function(e,t){for(var i=-1,n=e?e.length:0;++i<n&&!1!==t(e[i],i););}(f||e,(function(r,s){f&&(r=e[s=r]),Me(d,s,ke(r,t,i,n,s,e,o))})),d}function Oe(e){var t=new e.constructor(e.byteLength);return new se(t).set(new se(e)),t}function Ne(e,t,i,n){i||(i={});for(var r=-1,s=t.length;++r<s;){var a=t[r],o=n?n(i[a],e[a],a,i,e):void 0;Me(i,a,void 0===o?e[a]:o)}return i}function Le(e,t){var i=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?i["string"==typeof t?"string":"hash"]:i.map}function xe(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return function(e){return!(!Ke(e)||function(e){return!!Z&&Z in e}(e))&&(We(e)||j(e)?ie:D).test($e(e))}(i)?i:void 0}we.prototype.clear=function(){this.__data__=Se?Se(null):{}},we.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},we.prototype.get=function(e){var t=this.__data__;if(Se){var i=t[e];return i===n?void 0:i}return ee.call(t,e)?t[e]:void 0},we.prototype.has=function(e){var t=this.__data__;return Se?void 0!==t[e]:ee.call(t,e)},we.prototype.set=function(e,t){return this.__data__[e]=Se&&void 0===t?n:t,this},Ae.prototype.clear=function(){this.__data__=[]},Ae.prototype.delete=function(e){var t=this.__data__,i=De(t,e);return!(i<0||(i==t.length-1?t.pop():ce.call(t,i,1),0))},Ae.prototype.get=function(e){var t=this.__data__,i=De(t,e);return i<0?void 0:t[i][1]},Ae.prototype.has=function(e){return De(this.__data__,e)>-1},Ae.prototype.set=function(e,t){var i=this.__data__,n=De(i,e);return n<0?i.push([e,t]):i[n][1]=t,this},Pe.prototype.clear=function(){this.__data__={hash:new we,map:new(pe||Ae),string:new we}},Pe.prototype.delete=function(e){return Le(this,e).delete(e)},Pe.prototype.get=function(e){return Le(this,e).get(e)},Pe.prototype.has=function(e){return Le(this,e).has(e)},Pe.prototype.set=function(e,t){return Le(this,e).set(e,t),this},Re.prototype.clear=function(){this.__data__=new Ae},Re.prototype.delete=function(e){return this.__data__.delete(e)},Re.prototype.get=function(e){return this.__data__.get(e)},Re.prototype.has=function(e){return this.__data__.has(e)},Re.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Ae){var n=i.__data__;if(!pe||n.length<199)return n.push([e,t]),this;i=this.__data__=new Pe(n)}return i.set(e,t),this};var Fe=de?q(de,Object):function(){return[]},Ue=function(e){return te.call(e)};function Be(e,t,i,n){var r=e.constructor;switch(t){case y:return Oe(e);case a:case o:return new r(+e);case C:return function(e,t){var i=t?Oe(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.byteLength)}(e,n);case T:case E:case b:case _:case I:case w:case A:case P:case R:return function(e,t){var i=t?Oe(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)}(e,n);case d:return function(e,t,i){return $(t?i(G(e),!0):G(e),V,new e.constructor)}(e,n,i);case u:case f:return new r(e);case p:return function(e){var t=new e.constructor(e.source,M.exec(e));return t.lastIndex=e.lastIndex,t}(e);case m:return function(e,t,i){return $(t?i(z(e),!0):z(e),H,new e.constructor)}(e,n,i);case v:return function(e){return Ie?Object(Ie.call(e)):{}}(e)}}function Ve(e,t){return!!(t=null==t?r:t)&&("number"==typeof e||k.test(e))&&e>-1&&e%1==0&&e<t}function He(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Y)}function $e(e){if(null!=e){try{return X.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function je(e,t){return e===t||e!=e&&t!=t}(ge&&Ue(new ge(new ArrayBuffer(1)))!=C||pe&&Ue(new pe)!=d||me&&Ue(me.resolve())!=g||fe&&Ue(new fe)!=m||ve&&Ue(new ve)!=S)&&(Ue=function(e){var t=te.call(e),i=t==h?e.constructor:void 0,n=i?$e(i):void 0;if(n)switch(n){case ye:return C;case Ce:return d;case Te:return g;case Ee:return m;case be:return S}return t});var Ge=Array.isArray;function qe(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=r}(e.length)&&!We(e)}var ze=ue||function(){return!1};function We(e){var t=Ke(e)?te.call(e):"";return t==l||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Je(e){return qe(e)?function(e,t){var i=Ge(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&qe(e)}(e)&&ee.call(e,"callee")&&(!le.call(e,"callee")||te.call(e)==s)}(e)?function(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n}(e.length,String):[],n=i.length,r=!!n;for(var a in e)!t&&!ee.call(e,a)||r&&("length"==a||Ve(a,n))||i.push(a);return i}(e):function(e){if(!He(e))return he(e);var t=[];for(var i in Object(e))ee.call(e,i)&&"constructor"!=i&&t.push(i);return t}(e)}t.exports=function(e){return ke(e,!0,!0)}}}),m=u({"../skype-calling-pluginless/dist/skype-calling-pluginless.bundle.js"(e,t){var i,n,r=window;i=e,n=(e,t)=>{var i={},n={exports:i},s=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,c=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[l(e)[0]])((t={exports:{}}).exports,t),t.exports},h=(e,t)=>{for(var i in t)a(e,i,{get:t[i],enumerable:!0})},g=(e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of l(t))d.call(e,r)||r===i||a(e,r,{get:()=>t[r],enumerable:!(n=o(t,r))||n.enumerable});return e},p=(e,t,i)=>(i=null!=e?s(c(e)):{},g(!t&&e&&e.__esModule?i:a(i,"default",{value:e,enumerable:!0}),e)),m=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?o(t,i):t,l=e.length-1;l>=0;l--)(r=e[l])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&a(t,i,s),s},f=(e,t)=>(i,n)=>t(i,n,e),v=u({"../node_modules/axios/lib/helpers/bind.js"(e,t){t.exports=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}}}}),S=u({"../node_modules/axios/lib/utils.js"(e,t){var i=v(),n=Object.prototype.toString;function r(e){return"[object Array]"===n.call(e)}function s(e){return void 0===e}function a(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===n.call(e)}function l(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),r(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}t.exports={isArray:r,isArrayBuffer:function(e){return"[object ArrayBuffer]"===n.call(e)},isBuffer:function(e){return null!==e&&!s(e)&&null!==e.constructor&&!s(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:a,isUndefined:s,isDate:function(e){return"[object Date]"===n.call(e)},isFile:function(e){return"[object File]"===n.call(e)},isBlob:function(e){return"[object Blob]"===n.call(e)},isFunction:o,isStream:function(e){return a(e)&&o(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:l,merge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]=i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},deepMerge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]="object"==typeof i?e({},i):i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},extend:function(e,t,n){return l(t,(function(t,r){e[r]=n&&"function"==typeof t?i(t,n):t})),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}}}}),y=u({"../node_modules/axios/lib/helpers/buildURL.js"(e,t){var i=S();function n(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(e,t,r){if(!t)return e;var s;if(r)s=r(t);else if(i.isURLSearchParams(t))s=t.toString();else{var a=[];i.forEach(t,(function(e,t){null!=e&&(i.isArray(e)?t+="[]":e=[e],i.forEach(e,(function(e){i.isDate(e)?e=e.toISOString():i.isObject(e)&&(e=JSON.stringify(e)),a.push(n(t)+"="+n(e))})))})),s=a.join("&")}if(s){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}}}),C=u({"../node_modules/axios/lib/core/InterceptorManager.js"(e,t){var i=S();function n(){this.handlers=[]}n.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},n.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},n.prototype.forEach=function(e){i.forEach(this.handlers,(function(t){null!==t&&e(t)}))},t.exports=n}}),T=u({"../node_modules/axios/lib/core/transformData.js"(e,t){var i=S();t.exports=function(e,t,n){return i.forEach(n,(function(i){e=i(e,t)})),e}}}),E=u({"../node_modules/axios/lib/cancel/isCancel.js"(e,t){t.exports=function(e){return!(!e||!e.__CANCEL__)}}}),b=u({"../node_modules/axios/lib/helpers/normalizeHeaderName.js"(e,t){var i=S();t.exports=function(e,t){i.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))}}}),_=u({"../node_modules/axios/lib/core/enhanceError.js"(e,t){t.exports=function(e,t,i,n,r){return e.config=t,i&&(e.code=i),e.request=n,e.response=r,e.isAxiosError=!0,e.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}},e}}}),I=u({"../node_modules/axios/lib/core/createError.js"(e,t){var i=_();t.exports=function(e,t,n,r,s){var a=new Error(e);return i(a,t,n,r,s)}}}),w=u({"../node_modules/axios/lib/core/settle.js"(e,t){var i=I();t.exports=function(e,t,n){var r=n.config.validateStatus;!r||r(n.status)?e(n):t(i("Request failed with status code "+n.status,n.config,null,n.request,n))}}}),A=u({"../node_modules/axios/lib/helpers/isAbsoluteURL.js"(e,t){t.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}}}),P=u({"../node_modules/axios/lib/helpers/combineURLs.js"(e,t){t.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}}}),R=u({"../node_modules/axios/lib/core/buildFullPath.js"(e,t){var i=A(),n=P();t.exports=function(e,t){return e&&!i(t)?n(e,t):t}}}),M=u({"../node_modules/axios/lib/helpers/parseHeaders.js"(e,t){var i=S(),n=["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"];t.exports=function(e){var t,r,s,a={};return e?(i.forEach(e.split("\n"),(function(e){if(s=e.indexOf(":"),t=i.trim(e.substr(0,s)).toLowerCase(),r=i.trim(e.substr(s+1)),t){if(a[t]&&n.indexOf(t)>=0)return;a[t]="set-cookie"===t?(a[t]?a[t]:[]).concat([r]):a[t]?a[t]+", "+r:r}})),a):a}}}),D=u({"../node_modules/axios/lib/helpers/isValidXss.js"(e,t){t.exports=function(e){return/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi.test(e)}}}),k=u({"../node_modules/axios/lib/helpers/isURLSameOrigin.js"(e,t){var i=S(),n=D();t.exports=i.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function s(e){var i=e;if(n(e))throw new Error("URL contains XSS injection attempt");return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=s(window.location.href),function(t){var n=i.isString(t)?s(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}}}),O=u({"../node_modules/axios/lib/helpers/cookies.js"(e,t){var i=S();t.exports=i.isStandardBrowserEnv()?{write:function(e,t,n,r,s,a){var o=[];o.push(e+"="+encodeURIComponent(t)),i.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),i.isString(r)&&o.push("path="+r),i.isString(s)&&o.push("domain="+s),!0===a&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}}),N=u({"../node_modules/axios/lib/adapters/xhr.js"(e,t){var i=S(),n=w(),r=y(),s=R(),a=M(),o=k(),l=I();t.exports=function(e){return new Promise((function(t,c){var d=e.data,u=e.headers;i.isFormData(d)&&delete u["Content-Type"];var h=new XMLHttpRequest;if(e.auth){var g=e.auth.username||"",p=e.auth.password||"";u.Authorization="Basic "+btoa(g+":"+p)}var m=s(e.baseURL,e.url);if(h.open(e.method.toUpperCase(),r(m,e.params,e.paramsSerializer),!0),h.timeout=e.timeout,h.onreadystatechange=function(){if(h&&4===h.readyState&&(0!==h.status||h.responseURL&&0===h.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in h?a(h.getAllResponseHeaders()):null,r={data:e.responseType&&"text"!==e.responseType?h.response:h.responseText,status:h.status,statusText:h.statusText,headers:i,config:e,request:h};n(t,c,r),h=null}},h.onabort=function(){h&&(c(l("Request aborted",e,"ECONNABORTED",h)),h=null)},h.onerror=function(){c(l("Network Error",e,null,h)),h=null},h.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),c(l(t,e,"ECONNABORTED",h)),h=null},i.isStandardBrowserEnv()){var f=O(),v=(e.withCredentials||o(m))&&e.xsrfCookieName?f.read(e.xsrfCookieName):void 0;v&&(u[e.xsrfHeaderName]=v)}if("setRequestHeader"in h&&i.forEach(u,(function(e,t){void 0===d&&"content-type"===t.toLowerCase()?delete u[t]:h.setRequestHeader(t,e)})),i.isUndefined(e.withCredentials)||(h.withCredentials=!!e.withCredentials),e.responseType)try{h.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&h.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&h.upload&&h.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){h&&(h.abort(),c(e),h=null)})),void 0===d&&(d=null),h.send(d)}))}}}),L=u({"../node_modules/axios/lib/defaults.js"(e,t){var i=S(),n=b(),r={"Content-Type":"application/x-www-form-urlencoded"};function s(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var a={adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=N()),e}(),transformRequest:[function(e,t){return n(t,"Accept"),n(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(s(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(s(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};i.forEach(["delete","get","head"],(function(e){a.headers[e]={}})),i.forEach(["post","put","patch"],(function(e){a.headers[e]=i.merge(r)})),t.exports=a}}),x=u({"../node_modules/axios/lib/core/dispatchRequest.js"(e,t){var i=S(),n=T(),r=E(),s=L();function a(e){e.cancelToken&&e.cancelToken.throwIfRequested()}t.exports=function(e){return a(e),e.headers=e.headers||{},e.data=n(e.data,e.headers,e.transformRequest),e.headers=i.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),i.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||s.adapter)(e).then((function(t){return a(e),t.data=n(t.data,t.headers,e.transformResponse),t}),(function(t){return r(t)||(a(e),t&&t.response&&(t.response.data=n(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))}}}),F=u({"../node_modules/axios/lib/core/mergeConfig.js"(e,t){var i=S();t.exports=function(e,t){t=t||{};var n={},r=["url","method","params","data"],s=["headers","auth","proxy"],a=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];i.forEach(r,(function(e){void 0!==t[e]&&(n[e]=t[e])})),i.forEach(s,(function(r){i.isObject(t[r])?n[r]=i.deepMerge(e[r],t[r]):void 0!==t[r]?n[r]=t[r]:i.isObject(e[r])?n[r]=i.deepMerge(e[r]):void 0!==e[r]&&(n[r]=e[r])})),i.forEach(a,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])}));var o=r.concat(s).concat(a),l=Object.keys(t).filter((function(e){return-1===o.indexOf(e)}));return i.forEach(l,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])})),n}}}),U=u({"../node_modules/axios/lib/core/Axios.js"(e,t){var i=S(),n=y(),r=C(),s=x(),a=F();function o(e){this.defaults=e,this.interceptors={request:new r,response:new r}}o.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=a(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=[s,void 0],i=Promise.resolve(e);for(this.interceptors.request.forEach((function(e){t.unshift(e.fulfilled,e.rejected)})),this.interceptors.response.forEach((function(e){t.push(e.fulfilled,e.rejected)}));t.length;)i=i.then(t.shift(),t.shift());return i},o.prototype.getUri=function(e){return e=a(this.defaults,e),n(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},i.forEach(["delete","get","head","options"],(function(e){o.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}})),i.forEach(["post","put","patch"],(function(e){o.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}})),t.exports=o}}),B=u({"../node_modules/axios/lib/cancel/Cancel.js"(e,t){function i(e){this.message=e}i.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},i.prototype.__CANCEL__=!0,t.exports=i}}),V=u({"../node_modules/axios/lib/cancel/CancelToken.js"(e,t){var i=B();function n(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;e((function(e){n.reason||(n.reason=new i(e),t(n.reason))}))}n.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},n.source=function(){var e;return{token:new n((function(t){e=t})),cancel:e}},t.exports=n}}),H=u({"../node_modules/axios/lib/helpers/spread.js"(e,t){t.exports=function(e){return function(t){return e.apply(null,t)}}}}),$=u({"../node_modules/axios/lib/axios.js"(e,t){var i=S(),n=v(),r=U(),s=F();function a(e){var t=new r(e),s=n(r.prototype.request,t);return i.extend(s,r.prototype,t),i.extend(s,t),s}var o=a(L());o.Axios=r,o.create=function(e){return a(s(o.defaults,e))},o.Cancel=B(),o.CancelToken=V(),o.isCancel=E(),o.all=function(e){return Promise.all(e)},o.spread=H(),t.exports=o,t.exports.default=o}}),j=u({"../node_modules/axios/index.js"(e,t){t.exports=$()}}),G=u({"../node_modules/ua-parser-js/src/ua-parser.js"(e,t){!function(i,n){var r="function",s="undefined",a="object",o="string",l="major",c="model",d="name",u="type",h="vendor",g="version",p="architecture",m="console",f="mobile",v="tablet",S="smarttv",y="wearable",C="embedded",T="Amazon",E="Apple",b="ASUS",_="BlackBerry",I="Browser",w="Chrome",A="Firefox",P="Google",R="Huawei",M="LG",D="Microsoft",k="Motorola",O="Opera",N="Samsung",L="Sharp",x="Sony",F="Xiaomi",U="Zebra",B="Facebook",V="Chromium OS",H="Mac OS",$=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},j=function(e,t){return typeof e===o&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},q=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},z=function(e,t){for(var i,s,o,l,c,d,u=0;u<t.length&&!c;){var h=t[u],g=t[u+1];for(i=s=0;i<h.length&&!c&&h[i];)if(c=h[i++].exec(e))for(o=0;o<g.length;o++)d=c[++s],typeof(l=g[o])===a&&l.length>0?2===l.length?typeof l[1]==r?this[l[0]]=l[1].call(this,d):this[l[0]]=l[1]:3===l.length?typeof l[1]!==r||l[1].exec&&l[1].test?this[l[0]]=d?d.replace(l[1],l[2]):n:this[l[0]]=d?l[1].call(this,d,l[2]):n:4===l.length&&(this[l[0]]=d?l[3].call(this,d.replace(l[1],l[2])):n):this[l]=d||n;u+=2}},W=function(e,t){for(var i in t)if(typeof t[i]===a&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(j(t[i][r],e))return"?"===i?n:i}else if(j(t[i],e))return"?"===i?n:i;return e},K={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"},J={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,g],[/opios[\/ ]+([\w\.]+)/i],[g,[d,O+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[g,[d,O+" GX"]],[/\bopr\/([\w\.]+)/i],[g,[d,O]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[g,[d,"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],[d,g],[/\bddg\/([\w\.]+)/i],[g,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[g,[d,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[g,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[g,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[g,[d,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+I],g],[/\bfocus\/([\w\.]+)/i],[g,[d,A+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[d,O+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[d,O+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[d,"MIUI "+I]],[/fxios\/([-\w\.]+)/i],[g,[d,A]],[/\bqihu|(qi?ho?o?|360)browser/i],[[d,"360 "+I]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1 "+I],g],[/samsungbrowser\/([\w\.]+)/i],[g,[d,N+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[d,/_/g," "],g],[/metasr[\/ ]?([\d\.]+)/i],[g,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[d,g],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,B],g],[/(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],[d,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[g,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[d,w+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,w+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[d,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,g],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[g,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[g,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[g,W,{"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],[d,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[d,A+" 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],[d,g],[/(cobalt)\/([\w\.]+)/i],[d,[g,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,G]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,G]]],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],[c,[h,N],[u,v]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[c,[h,N],[u,f]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[c,[h,E],[u,f]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[c,[h,E],[u,v]],[/(macintosh);/i],[c,[h,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[c,[h,L],[u,f]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[c,[h,R],[u,v]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[c,[h,R],[u,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],[[c,/_/g," "],[h,F],[u,f]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[c,/_/g," "],[h,F],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[c,[h,"OPPO"],[u,f]],[/\b(opd2\d{3}a?) bui/i],[c,[h,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[c,[h,"Vivo"],[u,f]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[c,[h,"Realme"],[u,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],[c,[h,k],[u,f]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[c,[h,k],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[c,[h,M],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[c,[h,M],[u,f]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[c,[h,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[c,/_/g," "],[h,"Nokia"],[u,f]],[/(pixel c)\b/i],[c,[h,P],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[c,[h,P],[u,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],[c,[h,x],[u,f]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[c,"Xperia Tablet"],[h,x],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[c,[h,"OnePlus"],[u,f]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[c,[h,T],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[c,/(.+)/g,"Fire Phone $1"],[h,T],[u,f]],[/(playbook);[-\w\),; ]+(rim)/i],[c,h,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[c,[h,_],[u,f]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[c,[h,b],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[c,[h,b],[u,f]],[/(nexus 9)/i],[c,[h,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[c,/_/g," "],[u,f]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[c,[h,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[c,[h,"Meizu"],[u,f]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[c,[h,"Ulefone"],[u,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],[h,c,[u,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],[h,c,[u,v]],[/(surface duo)/i],[c,[h,D],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[c,[h,"Fairphone"],[u,f]],[/(u304aa)/i],[c,[h,"AT&T"],[u,f]],[/\bsie-(\w*)/i],[c,[h,"Siemens"],[u,f]],[/\b(rct\w+) b/i],[c,[h,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[c,[h,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[c,[h,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[c,[h,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[c,[h,"NuVision"],[u,v]],[/\b(k88) b/i],[c,[h,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[c,[h,"ZTE"],[u,f]],[/\b(gen\d{3}) b.+49h/i],[c,[h,"Swiss"],[u,f]],[/\b(zur\d{3}) b/i],[c,[h,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[c,[h,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],c,[u,v]],[/\b(ns-?\w{0,9}) b/i],[c,[h,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[c,[h,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],c,[u,f]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],c,[u,f]],[/\b(ph-1) /i],[c,[h,"Essential"],[u,f]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[c,[h,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[c,[h,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[c,[h,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[c,[h,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[h,c,[u,f]],[/(kin\.[onetw]{3})/i],[[c,/\./g," "],[h,D],[u,f]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[c,[h,U],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[c,[h,U],[u,f]],[/smart-tv.+(samsung)/i],[h,[u,S]],[/hbbtv.+maple;(\d+)/i],[[c,/^/,"SmartTV"],[h,N],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,M],[u,S]],[/(apple) ?tv/i],[h,[c,E+" TV"],[u,S]],[/crkey/i],[[c,w+"cast"],[h,P],[u,S]],[/droid.+aft(\w+)( bui|\))/i],[c,[h,T],[u,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[c,[h,L],[u,S]],[/(bravia[\w ]+)( bui|\))/i],[c,[h,x],[u,S]],[/(mitv-\w{5}) bui/i],[c,[h,F],[u,S]],[/Hbbtv.*(technisat) (.*);/i],[h,c,[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,q],[c,q],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,c,[u,m]],[/droid.+; (shield) bui/i],[c,[h,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[c,[h,x],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[c,[h,D],[u,m]],[/((pebble))app/i],[h,c,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[c,[h,E],[u,y]],[/droid.+; (glass) \d/i],[c,[h,P],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[c,[h,U],[u,y]],[/(quest( \d| pro)?)/i],[c,[h,B],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,C]],[/(aeobc)\b/i],[c,[h,T],[u,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[c,[u,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[c,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,f]],[/(android[-\w\. ]{0,9});.+buil/i],[c,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[d,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[d,"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],[d,g],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,g],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[g,W,K]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,W,K],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,H],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[g,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,g],[/\(bb(10);/i],[g,[d,_]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[g,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[g,[d,A+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[g,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[g,[d,w+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,V],g],[/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],[d,g],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],g],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,g]]},Y=function(e,t){if(typeof e===a&&(t=e,e=n),!(this instanceof Y))return new Y(e,t).getResult();var m=typeof i!==s&&i.navigator?i.navigator:n,S=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:n,C=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(J,t):J,T=m&&m.userAgent==S;return this.getBrowser=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.browser),e[l]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[g]),T&&m&&m.brave&&typeof m.brave.isBrave==r&&(e[d]="Brave"),e},this.getCPU=function(){var e={};return e[p]=n,z.call(e,S,C.cpu),e},this.getDevice=function(){var e={};return e[h]=n,e[c]=n,e[u]=n,z.call(e,S,C.device),T&&!e[u]&&y&&y.mobile&&(e[u]=f),T&&"Macintosh"==e[c]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[c]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.engine),e},this.getOS=function(){var e={};return e[d]=n,e[g]=n,z.call(e,S,C.os),T&&!e[d]&&y&&y.platform&&"Unknown"!=y.platform&&(e[d]=y.platform.replace(/chrome os/i,V).replace(/macos/i,H)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=typeof e===o&&e.length>500?q(e,500):e,this},this.setUA(S),this};Y.VERSION="1.0.38",Y.BROWSER=$([d,g,l]),Y.CPU=$([p]),Y.DEVICE=$([c,h,u,m,f,S,v,y,C]),Y.ENGINE=Y.OS=$([d,g]),typeof e!==s?(typeof t!==s&&t.exports&&(e=t.exports=Y),e.UAParser=Y):typeof i!==s&&(i.UAParser=Y);var Q=typeof i!==s&&(i.jQuery||i.Zepto);if(Q&&!Q.ua){var Z=new Y;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:e)}}),q=u({"../node_modules/@skype/hydra_player_sdk/hydra_player_sdk_bundle.js"(e,t){var i,n;i=e,n=function(){return e={103:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(){var e,t;return{promise:new Promise((function(i,n){e=i,t=n})),resolve:e,reject:t}}},457:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.iframeConfigDefault=void 0,t.iframeConfigDefault={scriptSrcDownload:!1,allowSameOrigin:!1}},1:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.liveStreamStatisticConfigDefault=void 0,t.liveStreamStatisticConfigDefault={maxUserInitiatedEventCount:100}},318:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.logSupportedCodecsConfigDefault=void 0,t.logSupportedCodecsConfigDefault={logSupportedCodecs:!1}},508:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.webRtcIceCandidateCollectorConfigDefault=void 0,t.webRtcIceCandidateCollectorConfigDefault={WebRtcIceCandidateCollectorDelayAfterCompleteMs:2500,WebRtcIceCandidateCollectorDelayAfterErrorMs:1e3,WebRtcIceCandidateCollectorMaxRetriesMs:5,WebRtcIceCandidateCollectorRetryDelayMs:100,WebRtcIceCandidateCollectorMaxCollectionTimeMs:6e4,WebRtcIceCandidateCollectorDisableCollection:!1}},10:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}},171:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},a=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LiveStreamStatistic=t.PlayerScenario=void 0;var o=i(346),l=i(963),c=i(1),d=i(534),u=i(318),h=function(){function e(e,t,i){this.name=e,this.details=t,this.failReason=i,this.timeStamp=Date.now()}return e.prototype.getName=function(){return this.name},e.prototype.getFailReason=function(){return this.failReason},e.prototype.getDetails=function(){return this.details},e.prototype.getTimeStamp=function(){return this.timeStamp},e}();t.PlayerScenario=h;var g=function(){function e(e,t,i,n){this.config=e,this.logFn=t,this.playerDiagnosticsLog=i,this.playerMetadata=n,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=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=e.maxPlayerExperimentalEvents||100,this.maxUserInitiatedEventCount=d.getECSSetting(this.config,"maxUserInitiatedEventCount",c.liveStreamStatisticConfigDefault.maxUserInitiatedEventCount),this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener(),d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs)&&this.populateSupportedCodecs()}return e.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e.prototype.setHydraInitResult=function(e){this.hydraInitResult=e},e.prototype.registerStatsUpdated=function(e){var t=this;this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((function(i){var n,r=i,s=null!==(n=t.playerDiagnosticsLog[i])&&void 0!==n?n:[];if(Array.isArray(s)){s.push(e[r]);var a="memoryLog"===r&&s.length>t.maxPlayerMemoryTraceLogCount,o="memoryLog"!==r&&s.length>t.maxPlayerDiagnosticsCount;(a||o)&&s.splice(0,1)}else t.playerDiagnosticsLog[i]=e[r]}))},e.prototype.registerEventLoadAttempt=function(e,t){this.registerScenario(e,t)},e.prototype.registerEventLoadFailed=function(e,t){this.completeScenario(e,t)},e.prototype.registerEventLoadSucceeded=function(e,t){this.completeScenario(e,void 0,t),e===l.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e.prototype.registerSdnPluginLoadAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginLoad,void 0,e)},e.prototype.registerSdnPluginInitializeAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginInitialize,e)},e.prototype.registerSdnPluginInitializeFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginInitialize,e)},e.prototype.registerSdnPluginInitializeSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginInitialize,void 0,e)},e.prototype.registerSdnPluginSetSourceAttempt=function(e){this.registerScenario(l.PlayerScenarioType.SdnPluginSetSource,e)},e.prototype.registerSdnPluginSetSourceFailed=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginSetSource,e)},e.prototype.registerSdnPluginSetSourceSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.SdnPluginSetSource,void 0,e)},e.prototype.registerStreamConnectionAttempt=function(e){this.registerScenario(l.PlayerScenarioType.StreamConnection,{streamUrl:e})},e.prototype.registerStreamConnectionSucceeded=function(e){this.completeScenario(l.PlayerScenarioType.StreamConnection,void 0,{result:d.stringifyObject(e)})},e.prototype.registerStreamConnectionFailed=function(e,t){this.completeScenario(l.PlayerScenarioType.StreamConnection,e,{result:d.stringifyObject(t)})},e.prototype.registerSetSourceAttempt=function(e,t,i){var n=e||"";i&&(n={src:e||"",isPrimary:d.stringifyObject(t),reason:i}),this.registerScenario(l.PlayerScenarioType.SetSource,n)},e.prototype.registerSetSourceSucceeded=function(e,t,i,n,r){this.completeScenario(l.PlayerScenarioType.SetSource,void 0,{src:e,isPrimary:d.stringifyObject(t),switchingDiagnostics:d.stringifyObject(i),stepDuration:d.stringifyObject(n),initialSeekToLiveEdge:d.stringifyObject(r)})},e.prototype.registerSetSourceFailed=function(e,t,i,n,r){this.completeScenario(l.PlayerScenarioType.SetSource,e,{src:d.stringifyObject(t),isPrimary:d.stringifyObject(i),switchingDiagnostics:d.stringifyObject(n),stepDuration:d.stringifyObject(r)})},e.prototype.registerPlayerDestroyed=function(e){this.registerScenario(l.PlayerScenarioType.Destroyed,e),this.completeScenario(l.PlayerScenarioType.Destroyed)},e.prototype.registerPlaybackStateChanged=function(e,t){var i,n,r,s,a,c;if(e!==o.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp){if(e===o.HydraPlayerPlaybackState.Playing){if(this.firstPlayingState||(this.firstPlayingState={timestamp:Date.now()},t&&(t.edgeLatency&&(this.firstPlayingState.edgeLatency=t.edgeLatency),t.bufferLength&&(this.firstPlayingState.bufferLength=t.bufferLength))),this.userInitiatedSeekEvents.length>0){var d=this.userInitiatedSeekEvents[this.userInitiatedSeekEvents.length-1];this.modifyTelemetryEventPayload(d,{playingStatePosition:null!==(n=null===(i=this.currentPlayerDiagnosticSnapshot)||void 0===i?void 0:i.currentPlayPosition)&&void 0!==n?n:-1,playingStateTimestamp:Date.now()},!1)}if(this.userInitiatedPlayEvents.length>0){var u=this.userInitiatedPlayEvents[this.userInitiatedPlayEvents.length-1];this.modifyTelemetryEventPayload(u,{playingStatePosition:null!==(s=null===(r=this.currentPlayerDiagnosticSnapshot)||void 0===r?void 0:r.currentPlayPosition)&&void 0!==s?s:-1,playingStateTimestamp:Date.now()},!1)}}else if(e===o.HydraPlayerPlaybackState.Pause&&this.userInitiatedPauseEvents.length>0){var h=this.userInitiatedPauseEvents[this.userInitiatedPauseEvents.length-1];this.modifyTelemetryEventPayload(h,{pauseStatePosition:null!==(c=null===(a=this.currentPlayerDiagnosticSnapshot)||void 0===a?void 0:a.currentPlayPosition)&&void 0!==c?c:-1,pauseStateTimestamp:Date.now()},!1)}}else this.firstReadyStateTimestamp=Date.now();this.registerPlaybackEvent(l.TelemetryEventType.StateChanged,e)},e.prototype.registerCapabilitiesUpdated=function(e){this.registerPlaybackEvent(l.TelemetryEventType.CapabilitiesUpdated,e)},e.prototype.registerHydraInputStateChanged=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.HydraInputStateChanged,e,t)},e.prototype.registerHydraOutputStateChanged=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.HydraOutputStateChanged,e,t)},e.prototype.registerPlaybackBuffering=function(e){this.registerPlaybackEvent(l.TelemetryEventType.Buffering,e)},e.prototype.registerSdnPluginEvent=function(e){var t=this.createTelemetryEvent(l.TelemetryEventType.EcdnPluginEvents,e);this.ecdnPluginEvents.push(t),this.ecdnPluginEvents.length>this.maxPlayerPlaybackEventCount&&this.ecdnPluginEvents.splice(0,1),this.logTelemetryEvent(t)},e.prototype.registerPlaybackError=function(e,t,i,n){this.registerPlaybackEvent(l.TelemetryEventType.Error,{errorType:e,details:t,errorSource:i,errorReason:n}),this.latestErrorReason=n},e.prototype.registerIgnoredPlaybackError=function(e){this.registerPlaybackEvent(l.TelemetryEventType.IgnoredError,e)},e.prototype.registerDownloadBitrateChanged=function(e){this.registerPlaybackEvent(l.TelemetryEventType.BitrateChangedDownload,e)},e.prototype.registerStreamOptionsConfigured=function(e,t){this.registerPlaybackEvent(l.TelemetryEventType.StreamOptionsConfigured,e,t)},e.prototype.registerPlaybackBitrateChanged=function(e){this.registerPlaybackEvent(l.TelemetryEventType.BitrateChangedPlayback,e)},e.prototype.registerVolumeChange=function(e){this.registerPlaybackEvent(l.TelemetryEventType.Volume,e)},e.prototype.getSnapshotReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),r=this.playbackEvents,s={};this.currentPlayerDiagnosticSnapshot&&(s=this.filterAndPrepareTelemetry());var a=d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs);return n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),a?{supportedCodecs:d.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),s)},e.prototype.getReport=function(){var e,t,i,r,s=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),a=this.playbackEvents,o=d.getECSSetting(this.config,"logSupportedCodecs",u.logSupportedCodecsConfigDefault.logSupportedCodecs);return n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(s)),this.getHydraInternalReport(a)),this.getPlaybackReport(a)),this.getBitrateReport(a)),this.getStreamConnectionReport(s)),this.getSdnReport(s)),this.getSetSourceReport(s)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),o?{supportedCodecs:d.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog()),{eventId:(null===(i=this.currentPlayerDiagnosticSnapshot)||void 0===i?void 0:i.eventId)||"",templateId:(null===(r=this.currentPlayerDiagnosticSnapshot)||void 0===r?void 0:r.templateId)||""})},e.prototype.buildCompleteTelemetryEvent=function(){this.playerEvents.sort((function(e,t){return e.getName()!==t.getName()?Object.keys(l.PlayerScenarioType).indexOf(e.getName())-Object.keys(l.PlayerScenarioType).indexOf(t.getName()):e.getTimeStamp()-t.getTimeStamp()}));for(var e,t,i,r,s,a=[],o=0,c=this.playerEvents;o<c.length;o++){var d=c[o],u=a[a.length-1];a.length&&d.getName()===u.name&&0===u.duration?a[a.length-1]=(e=u,i=(t=d).getFailReason()?{failReason:t.getFailReason()}:{},r=t.getDetails()?{details:t.getDetails()}:{},s={name:e.name,startTime:e.startTime,duration:t.getTimeStamp()>e.startTime?t.getTimeStamp()-e.startTime:e.duration},n(n(n({},s),i),r)):a.push({name:l.PlayerScenarioType[d.getName()],startTime:d.getTimeStamp(),duration:0})}return a},e.prototype.getHydraLoadEvent=function(){var e,t,i,n={name:l.PlayerScenarioType.LoadHydra,startTime:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initStartTime)||-1,duration:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initDuration)||0};(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)&&(n.failReason=this.hydraInitResult.errorMsg);var r=this.getHydraRuntimeDownloadDetails();return r&&(n.details=r),n},e.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var e=[],t=0,i=this.hydraInitResult.runtimeDownloadResults;t<i.length;t++){var n=i[t],r={success:n.success,url:n.url,startTime:n.startTime,duration:n.duration,trackingReference:n.trackingReference,timeTakenToDownloadScript:n.timeTakenToDownloadScript};n.errorMsg&&(r.errorMsg=n.errorMsg),e.push(r)}return d.stringifyObject(e)}return null},e.prototype.getTotalLoadEvent=function(){var e,t,i,n=this.getScenario(l.PlayerScenarioType.LoadPlayer),r=(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initDuration)||0,s=n.length>0?n[n.length-1].getTimeStamp()-n[0].getTimeStamp():0,a=n.length>0?n[n.length-1].getFailReason():void 0,o={name:l.PlayerScenarioType.Load,startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,duration:r+s};return(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)?o.failReason=this.hydraInitResult.errorMsg:a&&(o.failReason=a),o},e.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}},e.prototype.registerPlaybackEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);e===l.TelemetryEventType.Error&&(null==t?void 0:t.errorType)!==o.HydraPlayerPlaybackErrorType.PlaybackRetried&&(n.fatal=!0,this.callDropped=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getPlayerDiagnosticLog=function(){var e=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var t=this.currentPlayerDiagnosticSnapshot,i=this.playerDiagnosticsLog,r=n(n({},t),i),s={};return Object.keys(r).forEach((function(t){s["player_".concat(t)]=e.prepareForTelemetry(r[t])})),s},e.prototype.getHydraInitializationReport=function(){var e,t,i,n;return{hydraInit_succeeded:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initSucceeded)||!1,hydraInit_startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,hydraInit_errorMessage:(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)||"",hydraInit_duration:(null===(n=this.hydraInitResult)||void 0===n?void 0:n.initDuration)||0}},e.prototype.getPlayerInitializationReport=function(e){var t,i=e.find((function(e){return e.name===l.PlayerScenarioType.Load})),n=this.playerEvents.find((function(e){return e.getName()===l.PlayerScenarioType.StreamConnection})),r={init_timeLoadToStreamConnectionEstablished:(i&&n?n.getTimeStamp()-i.startTime:-1)||-1,init_timeLoadToReady:(i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(i&&(null===(t=this.firstPlayingState)||void 0===t?void 0:t.timestamp)?this.firstPlayingState.timestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)};return this.firstPlayingState&&(r.init_firstPlayingStateStatistics=this.prepareForTelemetry(this.firstPlayingState)),r},e.prototype.getHydraInternalReport=function(e){var t=e.filter((function(e){return e.eventType===l.TelemetryEventType.HydraInputStateChanged})),i=e.filter((function(e){return e.eventType===l.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(t),hydra_outputStateChangeEvents:this.prepareForTelemetry(i)}},e.prototype.getPlaybackReport=function(e){var t=e.filter((function(e){return e.eventType===l.TelemetryEventType.StateChanged})),i=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.CanPlayThrough})),n=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Play})),r=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Start})),s=t.find((function(e){return e.payload===o.HydraPlayerPlaybackState.Playing})),a=null!=i&&null!=n?n.timestamp-i.timestamp:-1,c=null!=n&&null!=r?r.timestamp-n.timestamp:-1,d=null!=r&&null!=s?s.timestamp-r.timestamp:-1,u=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Seeked})),h=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Seeking})),g=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Pause})),p=t.filter((function(e){return e.payload===o.HydraPlayerPlaybackState.Waiting})),m=[l.TelemetryEventType.BitrateChangedDownload,l.TelemetryEventType.BitrateChangedPlayback,l.TelemetryEventType.Error,l.TelemetryEventType.Mute,l.TelemetryEventType.StateChanged,l.TelemetryEventType.Volume,l.TelemetryEventType.StreamOptionsConfigured,l.TelemetryEventType.IgnoredError],f=e.filter((function(e){return e.eventType===l.TelemetryEventType.Error})),v=e.filter((function(e){return e.eventType===l.TelemetryEventType.IgnoredError})),S=e.filter((function(e){return e.eventType===l.TelemetryEventType.Volume||e.eventType===l.TelemetryEventType.Mute})),y=e.filter((function(e){return e.eventType===l.TelemetryEventType.StreamOptionsConfigured})),C=e.filter((function(e){return!m.includes(e.eventType)}));return{playback_timeReadyToPlay:a,playback_timePlayToStart:c,playback_timeStartToPlaying:d,playback_bufferingEvents:this.prepareForTelemetry(p),playback_errorEvents:this.prepareForTelemetry(f),playback_ignoredErrorEvents:this.prepareForTelemetry(v),playback_pauseEvents:this.prepareForTelemetry(g),playback_otherEvents:this.prepareForTelemetry(C),playback_seekedEvents:this.prepareForTelemetry(u),playback_seekingEvents:this.prepareForTelemetry(h),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(S),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(y),playback_latestErrorReason:this.latestErrorReason||""}},e.prototype.getBitrateReport=function(e){var t,i,r,s,a=e.filter((function(e){return e.eventType===l.TelemetryEventType.BitrateChangedDownload})),o=a.sort((function(e){return Number(e.payload)})),c=a.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(a),bitrate_downloadChangeCount:a.length>0||-1,bitrate_downloadMin:(null===(t=o[0])||void 0===t?void 0:t.payload)||-1,bitrate_downloadMax:(null===(i=o[o.length-1])||void 0===i?void 0:i.payload)||-1}:{},d=e.filter((function(e){return e.eventType===l.TelemetryEventType.BitrateChangedPlayback})),u=d.sort((function(e){return Number(e.payload)})),h=d.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(d),bitrate_playbackChangeCount:d.length>0||-1,bitrate_playbackMin:(null===(r=u[0])||void 0===r?void 0:r.payload)||-1,bitrate_playbackMax:(null===(s=u[u.length-1])||void 0===s?void 0:s.payload)||-1}:{};return n(n({},c),h)},e.prototype.addNetworkTypeEventListener=function(){var e,t,i,n,r=this;(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)&&(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n||n.addEventListener("change",(function(){r.updateClientNetworkType()})))},e.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e.prototype.getClientNetworkType=function(){var e,t,i,n;if(void 0===this.clientNetworkType){var r="Unknown";if(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)switch(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n?void 0:n.type){case"cellular":r="WWAN";break;case"ethernet":r="Wired";break;case"wifi":r="Wireless";break;default:r="Unknown"}this.clientNetworkType=r}return this.clientNetworkType},e.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}}]},e.prototype.getAudioVideoCodecsSupported=function(e){return r(this,void 0,void 0,(function(){var t,i,n=this;return s(this,(function(a){switch(a.label){case 0:return t=[],"mediaCapabilities"in navigator?(i=e.map((function(e){return r(n,void 0,void 0,(function(){var i,n;return s(this,(function(r){switch(r.label){case 0:i=e,r.label=1;case 1:return r.trys.push([1,3,,4]),[4,navigator.mediaCapabilities.decodingInfo(i)];case 2:return(n=r.sent()).supported&&(e.video?t.push({codec:e.video.contentType,supported:n.supported,smooth:n.smooth,powerEfficient:n.powerEfficient,resolution:e.video.height,framerate:e.video.framerate}):e.audio&&t.push({codec:e.audio.contentType,supported:n.supported,smooth:n.smooth,powerEfficient:n.powerEfficient})),[3,4];case 3:return r.sent(),[3,4];case 4:return[2]}}))}))})),[4,Promise.allSettled(i)]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2,t]}}))}))},e.prototype.populateSupportedCodecs=function(){var e=this;void 0===this.supportedCodecs&&this.getAudioVideoCodecsSupported(this.getCodecList()).then((function(t){e.supportedCodecs=t}))},e.prototype.getSdnReport=function(e){var t,i=e.filter((function(e){return[l.PlayerScenarioType.SdnPluginLoad,l.PlayerScenarioType.SdnPluginInitialize,l.PlayerScenarioType.SdnPluginSetSource].includes(e.name)})),n=a(a([],i,!0),this.ecdnPluginEvents,!0),r=i.filter((function(e){return void 0!==e.failReason})),s=i.filter((function(e){return e.name===l.PlayerScenarioType.SdnPluginLoad})).sort((function(e,t){return t.startTime-e.startTime}))[0];return{sdn_loaded:!(null==s||void 0!==s.failReason),sdn_details:null!==(t=null==s?void 0:s.details)&&void 0!==t?t:"",sdn_error:r.length>0&&r[r.length-1].failReason||"",sdn_events:this.prepareForTelemetry(n)}},e.prototype.getStreamConnectionReport=function(e){var t=e.filter((function(e){return e.name===l.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(t)}},e.prototype.getSetSourceReport=function(e){var t=e.filter((function(e){return e.name===l.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(t)}},e.prototype.registerScenario=function(e,t){this.playerEvents.push(new h(e,t))},e.prototype.completeScenario=function(e,t,i){this.playerEvents.push(new h(e,i,t))},e.prototype.logTelemetryEvent=function(e){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(e))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e.prototype.filterAndPrepareTelemetry=function(){var e=this,t=new Set;t.add("serviceLatencyCdg"),t.add("endToEndLatencyCdg"),t.add("videoEdgeLatencyCdg"),t.add("eventId"),t.add("templateId");var i={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(n){t.has(n)||(i["player_".concat(n)]=e.prepareForTelemetry(e.currentPlayerDiagnosticSnapshot[n]))})),i},e.prototype.prepareForTelemetry=function(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?null!=e?e:-1:JSON.stringify(e)},e.prototype.getScenario=function(e){return this.playerEvents.filter((function(t){return t.getName()===e}))},e.prototype.createTelemetryEvent=function(e,t,i){var n,r,s={eventType:e,timestamp:Date.now(),currentPlayPosition:null!==(r=null===(n=this.currentPlayerDiagnosticSnapshot)||void 0===n?void 0:n.currentPlayPosition)&&void 0!==r?r:-1};return void 0!==t&&(s.payload=this.prepareForTelemetry(t)),s.message=i,s},e.prototype.modifyTelemetryEventPayload=function(e,t,i){try{if(e.payload){var r=JSON.parse(e.payload);r=i?n(n({},r),t):n(n({},t),r),e.payload=this.prepareForTelemetry(r)}else e.payload=this.prepareForTelemetry(t)}catch(t){this.logFn("error","Failed to modify payload for event: ".concat(d.stringifyObject(e),", error: ").concat(t))}},e.prototype.registerExperimentalEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e.prototype.registerUserInitiatedSeek=function(e){var t,i,n={newCurrentPlayPosition:e,seekForward:(null!==(i=null===(t=this.currentPlayerDiagnosticSnapshot)||void 0===t?void 0:t.currentPlayPosition)&&void 0!==i?i:-1)<e},r=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedSeek,n);this.userInitiatedSeekEvents.push(r),this.userInitiatedSeekEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedSeekEvents.splice(0,1)},e.prototype.registerUserInitiatedPlay=function(){var e=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedPlay);this.userInitiatedPlayEvents.push(e),this.userInitiatedPlayEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPlayEvents.splice(0,1)},e.prototype.registerUserInitiatedPause=function(){var e=this.createTelemetryEvent(l.TelemetryEventType.UserInitiatedPause);this.userInitiatedPauseEvents.push(e),this.userInitiatedPauseEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPauseEvents.splice(0,1)},e.prototype.getUserInitiatedSeekEvents=function(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents),playback_userInitiatedPlayEvents:this.prepareForTelemetry(this.userInitiatedPlayEvents),playback_userInitiatedPauseEvents:this.prepareForTelemetry(this.userInitiatedPauseEvents)}},e.prototype.registerPlayBlocked=function(e){this.registerScenario(l.PlayerScenarioType.PlayAttemptBlocked,"Called video element play() but it failed with error: ".concat(e)),this.completeScenario(l.PlayerScenarioType.PlayAttemptBlocked)},e}();t.LiveStreamStatistic=g},42:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Spinner=void 0;var i=function(){function e(e){this.container=e,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var t=this.container.ownerDocument.getElementById(this.spinnerId);if(t)return this.spinner=t,void this.show();var i=this.container.ownerDocument.createElement("style");i.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(i),this.container.style.position="relative";var n=this.container.ownerDocument.createElement("div");n.classList.add("ml-player-spinner-container"),this.container.appendChild(n),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,n.appendChild(this.spinner);var r=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");r.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(r);var s=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");s.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(s),this.show()}return Object.defineProperty(e.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var e=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];e.hideTimestamp||(e.displayDuration=Date.now()-e.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e.prototype.show=function(){var e=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=e),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:e,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e.prototype.hide=function(){var e=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=e),this.spinnerInfoHistory.length>0){var t=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];t.hideTimestamp||(t.hideTimestamp=e,t.displayDuration=e-t.showTimestamp)}this.spinner.style.display="none"},e.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e}();t.Spinner=i},378:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageType=void 0,(n=i||(t.MessageType=i={})).Command="Command",n.CommandSuccessResult="CommandSuccessResult",n.CommandFailureResult="CommandFailureResult",n.PlayerEvent="PlayerEvent",n.InternalPlayerEvent="InternalPlayerEvent"},963:function(e,t){var i,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.PlayerScenarioType=t.TelemetryEventType=void 0,(r=i||(t.TelemetryEventType=i={})).BitrateChangedDownload="BitrateChangedDownload",r.StreamOptionsConfigured="StreamOptionsConfigured",r.BitrateChangedPlayback="BitrateChangedPlayback",r.CaptionsToggled="CaptionsToggled",r.Error="Error",r.IgnoredError="IgnoredError",r.FullscreenChanged="FullscreenChanged",r.Mute="Mute",r.PotentialMediaFreeze="PotentialMediaFreeze",r.StateChanged="StateChanged",r.HydraInputStateChanged="HydraInputStateChanged",r.HydraOutputStateChanged="HydraOutputStateChanged",r.Volume="Volume",r.Buffering="Buffering",r.Online="Online",r.Offline="Offline",r.NetworkChange="NetworkChange",r.HlsEvents="HlsEvents",r.EcdnPluginEvents="EcdnPluginEvents",r.UserInitiatedSeek="UserInitiatedSeek",r.UserInitiatedPlay="UserInitiatedPlay",r.UserInitiatedPause="UserInitiatedPause",r.CapabilitiesUpdated="CapabilitiesUpdated",function(e){e.LoadHydra="LoadHydra",e.LoadHlsScript="LoadHlsScript",e.LoadPlayer="LoadPlayer",e.Load="Load",e.LoadHlsAuthCookie="LoadHlsAuthCookie",e.HlsManifestLoad="HlsManifestLoad",e.HlsKeyLoad="HlsKeyLoad",e.LoadHlsFirstFragment="LoadHlsFirstFragment",e.SetSource="SetSource",e.SdnPluginLoad="SdnPluginLoad",e.ThaPluginLoad="ThaPluginLoad",e.HydraPipelineInitialization="HydraPipelineInitialization",e.Destroyed="Destroyed",e.Setup="Setup",e.StreamConnection="StreamConnection",e.SdnPluginInitialize="SdnPluginInitialize",e.SdnPluginSetSource="SdnPluginSetSource",e.PlayAttemptBlocked="PlayAttemptBlocked"}(n||(t.PlayerScenarioType=n={}))},176:function(e,t){var i,n,r,s,a,o,l,c;Object.defineProperty(t,"__esModule",{value:!0}),t.MobileInteractionType=t.HydraSupportedSDN=t.HydraPlayerDestroyedReason=t.HydraOutputState=t.HydraInputState=t.HydraPlayerPlaybackErrorSource=t.PlaybackMode=void 0,(c=i||(t.PlaybackMode=i={})).Live="Live",c.DVR="DVR",function(e){e.Stream="Stream",e.HydraPipeline="HydraPipeline",e.VideoPlayer="VideoPlayer"}(n||(t.HydraPlayerPlaybackErrorSource=n={})),function(e){e.Idle="Idle",e.Started="Started",e.BufferReceived="BufferReceived",e.Ended="Ended",e.Stopped="Stopped",e.Destroyed="Destroyed"}(r||(t.HydraInputState=r={})),function(e){e.Idle="Idle",e.Attached="Attached",e.Starting="Starting",e.Started="Started",e.BufferReceived="BufferReceived",e.BufferAppended="BufferAppended",e.Stopped="Stopped",e.Destroyed="Destroyed"}(s||(t.HydraOutputState=s={})),function(e){e.PlayerStopped="PlayerStopped",e.PlaybackError="PlaybackError"}(a||(t.HydraPlayerDestroyedReason=a={})),function(e){e.Hive="hive",e.Kollective="kollective",e.Ramp="ramp",e.Peer5="peer5",e.Microsoft="microsoft"}(o||(t.HydraSupportedSDN=o={})),function(e){e[e.DoublePress3Fingers=0]="DoublePress3Fingers"}(l||(t.MobileInteractionType=l={}))},346:function(e,t){var i,n,r,s,a,o,l,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.HttpFetchErrorReason=t.IframeMessages=t.HydraPlayerType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=t.HydraStreamingEventType=void 0,(d=i||(t.HydraStreamingEventType=i={})).TLE="TLE",d.Overflow="Overflow",d.TownHallBasic="TownHall_Basic",d.TownHallPremium="TownHall_Premium",d.TownHall="TownHall",function(e){e.AMS="AMS",e.HLS="MiddleLaneHttpLiveStreaming",e.Ums="MiddleLaneUltraLowLatency"}(n||(t.HydraStreamDeliveryPipeline=n={})),function(e){e.MultiplePlayerLoad="MultiplePlayerLoad",e.PlayerInitializationFailed="PlayerInitializationFailed",e.InvalidStream="InvalidStream",e.SetSourceFailed="SetSourceFailed"}(r||(t.HydraPlayerSetupErrorType=r={})),function(e){e.LoadStart="loadstart",e.LoadedData="loadeddata",e.LoadedMetadata="loadedmetadata",e.Start="start",e.CanPlayThrough="canplaythrough",e.Play="play",e.Playing="playing",e.Pause="pause",e.Waiting="waiting",e.Seeking="seeking",e.Seeked="seeked",e.Ended="ended",e.Error="error",e.Destroyed="destroyed",e.Initialized="initialized",e.Stalled="stalled",e.VolumeChange="volumechange",e.PlaybackBitrateChanged="playbackbitratechanged",e.DownloadBitrateChanged="downloadbitratechanged",e.TimeUpdate="timeupdate",e.DurationChange="durationchange",e.HlsKeyLoading="hlsKeyLoading",e.HlsKeyLoaded="hlsKeyLoaded",e.HlsKeyLoadedFailed="hlsKeyLoadedFailed",e.HlsManifestLoading="hlsManifestLoading",e.HlsManifestLoaded="hlsManifestLoaded",e.HlsManifestLoadedFailed="hlsManifestLoadedFailed",e.HlsFirstFragmentLoading="hlsFragLoading",e.HlsFirstFragmentBuffered="hlsFragBuffered",e.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",e.HlsFragmentChanged="hlsFragmentChanged",e.Online="online",e.Offline="offline",e.NetworkChange="networkChange"}(s||(t.HydraPlayerPlaybackState=s={})),function(e){e.UnsupportedPlatform="UnsupportedPlatform",e.NetworkError="NetworkError",e.PlaybackRetried="PlaybackRetried",e.PlaybackError="PlaybackError",e.Unknown="Unknown",e.MediaTimeout="MediaTimeout",e.NoMediaFlow="NoMediaFlow"}(a||(t.HydraPlayerPlaybackErrorType=a={})),function(e){e[e.Hls=1]="Hls",e[e.Ums=2]="Ums"}(o||(t.HydraPlayerType=o={})),function(e){e.RequestIceCandidates="RequestIceCandidates"}(l||(t.IframeMessages=l={})),function(e){e.Unknown="Unknown",e.ClientNetwork="ClientNetwork",e.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",e.ServerNetwork="ServerNetwork",e.ClientAuthIssue="ClientAuthIssue",e.ServerResourceNotFound="ServerResourceNotFound"}(c||(t.HttpFetchErrorReason=c={}))},534:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaybackStoppingState=t.tryCallVideoElementPlay=t.sanitizeForFormatSpecifiers=t.addEvent=t.TimeRanges=t.NO_OP_BUFFERED=t.getHttpFetchErrorReason=t.createVideoPlayButton=t.createVideoElement=t.createVideoElementDiv=t.showPlayerControls=t.repeatUntilCancel=t.wait=t.stringifyError=t.stringifyObject=t.getRandomHexString=t.getPlayerSetting=t.getECSSetting=t.retry=t.createIFrame=t.getMajorFromVersion=void 0;var s=i(346),a=i(457);function o(e,t,i,s,a,o,l){return n(this,void 0,void 0,(function(){var d,u,g,p,m,f=this;return r(this,(function(v){switch(v.label){case 0:return d=100,u=Date.now(),[4,c(i,g={trackingRef:"",timeTakenToDownloadScript:-1},a,o,l).catch((function(e){return n(f,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return t="Failed to get IFrame source: ".concat(h(e)),s.push({success:!1,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript,errorMsg:t}),s.length>d&&s.shift(),[4,Promise.reject(new Error(t))];case 1:return[2,n.sent()]}}))}))}))];case 1:return p=v.sent(),t.srcdoc=p,m=new Promise((function(e,n){t.onload=function(){s.push({success:!0,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript}),s.length>d&&s.shift(),e()},t.onerror=function(e){var t="Failed to load HydraPlayer IFrame: ".concat(h(e));s.push({success:!1,url:i,startTime:u,duration:Date.now()-u,trackingReference:g.trackingRef,timeTakenToDownloadScript:g.timeTakenToDownloadScript,errorMsg:t}),s.length>d&&s.shift(),n(new Error(t))}})),e.appendChild(t),[4,m];case 2:return v.sent(),[2]}}))}))}function l(e){return n(this,arguments,void 0,(function(e,t,i){var s=this;return void 0===t&&(t=5),void 0===i&&(i=200),r(this,(function(a){switch(a.label){case 0:return[4,e(t).catch((function(a){return n(s,void 0,void 0,(function(){var s=this;return r(this,(function(o){switch(o.label){case 0:return 0!=--t?[3,2]:[4,Promise.reject(new Error("[retry] retries exhausted: ".concat(g(a))))];case 1:case 3:return[2,o.sent()];case 2:return[4,new Promise((function(o){return setTimeout((function(){o(l(e,t,i).catch((function(e){return n(s,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(new Error("".concat(g(a)).concat(", ",g(e))))];case 1:return[2,t.sent()]}}))}))})))}),i)}))]}}))}))}))];case 1:return[2,a.sent()]}}))}))}function c(e,t,i,s,a){return n(this,void 0,void 0,(function(){var o,l,c,u=this;return r(this,(function(h){switch(h.label){case 0:return o=Date.now(),i?(l='<script src="'.concat(e,'"></script')+">",[3,3]):[3,1];case 1:return[4,d(e,t,s).catch((function(e){return n(u,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(e)];case 1:return[2,t.sent()]}}))}))}))];case 2:c=h.sent(),l=a?'<script nonce="'.concat(a,'">').concat(c,"</script")+">":"<script>".concat(c,"</script")+">",h.label=3;case 3:return t.timeTakenToDownloadScript=Date.now()-o,[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(l,"\n </body>\n </html>\n ")]}}))}))}function d(e,t,i){return n(this,void 0,void 0,(function(){var s,a,o,l=this;return r(this,(function(c){switch(c.label){case 0:return s=function(e,t){var i,n;return t.includes("vz")?null!==(n=e.headers.get("uuid"))&&void 0!==n?n:"":null!==(i=e.headers.get("X-Azure-Ref"))&&void 0!==i?i:""},i?(a=new AbortController,o=setTimeout((function(){a.abort()}),i),[4,fetch(e,{signal:a.signal,cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return clearTimeout(o),i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=s(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return[4,t.text().then((function(s){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return s?[2,s]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,s.sent()]}}))}))})).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){throw clearTimeout(o),e}))}))}))]):[3,2];case 1:case 3:return[2,c.sent()];case 2:return[4,fetch(e,{cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=s(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return[4,t.text().then((function(s){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return s?[2,s]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,s.sent()]}}))}))}))]}}))}))}function u(e,t,i){var n,r=i,s=null===(n=e.ecsSettings)||void 0===n?void 0:n[t];return typeof s==typeof r&&(r=s),r}function h(e){try{if(!e)return"".concat(e);if(e instanceof Map)return i={},e.forEach((function(e,t){i[t.toString()]=e})),JSON.stringify(i);var t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}catch(e){return""}var i}function g(e){return e instanceof Error?e.message:h(e)}function p(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){return setTimeout(t,e)}))];case 1:return t.sent(),[2]}}))}))}function m(e){return e?e.replace(/%[a-zA-Z]/g,""):e}t.getMajorFromVersion=function(e){var t=e.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return t?t[1]:null},t.createIFrame=function(e,t,i){return n(this,void 0,void 0,(function(){var s,c,d,g,p,m,f,v,S,y,C=this;return r(this,(function(T){switch(T.label){case 0:return s=u(i,"scriptSrcDownload",a.iframeConfigDefault.scriptSrcDownload),c=u(i,"allowSameOrigin",a.iframeConfigDefault.allowSameOrigin),d=i.maxRetryCountForLoadingResources,g=i.disableSandbox,p=i.hydraRuntimeFetchTimeout,m=[],(f=e.ownerDocument.createElement("iframe")).id="player-iframe",g||(c?null===(S=f.sandbox)||void 0===S||S.add("allow-scripts","allow-same-origin"):null===(y=f.sandbox)||void 0===y||y.add("allow-scripts")),f.allowFullscreen=!0,f.allow="camera; microphone; autoplay",f.style.height="100%",f.style.width="100%",f.style.border="none",v=function(e){return t[e%t.length]},[4,l((function(t){return n(C,void 0,void 0,(function(){var n,a,l;return r(this,(function(r){switch(r.label){case 0:return n=v(t),a=null!==(l=i.nonce)&&void 0!==l?l:"",[4,o(e,f,n,m,s,p,a)];case 1:return r.sent(),[2]}}))}))}),d).then((function(){return{iframe:f,initResult:{isSuccess:!0,runtimeDownloadResults:m}}})).catch((function(e){return n(C,void 0,void 0,(function(){var i;return r(this,(function(n){return i="Failed to load Hydra player runtime scripts, src: ",t.forEach((function(e){return i=i.concat(e,", ")})),i+="errors: ".concat(h(e)),[2,{initResult:{isSuccess:!1,runtimeDownloadResults:m,errorMsg:i}}]}))}))}))];case 1:return[2,T.sent()]}}))}))},t.retry=l,t.getECSSetting=u,t.getPlayerSetting=function(e,t){var i;return void 0!==(null===(i=e.ecsSettings)||void 0===i?void 0:i[t])?e.ecsSettings[t]:e[t]},t.getRandomHexString=function(e){return Array.from(Array(e)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},t.stringifyObject=h,t.stringifyError=g,t.wait=p,t.repeatUntilCancel=function(e,t,i,s){var a=!1,o=s||console.log,l=m(e);return o("RepeatUntilCancel starting task: ".concat(l)),n(this,void 0,void 0,(function(){var e,n,s;return r(this,(function(r){switch(r.label){case 0:return a?[3,2]:(e=new Date,t(),n=(new Date).getTime()-e.getTime(),(s=i-n)<0&&(s=i+s%i,o("Skipping execution for ".concat(l,", last execution took: ").concat(n," ms, delayMs: ").concat(i),"warn")),[4,p(s)]);case 1:return r.sent(),[3,0];case 2:return[2]}}))})),function(){o("RepeatUntilCancel stopping task: ".concat(l)),a=!0}},t.showPlayerControls=function(e){return void 0!==e.allowPlayerControls?e.allowPlayerControls:e.streamingEventType===s.HydraStreamingEventType.TLE},t.createVideoElementDiv=function(e,t,i){i("createVideoElementDiv started");var n=t.ownerDocument.createElement("div");return n.id=e,n.style.position="relative",n.style.width="100%",n.style.height="100%",t.appendChild(n),i("createVideoElementDiv done"),n},t.createVideoElement=function(e,t,i,n,r){r("createVideoElement started");var s=t.ownerDocument.createElement("video");s.controls=n,s.id=e,s.setAttribute("playsinline","");var a=i.videoLang;a&&(s.setAttribute("lang",a),r("createVideoElement: language set to ".concat(a)));var o=i.videoElementStyles;if(o)for(var l=0;l<o.length;l++)s.classList.add(o[l]);return s.style.width="100%",s.style.height="100%",s.style.position="absolute",s.muted=i.muteVideo,s.addEventListener("contextmenu",(function(e){e.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(e){try{navigator.mediaSession.setActionHandler(e,(function(){}))}catch(e){}})),t.appendChild(s),r("createVideoElement done"),s},t.createVideoPlayButton=function(e,t,i,n){n("createVideoPlayButton started");var r=t.ownerDocument.createElement("style");r.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 ",t.ownerDocument.head.appendChild(r);var s=t.ownerDocument.createElement("div");s.id=e,s.className="hydra-play-button";var a=document.createElement("div");return a.className="triangle",s.appendChild(a),i||(s.style.display="none"),t.appendChild(s),n("createVideoPlayButton done"),s},t.getHttpFetchErrorReason=function(e){return void 0===e?s.HttpFetchErrorReason.Unknown:0===e?s.HttpFetchErrorReason.ClientNetworkOrUnreachableServer:401===e?s.HttpFetchErrorReason.ClientAuthIssue:404===e?s.HttpFetchErrorReason.ServerResourceNotFound:e>=400&&e<=499?s.HttpFetchErrorReason.ClientNetwork:e>=500&&e<=599?s.HttpFetchErrorReason.ServerNetwork:s.HttpFetchErrorReason.Unknown},t.NO_OP_BUFFERED={length:0,start:function(){return 0},end:function(){return 0}},t.TimeRanges={toString:function(e){for(var t="",i=e.length,n=0;n<i;n++)t+="[".concat(e.start(n).toFixed(3),"-").concat(e.end(n).toFixed(3),"]");return t},range:function(e){return e&&0!==e.length?[e.start(e.length-1),e.end(e.length-1)]:[0,0]},prevRange:function(e){if(e&&2===e.length)return[e.start(e.length-2),e.end(e.length-2)]}},t.addEvent=function(e,t){var i={};return(null==t?void 0:t.detail)&&(i={detail:t.detail}),new CustomEvent(e,i)},t.sanitizeForFormatSpecifiers=m,t.tryCallVideoElementPlay=function(e){var t=e.play();return void 0!==t?t:new Promise((function(e){return e()}))},t.isPlaybackStoppingState=function(e){return e===s.HydraPlayerPlaybackState.Pause||e===s.HydraPlayerPlaybackState.Ended||e===s.HydraPlayerPlaybackState.Seeking||e===s.HydraPlayerPlaybackState.Waiting||e===s.HydraPlayerPlaybackState.Stalled||e===s.HydraPlayerPlaybackState.Destroyed}},564:function(e,t){var i,n,r,s,a,o,l,c,d,u;Object.defineProperty(t,"__esModule",{value:!0}),t.UmsModality=t.HttpFetchErrorReason=t.IframeMessages=t.HydraPlayerType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=t.HydraStreamingEventType=void 0,(u=i||(t.HydraStreamingEventType=i={})).TLE="TLE",u.Overflow="Overflow",u.TownHallBasic="TownHall_Basic",u.TownHallPremium="TownHall_Premium",u.TownHall="TownHall",function(e){e.AMS="AMS",e.HLS="MiddleLaneHttpLiveStreaming",e.Ums="MiddleLaneUltraLowLatency"}(n||(t.HydraStreamDeliveryPipeline=n={})),function(e){e.MultiplePlayerLoad="MultiplePlayerLoad",e.PlayerInitializationFailed="PlayerInitializationFailed",e.InvalidStream="InvalidStream",e.SetSourceFailed="SetSourceFailed"}(r||(t.HydraPlayerSetupErrorType=r={})),function(e){e.LoadStart="loadstart",e.LoadedData="loadeddata",e.LoadedMetadata="loadedmetadata",e.Start="start",e.CanPlayThrough="canplaythrough",e.Play="play",e.Playing="playing",e.Pause="pause",e.Waiting="waiting",e.Seeking="seeking",e.Seeked="seeked",e.Ended="ended",e.Error="error",e.Destroyed="destroyed",e.Initialized="initialized",e.Stalled="stalled",e.VolumeChange="volumechange",e.PlaybackBitrateChanged="playbackbitratechanged",e.DownloadBitrateChanged="downloadbitratechanged",e.TimeUpdate="timeupdate",e.DurationChange="durationchange",e.HlsKeyLoading="hlsKeyLoading",e.HlsKeyLoaded="hlsKeyLoaded",e.HlsKeyLoadedFailed="hlsKeyLoadedFailed",e.HlsManifestLoading="hlsManifestLoading",e.HlsManifestLoaded="hlsManifestLoaded",e.HlsManifestLoadedFailed="hlsManifestLoadedFailed",e.HlsFirstFragmentLoading="hlsFragLoading",e.HlsFirstFragmentBuffered="hlsFragBuffered",e.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",e.HlsFragmentChanged="hlsFragmentChanged",e.Online="online",e.Offline="offline",e.NetworkChange="networkChange"}(s||(t.HydraPlayerPlaybackState=s={})),function(e){e.UnsupportedPlatform="UnsupportedPlatform",e.NetworkError="NetworkError",e.PlaybackRetried="PlaybackRetried",e.PlaybackError="PlaybackError",e.Unknown="Unknown",e.MediaTimeout="MediaTimeout",e.NoMediaFlow="NoMediaFlow"}(a||(t.HydraPlayerPlaybackErrorType=a={})),function(e){e[e.Hls=1]="Hls",e[e.Ums=2]="Ums"}(o||(t.HydraPlayerType=o={})),function(e){e.RequestIceCandidates="RequestIceCandidates"}(l||(t.IframeMessages=l={})),function(e){e.Unknown="Unknown",e.ClientNetwork="ClientNetwork",e.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",e.ServerNetwork="ServerNetwork",e.ClientAuthIssue="ClientAuthIssue",e.ServerResourceNotFound="ServerResourceNotFound"}(c||(t.HttpFetchErrorReason=c={})),function(e){e.audio="Audio",e.video="Video",e.text="Text"}(d||(t.UmsModality=d={}))},521:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayer=t.getSdkVersion=void 0;var s=i(346),a=i(378),o=i(715),l=i(357),c=i(534),d=i(42),u=i(103),h=i(282),g=i(10);t.getSdkVersion=function(){return"4.2521.1"};var p=function(){function e(e,t){this.playerSettings=e,this.eventHandler=t,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 o.HydraPlayerInternalEventHandler}return e.prototype.dispose=function(){var e;null===(e=this.telemetryReportHandler)||void 0===e||e.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.callPlayerApi("disposeHydraPlayer")},e.prototype.release=function(){var e;null===(e=this.spinner)||void 0===e||e.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)},e.prototype.setup=function(e){return n(this,void 0,void 0,(function(){var t,i,n,a,o,l,u,h;return r(this,(function(r){switch(r.label){case 0:t=Date.now(),this.container=e,i=null,r.label=1;case 1:return r.trys.push([1,14,,15]),this.spinner=new d.Spinner(this.container),this.playerInternalEventHandler.setSpinner(this.spinner),[4,this.initializeIFrame()];case 2:if(!(i=r.sent()).isSuccess)return[3,12];n={initSucceeded:!0,initStartTime:t,initDuration:Date.now()-t,runtimeDownloadResults:i.runtimeDownloadResults||[]},r.label=3;case 3:return r.trys.push([3,5,,11]),[4,this.callPlayerApi("createHydraPlayer",this.playerSettings,n)];case 4:return r.sent(),[3,11];case 5:return a=r.sent(),this.eventHandler.log("warn","Failed to create HydraPlayer: ".concat(a)),this.playerSettings.playerType!==s.HydraPlayerType.Hls?[3,7]:[4,this.callPlayerApi("createHlsHydraPlayer",this.playerSettings,n)];case 6:return r.sent(),[3,10];case 7:return this.playerSettings.playerType!==s.HydraPlayerType.Ums?[3,9]:[4,this.callPlayerApi("createUmsHydraPlayer",this.playerSettings,n)];case 8:return r.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(n),[2,!0];case 12:throw new Error(i.errorMsg);case 13:return[3,15];case 14:o=r.sent(),l=(0,c.stringifyObject)(o),this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(l)),u={initSucceeded:!1,initStartTime:t,initDuration:Date.now()-t,runtimeDownloadResults:(null==i?void 0:i.runtimeDownloadResults)||[],errorMsg:l};try{null===(h=this.spinner)||void 0===h||h.hide()}catch(e){this.eventHandler.log("error","Failed to hide spinner: ".concat((0,c.stringifyObject)(e)))}return this.onSetupCompleted(u),[2,!1];case 15:return[2]}}))}))},e.prototype.onSetupCompleted=function(e){this.telemetryReportHandler=new l.TelemetryReportHandler(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),e,this.spinner),this.playerInternalEventHandler.setTelemetryReportHandler(this.telemetryReportHandler)},e.prototype.getFullTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getFullTelemetryReport())||{}},e.prototype.getSnapshotTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getSnapshotTelemetryReport())||{}},e.prototype.callPlayerApi=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return n(this,void 0,void 0,(function(){var i,n,s,o,l;return r(this,(function(r){switch(r.label){case 0:return this.iframe?[3,2]:[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))];case 1:case 3:return[2,r.sent()];case 2:if(i=(0,g.default)(),n={msgType:a.MessageType.Command,id:i,name:e,args:t},!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 s=u.defer(),o={name:e,id:i},this.commandResultsMap.set(o,s),null===(l=this.iframe.contentWindow)||void 0===l||l.postMessage(n,"*"),[4,s.promise]}}))}))},Object.defineProperty(e.prototype,"contextWindow",{get:function(){var e;return null===(e=this.container)||void 0===e?void 0:e.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e.prototype.isIFrameCommunicationActive=function(){var e;return!!(null===(e=this.iframe)||void 0===e?void 0:e.contentWindow)&&!!this.contextWindow},e.prototype.getRuntimeUrls=function(e){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var t=(0,c.getMajorFromVersion)(e);return t&&this.playerSettings.playerRuntimeJsUrls[t]||[]}return this.playerSettings.playerRuntimeJsUrls},e.prototype.initializeIFrame=function(){return n(this,void 0,void 0,(function(){var e;return r(this,(function(t){switch(t.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,c.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,c.stringifyObject)(this.playerSettings.playerRuntimeJsUrls))}];case 1:return(e=t.sent()).initResult.isSuccess&&e.iframe&&(this.iframe=e.iframe,this.iframeCommunicationHandler=new h.IframeCommunicationHandler(this.iframe,this.playerSettings,this.eventHandler.log),this.contextWindow.addEventListener("message",this.onMessage.bind(this))),[2,e.initResult]}}))}))},e.prototype.onMessage=function(e){switch(e.data.msgType){case a.MessageType.PlayerEvent:this.processPlayerEvent(e.data);break;case a.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(e.data);break;case a.MessageType.CommandSuccessResult:this.processCommandSuccessResult(e.data);break;case a.MessageType.CommandFailureResult:this.processCommandFailureResult(e.data)}},e.prototype.processCommandSuccessResult=function(e){var t=this;this.eventHandler.log("debug","HydraPlayer command succeeded for ".concat(e.name," - result: ").concat((0,c.stringifyObject)(e.result))),this.getMapCommandResults(e).forEach((function(i){i[1].resolve(e.result),t.commandResultsMap.delete(i[0])}))},e.prototype.processCommandFailureResult=function(e){var t=this;this.eventHandler.log("debug","HydraPlayer command failed for ".concat(e.name," - error: ").concat(e.error.message)),this.getMapCommandResults(e).forEach((function(i){i[1].reject(e.error),t.commandResultsMap.delete(i[0])}))},e.prototype.getMapCommandResults=function(e){var t=Array.from(this.commandResultsMap.entries()),i=[];return e.id?i=t.filter((function(t){return t[0].id===e.id})):e.name&&(i=t.filter((function(t){return t[0].name===e.name}))),i},e.prototype.processPlayerEvent=function(e){var t;null===(t=this.eventHandler[e.name])||void 0===t||t.apply(this.eventHandler,e.args)},e.prototype.processInternalPlayerEvent=function(e){this.playerInternalEventHandler&&this.playerInternalEventHandler[e.name].apply(this,e.args)},e}();t.HydraPlayer=p},282:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.IframeCommunicationHandler=void 0;var n=i(346),r=i(735),s=function(){function e(e,t,i){var n=this;this.iframe=e,this.playerSettings=t,this.logger=i,this.setupMessageListener(),this.candidatesCollector=new r.WebRtcIceCandidateCollector(this.playerSettings),this.candidatesCollector.startCandidatesCollection().catch((function(e){n.logger("warn","Failed to start collecting ICE candidates ".concat(e))}))}return e.prototype.setupMessageListener=function(){var e;null===(e=this.iframe.ownerDocument.defaultView)||void 0===e||e.addEventListener("message",this.processMessage.bind(this))},e.prototype.postMessageToIframe=function(e){var t;null===(t=this.iframe.contentWindow)||void 0===t||t.postMessage(e,"*")},e.prototype.dispose=function(){var e;null===(e=this.iframe.ownerDocument.defaultView)||void 0===e||e.removeEventListener("message",this.processMessage.bind(this)),this.candidatesCollector&&this.candidatesCollector.destroy()},e.prototype.processMessage=function(e){var t=this;e.data===n.IframeMessages.RequestIceCandidates&&void 0===e.data.candidates&&this.candidatesCollector.getCandidates().then((function(e){var i=JSON.stringify(e.map((function(e){return JSON.stringify(e)})));t.postMessageToIframe({topic:n.IframeMessages.RequestIceCandidates,candidates:i})})).catch((function(){t.postMessageToIframe({topic:n.IframeMessages.RequestIceCandidates,candidates:[]})}))},e}();t.IframeCommunicationHandler=s},260:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),r(i(521),t),r(i(564),t)},715:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerInternalEventHandler=void 0;var i=function(){function e(){this.spinner=null,this.telemetryReportHandler=null}return e.prototype.setSpinner=function(e){this.spinner=e},e.prototype.setTelemetryReportHandler=function(e){this.telemetryReportHandler=e},e.prototype.firstPlayerLoadAttemptDone=function(){var e;null===(e=this.spinner)||void 0===e||e.hide()},e.prototype.fullTelemetryReportUpdated=function(e){var t;null===(t=this.telemetryReportHandler)||void 0===t||t.setFullTelemetryReport(e)},e.prototype.snapshotTelemetryReportUpdated=function(e){var t;null===(t=this.telemetryReportHandler)||void 0===t||t.setSnapshotTelemetryReport(e)},e}();t.HydraPlayerInternalEventHandler=i},357:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.TelemetryReportHandler=void 0;var r=i(346),s=i(176),a=i(963),o=i(171),l=i(534),c=function(){function e(e,t,i,n){var s=this;this.logFn=t,this.spinner=n,this.initialLiveStreamStatistic=new o.LiveStreamStatistic(e,(function(e,t){s.logFn(e,t)}),{videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],statsInterval:[]},{hydraPlayerSdkVersion:e.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:r.HydraPlayerType.Hls}),this.initialLiveStreamStatistic.setHydraInitResult(i),this.fullTelemetryReport=this.initialLiveStreamStatistic.getReport(),this.snapshotTelemetryReport=this.initialLiveStreamStatistic.getSnapshotReport()}return e.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e.prototype.setFullTelemetryReport=function(e){var t,i,r,s,a,o,l;this.fullTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(i=null===(t=this.spinner)||void 0===t?void 0:t.firstShowTimestamp)&&void 0!==i?i:-1,init_spinnerHideTimestamp:null!==(s=null===(r=this.spinner)||void 0===r?void 0:r.firstHideTimestamp)&&void 0!==s?s:-1,init_spinnerDuration:null!==(o=null===(a=this.spinner)||void 0===a?void 0:a.firstSpinnerDuration)&&void 0!==o?o:-1,init_spinnerVisible:(null===(l=this.spinner)||void 0===l?void 0:l.isVisible())||!1})},e.prototype.setSnapshotTelemetryReport=function(e){var t,i,r,s,a,o,l;this.snapshotTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(i=null===(t=this.spinner)||void 0===t?void 0:t.firstShowTimestamp)&&void 0!==i?i:-1,init_spinnerHideTimestamp:null!==(s=null===(r=this.spinner)||void 0===r?void 0:r.firstHideTimestamp)&&void 0!==s?s:-1,init_spinnerDuration:null!==(o=null===(a=this.spinner)||void 0===a?void 0:a.firstSpinnerDuration)&&void 0!==o?o:-1,init_spinnerVisible:(null===(l=this.spinner)||void 0===l?void 0:l.isVisible())||!1})},e.prototype.addDisposeTelemetry=function(){var e=Date.now();this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,e,"full"),this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,e,"snapshot"),this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,e,"full"),this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,e,"snapshot")},e.prototype.updateInitEventsWithDisposeEvent=function(e,t,i){try{var n=e.init_allEvents,r=JSON.parse(n);r[r.length-1].name!==a.PlayerScenarioType.Destroyed&&r.push({name:a.PlayerScenarioType.Destroyed,startTime:t,duration:0,details:s.HydraPlayerDestroyedReason.PlayerStopped}),e.init_allEvents=(0,l.stringifyObject)(r)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in ".concat(i," telemetry report."))}},e.prototype.updateStateChangeEventsWithDisposeEvent=function(e,t,i){try{var n=e.playback_stateChangeEvents,s=JSON.parse(n);s[s.length-1].name!==r.HydraPlayerPlaybackState.Destroyed&&s.push({eventType:a.TelemetryEventType.StateChanged,timestamp:t,currentPlayPosition:-1,payload:r.HydraPlayerPlaybackState.Destroyed}),e.playback_stateChangeEvents=(0,l.stringifyObject)(s)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in ".concat(i," telemetry report."))}},e}();t.TelemetryReportHandler=c},735:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},s=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcIceCandidateCollector=void 0;var a=i(103),o=i(534),l=i(508),c=function(){function e(e){this.playerSettings=e,this.latestCandidates=[],this.newCandidates=[],this.peerConnection=null,this.timeoutId=void 0,this.candidatesCollectionDefer=null,this.delayAfterComplete=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterCompleteMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterCompleteMs),this.delayAfterError=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterErrorMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterErrorMs),this.maxRetries=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxRetriesMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxRetriesMs),this.retryDelay=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorRetryDelayMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorRetryDelayMs),this.maxCollectionTime=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxCollectionTimeMs",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxCollectionTimeMs),this.disabledCollection=(0,o.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDisableCollection",l.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDisableCollection)}return e.prototype.handleIceCandidate=function(e){e.candidate&&this.newCandidates.push(e.candidate)},e.prototype.handleIceGatheringStateChange=function(){var e,t;"complete"===(null===(e=this.peerConnection)||void 0===e?void 0:e.iceGatheringState)&&(this.latestCandidates=s([],this.newCandidates,!0),this.newCandidates=[],null===(t=this.candidatesCollectionDefer)||void 0===t||t.resolve(),this.candidatesCollectionDefer=null,this.destroyConnection(),this.clearCollectionTimeout(),this.startCandidatesCollection(this.delayAfterComplete))},e.prototype.setUpPeerConnection=function(){return n(this,void 0,void 0,(function(){var e,t,i,n;return r(this,(function(r){switch(r.label){case 0:return r.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===(i=this.peerConnection)||void 0===i?void 0:i.createOffer()];case 1:return e=r.sent(),[4,null===(n=this.peerConnection)||void 0===n?void 0:n.setLocalDescription(e)];case 2:return r.sent(),[3,4];case 3:throw t=r.sent(),this.destroyConnection(),new Error("Failure starting collection: ".concat((0,o.stringifyError)(t)));case 4:return[2]}}))}))},e.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)},e.prototype.clearCollectionTimeout=function(){void 0!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)},e.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)},e.prototype.startCandidatesCollection=function(){return n(this,arguments,void 0,(function(e){var t,i=this;return void 0===e&&(e=0),r(this,(function(s){switch(s.label){case 0:return this.candidatesCollectionDefer||this.disabledCollection?[2]:e>0?[4,new Promise((function(t){return setTimeout(t,e)}))]:[3,2];case 1:s.sent(),s.label=2;case 2:return this.candidatesCollectionDefer=(0,a.defer)(),this.candidatesCollectionDefer.promise.catch((function(){})),t=this.setUpPeerConnection.bind(this),[4,(0,o.retry)(t,this.maxRetries,this.retryDelay).then((function(){i.timeoutId=setTimeout((function(){var e;null===(e=i.candidatesCollectionDefer)||void 0===e||e.reject(new Error("Collection timed out")),i.candidatesCollectionDefer=null,i.destroyConnection(),i.startCandidatesCollection(i.delayAfterError)}),i.maxCollectionTime)})).catch((function(e){return n(i,void 0,void 0,(function(){var t,i;return r(this,(function(n){switch(n.label){case 0:return t="Failed to start collection ".concat((0,o.stringifyError)(e)),null===(i=this.candidatesCollectionDefer)||void 0===i||i.reject(new Error(t)),this.candidatesCollectionDefer=null,[4,Promise.reject(new Error(t))];case 1:return n.sent(),this.startCandidatesCollection(this.delayAfterError),[2]}}))}))}))];case 3:return s.sent(),[2]}}))}))},e.prototype.getCandidates=function(){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return 0===this.latestCandidates.length&&this.candidatesCollectionDefer?[4,this.candidatesCollectionDefer.promise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2,this.latestCandidates]}}))}))},e}();t.WebRtcIceCandidateCollector=c}},t={},function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}(260);var e,t},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e.hydra_player_sdk=n():i.hydra_player_sdk=n()}}),z=u({"../node_modules/pako/lib/utils/common.js"(e){var t="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var r in n)i(n,r)&&(e[r]=n[r])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),r);else for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){var t,i,n,r,s,a;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(a=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)s=e[t],a.set(s,r),r+=s.length;return a}},r={arraySet:function(e,t,i,n,r){for(var s=0;s<n;s++)e[r+s]=t[i+s]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,r))},e.setTyped(t)}}),W=u({"../node_modules/pako/lib/zlib/trees.js"(e){var t=z();function i(e){for(var t=e.length;--t>=0;)e[t]=0}var n=[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],r=[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],s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],a=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],o=new Array(576);i(o);var l=new Array(60);i(l);var c=new Array(512);i(c);var d=new Array(256);i(d);var u=new Array(29);i(u);var h,g,p,m=new Array(30);function f(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function S(e){return e<256?c[e]:c[256+(e>>>7)]}function y(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function C(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,y(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function T(e,t,i){C(e,i[2*t],i[2*t+1])}function E(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function b(e,t,i){var n,r,s=new Array(16),a=0;for(n=1;n<=15;n++)s[n]=a=a+i[n-1]<<1;for(r=0;r<=t;r++){var o=e[2*r+1];0!==o&&(e[2*r]=E(s[o]++,o))}}function _(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function I(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function w(e,i,n,r){I(e),r&&(y(e,n),y(e,~n)),t.arraySet(e.pending_buf,e.window,i,n,e.pending),e.pending+=n}function A(e,t,i,n){var r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]}function P(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&A(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!A(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function R(e,t,i){var s,a,o,l,c=0;if(0!==e.last_lit)do{s=e.pending_buf[e.d_buf+2*c]<<8|e.pending_buf[e.d_buf+2*c+1],a=e.pending_buf[e.l_buf+c],c++,0===s?T(e,a,t):(T(e,(o=d[a])+256+1,t),0!==(l=n[o])&&C(e,a-=u[o],l),T(e,o=S(--s),i),0!==(l=r[o])&&C(e,s-=m[o],l))}while(c<e.last_lit);T(e,256,t)}function M(e,t){var i,n,r,s=t.dyn_tree,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<l;i++)0!==s[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):s[2*i+1]=0;for(;e.heap_len<2;)s[2*(r=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[r]=0,e.opt_len--,o&&(e.static_len-=a[2*r+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)P(e,s,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],P(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,s[2*r]=s[2*i]+s[2*n],e.depth[r]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,s[2*i+1]=s[2*n+1]=r,e.heap[1]=r++,P(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,r,s,a,o,l=t.dyn_tree,c=t.max_code,d=t.stat_desc.static_tree,u=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,g=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=15;s++)e.bl_count[s]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(s=l[2*l[2*(n=e.heap[i])+1]+1]+1)>p&&(s=p,m++),l[2*n+1]=s,n>c||(e.bl_count[s]++,a=0,n>=g&&(a=h[n-g]),o=l[2*n],e.opt_len+=o*(s+a),u&&(e.static_len+=o*(d[2*n+1]+a)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(n=e.bl_count[s];0!==n;)(r=e.heap[--i])>c||(l[2*r+1]!==s&&(e.opt_len+=(s-l[2*r+1])*l[2*r],l[2*r+1]=s),n--)}}(e,t),b(s,c,e.bl_count)}function D(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=a,a=t[2*(n+1)+1],++o<l&&r===a||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4))}function k(e,t,i){var n,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),n=0;n<=i;n++)if(r=a,a=t[2*(n+1)+1],!(++o<l&&r===a)){if(o<c)do{T(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==s&&(T(e,r,e.bl_tree),o--),T(e,16,e.bl_tree),C(e,o-3,2)):o<=10?(T(e,17,e.bl_tree),C(e,o-3,3)):(T(e,18,e.bl_tree),C(e,o-11,7));o=0,s=r,0===a?(l=138,c=3):r===a?(l=6,c=3):(l=7,c=4)}}i(m);var O=!1;function N(e,t,i,n){C(e,0+(n?1:0),3),w(e,t,i,!0)}e._tr_init=function(e){O||(function(){var e,t,i,a,v,S=new Array(16);for(i=0,a=0;a<28;a++)for(u[a]=i,e=0;e<1<<n[a];e++)d[i++]=a;for(d[i-1]=a,v=0,a=0;a<16;a++)for(m[a]=v,e=0;e<1<<r[a];e++)c[v++]=a;for(v>>=7;a<30;a++)for(m[a]=v<<7,e=0;e<1<<r[a]-7;e++)c[256+v++]=a;for(t=0;t<=15;t++)S[t]=0;for(e=0;e<=143;)o[2*e+1]=8,e++,S[8]++;for(;e<=255;)o[2*e+1]=9,e++,S[9]++;for(;e<=279;)o[2*e+1]=7,e++,S[7]++;for(;e<=287;)o[2*e+1]=8,e++,S[8]++;for(b(o,287,S),e=0;e<30;e++)l[2*e+1]=5,l[2*e]=E(e,5);h=new f(o,n,257,286,15),g=new f(l,r,0,30,15),p=new f(new Array(0),s,0,19,7)}(),O=!0),e.l_desc=new v(e.dyn_ltree,h),e.d_desc=new v(e.dyn_dtree,g),e.bl_desc=new v(e.bl_tree,p),e.bi_buf=0,e.bi_valid=0,_(e)},e._tr_stored_block=N,e._tr_flush_block=function(e,t,i,n){var r,s,c=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),M(e,e.l_desc),M(e,e.d_desc),c=function(e){var t;for(D(e,e.dyn_ltree,e.l_desc.max_code),D(e,e.dyn_dtree,e.d_desc.max_code),M(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*a[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?N(e,t,i,n):4===e.strategy||s===r?(C(e,2+(n?1:0),3),R(e,o,l)):(C(e,4+(n?1:0),3),function(e,t,i,n){var r;for(C(e,t-257,5),C(e,i-1,5),C(e,n-4,4),r=0;r<n;r++)C(e,e.bl_tree[2*a[r]+1],3);k(e,e.dyn_ltree,t-1),k(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,c+1),R(e,e.dyn_ltree,e.dyn_dtree)),_(e),n&&I(e)},e._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(d[i]+256+1)]++,e.dyn_dtree[2*S(t)]++),e.last_lit===e.lit_bufsize-1},e._tr_align=function(e){C(e,2,3),T(e,256,o),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}}}),K=u({"../node_modules/pako/lib/zlib/adler32.js"(e,t){t.exports=function(e,t,i,n){for(var r=65535&e,s=e>>>16&65535,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{s=s+(r=r+t[n++]|0)|0}while(--a);r%=65521,s%=65521}return r|s<<16}}}),J=u({"../node_modules/pako/lib/zlib/crc32.js"(e,t){var i=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,n,r){var s=i,a=r+n;e^=-1;for(var o=r;o<a;o++)e=e>>>8^s[255&(e^t[o])];return~e}}}),Y=u({"../node_modules/pako/lib/zlib/messages.js"(e,t){t.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"}}}),X=u({"../node_modules/pako/lib/zlib/deflate.js"(e){var t,i=z(),n=W(),r=K(),s=J(),a=Y(),o=-2,l=258,c=262,d=103,u=113,h=666;function g(e,t){return e.msg=a[t],t}function p(e){return(e<<1)-(e>4?9:0)}function m(e){for(var t=e.length;--t>=0;)e[t]=0}function f(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(i.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))}function v(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,f(e.strm)}function S(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function C(e,t,n,a){var o=e.avail_in;return o>a&&(o=a),0===o?0:(e.avail_in-=o,i.arraySet(t,e.input,e.next_in,o,n),1===e.state.wrap?e.adler=r(e.adler,t,o,n):2===e.state.wrap&&(e.adler=s(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)}function T(e,t){var i,n,r=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,d=e.strstart>e.w_size-c?e.strstart-(e.w_size-c):0,u=e.window,h=e.w_mask,g=e.prev,p=e.strstart+l,m=u[s+a-1],f=u[s+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(u[(i=t)+a]===f&&u[i+a-1]===m&&u[i]===u[s]&&u[++i]===u[s+1]){s+=2,i++;do{}while(u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&u[++s]===u[++i]&&s<p);if(n=l-(p-s),s=p-l,n>a){if(e.match_start=t,a=n,n>=o)break;m=u[s+a-1],f=u[s+a]}}}while((t=g[t&h])>d&&0!=--r);return a<=e.lookahead?a:e.lookahead}function E(e){var t,n,r,s,a,o=e.w_size;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-c)){i.arraySet(e.window,e.window,o,o,0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=n=e.hash_size;do{r=e.head[--t],e.head[t]=r>=o?r-o:0}while(--n);t=n=o;do{r=e.prev[--t],e.prev[t]=r>=o?r-o:0}while(--n);s+=o}if(0===e.strm.avail_in)break;if(n=C(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=n,e.lookahead+e.insert>=3)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+3-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<c&&0!==e.strm.avail_in)}function b(e,t){for(var i,r;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-c&&(e.match_length=T(e,i)),e.match_length>=3)if(r=n._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function _(e,t){for(var i,r,s;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-c&&(e.match_length=T(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(v(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=n._tr_tally(e,0,e.window[e.strstart-1]))&&v(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function I(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}function w(e){e.window_size=2*e.w_size,m(e.head),e.max_lazy_match=t[e.level].max_lazy,e.good_match=t[e.level].good_length,e.nice_match=t[e.level].nice_length,e.max_chain_length=t[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0}function A(){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=8,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 i.Buf16(1146),this.dyn_dtree=new i.Buf16(122),this.bl_tree=new i.Buf16(78),m(this.dyn_ltree),m(this.dyn_dtree),m(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(16),this.heap=new i.Buf16(573),m(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(573),m(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 P(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:u,e.adler=2===t.wrap?0:1,t.last_flush=0,n._tr_init(t),0):g(e,o)}function R(e){var t=P(e);return 0===t&&w(e.state),t}function M(e,t,n,r,s,a){if(!e)return o;var l=1;if(-1===t&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),s<1||s>9||8!==n||r<8||r>15||t<0||t>9||a<0||a>4)return g(e,o);8===r&&(r=9);var c=new A;return e.state=c,c.strm=e,c.wrap=l,c.gzhead=null,c.w_bits=r,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=s+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+3-1)/3),c.window=new i.Buf8(2*c.w_size),c.head=new i.Buf16(c.hash_size),c.prev=new i.Buf16(c.w_size),c.lit_bufsize=1<<s+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new i.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=t,c.strategy=a,c.method=n,R(e)}t=[new I(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(E(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,v(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-c&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(v(e,!1),e.strm.avail_out),1)})),new I(4,4,8,4,b),new I(4,5,16,8,b),new I(4,6,32,32,b),new I(4,4,16,16,_),new I(8,16,32,32,_),new I(8,16,128,128,_),new I(8,32,128,256,_),new I(32,128,258,1024,_),new I(32,258,258,4096,_)],e.deflateInit=function(e,t){return M(e,t,8,15,8,0)},e.deflateInit2=M,e.deflateReset=R,e.deflateResetKeep=P,e.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?o:(e.state.gzhead=t,0):o},e.deflate=function(e,i){var r,a,c,C;if(!e||!e.state||i>5||i<0)return e?g(e,o):o;if(a=e.state,!e.output||!e.input&&0!==e.avail_in||a.status===h&&4!==i)return g(e,0===e.avail_out?-5:o);if(a.strm=e,r=a.last_flush,a.last_flush=i,42===a.status)if(2===a.wrap)e.adler=0,S(a,31),S(a,139),S(a,8),a.gzhead?(S(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),S(a,255&a.gzhead.time),S(a,a.gzhead.time>>8&255),S(a,a.gzhead.time>>16&255),S(a,a.gzhead.time>>24&255),S(a,9===a.level?2:a.strategy>=2||a.level<2?4:0),S(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(S(a,255&a.gzhead.extra.length),S(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(e.adler=s(e.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69):(S(a,0),S(a,0),S(a,0),S(a,0),S(a,0),S(a,9===a.level?2:a.strategy>=2||a.level<2?4:0),S(a,3),a.status=u);else{var T=8+(a.w_bits-8<<4)<<8;T|=(a.strategy>=2||a.level<2?0:a.level<6?1:6===a.level?2:3)<<6,0!==a.strstart&&(T|=32),T+=31-T%31,a.status=u,y(a,T),0!==a.strstart&&(y(a,e.adler>>>16),y(a,65535&e.adler)),e.adler=1}if(69===a.status)if(a.gzhead.extra){for(c=a.pending;a.gzindex<(65535&a.gzhead.extra.length)&&(a.pending!==a.pending_buf_size||(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending!==a.pending_buf_size));)S(a,255&a.gzhead.extra[a.gzindex]),a.gzindex++;a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=73)}else a.status=73;if(73===a.status)if(a.gzhead.name){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending===a.pending_buf_size)){C=1;break}C=a.gzindex<a.gzhead.name.length?255&a.gzhead.name.charCodeAt(a.gzindex++):0,S(a,C)}while(0!==C);a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),0===C&&(a.gzindex=0,a.status=91)}else a.status=91;if(91===a.status)if(a.gzhead.comment){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),f(e),c=a.pending,a.pending===a.pending_buf_size)){C=1;break}C=a.gzindex<a.gzhead.comment.length?255&a.gzhead.comment.charCodeAt(a.gzindex++):0,S(a,C)}while(0!==C);a.gzhead.hcrc&&a.pending>c&&(e.adler=s(e.adler,a.pending_buf,a.pending-c,c)),0===C&&(a.status=d)}else a.status=d;if(a.status===d&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&f(e),a.pending+2<=a.pending_buf_size&&(S(a,255&e.adler),S(a,e.adler>>8&255),e.adler=0,a.status=u)):a.status=u),0!==a.pending){if(f(e),0===e.avail_out)return a.last_flush=-1,0}else if(0===e.avail_in&&p(i)<=p(r)&&4!==i)return g(e,-5);if(a.status===h&&0!==e.avail_in)return g(e,-5);if(0!==e.avail_in||0!==a.lookahead||0!==i&&a.status!==h){var b=2===a.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(E(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(a,i):3===a.strategy?function(e,t){for(var i,r,s,a,o=e.window;;){if(e.lookahead<=l){if(E(e),e.lookahead<=l&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=o[s=e.strstart-1])===o[++s]&&r===o[++s]&&r===o[++s]){a=e.strstart+l;do{}while(r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&s<a);e.match_length=l-(a-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=n._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(a,i):t[a.level].func(a,i);if(3!==b&&4!==b||(a.status=h),1===b||3===b)return 0===e.avail_out&&(a.last_flush=-1),0;if(2===b&&(1===i?n._tr_align(a):5!==i&&(n._tr_stored_block(a,0,0,!1),3===i&&(m(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),f(e),0===e.avail_out))return a.last_flush=-1,0}return 4!==i?0:a.wrap<=0?1:(2===a.wrap?(S(a,255&e.adler),S(a,e.adler>>8&255),S(a,e.adler>>16&255),S(a,e.adler>>24&255),S(a,255&e.total_in),S(a,e.total_in>>8&255),S(a,e.total_in>>16&255),S(a,e.total_in>>24&255)):(y(a,e.adler>>>16),y(a,65535&e.adler)),f(e),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?0:1)},e.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==d&&t!==u&&t!==h?g(e,o):(e.state=null,t===u?g(e,-3):0):o},e.deflateSetDictionary=function(e,t){var n,s,a,l,c,d,u,h,g=t.length;if(!e||!e.state)return o;if(2===(l=(n=e.state).wrap)||1===l&&42!==n.status||n.lookahead)return o;for(1===l&&(e.adler=r(e.adler,t,g,0)),n.wrap=0,g>=n.w_size&&(0===l&&(m(n.head),n.strstart=0,n.block_start=0,n.insert=0),h=new i.Buf8(n.w_size),i.arraySet(h,t,g-n.w_size,n.w_size,0),t=h,g=n.w_size),c=e.avail_in,d=e.next_in,u=e.input,e.avail_in=g,e.next_in=0,e.input=t,E(n);n.lookahead>=3;){s=n.strstart,a=n.lookahead-2;do{n.ins_h=(n.ins_h<<n.hash_shift^n.window[s+3-1])&n.hash_mask,n.prev[s&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=s,s++}while(--a);n.strstart=s,n.lookahead=2,E(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=d,e.input=u,e.avail_in=c,n.wrap=l,0},e.deflateInfo="pako deflate (from Nodeca project)"}}),ee=u({"../node_modules/pako/lib/utils/strings.js"(e){var t=z(),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}var r,s=new t.Buf8(256);for(r=0;r<256;r++)s[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;function a(e,r){if(r<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,t.shrinkBuf(e,r));for(var s="",a=0;a<r;a++)s+=String.fromCharCode(e[a]);return s}s[254]=s[254]=1,e.string2buf=function(e){var i,n,r,s,a,o=e.length,l=0;for(s=0;s<o;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),l+=n<128?1:n<2048?2:n<65536?3:4;for(i=new t.Buf8(l),a=0,s=0;a<l;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),n<128?i[a++]=n:n<2048?(i[a++]=192|n>>>6,i[a++]=128|63&n):n<65536?(i[a++]=224|n>>>12,i[a++]=128|n>>>6&63,i[a++]=128|63&n):(i[a++]=240|n>>>18,i[a++]=128|n>>>12&63,i[a++]=128|n>>>6&63,i[a++]=128|63&n);return i},e.buf2binstring=function(e){return a(e,e.length)},e.binstring2buf=function(e){for(var i=new t.Buf8(e.length),n=0,r=i.length;n<r;n++)i[n]=e.charCodeAt(n);return i},e.buf2string=function(e,t){var i,n,r,o,l=t||e.length,c=new Array(2*l);for(n=0,i=0;i<l;)if((r=e[i++])<128)c[n++]=r;else if((o=s[r])>4)c[n++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i<l;)r=r<<6|63&e[i++],o--;o>1?c[n++]=65533:r<65536?c[n++]=r:(r-=65536,c[n++]=55296|r>>10&1023,c[n++]=56320|1023&r)}return a(c,n)},e.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+s[e[i]]>t?i:t}}}),te=u({"../node_modules/pako/lib/zlib/zstream.js"(e,t){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}}),ie=u({"../node_modules/pako/lib/deflate.js"(e){var t=X(),i=z(),n=ee(),r=Y(),s=te(),a=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=i.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var l=this.options;l.raw&&l.windowBits>0?l.windowBits=-l.windowBits:l.gzip&&l.windowBits>0&&l.windowBits<16&&(l.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,l.level,l.method,l.windowBits,l.memLevel,l.strategy);if(0!==c)throw new Error(r[c]);if(l.header&&t.deflateSetHeader(this.strm,l.header),l.dictionary){var d;if(d="string"==typeof l.dictionary?n.string2buf(l.dictionary):"[object ArrayBuffer]"===a.call(l.dictionary)?new Uint8Array(l.dictionary):l.dictionary,0!==(c=t.deflateSetDictionary(this.strm,d)))throw new Error(r[c]);this._dict_set=!0}}function l(e,t){var i=new o(t);if(i.push(e,!0),i.err)throw i.msg||r[i.err];return i.result}o.prototype.push=function(e,r){var s,o,l=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=r===~~r?r:!0===r?4:0,"string"==typeof e?l.input=n.string2buf(e):"[object ArrayBuffer]"===a.call(e)?l.input=new Uint8Array(e):l.input=e,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new i.Buf8(c),l.next_out=0,l.avail_out=c),1!==(s=t.deflate(l,o))&&0!==s)return this.onEnd(s),this.ended=!0,!1;0!==l.avail_out&&(0!==l.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(n.buf2binstring(i.shrinkBuf(l.output,l.next_out))):this.onData(i.shrinkBuf(l.output,l.next_out)))}while((l.avail_in>0||0===l.avail_out)&&1!==s);return 4===o?(s=t.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,0===s):2!==o||(this.onEnd(0),l.avail_out=0,!0)},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Deflate=o,e.deflate=l,e.deflateRaw=function(e,t){return(t=t||{}).raw=!0,l(e,t)},e.gzip=function(e,t){return(t=t||{}).gzip=!0,l(e,t)}}}),ne=u({"../node_modules/pako/lib/zlib/inffast.js"(e,t){t.exports=function(e,t){var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w;i=e.state,n=e.next_in,I=e.input,r=n+(e.avail_in-5),s=e.next_out,w=e.output,a=s-(t-e.avail_out),o=s+(e.avail_out-257),l=i.dmax,c=i.wsize,d=i.whave,u=i.wnext,h=i.window,g=i.hold,p=i.bits,m=i.lencode,f=i.distcode,v=(1<<i.lenbits)-1,S=(1<<i.distbits)-1;e:do{p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=m[g&v];t:for(;;){if(g>>>=C=y>>>24,p-=C,0==(C=y>>>16&255))w[s++]=65535&y;else{if(!(16&C)){if(64&C){if(32&C){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}y=m[(65535&y)+(g&(1<<C)-1)];continue t}for(T=65535&y,(C&=15)&&(p<C&&(g+=I[n++]<<p,p+=8),T+=g&(1<<C)-1,g>>>=C,p-=C),p<15&&(g+=I[n++]<<p,p+=8,g+=I[n++]<<p,p+=8),y=f[g&S];;){if(g>>>=C=y>>>24,p-=C,16&(C=y>>>16&255)){if(E=65535&y,p<(C&=15)&&(g+=I[n++]<<p,(p+=8)<C&&(g+=I[n++]<<p,p+=8)),(E+=g&(1<<C)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(g>>>=C,p-=C,E>(C=s-a)){if((C=E-C)>d&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(b=0,_=h,0===u){if(b+=c-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}else if(u<C){if(b+=c+u-C,(C-=u)<T){T-=C;do{w[s++]=h[b++]}while(--C);if(b=0,u<T){T-=C=u;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}}}else if(b+=u-C,C<T){T-=C;do{w[s++]=h[b++]}while(--C);b=s-E,_=w}for(;T>2;)w[s++]=_[b++],w[s++]=_[b++],w[s++]=_[b++],T-=3;T&&(w[s++]=_[b++],T>1&&(w[s++]=_[b++]))}else{b=s-E;do{w[s++]=w[b++],w[s++]=w[b++],w[s++]=w[b++],T-=3}while(T>2);T&&(w[s++]=w[b++],T>1&&(w[s++]=w[b++]))}break}if(64&C){e.msg="invalid distance code",i.mode=30;break e}y=f[(65535&y)+(g&(1<<C)-1)]}}break}}while(n<r&&s<o);n-=T=p>>3,g&=(1<<(p-=T<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=s<o?o-s+257:257-(s-o),i.hold=g,i.bits=p}}}),re=u({"../node_modules/pako/lib/zlib/inftrees.js"(e,t){var i=z(),n=[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],r=[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],s=[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],a=[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];t.exports=function(e,t,o,l,c,d,u,h){var g,p,m,f,v,S,y,C,T,E=h.bits,b=0,_=0,I=0,w=0,A=0,P=0,R=0,M=0,D=0,k=0,O=null,N=0,L=new i.Buf16(16),x=new i.Buf16(16),F=null,U=0;for(b=0;b<=15;b++)L[b]=0;for(_=0;_<l;_++)L[t[o+_]]++;for(A=E,w=15;w>=1&&0===L[w];w--);if(A>w&&(A=w),0===w)return c[d++]=20971520,c[d++]=20971520,h.bits=1,0;for(I=1;I<w&&0===L[I];I++);for(A<I&&(A=I),M=1,b=1;b<=15;b++)if(M<<=1,(M-=L[b])<0)return-1;if(M>0&&(0===e||1!==w))return-1;for(x[1]=0,b=1;b<15;b++)x[b+1]=x[b]+L[b];for(_=0;_<l;_++)0!==t[o+_]&&(u[x[t[o+_]]++]=_);if(0===e?(O=F=u,S=19):1===e?(O=n,N-=257,F=r,U-=257,S=256):(O=s,F=a,S=-1),k=0,_=0,b=I,v=d,P=A,R=0,m=-1,f=(D=1<<A)-1,1===e&&D>852||2===e&&D>592)return 1;for(;;){y=b-R,u[_]<S?(C=0,T=u[_]):u[_]>S?(C=F[U+u[_]],T=O[N+u[_]]):(C=96,T=0),g=1<<b-R,I=p=1<<P;do{c[v+(k>>R)+(p-=g)]=y<<24|C<<16|T}while(0!==p);for(g=1<<b-1;k&g;)g>>=1;if(0!==g?(k&=g-1,k+=g):k=0,_++,0==--L[b]){if(b===w)break;b=t[o+u[_]]}if(b>A&&(k&f)!==m){for(0===R&&(R=A),v+=I,M=1<<(P=b-R);P+R<w&&!((M-=L[P+R])<=0);)P++,M<<=1;if(D+=1<<P,1===e&&D>852||2===e&&D>592)return 1;c[m=k&f]=A<<24|P<<16|v-d}}return 0!==k&&(c[v+k]=b-R<<24|64<<16),h.bits=A,0}}}),se=u({"../node_modules/pako/lib/zlib/inflate.js"(e){var t=z(),i=K(),n=J(),r=ne(),s=re(),a=-2,o=12,l=30;function c(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function d(){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 t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function u(e){var i;return e&&e.state?(i=e.state,e.total_in=e.total_out=i.total=0,e.msg="",i.wrap&&(e.adler=1&i.wrap),i.mode=1,i.last=0,i.havedict=0,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new t.Buf32(852),i.distcode=i.distdyn=new t.Buf32(592),i.sane=1,i.back=-1,0):a}function h(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,u(e)):a}function g(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?a:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,h(e))):a}function p(e,t){var i,n;return e?(n=new d,e.state=n,n.window=null,0!==(i=g(e,t))&&(e.state=null),i):a}var m,f,v=!0;function S(e){if(v){var i;for(m=new t.Buf32(512),f=new t.Buf32(32),i=0;i<144;)e.lens[i++]=8;for(;i<256;)e.lens[i++]=9;for(;i<280;)e.lens[i++]=7;for(;i<288;)e.lens[i++]=8;for(s(1,e.lens,0,288,m,0,e.work,{bits:9}),i=0;i<32;)e.lens[i++]=5;s(2,e.lens,0,32,f,0,e.work,{bits:5}),v=!1}e.lencode=m,e.lenbits=9,e.distcode=f,e.distbits=5}function y(e,i,n,r){var s,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new t.Buf8(a.wsize)),r>=a.wsize?(t.arraySet(a.window,i,n-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((s=a.wsize-a.wnext)>r&&(s=r),t.arraySet(a.window,i,n-r,s,a.wnext),(r-=s)?(t.arraySet(a.window,i,n-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=s,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=s))),0}e.inflateReset=h,e.inflateReset2=g,e.inflateResetKeep=u,e.inflateInit=function(e){return p(e,15)},e.inflateInit2=p,e.inflate=function(e,d){var u,h,g,p,m,f,v,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x,F=0,U=new t.Buf8(4),B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return a;(u=e.state).mode===o&&(u.mode=13),m=e.next_out,g=e.output,v=e.avail_out,p=e.next_in,h=e.input,f=e.avail_in,C=u.hold,T=u.bits,E=f,b=v,N=0;e:for(;;)switch(u.mode){case 1:if(0===u.wrap){u.mode=13;break}for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(2&u.wrap&&35615===C){u.check=0,U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0),C=0,T=0,u.mode=2;break}if(u.flags=0,u.head&&(u.head.done=!1),!(1&u.wrap)||(((255&C)<<8)+(C>>8))%31){e.msg="incorrect header check",u.mode=l;break}if(8!=(15&C)){e.msg="unknown compression method",u.mode=l;break}if(T-=4,O=8+(15&(C>>>=4)),0===u.wbits)u.wbits=O;else if(O>u.wbits){e.msg="invalid window size",u.mode=l;break}u.dmax=1<<O,e.adler=u.check=1,u.mode=512&C?10:o,C=0,T=0;break;case 2:for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(u.flags=C,8!=(255&u.flags)){e.msg="unknown compression method",u.mode=l;break}if(57344&u.flags){e.msg="unknown header flags set",u.mode=l;break}u.head&&(u.head.text=C>>8&1),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0,u.mode=3;case 3:for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.head&&(u.head.time=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,U[2]=C>>>16&255,U[3]=C>>>24&255,u.check=n(u.check,U,4,0)),C=0,T=0,u.mode=4;case 4:for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.head&&(u.head.xflags=255&C,u.head.os=C>>8),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0,u.mode=5;case 5:if(1024&u.flags){for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.length=C,u.head&&(u.head.extra_len=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,T=0}else u.head&&(u.head.extra=null);u.mode=6;case 6:if(1024&u.flags&&((_=u.length)>f&&(_=f),_&&(u.head&&(O=u.head.extra_len-u.length,u.head.extra||(u.head.extra=new Array(u.head.extra_len)),t.arraySet(u.head.extra,h,p,_,O)),512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,u.length-=_),u.length))break e;u.length=0,u.mode=7;case 7:if(2048&u.flags){if(0===f)break e;_=0;do{O=h[p+_++],u.head&&O&&u.length<65536&&(u.head.name+=String.fromCharCode(O))}while(O&&_<f);if(512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,O)break e}else u.head&&(u.head.name=null);u.length=0,u.mode=8;case 8:if(4096&u.flags){if(0===f)break e;_=0;do{O=h[p+_++],u.head&&O&&u.length<65536&&(u.head.comment+=String.fromCharCode(O))}while(O&&_<f);if(512&u.flags&&(u.check=n(u.check,h,_,p)),f-=_,p+=_,O)break e}else u.head&&(u.head.comment=null);u.mode=9;case 9:if(512&u.flags){for(;T<16;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C!==(65535&u.check)){e.msg="header crc mismatch",u.mode=l;break}C=0,T=0}u.head&&(u.head.hcrc=u.flags>>9&1,u.head.done=!0),e.adler=u.check=0,u.mode=o;break;case 10:for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}e.adler=u.check=c(C),C=0,T=0,u.mode=11;case 11:if(0===u.havedict)return e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,2;e.adler=u.check=1,u.mode=o;case o:if(5===d||6===d)break e;case 13:if(u.last){C>>>=7&T,T-=7&T,u.mode=27;break}for(;T<3;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}switch(u.last=1&C,T-=1,3&(C>>>=1)){case 0:u.mode=14;break;case 1:if(S(u),u.mode=20,6===d){C>>>=2,T-=2;break e}break;case 2:u.mode=17;break;case 3:e.msg="invalid block type",u.mode=l}C>>>=2,T-=2;break;case 14:for(C>>>=7&T,T-=7&T;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if((65535&C)!=(C>>>16^65535)){e.msg="invalid stored block lengths",u.mode=l;break}if(u.length=65535&C,C=0,T=0,u.mode=15,6===d)break e;case 15:u.mode=16;case 16:if(_=u.length){if(_>f&&(_=f),_>v&&(_=v),0===_)break e;t.arraySet(g,h,p,_,m),f-=_,p+=_,v-=_,m+=_,u.length-=_;break}u.mode=o;break;case 17:for(;T<14;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(u.nlen=257+(31&C),C>>>=5,T-=5,u.ndist=1+(31&C),C>>>=5,T-=5,u.ncode=4+(15&C),C>>>=4,T-=4,u.nlen>286||u.ndist>30){e.msg="too many length or distance symbols",u.mode=l;break}u.have=0,u.mode=18;case 18:for(;u.have<u.ncode;){for(;T<3;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.lens[B[u.have++]]=7&C,C>>>=3,T-=3}for(;u.have<19;)u.lens[B[u.have++]]=0;if(u.lencode=u.lendyn,u.lenbits=7,L={bits:u.lenbits},N=s(0,u.lens,0,19,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid code lengths set",u.mode=l;break}u.have=0,u.mode=19;case 19:for(;u.have<u.nlen+u.ndist;){for(;P=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(R<16)C>>>=A,T-=A,u.lens[u.have++]=R;else{if(16===R){for(x=A+2;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C>>>=A,T-=A,0===u.have){e.msg="invalid bit length repeat",u.mode=l;break}O=u.lens[u.have-1],_=3+(3&C),C>>>=2,T-=2}else if(17===R){for(x=A+3;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}T-=A,O=0,_=3+(7&(C>>>=A)),C>>>=3,T-=3}else{for(x=A+7;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}T-=A,O=0,_=11+(127&(C>>>=A)),C>>>=7,T-=7}if(u.have+_>u.nlen+u.ndist){e.msg="invalid bit length repeat",u.mode=l;break}for(;_--;)u.lens[u.have++]=O}}if(u.mode===l)break;if(0===u.lens[256]){e.msg="invalid code -- missing end-of-block",u.mode=l;break}if(u.lenbits=9,L={bits:u.lenbits},N=s(1,u.lens,0,u.nlen,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid literal/lengths set",u.mode=l;break}if(u.distbits=6,u.distcode=u.distdyn,L={bits:u.distbits},N=s(2,u.lens,u.nlen,u.ndist,u.distcode,0,u.work,L),u.distbits=L.bits,N){e.msg="invalid distances set",u.mode=l;break}if(u.mode=20,6===d)break e;case 20:u.mode=21;case 21:if(f>=6&&v>=258){e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,r(e,b),m=e.next_out,g=e.output,v=e.avail_out,p=e.next_in,h=e.input,f=e.avail_in,C=u.hold,T=u.bits,u.mode===o&&(u.back=-1);break}for(u.back=0;P=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(P&&!(240&P)){for(M=A,D=P,k=R;P=(F=u.lencode[k+((C&(1<<M+D)-1)>>M)])>>>16&255,R=65535&F,!(M+(A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}C>>>=M,T-=M,u.back+=M}if(C>>>=A,T-=A,u.back+=A,u.length=R,0===P){u.mode=26;break}if(32&P){u.back=-1,u.mode=o;break}if(64&P){e.msg="invalid literal/length code",u.mode=l;break}u.extra=15&P,u.mode=22;case 22:if(u.extra){for(x=u.extra;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.length+=C&(1<<u.extra)-1,C>>>=u.extra,T-=u.extra,u.back+=u.extra}u.was=u.length,u.mode=23;case 23:for(;P=(F=u.distcode[C&(1<<u.distbits)-1])>>>16&255,R=65535&F,!((A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(!(240&P)){for(M=A,D=P,k=R;P=(F=u.distcode[k+((C&(1<<M+D)-1)>>M)])>>>16&255,R=65535&F,!(M+(A=F>>>24)<=T);){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}C>>>=M,T-=M,u.back+=M}if(C>>>=A,T-=A,u.back+=A,64&P){e.msg="invalid distance code",u.mode=l;break}u.offset=R,u.extra=15&P,u.mode=24;case 24:if(u.extra){for(x=u.extra;T<x;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}u.offset+=C&(1<<u.extra)-1,C>>>=u.extra,T-=u.extra,u.back+=u.extra}if(u.offset>u.dmax){e.msg="invalid distance too far back",u.mode=l;break}u.mode=25;case 25:if(0===v)break e;if(_=b-v,u.offset>_){if((_=u.offset-_)>u.whave&&u.sane){e.msg="invalid distance too far back",u.mode=l;break}_>u.wnext?(_-=u.wnext,I=u.wsize-_):I=u.wnext-_,_>u.length&&(_=u.length),w=u.window}else w=g,I=m-u.offset,_=u.length;_>v&&(_=v),v-=_,u.length-=_;do{g[m++]=w[I++]}while(--_);0===u.length&&(u.mode=21);break;case 26:if(0===v)break e;g[m++]=u.length,v--,u.mode=21;break;case 27:if(u.wrap){for(;T<32;){if(0===f)break e;f--,C|=h[p++]<<T,T+=8}if(b-=v,e.total_out+=b,u.total+=b,b&&(e.adler=u.check=u.flags?n(u.check,g,b,m-b):i(u.check,g,b,m-b)),b=v,(u.flags?C:c(C))!==u.check){e.msg="incorrect data check",u.mode=l;break}C=0,T=0}u.mode=28;case 28:if(u.wrap&&u.flags){for(;T<32;){if(0===f)break e;f--,C+=h[p++]<<T,T+=8}if(C!==(4294967295&u.total)){e.msg="incorrect length check",u.mode=l;break}C=0,T=0}u.mode=29;case 29:N=1;break e;case l:N=-3;break e;case 31:return-4;default:return a}return e.next_out=m,e.avail_out=v,e.next_in=p,e.avail_in=f,u.hold=C,u.bits=T,(u.wsize||b!==e.avail_out&&u.mode<l&&(u.mode<27||4!==d))&&y(e,e.output,e.next_out,b-e.avail_out),E-=e.avail_in,b-=e.avail_out,e.total_in+=E,e.total_out+=b,u.total+=b,u.wrap&&b&&(e.adler=u.check=u.flags?n(u.check,g,b,e.next_out-b):i(u.check,g,b,e.next_out-b)),e.data_type=u.bits+(u.last?64:0)+(u.mode===o?128:0)+(20===u.mode||15===u.mode?256:0),(0===E&&0===b||4===d)&&0===N&&(N=-5),N},e.inflateEnd=function(e){if(!e||!e.state)return a;var t=e.state;return t.window&&(t.window=null),e.state=null,0},e.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,0):a},e.inflateSetDictionary=function(e,t){var n,r=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?a:11===n.mode&&i(1,t,r,0)!==n.check?-3:y(e,t,r,r)?(n.mode=31,-4):(n.havedict=1,0):a},e.inflateInfo="pako inflate (from Nodeca project)"}}),ae=u({"../node_modules/pako/lib/zlib/constants.js"(e,t){t.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}}}),oe=u({"../node_modules/pako/lib/zlib/gzheader.js"(e,t){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}}}),le=u({"../node_modules/pako/lib/inflate.js"(e){var t=se(),i=z(),n=ee(),r=ae(),s=Y(),a=te(),o=oe(),l=Object.prototype.toString;function c(e){if(!(this instanceof c))return new c(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var d=this.options;d.raw&&d.windowBits>=0&&d.windowBits<16&&(d.windowBits=-d.windowBits,0===d.windowBits&&(d.windowBits=-15)),!(d.windowBits>=0&&d.windowBits<16)||e&&e.windowBits||(d.windowBits+=32),d.windowBits>15&&d.windowBits<48&&(15&d.windowBits||(d.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var u=t.inflateInit2(this.strm,d.windowBits);if(u!==r.Z_OK)throw new Error(s[u]);if(this.header=new o,t.inflateGetHeader(this.strm,this.header),d.dictionary&&("string"==typeof d.dictionary?d.dictionary=n.string2buf(d.dictionary):"[object ArrayBuffer]"===l.call(d.dictionary)&&(d.dictionary=new Uint8Array(d.dictionary)),d.raw&&(u=t.inflateSetDictionary(this.strm,d.dictionary))!==r.Z_OK))throw new Error(s[u])}function d(e,t){var i=new c(t);if(i.push(e,!0),i.err)throw i.msg||s[i.err];return i.result}c.prototype.push=function(e,s){var a,o,c,d,u,h=this.strm,g=this.options.chunkSize,p=this.options.dictionary,m=!1;if(this.ended)return!1;o=s===~~s?s:!0===s?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=n.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(g),h.next_out=0,h.avail_out=g),(a=t.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&p&&(a=t.inflateSetDictionary(this.strm,p)),a===r.Z_BUF_ERROR&&!0===m&&(a=r.Z_OK,m=!1),a!==r.Z_STREAM_END&&a!==r.Z_OK)return this.onEnd(a),this.ended=!0,!1;h.next_out&&(0!==h.avail_out&&a!==r.Z_STREAM_END&&(0!==h.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=n.utf8border(h.output,h.next_out),d=h.next_out-c,u=n.buf2string(h.output,c),h.next_out=d,h.avail_out=g-d,d&&i.arraySet(h.output,h.output,c,d,0),this.onData(u)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(m=!0)}while((h.avail_in>0||0===h.avail_out)&&a!==r.Z_STREAM_END);return a===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(a=t.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),h.avail_out=0,!0)},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Inflate=c,e.inflate=d,e.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},e.ungzip=d}}),ce=u({"../node_modules/pako/index.js"(e,t){var i={};(0,z().assign)(i,ie(),le(),ae()),t.exports=i}}),de=u({"../signaling-agent/node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.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(e){return null!=e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.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(e){return null!=e.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(e){return null!=e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.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(e){return"x-signaling-fb:"+("*"===e.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(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ue=u({"../signaling-agent/node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))})(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=de(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),he=u({"../signaling-agent/node_modules/sdp-transform/lib/writer.js"(e,t){var i=de(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?n.push(i[t.name][a]):n.push(i[t.names[s]])}else n.push(i[t.name]);return r.apply(null,n)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||a,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))})),e.media.forEach((function(e){l.push(s("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),ge=u({"../signaling-agent/node_modules/sdp-transform/lib/index.js"(e){var t=ue(),i=he();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),pe=u({"../skype-calling-utilities/dist/skype-calling-utilities.bundle.js"(e,t){var i,n;i=e,n=(e,t)=>{var i={},n={exports:i},r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,l={};((e,t)=>{for(var i in t)r(e,i,{get:t[i],enumerable:!0})})(l,{SlimCoreElectronControlCapturer:()=>p}),n.exports=(e=>((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of a(t))o.call(e,i)||undefined===i||r(e,i,{get:()=>t[i],enumerable:!(n=s(t,i))||n.enumerable});return e})(r({},"__esModule",{value:!0}),e))(l);var c=Z;var d,u=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new h(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",function(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}(e))}}))}},h=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,c.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},g=class extends u{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}async onAsync(e,t){return this.on(e,t)}async onceAsync(e,t,i){return this.once(e,t,i)}async changedAsync(e,t){return this.changed(e,t)}async disposeAsync(e){this.dispose(e)}};(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,s=(e.buttonDown?1:0)<<5,a=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|s|a),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,s=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|s),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(d||(d={}));var p=class extends g{constructor(e,t,i=!0,n=1){super(),this._logger=e,this._element=t,this._captureRegionPreserveAspectRatio=i,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()}),250)},this._handleMouseLeave=e=>{!this._isOnScreenContent(e)&&this._isMouseOnRenderer&&(this._raiseCaptureEvent(2),this._logger.info("Mouse leaving render region")),this._isMouseOnRenderer=!1},this._handleMouseEnter=e=>{this._isOnScreenContent(e)&&(this._isMouseOnRenderer=!0,this._raiseCaptureEvent(1),this._logger.info("Mouse entering render region"))},this._handleLosingFocus=()=>{this._syncKeyStates(!0)},this._handleClick=e=>{this._isOnScreenContent(e)&&(this._raiseCaptureEvent(0),this._logger.info("Mouse clicked"))},this._handleMouseMove=e=>{if(!this._isOnScreenContent(e)&&this._isMouseOnRenderer)return this._raiseCaptureEvent(2),this._isMouseOnRenderer=!1,void this._logger.info("Mouse leaving render region");if(this._isOnScreenContent(e)&&!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(e)||!this._shouldMoveMouse())return}else if(!this._isOnScreenContent(e)||this._mouseMoveCount%2==0)return;const t={type:0};this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseDown=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:m(e.button),buttonDown:!0};this._isMouseDown=!0,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseUp=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:m(e.button),buttonDown:!1};this._isMouseDown=!1,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleKeyDown=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!1}),e.stopPropagation(),e.preventDefault()},this._handleKeyUp=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!0}),e.stopPropagation(),e.preventDefault()},this._handleWheel=e=>{this._raiseMouseEvent({type:1,wheelRotation:e.deltaY>0?-120:120})},this._handleContextMenu=e=>{e.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(t.clientHeight*n),height:t.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(e){this._mouseMoveThrottlingEnabled=e}dispose(e){this._logger.info(`dispose causeId: ${e}`),window.clearTimeout(this._pollTimerID),this._element.ownerDocument?.defaultView?.removeEventListener("resize",this._handleResizeEvents,!1),super.dispose(e)}updateVideoSize(e,t){this._videoSize.width=e,this._videoSize.height=t,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(e){3===this._captureMode&&3!==e&&this._syncKeyStates(!0),this._captureMode=e,0!==e?("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===e?(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()}),3e3)}_raiseMouseEvent(e){this.event("mouseControlEvent").raise(e)}_raiseKeyboardEvent(e){this.event("keyboardControlEvent").raise(e)}_raiseCaptureEvent(e){this.event("ctrlCaptureEvent").raise(e)}_normalizeMousePosition(e,t){t.xPos=(e.offsetX-this._captureRegion.left)/this._captureRegion.width*65535,t.yPos=(e.offsetY-this._captureRegion.top)/this._captureRegion.height*65535}_isOnScreenContent(e){const t=this._captureRegion.left,i=this._captureRegion.left+this._captureRegion.width,n=this._captureRegion.top,r=this._captureRegion.top+this._captureRegion.height;return t<=e.offsetX&&e.offsetX<i&&n<=e.offsetY&&e.offsetY<r}_shouldMoveMouse(){if(this._mouseMoveStartTime){const e=(new Date).getTime(),t=e-this._mouseMoveStartTime;if(this._isMouseDown&&t>=30||!this._isMouseDown&&t>=50)return this._mouseMoveStartTime=e,!0}else this._mouseMoveStartTime=(new Date).getTime();return!1}_syncKeyStates(e){this._raiseKeyboardEvent({codeType:1,code:17,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:16,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:18,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:91,repeat:!1,keyUp:e}),this._logger.info("Synced Key states.")}static formatMouseEvent(e){return d.encodeMouseEvent(e)}static formatKeyboardEvent(e){return d.encodeKeyboardEvent(e)}};function m(e){switch(e){case 0:return 0;case 2:return 1;case 1:return 2;default:return}}return"object"==typeof n.exports&&(n.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||undefined===i||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(n=Object.getOwnPropertyDescriptor(t,i))||n.enumerable});return e})(n.exports,i)),n.exports},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e["skype-calling-utilities"]=n():i["skype-calling-utilities"]=n(i["@skype/rt-js-bindings"],i.lodash)}}),me=u({"../node_modules/synctasks/dist/SyncTasks.js"(e){function t(e){return null!=e&&"function"==typeof e.then}function i(e){return null!=e&&"function"==typeof e.cancel}function n(t,i){if(!e.config.catchExceptions)return t();try{return t()}catch(e){return i(e)}}Object.defineProperty(e,"__esModule",{value:!0}),e.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(e){throw e}},e.fromThenable=function(e){var t=u();return e.then((function(e){t.resolve(e)}),(function(e){t.reject(e)})),t.promise().thenAsync((function(e){return e}))};var r,s,a,o=[],l="undefined"!=typeof setImmediate;function c(e){o.push(e),1===o.length&&(l?setImmediate(d):setTimeout(d,0))}function d(){var e=o;o=[];for(var t=0;t<e.length;t++)e[t]()}function u(){return new r.SyncTask}function h(e){return(new r.SyncTask).resolve(e).promise()}function g(e){var n=u(),s=!1;return n.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))})),e.forEach((function(e){t(e)?e.then((function(e){s||(s=!0,n.resolve(e))}),(function(e){s||(s=!0,n.reject(e))})):s||(s=!0,n.resolve(e))})),n.promise()}e.asyncCallback=c,s=r||(r={}),a=function(){function r(){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 r.prototype._addCallbackSet=function(e,t){var i=this,n=new r;return n.onCancel((function(t){e.wasCanceled=!0,e.cancelContext=t,i._cancelInternal(t)})),e.task=n,this._storedCallbackSets.push(e),t?this._mustHandleError=!1:n._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),n.promise()},r.prototype.onCancel=function(e){return this._completedSuccess||this._completedFail||(this._wasCanceled?e(this._cancelContext):this._cancelCallbacks.push(e)),this},r.prototype.then=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t},!0)},r.prototype.thenAsync=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t,asyncCallback:!0},!0)},r.prototype.catch=function(e){return this._addCallbackSet({failFunc:e},!0)},r.prototype.always=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!0)},r.prototype.setTracingEnabled=function(e){return this._traceEnabled=e,this},r.prototype.finally=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!1),this},r.prototype.done=function(e){return this._addCallbackSet({successFunc:e},!1),this},r.prototype.fail=function(e){return this._addCallbackSet({failFunc:e},!1),this},r.prototype.resolve=function(e){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=e,this._cancelCallbacks=[],this._resolveSuccesses(),this},r.prototype.reject=function(e){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=e,this._cancelCallbacks=[],this._resolveFailures(),r._enforceErrorHandled(this),this},r.prototype._checkState=function(t){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var i="Failed to "+(t?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(i)}(e.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},r._enforceErrorHandled=function(t){t._mustHandleError&&(r._rejectedTasks.push(t),r._enforceErrorHandledTimer||(r._enforceErrorHandledTimer=setTimeout((function(){r._enforceErrorHandledTimer=void 0;var t=r._rejectedTasks;r._rejectedTasks=[],t.forEach((function(t,i){t._mustHandleError&&e.config.unhandledErrorHandler(t._storedErrResolution)}))}),0)))},r.prototype.cancel=function(e){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(e)},r.prototype._cancelInternal=function(e){var t=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=e;var i=this._cancelCallbacks;this._cancelCallbacks=[],i.length>0&&i.forEach((function(e){t._completedSuccess||t._completedFail||e(t._cancelContext)}))}},r.cancelOtherInternal=function(e,t){var i=e;i._storedCallbackSets&&i._cancelInternal?i._cancelInternal(t):e.cancel(t)},r.prototype.promise=function(){return this},r.prototype._resolveSuccesses=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveSuccessCallback(t)})):e._resolveSuccessCallback(t)}))}this._resolving=!1},r.prototype._resolveSuccessCallback=function(e){var s=this;e.successFunc?n((function(){var n=e.successFunc(s._storedResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){s._handleException(t,"SyncTask caught exception in success block: "+t.toString()),e.task.reject(t)})):e.task.resolve(this._storedResolution)},r.prototype._resolveFailures=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveFailureCallback(t)})):e._resolveFailureCallback(t)}))}this._resolving=!1},r.prototype._resolveFailureCallback=function(e){var s=this;e.failFunc?n((function(){var n=e.failFunc(s._storedErrResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){s._handleException(t,"SyncTask caught exception in failure block: "+t.toString()),e.task.reject(t)})):e.task.reject(this._storedErrResolution)},r.prototype._handleException=function(t,i){e.config.exceptionsToConsole&&console.error(i),e.config.exceptionHandler&&e.config.exceptionHandler(t)},r.prototype.toEs6Promise=function(){var e=this;return new Promise((function(t,i){return e.then(t,i)}))},r._rejectedTasks=[],r}(),s.SyncTask=a,e.all=function(e){if(0===e.length)return h([]);var n,s=u(),a=e.length,o=Array(e.length);s.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))}));var l=function(){0==--a&&(void 0!==n?s.reject(n):s.resolve(o))};return e.forEach((function(e,i){t(e)?e.then((function(e){o[i]=e,l()}),(function(e){void 0===n&&(n=void 0===e||e),l()})):(o[i]=e,l())})),s.promise()},e.Defer=u,e.Resolved=h,e.Rejected=function(e){return(new r.SyncTask).reject(e).promise()},e.race=g,e.raceTimer=function(e,t){var i=u(),n=setTimeout((function(){i.resolve({timedOut:!0})}),t);return g([e.then((function(e){return clearTimeout(n),{timedOut:!1,result:e}})),i.promise()])}}}),fe=u({"../node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.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(e){return null!=e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.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(e){return null!=e.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(e){return null!=e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.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(e){return"x-signaling-fb:"+("*"===e.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(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ve=u({"../node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))})(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=fe(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),Se=u({"../node_modules/sdp-transform/lib/writer.js"(e,t){var i=fe(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?n.push(i[t.name][a]):n.push(i[t.names[s]])}else n.push(i[t.name]);return r.apply(null,n)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||a,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))})),e.media.forEach((function(e){l.push(s("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(s(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),ye=u({"../node_modules/sdp-transform/lib/index.js"(e){var t=ve(),i=Se();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),Ce={};h(Ce,{HttpRequestDispatcherImplementation:()=>st,generateCauseId:()=>be,getOvb:()=>mt,getVersion:()=>pt,pluginlessStackFactory:()=>lG,whiteList:()=>cG}),n.exports=(e=>g(a({},"__esModule",{value:!0}),e))(Ce);var Te=p(j()),Ee=8;function be(){let e="";for(let t=0;t<Ee;t++)e+="abcdef0123456789".charAt(Math.floor(16*Math.random()));return e}function _e(e){return new RegExp("^[a-f0-9]{8}$").test(e)&&e.length===Ee}var Ie=Q,we=Z,Ae=class e{constructor(e,t,i=""){this.ulLogComponent=e,this.ulSafeComponent=t,this._getPrefix=(0,we.isFunction)(i)?i:()=>i,this.logComponent=Ie.LogFactory.instance().component(this.ulLogComponent),Ie.LogFactory.instance().declareComponentSafe(this.ulLogComponent,t)}createChild(t){const i=(0,we.isFunction)(t)?t:()=>t;return new e(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${i()}`:i()))}log(...e){this._apply((e=>this.logComponent.debug2(null,e)),e)}debug(...e){this._apply((e=>this.logComponent.debug4(null,e)),e)}info(...e){this._apply((e=>this.logComponent.debug1(null,e)),e)}warn(...e){this._apply((e=>this.logComponent.warn(null,e)),e)}error(...e){this._apply((e=>this.logComponent.error(null,e)),e)}_apply(e,t=[]){this._addPrefix(t),e(t.map((e=>e instanceof DOMException?e.toString():e)).map((e=>(0,we.isObject)(e)?JSON.stringify(e):e)).join(", "))}_addPrefix(e){if(e&&e[0]){const t=`${this._getPrefix()} ${e[0]}`;e[0]=t}}},Pe=Q,Re=class{constructor(e,t){this.value=e,this.piiKind=t}},Me=["id"," orgid","username","phonenumber"];function De(e){return"string"==typeof e?Pe.pii.Mri(e):Pe.pii.Omit(e)}function ke(e,t=["id"],i={threadId:8}){if(!e||"object"!=typeof e)return e;try{let n=function(e){if(!e||"object"!=typeof e)return e;const t=new Set,i=JSON.stringify(e,((e,i)=>{if("object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}));return JSON.parse(i)}(e);return n=Fe(n,t,i),n}catch(e){return{error:"failed to scrub object fields"}}}function Oe(e){try{const t={};return Object.keys(e).forEach((i=>{const n=De(i);t[n]=e[i]})),t}catch(e){return{error:"failed to scrub mri keys"}}}function Ne(e){return JSON.stringify(Oe(e))}function Le(e){return e&&Pe.pii.Mri(e)}function xe(e){const t=function(e){return e&&"99:"===e.substr(0,3)?Pe.pii.Omit(e):e}(e);return t&&t.substr(0,8)}function Fe(e,t,i){if(!e||"object"!=typeof e)return e;const n={...e};for(const[r,s]of Object.entries(e))Array.isArray(s)?n[r]=s.map((e=>Fe(e,t,i))):"object"==typeof s?n[r]=Fe(s,t,i):"displayname"===r.toLowerCase()?n[r]="<redacted>":s&&(t.includes(r)||Me.includes(r.toLowerCase())?n[r]=De(s):i[r]&&"string"==typeof s&&(n[r]=s.toString().substring(0,i[r])));return n}function Ue(e){const t=String.raw`[\\]*['|\"]?\s*[\:|=]\s*[\\]*['|\"]?`,i=String.raw`[a-zA-Z\d#.~?!@$%^&*-_()+]*?`;return new RegExp(String.raw`((?:${e})${t})(${i})(\\{0,2}['\"])`,"g")}function Be(e){return(t,i,n,r)=>"false"===n?.toLowerCase()||"true"===n?.toLowerCase()?t:String.raw`${i}${e(n)}${r}`}var Ve=p(Z),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 $e(e){try{return JSON.parse(JSON.stringify(e,He,4))}catch(e){return{error:"failed to parse object"}}}function je(e,t=!1){if(null==e)return"void";if(e instanceof Error)return e.toString();if(e instanceof String||e instanceof Number||e instanceof Boolean)return e.toString();try{return e.stack&&(e.stack=(e=>{try{return e.split("\n")[0]}catch(e){return"invalid stack"}})(e.stack)),(t?JSON.stringify(e):JSON.stringify(e,He,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(t){return`failed to get error information:${e&&"function"==typeof e.toString&&e.toString()} ${e?.response&&JSON.stringify(e.response)}`}}function Ge(e){try{return JSON.stringify(e,null,2)}catch(t){return`failed to stringify obj ${e}`}}function qe(e,t){try{return e.substring(0,t)}catch(t){return e}}function ze(e){return e||!1===e||""===e||0===e}function We(e,t){try{const i=ke(e);return Object.keys(e).forEach((n=>{t.includes(n)?i[n]=De(e[n]):"conversationId"===n&&(i[n]=xe(e[n]))})),Ge(Ve.omit(i,["body.gp"]))}catch(e){return{error:"failed to get safe payload"}}}function Ke(e){try{let t=ke(e,["id","groupCallInitiator","organizerId"]);return Ze(t,"response.roster.participants"),Ze(t,"response.additionalActionResponses.0.output.roster.participants"),Ze(t,"response.muteUnmuteResponse"),t=Ve.omit(t,["meetingChatProperties"]),t=Ye(t),t}catch(e){return"failed to return safe response"}}function Je(e){try{return Ye(ke(e))}catch(e){return"failed to return safe request"}}function Ye(e){if(e?.config?.data){let t=e.config.data;t=JSON.parse(t),t=ke(t),e.config.data=Ge(t)}return Ge(e)}function Qe(e){try{return Ge(ke(e,["originalId"]))}catch(e){return"failed to return safe endpoint details"}}function Ze(e,t){e&&Ve.get(e,t)&&Ve.set(e,t,Oe(Ve.get(e,t)))}function Xe(e){if(!e)return!1;try{return atob(e),!0}catch(e){return!1}}function et(e){return!!e&&"function"==typeof e.then}function tt(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}function it(e){try{if(e.status)return`status: ${e.status}, URL: ${e.responseURL}, statusText: ${e.responseText}`}catch(e){}return tt(e)}function nt(e,t,i=0){return e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t),e}function rt(e,t,i,n=0){nt(e,0===i?0:i-1,n),0!==i&&e.push(t)}var st=class{constructor(e){e&&"function"==typeof e.createChild?this.logger=e.createChild("RequestDispatcher"):this.logger=new Ae("JS.TsCalling.RequestDispatcher",!1)}getRequestOptions(e,t,i,n,r){return{headers:t||{},timeout:n,payload:i||null,responseType:r}}getAsync(e,t){return this.sendRequest(e,t,"GET")}postAsync(e,t){return this.sendRequest(e,t,"POST")}putAsync(e,t){return this.sendRequest(e,t,"PUT")}removeAsync(e,t){return this.sendRequest(e,t,"DELETE")}async sendRequest(e,t={headers:{}},i){return t.useFetch?this.sendFetchRequest(e,t,i):this.sendAxiosRequest(e,t,i)}async sendAxiosRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||be()}][AxiosRequest]`);n.info(`sending, ${i}-${e}`);const r=Date.now();let s;ot(t);try{const a=Te.default.request({url:e,method:i,headers:t.headers,timeout:"number"==typeof t.timeout?t.timeout:45e3,data:t.payload||"",responseType:t.responseType||t.dataType||"json",withCredentials:at(t.withCredentials,!1),cancelToken:new Te.default.CancelToken((e=>{s=e}))});et(t.timeout)&&t.timeout.then((()=>{n.info("Aborting pending request"),s()}),(()=>{n.info("Timeout promise rejected, ignoring")}));const o=await a;return n.info(`success, status=${o.status}`),{response:o.data,request:{status:o.status,statusText:o.statusText,headers:o.headers,responseURL:o.request.responseURL,readyState:o.request.readyState,response:o.request.response,responseText:""===o.request.responseType||"text"===o.request.responseType?o.request.responseText:"",withCredentials:o.request.withCredentials},duration:Date.now()-r}}catch(e){if(n.info("failed"),Te.default.isCancel(e))throw n.info(`response=${Ke(e.message)}`),{aborted:!0};throw e.response?n.info(`response=${Ke(e.response)}`):e.request?n.info(`no response, request=${Je(e.request)}`):n.info(`request not made, error=${je(e)}`),e||new Error("Request failed")}}async sendFetchRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||be()}][FetchRequest]`);n.info(`sending, ${i}-${e}`);const r=Date.now(),s=new AbortController;let a,o=null,l=null;const c=()=>{n.info("Aborting pending request"),s.abort()};ot(t);try{if(t.fetchUseKeepAlive&&t.payload?.toString().length>65e3&&n.warn("Using fetch with keep alive with more than 64kib data"),n.info(`${JSON.stringify(t.headers)}`),o=fetch(e,{method:i,headers:t.headers,body:t.payload,credentials:t.withCredentials?"include":"same-origin",signal:s.signal,keepalive:t.fetchUseKeepAlive}),et(t.timeout))t.timeout.then((()=>{c()}),(()=>{n.info("Timeout promise rejected, ignoring")}));else if(t.timeout){const e=setTimeout((()=>c()),t.timeout);o=o.finally((()=>clearTimeout(e)))}l=await o;try{a=await l.json()}catch(e){n.info(`unable to parse response as json with error ${e}`)}const d={response:a,request:{status:l.status,statusText:l.statusText,headers:Object.fromEntries(l.headers.entries()),responseURL:l.url,response:a,withCredentials:t.withCredentials},duration:Date.now()-r};if(!l.ok)throw n.info(`failed response, status=${l.status}`),d;return n.info(`success, status=${l.status}`),d}catch(e){if(n.info(`failed error=${je(e)}`),"AbortError"===e.name)throw{aborted:!0};throw e||new Error("Request failed")}}};function at(e,t){return void 0!==e?e:t}function ot(e){e.headers=e.headers||{},e.headers["content-type"]||(e.headers["content-type"]=e.contentType||"application/json")}var lt=Z,ct=class e{constructor(e){this._callingLogger=e,this._maybeLog=(e,...t)=>{try{this._callingLogger[e](...t)}catch(e){this._callingLogger.info("[failed to log]",je(e))}}}getPrefix(e,t){let i="";return t&&(i+=`[${t}]`),e&&(i+=`[${e}]`),i}createChild(t,i){return new e(this._callingLogger.createChild(t,i))}createFnLogger(t,i,...n){return new e(this._callingLogger.createChild(this.getPrefix(t,i)+n.join(""),!1))}logSuccess(e){this._maybeLog("info",`success=${e}}`)}logFailure(e){const t=je(e);this._maybeLog("info",`failed=${t}}`)}log(...e){this._maybeLog("log",...e)}debug(...e){this._maybeLog("debug",...e)}info(...e){this._maybeLog("info",...e)}warn(...e){this._maybeLog("warn",...e)}error(...e){this._maybeLog("error",...e)}},dt=Z,ut=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new ht(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",tt(e))}}))}},ht=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,dt.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},gt=class extends ut{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}async onAsync(e,t){return this.on(e,t)}async onceAsync(e,t,i){return this.once(e,t,i)}async changedAsync(e,t){return this.changed(e,t)}async disposeAsync(e){this.dispose(e)}};function pt(){return"2025.07.01.15"}function mt(){return"8962f6ae8324f6a345d7997ae8f276ff81198956"}var ft=Z,vt=p(G()),St="Android",yt="iOS",Ct="Mac OS",Tt="Opera",Et="Edge",bt="Yandex",_t="Safari",It="Mobile Safari",wt="WebKit",At="Blink",Pt="EdgeHTML",Rt="Gecko",Mt="WebKit",Dt="Unknown",kt="0.0",Ot=class e{constructor(){const e=navigator.userAgent,t=new vt.UAParser(e).getResult();this.browserInfo={name:t.browser.name||"Unknown",engine:t.engine.name||"Unknown",version:t.browser.version||kt,formFactor:Nt(t)||"Unknown",osName:t.os.name||Dt,osVersion:t.os.version||Dt},this.modifyParserResult(t)}static get instance(){return e._instance||(e._instance=new e),e._instance}static isFormFactor(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().formFactor)}static isEngine(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().engine)}static isBrowser(...e){return e.map((e=>e.toString())).includes(this.getBrowserInfo().name)}static isVersionGreaterOrEqual(e){const t=this.getBrowserInfo().version,i=e.split(".").map((e=>parseInt(e,10))),n=t.split(".").map((e=>parseInt(e,10)));return n[0]>i[0]||n[0]===i[0]&&n[1]>=i[1]}static getBrowserInfo(){return this.instance.browserInfo}static isRemote(){return window.navigator.mediaDevices?.isRemote}static toString(){const e=this.getBrowserInfo();return`${e.name}/${e.version} ${e.engine} ${e.formFactor}`}modifyParserResult(t){switch(t.engine.name){case Pt:this.browserInfo.engine="Edge";break;case At:this.browserInfo.engine="Chromium";break;case Mt:t.browser.name?.includes("Safari")||(this.browserInfo.engine="Chromium");break;case Rt:this.browserInfo.engine="Firefox"}t.engine.name===At&&t.browser.name===Et&&(this.browserInfo.name="EdgeAnaheim"),t.engine.name===At&&t.os.name===St&&(this.browserInfo.version=t.engine.version||kt),t.browser.name!==Tt&&t.browser.name!==bt||(this.browserInfo.version=t.engine.version||kt,t.browser.name===bt&&(this.browserInfo.name="YandexBrowser")),(t.os.name===yt||t.browser.name?.includes(_t))&&(this.browserInfo.engine="Safari"),t.os.name!==Ct&&t.os.name!==yt||t.browser.name!==wt||(this.browserInfo.engine="Safari",this.browserInfo.name="AppleWebView"),t.os.name===yt&&(this.browserInfo.version=t.os.version||kt),t.browser.name===It&&(this.browserInfo.name="Safari"),t.ua.includes("maglev")&&(this.browserInfo.name="Maglev",this.browserInfo.version=t.engine.version||kt),e.isRemote()&&(this.browserInfo.engine="ChromiumAVD"),t.ua.includes("Cisco")&&(this.browserInfo.name="CiscoOS"),t.ua.includes("ZoomRoom")&&(this.browserInfo.name="ZoomRoom"),t.ua.includes("TeamsSamsungTVBrowser")&&(this.browserInfo.name="SamsungTV")}};function Nt(e){if("136"===function(){const e="os-sku",t=window.external;return t?.getHostEnvironmentValue?JSON.parse(t.getHostEnvironmentValue(e))[e]:"-1"}())return"Hololens";if(/hostAudio-Processing/i.test(e.ua))return"RoomAudioProcessing";const t=e.device.type;return"mobile"===t||"tablet"===t?"Mobile":void 0===e.browser.name?"Unknown":"Desktop"}var Lt={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},xt={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"]},Ft={src:[],css:[],styles:[],playerType:2,hydraPlayerWebSdkUrls:["https://res.cdn.office.net/s01-ml-player/4.24352.3/hydra_player_ums_bundle.js"]},Ut=class{constructor(e,t,i,n){this.configIds=i,this.logger=n,this.defaultSettings=(Ot.isEngine("Safari")?new Vt:new Bt).getSettings(),this.logger.info(`client settings: ${JSON.stringify(t)}`),this.defaultSettings.debug=t?.debug||!1,this.defaultSettings.playerType=t?.playerConfig?.playerType||this.defaultSettings.playerType,t?.playerConfig&&(0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration=t.playerConfig:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration=t.playerConfig:2===this.defaultSettings.playerType&&(this.defaultSettings.umsSettings.liveStreamPlayerConfiguration=t.playerConfig)),(0,ft.mergeWith)(this.defaultSettings,e,Ht),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}},Bt=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:Lt,sourceResetTimeoutInMs:1e3,streamingUrlSwitchMaxCount:2,resetStreamingUrlSwitchCount:!1,useBrowserWindowSizeForBitRate:!0,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,collectUserInitiatedSeekEventsTelemetry:!0,maxUserInitiatedSeekEventCount:100,noMediaTimeoutMs:-1},hlsSettings:{liveStreamPlayerConfiguration:xt,timeoutForSwitchingUrl:9e3,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,playlistInitialSequenceNumber:1,skipNonce:!1,maxStreamConnectionResultsLogCount:100,logHlsJsEvents:!1,logHlsJsEventsEveryMs:5e3,maxPlayerExperimentalEvents:100},umsSettings:{liveStreamPlayerConfiguration:Ft,timeoutForSwitchingUrl:9e3,maxStreamConnectionResultsLogCount:100,minTargetEdgeLatency:.2,latencyCompensationThreshold:.5,maxPlayerExperimentalEvents:100}}}getSettings(){return this.defaultSettings}},Vt=class extends Bt{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 Ht(e,t){if((0,ft.isArray)(e))return t.slice()}function $t(e){return!!e&&!!e.url&&!!e.decryptionToken}function jt(e,t,i){if(!e&&!i)throw new Error("Assert failed"+(void 0!==t?`: ${t}`:""))}var Gt=class{constructor(e,t,i){this.name=e,this.stopCrash=t,this.start(i)}complete(){jt(this.startTime,"not started",this.stopCrash),jt(void 0===this.duration,"already completed",this.stopCrash),this.duration=Date.now()-this.startTime}updateDetails(e,t){if(this.details&&"object"==typeof this.details)for(let i=0;i<e.length;i++)this.details[e[i]]=t[i]}fail(e){this.failReason=e,this.complete()}set detail(e){this.details=e}getTelemetryEvent(){jt(this.startTime,"not started",this.stopCrash);try{jt(void 0!==this.duration,"not completed",this.stopCrash)}catch(e){if("SetSource"!==this.name&&"Load"!==this.name)throw e}const e={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(e.failReason=this.failReason),this.details&&(e.details=this.details),e}start(e){jt(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),this.details=e}},qt=class{constructor(e,t,i){this.config=e,this.logger=t,this.playerDiagnosticsLog=i,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.userInitiatedSeekEvents=[],this.experimentalEvents=[],this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxUserInitiatedSeekEventCount=e.ampSettings?.maxUserInitiatedSeekEventCount||100,this.stopCrash=e.stopCrash||!1,this.config.debug&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}getPlayerDiagnosticSnapshot(){return this.currentPlayerDiagnosticSnapshot}registerStatsUpdated(e){this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((t=>{const i=t,n=this.playerDiagnosticsLog[t];if(Array.isArray(n)){n.push(e[i]);const t="memoryLog"===i&&n.length>this.maxPlayerMemoryTraceLogCount,r="memoryLog"!==i&&n.length>this.maxPlayerDiagnosticsCount;(t||r)&&n.splice(0,1)}else this.playerDiagnosticsLog[t]=e[i]}))}registerEventLoadAttempt(e,t){this.registerScenario(e,t)}registerEventLoadFailed(e,t){this.completeScenario(e,t)}registerEventLoadSucceeded(e,t){this.completeScenario(e,void 0,t)}registerPlayerLoadAttempt(){this.registerScenario("Load")}registerPlayerLoadSucceeded(e){this.completeScenario("Load",void 0,e)}registerPlayerLoadFailed(e){this.completeScenario("Load",e)}registerPlayerSetupAttempt(){this.registerScenario("Setup")}registerPlayerSetupSucceeded(){this.completeScenario("Setup")}registerPlayerSetupFailed(e){this.completeScenario("Setup",e)}registerStreamConnectionAttempt(e){this.registerScenario("StreamConnection")}registerStreamConnectionSucceeded(){this.completeScenario("StreamConnection")}registerStreamConnectionFailed(e){this.completeScenario("StreamConnection",e)}registerSetSourceAttempt(e,t){let i=e;t&&(i={src:e,reason:t}),this.registerScenario("SetSource",i)}registerSetSourceSucceeded(e){this.getScenario("SetSource").updateDetails(["src"],[e]),this.completeScenario("SetSource")}registerSetSourcedFailed(e,t){this.getScenario("SetSource").updateDetails(["src"],[t]),this.completeScenario("SetSource",e)}registerSdnPluginLoad(e,t,i){this.registerScenario("SdnPluginLoad",e);const n=t?void 0:i;this.completeScenario("SdnPluginLoad",n)}registerPlayerDestroyed(e){this.registerScenario("Destroyed",e),this.completeScenario("Destroyed")}registerPlaybackStateChanged(e,t){let i;"Ready"!==e||this.firstReadyStateTimestamp?"Playing"!==e||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),t&&"Buffering"===e&&(t?i=t.message:this.logger.debug(`Unexpected buffering payload: ${JSON.stringify(t)}`)),this.registerPlaybackEvent("StateChanged",e,i)}registerPlaybackError(e,t){this.registerPlaybackEvent("Error",{errorType:e,details:t})}registerDownloadBitratechanged(e){this.registerPlaybackEvent("BitrateChangedDownload",e)}registerStreamOptionsConfigured(e,t){this.registerPlaybackEvent("StreamOptionsConfigured",this.generateCleanedStreamOption(e),t)}registerPlaybackBitratechanged(e){this.registerPlaybackEvent("BitrateChangedPlayback",e)}registerPotentialMediaFreeze(e){this.registerPlaybackEvent("PotentialMediaFreeze",e)}registerCaptionToggle(e,t,i){const n={isEnabled:e,culture:t,playerTime:i};this.registerPlaybackEvent("CaptionsToggled",n)}registerFullScreenChange(e){this.registerPlaybackEvent("FullscreenChanged",e)}registerMute(e){this.registerPlaybackEvent("Mute",e)}registerVolumeChange(e){this.registerPlaybackEvent("Volume",e)}getExperimentalEvents(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}}getUserInitiatedSeekEvents(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents)}}getSnapshotReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;let n={};return this.currentPlayerDiagnosticSnapshot&&(n=this.filterAndPrepareTelemetry()),{isFullReport:!1,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2025.07.01.15",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...n}}getReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;return{callendReason:e.callendReason,isFullReport:!0,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2025.07.01.15",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...this.getPlayerDiagnosticLog()}}registerExperimentalEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.logTelemetryEvent(n)}registerUserInitiatedSeek(e){const t=(this.currentPlayerDiagnosticSnapshot?.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1)<e.newCurrentPlayPosition,i={...e,seekForward:t},n=this.createTelemetryEvent("UserInitiatedSeek",i);this.userInitiatedSeekEvents.push(n),this.userInitiatedSeekEvents.length>this.maxUserInitiatedSeekEventCount&&this.userInitiatedSeekEvents.splice(0,1)}createTelemetryEvent(e,t,i){const n={eventType:e,timestamp:Date.now(),currentPlayPosition:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1};return void 0!==t&&(n.payload=this.prepareForTelemetry(t)),n.message=i,n}registerPlaybackEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);"Error"===e&&"PlaybackRetried"!==t?.errorType&&(n.fatal=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)}getPlayerDiagnosticLog(){if(!this.currentPlayerDiagnosticSnapshot)return{};const e={...this.currentPlayerDiagnosticSnapshot,...this.playerDiagnosticsLog},t={};return Object.keys(e).forEach((i=>{t[`player_${i}`]=this.prepareForTelemetry(e[i])})),t}getCallSetupSucceeded(e){const t=e.find((e=>"Load"===e.name));return!!t&&!t.failReason}getCallDropped(e){return!!e.filter((e=>"Error"===e.eventType)).find((e=>e.fatal))}getInitializationReport(e,t){const i=e.find((e=>"Load"===e.name));return{init_timeLoadToStreamConnectionEstablished:(i&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-i.startTime:-1)||-1,init_timeLoadToReady:(i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(i&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)}}getPlaybackReport(e){const t=e.filter((e=>"StateChanged"===e.eventType)),i=t.find((e=>"Ready"===e.payload)),n=t.find((e=>"Play"===e.payload)),r=t.find((e=>"Start"===e.payload)),s=t.find((e=>"Playing"===e.payload)),a=i&&n?n.timestamp-i.timestamp:-1,o=n&&r?r.timestamp-n.timestamp:-1,l=r&&s?s.timestamp-r.timestamp:-1,c=t.filter((e=>"Seeked"===e.payload)),d=t.filter((e=>"Seeking"===e.payload)),u=t.filter((e=>"Paused"===e.payload)),h=t.filter((e=>"Resume"===e.payload)),g=t.filter((e=>"Buffering"===e.payload)),p=["BitrateChangedDownload","BitrateChangedPlayback","Error","Mute","StateChanged","Volume","StreamOptionsConfigured"],m=e.filter((e=>"Error"===e.eventType)),f=e.filter((e=>"Volume"===e.eventType||"Mute"===e.eventType)),v=e.filter((e=>"StreamOptionsConfigured"===e.eventType)),S=e.filter((e=>!p.includes(e.eventType)));return{playback_timeReadyToPlay:a,playback_timePlayToStart:o,playback_timeStartToPlaying:l,playback_bufferingEvents:this.prepareForTelemetry(g),playback_errorEvents:this.prepareForTelemetry(m),playback_pauseEvents:this.prepareForTelemetry(u),playback_resumeEvents:this.prepareForTelemetry(h),playback_otherEvents:this.prepareForTelemetry(S),playback_seekedEvents:this.prepareForTelemetry(c),playback_seekingEvents:this.prepareForTelemetry(d),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(f),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(v)}}generateCleanedStreamOption(e){return{...e,stream:{...e?.stream,decryptionToken:e?.stream?.decryptionToken?"valid":"empty",sdnContext:e?.stream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"},altStream:e?.altStream?{...e?.altStream,decryptionToken:e?.altStream?.decryptionToken?"valid":"empty",sdnContext:e?.altStream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"}:void 0}}getBitrateReport(e){const t=e.filter((e=>"BitrateChangedDownload"===e.eventType)),i=t.sort((e=>Number(e.payload))),n=t.length?{bitrate_downloadChanges:this.prepareForTelemetry(t),bitrate_downloadChangeCount:t.length||-1,bitrate_downloadMin:i[0].payload||-1,bitrate_downloadMax:i[i.length-1].payload||-1}:{},r=e.filter((e=>"BitrateChangedPlayback"===e.eventType)),s=r.sort((e=>Number(e.payload)));return{...n,...r.length?{bitrate_playbackChanges:this.prepareForTelemetry(r),bitrate_playbackChangeCount:r.length||-1,bitrate_playbackMin:s[0].payload||-1,bitrate_playbackMax:s[s.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 e="Unknown";if(window.navigator?.connection?.type){const t=window.navigator?.connection?.type;switch(t){case"cellular":e="WWAN";break;case"ethernet":e="Wired";break;case"wifi":e="Wireless";break;default:e="Unknown"}}this.clientNetworkType=e}return this.clientNetworkType}getSdnReport(e){const t=e.filter((e=>"SdnPluginLoad"===e.name)),i=t.length?t[t.length-1]:void 0;return{sdn_loaded:!(!i||void 0!==i.failReason),sdn_details:i&&i.details||"",sdn_error:i&&i.failReason||"",sdn_events:this.prepareForTelemetry(t)}}getSetSourceReport(e){const t=e.filter((e=>"SetSource"===e.name));return{set_source_events:this.prepareForTelemetry(t)}}registerScenario(e,t){const i=this.currentScenarioMap.get(e),n=new Gt(e,this.stopCrash,t);jt(!i,`previous scenario:${tt(i)} is not completed, new scenario:${tt(n)}`,this.stopCrash),this.currentScenarioMap.set(e,n),this.playerEvents.push(n)}getScenario(e){return this.currentScenarioMap.get(e)}completeScenario(e,t,i){const n=this.currentScenarioMap.get(e);jt(n,"no scenario to complete",this.stopCrash),t?n.fail(t):("StreamConnection"!==e||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),i&&(n.detail=i),n.complete()),this.currentScenarioMap.delete(e)}logTelemetryEvent(e){this.config.debug&&(this.logger.debug(`PlayerTelemetryEvent: ${JSON.stringify(e)}`),this.logger.debug(`PlayerDiagnosticData: ${JSON.stringify(this.currentPlayerDiagnosticSnapshot)}`))}filterAndPrepareTelemetry(){const e=new Set;e.add("serviceLatencyCdg"),e.add("endToEndLatencyCdg"),e.add("videoEdgeLatencyCdg");const t={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((i=>{e.has(i)||(t[`player_${i}`]=this.prepareForTelemetry(this.currentPlayerDiagnosticSnapshot[i]))})),t}prepareForTelemetry(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?e??-1:JSON.stringify(e)}},zt=Z;function Wt(e){return new Promise((t=>{t(e())}))}var Kt=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((e,t)=>{this.resolveInt=e,this.rejectInt=t}))}get resolve(){return e=>{this.isPendingInt=!1,this.resolveInt(e),this.clearTimeout()}}get reject(){return e=>{this.isPendingInt=!1,this.rejectInt(e),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(e,t=`deferred timed out after ${e}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(t)}),e))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function Jt(e,t=`deferred timed out after ${e}ms`){const i=new Kt;return i.setTimeout(e,t),i}function Yt(e){return new Promise((t=>setTimeout(t,e)))}var Qt=class{static build(e,t){return new Zt(e,t)}},Zt=class{constructor(e,t){this.ontimeout=e,this.name=t}start(e){if(void 0!==this.timeoutId)throw new Error(`Timer ${this.name} already started`);return this.timeoutId=window.setTimeout((()=>this.ontimeout()),e),this}stop(){if(void 0===this.timeoutId)throw new Error(`Timer ${this.name} is not defined`);clearTimeout(this.timeoutId),this.timeoutId=void 0}};function Xt(){const e=ai(),t=oi();let i;return(i||(i={})).CaptionFunctionalityNotSupported="CaptionFunctionalityNotSupported",class{constructor(e,t){this.container=e,this.eventsHandler=t,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(e,t,i){this.liveStreamOptions=e,this.playerId=i,t&&(this.configProvider=t,this.statsInterval=t.config.playerTelemetryTickMs||this.statsInterval,this.maxMemoryTraceLogCount=t.config.maxPlayerMemoryTraceLogCount||this.maxMemoryTraceLogCount)}getIceCandidates(){let e=[];try{const t=this.liveStreamOptions.stream.sdnContext||this.liveStreamOptions.altStream?.sdnContext||"",i=JSON.parse(t),n=JSON.parse(i.sdnConfig);if(!n.RTCIceCandidates)throw new Error("RTCIceCandidates not present in SDN Context");e=n.RTCIceCandidates}catch(e){this.log(`getIceCandidates failed: ${JSON.stringify(e.message)}`,"error")}return this.log(`getIceCandidates: ${JSON.stringify(e)}`,"debug"),e}loadPlayerScript(){let e=Promise.resolve("");const t=this.configProvider.playerConfig.nonce,i=this.configProvider.playerConfig.css;for(let n=0;n<i.length;n++)e=e.then((()=>this.retry((()=>this.loadCss(this.container.ownerDocument,i[n],t)))));return e=e.then((()=>this.loadAmpScript())),e}loadAmpScript(){this.log("loadPlayerScript started");let e=Promise.resolve("");const t=this.configProvider.playerConfig?.nonce,i=this.configProvider.playerConfig?.src||[],n=Math.max(2,this.configProvider.config.maxRetryCountForLoadingResources);if(0===i.length)return Promise.reject("AMP Player Src is empty");for(let r=0;r<i.length;++r)e=e.then((()=>this.loadScriptPromise(i,r,t,n)));return e}loadScriptPromise(e,t,i,n,r=""){return this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i} `.concat(r))).catch((s=>this.retry((()=>this.setScriptByBlob(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i}`.concat(` ${s} `,` ${r} `))).catch((a=>this.retry((()=>this.setScriptByInnerHtml(this.container.ownerDocument,e[t],i)),1).then((i=>`${e[t]}: ${i}`.concat(` ${s} `,`${a} `,` ${r} `))).catch((s=>{let o=r;return t<e.length&&(o=o.concat(`Failed to load script, nonce: ${i}, src: ${e[t]} index: ${t} `),o=o.concat(`${n} attempts LoadFailure `,`${n} attempts BlobFetchFailure: `,a,", 1 attempt InnerHtmlFailure: ",`${s} `)),Promise.reject(o)}))))))}retry(e,t=this.configProvider.config.maxRetryCountForLoadingResources,i=1,n=200){return e(t).then((e=>`${e}, succeeded on load number: ${i} `)).catch((r=>(this.log(`Error loading resource: ${r} -- ${t} retriesLeft`),0==--t?Promise.reject(`${r}`):new Promise((s=>setTimeout((()=>s(this.retry(e,t,i+1).then((e=>"string"==typeof e?`${e}, succeeded on load number: ${i}`:e)).catch((e=>Promise.reject(`${r}`.concat(", ",e)))))),n))))))}setScriptByLoad(e,t,i){const n=e.createElement("script"),r=this.getElementLoadPromise(n,t);return n.src=t,i&&(n.nonce=i),e.head.appendChild(n),r.then((()=>Promise.resolve("Success: setScriptByLoad")))}setScriptByBlob(e,t,i){return this.safeResponse(t).then((t=>t.blob().then((n=>{if(n){const t=URL.createObjectURL(n);return this.setScriptByLoad(e,t,i).then((()=>Promise.resolve("Success: setScriptByBlob")))}return Promise.reject(`${t.status}, blob is null`)}))))}setScriptByInnerHtml(e,t,i){return this.safeResponse(t).then((t=>t.text().then((n=>{if(n){const t=document.createElement("script");return t.innerHTML=n,i&&!this.configProvider.config.hlsSettings.skipNonce&&(t.nonce=i),e.head.appendChild(t),Promise.resolve("Success: setScriptByInnerHtml")}return Promise.reject(`status code:${t.status}, text is null`)}))))}safeResponse(e){return fetch(e).then((e=>e.ok?e:Promise.reject(`${e.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 i=this.getAmpOptions();if(this.playerInstance=this.contextWindow.amp(this.video.id,i),!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 ri(this.log.bind(this)),this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider,this.absoluteTimeOffsetEstimator),this.absoluteTimeOffsetEstimator.setEstimationResultCallback(this.onAbsoluteTimeOffsetEstimation.bind(this))):this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider);const n={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 t(this.playerInstance,this,n,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(e){if(this.diagnosticProvider.appendAbsoluteTimeOffsetEstimation(e),!e.isSuccess){const e=this.addEvent("CaptionFunctionalityNotSupported",{detail:{data:{fatal:!0,details:"absolute time offset estimation failed - captions will fail"}}});this.video.dispatchEvent(e)}}addEvent(e,t){let i={};return t?.detail&&(i={detail:t.detail}),new CustomEvent(e,i)}setSource(e){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 t={src:e.url,type:this.videoSourceType,protectionInfo:e.decryptionToken?[{type:"AES",authenticationToken:e.decryptionToken}]:null};this.configureSdnSource(t,e),this.diagnosticProvider.setValue("streamUrl",e.url),this.diagnosticProvider.setValue("streamId",this.getStreamIdFromStreamUrl(e.url)),this.diagnosticProvider.setValue("streamDeliveryPipeline",e.streamDeliveryPipeline||""),this.playerInstance.src([t],this.getTextTracks()),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.setManifestFileURL(e.url+"(format=m3u8-aapl-v4)"),this.log("setSource done")}getStreamIdFromStreamUrl(e){try{const t=new URL(e).pathname;if(t){const e=t.split("/");if(e?.length>1)return e[1]}return this.log(`unable to parse stream ID from stream URL: ${e}`,"warn"),""}catch{return this.log(`cannot parse stream ID from invalid stream URL: ${e}`,"warn"),""}}setPlayTime(e){e&&(this.log(`setPlayerTime: ${e}`),this.playerInstance.currentTime(e))}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(e){this.log(`showCaptions: ${e}`),this.captionsControl.showCaptions(e)}addCues(e){e=e.filter((e=>e.text&&0!==e.text.trim().length)),this.captionsControl.addCues(e)}clearCues(){this.captionsControl.clearCues()}captionsToggled(e,t,i){this.log(`captionsToggled: ${e} for culture ${t} at ${i}`),this.eventsHandler.message("captionsToggled").send(e,t,i)}createVideoElement(){this.log("createVideoElement started"),this.video=this.container.ownerDocument.createElement("video"),this.video.id="amp-player",this.video.setAttribute("playsinline","");const e=this.configProvider.playerConfig.lang;e&&(this.video.setAttribute("lang",e),this.log(`createVideoElement: language set to ${e}`));const t=this.configProvider.playerConfig.styles;for(let e=0;e<t.length;e++)this.video.classList.add(t[e]);this.container.appendChild(this.video),this.log("createVideoElement done")}getAmpOptions(){const e=[];this.configProvider.config.debug?e.push({target:"memory",maxMemoryTraceCount:this.maxMemoryTraceLogCount}):e.push({target:"console"});const t={TraceTargets:e,maxLogLevel:this.configProvider.config.debug?3:2},i={techOrder:["azureHtml5JS","html5"],nativeControlsForTouch:!1,autoplay:!0,preload:"auto",controls:!this.isControlsDisabled(),logo:{enabled:!1},height:"100%",width:"100%",traceConfig:t,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(i),i}isStreamValid(e){return e&&!!e.url&&!!e.decryptionToken}initializePluginOptions(e){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;const t=this.isStreamValid(this.liveStreamOptions.stream)?this.liveStreamOptions.stream:this.liveStreamOptions.altStream;this.log(`initializePluginOptions, receivedSDNContext: ${JSON.stringify(t?.sdnContext)}`,"info");try{const i=this.liveStreamOptions.correlationId||this.playerId;switch(this.liveStreamOptions.sdn.name){case"hive":if(e.plugins={hive:{debugLevel:this.configProvider.config.debug?"debug":"notice",telemetryId:i}},t&&t.sdnContext)try{const i=JSON.parse(t.sdnContext);if(i.sdnConfig){const t=JSON.parse(i.sdnConfig);t.candidateTopicName="RequestIceCandidates",delete t.RTCIceCandidates,Object.assign(e.plugins.hive,t)}}catch(e){this.log(`initializePluginOptions, failed to parse Hive sdnConfig Json from sdnContext Json, error: ${e}`,"warn")}break;case"kollective":if(t&&t.sdnContext){let n=null,r=null,s=null;try{n=this.parseJson(t.sdnContext,"kollective sdn context")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext Json, error: ${e}`,"error")}if(n){try{r=this.parseJson(n.playbackinfo,"kollective sdn playback info")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext playbackinfo Json, error: ${e}`,"error")}try{s=this.parseJson(n.sdnConfig,"kollective sdn config")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext sdnConfig Json, error: ${e}`,"error")}}e.plugins={kollectiveSDN:{playbackInfo:r,sdnConfig:s,reportSessionId:i}}}break;case"ramp":t&&t.sdnContext&&(e.plugins={RampMOPlugin:this.parseJson(t.sdnContext,"ramp sdn context")},this.configProvider.config.debug&&(e.plugins.RampMOPlugin.verbose=!0));break;case"peer5":t.sdnContext&&(e.plugins={peer5:this.parseJson(t.sdnContext,"peer5 sdn context")})}}catch(e){this.log(`initializePluginOptions failed, error: ${e.message}`,"error")}this.log(`initializePluginOptions, configured plugin options: ${JSON.stringify(e.plugins)}`,"info")}getTextTracks(){const e=[];if(this.isControlsDisabled())e.push({id:"amp-player_default",kind:"captions",label:"default-text-track",src:"",srclang:"en"});else if(this.liveStreamOptions.supportedSubtitleLanguages){const t=this.liveStreamOptions.supportedSubtitleLanguages;for(let i=0;i<t.length;i++)e.push({id:`amp-player_${t[i].culture}`,kind:this.configProvider.config.textTrackKind,label:t[i].name||t[i].culture,src:"",srclang:t[i].culture.substr(0,2)})}return e}configureSdnSource(e,t){if(this.sdnPluginLoaded&&this.liveStreamOptions.sdn){switch(this.liveStreamOptions.sdn.name){case"hive":if(!t.sdnContext){e.sdnList=[];break}try{const i=JSON.parse(t.sdnContext);i.playbackinfo&&(e.sdnList=[{sdnName:"hive",sdnUrl:i.playbackinfo}])}catch(i){e.sdnList=[{sdnName:"hive",sdnUrl:t.sdnContext}]}break;case"kollective":if(!t.sdnContext){e.sdnList=[];break}try{const i=this.parseJson(t.sdnContext,"kollective sdn list context"),n=this.parseJson(i.playbackinfo,"kollective sdn list playback info"),r=this.parseJson(i.sdnConfig,"kollective sdn list sdn config");e.sdnList=[{sdnName:"kollectiveSDN",playbackInfo:n,sdnConfig:r}]}catch(t){return e.sdnList=[],void this.log(`configureSdnSource failed, error: ${t}`,"error")}break;case"ramp":case"peer5":e.sdnList=[];break;default:return}this.log(`configureSdnSource, configured source context: ${JSON.stringify(e)}`,"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(i).forEach((e=>{this.registerVideoEvent(e,(t=>{this.handleUserExperienceErrorEvent(e,t.detail.data.details,t.detail.data.fatal)}))})),this.configProvider.config.ampSettings.collectUserInitiatedSeekEventsTelemetry&&(this.playerEvents.push("currentTimeChanging"),this.playerInstance.addEventListener("currentTimeChanging",((e,t)=>this.onAmpCurrentTimeChangingEvent(e,t))))}onAmpCurrentTimeChangingEvent(e,t){if("currentTimeChanging"!==e.type||!t.time)return;const i={newCurrentPlayPosition:t.time};this.eventsHandler.message("stateChanged").send("UserInitiatedSeek",i)}registerPlayerEvent(e,t){this.playerEvents.push(e),this.playerInstance.addEventListener(e,t)}registerVideoEvent(e,t){this.videoElementEvents.push({name:e,callback:t}),this.video.addEventListener(e,t)}removePlayerEventListeners(){this.playerEvents.forEach((e=>{this.playerInstance.removeEventListener(e)}))}removeVideoEventListeners(){this.videoElementEvents.forEach((e=>{this.video.removeEventListener(e.name,e.callback)}))}onAmpEvent(e){let t,i;switch(e){case this.contextWindow.amp.eventName.error:i=this.playerInstance.error(),t={currentTime:this.playerInstance.currentTime(),errorCode:i?i.code:0,message:i?i.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:t={isFullscreen:this.playerInstance.isFullscreen()};break;case this.contextWindow.amp.eventName.playbackbitratechanged:t={bitrate:this.playerInstance.currentPlaybackBitrate()};break;case this.contextWindow.amp.eventName.downloadbitratechanged:t={bitrate:this.playerInstance.currentDownloadBitrate()};break;case this.contextWindow.amp.eventName.seeked:t={captionsTimestamp:this.isControlsDisabled()?this.playerInstance.currentMediaTime():this.playerInstance.currentTime()};break;case this.contextWindow.amp.eventName.volumechange:t={value:this.playerInstance.volume()}}this.updatePlaybackDiagnostics(),this.updatePlayerState(e),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(e,t)}updatePlayerState(e){this.updatePlayingState(e),this.updateBufferingState(e),this.updateCurrentVideoTrackBitrate(e),e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error||this.handlePlaybackStopped()}handleUserExperienceErrorEvent(e,t,i){const n={currentTime:this.video?this.video.currentTime:0,message:t,type:e,errorCode:0,fatal:i};this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(this.contextWindow.amp.eventName.error,n)}updatePlayingState(e){this.isPlaying?e!==this.contextWindow.amp.eventName.pause&&e!==this.contextWindow.amp.eventName.seeking&&e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error&&e!==this.contextWindow.amp.eventName.waiting||(this.isPlaying=!1):e===this.contextWindow.amp.eventName.playing&&(this.isPlaying=!0)}updateBufferingState(e){this.isBuffering?(e===this.contextWindow.amp.eventName.pause&&"html5"===this.playerInstance.currentTechName()?.toLowerCase()||e===this.contextWindow.amp.eventName.seeking||e===this.contextWindow.amp.eventName.ended||e===this.contextWindow.amp.eventName.error||e===this.contextWindow.amp.eventName.playing)&&(this.isBuffering=!1):e===this.contextWindow.amp.eventName.waiting&&(this.isBuffering=!0)}updateCurrentVideoTrackBitrate(e){e===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 e=new Date;if(this.currentVideoPlaybackBitrate){const t=this.diagnosticProvider.getValue("videoTrackHistory"),i=this.diagnosticProvider.getValue("videoTrackTotalDurations");if(t.length>0&&this.currentVideoPlaybackBitrate===t[t.length-1].trackPlaybackBitrate){if(this.videoTrackHistoryUpdatedTimestamp){this.latestVideoTrackDuration+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,t[t.length-1].durationInSeconds=Number(this.latestVideoTrackDuration.toFixed(0));const n=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate)),r=i.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));n&&r&&(n.totalDurationInSeconds+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,r.totalDurationInSeconds=Number(n.totalDurationInSeconds.toFixed(0)))}}else{const n=this.playerInstance.videoBufferData();let r=null;n&&n.perceivedBandwidth&&(r=n.perceivedBandwidth),t.push({trackPlaybackBitrate:this.currentVideoPlaybackBitrate,trackSwitchTimestamp:e.getTime(),trackSwitchMeasuredBandwidth:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredBandwidth():null,trackSwitchMeasuredByteSize:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredVideoDownloadSize():null,trackSwitchPerceivedBandwidth:r,durationInSeconds:0}),this.latestVideoTrackDuration=0,t.length>this.configProvider.config.maxVideoTrackHistoryLogCount&&t.splice(0,1);const s=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));if(!s){const e={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0},t={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0};this.videoTrackTotalDurations.push(e),i.push(t)}}}this.videoTrackHistoryUpdatedTimestamp=e}updateTotalPlayingTimeStatistic(){const e=new Date;this.isPlaying&&this.totalPlayingTimeUpdatedTimestamp&&(this.totalPlayingTime+=e.getTime()-this.totalPlayingTimeUpdatedTimestamp.getTime()),this.totalPlayingTimeUpdatedTimestamp=e,this.diagnosticProvider.setValue("totalPlayingTimeInSeconds",Number((this.totalPlayingTime/1e3).toFixed(0)))}updateBufferingRateStatistic(){const e=new Date;this.isBuffering&&this.bufferingRateStatUpdatedTimestamp&&(this.totalBufferingTime+=e.getTime()-this.bufferingRateStatUpdatedTimestamp.getTime()),this.bufferingRateStatUpdatedTimestamp=e;const t=this.totalPlayingTime>0||this.totalBufferingTime>0?this.totalBufferingTime/(this.totalPlayingTime+this.totalBufferingTime):0;this.diagnosticProvider.setValue("bufferingRate",Number(t.toFixed(3)))}getPlayerDiagnostics(){const e=this.diagnosticProvider.getPlayerDiagnosticSnapshot();return e.statsInterval=this.statsInterval,this.configProvider.config.debug&&(e.memoryLog=this.playerInstance.getMemoryLog(!0)),e}log(e,t="info"){const i=`[AmpPlayer${1===this.configProvider.config.loadType?"IFrame":""}]: ${e}`;this.configProvider.config.debug&&console.log(i),this.eventsHandler.message("log").send(t,i)}getElementLoadPromise(e,t){return new Promise(((i,n)=>{e.onload=()=>{i("Element Load success")},e.onerror=()=>{n(`Failed to load script: ${t}`)}}))}loadCss(e,t,i){const n=e.createElement("link"),r=this.getElementLoadPromise(n,t);return n.href=t,n.rel="stylesheet",i&&(n.nonce=i),e.head.appendChild(n),r}parseJson(e,t){try{return JSON.parse(e)}catch(e){throw this.log(`Error parsing JSON for ${t}, error: ${JSON.stringify(e)}`),e}}}}function ei(){const e=Xt();return class{constructor(t,i){this.pipe=t,this.amp=new e(i,this)}processMessage(e){"Command"===e.msgType&&Promise.resolve().then((()=>this.amp[e.cmd].apply(this.amp,e.args))).then((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,result:JSON.stringify(t)})})).catch((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,error:t})}))}message(e){return{send:this.fromMessage(((...t)=>{this.sendMessageImpl(e,t)}))}}ampDisposed(){this.pipe.dispose(),this.pipe=null,this.amp=null}fromMessage(e){return e}sendMessageImpl(e,t){this.pipe.sendMsg({msgType:"PlayerNotification",name:e,args:t})}}}Xt();var ti=ei();function ii(){function e(e){let t="unknown";try{t="string"==typeof e?e:"toString"in e&&0!==e.toString().indexOf("[object")?e.toString():JSON.stringify(e)}catch(t){console.error("Failed to stringify error",e)}return t}return class{constructor(){this.processMsg=this.processMsg.bind(this),window.addEventListener("message",this.processMsg)}sendMsg(t){try{let i=t;(function(e){return"CommandResult"===e.msgType})(t)&&t.error instanceof Event&&(console.debug("Stringifying error Event before trying to postMessage:",t),i={msgType:t.msgType,cmd:t.cmd,error:`Event: ${e(t.error)}`}),this.postMessage(i)}catch(i){console.error("Unexpected exception caught from postMessage.\n","message:",t,"\n","exception:",i);const n={msgType:"PlayerNotification",name:"log",args:["error",`Unexpected error with postMessage: ${e(i)}`]};throw this.postMessage(n),i}}registerObserver(e){this.observer=e}dispose(){window.removeEventListener("message",this.processMsg),this.observer=null}processMsg(e){this.observer.processMessage(e.data)}postMessage(e){window.parent.postMessage(e,"*")}}}function ni(){const e=si();return class{constructor(t){this.playlistFileDownloadPromise=Promise.resolve(),this.playlistFileDownloadRetryWaitTime=250,this.playlistFileDownloadMaxRetryCount=20,this.playlistFileDownloadCancellationFlag=!1,this.logFn=(e,i)=>t(`[HlsAbsoluteTimeOffsetEstimator]: ${e}`,i),this.hlsFileParser=new e(t)}get absoluteTimeOffset(){return this.estimatedAbsoluteTimeOffset}setEstimationResultCallback(e){this.onAbsoluteTimeOffsetEstimation=e}restartStreamAbsoluteTimeOffsetRetrieval(){this.stopStreamAbsoluteTimeOffsetRetrieval().then((()=>this.startStreamAbsoluteTimeOffsetRetrieval()))}setManifestFileURL(e){this.cachedManifestUrl=e}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((e=>{this.logFn(`Failed to download playlist files to estimate absolute stream time offset: ${e.message}`,"error")}))}stopStreamAbsoluteTimeOffsetRetrieval(){return this.playlistFileDownloadCancellationFlag=!0,this.playlistFileDownloadPromise.then((()=>{this.playlistFileDownloadCancellationFlag=!1,this.currentManifestUrl=this.cachedManifestUrl,this.cachedManifestUrl=null}))}retryPlaylistFileDownload(e,t=0){let i=Promise.resolve();return i=e().then((()=>(this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!0,absoluteTimeOffsetEstimation:this.absoluteTimeOffset}),Promise.resolve()))).catch((i=>(t++,this.logFn(`Error loading playlist file: ${i} -- attempt ${t}`),this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!1,error:i.message}),t===this.playlistFileDownloadMaxRetryCount?Promise.reject(new Error(`${i} after ${t} attempts`)):this.playlistFileDownloadCancellationFlag?Promise.reject(new Error("cancelling playlist file download")):new Promise((i=>setTimeout((()=>i(this.retryPlaylistFileDownload(e,t))),this.playlistFileDownloadRetryWaitTime)))))),i}estimateStreamTimeFromPlaylist(e){return this.hlsFileParser.getStreamRenditionsUrlsFromManifest(e).then((t=>{if(0===t.audioRenditions.length&&0===t.videoRenditions.length)throw new Error(`Unable to retrieve renditions URLs from manifest: ${e}`);return Promise.all([t.videoRenditions.length>0?this.hlsFileParser.getTextFileContent(t.videoRenditions[0]):Promise.resolve(null),t.audioRenditions.length>0?this.hlsFileParser.getTextFileContent(t.audioRenditions[0]):Promise.resolve(null)])})).then((e=>{let t;for(let i=0;i<e.length;i++){const n=e[i];if(n){this.logFn("Using segment duration and sequence number to calculate absolute time offset","debug");const e=this.hlsFileParser.getHlsFieldByName("SequenceNumber",n);if(0==e.length)throw new Error("Unable to retrieve sequence number from playlist file");const i=this.hlsFileParser.getHlsFieldByName("SegmentDuration",n,10);if(0==i.length)throw new Error("Unable to retrieve segment durations from playlist file");const r=i.map(Number);r.sort(((e,t)=>e-t));const s=r[Math.floor(r.length/2)],a=Number(e[0])*Number(s);t=t?Math.max(t,a):a}}this.estimatedAbsoluteTimeOffset=t}))}}}var ri=ni();function si(){return class{constructor(e){this.fieldNameRegexMap={BaseUrl:/(.*)\/.*/,AudioManifestFile:/#EXT-X-MEDIA:TYPE=AUDIO.*URI=\"(.*)\"/,SequenceNumber:/#EXT-X-MEDIA-SEQUENCE:(\d+)/,SegmentDuration:/#EXTINF:(\d+(\.\d+)?)/},this.logFn=(t,i)=>e(`[HlsFileParser]: ${t}`,i)}getHlsFieldByName(e,t,i=1){const n=[];for(let r=1;r<=i;r++){const i=this.fieldNameRegexMap[e].exec(t);if(!(i&&i.length>0))break;n.push(i[1]),t=t.substring(i.index+i[0].length)}return n}getStreamRenditionsUrlsFromManifest(e){return e?this.getTextFileContent(e).then((t=>{const i={audioRenditions:[],videoRenditions:[]},n=t.split("\n"),r=this.getHlsFieldByName("BaseUrl",e);for(let e=0;e<n.length;e++)if(n[e].includes("#EXT-X-STREAM-INF")){const t=n[e+1];t.includes("http")?i.videoRenditions.push(t):r.length>0&&i.videoRenditions.push(`${r[0]}/${t}`)}else if(n[e].includes("EXT-X-MEDIA:TYPE")){const t=this.getHlsFieldByName("AudioManifestFile",n[e]);if(t.length>0){const e=t[0];e.includes("http")?i.audioRenditions.push(e):r.length>0&&i.audioRenditions.push(`${r[0]}/${e}`)}}return i})).catch((e=>(this.logFn(`Failed to extract stream renditions from manifest, error: ${e.message}`,"error"),{audioRenditions:[],videoRenditions:[]}))):(this.logFn("No manifest URL provided to parse"),Promise.resolve({audioRenditions:[],videoRenditions:[]}))}getTextFileContent(e){return fetch(e).then((t=>{if(!t.ok)throw new Error(`http-error ${t.status} when downloading: ${e}`);return t.text()})).catch((e=>(this.logFn(`Error downloading resource: ${e}`,"error"),Promise.reject(e))))}}}function ai(){return class{constructor(e,t,i,n,r){this.playerInstance=e,this.contextWindow=t,this.streamingStartedTimestamp=i,this.configProvider=n,this.absoluteTimeOffsetEstimator=r,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(e,t){this.currentDiagnosticSnapshot[e]=t}getValue(e){return this.currentDiagnosticSnapshot[e]}appendAbsoluteTimeOffsetEstimation(e){this.absoluteTimeOffsetEstimationResults.push(e),this.absoluteTimeOffsetEstimationResults.length>this.configProvider.config.ampSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount&&this.absoluteTimeOffsetEstimationResults.splice(0,1)}getPlayerDiagnosticSnapshot(){if(!this.playerInstance)return null;const e=window.screen,t=this.playerInstance.error(),i=e=>{const t=e.slice().sort();return t[Math.floor(t.length/2)]};this.currentDiagnosticSnapshot.errorCode=t&&t.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 n=this.getPlayerCachedLength(),r=this.getPlayerEdgeLatency();this.currentDiagnosticSnapshot.audioBufferLength=this.playerAudioBuffer?this.playerAudioBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.audioCachedLength=n,this.currentDiagnosticSnapshot.audioEdgeLatency=r,this.currentDiagnosticSnapshot.videoBufferLength=this.playerVideoBuffer?this.playerVideoBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.videoCachedLength=n,this.currentDiagnosticSnapshot.videoEdgeLatency=r,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=e?e.height:0,this.currentDiagnosticSnapshot.windowWidth=e?e.width:0,this.currentDiagnosticSnapshot.isFullscreen=this.playerInstance.isFullscreen(),this.currentDiagnosticSnapshot.avgAudioDownloadLatency=i(this.audioDownloadLatencies),this.currentDiagnosticSnapshot.avgVideoDownloadLatency=i(this.videoDownloadLatencies),this.currentDiagnosticSnapshot.avgAudioDownloadBytes=i(this.audioDownloadBytes),this.currentDiagnosticSnapshot.avgVideoDownloadBytes=i(this.videoDownloadBytes),this.currentDiagnosticSnapshot.maxVideoDownloadBytes=Math.max.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.minVideoDownloadBytes=Math.min.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.avgAudioDownloadBandwidth=i(this.audioDownloadBandwidths),this.currentDiagnosticSnapshot.avgVideoDownloadBandwidth=i(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 s=this.getDiagnosticWritableField();return Object.keys(s).forEach((e=>{this.currentDiagnosticSnapshot[e]=s[e]})),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 e="options_";return this.playerInstance[e]&&this.playerInstance[e].sdn&&this.playerInstance[e].sdn.name}getStreamType(e){let t="";return this.playerInstance&&(t=this.playerInstance.isLive()?"LIVE":"DVR"),""===t||"LIVE"===e&&t!==e?e||"":t}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 e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;return Number(e.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 e=this.playerAudioBuffer.downloadCompleted.mediaDownload.bitrate;e!==this.lastAudioDownloadBitrate&&(this.lastAudioDownloadBitrate=e)}addToList(e,t,i){e.push(t),e.length>i&&e.shift()}onVideoDownloadError(){this.videoDownloadFailureCount++,this.addDownloadFailureInfo(this.playerVideoBuffer.downloadFailed,this.videoDownloadFailures)}onAudioDownloadError(){this.audioDownloadFailureCount++,this.addDownloadFailureInfo(this.playerAudioBuffer.downloadFailed,this.audioDownloadFailures)}addDownloadFailureInfo(e,t){const i={bitrate:e.mediaDownload.bitrate,errorCode:e.code,mediaTime:e.mediaDownload.mediaTime,message:e.message,timestamp:Date.now()};this.addToList(t,i,this.downloadFailuresLimit)}getAudioStreamData(){const e=this.playerInstance.currentAudioStreamList();if(e)try{const t=e.streams[e.enabledIndices[0]];return{bitrate:t.bitrate,codec:t.codec,enabled:t.enabled,name:t.name,language:t.language}}catch(e){return}}getVideoStreamData(){const e=this.playerInstance.currentVideoStreamList();if(e)try{const t=e.streams[e.selectedIndex],i=this.playerInstance.currentPlaybackBitrate(),n=e=>({bitrate:e.bitrate,height:e.height,id:e.id,selectable:e.selectable,width:e.width}),r=t.tracks?t.tracks.map(n).find((e=>e.bitrate===i)):null;return{codec:t.codec,name:t.name,currentTrack:r}}catch(e){return}}getLivePosition(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t}getAverageDownloadBitrate(){if(this.streamingStartedTimestamp&&this.totalDownloadedBytes){const e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;if(e>0)return 8*this.totalDownloadedBytes/e}return 0}getRetryFrequency(){const e=this.currentDiagnosticSnapshot.retryCount;if(this.streamingStartedTimestamp&&e){const t=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/6e4;if(t>0)return e/t}return 0}getAverageMeasuredBandwidth(){if(0===this.videoDownloadBandwidths.length)return null;let e=0;for(let t=0;t<this.videoDownloadBandwidths.length;t++)e+=this.videoDownloadBandwidths[t];return e/this.videoDownloadBandwidths.length}getAverageMeasuredVideoDownloadSize(){if(0===this.videoDownloadBytes.length)return null;let e=0;for(let t=0;t<this.videoDownloadBytes.length;t++)e+=this.videoDownloadBytes[t];return e/this.videoDownloadBytes.length}getPlayerCachedLength(){const e=this.playerInstance.buffered();let t=0;for(let i=0;i<e.length;i++)t+=e.end(i)-e.start(i);return t}getPlayerEdgeLatency(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t-this.playerInstance.currentTime()}}}function oi(){return class{constructor(e,t,i,n){this.player=e,this.toggleListener=t,this.config=i,this.diagnosticProvider=n,this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.isHtml5Tech="html5"===this.player.currentTechName()?.toLowerCase()}dispose(){this.unsubscribeFromTrackEvents(),this.player=null,this.toggleListener=null}initialize(){const e=this.getPlayerTextTracksAsArray();if(!this.config.controlsEnabled&&e.length>0)e[0].mode="showing";else for(let t=0;t<e.length;t++)e[t].mode="disabled";this.subscribeOnTrackEvents()}addCues(e){const t=this.player.getCurrentTextTrack();if(!t)return;const i=this.getCurrentAbsoluteTime()||1,n=this.getCurrentTime(),r=this.config.controlsEnabled?i-n:Math.max(i-n,0),s=this.isHtml5Tech?window.VTTCue:window.vttjs&&window.vttjs.VTTCue||window.VTTCue;for(let i=0;i<e.length;i++){const{start:n,end:a,text:o}=e[i],l=2,c=new s(Number((n-r).toFixed(l)),Number((a-r).toFixed(l)),o);c.size=100,!this.containsCue(t,c)&&t.addCue(c)}}clearCues(){const e=this.player.getCurrentTextTrack();if(e)try{if(e.activeCues&&e.removeCue)for(;e.activeCues.length>0;)e.removeCue(e.activeCues[0]);const t="setCues_";if(e.cues[t]){e.cues_&&(e.cues_.length=0),e.cues[t]([]);const i=Object.getOwnPropertyNames(e.cues);for(let t=0;t<i.length;t++)"length"!==i[t]&&"length_"!==i[t]&&"cues_"!==i[t]&&delete e.cues[i[t]]}}catch(e){this.config.logFn(`[clearCues]: ${e}`,"warn")}}showCaptions(e){this.config.logFn(`[CaptionsControl]: showCaptions(${e})`),e?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 e=this.player.textTracks(),t="addEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}unsubscribeFromTrackEvents(){const e=this.player.textTracks(),t="removeEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}onTextTrackChanged(){const e=this.player.getCurrentTextTrack();if(!e||!this.currentTextTrack||this.currentTextTrack.label!==e.label||this.currentTextTrack.mode!==e.mode){if(e||this.currentTextTrack){const t=!!e&&"showing"===e.mode,i=this.getCulture(e||this.currentTextTrack),n=this.getCurrentTime();this.toggleListener.captionsToggled(t,i,n),this.config.logFn(`[CaptionsControl]: track changed: culture '${i}', timestamp '${n}'`)}this.currentTextTrack=e}}onAddTrack(e){const t=e?.track;"captions"===t?.kind&&!t.label&&!t.id&&(this.player?.textTracks_?.removeTrack_(t),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(e){if(!e)return"";if(e.id){const t=e.id.split("_")[1];if(t)return t}return""}getPlayerTextTracksAsArray(){const e=this.player.textTracks();return e&&e.tracks_||[]}containsCue(e,t){return Array.from(e?.cues||[]).some((e=>this.areCueEquals(e,t)))}areCueEquals(e,t){function i(e){return{start:e.start?e.start:e.startTime,end:e.end?e.end:e.endTime,text:e.text}}const n=i(e),r=i(t);return n.start===r.start&&n.end===r.end&&n.text===r.text}}}function li(){const e=ii(),t=ei(),i=new e,n=new t(i,document.body);i.registerObserver(n)}function ci(){let e=`(${li.toString()})();`;return e+=Xt.toString()+";",e+=ii.toString()+";",e+=ei.toString()+";",e+=oi.toString()+";",e+=ai.toString()+";",e+=ni.toString()+";",e+=si.toString()+";",e+="//# sourceURL=TsCallingAmpPlayer.js",e}var di=class{sendMsg(e){this.peer.onMsg(e)}registerObserver(e){this.observer=e}onMsg(e){this.observer&&this.observer.processMessage(e)}connect(e){this.peer=e}dispose(){this.peer=null,this.observer=null}},ui=class{constructor(e){this.container=e}get contextWindow(){return this.container.ownerDocument.defaultView}sendMsg(e){this.iframe?.contentWindow?.postMessage(e,"*")}registerObserver(e){this.observer=e}dispose(){this.contextWindow&&this.contextWindow.removeEventListener("message",this.processMsg),this.iframe&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe),this.iframe=null}initializeAmpIframe(e){const t=this.initializeIframe();return this.setAmpIframeContent(e),this.finalizeIframe(t)}initializeIframe(){const e=new Kt;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=()=>{e.resolve()},this.iframe.onerror=()=>{e.reject("iframe load failed")},e}finalizeIframe(e){return this.container.appendChild(this.iframe),this.processMsg=this.processMsg.bind(this),this.contextWindow.addEventListener("message",this.processMsg),e.promise}processMsg(e){"null"===e.origin&&e.source===this.iframe.contentWindow&&this.observer&&("RequestIceCandidates"===e.data?this.observer.processMessage({msgType:"Command",cmd:"getIceCandidates",args:[]}):this.observer.processMessage(e.data))}setAmpIframeContent(e){const t=ci(),i=`\n <html class style='height: 100%; width: 100%; overflow: hidden'>\n <head></head>\n <body class style='height: 100%; width: 100%; margin: 0px'>\n ${e?`<script nonce='${e}'> ${t}<\/script>`:`<script> ${t}<\/script>`}\n </body>\n </html>\n `;this.iframe.srcdoc=i}},hi=class extends gt{constructor(e){super(e),this.logger=e,this.resultsMap=new Map,this.on("log",((e,t)=>{this.logger[e](t)}))}async initialize(e,t,i,n){const r={config:i.config,playerConfig:i.playerConfig},s=i.playerConfig?.nonce||"";this.pipe=await async function(e,t,i){if(0===t){const t=new di,i=new di;return t.connect(i),i.connect(t),i.registerObserver(new ti(i,e)),t}if(1===t){const t=new ui(e);return await t.initializeAmpIframe(i),t}throw new Error(`Unsupported communication type ${t}`)}(e,i.config.loadType,s),this.pipe.registerObserver(this),await this.message("configure").send(t,r,n)}message(e){return{send:this.fromMessage(((...t)=>this.sendMessageImpl(e,...t)))}}dispose(){super.dispose(),this.pipe.sendMsg(this.buildMsg("dispose")),this.pipe.dispose()}processMessage(e){let t;switch(e.msgType){case"CommandResult":t=this.getDeferred(e.cmd.toString()),t&&(e.error?(t.reject(e.error),this.logger.warn(`remote command failed: ${String(e.cmd)}, ${e.error}`)):e.result?t.resolve(e.result):t.resolve(),this.processCommandResult(e),this.resultsMap.delete(e.cmd.toString()));break;case"PlayerNotification":{const t=this.event(e.name);t.raise.apply(t,e.args);break}case"Command":this.processCommand(e).catch((t=>this.logger.warn(`error while processing command: ${JSON.stringify(e)}: ${t}`)));break;default:this.logger.warn(`unexpected message received: ${JSON.stringify(e)}`)}}async processCommand(e){"getIceCandidates"===e.cmd.toString()?await this.message("getIceCandidates").send():this.logger.warn(`unsupported command received: ${JSON.stringify(e)}`)}processCommandResult(e){"getIceCandidates"===e.cmd.toString()?this.pipe.sendMsg({topic:"RequestIceCandidates",candidates:e.result}):this.logger.debug(`ignoring command result for: ${JSON.stringify(e)}`)}fromMessage(e){return e}sendMessageImpl(e,...t){return this.pipe.sendMsg(this.buildMsg(e,t)),this.waitForCompletion(e.toString())}buildMsg(e,t){return{msgType:"Command",cmd:e,args:t}}getDeferred(e){return this.resultsMap.get(e)}waitForCompletion(e){const t=this.getDeferred(e);t&&t.reject(new Error(`function ${e} is invoked again, before previous call is completed`));const i=new Kt;return this.resultsMap.set(e,i),i.promise}},gi=class extends gt{constructor(e,t){super(),this.player=e,this.logger=t,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(e){this.player.seek(e)}seekToLiveEdge(){this.player.seekToLiveEdge()}play(){this.player.play()}pause(){this.player.pause()}setVolume(e){this.player.setVolume(e)}selectVideoTrack(e){this.player.selectVideoTrack(e)}dispose(){this.stopPlayer(),super.dispose()}captions(){return this.player.getCaptionsControl()}getStats(){throw new Error("Method not implemented.")}setScalingMode(e,t){throw new Error("Method not implemented.")}captureFrame(e,t){throw new Error("Method not implemented.")}stopPlayer(){const e=this.player;this.player=null,e&&(this.logger.info("stopPlayer"),this.unsubscribeFromPlayerEvents(),e.stop())}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("fullscreenToggled",(e=>this.onFullScreenToggled(e)))),this.playerSubs.push(this.player.on("captionsToggled",((e,t,i)=>this.onCaptionsToggled(e,t,i)))),this.playerSubs.push(this.player.on("playbackTimeUpdated",(e=>this.onPlaybackTimeUpdated(e)))),this.playerSubs.push(this.player.on("videoTracksChanged",(e=>this.onVideoTracksChanged(e))))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onFullScreenToggled(e){this.event("fullScreenToggled").raise(e)}onCaptionsToggled(e,t,i){this.logger.info(`Turned captions ${e?"ON":"OFF"} for culture [${t}] at player time [${i}]`),this.event("captionsToggled").raise(e,t,i)}onPlaybackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}onVideoTracksChanged(e){this.event("videoTracksUpdated").raise(e)}},pi=class{constructor(e,t){this.player=e,this.availableCultures=t,this.selectedCulture="",this.disposable=this.player.on("captionsToggled",((e,t,i)=>{this.selectedCulture=e?t:""}))}async addCues(e){await this.player.message("addCues").send(e)}async clearCues(){await this.player.message("clearCues").send()}async showCaptions(e){await this.player.message("showCaptions").send(e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.disposable.dispose(),this.player=null}};function mi(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function fi(e){return new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)&&36===e.length}var vi=[2097152,2097552,2097556,2097557,2097564,2097652,2097654,2097655,2097656,2097752,3145728,4194305,4194306,4194307,4194308,4194309,5242880,5242881,5242882,5242884,5242885,5242886],Si=2097753,yi=class extends gt{constructor(e,t,i){super(),this.logger=e,this.liveStreamStatistic=t,this.configProvider=i,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=mi(),this.logger.info(`AmpLiveStreamPlayer created: ID: ${this.id}`)}get playerId(){return this.id}async configure(e){if(!$t(e.stream)&&!$t(e.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=e;const t=$t(e.stream)?e.stream:e.altStream;if(this.playerInstance&&!this.isPlaybackUnsupported){try{await this.playerInstance.message("configure").send(e)}catch(e){const t=tt(e);this.logger.error(`configure failed: ${t}`)}await this.handleStreamInfoUpdate(t)}else this.selectedStreamDetails=t}async loadPlayer(e){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||!$t(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 hi(this.logger.createChild("AmpPlayerWrapper")),this.playerInstance.on("stateChanged",((e,t)=>this.ampStateChanged(e,t))),this.playerInstance.on("captionsToggled",((e,t,i)=>this.captionsToggled(e,t,i))),this.playerInstance.on("statsUpdated",(e=>this.liveStreamStatistic.registerStatsUpdated(e)));const t=this.configProvider.config.ampSettings.noMediaTimeoutMs;let i;-1!==t&&-1===this.noMediaTimeoutId&&(this.noMediaTimeoutId=self.setTimeout((()=>this.callDropDueToMediaTimeout()),t)),await this.playerInstance.initialize(e,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{i=await this.srcLoadPromise}catch(e){const t=tt(e);return this.logger.error(`playerLoadFailed: player scripts load failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("LoadScript",`Load Script failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`script load failed: ${i}`),this.srcLoadPromise=null,{setupSucceeded:!1,playerSetupError:{errorType:"PlayerScriptLoadFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("LoadScript"),await this.tryLoadSdnPlugin(),this.liveStreamStatistic.registerEventLoadAttempt("CreateAmp");try{await this.playerInstance.message("createAmp").send()}catch(e){const t=tt(e);return this.logger.error(`playerLoadFailed: createAmp failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("CreateAmp",`createAmp failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`create amp failed ${t}, script load: ${i}`),{setupSucceeded:!1,playerSetupError:{errorType:"PlayerInitializationFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("CreateAmp");try{return await this.setPlayerSource(this.selectedStreamDetails),this.loadSucceeded=!0,this.logger.info(`loadPlayer succeeded: ${this.loadSucceeded}`),this.liveStreamStatistic.registerPlayerLoadSucceeded(i),this.playerState="Initialized",{setupSucceeded:this.loadSucceeded}}catch(e){const t=tt(e);return this.loadSucceeded=!1,this.logger.error(`loadPlayer succeeded: ${this.loadSucceeded}: setSource failed: ${t}`),this.liveStreamStatistic.registerPlayerLoadFailed(`setPlayerSource failed; script load: ${i}`),{setupSucceeded:this.loadSucceeded,playerSetupError:{errorType:"SetSourceFailed",errorMessage:t}}}}getRenderer(){return!this.renderer&&this.playerInstance&&(this.renderer=new gi(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}seek(e){throw new Error(`Method not implemented - cannot perform video seek operation with args: [timestamp: ${e}]`)}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(e){throw new Error(`Method not implemented - cannot set video volume with args: [volume: ${e}]`)}selectVideoTrack(e){throw new Error(`Method not implemented - cannot select video track with args: [track: ${e}]`)}stop(){this.destroy("PlayerStopped")}getPlaybackState(){return this.playerState}getCaptionsTimestamp(){return this.captionsTimestamp}getCaptionsControl(){if(!this.captionsControl&&this.playerInstance){const e=this.liveStreamOptions.supportedSubtitleLanguages?this.liveStreamOptions.supportedSubtitleLanguages.map((e=>e.culture)):[];this.captionsControl=new pi(this.playerInstance,e)}return this.captionsControl}getStreamSize(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e?{width:e.mediaWidth,height:e.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.height>0}ampStateChanged(e,t){switch(e){case"error":return this.handlePlaybackError(t);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(t);case"loadedmetadata":return this.onMetadataLoaded();case"waiting":return this.onWaiting();case"playbackbitratechanged":return this.onPlaybackBitrateChanged(t);case"downloadbitratechanged":return this.onDownloadBitrateChanged(t);case"fullscreenchange":return this.onFullscreenChange(t);case"potentialMediaFreeze":return this.onPotentialMediaFreeze();case"mute":return this.onMute();case"unmute":return this.onUnmute();case"volumechange":return this.onVolumeChange(t);case"loadstart":return this.onLoadStart();case"loadeddata":return this.onLoadedData();case"UserInitiatedSeek":return this.onUserInitiatedSeek(t);default:this.logger.warn(`Unknown amp event ${e}`)}}onUserInitiatedSeek(e){this.liveStreamStatistic.registerUserInitiatedSeek(e)}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i),this.liveStreamStatistic.registerCaptionToggle(e,t,i)}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 e;this.liveStreamStatistic.registerEventLoadAttempt("SdnPluginLoad");try{this.sdnPluginLoadPromise=this.playerInstance.message("tryLoadSdnPlugin").send(),await this.sdnPluginLoadPromise,this.liveStreamStatistic.registerEventLoadSucceeded("SdnPluginLoad",this.liveStreamOptions.sdn.name)}catch(t){e=tt(t),this.sdnPluginLoadPromise=void 0,this.logger.error(`loadSdnPlugin failed: ${e}`),this.liveStreamStatistic.registerEventLoadFailed("SdnPluginLoad",e),this.event("sdnPluginLoadFailed").raise(e)}}raiseSdnPluginSkippedEvent(e){this.logger.warn(`skipping SDN plugin load: ${e}`),this.event("sdnPluginLoadSkipped").raise(e)}async setPlayerSource(e){if(!e)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: [${e.url}]`),this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;try{this.logger.info("setPlayerSource: src changed"),this.selectedStreamDetails=e,this.liveStreamStatistic.registerSetSourceAttempt(e.url),await this.playerInstance.message("setSource").send(e),this.liveStreamStatistic.registerSetSourceSucceeded()}catch(e){const t=tt(e);throw this.logger.error(`setPlayerSource: failed with error [${t}]`),this.liveStreamStatistic.registerSetSourcedFailed(t),e}}async handleStreamInfoUpdate(e){this.loadSucceeded&&e.url!==this.selectedStreamDetails.url?await this.setPlayerSource(e):this.loadSucceeded&&this.playerInstance&&this.getCurrentTime()>0&&this.setPlaybackState("Start")}async switchStreamingUrl(e,t){if(this.streamingUrlSwitchCount>=this.configProvider.config.ampSettings.streamingUrlSwitchMaxCount||!(0,zt.includes)(this.configProvider.config.ampSettings.errorCodesEligibleForStreamingUrlSwitch,e)&&!t)return!1;const i=this.selectedStreamDetails.url===this.liveStreamOptions.stream?.url,n=i?this.liveStreamOptions.altStream:this.liveStreamOptions.stream;return $t(n)?(this.isSwitchStreamingUrlOngoing=!0,this.streamingUrlSwitchCount++,this.setPlayerSource(n).then((()=>!0)).catch((()=>!1))):(this.logger.error(`Stream to switch (${i?"alternative":"primary"}) is not valid`),!1)}destroy(e){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(e),this.playerInstance.dispose(),this.playerInstance=null,this.setPlaybackState("Destroyed"))}getCurrentTime(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e&&e.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(e){this.captionsTimestamp=e.captionsTimestamp,this.setPlaybackState("Seeked")}onMetadataLoaded(){this.setPlaybackState("LoadedMetadata")}onWaiting(){this.setPlaybackState("Buffering")}onLoadedData(){this.setPlaybackState("LoadedData")}onLoadStart(){this.setPlaybackState("LoadStart")}setPlaybackState(e){this.playerState=e,this.logger.debug(`playback state changed: ${e}`),this.liveStreamStatistic.registerPlaybackStateChanged(e),this.event("playbackStateChanged").raise()}onPlaybackBitrateChanged(e){this.liveStreamStatistic.registerPlaybackBitratechanged(e.bitrate)}onDownloadBitrateChanged(e){this.liveStreamStatistic.registerDownloadBitratechanged(e.bitrate)}onFullscreenChange(e){this.logger.debug(`fullscreenchange, isFullscreen=${e.isFullscreen}`),this.event("fullscreenToggled").raise(e.isFullscreen),this.liveStreamStatistic.registerFullScreenChange(e.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(e){this.liveStreamStatistic.registerVolumeChange(e.value)}stringifyPlayerError(e){return JSON.stringify(e,(function(e,t){return"errorCode"===e?t.toString(16):t}))}async handlePlaybackError(e){const t=4194307;this.playerState="Error",this.lastPlaybackError=e;const i=this.stringifyPlayerError(e);if(this.logger.info(`Playback error ${i}`),!e.errorCode&&null==e.fatal)return void this.logger.error("onError: error details are not available");if((e.errorCode&t)===t)return this.isPlaybackUnsupported=!0,this.raisePlaybackError("UnsupportedPlatform",i),void this.destroy("PlaybackError");this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;const n=e.errorCode,r=268435455&n;this.logger.error(`onError: errorCode: 0x${n.toString(16)}, errorCodeExcludingTech: 0x${r.toString(16)}, message: ${e.message}`),this.retryCount<this.configProvider.config.maxRetryCount&&(!1===e.fatal||-1!==(0,zt.indexOf)(vi,r))?setTimeout((async()=>{this.logger.info(`Retry loading stream because of error code: 0x${n.toString(16)}`),this.retryCount++,this.raisePlaybackError("PlaybackRetried",i),this.setPlayerSource(this.selectedStreamDetails)}),this.configProvider.config.ampSettings.sourceResetTimeoutInMs):await this.switchStreamingUrl(r,e.fatal)?this.configProvider.config.ampSettings.resetStreamingUrlSwitchCount&&(this.streamingUrlSwitchCount=0):(r===Si||e.message?.includes(Si.toString(16))?this.raisePlaybackError("NetworkError",i):this.raisePlaybackError("PlaybackError",i),this.destroy("PlaybackError"))}raisePlaybackError(e,t){this.liveStreamStatistic.registerPlaybackError(e,t),this.event("playbackError").raise(e,t)}callDropDueToMediaTimeout(){const e={currentTime:-1,errorCode:0,message:JSON.stringify({state:this.playerState,error:this.stringifyPlayerError(this.lastPlaybackError)}),fatal:!0},t=this.stringifyPlayerError(e);this.raisePlaybackError("MediaTimeout",t),this.destroy("MediaTimeout")}},Ci=p(q()),Ti=class extends gt{constructor(e,t,i){super(),this.logger=e,this.telemetryLogger=i,this.playerLoaded=!1,this.playbackState="Destroyed",this.playerSubs=[],this.isFinalTelemetrySent=!1,this.captionsTimestamp=0,this.configProvider=t;const n=this.createHydraPlayerSettings();this.eventHandler=this.createEventHandler(),this.addPlayerEventSubscribers(),this.hydraPlayer=new Ci.HydraPlayer(n,this.eventHandler)}async configure(e){if(this.streamOptions=e,this.threadId=e.threadId,this.playerLoaded){const e=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}}async loadPlayer(e){if(!await this.hydraPlayer.setup(e))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const e=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}else this.logger.warn("No stream options configured before Hydra player loaded");const t=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return t.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(t)}convertStreamDeliveryPipeline(e){switch(e){case"AMS":return Ci.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return Ci.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return Ci.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${e} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(e){switch(e){case"TLE":return Ci.HydraStreamingEventType.TLE;case"Overflow":return Ci.HydraStreamingEventType.Overflow;case"TownHall_Basic":return Ci.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return Ci.HydraStreamingEventType.TownHallPremium;case"TownHall":return Ci.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${e} to HydraStreamingEventType`)}}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(e=>{this.onPlaybackStateChanged(e)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(e=>{this.onPlaybackSeeked(e)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("playbackTimeUpdated",(e=>{this.onPlaybackTimeUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("videoTracksUpdated",(e=>{this.onVideoTracksUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(e=>{this.onStatsUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("log",((e,t)=>{this.onLog(e,t)}))),this.playerSubs.push(this.eventHandler.on("capabilitiesUpdated",(e=>{this.onCapabilitiesUpdated(e)})))}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}startTelemetryGathering(){let e,t;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?(e=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs):(e=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs),e&&(this.diagSub=window.setInterval((async()=>{this.sendSnapshotTelemetry()}),t))}getHydraPlayerSetupResult(e){return{setupSucceeded:e.setupSucceeded,playerSetupError:e.playerSetupError?{errorType:this.convertHydraPlayerSetupError(e.playerSetupError.errorType),errorMessage:e.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(e){switch(e){case Ci.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case Ci.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case Ci.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case Ci.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new gi(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(e){this.playerStats=e}getStats(){return this.playerStats}onLog(e,t){this.logger[e](t)}onPlaybackStateChanged(e){try{this.playbackState=this.convertHydraPlaybackState(e),this.event("playbackStateChanged").raise()}catch(e){this.logger.warn(`Not handling playback state changed event: ${tt(e)}`)}}convertHydraPlaybackState(e){switch(e){case Ci.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case Ci.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case Ci.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case Ci.HydraPlayerPlaybackState.Start:return"Start";case Ci.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case Ci.HydraPlayerPlaybackState.Play:return"Play";case Ci.HydraPlayerPlaybackState.Playing:return"Playing";case Ci.HydraPlayerPlaybackState.Pause:return"Paused";case Ci.HydraPlayerPlaybackState.Waiting:return"Buffering";case Ci.HydraPlayerPlaybackState.Seeking:return"Seeking";case Ci.HydraPlayerPlaybackState.Seeked:return"Seeked";case Ci.HydraPlayerPlaybackState.Ended:return"Ended";case Ci.HydraPlayerPlaybackState.Error:return"Error";case Ci.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case Ci.HydraPlayerPlaybackState.Initialized:return"Initialized";case Ci.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${e} to PlaybackState`)}}onPlaybackError(e,t){try{const i=this.convertHydraPlaybackErrorType(e);this.event("playbackError").raise(i,t)}catch(e){this.logger.warn(`Not handling playback error event: ${tt(e)}`)}}convertHydraPlaybackErrorType(e){switch(e){case Ci.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case Ci.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case Ci.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case Ci.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case Ci.HydraPlayerPlaybackErrorType.MediaTimeout:return"MediaTimeout";case Ci.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${e} to PlaybackErrorType`)}}seek(e){this.hydraPlayer.callPlayerApi("seekHydraPlayer",e)}seekToLiveEdge(){this.hydraPlayer.callPlayerApi("seekHydraPlayerToLiveEdge")}play(){this.hydraPlayer.callPlayerApi("playHydraPlayer")}pause(){this.hydraPlayer.callPlayerApi("pauseHydraPlayer")}setVolume(e){this.hydraPlayer.callPlayerApi("setHydraPlayerVolume",e)}selectVideoTrack(e){this.hydraPlayer.callPlayerApi("selectHydraPlayerVideoTrack",e)}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.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(e){if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const t={...this.getTelemetryReport(),isFinal:e,threadId:this.threadId,tsCallingVersion:"2025.07.01.15",correlationId:this.streamOptions.correlationId};this.logger.debug("generated live stream report: ",t),this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}else this.logger.info("telemetry not sent")}sendSnapshotTelemetry(){if(this.telemetryLogger){const e={...this.getSnapshotTelemetryReport(),isFinal:!1,threadId:this.threadId,tsCallingVersion:"2025.07.01.15",correlationId:this.streamOptions.correlationId};this.logger.debug("sending snapshot telemetry: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set")}clearPlayerEventSubscribers(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackSeeked(e){this.captionsTimestamp=e}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}onVideoTracksUpdated(e){this.event("videoTracksChanged").raise(e)}onCapabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},Ei=class extends gt{constructor(){super()}playbackStateChanged(e){this.event("playbackStateChanged").raise(e)}playbackSeeked(e){this.event("playbackSeeked").raise(e)}log(e,t){this.event("log").raise(e,t)}playbackError(e,t){this.event("playbackError").raise(e,t)}urlSwitched(e){this.event("urlSwitched").raise(e)}sdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}sdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}statsUpdated(e){this.event("statsUpdated").raise(e)}playbackStarted(){this.event("playbackStarted").raise()}playbackTimeUpdated(e){this.event("playbackTimeUpdated").raise(e)}videoTracksUpdated(e){this.event("videoTracksUpdated").raise(e)}capabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},bi=p(q());function _i(e){if(e.playbackCoordinates)return e.playbackCoordinates;if(!e.url&&!e.hlsUrls)return[];const t=[];return(e.hlsUrls?e.hlsUrls:[e.url]).forEach((i=>{t.push({url:i,sdnContext:e.sdnContext})})),t}function Ii(e){return e.url?[{url:e.url,sdnContext:e.sdnContext}]:[]}var wi=["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"],Ai=class extends Ti{createEventHandler(){return new Ri}createHydraPlayerSettings(){return{playerType:bi.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??wi,disableSandbox:this.configProvider.config.hlsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??""}}createHydraStreamOptions(){let e=bi.HydraStreamingEventType.TLE;e=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?bi.HydraStreamingEventType.Overflow:bi.HydraStreamingEventType.TLE;const t={stream:{playbackCoordinates:_i(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:_i(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:e,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&&(t.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(t.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(t.meetingMetadata=this.streamOptions.meetingMetadata),t}onCaptionsToggled(e,t,i){this.captionsControl&&this.captionsControl.toggleCaptions(e,t),this.event("captionsToggled").raise(e,t,i)}getCaptionsControl(){if(!this.captionsControl&&this.hydraPlayer){const e=this.streamOptions?.supportedSubtitleLanguages?this.streamOptions.supportedSubtitleLanguages.map((e=>e.culture)):["en","es"];this.captionsControl=new Pi(this.hydraPlayer,e)}return this.captionsControl}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("captionsToggled",((e,t,i)=>{this.onCaptionsToggled(e,t,i)})))}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Pi=class{constructor(e,t){this.hydraPlayer=e,this.availableCultures=t,this.selectedCulture=""}async addCues(e){const t=this.convertCues(e);await this.hydraPlayer.callPlayerApi("addHydraPlayerCues",t)}convertCues(e){const t=[];return e.forEach((e=>{t.push({start:e.start,end:e.end,text:e.text})})),t}async clearCues(){await this.hydraPlayer.callPlayerApi("clearHydraPlayerCues")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.hydraPlayer=null}toggleCaptions(e,t){this.selectedCulture=e?t:""}},Ri=class extends Ei{constructor(){super()}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i)}},Mi=p(q()),Di=class extends Ti{get tracks(){return this.trackInfo}createEventHandler(){return new Oi}createHydraPlayerSettings(){return{playerType:Mi.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 e=Mi.HydraStreamingEventType.TLE;e=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?Mi.HydraStreamingEventType.Overflow:Mi.HydraStreamingEventType.TLE;const t={stream:{playbackCoordinates:Ii(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:Ii(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:e,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&&(t.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(t.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(t.meetingMetadata=this.streamOptions.meetingMetadata),t}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("trackListUpdated",(e=>{this.onTrackListUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("trackSelected",(e=>{this.onTrackSelected(e)})))}onTrackListUpdated(e){this.trackInfo=e;const t=tt(e);this.logger.info(`[onTrackListUpdated]: Track list updated to: ${t}`)}onTrackSelected(e){const t=tt(e);this.logger.info(`[onTrackSelected]: Track selected: ${t}`)}getCaptionsControl(){return!this.captionsControl&&this.hydraPlayer&&(this.captionsControl=new ki(this.hydraPlayer,this.logger.createChild("CaptionsControl"))),this.captionsControl}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},ki=class{constructor(e,t){this.hydraPlayer=e,this.logger=t}async addCues(e){this.logger.warn("[addCues]: not implemented for UMS player")}async clearCues(){this.logger.warn("[clearCues]: not implemented for UMS player")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",e)}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(e){await this.hydraPlayer.callPlayerApi("selectHydraPlayerTextTrack",e)}},Oi=class extends Ei{constructor(){super()}trackListUpdated(e){this.event("trackListUpdated").raise(e)}trackSelected(e){this.event("trackSelected").raise(e)}},Ni=class extends gt{constructor(e,t,i){super(),this.configProvider=e,this.logger=t,this.getTelemetryLogger=i,this.isAvailable=!0,this._isStreaming=!1,this.playerSubs=[],this.isFinalTelemetrySent=!1,this.telemetryLogger=this.getTelemetryLogger(),1===this.configProvider.playerConfig.playerType?this.player=new Ai(this.logger.createChild("HlsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):2===this.configProvider.playerConfig.playerType?this.player=new Di(this.logger.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):(this.initializeAmpTelemetry(),this.player=new yi(this.logger.createChild("AmpLiveStreamPlayer"),this.liveStreamStatistic,this.configProvider)),this.subscribeForPlayerEvents()}get isStreaming(){return this._isStreaming}isActive(){return this.isAvailable&&this.isStreaming}async start(e,t){await this.setOptions(t),this.isFinalTelemetrySent=!1;const i=await this.player.loadPlayer(e);if(!i.setupSucceeded){this.player.stop(),this.logger.error("playerLoadFailed");const e=JSON.stringify(i.playerSetupError);throw this.sendFinalTelemetry(e),new Error(e)}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(){this.liveStreamStatistic=new qt(this.configProvider.config,this.logger.createChild("LiveStreamStatistic"),{perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],currentMediaTime:[],statsInterval:[]})}async stop(){}async setOptions(e){return void 0!==e.overflow&&(e.streamingEventType||(e.streamingEventType=e.overflow?"Overflow":"TLE"),delete e.overflow),this.options=e,this.player.configure(e)}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(e){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0,e))}sendTelemetry(e,t){if(this.liveStreamStatistic)if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const i={configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:e,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton,callendReason:t},n=this.liveStreamStatistic?.getReport(i);this.logger.debug("generated live stream report",n),this.telemetryLogger.sendEvent({eventName:"live_events",props:n})}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 e=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: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}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",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.player.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.player.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.player.on("capabilitiesUpdated",(e=>this.onCapabilitiesUpdated(e))))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackStateChanged(){const e=this.player.getPlaybackState();switch(e){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: ${e}`)}this.event("playbackStateChanged").raise(this.player.getPlaybackState())}onPlaybackError(e,t){this.event("error").raise(e,t)}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}onCapabilitiesUpdated(e){this.event("capabilitiesUpdated").raise(e)}},Li=class{constructor(e,t,i){this.ecsConfig=e,this.logger=t,this.getTelemetryLogger=i}configure(e){this.configuration=e}async initialize(){const e="MDN_MIDDLELANE_TEAMS",t="liveStream",i=this.ecsConfig.getString(e,t);let n={};try{n=JSON.parse(i)}catch(i){this.logger.warn(`failed to parse ECS configuration for ${e}/${t}`)}const r=this.ecsConfig.getString("ConfigIDs",e);this._configProvider=new Ut(n,this.configuration,r,this.logger.createChild("LiveStreamConfigProvider"))}createLiveStream(){return new Ni(this._configProvider,this.logger.createChild("LiveStream"),this.getTelemetryLogger)}dispose(){}},xi=class extends gt{constructor(){super(...arguments),this.isAudioOutputSelectionSupported=!1}createAudioPlayer(){return null}createAudioRenderer(){return null}getRawDeviceMediaStream(e){return null}askDevicePermission(){return Promise.resolve({audio:!1,video:!1})}getPermissionState(e){return"granted"}enumerateDevicesAsync(){return Promise.resolve([])}getPreferredCamera(){return null}selectDevices(){}getSelectedDevices(){return{}}startPreview(){return null}createPreview(){return Promise.resolve(new Fi)}createPreviewRenderer(){return Promise.resolve(new Fi)}createScreenSharingPreviewRenderer(){return Promise.resolve(new Fi)}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(e){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(e,t){return Promise.resolve()}downloadAiModel(e,t){return Promise.resolve("")}setAudioProcessingFlags(e){}getSpeakerVolume(){return Promise.resolve(0)}getSpeakerSystemVolume(){return Promise.resolve(0)}setSpeakerVolume(e){return Promise.resolve()}setSpeakerSystemVolume(e){return Promise.resolve()}unmuteMicrophone(){return Promise.resolve()}unmuteSpeaker(){return Promise.resolve()}getNrgLevelsForDeviceTuner(e){return Promise.resolve(0)}getNrgLevelPollerForDeviceTuner(e){return Promise.resolve(new Bi)}setAudioEffectsAsync(){return Promise.resolve()}getAudioFeatureCapability(e){return Promise.resolve(0)}getMicrophoneVolume(){return Promise.resolve(0)}setMicrophoneVolume(e){return Promise.resolve()}setDeviceTelemetryData(e,t,i,n=0){return Promise.resolve()}getSpeakerDeviceDomIdAsync(e,t){return Promise.reject()}mapBrowserDevices(e,t){return Promise.reject()}getSourceFormats(e){return Promise.resolve([])}enableShellSharing(){return Promise.resolve()}disableShellSharing(){return Promise.resolve()}enableParticipantCameras(){return Promise.resolve()}registerDerivedSource(e,t){return Promise.resolve()}unregisterDerivedSource(e){return Promise.resolve()}startAudioLoopbackDevice(e){return Promise.resolve()}async dispose(e){return Promise.resolve()}},Fi=class extends gt{constructor(){super(...arguments),this.isRendering=!1,this.streamSize={width:0,height:0},this.rendererType=-1,this.frameType=-1}captureFrame(){return Promise.resolve(new Ui)}getStats(){return Promise.resolve({framesDropped:0,framesTotal:0})}setScalingMode(){return Promise.resolve()}cameraAutoControl(e){return Promise.resolve(!1)}getCameraManualControlStates(e){return Promise.resolve([])}setCameraManualControlStates(e){return Promise.resolve([])}enumerateCameraManualControls(){return Promise.resolve([])}isCameraAdvancedControlCapable(){return Promise.resolve(!1)}dispose(){}},Ui=class extends gt{getSize(){return{width:0,height:0}}isMirrored(){return!1}},Bi=class{getInputLevel(){return 0}getInputLevelNormalized(e,t){return 0}dispose(){}},Vi=gt,Hi="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",$i="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",ji="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00",Gi={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:Hi,MSSDP_ENCODED_URI:Hi.replace(/\//g,"\\"),ATTRIBUTE:"transport-cc"},ABS_SEND_TIME:{EXT_URI:$i,MSSDP_ENCODED_URI:$i.replace(/\//g,"\\")},VLA:{EXT_URI:ji,EXT_URI_NON_ADV:ji+"-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}]},NATIVE_RATIO_PRECISION:6};function qi(e,t){for(const i in e)e.hasOwnProperty(i)&&t(e[i],i)}function zi(e,t){for(const i in e)e.hasOwnProperty(i)&&("object"==typeof e[i]?zi(e[i],t):t(e[i],i,e))}function Wi(e){return null!=e&&!Number.isNaN(e)}function Ki(e,t){return Wi(t)?Wi(e)?Math.min(e,t):t:e}function Ji(e,t){return Wi(t)?Wi(e)?Math.max(e,t):t:e}function Yi(e){let t=0;return e.forEach((e=>t+=e)),t/=e.length,t}function Qi(e,t){let i=!1;for(let n=e.length;n-- >0;)t(e[n],n,e)&&(e.splice(n,1),i=!0);return i}function Zi(e){const t=[];for(const i in e)e.hasOwnProperty(i)&&t.push(e[i]);return t}function Xi(e){return!Object.keys(e).length}function en(e){return Object.keys(e)}function tn(e){const t={};return qi(e,((e,i)=>{t[i]=e})),t}function nn(e){let t;if(!e||"object"!=typeof e)return e;if(e instanceof Date)return t=new Date,t.setTime(e.getTime()),t;if(e instanceof Array){t=[];for(let i=0,n=e.length;i<n;i++)t[i]=nn(e[i]);return t}if(e instanceof Object)return t={},qi(e,(function(e,i){t[i]=nn(e)})),t;throw new Error("Unable to copy: "+tt(e))}function rn(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function sn(){const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+e()+"4"+e().substring(1)+"b"+e().substring(1)+e()+e()+e()}function an(e,t){let i;const n=typeof e;if(e===t)return!0;if(n!==typeof t||"object"!==n&&"function"!==n)return!1;if(null===e||null===t)return e===t;if(e instanceof Date&&t instanceof Date)return+e==+t;if(e instanceof Map&&t instanceof Map)return function(e,t){let i;if(e.size!==t.size)return!1;let n=!0;return e.forEach(((e,r)=>{i=t.get(r),(i!==e||void 0===i&&!t.has(r))&&(n=!1)})),n}(e,t);for(i in e)if(!(i in t)||!an(e[i],t[i]))return!1;for(i in t)if(!(i in e)||!an(e[i],t[i]))return!1;return!0}function on(e,t){if(-1===t.indexOf(e))throw{detail:`${e} mediaContent.contentType is not supported`,type:Gi.MEDIA_ERROR.incompatibleOffer}}function ln(e,t){e.forEach((e=>{if(""!==e&&-1!==t.findIndex((t=>t===e)))throw{detail:`Required feature '${e}' is not acceptable.`,type:Gi.MEDIA_ERROR.incompatibleOffer}}))}function cn(e,t,i,n=0){for(let r=1;r<e.length;r++)if(e[r-1]+n<t&&t<=e[r]+n)return i?e[r]:e[r-1];return e[0]}function dn(e,t,i){return t<=e&&e<=i}function un(e,...t){for(const i of t)if(i.hasOwnProperty(e))return i[e]}function hn(e,t){return e.filter((e=>!t.some((t=>t===e))))}function gn(e,t){if(e===t)return e;let i=0,n=0,r="";for(let s=0;s<e.length&&!(r.length>e.length-s);s++){let a=s;n-i>r.length&&(r=e.substring(i,n),s=n-1),i=s,n=s;for(let o=0;o<t.length;o++)a<e.length&&t[o]===e[a++]?n=a:(a=s,n-i>r.length&&(r=e.substring(i,n),s=n-1),i=s,n=s)}return r}function pn(e,t){const i=new Array(e.length+1);for(let n=0;n<e.length+1;n++){i[n]=new Array(t.length+1);for(let e=0;e<t.length+1;e++)i[n][e]=0}for(let t=1;t<e.length+1;t++)i[t][0]=t;for(let e=1;e<t.length+1;e++)i[0][e]=e;for(let n=1;n<e.length+1;n++)for(let r=1;r<t.length+1;r++){let s=1;e[n-1]===t[r-1]&&(s=0),i[n][r]=Math.min(i[n-1][r]+1,i[n][r-1]+1,i[n-1][r-1]+s)}return i[e.length][t.length]}function mn(e,t=3){return e&&parseFloat(e.toFixed(t))}function fn(e,t){if(!e)return"";if(e.length<3)return e;const i=[],n=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);n&&i.push(n[1]);try{if(t?.length){const n=new RegExp(`(${t.join("|")})`,"gi");let r=n.exec(e);for(;r;)i.push(r[1]),r=n.exec(e)}else i.push("no_keywords")}catch(e){i.push(`Error: ${tt(e)}`)}return 0===i.length?"unknown":i.join(" ")}function vn(e,t,i=0){return e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t),e}function Sn(e,t,i,n=0){vn(e,0===i?0:i-1,n),0!==i&&e.push(t)}function yn(e,t){const i={};for(const e in t)i[e]={get:t[e],configurable:!1,enumerable:!0};Object.defineProperties(e,i)}function Cn(e){return e?.length>0?e[e.length-1]:void 0}var Tn=globalThis?.performance?.now&&globalThis?.performance?.timeOrigin,En=Tn?()=>globalThis.performance.now():()=>Date.now(),bn=Tn?globalThis.performance.timeOrigin:0,_n=En,In=bn;function wn(e,t,i){if(e?.length>0){const n=[];for(const r of e){const e=nn(r);e[t]=e[t]&&e[t]-i,n.push(e)}return n}return e}function An(e,t,i){if(!e)return;const n={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]};for(const[r,s]of Object.entries(e))for(const e of s)Sn(n[r],e-t,i);return n}function Pn(e,t,i=!1){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e&&(!1===i||0!==e)));return n?.length?n.join(","):void 0}function Rn(e,t,i){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e)).splice(-i);return n?.length?n:void 0}function Mn(e,t){const i=[];for(const n of e.keys())t.has(n)||i.push(n);for(const t of i)e.delete(t)}function Dn(e){return"object"==typeof e?tt(e):e}function kn(e){const t=Object.keys(e).map(Number).sort(((e,t)=>e-t)),i=t.reduce(((t,i)=>t+(e[i]??0)),0);return{getPercentile:n=>{const r=i*n;let s=0;for(const i of t)if(s+=e[i],s>=r)return i}}}function On(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}function Nn(e){const t=e.toLowerCase(),i=t.indexOf('token_types="');if(-1===i)return[];const n=t.indexOf('"',i+13);if(-1===n)return[];const r=t.substring(i+13,n).trim();return""===r?[]:r.split(" ")}function Ln(e){return 16*Math.ceil(e/16)}function xn(e,t,i,n){return JSON.stringify(wn(vn(e,t),i,n))}var Fn=Z;function Un(e){return e.map((e=>new Bn(e.w,e.h,e.fps,e.minBr,e.maxBr)))}var Bn=class{constructor(e,t,i=0,n=0,r=0){this.width=e,this.height=t,this.fps=i,this.minBitrate=n,this.maxBitrate=r,this.fs=Math.ceil(e/Gi.MACROBLOCK_SIZE)*Math.ceil(t/Gi.MACROBLOCK_SIZE)}toString(){return this.height?`${this.height}p`:`${this.fs}fs`}},Vn=class e{constructor(e){e||(this.resolutions=Un(Gi.RES_TABLE.SEND)),this.resolutions=Un(e)}static initialize(t){e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride),t.on("configUpdated",(()=>{e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride)}))}get initialResolution(){return this.resolutions[this.resolutions.length-1]}getResolutionByFs(e){return this.getResolutionRecord(void 0,e)}getMaxFsForHeight(e){return this.getResolutionRecord(e).fs}getResolutionForBitrate(e){let t=this.resolutions.filter((t=>t.maxBitrate&&t.maxBitrate>=e)).shift(),i=this.resolutions.filter((t=>t.minBitrate&&t.minBitrate<=e)).pop();return t=t??i,i=i??t,{lowRes:t,highRes:i}}getBitrateForResolution(e,t){const i=this.getResolutionRecord(Math.min(e,t));return{minBitrate:i.minBitrate,maxBitrate:i.maxBitrate}}getResolutionRecord(t,i){if(this===e.Send){for(let e=this.resolutions.length-1;e>=0;e--){if(t&&this.resolutions[e].height<=t)return this.resolutions[e];if(i&&this.resolutions[e].fs<=i)return this.resolutions[e]}return this.resolutions[0]}for(const e of this.resolutions){if(t&&e.height>=t)return e;if(i&&e.fs>=i)return e}return this.resolutions[this.resolutions.length-1]}getNextLowerResolution(t,i){const n=Math.min(t,i),r=this.getResolutionRecord(n),s=this.resolutions.indexOf(r);return n===Math.min(r.width,r.height)||this===e.Recv?this.resolutions[s-1]:this.resolutions[s]}getNextHigherResolution(t,i){const n=Math.min(t,i),r=this.getResolutionRecord(n),s=this.resolutions.indexOf(r);return n===Math.min(r.width,r.height)?this.resolutions[s+1]:this===e.Recv?this.resolutions[s]:this.resolutions[s+1]}getResolutions(){return[...this.resolutions]}};Vn.Recv=new Vn(Gi.RES_TABLE.RECV),Vn.Send=new Vn(Gi.RES_TABLE.SEND);var Hn=Vn,$n=e=>Hn.Send.getResolutionByFs(e).height,jn=e=>Hn.Send.getMaxFsForHeight(e),Gn={numVideoChannelsGvc:({current:e,constraints:t})=>Wn(e,t),specCompliantSimulcast:({current:e,constraints:t})=>Jn(e,t),multiviewResolutionLimits:({current:e,constraints:t,logger:i})=>Kn(e,t,i),enableVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),allowRemoteVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),enableNonAdvVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>er(e,t,i,n),outgoingVideoLimit:({current:e,settings:t,constraints:i})=>Zn(e,t,i),webrtcCameraOpenFs:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Xn(e,t,i,n),webrtcVideoCapabilityMaxFS:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Xn(e,t,i,n)},qn=(e,t,i)=>({...zn(e,t,i),...zn(e,t,i,"1on1"),...zn(e,t,i,"Multiparty")}),zn=(e,t,i,n)=>{const r={};for(const s of Object.keys(Gn)){const a=`${s}${n??""}`;n&&!Wi(t[a])||(r[a]=Gn[s]({current:t[a],settings:t,constraints:i,settingsSuffix:n,logger:e}))}return r},Wn=(e,t)=>Ki(e,t.maxIncomingStreams),Kn=(e,t,i)=>{const n=t.maxParticipantResolutions;if(!n)return e;const r={more:e.more};if(Number.isInteger(n))Object.keys(e).forEach((t=>{r[t]=Ki(n,e[t])}));else{const t=Object.keys(n);if(!t.length)return i.warn(`ignoring invalid value provided for maxParticipantResolutions: ${n}}`),e;t.forEach((t=>{r[t]=Ki(n[t],e[t]||e.more)}))}return r},Jn=(e,t)=>void 0!==t.maxSimulcastLayers||e.allowOverride?{...e,video:Yn(e.video,t),sharing:Yn(e.sharing,t)}:e,Yn=(e,t)=>{const i=e?.layerScaleFactors?.filter((e=>e<=t.maxSimulcastLayers));return i?.length>1?{...e,layerScaleFactors:i}:{...e,enableLocally:!1,allowEnableRemotely:!1}},Qn=e=>Ki((0,Fn.isNumber)(e?.outgoingVideoLimit)?e?.outgoingVideoLimit:e?.outgoingVideoLimit?.maxResolution,e?.maxOutgoingResolution),Zn=(e,t,i)=>{const{outgoingVideoLimit:n}=i,r=(0,Fn.isNumber)(n),s=Qn(i);if(t.sendVideoCapabilityManager?.isEnabled){const s=e=>e?$n(e):e,a=(e,t,i,n)=>t?Ji(Ki(t,n),i):e,o=r?void 0:n?.maxFramerate,l=r?void 0:n?.maxBitrate,c=Qn(i);return{...e,maxResolution:a(e?.maxResolution,c,s(t.sendVideoCapabilityManager?.minFS),s(t.sendVideoCapabilityManager?.maxFS)),maxFramerate:a(e?.maxFramerate,o,t.sendVideoCapabilityManager?.minFPS,t.sendVideoCapabilityManager?.maxFPS),maxBitrate:a(e?.maxBitrate,l)}}let a=Ki(e?.maxResolution,s);if(s>0&&t.maxCameraFsViaCallConstraints>0){const e=$n(t.maxCameraFsViaCallConstraints);a=Ji(Ki(a,e),Ki(s,e))}const o=Ki(e?.maxBitrate,r?void 0:n?.maxBitrate),l=Ki(e?.maxFramerate,r?void 0:n?.maxFramerate);return{...e,maxResolution:a,maxBitrate:o,maxFramerate:l}},Xn=(e,t,i,n)=>{if(Qn(i)>0&&t.maxCameraFsViaCallConstraints>0){const r=`outgoingVideoLimit${n??""}`,{maxResolution:s}=Zn(t[r],t,i);return Ji(e,s?jn(s):e)}return e},er=(e,t,i,n)=>!((t.specCompliantSimulcast.constraintsDisableVla||t[`specCompliantSimulcast${n}`]?.constraintsDisableVla)&&i.maxSimulcastLayers<2)&&e,tr=class extends Vi{constructor(e){super(e),this.logger=e,this._constraints={},this._callConstraintsTelemetry=[]}get constraints(){return this._constraints}get callConstraintsTelemetry(){return this._callConstraintsTelemetry}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};this._callConstraintsTelemetry.push(i)}setConstraints(e){this.logger.debug("Setting new platform call constraints",JSON.stringify(e)),this._constraints=e,this.addCallConstraintsTelemetryEvent(e,"requested"),this.raiseChanged()}getSettings(e){return qn(this.logger,e,this._constraints)}},ir=Z,nr='"rtcmedia"';function rr(e){return{expires:e.expires,username:e.username,password:e.password,realm:e.realm}}var sr=class{constructor(e){this.version=e,this.reports={},this.version||(this.version=1)}watch(e){const t={time:Date.now(),duration:-1,version:this.version};return this.reports[e]&&(e=`${e}_last`),this.reports[e]=t,{end:e=>{e&&(t.error=e),t.duration=Date.now()-t.time}}}getReports(){return this.reports}};function ar(e){return{Service:e.Service,Relay:e.Relay,Token:e.Token}}var or="configFetch",lr="skypeTokenFetch",cr="trapTokenFetch",dr=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new sr,this.context=e,this.logger=e.logger.createChild("RM"),this.request=e.request,this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e)}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getAuthTokenStats(){}getStats(){return{config:ar(this.config),stats:this.timers.getReports()}}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",it(t)):this.logger.error("failed to retrieve relays",it(t)),null)));return t}refreshRelaysFromConfig(){this.request.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}updateRelaysAsync(){const e=this.config.Service.tokenUrl;let t;const i=this.context.trapTokenCredentialsProvider?async()=>(t=this.timers.watch(cr),this.context.trapTokenCredentialsProvider()):async()=>{const i=this.timers.watch(lr);let n="";try{n=await this.context.tokenProvider(),this.logger.info("fetching skypeToken")}catch(e){throw i.end(it(e)),e}return i.end(),t=this.timers.watch(cr),(await this.request.get(e,{headers:{"X-Skypetoken":n,"api-version":2}})).response};return this.logger.info("Fetch TRAP token "+(this.context.trapTokenCredentialsProvider?"with provider":"directly")),i().then((e=>{t.end();let i=0;const n=this.config.Token.earlyRefreshMinutes,r=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),i=Math.max(e.expires-60*n,e.expires*r/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*i);const s=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:nr,a=rr(this.getTrapToken(s)),o={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"},l={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"},c={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"},d={Skype:[{...o,...a}],Lync:[{...l,...a}],Turn:[{...c,...a}]};return this.logger.info("relays from trap",[o,l,c]),d})).catch((e=>{throw t&&t.end(it(e)),e}))}storeTrapTokens(e){if(!e?.tokens)return void this.logger.error("failed to get tokens from trap response");const t={};e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}})),this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch(or);try{const t=await this.context.configProvider();e.end(),this.logger.info("retrieved configuration:",t),(0,ir.isEmpty)(t)||(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",tt(t)),e.end(it(t))}}},ur=Z,hr=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new sr(2),this.context=e,this.authTokenFetcher=this.context.authTokenFetcher,this.logger=e.logger.createChild("RM2")}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e),this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setClientSupportsGenericTokenApi(e){this.authTokenFetcher.supportsGenericTokenApi=e}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getStats(){return{config:ar(this.config),stats:this.timers.getReports()}}getAuthTokenStats(){return this.context.authTokenFetcher.getStats()}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",it(t)):this.logger.error("failed to retrieve relays",it(t)),null)));return t}refreshRelaysFromConfig(){this.context.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}async updateRelaysAsync(){const e=this.context.configProvider?.config.useNewTokenApi?"aadTokenFetch":lr,t=this.timers.watch(e),i=be();this.logger.info(`${i}[RM2] Fetch TRAP token`);try{const e=await this.context.authTokenFetcher.fetchTrapToken(i,this.config);t.end();let n=0;const r=this.config.Token.earlyRefreshMinutes,s=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),n=Math.max(e.expires-60*r,e.expires*s/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*n);const a=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:nr,o=rr(this.getTrapToken(a)),l={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"},c={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"},d={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"},u={Skype:[{...l,...o}],Lync:[{...c,...o}],Turn:[{...d,...o}]};return this.logger.info("relays from trap",[l,c,d]),u}catch(e){throw this.logger.info(`Fetch TRAP token failed with error ${e}`),t&&t.end(it(e)),e}}storeTrapTokens(e){const t={};if(e?.tokens)e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}}));else{if(!e.realm)return void this.logger.error("failed to get tokens from trap response");t[e.realm]=e}this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch(or);try{const t=await this.context.relayConfigProvider();e.end(),this.logger.info("retrieved configuration:",t),(0,ur.isEmpty)(t)||(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",it(t)),e.end(it(t))}}},gr=class{constructor(e,t,i,n,r){this.signalingAgentProvider=t,this.request=i,this.tokenProviders=n,this.configProvider=r,this.errors=[],this.clientSupportsGenericTokenAPI=!1,this.logger=e.createChild("AuthTokenFetcher")}set supportsGenericTokenApi(e){this.clientSupportsGenericTokenAPI=e}buildHeaders(e,t){const i={"api-version":2};switch(this.configProvider?.config.useTokenMigrationHeader&&(i["X-MS-Migration"]="True"),e){case 4:case 8:return i.Authorization=`Bearer ${t}`,i;case 1:return i["X-Skypetoken"]=t,i;default:throw new Error(`TokenType ${e} is not supported`)}}serviceSupportedTokenTypes(e){let t=null;if(void 0===e)t=this.clientSupportedTokenTypes();else{const i=e?.toLowerCase();t=this.constructTokenType(i)}return null===t&&this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader&&(t|=1),t}extractWwwauthenticateHeaders(e){let t={};if(e){const i=On(e,"www-authenticate");i&&(t={authenticationHeaders:[i]})}return t}convertStringToTokenType(e){switch(e){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(e,t){if(!this.clientSupportsGenericTokenAPI)return 1;let i=null;const n=t?.authenticationHeaders;if(!n&&e)this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader?(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),i=1):(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),i=this.clientSupportedTokenTypes());else if(n||e){if(n&&e)for(const e of n){const t=Nn(e);if(this.configProvider?.config.supportMissingTokenTypesInResponse&&0===t.length)this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),i=this.clientSupportedTokenTypes();else for(const e of t){const t=this.convertStringToTokenType(e.toLowerCase());this.configProvider?.config.clientSupportsCaeToken&&8===t&&(i|=8),this.configProvider?.config.clientSupportsAadToken&&4===t&&(i|=4),this.configProvider?.config.clientSupportsSkypeToken&&1===t&&(i|=1)}}}else this.logger.info("[authTokenFetcher][getTokenTypeFromHeaders] retrying to fetch token woth client supported tokens"),i=this.clientSupportedTokenTypes();return i}constructTokenType(e){let t=null;return e.includes("aad")&&this.configProvider?.config.clientSupportsAadToken&&(t|=4),e.includes("cae")&&this.configProvider?.config.clientSupportsCaeToken&&(t|=8),e.includes("skype")&&this.configProvider?.config.clientSupportsSkypeToken&&(t|=1),t}getTokenMetadataForTrapService(e,t,i){const n={verb:"POST",path:e},r=JSON.stringify(n);let s=null;const a=this.extractWwwauthenticateHeaders(i),o=!!a?.authenticationHeaders;return s=i?this.getTokenTypeFromHeaders(o,a):this.serviceSupportedTokenTypes(t),this.logger.info(`[authTokenFetcher][getTokenMetadata] return token type=${s}, factoJson=${r}`),{tokenType:s,factorsJson:r,requestMetadataJson:a,isUnauthorized:o}}clientSupportedTokenTypes(){let e=null;return this.configProvider?.config.clientSupportsAadToken&&(e|=4),this.configProvider?.config.clientSupportsCaeToken&&(e|=8),this.configProvider?.config.clientSupportsSkypeToken&&(e|=1),e}async handleAuthTokenFailure(e,t,i,n){this.logger.info("[authTokenFetcher][handleAuthTokenFailure] failed to fetch token, retrying");try{const r=this.getTokenMetadataForTrapService(t,void 0,i);return this.logger.info(`[authTokenFetcher][handleAuthTokenFailure] token request options=${r}`),r.invalidToken=n,await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(e,!1,r)}catch(e){const t={status:e?.response?.status||e?.status,error:e,fatal:!0};this.errors.push(tt(t)),this.logger.error(`[authTokenFetcher] failed to fetch token trough new api with error: ${tt(t)}, quiting`)}}getRequestToken(e){const t=On(e,"X-Skypetoken");if(t)return t;const i=On(e,"Authorization");if(i){const e=i.split(" ");if(2===e.length)return e[1]}}async fetchTrapCredentials(e,t,i){const n=this.buildHeaders(t,e),r=await this.request.get(i,{headers:n});return r?.response}async fetchTrapTokenWithNewTokenApi(e,t,i){let n;this.logger.info(`${i}[authTokenFetcher] fetching token through fetchTrapTokenWithNewTokenApi`);const r=this.getTokenMetadataForTrapService(e,t);try{return n=await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(i,!1,r),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}catch(t){const r={status:t?.response?.status||t?.status,error:t,fatal:!1};this.errors.push(tt(r)),this.logger.error(`${i}[authTokenFetcher] fetchTrapTokenWithNewTokenApi failed with ${tt(r)}, retrying...`);const s=t?.response?.headers;if(s){const t=this.getRequestToken(s);return n=await this.handleAuthTokenFailure(i,e,s,t),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}throw t}}async fetchTrapTokenThroughProvider(){return this.logger.info("[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokenThroughProvider"),this.tokenProviders.trapTokenCredentialsProvider()}async fetchTrapTokensWithLegacyTokenFetcher(e,t){this.logger.info(`${t}[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokensWithLegacyTokenFetcher`);try{this.tokenTypeFetched=1;const t=await this.tokenProviders.skypeTokenProvider();return(await this.request.get(e,{headers:{"X-Skypetoken":t,"api-version":2}})).response}catch(e){throw this.errors.push(tt(e)),this.logger.error(`${t}[authTokenFetcher] fetchTrapTokensWithLegacyTokenFetcher failed with ${tt(e)}`),e}}getStats(){return{tokenType:this.tokenTypeFetched,errors:nt(this.errors,this.configProvider?.config.diagnostics.telemetryLimits.numAuthTokenErrors??100)}}async fetchTrapToken(e,t){let i;this.logger.info(`${e}[AuthTokenFetcher] Start fetching token`);const n=t.Service.tokenUrl,r=t.Service.supportedTokenTypes;return i=this.configProvider?.config.useNewTokenApi?this.fetchTrapTokenWithNewTokenApi(n,r,e):this.tokenProviders.trapTokenCredentialsProvider?this.fetchTrapTokenThroughProvider():this.fetchTrapTokensWithLegacyTokenFetcher(n,e),i}},pr=class{constructor(e,t,i,n){this.config=e,this.signalingAgentProvider=t,this.ecsProvider=i,this.logger=n}getOrCreateRelayManager(){return this.config.relayManager?this.config.relayManager:this.relayManager||this.createRelayManager()}setConfigProvider(e){this.configProvider=e}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(e,t,i,n,r,s){const a=e||new st(this.logger),o=this.ecsProvider.getEcsConfig("SkypeCalling","enableFetchApi"),l={get:(e,t)=>a.getAsync(e,{...a.getRequestOptions("GET",t?.headers,null,t?.timeout),useFetch:o}),isOnline:n.isOnline};if(this.configProvider?.config.useNewTokenApi){const e=new gr(this.logger,this.signalingAgentProvider,l,{skypeTokenProvider:t,trapTokenCredentialsProvider:r},s);return new hr({logger:this.logger,relayConfigProvider:()=>i.getRelayConfig(),isOnline:n.isOnline,authTokenFetcher:e,configProvider:s})}return function(e){return new dr(e)}({logger:this.logger,tokenProvider:t,trapTokenCredentialsProvider:r,configProvider:()=>i.getRelayConfig(),request:{get:(e,t)=>a.getAsync(e,{...a.getRequestOptions("GET",t?.headers,null,t?.timeout),useFetch:o}),isOnline:n.isOnline}})}},mr="*13",fr={totalParticipants:0,preheatedParticipants:0,lobbyParticipants:0,totalPresenters:0,requestingAttentionPresenters:0,totalAttendees:0,requestingAttentionAttendees:0,overflowAttendees:0},vr=Q,Sr=class{constructor(e,t,i,n,r){this.eventName=e,this.eventStartTime=t,this.type=i,this.causeId=n,this.status="Pending",this.eventStartTimestamp=(new Date).getTime(),this.data=[],this.causeId=n?.substring(0,8),"Event"===this.type&&delete this.status,r&&this.data.push(r)}set variant(e){this.eventVariant=e}recordSuccess(e,t){this.recordResult("Success",e,t)}recordFailure(e,t){this.recordResult("Failure",e,t)}recordTimeout(e,t){this.recordResult("Timeout",e,t)}addData(e){this.data.push(e)}isPending(){return"Pending"===this.status}getEvent(){const e={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((e=>this.prepareData(e,!0))).filter((e=>!!e))};return"Event"===this.type&&delete e.status,e.data.length||delete e.data,e.causeId||delete e.causeId,e.resultCauseId||delete e.resultCauseId,e.result||delete e.result,e.variant||delete e.variant,{[this.eventName]:e}}recordResult(e,t,i){this.status=e,this.result=this.prepareData(t),this.causeId!==i&&(this.resultCauseId=i),this.duration=(new Date).getTime()-this.eventStartTimestamp}prepareData(e,t=!1){if(null==e)return"";if("string"==typeof e)return De(e);if("number"==typeof e||"boolean"==typeof e)return String(e);if("function"==typeof e)return"";if(e instanceof Error)return e.toString();try{return Object.keys(e).length?t?e:$e(e):""}catch(e){return"invalid"}}},yr=class{constructor(e,t,i,n){this.logger=e,this.startTime=t,this.maxEventsExceeded=i,this.perfModule=n,this.recordedEvents=[],this.ipcStats=[],this.ongoingOperations={}}recordEvent(e,t,i=be()){this.logger.debug("Event:",e,vr.pii.Omit(t));const n=new Sr(e,this.getEventStartTime(),"Event",i,t);return this.pushToRecordedEvents(n),n}recordOperationSuccess(e,t=null,i,n,r){this.logger.info("Event success:",n,e,vr.pii.Omit(i),vr.pii.Omit(t)),this.recordOperationResult(e,t,"Success",i,n,r)}recordOperationFailure(e,t,i,n,r){this.logger.info("Event failure:",e,vr.pii.Omit(i),t),this.recordOperationResult(e,t,"Failure",i,n,r)}recordOperationTimeout(e,t,i,n,r){this.logger.info("Event timeout:",e,vr.pii.Omit(i),t),this.recordOperationResult(e,t,"Timeout",i,n,r)}maybeRecordOperationSuccess(e,t=null,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationSuccess(e,t,i,n,r)}maybeRecordOperationFailure(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationFailure(e,t,i,n,r)}maybeRecordOperationTimeout(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationTimeout(e,t,i,n,r)}recordOperationResult(e,t,i,n,r,s){this.hasOngoingEvent(e,n)||this.recordOperation(e,r,n);let a=this.ongoingOperations[e];switch(n&&(a=a[n]),s&&a.addData(s),i){case"Success":a.recordSuccess(t,r);break;case"Failure":a.recordFailure(t,r);break;case"Timeout":a.recordTimeout(t,r);break;default:this.logger.error("Unknown operation record state in record operation result.")}n?delete this.ongoingOperations[e][n]:delete this.ongoingOperations[e]}recordOperation(e,t,i,n){this.logger.debug("Event create:",t,e,vr.pii.Omit(i),n);const r=new Sr(e,this.getEventStartTime(),"Operation",t,n);return this.ongoingOperations[e]||(this.ongoingOperations[e]={}),i?this.ongoingOperations[e][i]=r:this.ongoingOperations[e]=r,this.pushToRecordedEvents(r),r}setOperationVariant(e,t,i){let n;n=i?this.ongoingOperations[e][i]:this.ongoingOperations[e],n?n.variant=t:this.logger.error(`Could not find operation ${e} to set variant ${t}`)}updateOperationData(e,t,i,n){try{if(!this.ongoingOperations[e])return void this.recordEvent(e,t,i);n?this.ongoingOperations[e][n]&&this.ongoingOperations[e][n].addData(t):this.ongoingOperations[e].addData(t)}catch(t){return void this.logger.info(`Unable to update operation: ${e} data`)}}pushToRecordedEvents(e){if(this.maxEventsExceeded&&this.maxEventsExceeded()&&this.recordedEvents.shift(),this.recordedEvents.push(e),this.perfModule&&this.ipcStats.length<=30){const e=this.perfModule.getIpcStats();e&&this.ipcStats.push({ingestionTime:this.getEventStartTime(),stats:e})}}hasOngoingEvent(e,t){return this.ongoingOperations[e]?!(t&&!this.ongoingOperations[e][t]&&(this.logger.warn(`Unable to find event for name\\id ${e}\\${vr.pii.Omit(t)}`),1)):(this.logger.warn(`Unable to find event for name ${e}`),!1)}getEventStartTime(){return(new Date).getTime()-this.startTime}getEventTimestampBag(e,t){const i=t?[t.getEvent()]:this.recordedEvents.filter((t=>!e||!t.isPending())).map((e=>e.getEvent())),n=JSON.stringify({eventStart:this.startTime,events:i});return this.logger.info(`Call eventTimestampBag ${vr.pii.Omit(n)}`),n}getIPCStats(){return 0!==this.ipcStats.length?JSON.stringify(this.ipcStats):""}removeRecordedEvent(e){const t=this.recordedEvents.indexOf(e);t>-1&&this.recordedEvents.splice(t,1)}},Cr=class extends yr{constructor(e,t){super(e,t,(()=>this.recordedEvents.length>150)),this.getHostName=()=>{try{return"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>"}catch(e){return"unknown"}},this.tsCallingVersion="2025.07.01.15",this.logger=e.createChild("CallRegistryTelemetry")}setClientType(e){this.clientType=e}setEndpointId(e){this.endpointId=e}setSkypeId(e){this.skypeId=De(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}getEvent(e,t){const i=e=>void 0===e?"":e;return{EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),userHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),TsCallingVersion:i(this.tsCallingVersion),HostName:this.getHostName(),EventTimestampBag:this.getEventTimestampBag(e,t),DiagnosticInfo:this.callEndDiagnosticInfo,ClientType:i(this.clientType)}}removeNonPendingOperations(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending()))}},Tr=class extends yr{constructor(e,t,i){super(e,t,(()=>this.inCallMode&&this.recordedEvents.length>150),i),this.inCallMode=!1,this.tsCallingVersion="2025.07.01.15",this.logger=e.createChild("CallTelemetry")}setClientType(e){this.clientType=e}setCallId(e){this.currentCallId&&(this.previousCallId=this.currentCallId),this.currentCallId=e}setConsultativeCallId(e){this.consultativeCallId=e}setEndpointId(e){this.endpointId=e}setParticipantId(e){this.participantId=e}setDisplayName(e){this.displayName=e}setPreheatFlags(e){this.preheatFlags=e}setCallOrigin(e){this.origin=e}setGroupId(e){this.groupId=e}setThreadId(e){this.threadId=e}setBackroomThreadId(e){this.backroomThreadId=e}setStreamThreadId(e){this.streamThreadId=e}setLobbyThreadId(e){this.lobbyThreadId=e}setComplianceRecordingContentLength(e){this.complianceRecordingContentLength=e}setConversationStartTime(e){this.conversationStartTime=e}setCompositionServiceState(e){this.compositionServiceState=e}setMessageId(e){this.messageId=e}setSkypeId(e){this.skypeId=De(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}setFailureType(e){this.failureType=e}setIsCast(e){this.isCast=e?"True":"False"}setIsHuddleGroupCall(e){this.isHuddleGroupCall=e?"True":"False"}setIsEmergency(e){this.isEmergency=e?"True":"False"}setRole(e){this.isAnonymous="admin"===e?"False":"True"}setCallType(e){this.callType=e}setConversationType(e){this.conversationType=e}setDirection(e){this.direction=e}setSelfParticipantRole(e){this.selfParticipantRole=e}setTerminationState(e){this.terminationState=e}setTerminationReason(e){this.terminationReason=e}setCallEndDiagnosticInfo(e){this.callEndDiagnosticInfo=e}setStackConfig(e){this.stackConfig=e}setJoinedFrom(e){this.joinedFrom=e}setMeetingCode(e){this.meetingCode=e}setMeetingUrl(e){this.meetingUrl=e}setHasMeetingRegistrationId(e){this.hasMeetingRegistrationId=e?"True":"False"}setHasParticipantPin(e){this.hasParticipantPin=e?"True":"False"}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.currentCallId),PreviousCorrelationId:i(this.previousCallId),ConsultativeCallId:i(this.consultativeCallId),EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ParticipantId:i(this.participantId),DisplayName:new Re(this.displayName??"",1),PreheatFlags:i(this.preheatFlags),CallType:i(this.callType),ConversationType:i(this.conversationType),Direction:i(this.direction),Origin:i(this.origin),SelfParticipantRole:i(this.selfParticipantRole),IsAnonymous:i(this.isAnonymous),GroupId:De(i(this.groupId)),ThreadId:xe(i(this.threadId)),MessageId:i(this.messageId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),UserHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),FailureType:i(this.failureType),IsCast:i(this.isCast),IsHuddleGroupCall:i(this.isHuddleGroupCall),IsEmergency:i(this.isEmergency),TsCallingVersion:i(this.tsCallingVersion),TerminationState:i(this.terminationState),TerminationReason:i(this.terminationReason),StackConfig:i(this.stackConfig),EventTimestampBag:this.getEventTimestampBag(e,t),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:i(this.complianceRecordingContentLength),ConversationStartTime:i(this.conversationStartTime),BackroomThreadId:xe(i(this.backroomThreadId)),StreamThreadId:xe(i(this.streamThreadId)),LobbyThreadId:xe(i(this.lobbyThreadId)),ClientType:i(this.clientType),CompositionServiceState:i(this.compositionServiceState)}}getShortEvent(){const e=e=>void 0===e?"":e;return{CorrelationId:e(this.currentCallId),EndpointId:e(this.endpointId),ParticipantId:e(this.participantId),DisplayName:new Re(this.displayName??"",1),CallType:e(this.callType),ConversationType:e(this.conversationType),Direction:e(this.direction),Origin:e(this.origin),SelfParticipantRole:e(this.selfParticipantRole),IsAnonymous:e(this.isAnonymous),ThreadId:xe(e(this.threadId)),ApplicationType:e(this.applicationType),Ring:e(this.ring),TenantId:e(this.tenantId),UserHexCID:e(this.userHexCID),AcsResourceId:e(this.acsResourceId),Region:e(this.region),TsCallingVersion:e(this.tsCallingVersion),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,ClientType:e(this.clientType)}}switchToInCallTelemetry(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending())),this.inCallMode=!0}getHostName(){try{return location.host}catch(e){return"unknown"}}},Er=e=>Array.isArray(e)?e.map((e=>({endpointId:e.endpointId,participantId:e.participantId}))):null;function br(e,t,i){if(!e)return i.info(`sanitizeMeetingCode[${t}] empty / undefined meeting code parameter`),e;let n=e.replace(/\s/g,"");return n=n.replace(/-/g,""),i.info(`sanitizeMeetingCode[${t}] meetingCode: ${e}, sanitizedMeetingCode: ${n}`),n}function _r(e,t,i){if(!e)return i.info(`getMeetingCodeFromMeetingUrl[${t}] empty / undefined meeting Url parameter`),e;const n=new URL(e);let r="";if(n&&n.pathname&&n.pathname.split("/").length>=2){const e=n.pathname.split("/");"meet"===e[e.length-2]&&(r=e[e.length-1])}return i.info(`getMeetingCodeFromMeetingUrl[${t}] meetingUrl: ${e}, meetingUrlObject: ${Ge(n)}, meetingCode: ${r}`),r}function Ir(e,t,i,n){const r=br(e&&e.meetingCode||"",i,n),s=br(t&&t.meetingCode||"",i,n),a=(e,t)=>!!e&&!!t&&e===t;if(a(r,s))return!0;let o=_r(e&&e.meetingUrl||"",i,n);o=br(o,i,n);let l=_r(t&&t.meetingUrl||"",i,n);if(l=br(l,i,n),a(o,l))return!0;if(a(o,s)||a(l,r))return!0;if(e&&e.meetingUrl&&t&&t.meetingUrl){const i=new URL(e.meetingUrl),n=new URL(t.meetingUrl);if(i.hostname===n.hostname&&i.pathname===n.pathname)return!0}return!1}function wr(){}var Ar=0,Pr=410,Rr=499,Mr=497,Dr=3e3,kr=3548,Or=3757,Nr=4990,Lr=5028,xr=4521,Fr=3545,Ur=4294967294,Br="_operationIdValue_",Vr="_causeIdValue_",Hr="_callStartOptionsValue_",$r="_clientReasonValue_",jr="_guidIdValue_";function Gr(e,t){return Qr(0,e,t)}function qr(e,t){return Qr(1,e,t)}var zr=(e,t,i)=>{if(e[t][Br])throw new Error("can not specify more than one operation id");e[t][Br]=i},Wr=(e,t,i)=>{if(e[t][Vr])throw new Error("can not specify more than one cause id");e[t][Vr]=i},Kr=(e,t,i)=>{if(e[t][Hr])throw new Error("can not specify options more than once");e[t][Hr]=i},Jr=(e,t,i)=>{if(e[t][$r])throw new Error("can not specify reason more than once");e[t][$r]=i},Yr=(e,t,i)=>{if(e[t][jr])throw new Error("can not specify more than one guid");e[t][jr]=i},Qr=(e,t,i)=>(n,r,s)=>{const a=s.value,o=n[r]?.[Br],l=n[r]?.[Vr],c=n[r]?.[jr],d=n[r]?.[Hr],u=n[r]?.[$r],h=i?.type||"Async";return s.value=function(...n){const r=this;let s=be();void 0!==l&&(n[l]&&(_e(n[l])||fi(n[l]))?s=n[l]:n[l]=s);let g,p=void 0!==o?n[o]:void 0;if(void 0!==p)if(Array.isArray(p))try{const e=p.map((e=>e.toString())).sort().concat().toString();p=function(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}(e).toString()}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`[${p}]${t} failed in array parsing in operationDecorator`};return Promise.reject(e)}else if(p&&"object"==typeof p)try{let e=JSON.stringify(p);i&&i.operationIdKey&&p.hasOwnProperty(i.operationIdKey)&&(e=p[i.operationIdKey]),p=e}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`[${p}]${t} failed in object parsing in operationDecorator`};return Promise.reject(e)}void 0!==u&&n[u]&&(g=n[u]);const m=Zr(r,e);if(m.logOperation(s,t),i&&i.singular&&m.hasPendingOperation(t))return m.logOperation(s,t,"Not allowed, pending operation exists"),Promise.reject(60);if(i&&i.idempotencyLevel&&m.getRecord(t)>0)switch(m.logOperation(s,t,`Called multiple times, handling operation according to specified policy: idempotency=${i.idempotencyLevel}`),i.idempotencyLevel){case"NoOp":return Promise.resolve();case"Error":return Promise.reject(60)}try{void 0!==d&&n[d]&&r.processCallStartOptions(n[d],s)}catch{const e={terminatedReason:32,terminatedReasonCode:Mr,terminatedReasonSubCode:Fr,errorMessage:`${t} failed in processCallStartOptions`};return Promise.reject(e)}if(void 0!==c&&n[c]&&_e(n[c])&&!fi(n[c])){let e=mi();e=e.replace(e.substring(0,8),n[c]),n[c]=e}const f=!(!i||!i.convertError),v=()=>"Chained"===h?m.executeChained(a.bind(this,...n),t,p,s,f,g,i):"Sync"===h?m.executeSync(a.bind(this,...n),t,p,s,f,g):m.execute(a.bind(this,...n),t,p,s,f,g,i);if("StartCall"!==t&&"JoinCall"!==t||m.hasPendingOperation("_CallStartOrJoinInitiated")||m.createPendingOperation("_CallStartOrJoinInitiated").catch(wr),i&&i.triggerAttach&&(m.hasPendingOperation("_ElectronSlimcoreReady")||m.createPendingOperation("_ElectronSlimcoreReady").catch(wr)),i&&"Sync"!==i.type){const e=i&&i.waitFor;if(Array.isArray(e))return Promise.all(e.map((e=>e&&m.hasPendingOperation(e)&&m.waitForOperation(e,void 0,s)))).then(v,v);if(e&&m.hasPendingOperation(e))return m.waitForOperation(e,void 0,s).then(v,v)}return v()},s},Zr=(e,t)=>{if(0===t)return e._callOperationHandler;if(1===t)return e._participantOperationHandler;throw new Error("Unsupported operation handler type!")},Xr=class{constructor(e){this._disposed=!1,this._logger=e.createChild("[ASYNC]"),this._endOperationDeferred=new Kt,this._endOperationDeferred.promise.catch((e=>{this._logger.info("Rejected all operations")})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._deferredOperationsWithCauseId={},this._logger=e}registerPromise(e,t){let i=!1;const n=()=>{i=!0};t.then(n,n);const r=this._endOperationDeferred.promise.catch((t=>{if(!i)throw new Error(`Operation ${e} did not complete, reason:${t}`)}));return Promise.race([r,t])}updateOperationId(e,t){this._logger.info(`updateOperationId ${e} ${t}`),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{i&&this._deferredOperationsWithOperationId[i]&&(this._logger.info(`_deferredOperationsWithOperationId ${i}`),Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{n&&this._deferredOperationsWithOperationId[i][n]&&(this._logger.info(`_deferredOperationsWithOperationId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))})),Object.keys(this._deferredOperationsWithCauseId).forEach((i=>{i&&this._deferredOperationsWithCauseId[i]&&(this._logger.info(`_deferredOperationsWithCauseId ${i}`),Object.keys(this._deferredOperationsWithCauseId[i]).forEach((n=>{n&&this._deferredOperationsWithCauseId[i][n]&&(this._logger.info(`_deferredOperationsWithCauseId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))}))}createPendingOperation(e,t,i=be(),n={}){const r=new Kt;r.promise.catch(wr);const s=this.getOperationInfoForLogging(i,e,t);let a;if(this._logger.info(`${s}[creating...]`),this._disposed)return this._logger.info(`${s}[create failed, call is disposed]`),Promise.reject(60);if(t){if(this._deferredOperationsWithOperationId[e]||(this._deferredOperationsWithOperationId[e]={}),this._deferredOperationsWithOperationId[e][t])return this._logger.warn(`${s} Deferred operation with given name and operation id is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}/${De(t)}`));this._deferredOperationsWithOperationId[e][t]={deferred:r,causeId:i},this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][t]={deferred:r,options:n,operationName:e},a=this._endOperationDeferred.promise.catch((i=>{if(this.hasPendingOperationWithOperationId(e,t))throw new Error(`Operation ${e} ${t} did not complete, reason:${i}`)}))}else{if(this._deferredOperations[e])return this._logger.warn(`${s} Deferred operation with given name is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}`));this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][""]={deferred:r,options:n,operationName:e},this._deferredOperations[e]={deferred:r,causeId:i},a=this._endOperationDeferred.promise.catch((t=>{if(this.hasPendingOperation(e))throw new Error(`Operation ${e} did not complete, reason:${t}`)}))}return Promise.race([a,r.promise])}hasPendingOperation(e){return!!this._deferredOperations[e]}hasAtleastOneOfPendingOperation(e){for(const t of e)if(this.hasPendingOperation(t))return!0;return!1}hasPendingOperationWithOperationId(e,t){return!(!t||!this._deferredOperationsWithOperationId[e]||!this._deferredOperationsWithOperationId[e][t])}hasPendingOperationWithCauseId(e,t){const i=t||"";return this._deferredOperationsWithCauseId[e]&&!!this._deferredOperationsWithCauseId[e][i]}getPendingOperationWithCauseId(e,t){return this.hasPendingOperationWithCauseId(e,t)?this._deferredOperationsWithCauseId[e][t].deferred.promise:Promise.reject(`[${e}][${t}]: getPendingOperationWithCauseId for given causeId, operationId`)}resolveOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return t.deferred.resolve(i),this._logger.info(`[${e}][${n}] resolved, result=${je(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] resolveOperationWithCauseId failed, operation not found`)}rejectOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return r.catch(wr),t.deferred.reject(i),this._logger.info(`[${e}][${n}] rejected, result=${je(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] rejectOperationWithCauseId failed, operation not found`)}maybeResolveOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.resolveOperationWithCauseId(e,t,i).catch((t=>{this._logger.info(`${e}maybeResolveOperationWithCauseId failed, reason=${je(t)}`)})):this._logger.info(`${e}maybeResolveOperationWithCauseId ignored, operation does not exist`)}maybeRejectOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.rejectOperationWithCauseId(e,t,i).catch(wr):this._logger.info(`${e}maybeRejectOperationWithCauseId ignored, operation does not exist`)}getPendingOperation(e,t,i=be()){return!t&&this._deferredOperations[e]?this._deferredOperations[e].deferred.promise:t&&this._deferredOperationsWithOperationId[e]&&this._deferredOperationsWithOperationId[e][t]?this._deferredOperationsWithOperationId[e][t].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}: Deferred operation with given name and operation does not exist`)}waitForOperation(e,t,i=be()){return t&&this.hasPendingOperationWithOperationId(e,t)?this._deferredOperationsWithOperationId[e][t].deferred.promise:this.hasPendingOperation(e)?this._deferredOperations[e].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}failed=wait failed, operation not found`)}resolveOperation(e,t,i,n=be(),r=!1){if(!e)return Promise.reject("Unable to resolve deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],s=n.deferred.promise;return n.deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${je(t)||"void"}`),r||delete this._deferredOperationsWithOperationId[e][i],s}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],s=this._deferredOperations[e].deferred.promise;return this._deferredOperations[e].deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${je(t)||"void"}`),r||delete this._deferredOperations[e],s}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=resolve failed, operation not found`)}rejectOperation(e,t,i,n=be()){if(!e)return Promise.reject("Unable to reject deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],r=n.deferred.promise;return r.catch(wr),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${je(t)||"void"}`),delete this._deferredOperationsWithOperationId[e][i],r}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],r=n.deferred.promise;return r.catch(wr),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${je(t)||"void"}`),delete this._deferredOperations[e],r}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=reject failed, operation not found`)}maybeResolveOperation(e,t,i,n=be()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.resolveOperation(e,t,i,n).catch((e=>{this._logger.info(`${r}maybeResolveOperation failed, reason=${je(e)}`)})):this._logger.info(`${r}maybeResolveOperation ignored, operation does not exist`)}maybeResolveOperations(e,t,i,n=be()){for(const r of e)this.maybeResolveOperation(r,t,i,n)}maybeRejectOperation(e,t,i,n=be()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.rejectOperation(e,t,i,n).catch(wr):this._logger.info(`${r}maybeRejectOperation ignored, operation does not exist`)}maybeRejectOperations(e,t,i,n=be()){for(const r of e)this.maybeRejectOperation(r,t,i,n)}rejectPendingOperations(e,t=be()){this._disposed=!0,this._logger.info(`[${t}]rejectPendingOperations=${JSON.stringify(e)}`),Object.keys(this._deferredOperations).forEach((i=>{this.maybeRejectOperation(i,e,void 0,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][""]})),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{this.maybeRejectOperation(i,e,n,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][n]}))})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._endOperationDeferred.reject(e)}maybeRejectPendingOperationsWithPredicate(e,t=be(),i){this._logger.info(`[${t}]rejectPendingOperationsWithPredicate`),Object.keys(this._deferredOperationsWithCauseId).forEach((t=>{Object.keys(this._deferredOperationsWithCauseId[t]).forEach((n=>{const r=this._deferredOperationsWithCauseId[t][n];r&&i(r.operationName,r.options)&&(this.maybeRejectOperation(r.operationName,e,n),this.maybeRejectOperationWithCauseId(t,n,e))}))}))}getOperationInfoForLogging(e,t,i=""){const n=i?`[${De(i)}]`:"";return`[${e.substring(0,8)}][${t}]${n}`}},es=Z,ts=class{constructor(e){this._logger=e,this._promise=Promise.resolve(void 0),this._actionQueue=[]}chainPromise(e,t,i=be(),n=!1){const r=Date.now(),s=(("function"==typeof t?t():t)||"").toString();this._actionQueue.push(s),this._logger.info(`[${i}][${s}]enqueueing, queue=[${this._actionQueue}], reset=${n}`);const a=()=>{this._actionQueue=this._actionQueue.filter((e=>e!==s))};return n&&this.reset(i),this._promise=this._promise.catch(es.noop).then((()=>{const t=Date.now()-r;return this._logger.info(`[${i}][${s}]begin, delayMs=${t}`),e()})),this._promise.then((()=>{a();const e=Date.now()-r;this._logger.info(`[${i}][${s}]success, durationMs=${e}`)}),(e=>{a();const t=Date.now()-r;this._logger.warn(`[${i}][${s}]failed=${Ge(e)}, durationMs=${t}`)})),this._promise}reset(e){this._logger.info(`[${e}] resetting`),this._promise=Promise.resolve(void 0)}};function is(e){return!!e?.code}function ns(e,t){let i;return i=is(e)?e:{code:499,subCode:void 0!==t?t:0,phrase:"string"==typeof e?e:je(e)},i}var rs=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 e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}get startTime(){return this._startTime}};function ss(){return new rs}var as=class extends Xr{constructor(e,t,i,n,r){super(e),this.callTelemetry=t,this._ecsConfig=i,this._publishCallback=n,this._preconditionFunction=r,this._record={},this.logSuccess=(e,t,i)=>{this._logger.info(`${e} execution succeeded, result=${t?je(t):"void"}, time=${i.duration()}`)},this.logFailure=(e,t,i)=>{this._logger.info(`${e} execution failed, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.logTimeout=(e,t,i)=>{this._logger.info(`${e} execution timed out, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.stringifyForLogging=e=>{let t;if(e instanceof Error)t=e.toString()||"Unknown Error";else try{t=JSON.stringify(e)}catch(e){t="Unable to stringify data"}return t},this.convertToTransactionEndIfErrorOrString=(e,t,i)=>{if(this._logger.info(`ecsEnableErrorConversion in operationHandler is: ${this._ecsConfig&&this._ecsConfig.enableErrorConversion}`),t&&this._ecsConfig&&this._ecsConfig.enableErrorConversion&&("string"==typeof e||e instanceof Error)){const t=ns(e);return this._logger.info(`${i} Error converted from ${e} to ${je(t)}`),t}return e},this._logger=e.createChild("[Operation]"),this._chainedPromise=new ts(this._logger.createChild("[Chained]"))}resetOperationChain(e){this._chainedPromise.reset(e)}executeSync(e,t,i,n=be(),r,s){const a=this.getOperationInfoForLogging(n,t,i),o=ss();this._logger.info(`${a}API calledSync`);const l=this.callTelemetry.recordOperation(t,n,i,s);let c;try{this._setRecord(t),c=e(),l.recordSuccess(c,n),this.logSuccess(a,c,o)}catch(e){const t=this.convertToTransactionEndIfErrorOrString(e,r,a);l.recordFailure(t,n),this.logFailure(a,t,o)}return c}async executeChained(e,t,i,n=be(),r,s,a){return this.checkPendingOperationAndExecute(e,!0,t,i,n,r,s,a)}async execute(e,t,i,n=be(),r,s,a){return this.checkPendingOperationAndExecute(e,!1,t,i,n,r,s,a)}logOperation(e,t,...i){const n=i.length&&i.map((e=>this.stringifyForLogging(De(e))));this._logger.info(`[${e.substring(0,8)}][${t}]API called, ${n?`with args=${n}`:""}`)}rejectPendingOperations(e,t=be(),i){if(i){for(const e of Object.keys(this._deferredOperations))this.callTelemetry.maybeRecordOperationFailure(e,i,void 0,t);for(const e of Object.keys(this._deferredOperationsWithOperationId))for(const n of Object.keys(this._deferredOperationsWithOperationId[e]))this.callTelemetry.maybeRecordOperationFailure(e,i,n,t)}super.rejectPendingOperations(e,t)}maybeRejectOperations(e,t,i,n=be(),r){if(r)for(const t of e)this.callTelemetry.maybeRecordOperationFailure(t,r,void 0,n);super.maybeRejectOperations(e,t,i,n)}checkPendingOperationAndExecute(e,t,i,n,r=be(),s,a,o){const l=this.getOperationInfoForLogging(r,i,n);let c=null,d=null;return this.hasPendingOperationWithOperationId(i,n)||this.hasPendingOperation(i)?(this._logger.info(`${l}already pending, returning existing operation`),c=this.waitForOperation(i,n,r)):d=this.createPendingOperation(i,n,r,o),t?(this._logger.info(`${l}chained`),this._chainedPromise.chainPromise((()=>c||this.executeInternal(d,r,e,i,n,s,a,o)),i,r)):c||this.executeInternal(d,r,e,i,n,s,a,o)}_setRecord(e){this._record.hasOwnProperty(e)||(this._record[e]=0),this._record[e]+=1}getRecord(e){return this._record[e]}_recordTelemetryTimeoutAndPublish(e,t,i,n,r,s,a){const o=e||60;return window.setTimeout((()=>{if(!this._publishCallback)return void this._logger.warn(`${r} is marked to publish telemetry but no publish callback is defined.`);if(!this.hasPendingOperationWithOperationId(n,a)&&!this.hasPendingOperation(n))return;const e=new Error(`${r} execution did not complete before telemetry timeout of ${o}s.`);this.logTimeout(r,e,s),this.callTelemetry.maybeRecordOperationTimeout(n,e,a,i),this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)}),1e3*o)}_instantTelemetryPublish(e,t){this._publishCallback?(this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)):this._logger.warn(`${e} is marked to publish telemetry but no publish callback is defined.`)}parseInstantTelemetryParameters(e){let t,i=!1;return e&&(i=e.enableInstantTelemetry,t=e.telemetryTimeout),[i,t]}async executeInternal(e,t,i,n,r,s,a,o){const l=this.getOperationInfoForLogging(t,n,r);this._logger.info(`${l} executing operation...`);const c=ss(),d=this.callTelemetry.recordOperation(n,t,r,a),[u,h]=this.parseInstantTelemetryParameters(o);try{let e;this._setRecord(n),u&&(e=this._recordTelemetryTimeoutAndPublish(h,d,t,n,l,c,r)),o?.preconditionTags?.length&&this._preconditionFunction&&this._preconditionFunction(n,o.preconditionTags);const s=await i();e&&clearTimeout(e),this.callTelemetry.maybeRecordOperationSuccess(n,s,r),this.logSuccess(l,s,c),this.maybeResolveOperation(n,s,r,t)}catch(e){const i=this.convertToTransactionEndIfErrorOrString(e,s,l);this.callTelemetry.maybeRecordOperationFailure(n,function(e){return function(e){return!!e?.terminatedReasonCode}(e)?{code:e.terminatedReasonCode,subCode:e.terminatedReasonSubCode,phrase:e.errorMessage}:e}(i),r),this.logFailure(l,i,c),this.maybeRejectOperation(n,i,r,t)}return u&&this._instantTelemetryPublish(l,d),e}getEcsConfig(){return this._ecsConfig}},os=487,ls=603,cs=480,ds=403,us=412,hs=0,gs=302,ps=400,ms=404,fs=406,vs=408,Ss=409,ys=410,Cs=413,Ts=450,Es=451,bs=452,_s=470,Is=481,ws=488,As=490,Ps=491,Rs=495,Ms=496,Ds=497,ks=498,Os=500,Ns=580,Ls=3109,xs={[hs]:1,[os]:12,[ls]:10,[cs]:2,[vs]:6,[Ts]:30,[gs]:75,[ms]:24,[Is]:46,[fs]:5,[ps]:5,[ys]:4,[Cs]:59,[Ns]:4,[As]:3,[Ms]:31,[ks]:25,[Es]:27,[bs]:28,[Rs]:29,[Os]:7,[Ss]:7,[Ps]:7,[_s]:7,[ws]:26,[Ds]:32,[ds]:8,[us]:65},Fs={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},Us={500:39,403:41,404:42,480:40},Bs={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},Vs={SHARED_LINE_CALL_RECORD:121,SHARED_LINE_V2_CALL_RECORD:123,MEETING_STARTED_NOTIFICATION:128},Hs={LOG_UPLOAD_EVENT:120},$s="CallEndReasonLocalUserInitiated",js="CallEndReasonRedirected",Gs=(e=>(e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.CallStart="CallStart",e.WaitForAnswer="WaitForAnswer",e.WaitForConnect="WaitForConnect",e.Accept="Accept",e))(Gs||{}),qs=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.UpdateMediaModalities="UpdateMediaModalities",e.CreateOffer="CreateOffer",e.CreateAnswer="CreateAnswer",e.ProcessAnswer="ProcessAnswer",e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.MuteUnmute="MuteUnmute",e.MuteUnmuteSpeakers="MuteUnmuteSpeakers",e.StartVideoSafe="StartVideoSafe",e.CompleteNegotiation="CompleteNegotiation",e.MuteInput="MuteInput",e.MuteOutput="MuteOutput",e.UnmuteInput="UnmuteInput",e.UnmuteOutput="UnmuteOutput",e.evaluateEndpointStatesForAccept="evaluateEndpointStatesForAccept",e.handleEndpointStatesForAccept="handleEndpointStatesForAccept",e))(qs||{}),zs=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.ProcessOffer="ProcessOffer",e.ProcessOfferedModalities="ProcessOfferedModalities",e.TrySendingProvisionalAnswer="TrySendingProvisionalAnswer",e))(zs||{}),Ws=Z,Ks=p(Z),Js=p(Z),Ys=p(ce()),Qs="Success",Zs="ExpectedError",Xs="UnexpectedClientError",ea={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:[Xs]},CALL_END_TOKEN_TIMEOUT_ERROR:{code:499,subCode:3119,phrase:"CallEndReasonTokenFetchTimeout",resultCategories:[Xs]},CALL_END_UNSUPPORTED_TOKEN_ERROR:{code:499,subCode:3126,phrase:"CallEndReasonUnsupportedTokenError",resultCategories:[Xs]},CALL_END_TOKEN_ERROR:{code:499,subCode:3127,phrase:"CallEndReasonTokenFetchError",resultCategories:[Xs]},CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED:{code:499,subCode:3128,phrase:"CallEndReasonTokenTimeoutInterActvityRequired",resultCategories:[Xs]},CALL_END_LOCAL_HTTP_STACK_ERROR:{code:496,subCode:4520,phrase:"LocalHTTPStackError",resultCategories:[Xs]},CALL_END_UNKNOWN_ERROR:{code:497,subCode:3121,phrase:"CallEndReasonUnknownError",resultCategories:[Xs]},CALL_END_NETWORK_ERROR:{code:490,subCode:4502,phrase:"CallEndReasonNetworkError",resultCategories:[Xs]},CALL_END_DNS_HOST_NAME_RESOLVE_ERROR:{code:490,subCode:4522,phrase:"CallEndReasonDnsHostNameResolveError",resultCategories:[Xs]},CALL_END_LOCAL_DECLINE:{code:486,subCode:4508,phrase:"LocalDecline",resultCategories:[Qs]},RESOURCE_NOT_FOUND_ERROR:{code:404,subCode:404,phrase:"ResourceNotFound",resultCategories:[Zs]},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:[Qs]},VALIDATION:{VALIDATION_FAILED:6e3,NULL_OR_EMPTY:6001}},ta={REQUEST_TIMEOUT:{status:ea.HTTP_STATUS_CODES.TIMEOUT,statusText:"Request timed out",readyState:0,response:ea.HTTP_STACK_ERROR.REQUEST_TIMEOUT},ATTEMPT_TIMEOUT:{status:ea.HTTP_STATUS_CODES.TIMEOUT,statusText:"Attempt timed out",readyState:0,response:ea.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT},REQUEST_ABORTED:{status:ea.HTTP_STATUS_CODES.ABORTED,statusText:"Request Aborted",readyState:0,response:ea.HTTP_STACK_ERROR.REQUEST_ABORTED},ATTEMPT_ABORTED:{status:ea.HTTP_STATUS_CODES.ABORTED,statusText:"Attempt Aborted",readyState:0,response:ea.HTTP_STACK_ERROR.ATTEMPT_ABORTED}},ia={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/"},na={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/"},ra={...ia,...na},sa="callNotification",aa="mediaAnswer",oa="mediaAcknowledgement",la="callAcceptance",ca="callEnd",da="callProgress",ua="callAcceptanceAcknowledgement",ha="mediaNegotiation",ga="mediaNegotiationFailure",pa="balanceUpdate",ma="retargetCompleted",fa="callTransfer",va="transferCompletion",Sa="transferAcceptance",ya="holdCompletion",Ca="resumeCompletion",Ta="updateMeetingLiveStateResponse",Ea="updateMeetingGroupsResponse",ba="setMeetingLayoutResponse",_a="updateMeetingStatesResponse",Ia="monitorCompletion",wa=ea,Aa=p(Z),Pa=class e{constructor(e){this.headers={},e&&Object.keys(e).forEach((t=>{this.headers[this.getLowerCaseName(t)]=e[t]}))}isEmpty(){return Aa.isEmpty(this.headers)}set(e,t){this.headers[this.getLowerCaseName(e)]=t}get(t,i){return i?e.getHeaderValue(this.headers,t)||i:e.getHeaderValue(this.headers,t)}delete(e){delete this.headers[e],delete this.headers[e.toLowerCase()]}hasOwnPropertyCaseInsensitive(e){return Object.keys(this.headers).filter((function(t){return t.toUpperCase()===e.toUpperCase()})).length>0}getAll(){return this.headers}getLowerCaseName(t){return e.useLowerCaseHeaders?t.toLowerCase():t}static getHeaderValue(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}};function Ra(e,t,i=Na()){return Fa(t,"trailingPath cannot be null"),Ua(e,"signalingSession cannot be null"),Ua(e.baseMessagingChannelUrl,"messaging channel url is not set"),`${e.baseMessagingChannelUrl}${wa.URL_BASE.CALLAGENT}/${e.sessionId}/${i}${t}`}function Ma(e){let t=1;return e.callingServiceSupportsAADTokens&&(t|=4),e.callingServiceSupportsCAETokens&&(t|=8),t}function Da(e){const t=e.toLowerCase(),i=t.indexOf('token_types="');if(-1===i)return[];const n=t.indexOf('"',i+13);if(-1===n)return[];const r=t.substring(i+13,n).trim();return""===r?[]:r.split(" ")}function ka(e){return!!e.match(/^8:/)}function Oa(e){return e.replace(/^\d+:/,"")}function Na(){return La().substr(0,8)}function La(){const e="0123456789abcdef";let t="",i=0,n=0;for(;n<36;){const r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[n];switch(i=n%8==0?4294967295*Math.random()|0:i>>4,r){case"x":t+=e[15&i];break;case"y":t+=e[3&i|8];break;case"4":case"-":t+=r}n++}return t}function xa(e,t){e||Va("Assert failed"+(void 0!==t?`:${t}`:""))}function Fa(e,t){(!e||e instanceof String&&""===e||e instanceof Array&&0===e.length)&&Va("AssertNotNullOrEmpty failed. "+(void 0!==t?`: ${t}`:""))}function Ua(e,t){e||Va("AssertNotNull failed. "+(void 0!==t?`: ${t}`:""))}function Ba(e){Fa(e,"callEndReason cannot be null or empty"),(void 0===e.code||void 0===e.subCode||void 0===e.phrase||e.code<0||e.subCode<0||" "===e.phrase)&&Va(`callEndReason must specify code, subCode and phrase. Invalid reason : ${je(e)}`)}function Va(e){throw{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.MISC_ERROR,phrase:e,resultCategories:[Zs]}}function Ha(e){Ua(e,"MediaTypes passed cannot be null");const t=[],i=wa.MEDIA_TYPES;for(const n of Object.keys(i))Ga(e,i[n])&&t.push(i[n]);return t}function $a(e,t){const i={};for(const n of Object.values(t)){const t=n.split("/");i[t[t.length-2]]=Ra(e,n)}return i}function ja(e,t){return e.length>=t.length&&e.indexOf(t,e.length-t.length)>-1}function Ga(e,t){const i=t.toString().toLowerCase();return e.map((e=>e.toString().toLowerCase())).indexOf(i)>-1}function qa(e,t,i){return!e.hasOwnProperty(t)&&(e[t]=i,!0)}function za(e,t){return!!e.hasOwnProperty(t)&&(delete e[t],!0)}function Wa(e){let t=null;try{return t=JSON.parse(e),"object"==typeof t?t:null}catch(e){return null}}function Ka(e,t){if(!e)return{telemetryEndSubCode:wa.CALL_END_CODE.UNKNOWN_ERROR,error:wa.CALL_END_UNKNOWN_ERROR};let i;if("object"==typeof e.response)i=e.response;else try{i=JSON.parse(e.response)}catch(e){}if(e.skypeTokenError)return{telemetryEndSubCode:wa.CALL_END_CODE.SKYPE_TOKEN_ERROR,error:wa.CALL_END_SKYPE_TOKEN_ERROR};if(e.tokenTimeoutError&&!e.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:wa.CALL_END_TOKEN_TIMEOUT_ERROR};if(e.tokenError){const t=e.tokenErrorSubCode?{code:wa.CALL_END_TOKEN_ERROR.code,subCode:e.tokenErrorSubCode,phrase:wa.CALL_END_TOKEN_ERROR.phrase,resultCategories:wa.CALL_END_TOKEN_ERROR.resultCategories}:wa.CALL_END_TOKEN_ERROR;return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:t}}if(e.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:wa.CALL_END_CODE.HTTP_OTHER_ERROR,error:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED};if(i&&(i.operationFailure||i.broadcastOperationFailure)){const e=i.operationFailure||i.broadcastOperationFailure;return{telemetryEndSubCode:e.code,error:e}}return i&&"net::err_name_not_resolved"===i._error?.toLowerCase()?{telemetryEndSubCode:wa.CALL_END_CODE.NETWORK_ERROR,error:wa.CALL_END_DNS_HOST_NAME_RESOLVE_ERROR}:i?.code?{telemetryEndSubCode:i.code,error:i}:isNaN(e.status)||e.status!==wa.CALL_END_CODE.NOT_FOUND?!isNaN(e.status)&&e.status?{telemetryEndSubCode:e.status,error:{code:e.status,subCode:isNaN(e.response)?0:e.response,phrase:e.statusText,resultCategories:[Xs]}}:!isNaN(e.response)&&e.response?{telemetryEndSubCode:0,error:{code:0,subCode:e.response,phrase:e.statusText,resultCategories:[Xs]}}:{telemetryEndSubCode:wa.CALL_END_CODE.NETWORK_ERROR,error:wa.CALL_END_NETWORK_ERROR}:{telemetryEndSubCode:wa.CALL_END_CODE.NOT_FOUND,error:wa.RESOURCE_NOT_FOUND_ERROR}}function Ja(e,t){if(e&&!e.isEmpty()&&t){const i=e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID),n=e.get(wa.HEADERS.MESSAGE_ID);if(n&&Ga(t,n)||i&&Ga(t,i))return!0;t.length>9&&t.shift(),t.push(i||n)}return!1}function Ya(e){const t="unknown";return e.headers?e.headers.get(wa.HEADERS.ORIGINAL_MESSAGE_ID,t):t}function Qa(e){try{return e.headers.get(wa.HEADERS.ORIGINAL_MESSAGE_ID).replace("-","").substr(0,8)}catch(e){return Na()}}function Za(e){return e&&e.hasOwnPropertyCaseInsensitive(wa.HEADERS.CONTENT_ENCODING)}function Xa(e){return e&&wa.KNOWN_PAYLOAD_ENCODINGS.hasOwnProperty(e.get(wa.HEADERS.CONTENT_ENCODING).toUpperCase())}function eo(e){const t=atob(e);return Ys.inflate(t,{to:"string"})}function to(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)}}}function io(e){let t=!1;try{if(t=e&&2===e.state(),navigator.onLine&&t)return 3;if(!navigator.onLine&&t)return 2;if(navigator.onLine&&!t)return 1}catch{}return 0}function no(e){return[wa.HTTP_STATUS_CODES.UNKNOWN,wa.HTTP_STATUS_CODES.UNAUTHORIZED,wa.HTTP_STATUS_CODES.NETWORK_ERROR,wa.HTTP_STATUS_CODES.OFFLINE,wa.HTTP_STATUS_CODES.TIMEOUT,wa.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,wa.HTTP_STATUS_CODES.BAD_GATEWAY,wa.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE,wa.HTTP_STATUS_CODES.GATEWAY_TIMEOUT].indexOf(e)>=0}function ro(e,t){switch(e){case wa.HEADERS.CAE_KEYWORD.toLowerCase():return 8;case wa.HEADERS.AAD_KEYWORD.toLowerCase():return 4;case wa.HEADERS.SKYPE_KEYWORD.toLowerCase():return 1;default:return t?.info("unexpected: unrecognized token type ${tokenType}"),null}}function so(e){switch(e){case 0:return"GET";case 1:return"POST";case 2:return"PUT";case 3:return"DELETE"}}function ao(e,t,i,n,r=!1,s,a){a?.createChild("[utils.ts]");const o={verb:so(i),path:n.url},l=JSON.stringify(o),c=function(e){let t={};if(e){const i=Pa.getHeaderValue(e,wa.HEADERS.AUTHENTICATE);i&&(t={authenticationHeaders:[i]})}return t}(s),d=function(e,t,i,n,r){if(!t)return 1;const{callingServiceSupportsAADTokens:s,callingServiceSupportsCAETokens:a,supportMissingTokenTypesInResponse:o,useSkypeTokenWhenNoAuthenticateHeader:l}=e,c=r?.authenticationHeaders;n?.info(`[getAuthHeadersTokenTypes] UnauthorizedResponse=${i} and authHeaders=${c}`);let d=null;if(!c&&i)l?(n?.info("[getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),d=1):(n?.info("[getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),d=Ma(e));else if(c||i){if(c&&i)for(const t of c){const i=Da(t);if(o&&0===i.length)n?.info("[getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),d=Ma(e);else for(const e of i){const t=ro(e.toLowerCase(),n);a&&8===t&&(d|=8),s&&4===t&&(d|=4),1===t&&(d|=1)}}}else n?.info("[getAuthHeadersTokenTypes] first time requesting token, request client supported token types"),d=Ma(e);return d}(e,t,r,a,c);return a?.info(`[getTokenMetadata] return token type=${d}, factoJson=${l}, headers=${c?.authenticationHeaders}`),{tokenType:d,factorsJson:l,requestMetadataJson:c,isUnauthorized:r}}function oo(){return Math.floor(Date.now()/1e3)}function lo(e){return 1e3*e}function co(e){switch(e){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 uo(e){switch(e){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 ho(e){switch(e){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 go(e){let t={};return e.additionalData&&e.customHeaderContext?t="object"==typeof e.additionalData?{...e.additionalData,customContext:e.customHeaderContext}:{additionalData:e.additionalData,customContext:e.customHeaderContext}:!e.additionalData&&e.customHeaderContext?t={customContext:e.customHeaderContext}:e.additionalData&&!e.customHeaderContext&&(t=e.additionalData),t}function po(e){if(!e)return;let t="unknown";return"substrate"===e&&(t="substrate"),t}var mo=class e{static isInLobby(e,t){for(const i of e)if(i.endpointId===t&&i.isLobby)return!0;return!1}static isParticipantServerMuted(e){for(const t of e)if(t.mediaStreams&&!t.mappedTo)for(const e of t.mediaStreams)if("audio"===e.type&&!0===e.serverMuted)return!0;return!1}static fromWireParticipant(t){return Ua(t,"invalid wireParticipant"),Fa(t.id,"participant must have valid Id"),new e({id:t.id,displayName:t.displayName,languageId:t.languageId,acceptedBy:t.acceptedBy})}static getPluginlessStateTypeFromWire(e){return uo(e)}static findOrCreateTypeState(e,t){let i=t.typeStates.findIndex((t=>t.type===e));if(-1===i){const n={participantStates:[],type:e};t.typeStates.push(n),i=t.typeStates.length-1}return i}static processPublishedStates(e,t){const i={typeStates:[]},n=e;return Ks.forEach(n,(e=>{const n=this.findOrCreateTypeState(this.getPluginlessStateTypeFromWire(e.stateType),i),r={id:t,publishedState:{content:e.content,stateId:e.stateId,typeRank:e.typeRank}};i.typeStates[n].participantStates.push(r)})),i}static fromRosterEndpoints(e){let t=[],i=!1,n=!1,r=!1,s=!1;return t=Object.keys(e).map((t=>{let a,o,l,c=[],d=!1,u=0;if(e[t].call&&(i=!0,c=e[t].call.mediaStreams||null,u=e[t].call.serverMuteVersion||0,o=e[t].call.appliedInteractivityLevel||"unknown",l=e[t].call.negotiationTag),e[t].lobby&&(d=!0,n=!0,c=e[t].lobby.mediaStreams||null),e[t].broadcast?.sessionInformation&&(a=e[t].broadcast.sessionInformation.role||null),e[t].mappedParticipant&&(r=!0,c=e[t].mappedParticipant.mediaStreams||null),!e[t].capabilities&&e[t].endpointCapabilities){const i=e[t].endpointCapabilities;e[t].capabilities={implicitCallback:16&i?"enabled":"disabled",cloudAudioVideoConference:1&i?"enabled":"disabled",cloudScreenSharing:2&i?"enabled":"disabled",hostlessConference:4&i?"enabled":"disabled",autoJoinOnConflict:32&i?"enabled":"disabled",serverMuteUnmute:64&i?"enabled":"disabled",supportsCompressedServicePayload:128&i?"enabled":"disabled",cloudMerge:8&i?"enabled":"disabled"}}return s=s||!!e[t].streamLobby||!!e[t].stream,{endpointId:t,participantId:e[t].participantId||null,clientVersion:e[t].clientVersion||null,endpointMetadata:e[t].endpointMetadata||null,originalId:e[t].originalId||null,contentSharing:e[t].contentSharing||null,capabilities:e[t].capabilities||null,endpointType:e[t].endpointType||"default",deviceType:e[t].deviceType||void 0,clientEndpointCapabilities:e[t].clientEndpointCapabilities||void 0,mediaStreams:c,serverMuteVersion:u,broadcastMeetingRole:a,isLobby:d,endpointState:e[t].endpointState||null,publishedStates:e[t].publishedStates||null,callLinks:e[t].callLinks||null,appliedInteractivityLevel:o||"unknown",mappedTo:e[t].mappedTo||null,meetingGroupDetails:e[t].meetingGroupDetails,streamInformation:e[t].streamInformation,propertyBag:e[t].propertyBag,streamLobby:e[t].streamLobby,stream:e[t].stream,endpointMeetingRoles:e[t].endpointMeetingRoles,negotiationTag:l}})),{endpointDetails:t,participantHasCallModality:i,participantIsInLobby:n,participantHasMappedEndpoint:r,participantHasStreamEndpoint:s}}static fromRoster(t,i=!1){Ua(t,`invalid rosterParticipant ${JSON.stringify(t)}`),Fa(t.details.id,"participant must have valid Id");const n=t.endpoints||{},r=this.fromRosterEndpoints(n),s=r.endpointDetails,a=r.participantHasCallModality,o=r.participantHasMappedEndpoint,l=r.participantHasStreamEndpoint;let c=r.participantIsInLobby;return a||c||o||i||l?(a&&(c=!1),new e({id:t.details.id,displayName:t.details.displayName,otpIdentity:t.details.otpIdentity,version:t.version||0,propertyBag:t.details.propertyBag||null,languageId:t.details.languageId,role:t.role||"",tenantId:t.details.tenantId||"",endpointDetails:s||[],acceptedBy:t.acceptedBy||"",isLobby:c,meetingRole:t.meetingRole,advancedMeetingRole:t.advancedMeetingRole,meetingRoles:t.meetingRoles,participantType:t.details.participantType,publishedStates:t.publishedStates||null,isIdentityMasked:t.details.isIdentityMasked,nonMaskedId:t.details.nonMaskedId||"",nonMaskedObjectId:t.details.nonMaskedObjectId||"",nonMaskedDisplayName:t.details.nonMaskedDisplayName||"",maskedIdSeqNumber:t.details.maskedIdSeqNumber||0,maskedId:t.details.maskedId||"",joinAsStreamingUser:t.joinAsStreamingUser,enableCaptcha:t.enableCaptcha})):null}static fromRosterSearchResults(e){Ua(e,`invalid rosterParticipant ${JSON.stringify(e)}`),Fa(e.details.id,"participant must have valid Id");const t=e.endpoints,{endpointDetails:i,participantHasCallModality:n,participantIsInLobby:r,participantHasMappedEndpoint:s,participantHasStreamEndpoint:a}=this.fromRosterEndpoints(t);let o=0;return n||a?o=3:r?o=10:s&&(o=3),{id:e.details.id,state:o,tenantId:e.details.tenantId||"",displayName:e.details.displayName,role:e.role||"",meetingRole:e.meetingRole,advancedMeetingRole:e.advancedMeetingRole,meetingRoles:e.meetingRoles,participantType:e.details.participantType,isServerMuted:this.isParticipantServerMuted(i),publishedStates:this.processPublishedStates(e.publishedStates,e.details.id),endpoints:i||[],isIdentityMasked:e.details.isIdentityMasked,nonMaskedId:e.details.nonMaskedId||"",nonMaskedDisplayName:e.details.nonMaskedDisplayName||"",nonMaskedObjectId:e.details.nonMaskedObjectId||"",maskedIdSeqNumber:e.details.maskedIdSeqNumber||0,maskedId:e.details.maskedId||"",joinAsStreamingUser:e.joinAsStreamingUser}}constructor(e){this.id=e.id,this.displayName=e.displayName||"",this.otpIdentity=e.otpIdentity,this.version=e.version,this.propertyBag=e.propertyBag,this.languageId=e.languageId||null,this.endpointDetails=e.endpointDetails||[],this.acceptedBy=e.acceptedBy,this.role=e.role,this.tenantId=e.tenantId,this.isLobby=e.isLobby,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.meetingRoles=e.meetingRoles,this.participantType=e.participantType,this.publishedStates=e.publishedStates,this.isIdentityMasked=e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,this.enableCaptcha=e.enableCaptcha}},fo="HandleMediaAcknowledgement",vo="HandleMediaAnswer",So="AddParticipant",yo="AddParticipantTimeout",Co="AddParticipantWithReplacesTimeout",To="AdmitFailure",Eo="RemoveParticipantTimeout",bo="HandleAddParticipantSuccess",_o="HandleRosterUpdateFail",Io="HandleCallAcceptanceFailed",wo="HandleCallEnd",Ao="TrouterUrlChanged",Po="TrouterUrlUpdateFailed",Ro="HandleContentSharingUpdate",Mo="HandleAddModalitySuccess",Do="HandleAddModalityFailure",ko="TransferCompletionFailed",Oo="TransferRequestReceived",No="DuplicateMessageIgnored",Lo="FailedToHandleMessage",xo="MessageMissingBody",Fo="HandlePstnBalanceUpdate",Uo="IgnoreOldRoster",Bo="TransferRequestSent",Vo="TransferRequestFailed",Ho="TransferCompleted",$o="WaitingForUpdateMeetingLiveStateCompletion",jo="WaitingForUpdateMeetingGroupsCompletion",Go="WaitingForSetMeetingLayoutCompletion",qo="UpdateParticipantsPropertiesResponseFailed",zo="WaitingForJoinMeetingGroupCompletion",Wo="WaitingForLeaveMeetingGroupCompletion",Ko="SendMessageCompletion",Jo="WaitingForUpdateMeetingStatesCompletion",Yo="UpdateMeetingStatesResponseFailure",Qo="WaitingForUpdateMonitorSessionCompletion",Zo={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}},Xo="Local",el="SkypeConcore",tl="skypecosi_concore_web_csa_conversation_callmodality",il="skypecosi_concore_web_csa_conversation_contentsharing",nl="skypecosi_concore_web_csa_conversation_httprequest",rl="skypecosi_concore_web_csa_conversation_token",sl="Direction",al="ContentSharingDirection",ol="ConnectedDurationInMsecs",ll="PreheatedCallSetupDurationInSeconds",cl="CallCancelationDurationInSeconds",dl="IsPreheated",ul="TimeToRingInMsecs",hl="CallTerminatingEnd",gl="NetworkRequestsPending",pl="NetworkRequestsCompleted",ml="LocalOperationsPerformed",fl="TrouterWaitOperations",vl="CallStartTime",Sl="CallEndTime",yl="IsGroupCall",Cl="IsHostLessCall",Tl="IsCastCall",El="IsHuddleGroupCall",bl="IsMeetupCall",_l="IsOnBehalfOfCall",Il="SdpInCallNotification",wl="Code",Al="SubCode",Pl="Phrase",Rl="ResultCategories",Ml="CauseId",Dl="ConflictingCallId",kl="ConversationServiceUrl",Ol="ContentSharingServiceUrl",Nl="MeetingInfo",Ll="JoinedFrom",xl="ResultValue",Fl="ResultDetail",Ul="ResultCauseId",Bl="LocalOfferAnswerGenerationTimestamps",Vl="SelfParticipantRole",Hl="Scenario",$l="Caller_Type",jl="Callee_Type",Gl="Call_Type",ql="Test_Context_Id",zl="Outgoing_Modalities",Wl="Incoming_Modalities",Kl="CallOfferredModalities",Jl="CallAnsweredModalities",Yl="VBSS_Operations",Ql="ChangingCorrelationId_NewId",Zl="ChangingCorrelationId_OldId",Xl="MessagingChannel",ec="EventTimestampBag",tc="RosterUpdatesBag",ic="NetworkRequestBag",nc="ClientInformation",rc="EcsEtag",sc="ApplicationType",ac="Ring",oc="TenantId",lc="UserHexCID",cc="AcsResourceId",dc="Region",uc="Partition",hc="CallEventCallEndClientSubCode",gc="CallEventCallEndClientPhrase",pc="MeetingCode",mc="MeetingJoinUrl",fc="BroadcastMeetingRole",vc="MeetingRole",Sc="AdvancedMeetingRole",yc="MeetingRoles",Cc="ParticipantType",Tc="DisplayName",Ec="ClientSupportsAudioOnlyWatermark",bc="ClientSupportsWatermark",_c="TargetApplicationType",Ic="IsReinviteless",wc="ClientType",Ac="ClientSupportsPreventScreenCapture",Pc="Trouter",Rc="Broker",Mc="JsCsaConfig",Dc="BrokerOutgoingEnabled",kc="BrokerIncomingEnabled",Oc="BrokerRequestBatchingEnabled",Nc="BrokerExclusivelyEnabled",Lc="SupportsCompressedPayload",xc="SyncTrouterResponse",Fc="serverMuteUnmute",Uc="handleMediaOfferFromPushNotification",Bc="handleNewOfferRequest",Vc="sendProgressFromCC",Hc="internalHttpDispatcher",$c="enableTokenCache",jc="enableTokenPrefetch",Gc="supportMediaRetargetWhileIncomingRenegotiation",qc="enableCallEstablishmentTimeoutsForStartJoinCall",zc="enableTokenCacheForGenericTokenAPI",Wc="enableLongOutgoing1To1SetupTimeoutForWeb",Kc="CorrelationId",Jc="SharedCorrelationId",Yc="SignalingSessionId",Qc="GroupId",Zc="ThreadId",Xc="TeamsMessageId",ed="TeamsMeetingInfo",td="EndpointId",id="ParticipantId",nd="ContentSharingSessionId",rd="ContentSharingCorrelationId",sd="Local",ad="Remote",od="Success",ld="Failure",cd="Incoming",dd="Outgoing",ud="caller",hd="callee",gd="join",pd="joinForRosterOnly",md="preheat",fd="Start",vd="Stop",Sd="Rejected",yd="RemoteStart",Cd="Timeout",Td="CallEnd",Ed="Started",bd="Ended",_d="Failed",Id="TokenTelemetry";function wd(e){e.cloudScreenSharingFlag="disabled"===e.cloudScreenSharingFlag?e.cloudScreenSharingFlag:"enabled",e.isWebRtcEnabled="undefined"==typeof RTCIceGatherer,e.shouldServiceSendNGCUpgradeMessages=Ad(e.shouldServiceSendNGCUpgradeMessages,!0),e.isGVCOutgoingEnabled=Ad(e.isGVCOutgoingEnabled,!0),e.supportsCompressedServicePayload=Ad(e.supportsCompressedServicePayload,!0),e.supportsSynchronousTrouterResponse=Ad(e.supportsSynchronousTrouterResponse,!0),e.supportsHostlessGroupCalls=Ad(e.supportsHostlessGroupCalls,!0),e.doHostlessCalling=Ad(e.doHostlessCalling,!1),e.brokerExclusively=Ad(e.brokerExclusively,!1),e.brokerEnabledOutgoing=Ad(e.brokerEnabledOutgoing,!0),e.brokerEnabledIncoming=Ad(e.brokerEnabledIncoming,!0),e.brokerRequestBatching=Ad(e.brokerRequestBatching,!0),e.handleMediaOfferFromPushNotification=Ad(e.handleMediaOfferFromPushNotification,!0),e.handleNewOfferRequest=Ad(e.handleNewOfferRequest,!1),e.autoJoinOnConflict=Ad(e.autoJoinOnConflict,!0),e.endConflictedCall=Ad(e.endConflictedCall,!1),e.autoResolveConflictedCall=Ad(e.autoResolveConflictedCall,!1),e.shouldServiceSendCallEventMessages=Ad(e.shouldServiceSendCallEventMessages,!1),e.forceTrouterReconnectOnNetworkOnline=Ad(e.forceTrouterReconnectOnNetworkOnline,!0),e.attemptHttpRequestWithCachedSkypetoken=Ad(e.attemptHttpRequestWithCachedSkypetoken,!0),e.useInternalHttpDispatcher=Ad(e.useInternalHttpDispatcher,!1),e.enableTokenCache=Ad(e.enableTokenCache,!1),e.enableTokenPrefetch=Ad(e.enableTokenPrefetch,!1),e.hedgeDelayMs=Ad(e.hedgeDelayMs,4e3),e.hedgeMaxParallelAttempts=Ad(e.hedgeMaxParallelAttempts,3),e.useInternalHttpDispatcher&&(e.httpRequestDispatcher=new st(e.logger)),e.enableQuickSendAcceptanceAck=Ad(e.enableQuickSendAcceptanceAck,!1),e.supportMediaRetargetWhileIncomingRenegotiation=Ad(e.supportMediaRetargetWhileIncomingRenegotiation,!1),e.callingServiceSupportsAADTokens=Ad(e.callingServiceSupportsAADTokens,!1),e.callingServiceSupportsCAETokens=Ad(e.callingServiceSupportsCAETokens,!1),e.aadTokenExpirationTimeInSeconds=Ad(e.aadTokenExpirationTimeInSeconds,3600),e.caeTokenExpirationTimeInSeconds=Ad(e.caeTokenExpirationTimeInSeconds,86400),e.disableTokenMigrationHeader=Ad(e.disableTokenMigrationHeader,!1),e.enablePublishTokenTelemetry=Ad(e.enablePublishTokenTelemetry,!1),e.forceClearExpiredTokens=Ad(e.forceClearExpiredTokens,!1),e.enableRefreshToken=Ad(e.enableRefreshToken,!0),e.refreshTimeBeforeTokenTimeoutInSeconds=Ad(e.refreshTimeBeforeTokenTimeoutInSeconds,30),e.enableCallEstablishmentTimeoutsForStartJoinCall=Ad(e.enableCallEstablishmentTimeoutsForStartJoinCall,!1),e.csaTimeoutConfiguration=function(e,t){return(t||e)&&{...t,...e}}(e.csaTimeoutConfiguration,{conversationKeepAliveTimeoutSec:2700,promotionUnmuteTimeoutSec:1e4}),e.reportPreviousErrorsForTimeout=Ad(e.reportPreviousErrorsForTimeout,!1),e.callingTokenLogicalUrl=Ad(e.callingTokenLogicalUrl,"https://calling.teams.microsoft.com"),e.enableAsyncDisablePreheat=Ad(e.enableAsyncDisablePreheat,!1),e.forceLowercaseHttpHeaders=Ad(e.forceLowercaseHttpHeaders,!1),e.enableResolveScreenSharingWhenNegotiationComplete=Ad(e.enableResolveScreenSharingWhenNegotiationComplete,!1),e.maxReinvitelessMediaForVideoForWeb=Ad(e.maxReinvitelessMediaForVideoForWeb,0),e.maxReinvitelessMediaForVBSSForWeb=Ad(e.maxReinvitelessMediaForVBSSForWeb,0),e.enableRefreshTokenRetry=Ad(e.enableRefreshTokenRetry,!0),e.enableRefreshTokenRetryInSeconds=Ad(e.enableRefreshTokenRetryInSeconds,60),e.enableConversationTypeUpdateOnCallEnd=Ad(e.enableConversationTypeUpdateOnCallEnd,!1),e.supportMissingTokenTypesInResponse=Ad(e.supportMissingTokenTypesInResponse,!0),e.useSkypeTokenWhenNoAuthenticateHeader=Ad(e.useSkypeTokenWhenNoAuthenticateHeader,!1),e.enableAutoPromotion=Ad(e.enableAutoPromotion,!1),e.enableBatchedSendMessageStatus=Ad(e.enableBatchedSendMessageStatus,!1),e.enableBatchedReceiveMessage=Ad(e.enableBatchedReceiveMessage,!1),e.enableAddParticipantEnhancements=Ad(e.enableAddParticipantEnhancements,!1),e.enableTokenCacheForGenericTokenAPI=Ad(e.enableTokenCacheForGenericTokenAPI,!1),e.disableRealTimeModeFromRoster=Ad(e.disableRealTimeModeFromRoster,!0),e.enableLongOutgoing1To1SetupTimeoutForWeb=Ad(e.enableLongOutgoing1To1SetupTimeoutForWeb,!1),e.checkAttendeeRoleInCreateContentSharing=Ad(e.checkAttendeeRoleInCreateContentSharing,!0),e.enableSpecificErrorCodesForCallEnd=Ad(e.enableSpecificErrorCodesForCallEnd,!1),e.enableSplitConversationEndUrl=Ad(e.enableSplitConversationEndUrl,!1),e.enableFetchRequestWithKeepAlive=Ad(e.enableFetchRequestWithKeepAlive,!1),e.enableFetchApi=Ad(e.enableFetchApi,!1),e.enableFetchApiForBeacon=Ad(e.enableFetchApiForBeacon,!1)}function Ad(e,t){return null==e?t:e}var Pd=class{constructor(){this.skypeTokenContext={},this.aadTokenContext={},this.caeTokenContext={}}getTokenContext(e){return 4===e?this.aadTokenContext:8===e?this.caeTokenContext:1===e?this.skypeTokenContext:void 0}getTokenExpiry(e,t){return 4===e?this.aadTokenContext?.expiryTime:8===e?this.caeTokenContext?.expiryTime:1===e?this.skypeTokenContext?.expiryTime:(t?.info("[getTokenExpiry] unrecognized token type, return Number.MAX_VALUE"),Number.MAX_VALUE)}getToken(e,t,i,n){return 8&e&&this.caeTokenContext?.token&&this.caeTokenContext.token!==n?{token:this.caeTokenContext.token,tokenType:8}:4&e&&this.aadTokenContext?.token&&this.aadTokenContext.token!==n?{token:this.aadTokenContext.token,tokenType:4}:1&e&&this.skypeTokenContext?.token&&this.skypeTokenContext.token!==n?{token:this.skypeTokenContext.token,tokenType:1}:(i?.info(`[getToken] no cached token found of token type: ${e}`),null)}setToken(e,t,i,n){switch(e){case 4:this.aadTokenContext.factorsJson=i,this.aadTokenContext.tokenType=e,this.aadTokenContext.token=t,this.aadTokenContext.expiryTime=n;break;case 1:this.skypeTokenContext.factorsJson=i,this.skypeTokenContext.tokenType=e,this.skypeTokenContext.token=t,this.skypeTokenContext.expiryTime=n;break;case 8:this.caeTokenContext.factorsJson=i,this.caeTokenContext.tokenType=e,this.caeTokenContext.token=t,this.caeTokenContext.expiryTime=n;break;default:throw new Error(`Invalid tokenType ${e}`)}}clearExpiredTokens(e){const t=Math.round(Date.now()/1e3);this.caeTokenContext?.expiryTime<=t&&(this.resetToken(8),e?.info("[cacheTokenManager] reset expired cae token")),this.aadTokenContext?.expiryTime<=t&&(this.resetToken(4),e?.info("[cacheTokenManager] reset expired aad token")),this.skypeTokenContext?.expiryTime<=t&&(this.resetToken(1),e?.info("[cacheTokenManager] reset expired skype token"))}resetToken(e){8===e?this.caeTokenContext={}:4===e?this.aadTokenContext={}:1===e&&(this.skypeTokenContext={})}},Rd=class{constructor(e){this.timers={},this.startTimer=(e,t,i,n)=>{this.logger.info(`startTimer called for : ${e} with timeoutInSeconds : ${i}s`);const r=window.setTimeout(t,1e3*i),s=n?`${e}${n}`:e;this.timers[s]=r},this.stopTimer=(e,t)=>{this.logger.info(`stopTimer called for : ${e}`);const i=t?`${e}${t}`:e;this.timers.hasOwnProperty(i)&&(clearTimeout(this.timers[i]),delete this.timers[i])},this.dispose=()=>{this.logger.info("timeoutManager :: dispose"),Object.keys(this.timers).forEach((e=>{this.stopTimer(e)}))},this.logger=e}},Md=class{constructor(e,t,i,n){this.tokenProvider=t,this.tokenCachingEnabled=!1,this.enableTokenCacheForGenericTokenAPI=!1,this.cachedToken="",this.lastTokenType=1,this.lastToken="",this.clientSupportsGenericTokenAPI=!1,this.stopTimerFlag=!1,this.tokensPromiseMap={},this.logger=e.createChild("TokenManager"),i&&this.updateTokenSettings(i),this.cacheTimers=new Rd(e),this.cacheTokenManager=new Pd,this.telemetryManager=n,this.nextRefreshTimePointInSeconds=Number.MAX_VALUE}deletePromisesByTriggeredByRefresh(e,t){if(this.tokensPromiseMap[e]){const i=this.tokensPromiseMap[e];for(let n=i.length-1;n>=0;n--)i[n]?.tokenRequestOptions.triggeredByRefresh===t&&this.tokensPromiseMap[e].splice(n,1)}}startTokenRefreshTimer(e){const t="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=${e}`);const i=oo(),n=function(e){return e/1e3}(e),r=i+n;this.nextRefreshTimePointInSeconds===Number.MAX_VALUE||this.nextRefreshTimePointInSeconds<i||r<this.nextRefreshTimePointInSeconds?(this.logger.info("[startTokenRefreshTimer] cancelling current refresh timer to create new one with shorter time"),this.cacheTimers.stopTimer(t),this.nextRefreshTimePointInSeconds=r,this.logger.info(`[startTokenRefreshTimer] start new timer with timeout=${n} at time=${i}`),this.cacheTimers.startTimer(t,(()=>{this.nextRefreshTimePointInSeconds=Number.MAX_VALUE,this.refreshToken()}),n)):this.logger.info("[startTokenRefreshTimer] no need to set a new refresh timer")}async refreshTokenWithContext(e){const t={triggeredByRefresh:!0},i=La(),n={causeId:i},r=Date.now();let s,a,o,l=2;this.logger.info(`[${i}][refreshTokenWithContext] refreshing token tokenType=${e.tokenType} factorsJson=${e.factorsJson}`);let c=null;try{const t=this.onTokenRequired({factorsJson:e.factorsJson,tokenType:e.tokenType,requestMetadataJson:n,invalidToken:void 0,isUnauthorized:void 0,triggeredByRefresh:!0}),r=await this.timeoutPromiseRace(t,this.enableRefreshTokenRetryInSeconds,"ActiveRefresh Token Timeout");s=Date.now(),o=r?.causeId,c=r?.tokenType,this.lastTokenType=c,this.lastToken=r.token,l=1,this.logger.info(`[${i}][refreshTokenWithContext] refresh token success for factorsJson ${e.factorsJson} and tokenType ${e.tokenType}`)}catch(t){a=t,o=a?.causeId,t?.timeOut?(this.logger.info(`[${i}][refreshTokenWithContext] refresh token timeout, UI did not respond with token in time ${je(t)}`),l=5):(this.logger.info(`[${i}][refreshTokenWithContext] failed to refresh token, UI did not respond with token ${je(t)}`),l=2),s=Date.now(),this.deletePromisesByTriggeredByRefresh(e.factorsJson,!0)}finally{t&&(t.requestCauseId=i,t.responseCauseId=o,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=e.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=s,t.tokenRequestStatus=l,t.requestTokenType=e.tokenType,t.foundInCache=!1,t.responseTokenType=c,t.errorCode=a?.errorCode,t.errorSubCode=a?.errorSubCode,this.sendTokenTelemetry(t))}}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 e=this.cacheTokenManager.getTokenContext(4),t=this.cacheTokenManager.getTokenContext(8),i=this.cacheTokenManager.getTokenContext(1);if(!e&&!t&&!i)return void this.logger.info("[refreshToken] no cached tokens available to refresh");const n=oo()+this.refreshTimeBeforeTokenTimeoutInSeconds;let r=Number.MAX_VALUE,s=!1;if(e)if(e.expiryTime>n){const t=e?.expiryTime-n;t<r&&(r=t)}else e.expiryTime<=n&&(this.refreshTokenWithContext(e),s=!0);if(t)if(t.expiryTime>n){const e=t?.expiryTime-n;e<r&&(r=e)}else t.expiryTime<=n&&(this.refreshTokenWithContext(t),s=!0);if(i)if(i.expiryTime>n){const e=i?.expiryTime-n;e<r&&(r=e)}else i.expiryTime<=n&&(this.refreshTokenWithContext(i),s=!0);s&&this.enableRefreshTokenRetry&&this.enableRefreshTokenRetryInSeconds>0&&this.enableRefreshTokenRetryInSeconds<r&&(r=this.enableRefreshTokenRetryInSeconds),r>=0&&r!==Number.MAX_VALUE&&this.startTokenRefreshTimer(lo(r))}async getTokenWithTokenType(e,t=!1,i,n){this.logger.info(`[${e}][getTokenWithTokenType] call with factorJson=${i?.factorsJson} and request tokenType ${i?.tokenType}`);const{factorsJson:r,requestMetadataJson:s,invalidToken:a,isUnauthorized:o}=i||{},l=Date.now(),c=i?.tokenType;let d,u,h,g=2,p=null;this.clearExpiredTokens(),this.startTokenRefreshTimer(1);try{if(t)this.invalidateCachedTokenWithTokenType(c,a,r);else if(this.enableTokenCacheForGenericTokenAPI){const t=this.cacheTokenManager.getToken(c,r,this.logger,a);if(t?.token)return this.logger.info(`[${e}][getTokenWithTokenType] returning cached token for factorsJson ${r} and request tokenType ${c}, response tokenType ${t.tokenType}`),g=3,d=Date.now(),p=t.tokenType,this.lastToken=t.token,this.lastTokenType=p,t}this.logger.info(`[${e}][getTokenWithTokenType] fetching new token for factorsJson ${r} and tokenType ${c}`);const i=s||{};i.causeId=e;const n=this.onTokenRequired({factorsJson:r,tokenType:c,requestMetadataJson:i,invalidToken:a,isUnauthorized:o,triggeredByRefresh:!1}),l=await this.timeoutPromiseRace(n,wa.TIMEOUT_VALUES_IN_SECONDS.TOKEN_REQUIRED_TIMEOUT,"Token not received from UI in time");return d=Date.now(),h=l?.causeId,p=l?.tokenType,this.lastToken=l?.token,this.lastTokenType=p,g=1,this.logger.info(`[${e}][getTokenWithTokenType] fetching new token success for factorsJson ${r} and tokenType ${c}`),l}catch(t){throw this.logger.info(`[${e}][getTokenWithTokenType] failed to fetch token ${je(t)}`),u=t,h=u?.causeId,u.timeOut&&(g=4),this.deletePromisesByTriggeredByRefresh(r,!1),t}finally{const t=!n?.tokenTelemetryData,r=t?{}:n?.tokenTelemetryData;r&&(r.requestCauseId=e,r.responseCauseId=h,r.supportTokenApi=this.clientSupportsGenericTokenAPI,r.requestTokenFactors=i?.factorsJson,r.tokenRequestTime=l,r.tokenResponseTime=d,r.tokenRequestStatus=g,r.requestTokenType=i?.tokenType,r.foundInCache=3===g,r.responseTokenType=p,r.timeToResponse=d?d-l:d,r.errorCode=u?.errorCode,r.errorSubCode=u?.errorSubCode),(!n||t&&!n.signalingSession)&&(this.logger?.info("[getTokenWithTokenType] TokenContext is not provided, sending token telemetry to Token table"),this.sendTokenTelemetry(r))}}async onTokenRequired(e){const{factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:s,triggeredByRefresh:a}=e;if(this.logger.info(`[onTokenRequired] factorsJson=${t} tokenType=${i}`),!i)return this.logger.info(`[onTokenRequired] factorsJson=${t} with no token type`),Promise.reject({errorCode:wa.HTTP_STATUS_CODES.UNAUTHORIZED,errorSubCode:0,causeId:n?.causeId});if(this.tokensPromiseMap[t]&&!a)for(const e of this.tokensPromiseMap[t])if(e.tokenRequestOptions.tokenType===i)return this.logger.info(`[onTokenRequired] factorsJson=${t} and tokenType ${i} has pending request`),e.defered.promise;this.tokensPromiseMap[t]||(this.tokensPromiseMap[t]=[]);const o=new Kt;return this.tokensPromiseMap[t].push({tokenRequestOptions:e,defered:o}),this.tokenCallback({factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:s}),o.promise}setTokenCaching(e,t){this.tokenCachingEnabled!==e&&(this.logger.info(`[authTokenManager]setTokenCaching=${e}`),this.tokenCachingEnabled=e)}setTokenCachingForGenericTokenAPI(e,t){this.enableTokenCacheForGenericTokenAPI!==e&&(this.logger.info(`[authTokenManager]setTokenCachingForGenericTokenAPI=${e}`),this.enableTokenCacheForGenericTokenAPI=e)}calculateTokenExpiry(e,t,i){const{factorsJson:n,tokenType:r}=t;let s=i-oo(),a=s,o=i;if(s&&s>0&&s>this.refreshTimeBeforeTokenTimeoutInSeconds){switch(r){case 4:s>this.aadTokenExpirationTimeInSeconds&&(s=this.aadTokenExpirationTimeInSeconds);break;case 8:s>this.caeTokenExpirationTimeInSeconds&&(s=this.caeTokenExpirationTimeInSeconds);break;default:s>3600&&(s=3600)}a=s-this.refreshTimeBeforeTokenTimeoutInSeconds,o=a+oo()}return this.logger.info(`[${e}][calculateTokenExpiry] calculate expiry to ${o} tokenType=${r} factorsJson=${n}`),o}addToCache(e,t,i,n){this.clearExpiredTokens(),this.cacheTokenManager.setToken(e,t,i,n)}clearExpiredTokens(){this.forceClearExpiredTokens&&this.cacheTokenManager.clearExpiredTokens(this.logger)}async getToken(e,t=!1,i,n){if(this.clientSupportsGenericTokenAPI){this.logger.info(`[${e}][getToken] callingTokenAPI is enabled so using new API to fetch it`);const{token:r}=await this.getTokenWithTokenType(e,t,i,n);return r}const r=Date.now();let s,a,o=2;try{if(t&&this.invalidateCachedToken(e),this.cachedToken&&this.tokenCachingEnabled)return this.logger.info(`[${e}][getToken] returning cached token`),o=3,this.lastTokenType=1,Promise.resolve(this.cachedToken);this.logger.info(`[${e}][getToken] fetching new token`);const i=await this.tokenProvider();return s=Date.now(),i?(this.tokenCachingEnabled&&(this.cachedToken=i),o=1,this.lastToken=i,this.lastTokenType=1,this.logger.info(`[${e}][getToken] fetching new token success`),i):(this.logger.info(`[${e}][getToken] received empty token`),Promise.reject("Received empty token"))}catch(t){throw this.logger.info(`[${e}][getToken] failed to fetch token=${je(t)}`),a=t,this.cachedToken="",t}finally{const t=n?.tokenTelemetryData;t&&(t.requestCauseId=e,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=i?.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=s,t.tokenRequestStatus=o,t.requestTokenType=i?.tokenType,t.foundInCache=3===o,t.responseTokenType=this.lastTokenType,t.timeToResponse=s?s-r:s,t.errorCode=a?.errorCode,t.errorSubCode=a?.errorSubCode)}}invalidateCachedToken(e){this.cachedToken&&(this.logger.info(`[${e}][invalidateCachedToken]`),this.cachedToken="")}invalidateCachedTokenWithTokenType(e,t,i){8===e&&this.cacheTokenManager.getToken(8,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(8)),4===e&&this.cacheTokenManager.getToken(4,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(4)),1===e&&this.cacheTokenManager.getToken(1,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(1))}getLastToken(e){return this.logger.info(`[${e}][getLastToken]`),this.lastToken}async timeoutPromiseRace(e,t,i){let n;const r=new Promise(((e,r)=>{n=window.setTimeout((()=>{r({phrase:i,timeOut:!0})}),lo(t))}));return Promise.race([e.then((e=>(clearTimeout(n),e))),r])}getLastTokenType(e){return this.logger.info(`[${e}][getLastTokenType] lastTokenType=${this.lastTokenType}`),this.lastTokenType}updateTokenSettings(e){const{clientSupportsGenericTokenAPI:t,aadTokenExpirationTimeInSeconds:i,caeTokenExpirationTimeInSeconds:n,refreshTimeBeforeTokenTimeoutInSeconds:r,enablePublishTokenTelemetry:s,enableRefreshToken:a,forceClearExpiredTokens:o,enableRefreshTokenRetry:l,enableRefreshTokenRetryInSeconds:c}=e;this.logger.info(`updateTokenSettings ${JSON.stringify(e)}`),this.clientSupportsGenericTokenAPI=t??this.clientSupportsGenericTokenAPI,this.aadTokenExpirationTimeInSeconds=i??this.aadTokenExpirationTimeInSeconds,this.caeTokenExpirationTimeInSeconds=n??this.caeTokenExpirationTimeInSeconds,this.refreshTimeBeforeTokenTimeoutInSeconds=r??this.refreshTimeBeforeTokenTimeoutInSeconds,this.enablePublishTokenTelemetry=s??this.enablePublishTokenTelemetry,this.forceClearExpiredTokens=o??this.forceClearExpiredTokens,this.enableRefreshToken=a??this.enableRefreshToken,this.enableRefreshTokenRetry=l??this.enableRefreshTokenRetry,this.enableRefreshTokenRetryInSeconds=c??this.enableRefreshTokenRetryInSeconds}updateToken(e,t,i,n,r){if(this.logger.info(`[${n}][updateToken] UI replies with a token with factorsJson=${e} updateMetadata=${JSON.stringify(t)} tokenExpirySecSinceEpoch?=${r}`),t.error){this.logger.info(`[${n}][updateToken] UI replies with error ${t.error} for factorsJson ${e}`);for(const i of this.tokensPromiseMap[e])i.tokenRequestOptions.requestMetadataJson.causeId===n&&i.defered.reject({phrase:t.error?.phrase,errorCode:t.error?.code,errorSubCode:t.error?.subCode,causeId:n});return}if(!i){this.logger.info(`[${n}][updateToken] received empty token`);for(const t of this.tokensPromiseMap[e])t.tokenRequestOptions.requestMetadataJson.causeId===n&&t.defered.reject({phrase:"Received empty token",causeId:n});return}if(r>oo()&&this.enableTokenCacheForGenericTokenAPI){this.logger.info(`[${n}][updateToken] caching Token with tokenType=${t.tokenType}`);const s={factorsJson:e,tokenType:t.tokenType,invalidToken:i};this.addToCache(t.tokenType,i,e,this.calculateTokenExpiry(n,s,r))}if(!this.tokensPromiseMap[e]){this.logger.warn(`[updateToken]: UI tries to update token with invalid factorsJson=${e}`);const i={responseCauseId:n,supportTokenApi:this.clientSupportsGenericTokenAPI,requestTokenFactors:e,tokenResponseTime:Date.now(),tokenRequestStatus:6,responseTokenType:t.tokenType};return void this.sendTokenTelemetry(i)}if(this.tokensPromiseMap[e]){const r=this.tokensPromiseMap[e];for(let s=r.length-1;s>=0;s--)(r[s]?.tokenRequestOptions.tokenType&t.tokenType)>0&&(r[s].defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),this.tokensPromiseMap[e].splice(s,1))}if(this.logger.info(`[${n}][updateToken] resolved and upateToken with factorsJson=${e} tokenType=${t.tokenType}`),0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e],4!==t.tokenType&&8!==t.tokenType&&1!==t.tokenType)return;if(Object.keys(this.tokensPromiseMap).length>0)for(const r of Object.values(this.tokensPromiseMap))for(let s=r.length-1;s>=0;s--){const a=r[s];a.tokenRequestOptions.factorsJson!==e&&(a.tokenRequestOptions.tokenType&t.tokenType)>0&&!a.tokenRequestOptions.isUnauthorized&&(a.defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),r.splice(s,1))}for(const e of Object.keys(this.tokensPromiseMap))0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e];const s=r-oo();this.startTokenRefreshTimer(s>=0?lo(s):0)}setTokenRequiredCallBack(e){this.tokenCallback=e}setDisableTimerFlag(e){this.logger.info(`[setDisableTimerFlag] set disableTimerFlag to ${e}`),this.stopTimerFlag=e}sendTokenTelemetry(e){if(!this.enablePublishTokenTelemetry)return;const t={};t[Id]=JSON.stringify(e),this.telemetryManager?(this.logger.info("[sendTokenTelemetry] sending token telemetry:",t),this.telemetryManager.sendEvent(rl,t)):this.logger.warn("[sendTokenTelemetry] telemetryManager is undefined, cannot send token telemetry")}dispose(){this.cacheTimers&&this.cacheTimers.dispose()}},Dd=class{constructor(e){this.piiScrubber=this.getPiiScrubber(e)}scrubParticipantsList(e){const t=[];return Array.isArray(e)&&e.forEach((e=>t.push(this.scrubMriOrOmit(e)))),t}scrubMriOrOmit(e){return"string"==typeof e?this.piiScrubber.mri(e):this.piiScrubber.omit(e)}getPiiScrubber(e){return e&&"function"==typeof e.omit&&"function"==typeof e.mri?e:{omit:()=>"<pii:omit/>",mri:()=>"<pii:mri/>"}}},kd=p(Z);function Od(e){switch(e){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 Nd(e){switch(e){case"audio":return 0;case"video":return 1;case"applicationsharing-video":case"xapplicationsharing-video":return 2;case"data":return 3;default:return}}function Ld(e,t){return e.endpoints?.endpointDetails.find((e=>e.participantId===t))}function xd(e,t){return e.participants.find((e=>function(e,t){return e.endpoints?.endpointDetails?.some((e=>e.participantId===t))??!1}(e,t)))}function Fd(e){return!!e?.meetingGroupDetails?.groups&&Object.keys(e.meetingGroupDetails.groups).some((e=>"stagingGroup"===e))}function Ud(e,t){let i=-1;try{if(e.endpoints)e:for(const n of e.endpoints.endpointDetails)if(void 0!==n?.mediaStreams){for(const e of n.mediaStreams)if(Nd(e.type)===t){i=e.sourceId;break e}}else i=Ur}catch(e){return-1}return i}function Bd(e,t,i){try{if(!e.endpoints)return;for(const n of e.endpoints.endpointDetails)if(n?.mediaStreams)for(const e of n.mediaStreams)if(i===e.sourceId&&Nd(e.type)===t)return n.participantId??null;return}catch(e){return}}function Vd(e){return"sendonly"===e.direction&&"applicationsharing-video"===e.label}function Hd(e){if(e.endpoints?.endpointDetails)return 1===e.endpoints.endpointDetails.length?e.endpoints.endpointDetails[0].participantId:e.endpoints.endpointDetails.find((e=>e?.mediaStreams?.some(Vd)))?.participantId}function $d(e){let t={};if(e.stateId)t.result=e.stateId;else if(e.results){const{results:i}=e;1===i.length&&i[0].stateId&&(t.result=i[0].stateId);const n={};e.results.forEach((e=>{const{result:i}=e,r=function(e){return e.participantId||e.participant&&e.participant.id}(e);(void 0===t.code||i.code>t.code)&&(t.code=i.code,t.subCode=i.subCode),n[r]=e})),t.result=JSON.stringify(n)}else e.result&&(t={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode,resultCategories:e.result.resultCategories},e.additionalDetail&&(t.result=e.additionalDetail));return t}var jd=class{constructor(e,t){this.broadcastContext=null,this.broadcastControllerUrl="",this.broadcastCallbackUrl="",this.broadcastState=null,this.setContext=(e=null)=>{this.logger.info("BroadcastSession :: set broadcast context",e),this.broadcastContext=e},this.getContext=()=>(this.logger.info("BroadcastSession :: get broadcast context",this.broadcastContext||null),this.broadcastContext||null),this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[Broadcast]"))}handleBroadcastStateChanged(e){const t=e.body;this.broadcastState=t;const i=Qa(e);this.signalingSession.telemetryHelper.recordIncomingEvent("BroadcastStateChanged",e),this.logger.info(`[${i}] broadcast state changed=${this.broadcastState}`),this.updateBroadcastMetadata(i)}updateBroadcastCallbackUrl(e){const t=Ra(this.signalingSession,ra.CONV_BROADCAST_UPDATE);this.broadcastCallbackUrl!==t&&(this.broadcastCallbackUrl=t,this.logger.info(`[${e}] broadcast callback url changed=${this.broadcastCallbackUrl}`),this.updateBroadcastMetadata(e))}handleBroadcastDetailsChanged(e,t){this.signalingSession.telemetryHelper.recordEvent("UpdateBroadcastDetails",{causeId:t}),e.activeModalities&&e.activeModalities.broadcast&&e.activeModalities.broadcast.controller!==this.broadcastControllerUrl&&(this.broadcastControllerUrl=e.activeModalities.broadcast.controller,this.broadcastAdditionalData=e.activeModalities.broadcast,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.signalingSessionCallback.onBroadcastMeetingConnected(wa.SUCCESS_TRANSACTION_END,t),this.updateBroadcastMetadata(t)),!this.broadcastControllerUrl||e.activeModalities&&e.activeModalities.broadcast||(this.broadcastControllerUrl="",this.broadcastContext=null,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.updateBroadcastMetadata(t),this.signalingSessionCallback.onBroadcastMeetingEnded(wa.SUCCESS_TRANSACTION_END,t))}handleAddBroadcastModalitySuccess(e,t){this.logger.info(`[${t}][handleAddBroadcastModalitySuccess]`)}handleAddBroadcastModalityFailure(e,t){this.logger.info(`[${t}][handleAddBroadcastModalityFailure]`);const i={...e.modalityFailure.broadcast};this.signalingSessionCallback.onBroadcastMeetingEnded(i,t)}updateBroadcastMetadata(e){const t={broadcastControllerUrl:this.broadcastControllerUrl,broadcastStateCallbackUrl:this.broadcastCallbackUrl,broadcastState:this.broadcastState,broadcastAdditionalData:this.broadcastAdditionalData};this.logger.info(`[${e}] update broadcast metadata=${t}`),this.signalingSessionCallback.onBroadcastMeetingUpdated&&this.signalingSessionCallback.onBroadcastMeetingUpdated(t,e)}},Gd=class{constructor(e){this._signalingSession=e,this.baseUrl="http://broker.invalid/",this.currentSubscriptionUrl=null,this._currentSubscriptionTimeoutInSec=30,this._subscribers=[],this._disposed=!1,this._reportedResultCount=0,this._subscriptionRetryBackoffInSec=5,this._notifySubscribers=e=>{this._logger.info("_notifySubscribers"),Promise.resolve().then((()=>{e.split(",").forEach((e=>{const t=function(e){const t=e.split(/\r?\n\r?\n/),i=t[0].split(/\r?\n/),n=t[1].split(/\r?\n/),r=i.shift().split(" "),s=r[0],a=r[1]||"",o=new Pa;for(const e of i)try{const[t,i]=e.split(":").map((e=>Js.trim(e)));o.set(t,i)}catch(t){throw new Error(`Malformed header: ${e+t}`)}return{url:a,headers:o,method:s,body:n.join("")}}(eo(e));let i=t.body;Za(t.headers)&&Xa(t.headers)&&(i=eo(i));const n={url:t.url,body:JSON.parse(i),headers:t.headers};this._logger.info("message length=",i.length,"n. of subscribers",this._subscribers.length),this._subscribers.forEach((e=>e(n)))}))})).catch((e=>{this._logger.error("_notifySubscribers, failed to decode message",e),this._signalingSession.telemetryHelper.recordEvent("BrokerDecodePayloadFailure")}))},this._subscribeToBroker=(e,t)=>{if(this._disposed)return void this._logger.warn("_subscribeToBroker, disposed, ignore subscription");const i=Na();this._logger.info("_subscribeToBroker, url: ",e,",timeout in sec",t),this.currentSubscriptionUrl=e,this._currentSubscriptionTimeoutInSec=t,this._clearAllPendingTimeouts(),this._setSubscriptionTimeout(t),this._signalingSession.http.sendGetRequest({url:this.currentSubscriptionUrl,requestName:Zo.BROKER_SUBSCRIBE.name,customHeaders:this._getBrokerRequestHeaders(i),payload:null,skipHttpTelemetry:!this._reportSubscriptionInTelemetry(),causeId:Na(),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(Zo.BROKER_SUBSCRIBE.name,Na())},this._setSubscriptionTimeout=e=>{this._cancelRequestTimer=Qt.build((()=>{this._disposed||(this._signalingSession.http.hasPendingRequest(Zo.BROKER_SUBSCRIBE.name)?(this._logger.warn("timeout subscription"),this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionTimeout"),this._signalingSession.http.cancelRequestIfPending(Zo.BROKER_SUBSCRIBE.name,Na())):this._logger.error("Unable to resolve timeout deferred, it is not defined!"))}),"TIMEOUT").start(1e3*e)},this._handleSubscriptionSuccess=e=>{if(this._disposed)this._logger.warn("_handleSubscriptionSuccess, disposed, ignore subscription success");else if(this._reportSubscriptionInTelemetry(e)&&this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionSuccessful"),e?.response){const t=e.response;this._logger.info("_handleSubscriptionSuccess, response",t),t.message&&this._notifySubscribers(t.message);const i=t.nextSubscribeUrl||this.currentSubscriptionUrl,n=t.expirationTimeInSec||this._currentSubscriptionTimeoutInSec;this._subscribeToBroker(i,n)}else this._logger.info("_handleSubscriptionSuccess, empty response")},this._handleSubscriptionFailure=e=>{if(this._disposed)return void this._logger.warn("_handleSubscriptionFailure, disposed, ignore subscription");if(e.status>=400&&e.status<500&&401!==e.status&&this.isNotNetworkErrors(e.status))return void this._logger.warn(`_handleSubscriptionFailure, received status ${e.status}, stop subscribing`);const t=je(e);this._logger.error("_handleSubscriptionFailure failed, re-subscribing",t),this._reportSubscriptionInTelemetry()&&this._signalingSession.telemetryHelper.recordEvent("BrokerSubscriptionFailed"),this._retryRequestTimer=Qt.build((()=>{this._subscribeToBroker(this.currentSubscriptionUrl,this._currentSubscriptionTimeoutInSec)}),"RETRY").start(1e3*this._subscriptionRetryBackoffInSec)},this._reportSubscriptionInTelemetry=e=>(this._reportedResultCount++,this._reportedResultCount<=1),this._getBrokerRequestHeaders=e=>{const t=new Pa;return t.set(wa.HEADERS.CONTENT_TYPE,wa.CONTENT_TYPE.JSON),this._signalingSession.signalingAgentConfig.brokerRequestBatching&&t.set(wa.HEADERS.BROKER_USE_BATCHING_HEADER_NAME,"1"),t},this._logger=this._signalingSession.logger.createChild("Broker"),this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration?.brokerRetryBackOffInSec&&(this._subscriptionRetryBackoffInSec=this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration.brokerRetryBackOffInSec)}subscribeToBroker(e){this._logger.info("subscribeToBroker called."),this._abortPendingRequest(),this._clearAllPendingTimeouts(),this._subscribeToBroker(e,this._currentSubscriptionTimeoutInSec)}onBrokerMessage(e){this._logger.info("onBrokerMessage callback added"),this._subscribers.push(e)}dispose(){this._disposed=!0,this._logger.info("dispose"),this._subscribers=[],this._clearAllPendingTimeouts(),this._abortPendingRequest()}isNotNetworkErrors(e){return 490!==e&&496!==e&&498!==e&&499!==e}},qd=class{constructor(e){this.requests={},this.logger=e}clear(e,t){const i=t||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{try{const n=parseInt(t,10);Object.keys(this.requests[n]).forEach((t=>{this.rejectOperation(n,t,e,i)}))}catch(e){this.logger.warn(`CallOperations: clear error = ${e}`)}}))}hasOperation(e,t){return this.requests.hasOwnProperty(e.valueOf())&&this.requests[e.valueOf()].hasOwnProperty(t)}getAllOperations(){return this.requests}getOperation(e,t){return this.hasOperation(e,t)?this.requests[e.valueOf()][t]:null}setOperation(e,t,i){return!this.hasOperation(e,t)&&(this.hasOwnProperty(e.valueOf())||(this.requests[e.valueOf()]={}),this.requests[e.valueOf()][t]=i,!0)}rejectOperation(e,t,i,n){if(this.hasOperation(e,t)){const i=e.valueOf(),r=this.requests[i][t].promise;delete this.requests[i][t],r.reject(n)}}resolveOperation(e,t,i,n){if(this.hasOperation(e,t)){const n=e.valueOf(),r=this.requests[n][t].promise;delete this.requests[n][t],r.resolve(i)}}},zd=class{constructor(e){this.logger=e,this.localRequests=new qd(e)}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}hasPendingOperation(e,t,i){return this.logger.info(`[${i}][hasPendingOperation] ${e} ${De(t)}}`),this.localRequests.hasOperation(e,t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${t} reason: ${i} endCode: ${n}`),this.localRequests.rejectOperation(e,t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${De(t)}`),this.localRequests.resolveOperation(e,t,i,n)}setPendingOperation(e,t,i,n){return this.logger.info(`[${n}][setPendingOperation] ${e} value: ${i}`),this.localRequests.setOperation(e,t,i)}rejectAllPendingOperations(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localRequests.clear(e,t)}};function Wd(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"content cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[]},contentSharing:{identifier:t.contentIdentifier,subject:t.subject,sessionState:t.sessionState,sequenceNumber:t.sequenceNumber,links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}function Kd(e){return Ua(e,"signalingSession cannot be null"),{payload:{contentSharing:{links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Jd(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{contentSharingTransactionEnd:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Yd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Qd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}}}}function Zd(e){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Xd(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"sessionState cannot be null"),Ua(i,"sequenceNumber cannot be null"),{payload:{sessionUpdateSequenceNumber:i,sessionState:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}var eu=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 e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}};function tu(){return new eu}var iu=class{constructor(e,t,i,n){this.signalingSession=e,this.correlationId=t,this.sessionId=null,this.fsmState=wa.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=wa.CONTENT_SHARING_FSM_STATE,this.logger=e.logger.createChild((()=>`[${this.fsmState}][cs=${this.sessionId}][cc=${this.correlationId}]`)),i&&(this.sessionId=i),n&&(this.links=n)}start(e,t,i,n){if(this.logger.info(`[${n}][start]`),Fa(e,"Correct addModality url is not provided"),!this.checkState("start",this.FSM_STATES.IDLE,this.addSessionPromise))return Promise.reject(null);this.addSessionPromise=i,this.confirmInRosterPromise=to(),this.fsmState=this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.addTelemetryOperation(Zo.ADD_CONTENT_SHARING_MODALITY.name,{causeId:n});const r=new Pa;return r.set(wa.HEADERS.CONTENT_SHARING_CORRELATION_ID,this.correlationId),this.signalingSession.http.sendPostRequest({url:e,payload:Wd(this.signalingSession,t),requestName:Zo.ADD_CONTENT_SHARING_MODALITY.name,customHeaders:r,onceTrouterReady:()=>{this.startContentSharingTimer(n)},causeId:n}).then((()=>{this.disposed||(this.presenterMri=this.signalingSession.participantManager.localParticipant.id,this.isPresenter=!0)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${n}][start] error: ${je(t)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise(je(e),t.error)),Promise.reject(null)}))}delete(e,t){this.logger.info(`[${t}][delete]`);let i=!1;if(this.fsmState===this.FSM_STATES.IDLE)return this.logger.info(`[${t}][delete] skipped because state is already ${this.fsmState}`),e.resolve(),Promise.resolve();if(this.fsmState===this.FSM_STATES.CONTENT_SHARING_START_INITIATED)i=!0,this.rejectPendingPromise("Session delete called before start was finished");else if(!this.checkState("delete",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return Promise.reject(null);i||Fa(this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],"Correct controller url is not set"),this.removeSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_DELETE_INITIATED;const n=tu(),r=this.addTelemetryOperation(Zo.DELETE_CONTENT_SHARING.name,{causeId:t});return(i?Promise.resolve(void 0):this.signalingSession.http.sendDeleteRequest({url:this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],requestName:Zo.DELETE_CONTENT_SHARING.name,payload:Jd(this.signalingSession,{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED}),causeId:t})).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};i&&(e.skipReason="Session delete called before start was finished"),this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}})).catch((e=>{const i=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][delete] error: ${je(i)}`),!this.disposed){const e={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}return Promise.reject(null)}))}join(e,t){if(this.logger.info(`[${t}][join]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],"Correct joinContentSharing url is not provided"),!this.checkState("join",this.FSM_STATES.IDLE,e))return;this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.addSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_JOIN_INITIATED;const i=tu(),n=this.addTelemetryOperation(Zo.JOIN_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],payload:Kd(this.signalingSession),requestName:Zo.JOIN_CONTENT_SHARING.name,causeId:t}).then((e=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),this.processStartOrJoinSuccess(e.response),this.resolvePendingPromise(e.response)}})).catch((e=>{const r=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][join] error: ${je(r)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const s=r.error;this.rejectPendingPromise(je(e),s)}}))}takeControl(e,t){if(this.logger.info(`[${t}][takeControl]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL],"correct contentSharingTakeControl url is not provided"),!this.checkState("takeControl",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=tu(),n=this.addTelemetryOperation(Zo.TAKE_CONTROL_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL],payload:Yd(this.signalingSession),requestName:Zo.TAKE_CONTROL_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((t=>{if(!this.disposed){const r={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,r);const s={contentIdentifier:t.response.identifier,presenter:t.response.presenter.id,subject:t.response.subject||null,sessionState:t.response.sessionState||null};e.resolve(s)}})).catch((r=>{const s=Ka(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][takeControl] error: ${je(s)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const a=new Error(je(r));a.endCode=s.error,e.reject(a)}}))}updateSessionState(e,t,i){if(this.logger.info(`[${i}][updateSessionState]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],"Correct sendUpdateSessionState url is not provided"),!this.checkState("updateSessionState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,t))return;const n=tu(),r=this.addTelemetryOperation(Zo.UPDATE_SESSION_STATE_CONTENT_SHARING.name,{causeId:i});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],payload:Xd(this.signalingSession,e,this.nextClientSequenceNumberToUse++),requestName:Zo.UPDATE_SESSION_STATE_CONTENT_SHARING.name,causeId:i}).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};this.updateTelemetryOperation(r,e),t.resolve()}})).catch((e=>{const s=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${i}][updateSessionState] error: ${je(s)}`),!this.disposed){const i={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,i);const a=new Error(je(e));a.endCode=s.error,t.reject(a)}}))}updateParticipantState(e,t){if(this.logger.info(`[${t}][updateParticipantState]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],"correct confirmContentSharingView url is not provided"),!this.checkState("updateParticipantState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=tu(),n=this.addTelemetryOperation(Zo.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],payload:Zd(this.signalingSession),requestName:Zo.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((()=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),e.resolve()}})).catch((r=>{const s=Ka(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][updateParticipantState] error: ${je(s)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const a=new Error(je(r));a.endCode=s.error,e.reject(a)}}))}updateNotificationLinks(e){if(this.logger.info(`[${e}][updateNotificationLinks]`),Fa(this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],"correct notificationLinks url is not provided"),!this.checkState("updateState",this.FSM_STATES.CONTENT_SHARING_CONNECTED))return;const t=tu(),i=this.addTelemetryOperation(Zo.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,{causeId:e});this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],payload:Qd(this.signalingSession),requestName:Zo.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,withoutTrouter:!0,causeId:e}).then((()=>{if(!this.disposed){const e={success:!0,duration:t.duration()};this.updateTelemetryOperation(i,e)}})).catch((n=>{const r=Ka(n,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${e}][updateNotificationLinks] error: ${je(r)}`),!this.disposed){const e={success:!1,duration:t.duration()};this.updateTelemetryOperation(i,e)}}))}confirmInRoster(){this.confirmInRosterPromise&&this.confirmInRosterPromise.isPending&&(this.logger.info("Confirmed in roster"),this.confirmInRosterPromise.resolve())}handleAddModalitySuccess(e,t){return this.logger.info(`[${t}][handleAddModalitySuccess]`),this.checkState("handleAddModalitySuccess",this.FSM_STATES.CONTENT_SHARING_START_INITIATED)?e.modalitySuccess&&e.modalitySuccess.contentSharing?(this.addTelemetryOperation(Mo,{causeId:t}),this.processStartOrJoinSuccess(e.modalitySuccess.contentSharing),this.confirmInRosterPromise.promise.then((()=>{delete this.confirmInRosterPromise,this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.resolvePendingPromise(e.modalitySuccess.contentSharing)})),!0):(this.addTelemetryOperation(Mo,{causeId:t,skipReason:"no content sharing blob"}),this.logger.info(`[${t}][handleAddModalitySuccess] ignored because modalitySuccess was missing or did not contain content sharing blob`),!1):(this.logger.info(`[${t}][handleAddModalitySuccess] ignored because session is not waiting to start`),!1)}handleAddModalityFailure(e,t){if(this.logger.info(`[${t}][handleAddModalityFailure]`),!this.checkState("handleAddModalityFailure",[this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.FSM_STATES.CONTENT_SHARING_CONNECTED]))return!1;if(!e.modalityFailure||!e.modalityFailure.contentSharing)return this.addTelemetryOperation(Do,{causeId:t,skipReason:"no content sharing blob"}),!1;const i=e.modalityFailure.contentSharing;this.addTelemetryOperation(Do,{reason:i,causeId:t});const n={...i};return this.sendTelemetryData(n),this.rejectPendingPromise(n.phrase,n),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),!0}handleStartFromRoster(e,t){this.logger.info(`[${t}][handleStartFromRoster]`),this.addTelemetryOperation("ContentSharingStartFromRoster",{causeId:t})}handleStopFromRoster(e,t){this.logger.info(`[${t}][handleStopFromRoster]`),this.addTelemetryOperation("ContentSharingEndFromRoster",{causeId:t}),this.sendTelemetryData(e)}handleStop(e,t){if(this.logger.info(`[${t}][handleStop]`),this.isSelfInitiatedAction(e))return this.logger.info(`[${t}][handleStop]handleStop skipped because session was ended by self`),!1;const i={...e.contentSharingTransactionEnd};return this.addTelemetryOperation("HandleContentSharingEnd",{causeId:t}),this.sendTelemetryData(i),!0}handleUpdate(e,t){return this.logger.info(`[${t}][handleUpdate]`),e.sequenceNumber<=this.lastUpdateSequenceNumber?(this.logger.info(`handleUpdate skipped because of old sequence number: last received ${this.lastUpdateSequenceNumber}, update contained ${e.sequenceNumber}`),this.addTelemetryOperation(Ro,{causeId:t,skipReason:"old sequence number"}),!1):(this.lastUpdateSequenceNumber=e.sequenceNumber,this.isPresenter=e.presenter.id===this.signalingSession.participantManager.localParticipant.id,this.addTelemetryOperation(Ro,{causeId:t}),!0)}dispose(e,t){this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.rejectPendingPromise("call ended",e||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED}),this.addTelemetryOperation(wo,{causeId:t}),this.sendTelemetryData(e)}rejectPendingPromise(e,t){this.logger.info("rejectPendingPromise");const i=new Error(e);t&&(i.endCode=t),this.removeSessionPromise&&(this.removeSessionPromise.reject(i),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.reject(i),this.addSessionPromise=null)}resolvePendingPromise(e){this.logger.info("resolvePendingPromise");let t=null;e&&(t={sessionId:e.sessionId,correlationId:e.contentSharingCorrelationId,contentIdentifier:e.identifier,presenter:e.presenter.id,subject:e.subject||null,sessionState:e.sessionState||null}),this.removeSessionPromise&&(this.removeSessionPromise.resolve(t),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.resolve(t),this.addSessionPromise=null)}processStartOrJoinSuccess(e){this.logger.info("processStartOrJoinSuccess"),this.sessionId=e.sessionId,this.fsmState=this.FSM_STATES.CONTENT_SHARING_CONNECTED,this.lastUpdateSequenceNumber=-1,this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER]=e.links.contentSharingController,this.links[wa.LINKS.CONTENT_SHARING_TAKE_CONTROL]=e.links.takeControl,this.links[wa.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE]=e.links.updateSessionState,this.links[wa.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE]=e.links.sync,this.links[wa.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[wa.LINKS.CONTENT_SHARING_LEAVE]=e.links.leave}checkState(e,t,i){let n;if(n="string"==typeof t?this.fsmState===t:t.indexOf(this.fsmState)>-1,n)return!0;{const n=`${e} requires state ${t}, but state is ${this.fsmState}`;return this.logger.error(n),i&&i.reject(n),!1}}isSelfInitiatedAction(e){return e.presenter.participantId===this.signalingSession.participantManager.localParticipant.participantId}startContentSharingTimer(e){this.logger.info("startContentSharingTimer"),this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY,(()=>{this.addTelemetryOperation("AddModalityTimeout",{causeId:e}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise("timed out waiting for ContentSharing to start",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT})}),wa.TIMEOUT_VALUES_IN_SECONDS.ADD_MODALITY_TIMEOUT)}addTelemetryOperation(e,t){return this.signalingSession.telemetryHelper.addContentSharingOperation(this.correlationId,e,t)}updateTelemetryOperation(e,t){this.signalingSession.telemetryHelper.updateContentSharingOperation(this.correlationId,e,t)}sendTelemetryData(e){this.signalingSession.telemetryHelper.sendContentSharingTelemetryData(this.correlationId,this.signalingSession.sessionId,this.isPresenter,e,this.links[wa.LINKS.CONTENT_SHARING_CONTROLLER],this.sessionId)}},nu=class{constructor(e,t){this.contentSharingToStartCallWith=null,this.contentSharingSessions={},this.DEFAULT_STOP_REASON={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.REMOTE_USER_INITIATED},this.DEFAULT_STOP_ID="8:unknown",this.deleteContentSharingAsync=(e,t)=>{this.logger.info(`[${t}][deleteContentSharingAsync]`);const i=to();let n=this.contentSharingSessions[e];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===e&&(n=this.pendingSessionToStart),n){const r=()=>{this.contentSharingSessions[e]&&delete this.contentSharingSessions[e]};n.delete(i,t).then(r,r)}else this.rejectBecauseOfMissingSession(e,i);return i.promise},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[ContentSharingManager]")),this.lastProcessedSequenceNumber=-1,this.lastProcessedSequenceNumberForParticipant={}}startContentSharingAsync(e,t,i,n,r,s,a){if(this.logger.info(`startContentSharingAsync called for: ${e}`),this.pendingSessionToStart){const e="There is already a ContentSharing session start pending";return this.logger.error(e),Promise.reject(new Error(e))}const o={contentIdentifier:e,subject:i||null,sessionState:t||null,sequenceNumber:1},l=to(),c=new iu(this.signalingSession,a||La());return this.pendingSessionToStart=c,r?(this.logger.info("Call connected, send content sharing request out immediately"),c.start(n,o,l,s)):(this.logger.info("Content sharing is to be started when startOutgoingCall is called"),c.addSessionPromise=l,c.fsmState=wa.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED,this.contentSharingToStartCallWith=o),l.promise.then((()=>{this.contentSharingSessions.hasOwnProperty(c.correlationId)||(this.contentSharingSessions[c.correlationId]=c),this.pendingSessionToStart=null})).catch((()=>{this.pendingSessionToStart=null})),l.promise}joinContentSharingAsync(e,t){this.logger.info(`[${t}][joinContentSharingAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.join(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingSessionStateAsync(e,t,i){this.logger.info(`[${i}][updateContentSharingSessionStateAsync][sessionState=${JSON.stringify(t)}]`);const n=to(),r=this.contentSharingSessions[e];return r?r.updateSessionState(t,n,i):this.rejectBecauseOfMissingSession(e,n),n.promise}takeContentSharingControlAsync(e,t){this.logger.info(`[${t}][takeContentSharingControlAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.takeControl(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingParticipantStateAsync(e,t){this.logger.info(`[${t}][updateContentSharingParticipantStateAsync]`);const i=to(),n=this.contentSharingSessions[e];return n?n.updateParticipantState(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingNotificationLinksAsync(e){this.logger.info(`[${e}][updateContentSharingNotificationLinksAsync]`);for(const t of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(t)){const i=this.contentSharingSessions[t];i&&i.updateNotificationLinks(e)}}getContentSharingInfoToStartSharing(){if(this.contentSharingToStartCallWith){const e=this.pendingSessionToStart,t=wa.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED;e&&e.fsmState===t||(this.contentSharingToStartCallWith=null,this.pendingSessionToStart=null)}return this.contentSharingToStartCallWith}dispose(e,t){this.logger.info(`[${t}][dispose]`);for(const i of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(i)){const n=this.contentSharingSessions[i];n&&n.dispose(e,t)}}handleContentSharingUpdate(e){const t=e.body,i=Qa(e),n=this.contentSharingSessions[t.contentSharingCorrelationId];n?n.handleUpdate(t,i)&&this.signalingSessionCallback.onContentSharingUpdated({sessionId:t.sessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:t.presenter.id,subject:t.subject||null,sessionState:t.sessionState||null},i):this.logger.info(`[${i}][handleContentSharingUpdate][failed][reason=no session with correlation ID ${t.correlationId}]`)}handleAddModalitySuccess(e,t){this.logger.info(`[${t}][handleAddModalitySuccess]`);const i=this.pendingSessionToStart;i?i.handleAddModalitySuccess(e,t):this.logger.info(`[${t}][handleAddModalitySuccess]Ignoring handleAddModalitySuccess because not waiting for one`)}handleAddModalityFailure(e,t){this.logger.info(`[${t}][handleAddModalityFailure]`);const i=this.pendingSessionToStart;i?i.handleAddModalityFailure(e,t):this.logger.info(`[${t}][handleAddModalityFailure]Ignoring handleAddModalityFailure because not waiting for one`)}handleIncomingContentSharingFromRoster(e,t,i){if(this.logger.info(`[${i}] handleIncomingContentSharingFromRoster: isFullRoster ${t} content ${je(e)}`),("MultiPartyEndpoint"===e.type||t)&&this.lastProcessedSequenceNumber>e.sequenceNumber)return void this.logger.info(`[${i}] handleIncomingContentSharingFromRoster invalid roster current sequenceNumber ${e.sequenceNumber} lastProcessedSequenceNumber ${this.lastProcessedSequenceNumber}`);const{sessionsWithPresenters:n,sessionsWithoutPresenters:r}=this.parseContentSharingSessionsFromRoster(e);this.startSessionsFromRoster(n,i),this.stopSessionsFromRoster(r,i),this.lastProcessedSequenceNumber=e.sequenceNumber}handleContentSharingEnd(e){const t=e.body,i=Qa(e);this.logger.info("handleContentSharingEnd : ",je(t));const n=this.contentSharingSessions[t.contentSharingCorrelationId];if(!n)return void this.logger.info("Ignoring contentSharingEnd since there is no corresponding sharing ongoing");if(!n.handleStop(t,i))return;const r={...t.contentSharingTransactionEnd};this.raiseContentSharingStopped(t.contentSharingCorrelationId,i,t.presenter.id,r)}parseContentSharingSessionsFromRoster(e){const t={},i={},n=new Set;for(const i of Object.keys(e.participants)){const r=e.participants[i];if("Delta"===e.type&&this.lastProcessedSequenceNumberForParticipant.hasOwnProperty(i)&&r.version<=this.lastProcessedSequenceNumberForParticipant[i])continue;if(r.version=r.version||-1,this.lastProcessedSequenceNumberForParticipant[i]=r.version,n.add(r.details.id),!r.endpoints)continue;const s=this.signalingSession.participantManager.localParticipant.participantId;for(const e of Object.keys(r.endpoints)){const i=r.endpoints[e],n=i?.contentSharing?.sessionInformation;"presenter"===n?.role&&(t[n.contentSharingCorrelationId]={presenterId:r.details.id,sessionInfo:n,selfEndpointIsPresenter:i.participantId===s})}}for(const e of Object.keys(this.contentSharingSessions))!t[e]&&n.has(this.contentSharingSessions[e].presenterMri)&&(i[e]=this.contentSharingSessions[e]);return{sessionsWithPresenters:t,sessionsWithoutPresenters:i}}stopSessionsFromRoster(e,t){this.logger.info(`[${t}][stopSessionsFromRoster]`);for(const i of Object.keys(e))this.logger.info(`[${t}][stopSessionsFromRoster] stopping session with correlationId ${i}`),this.stopSession(e[i],t)}stopSession(e,t){this.logger.info(`[${t}][stopSession] Stopping session ${e.sessionId}`),e.handleStopFromRoster(this.DEFAULT_STOP_REASON,t),this.raiseContentSharingStopped(e.correlationId,t)}startSessionsFromRoster(e,t){this.logger.info(`[${t}][startSessionsFromRoster]`);for(const i of Object.keys(e)){this.logger.info(`[${t}][startSessionsFromRoster]`);const n=this.contentSharingSessions[i],r=e[i];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===i?this.pendingSessionToStart.confirmInRoster():n&&n.confirmInRoster(),n)n&&(this.contentSharingSessions[i].presenterMri=r.presenterId,this.logger.info(`[${t}][startSessionsFromRoster]Session ${i} is already present locally`));else{if(r.selfEndpointIsPresenter){this.logger.info(`[${t}][startSessionsFromRoster]This endpoint is presenting, dont fire callback`);continue}this.logger.info(`[${t}][startSessionsFromRoster]New sharing session found. Raising ContentSharingStarted`),this.raiseContentSharingStarted(r.presenterId,r.sessionInfo,t).handleStartFromRoster(r.presenterId,t)}}}raiseContentSharingStopped(e,t,i,n){this.logger.info(`[${t}][raiseContentSharingStopped]`),this.signalingSessionCallback.onContentSharingStopped({sessionId:this.contentSharingSessions[e].sessionId,correlationId:e,endedBy:i||this.DEFAULT_STOP_ID,reason:n||this.DEFAULT_STOP_REASON},t),delete this.contentSharingSessions[e]}raiseContentSharingStarted(e,t,i){this.logger.info(`[${i}][raiseContentSharingStarted]`);const n=new iu(this.signalingSession,t.contentSharingCorrelationId,t.contentSharingSessionId,{[wa.LINKS.CONTENT_SHARING_CONTROLLER]:t.contentSharingController});n.presenterMri=e,this.contentSharingSessions[n.correlationId]=n;const r={sessionId:t.contentSharingSessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:e,subject:t.subject||null,sessionState:t.sessionState||null};return this.signalingSessionCallback.onContentSharingStarted(r,i),n}rejectBecauseOfMissingSession(e,t){const i=`There is no ContentSharing session with the correlation ID ${e}`;this.logger.error(i),t&&t.reject(new Error(i))}},ru={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}},su={CallSetup:{requestHedgingCapability:["disabled"],hedgeDelayMs:4e3},Other:{requestHedgingCapability:["disabled"]},BrokerSubscribe:{requestHedgingCapability:["disabled"]}},au="HttpRequestDispatcherFactory";function ou(e,t,i){t?.signalingSession?t.signalingSession.telemetryHelper?.addTokenTelemetry(e,t?.tokenTelemetryData):i?.info("[reportTokenTelemetryData] signaling session is not available, cannot send token telemetry")}function lu(e,t){const{signalingSession:i,operation:n,causeId:r,data:s,customHeaders:a={},forceFetchToken:o,tokenRequestOptions:l,useFetch:c,fetchUseKeepAlive:d}=e;if(i.disposed)return Promise.reject("Session already disposed");const u=e=>{const t="string"==typeof e?new Error(e):e;throw i.signalingAgent.clientSupportsGenericTokenAPI?e.timeOut?t.tokenTimeoutError=!0:(t.tokenError=!0,t.tokenErrorSubCode=e.errorSubCode):t.skypeTokenError=!0,t};let h=!1;const g={signalingSession:i,tokenTelemetryData:{}};return i.signalingAgent.authTokenManager.getToken(r,o,l,g).catch((n=>(ou(e.requestId,g,t),!o&&function(e){const t=io(e.signalingAgentConfig.trouterServiceProvider);return 3===t||1===t}(i)&&i.signalingAgentConfig.attemptHttpRequestWithCachedSkypetoken&&i.signalingAgent.authTokenManager.getLastToken(r)?(h=!0,t?.info(`[${r}][requestBuilder] failed to fetch token, using lastToken`),Promise.resolve(i.signalingAgent.authTokenManager.getLastToken(r))):(t?.info(`[${r}][requestBuilder] getToken failed with error ${n}`),u(n))))).then((o=>{if(i.disposed)throw new Error("token returned too late. Object is already disposed");ou(e.requestId,g,t);const l=new Pa;if(l.set(wa.HEADERS.CORRELATION_ID,i.correlationId),l.set(wa.HEADERS.MESSAGE_ID,function(e){return e&&/^[a-z0-9]{8}$/.test(e)?e+La().substr(8):La()}(r)),l.set(wa.HEADERS.CLIENT_USER_AGENT,i.signalingAgentConfig.clientInformation),i.signalingAgent.clientSupportsGenericTokenAPI){const e=i.signalingAgent.authTokenManager.getLastTokenType(r);switch(i.signalingAgentConfig.disableTokenMigrationHeader||l.set(wa.HEADERS.TOKEN_MIGRATION,"True"),e){case 8:case 4:l.set(wa.HEADERS.AUTHORIZATION,`${wa.HEADERS.BEARER_KEYWORD} ${o}`),l.delete(wa.HEADERS.SKYPE_TOKEN);break;case 1:l.set(wa.HEADERS.SKYPE_TOKEN,o),l.delete(wa.HEADERS.AUTHORIZATION);break;default:throw new Error(`Error in RequestBuilder. TokenType ${e} is not supported`)}}else l.set(wa.HEADERS.SKYPE_TOKEN,o);const u=i.participantManager.localParticipant;u&&(u.ring&&l.set(wa.HEADERS.RING,u.ring),u.region&&l.set(wa.HEADERS.REGION,u.region),u.partition&&l.set(wa.HEADERS.PARTITION,u.partition));const p=s?.payload?JSON.stringify(s.payload):null,m={headers:{...l?.getAll(),...a},payload:p,usedCachedSkypetoken:h,reporting:{serviceName:n?`${au}-${n}`:au},useFetch:c,fetchUseKeepAlive:d};return i.telemetryHelper.addNetworkOperationStarted(n),m})).catch(u)}var cu=class{constructor(e,t,i,n,r,s,a,o,l){this.causeId=e,this.logger=t,this.dispatcher=i,this.requestType=n,this.url=r,this.request=s,this.onRequestFailed=a,this.authRequiredCallback=o,this.settings=l,this.requestsSent=0,this.otherAttemptSuccessful=!1,this.pendingAttempts=[],this.hedgeDelayMs=3e3,this.hedgeMaxParallelAttempts=3,this.stopStandardRetryTimer=()=>{this.standardRetryTimer&&(this.standardRetryTimer.stop(),this.standardRetryTimer=null)},this.stopHedgeTimer=()=>{this.hedgeTimer&&(this.hedgeTimer.stop(),this.hedgeTimer=null)},this.stopAttemptTimeoutTimer=e=>{try{e.timeoutTimer&&(e.timeoutTimer.stop(),this.logger.info("attempt timer stopped"))}catch(e){this.logger.info(`stopAttemptTimeoutTimer error ${e}`)}},this.stopRequestTimer=()=>{try{this.requestTimer&&(this.requestTimer.stop(),this.logger.info("Request timer stopped"))}catch(e){this.logger.info(`stopRequestTimer error ${e}`)}this.requestTimer=null},this.canScheduleNextAttempt=()=>{if(this.stackError===wa.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 e=this.pendingAttempts.length<this.hedgeMaxParallelAttempts;return e||this.logger.info(`canScheduleNextAttempt enableRequestHedging attempts sent: ${this.pendingAttempts.length} max attempts: ${this.hedgeMaxParallelAttempts}`),e}{const e=this.requestsSent<this.settings.retryIntervalsMs.length;return e||this.logger.info(`canScheduleNextAttempt attempts sent: ${this.requestsSent} max attempts: ${this.settings.retryIntervalsMs.length}`),e}},this.scheduleNextRequest=e=>{this.settings.enableRequestHedging?(this.logger.info("scheduleNextRequest with hedging"),this.hedgeTimer=Qt.build((()=>{this.attempt(),this.canScheduleNextAttempt()&&this.scheduleNextRequest(!1)}),"HEDGE").start(this.getNextDelay(e))):(this.logger.info("scheduleNextRequest with retry"),this.standardRetryTimer=Qt.build((()=>{this.attempt()}),"RETRY").start(this.getNextDelay(e)))},this.standardizeFailedRequest=(e,t)=>{let i;const n=this.logger.createChild("[standardizeFailedRequest]");try{if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT)n.info("request timed out"),i=ta.REQUEST_TIMEOUT;else if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_ABORTED)n.info("request aborted"),i=ta.REQUEST_ABORTED;else if(t&&t.status===wa.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT)n.info("request attempt timed out"),i=ta.ATTEMPT_TIMEOUT;else if(t&&[wa.HTTP_STACK_ERROR.ATTEMPT_ABORTED,wa.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL].indexOf(t.status)>-1)n.info("request attempt aborted"),i=ta.ATTEMPT_ABORTED;else if(e){if(n.info(`request ${Je(e)}`),e.request?.response){const t=e;i={response:{..."string"==typeof t?.request?.response?t?.response?.data:t?.request?.response,headers:t.response?.headers},status:t.request.status,statusText:t.request.statusText,readyState:t.request.readyState}}else e.status||e.statusCode||e.response?i={response:e.response,status:[void 0,null,""].indexOf(e.status)>-1?e.statusCode:e.status,statusText:e.statusText,readyState:e.readyState}:(n.info("Local http stack error"),i={response:wa.CALL_END_SUB_CODE.LOCAL_HTTP_STACK_ERROR,status:wa.CALL_END_CODE.LOCAL_HTTP_STACK_ERROR,statusText:"LocalHTTPStackError",readyState:e.readyState||0});this.isBrowserOffline()&&0===i.status&&4===i.readyState&&(n.info("offline"),i={response:wa.HTTP_STACK_ERROR.CANNOT_CONNECT,status:wa.HTTP_STATUS_CODES.OFFLINE,statusText:"offline",readyState:i.readyState}),e.response?.message&&(e.response.message.operationFailure||e.response.message.broadcastOperationFailure)?i={response:e.response.message}:!e.response&&e.body?.operationFailure&&(i={response:e.body})}else n.info("no response"),i={response:wa.HTTP_STACK_ERROR.NONE,status:wa.HTTP_STATUS_CODES.OTHER,statusText:"Empty Response",readyState:0}}catch(e){n.info(`Failed to handle error ${e}`),i={response:"",status:wa.HTTP_STATUS_CODES.OTHER,statusText:"FailedToHandleError",readyState:0}}return i},this.hasPendingAttempts=()=>this.pendingAttempts.some((e=>e.pending)),this.getRequestFromStatus=e=>e?.request?.status||0,this.isBrowserOffline=()=>navigator&&!1===navigator.onLine,this.logger=t.createChild(`[${this.causeId}][Dispatcher]`),this.logger.info(`created request, url=${r}`),!isNaN(this.settings.hedgeDelayMs)&&this.settings.hedgeDelayMs>=500&&this.settings.hedgeDelayMs<=1e4&&(this.hedgeDelayMs=this.settings.hedgeDelayMs),!isNaN(this.settings.hedgeMaxParallelAttempts)&&this.settings.hedgeMaxParallelAttempts>=0&&this.settings.hedgeMaxParallelAttempts<=4&&(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(){return this.stackError=wa.HTTP_STACK_ERROR.NONE,this.logger.info("send api called"),this.requestTimer=Qt.build((()=>{this.stackError=wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT,this.cancelAllAttempts(wa.HTTP_STACK_ERROR.REQUEST_TIMEOUT)}),"REQUEST_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perRequestTimeoutWithHedgingMs:this.settings.perRequestTimeoutMs),new Promise(((e,t)=>{this.resolve=e,this.reject=t,this.scheduleNextRequest(!0)}))}cancelRequest(){this.logger.info("cancelRequest"),this.stackError=wa.HTTP_STACK_ERROR.REQUEST_ABORTED,this.cancelAllAttempts(wa.HTTP_STACK_ERROR.ATTEMPT_ABORTED)}cancelOtherAttempts(e){this.pendingAttempts.splice(e-1,1),this.cancelAllAttempts(wa.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL)}cancelAllAttempts(e){this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.pendingAttempts.forEach((t=>{t.status=e,t.cancelDeferred.resolve(),this.stopAttemptTimeoutTimer(t)})),this.stopRequestTimer()}getRequestMethod(e){switch(e){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(e){const t=e&&this.isNotRetryable(e);if(this.logger.info("queueAttempt"),t||!this.canScheduleNextAttempt())return this.logger.info(`unable to retry isNotRetryable ${t} ${JSON.stringify(e)}`),this.stopHedgeTimer(),this.stopRequestTimer(),void(this.hasPendingAttempts()||(this.settings.reportPreviousErrorsForTimeout&&e===ta.ATTEMPT_TIMEOUT&&this.previousAttempt?this.reject(this.previousAttempt):this.reject(e)));if(this.isAuthFailedStatus(e)){this.logger.info("auth failed"),this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.stopRequestTimer();try{const t=e?.response?.headers,i=function(e){const t=Pa.getHeaderValue(e,wa.HEADERS.SKYPE_TOKEN);if(t)return t;const i=Pa.getHeaderValue(e,wa.HEADERS.AUTHORIZATION);if(i){const e=i.split(" ");if(2===e.length)return e[1]}}(this.request?.headers),n=e.response?.status===wa.HTTP_STATUS_CODES.UNAUTHORIZED&&e.response?.operationFailure?.subCode===wa.CALL_END_SUB_CODE.CONVERSATION_TERMINATION_INTERACTION_REQUIRED,r=await this.authRequiredCallback(t,i,{IPCAFailure:n});this.request=r}catch(t){return t.authCallBackFailure=!0,e.error=t,void this.reject(e)}}this.previousAttempt=e,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===wa.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful)return;const e=(new Date).getTime();this.requestsSent++;const t=this.requestsSent,i=to();this.request.timeout=i.promise;const n={cancelDeferred:i,status:wa.HTTP_STACK_ERROR.NONE,timeoutTimer:null,pending:!0},r=Qt.build((()=>{n.status=wa.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT,n.cancelDeferred.resolve()}),"ATTEMPT_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perAttemptTimeoutWithHedgingMs:this.settings.perAttemptTimeoutMs);n.timeoutTimer=r,this.pendingAttempts.push(n),this.getRequestMethod(this.requestType)(this.url,this.request).then((i=>{if(this.logger.info(`attempt successful, request response=${Ke(i)} status=${this.getRequestFromStatus(i)}`),this.otherAttemptSuccessful)throw"Other attempt succesful";if(this.stackError===wa.HTTP_STACK_ERROR.REQUEST_ABORTED)throw"Session disposed";if(!i)throw"Invalid response";n.pending=!1,this.otherAttemptSuccessful=!0,this.stopRequestTimer(),this.stopHedgeTimer(),this.stopAttemptTimeoutTimer(n),this.cancelOtherAttempts(t),this.resolve({success:!0,request:i.request,response:i.response,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()})})).catch((t=>{n.pending=!1,this.stopAttemptTimeoutTimer(n);const i=this.standardizeFailedRequest(t,n);this.logger.info(`attempt failed, request: ${Je(t)} status=${i.status}`),this.onRequestFailed({abandoned:this.otherAttemptSuccessful,success:!1,request:i,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()}),this.queueAttempt(i)}))}getNextDelay(e){let t;if(e)t=0;else if(this.settings.enableRequestHedging)t=this.hedgeDelayMs;else{if(!(this.requestsSent<=this.settings.retryIntervalsMs.length))throw"Unable to get next delay";t=this.settings.retryIntervalsMs[this.requestsSent-1]}return this.logger.info(`next delay= ${t} ms`),t}isRequestWithStatus(e,t){return!!e&&t.indexOf(e.status)>-1}isNotRetryable(e){return!no(e?.status)}isAuthFailedStatus(e){return this.isRequestWithStatus(e,[wa.HTTP_STATUS_CODES.UNAUTHORIZED])}},du={1:"POST",0:"GET",2:"PUT",3:"DELETE"},uu=class{constructor(e,t){this.signalingSession=e,this.callStartTime=t,this.pendingRequests={},this.sendGetRequest=e=>this.sendRequest(0,e),this.sendPostRequest=e=>this.sendRequest(1,e),this.sendPutRequest=e=>this.sendRequest(2,e),this.sendDeleteRequest=e=>this.sendRequest(3,e),this.cancelRequestIfPending=(e,t,i,n)=>{this.logger.info(`[${t}][cancelRequestIfPending]`),this.pendingRequests[e]?i?this.hasPendingRequest(e,i)&&this.cancelRequest(e,i,t,n):Object.keys(this.pendingRequests[e]).forEach((i=>this.cancelRequest(e,i,t,n))):this.logger.info(`[${t}][cancelRequestIfPending]no pending request with name=${e}`)},this.cancelAllRequests=e=>{this.logger.info(`[${e}][cancelAllRequests]`);const t=[];return Object.keys(this.pendingRequests).forEach((i=>{Object.keys(this.pendingRequests[i]).forEach((n=>{t.push(this.cancelRequest(i,n,e))}))})),Promise.all(t).catch((()=>{}))},this.hasPendingRequest=(e,t)=>!!this.pendingRequests[e]&&Boolean(t?this.pendingRequests[e][t]:this.pendingRequests[e]),this.cancelRequest=(e,t,i,n)=>{try{return this.pendingRequests[e][t].dispatcher&&this.pendingRequests[e][t].dispatcher.cancelRequest(),this.pendingRequests[e][t].aborted=!0,this.pendingRequests[e][t].errorDetails=n,this.logger.info(`[${i}][cancelRequest]Request=${e} aborted ${n?`with errorDetails ${JSON.stringify(n)}`:""}`),this.pendingRequests[e][t].requestPromise.catch((()=>{}))}catch(n){return this.logger.warn(`[${i}][cancelRequest]Unable to cancel request=${e}, requestId=${t}`),Promise.resolve()}},this.buildRequestTelemetry=(e,t,i,n)=>({name:`${du[e]}-${t.requestName}`,url:t.url,eventStart:i-this.callStartTime,trouterReady:-1,requestReady:-1,status:-1,attempts:[],rtt:-1,uid:t.requestId,causeId:t.causeId,requestDispatcherConfig:n,enableRequestHedging:this.shouldEnableRequestHedging(n)}),this.addPendingRequest=e=>(this.pendingRequests[e.requestName]||(this.pendingRequests[e.requestName]={}),this.pendingRequests[e.requestName][e.requestId]={dispatcher:null,requestPromise:null,aborted:!1},this.pendingRequests[e.requestName][e.requestId]),this.sendRequest=(e,t)=>{if(!t.url){this.logger.error(t.requestName,"Link does not exist");const e={code:wa.CALL_END_CODE.HTTP_OTHER_ERROR,subCode:wa.CALL_END_SUB_CODE.MISSING_REQUEST_URI,phrase:`Link does not exist for requestName: ${t.requestName}.`};return Promise.reject(e)}t.requestId||(t.requestId=La()),t.causeId||(t.causeId=Na());let i=!1,n=!1;const r=this.logger.createChild(`[${t.causeId}][${t.requestName}]`);r.info("[scheduled]");const s=this.getInternalHttpDispatcherConfig(t.requestName,t.operationType);let a;t.skipHttpTelemetry||(t.skipHttpTelemetry=!1);const o=tu(),l=(new Date).getTime(),c=[],d=this.buildRequestTelemetry(e,t,l,s),u=()=>{this.signalingSession.disposed?this.logger.info("Unable to record telemetry, session disposed"):this.signalingSession.telemetryHelper.updateNetworkRequest(d)},h=()=>{this.signalingSession.telemetryHelper.deleteNetworkRequest(d)};u();const g=(e,i,s)=>{if(!e?.request)return void this.logger.warn(t.requestName,"missing request details, unable to record for telemetry!");r.info(`[finished][status=${e.request.status}][statusText=${e.request.statusText}][retryCount=${e.attempt}]`);const a=e.request.status,o=e.request.response?.operationFailure?.subCode,c={status:a,statusSubCode:o||s,start:e.attemptStartTimestamp-l,end:e.attemptResponseTimestamp-l,online:io(this.signalingSession.signalingAgentConfig.trouterServiceProvider)};e.abandoned&&(c.abandoned=!0),e.request.statusText&&(c.statusText=e.request.statusText),!i&&n||(d.status=a,d.statusSubCode=s||o),(i||!n&&a>=200&&a<400)&&(n=!0),d.attempts.push(c),u()};if(this.hasPendingRequest(t.requestName,t.requestId))return this.logger.warn(t.requestName,t.requestId,"is already pending request!!"),this.pendingRequests[t.requestName][t.requestId].requestPromise;a=this.addPendingRequest(t);const p=(e,i,n,s)=>{if(e&&t.skipHttpTelemetry)return this.logger.info("Skipping telemetry"),void h();r.info(`[steps=${c}]`),this.pendingRequests[t.requestName][t.requestId].aborted&&(d.aborted=!0),this.hasPendingRequest(t.requestName,t.requestId)?(delete this.pendingRequests[i][n],Object.keys(this.pendingRequests[i]).length||delete this.pendingRequests[i]):this.logger.warn("Unable to clean up!"),this.signalingSession.disposed||(s&&(d.error=s),d.rtt=o.duration(),this.signalingSession.telemetryHelper.addNetworkOperationCompleted(t.requestName,e,o.duration()),u(),this.signalingSession.telemetryHelper.sendHttpTelemetryData(d.uid))},m=e=>(...i)=>{if(this.signalingSession.disposed){const e=`[${t.causeId}][${t.requestName}][failed][reason=Session disposed]`;throw r.info("[failed][reason=Session disposed]"),new Error(e)}if(this.hasPendingRequest(t.requestName,t.requestId)&&this.pendingRequests[t.requestName][t.requestId].aborted){let e;const i=`[${t.causeId}][${t.requestName}][failed][reason=request already aborted]`,n=this.pendingRequests[t.requestName][t.requestId].errorDetails;throw n?(e=n,e.phrase=i):e=i,r.info(`${i}`),new Error(JSON.stringify(e))}return e(...i)},f=m((()=>(c.push("[waitForTrouter]"),t.withoutTrouter?Promise.resolve():this.signalingSession.ensureMessageChannelReady(t.requestName)))),v=m((()=>(c.push("[trouterReady]"),d.trouterReady=o.duration(),t.onceTrouterReady&&t.onceTrouterReady(),u(),Promise.resolve()))),S=m((()=>{const i=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,n=this.signalingSession.signalingAgentConfig.enableFetchApi||t.useFetch,r=ao(this.signalingSession.signalingAgentConfig,i,e,t,!1,void 0,this.logger);return c.push("[buildRequest]"),lu({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,tokenRequestOptions:r,requestId:t.requestId,useFetch:n,fetchUseKeepAlive:t.fetchUseKeepAlive},this.logger)})),y=e=>{const t={request:{status:wa.HTTP_STATUS_CODES.OTHER,statusText:"Local error"},attempt:1,success:!1,attemptResponseTimestamp:(new Date).getTime(),attemptStartTimestamp:(new Date).getTime()};let n;e&&(e.skypeTokenError?(t.request={status:wa.CALL_END_SKYPE_TOKEN_ERROR.code,statusText:wa.CALL_END_SKYPE_TOKEN_ERROR.phrase},n=wa.CALL_END_SKYPE_TOKEN_ERROR.subCode):e.tokenError?(t.request={status:wa.CALL_END_TOKEN_ERROR.code,statusText:wa.CALL_END_TOKEN_ERROR.phrase},n=e.errorSubCode&&e.errorSubCode>0?e.errorSubCode:wa.CALL_END_TOKEN_ERROR.subCode):e.tokenTimeoutError&&(i?(t.request={status:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.code,statusText:wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.phrase},n=wa.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.subCode,e.tokenInteractivityRequiredTimeout=!0):(t.request={status:wa.CALL_END_TOKEN_TIMEOUT_ERROR.code,statusText:wa.CALL_END_TOKEN_TIMEOUT_ERROR.phrase},n=wa.CALL_END_TOKEN_TIMEOUT_ERROR.subCode))),g(t,!1,n)},C=m((e=>(c.push("[failedToBuildRequestOptions]"),y(e),Promise.reject(e)))),T=m((e=>(c.push("[requestBuilt]"),d.requestReady=o.duration(),e.usedCachedSkypetoken&&(d.usedCachedSkypetoken=e.usedCachedSkypetoken),u(),Promise.resolve(e)))),E=(n,r,s)=>{c.push("[authRequired]"),s?.IPCAFailure&&(i=!0);const a=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,o=ao(this.signalingSession.signalingAgentConfig,a,e,t,!0,n,this.logger);return o.invalidToken=r,lu({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,forceFetchToken:!0,tokenRequestOptions:o,requestId:t.requestId},this.logger)},b=m((i=>{c.push("[sendRequest]");const n={...s,enableRequestHedging:this.shouldEnableRequestHedging(s),hedgeDelayMs:s.hedgeDelayMs,hedgeMaxParallelAttempts:this.signalingSession.signalingAgentConfig.hedgeMaxParallelAttempts,retryIntervalsMs:t.disableRetry||!s.retryIntervalsMs?[]:s.retryIntervalsMs,reportPreviousErrorsForTimeout:this.signalingSession.signalingAgentConfig.reportPreviousErrorsForTimeout},r=function(e){return new cu(e.causeId,e.logger,e.dispatcher,e.requestType,e.url,e.request,e.attemptFailureCallback,e.authRequiredCallback,e.settings)}({logger:this.logger,causeId:t.causeId,dispatcher:this.signalingSession.signalingAgentConfig.httpRequestDispatcher,url:t.url,request:i,requestType:e,authRequiredCallback:E,attemptFailureCallback:e=>{g(e,!1)},settings:n});return a.dispatcher=r,u(),r.sendRequest()})),_=m((async e=>(g(e,!0),r.info("[success]"),p(!0,t.requestName,t.requestId),e))),I=Promise.resolve().then(f).then(v).then(S).catch(C).then(T).then(b).then(_).catch((e=>{const i=je(e);r.info(`onFailure err:${i}`);let n=e;return e.error?.authCallBackFailure&&(n=e.error,r.info(`authCallBackerror:${je(n)}`),y(n)),p(!1,t.requestName,t.requestId,i),!e||e.readyState||e.status?r.info(`[failed][reason=${i}]`):r.info(`[failed][offline][reason=${i}]`),Promise.reject(n)}));return a.requestPromise=I,I},this.logger=this.signalingSession.logger.createChild("[HTTP]")}getInternalHttpDispatcherConfig(e,t="Other"){let i={...ru.Default,...su[t],...ru[e]};return this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap[t]}),this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap.Default,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap[e]}),this.logger.info(`getInternalHttpDispatcherConfig request type: ${e} config: ${Ge(i)}`),i}shouldEnableRequestHedging(e){return!!(this.signalingSession.getMeetingInfo()&&e.requestHedgingCapability.indexOf("enabledForMeetings")>-1)||!this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForP2PCalls")>-1||!!(this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForGroupCalls")>-1)||e.requestHedgingCapability.indexOf("enabled")>-1}};function hu(e,t,i){Ua(e,"signalingSession cannot be null");let n=[];i&&(n=Ha(i),e.telemetryHelper.addOutgoingModalities(n));const r=Na();return{payload:{mediaNegotiation:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAnswer:Ra(e,ra.MEDIA_ANSWER,r),rejection:Ra(e,ra.MEDIA_REJECTION,r)},mediaContent:t}}}}function gu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{mediaNegotiationFailure:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},code:t.code,subCode:t.subCode,phrase:t.phrase},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}function pu(e,t,i){Ua(e,"signalingSession cannot be null");let n=[];return i&&(n=Ha(i),e.telemetryHelper.addOutgoingModalities(n)),{payload:{mediaAnswer:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAcknowledgement:Ra(e,ra.MEDIA_ACKNOWLEDGEMENT)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}var mu=class{constructor(e,t,i){this.telemetryHelper=i,this.vbssInitiated=!1,this.disposed=!1,this.fsmState=wa.MEDIA_RENEGOTIATION_FSM_STATE.IDLE,this.fsmStateCauseId="",this.links={},this.renegotiationOffersSeenSoFar=[],this.isOutgoingRenegotiationInProgress=()=>this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION||this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.isIncomingRenegotiationInProgress=()=>this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION||this.fsmState===wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.acceptRenegotiationAsync=(e,t,i)=>{this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.signalingSession.telemetryHelper.recordEvent("AcceptRenegotiation",{mediaTypes:t,causeId:i}),Fa(this.links[wa.LINKS.MEDIA_ANSWER],"MediaAnswer link not set");const n=to();switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,i);break;default:return this.logger.info(`[${i}][acceptRenegotiationAsync]there is no incoming media renegotiation offer to accept`),n.reject(new Error("there is no incoming media renegotiation offer to accept")),n.promise}return this.signalingSession.http.sendPostRequest({url:this.links[wa.LINKS.MEDIA_ANSWER],payload:pu(this.signalingSession,e,t),requestName:Zo.SEND_MEDIA_ANSWER.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT,this.handleMediaAnswerAcknowledgmentTimeout.bind(this,i),wa.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT)},causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][acceptRenegotiationAsync] error: ${je(t)}`),this.disposed||this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),n.reject(new Error(`acceptRenegotiationAsync failed because : ${je(e)}`))})),n.promise},this.startRenegotiationAsync=(e,t,i,n)=>{this.logger.info(`[${n}][startRenegotiationAsync][mediaTypes=${i}]`),this.signalingSession.telemetryHelper.recordEvent("StartRenegotiation",{causeId:n,mediaTypes:i}),Fa(t,"MediaRenegotiation link not set");const r=to();switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed with no current outstanding renegotiations, previous negotiation causeId=${this.fsmStateCauseId}`),this.signalingSessionCallback.onMediaRenegotiationRejection(this.getGlareError(),n),Promise.resolve(null);default:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed on an established call`),r.reject(new Error("media renegotiation can only be performed on an established call")),r.promise}const s=i&&Ga(i,wa.MEDIA_TYPES.SCREEN_SHARER);return s?(this.vbssInitiated=!0,this.signalingSession.telemetryHelper.addVbssOperations(fd)):!s&&this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(vd)),this.signalingSession.http.sendPostRequest({url:t,payload:hu(this.signalingSession,e,i),requestName:Zo.START_RENEGOTIATION.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER,this.handleMediaAnswerTimeout.bind(this),wa.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_TIMEOUT)},causeId:n}).then((e=>{r.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${n}][startRenegotiationAsync] error: ${je(t)}`),!this.disposed){switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n)}this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER)}r.reject(new Error(`startRenegotiationAsync failed because : ${je(e)}`))})),r.promise},this.handleMediaAcknowledgment=(e,t)=>{this.signalingSession.telemetryHelper.recordEvent(fo,{causeId:t}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSession.saveMediaControllerLinksIfAny(e),this.signalingSession.saveUpdatedCallLinksIfAny(e),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!0,t)},this.onCallConnected=e=>{this.logger.info("onCallConnected"),this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,e)},this.handleMediaNegotiationFailure=e=>{const t=Qa(e);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleMediaNegotiationFailure",e),this.handleMediaNegotiationFailureInternal(e.body.mediaNegotiationFailure,e.origin,t)},this.handleMediaAnswer=(e,t)=>{switch(this.logger.info(`[${t}][handleMediaAnswer]`),this.signalingSession.telemetryHelper.recordEvent(vo,{causeId:t}),this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,t);break;default:return}this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER);let i=[];e.mediaAnswer.callModalities&&e.mediaAnswer.callModalities.length>0&&(i=Ha(e.mediaAnswer.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i));const n={provisional:!1,renegotiation:!0,mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaAnswer.mediaContent),mediaContent:e.mediaAnswer.mediaContent};this.signalingSession.http.sendPostRequest({url:e.mediaAnswer.links.mediaAcknowledgement,payload:null,requestName:Zo.SEND_MEDIA_ACKNOWLEDGEMENT.name,causeId:t}).catch((e=>{const i=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${t}][handleMediaAnswer] error: ${je(i)}`),this.signalingSession.disposed||this.signalingSession.telemetryHelper.recordEvent("HandleMediaAnswerFailed",{causeId:t})})),this.signalingSessionCallback.onAnswer(n,t)},this.handleMediaNegotiationOffer=e=>{const t=e.body,i=e.headers,n=Qa(e);this.logger.info(`[${n}][handleMediaNegotiationOffer]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleMediaOffer",e);const r=Ja(i,this.renegotiationOffersSeenSoFar);switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,n),this.raiseMediaRenegotiationOffer(t,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n),this.raiseMediaRenegotiationOffer(t,n);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:if(this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.supportMediaRetargetWhileIncomingRenegotiation){this.raiseMediaRenegotiationOffer(t,n);break}this.rejectAndLog(n,r,t);break;default:this.rejectAndLog(n,r,t)}},this.rejectRenegotiationAsync=(e,t)=>{this.logger.info(`[${t}][rejectRenegotiationAsync]`),this.signalingSession.telemetryHelper.recordEvent("RejectRenegotiation",{rejectionData:e,causeId:t}),Fa(this.links[wa.LINKS.MEDIA_REJECTION],"MediaRejection link not set");const i=e||{code:wa.CALL_END_CODE.NOT_ACCEPTABLE_HERE,subCode:wa.CALL_END_SUB_CODE.MEDIA_ANSWER_PROCESSING_ERROR,phrase:wa.CALL_END_PHRASE.MEDIA_ANSWER_ERROR};switch(this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:return this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t),this.rejectMediaRenegotiation(this.links[wa.LINKS.MEDIA_REJECTION],i,t);case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,t),this.rejectMediaRenegotiation(this.links[wa.LINKS.MEDIA_REJECTION],i,t);default:return this.logger.error(`[${t}][rejectRenegotiationAsync][failed] There is no incoming media renegotiation offer to reject`),Promise.resolve(null)}},this.handleRetargetCompleted=e=>{const t=e.body.retargetCompleted,i=Qa(e);this.logger.info(`[${i}][handleRetargetCompleted][details=${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRetargetCompleted",e,$e(t)),0===t.code?this.signalingSessionCallback.onReTargetCompletedSuccess(i):this.signalingSessionCallback.onReTargetCompletedFailure(t,i)},this.dispose=()=>{this.logger.info("mediaRenegotiationManager :: dispose"),this.disposed=!0},this.getGlareError=()=>({code:wa.CALL_END_CODE.GLARE_ERROR,subCode:wa.CALL_END_SUB_CODE.MEDIA_GLARE_ERROR,phrase:wa.CALL_END_PHRASE.RENEGOTIATION_IN_PROGRESS,previousNegotiationCauseId:this.fsmStateCauseId}),this.handleMediaNegotiationFailureInternal=(e,t,i)=>{switch(this.logger.info(`[${i}][handleMediaNegotiationFailureInternal][failureData=${$e(e)}]`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.fsmState){case wa.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case wa.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(wa.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,i);break;default:return}this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(Sd)),this.signalingSession.telemetryHelper.addIncomingModalities(["Rejected"]),this.signalingSessionCallback.onMediaRenegotiationRejection({code:e.code,subCode:e.subCode,phrase:e.phrase},i)},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>`[RenegotiationManager][${this.fsmState}][stateCauseId=${this.fsmStateCauseId}]`))}rejectAndLog(e,t,i){this.logger.error(`[${e}][handleMediaNegotiationOffer] Cannot handle the incoming mediaRenegotiation offer in present callstate. Either call not connected or renegotiation in progress. isDuplicateOffer=${t}`),t||this.rejectMediaRenegotiation(i.mediaNegotiation.links.rejection,this.getGlareError(),e)}setFsmState(e,t){this.fsmState=e,this.fsmStateCauseId=t,this.logger.info(`[setFsmState]state=${e}`),this.telemetryHelper.recordEvent("MediaFsmStateChanged",{state:e,causeId:t})}raiseMediaRenegotiationOffer(e,t){this.logger.info(`[${t}][raiseMediaRenegotiationOffer]`),this.links[wa.LINKS.MEDIA_ANSWER]=e.mediaNegotiation.links.mediaAnswer,this.links[wa.LINKS.MEDIA_REJECTION]=e.mediaNegotiation.links.rejection;let i=[];e.mediaNegotiation.callModalities&&e.mediaNegotiation.callModalities.length>0&&(i=Ha(e.mediaNegotiation.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i),Ga(i,wa.MEDIA_TYPES.SCREEN_SHARER)&&this.signalingSession.telemetryHelper.addVbssOperations(yd));const n={mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaNegotiation.mediaContent),mediaContent:e.mediaNegotiation.mediaContent,renegotiation:!0};this.signalingSessionCallback.onOffer(n,t)}rejectMediaRenegotiation(e,t,i){this.logger.info(`[${i}][rejectMediaRenegotiation][rejectionData=${$e(t)}]`);const n=to();return this.signalingSession.http.sendPostRequest({url:e,payload:gu(this.signalingSession,t),requestName:Zo.SEND_MEDIA_REJECTION.name,causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][rejectMediaRenegotiation] error: ${je(t)}`),n.reject(new Error(`rejectMediaRenegotiation failed because : ${je(e)}`))})),n.promise}handleMediaAnswerTimeout(e){this.logger.info(`[${e}][handleMediaAnswerTimeout]`),this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(Cd)),this.signalingSession.telemetryHelper.addIncomingModalities(["Timeout"]),this.signalingSession.telemetryHelper.recordEvent("HandleMediaAnswerTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.handleMediaNegotiationFailureInternal({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.MEDIA_FINAL_ANSWER_TIMEOUT,phrase:wa.CALL_END_PHRASE.MEDIA_FINAL_ANSWER_TIMEOUT},Xo,e)}handleMediaAnswerAcknowledgmentTimeout(e){this.logger.info(`[${e}][handleMediaAnswerAcknowledgmentTimeout]`),this.signalingSession.telemetryHelper.recordEvent("HandleMediaAcknowledgementTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSessionCallback.onMediaAcknowledgementFailure(!0,{reason:"timed out waiting for Media Answer Acknowledgement"},e)}},fu=class{constructor(){this.requests={}}clear(e,t){const i=t||{code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{this.rejectOperation(t,e,i)}))}hasOperation(e){return this.requests.hasOwnProperty(e)}getAllOperations(){return this.requests}getOperation(e){return this.hasOperation(e)?this.requests[e]:null}setOperation(e,t){return!this.hasOperation(e)&&(this.requests[e]=t,!0)}rejectOperation(e,t,i){const n=new Error(t);if(i&&(n.endCode=i),this.hasOperation(e)){const t=this.requests[e].promise;delete this.requests[e],t.reject(n)}}resolveOperation(e,t){if(this.hasOperation(e)){const i=this.requests[e].promise;delete this.requests[e],i.resolve(t)}}},vu=class{constructor(e){this.logger=e,this.localAddParticipantRequests=new fu,this.localAdmitParticipantRequests=new fu,this.localCallMeBackRequests=new fu,this.localRemoveParticipantEndpointRequests=new fu,this.localRemoveParticipantRequests=new fu,this.localUpdateParticipantInterpretationStateRequest=new fu,this.participantIdMriMap=new Map}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}getAllPendingOperations(e,t){this.logger.info(`[${t}][getAllPendingOperations] ${e}`);const i=this.getOperationTable(e);return i?i.getAllOperations():null}getPendingOperation(e,t,i){this.logger.info(`[${i}][getPendingOperation] ${e} ${t}`);const n=this.getOperationTable(e);return n?n.getOperation(t):null}getRnlMri(e,t){this.logger.info(`[${t}][getRnlMri] ${e}`);for(const t of e)if(this.participantIdMriMap.has(t))return this.participantIdMriMap.get(t);return""}hasPendingOperation(e,t,i){this.logger.info(`[${i}][hasPendingOperation] ${e} ${De(t)}`);const n=this.getOperationTable(e);return!!n&&n.hasOperation(t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${De(t)} reason: ${i}`);const s=this.getOperationTable(e);s&&s.rejectOperation(t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${De(t)}`);const r=this.getOperationTable(e);r&&r.resolveOperation(t,i)}setPendingOperation(e,t,i,n){this.logger.info(`[${n}][setPendingOperation] ${e} ${De(t)} value: ${i}`);const r=this.getOperationTable(e);if(!r)return!1;if(0===e){const e=i&&i.participant&&i.participant.participantId;e&&this.participantIdMriMap.set(e,t)}return r.setOperation(t,i)}setParticipantIdToMriMapping(e,t,i,n){n?(this.logger.info(`[${i}][setParticipantIdMriMap] ${Le(e)}: ${De(t)} clear mapping.`),this.participantIdMriMap.delete(e)):e&&t&&(this.logger.info(`[${i}][setParticipantIdMriMap] ${Le(e)}: ${De(t)}`),this.participantIdMriMap.set(e,t))}getOperationTable(e){switch(e){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(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localAddParticipantRequests.clear(e,t),this.localAdmitParticipantRequests.clear(e,t),this.localCallMeBackRequests.clear(e,t),this.localRemoveParticipantRequests.clear(e,t),this.localRemoveParticipantEndpointRequests.clear(e,t),this.localUpdateParticipantInterpretationStateRequest.clear(e,t)}};function Su(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=i.groupId?{id:i.groupId}:null,s=i.threadId?{threadId:i.threadId,messageId:i.messageId||null}:null;let a=[],o={};t&&t.length>0?(a=t.map((t=>({id:t.nonMaskedId?t.nonMaskedId:t.id,assertedId:t.assertedId,displayName:t.displayName,participantId:t.participantId,replacementDetails:3===i.replacementType?e.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,t.id,t.replacementParticipantId):void 0}))),o={addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)}):o={addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)};const l={payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:a},participantInvitationData:go(i),replacementDetails:3===i.replacementType?void 0:n,groupContext:r,groupChat:s,links:o}};return i&&i.alternateId&&(l.payload.participants.from.alternateId=i.alternateId),i?.callingLineIdentity&&(l.payload.participants.from.callingLineIdentity=i.callingLineIdentity),i?.clientScenario&&(l.payload.debugContent={clientScenario:i.clientScenario}),l}function yu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{admitFailure:Ra(e,ra.CONV_ADMIT_PARTICIPANT_FAILURE),admitSuccess:Ra(e,ra.CONV_ADMIT_PARTICIPANT_SUCCESS)},debugContent:{causeId:i}}}}function Cu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,toEndpoints:[{id:t.id,endpointId:t.endpointId}]},links:{removeParticipantSuccess:Ra(e,ra.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Ra(e,ra.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function Tu(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{removeParticipantSuccess:Ra(e,ra.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Ra(e,ra.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function Eu(e,t,i,n=""){Ua(i&&"specified"===i,"Only non-null non-empty scope of 'specified' is supported."),Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const r=[];return t.forEach((e=>{const t={id:e,meetingRole:n};r.push(t)})),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,to:r}}}var bu=p(Z),_u=class{constructor(e,t){this.participantManager=e,this.logger=t,this.handleRosterUpdate=(e,t,i,n)=>{if("Delta"===e.type||"MultiPartyEndpoint"===e.type){if(void 0===e.sequenceNumber&&(e.sequenceNumber=this.lastRosterUpdateSeqNumber),this.logger.info(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}]`),this.rostersInLifetime.add(e.sequenceNumber),"Delta"===e.type)this.logger.info(`[${n}][handleRosterUpdate], RosterType: Delta, isFullRoster: ${i}`),this.handleDeltaRoster(e,i,t,n);else{if(this.logger.info(`[${n}][handleRosterUpdate], RosterType: MultiPartyEndpoint`),this.isRosterStale(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(Uo,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const i of Object.keys(e.participants)){const r=mo.fromRoster(e.participants[i]);this.handleRosterParticipant(r,t,n)}this.checkForRemovedParticipants(t,e.participants,n),this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n)}if(e.sequenceNumber>this.lastRosterUpdateSeqNumber){this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n),this.lastRosterUpdateSeqNumber=e.sequenceNumber,this.firstRosterUpdateSeqNumber<0&&(this.firstRosterUpdateSeqNumber=this.lastRosterUpdateSeqNumber);const t=Object.keys(e.participants||0).length;this.participantCountInFirstRoster<0&&(this.participantCountInFirstRoster=t),this.maxConcurrentParticipantsDuringLeg=Math.max(this.maxConcurrentParticipantsDuringLeg,t)}this.recordTelemetry(e,i,n),this.participantManager.signalingSessionCallback.onRosterHandlingComplete()}else this.logger.warn(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}] invalid roster type ${e.type}`)},this.isRosterStaleFromFull=(e,t)=>(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastFullRosterSeqNumber}`),e.sequenceNumber<this.lastFullRosterSeqNumber),this.isRosterStale=(e,t)=>(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastRosterUpdateSeqNumber}`),e.sequenceNumber<this.lastRosterUpdateSeqNumber),this.updateLocalParticipantFromSubscribe=(e,t)=>{this.logger.info(`[${t}][updateLocalParticipantFromSubscribe]`),this.updateLocalParticipant(e,t)},this.handleParticipantAcceptedBy=(e,t,i)=>{const n=t.hasOwnProperty(e.id),r=e.id===e.acceptedBy.id;this.logger.info(`[${i}][RosterManager::handleParticipantAcceptedBy] oldParticipantInRoster: ${n}`),this.participantManager.participantOperationHandler.setParticipantIdToMriMapping(e.participantId,e.id,i,!0),n&&!r&&this.handleRemovedDeltaRosterParticipant(new mo({id:e.id}),this.lastRosterUpdateSeqNumber,t,i)},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(e,t,i){const n={participantCountInLastRoster:Object.keys(e.participants||0).length,participantCountInFirstRoster:this.participantCountInFirstRoster,sequenceNumberOfLastRoster:this.lastRosterUpdateSeqNumber,sequenceNumberOfLastFullRoster:this.lastFullRosterSeqNumber,sequenceNumberOfFirstRoster:this.firstRosterUpdateSeqNumber,rosterType:e.type,isFullRoster:t,maxConcurrentParticipantsDuringLeg:this.maxConcurrentParticipantsDuringLeg,totalParticipantsDuringLifetimeOfLeg:this.tombstoneSequence.size+this.latestRosterVersionForActiveParticipants.size,countOfMissingNotifications:this.getMissingNotificiations()};this.logger.info(`[recordTelemetry] data ${JSON.stringify(n,null,4)}`),this.participantManager.signalingSession.telemetryHelper.recordRosterEvent(n,"HandleRosterUpdate",i)}getMissingNotificiations(){const e=this.lastRosterUpdateSeqNumber-this.firstRosterUpdateSeqNumber+1-this.rostersInLifetime.size;return e>0?e:0}isParticipantRosterStale(e,t){if(this.logger.info(`[isParticipantRosterStale], rosterParticipantVersion ${t}`),t){if(this.tombstoneSequence.has(e))return t<=this.tombstoneSequence.get(e);if(this.latestRosterVersionForActiveParticipants.has(e))return t<=this.latestRosterVersionForActiveParticipants.get(e)}return!1}handleDeltaRoster(e,t,i,n){if(this.logger.info(`[${n}][handleDeltaRoster] isFullRoster ${t}`),this.isRosterStaleFromFull(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(Uo,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,lastFullRosterSeqNumber:this.lastFullRosterSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled full roster ${this.lastFullRosterSeqNumber}`);if(t){for(const t of Object.keys(i))if(!e.participants.hasOwnProperty(t)&&!this.isParticipantRosterStale(t,e.sequenceNumber)){const r=new mo({id:t});this.logger.info(`[${n}][handleRosterUpdate] participant missing from delta, full roster`),this.handleRemovedDeltaRosterParticipant(r,e.sequenceNumber,i,n)}this.lastFullRosterSeqNumber=e.sequenceNumber}else if(!e?.participants)return void this.logger.warn(`[${n}][handleRosterUpdate] participants blob empty in delta roster`);for(const t of Object.keys(e.participants)){const r=e.participants[t];if(!this.isParticipantRosterStale(t,r.version)){let e=mo.fromRoster(r);r.state&&"active"===r.state?(this.logger.info(`[${n}][handleDeltaRoster] participant active`),this.handleRosterParticipant(e,i,n),this.tombstoneSequence.has(t)&&this.tombstoneSequence.delete(t),this.latestRosterVersionForActiveParticipants.set(t,r.version)):r.state&&"inactive"===r.state?(e=e||new mo({id:r.details.id}),this.logger.info(`[${n}][handleDeltaRoster] participant inactive`),this.handleRemovedDeltaRosterParticipant(e,r.version,i,n)):this.logger.info(`[${n}][handleDeltaRoster] unexpected participant state ${r.state}`)}}this.handleRemoveParticipantRequests(this.getActiveParticipants(e.participants),n)}getRnlMri(e,t){const i=this.participantManager.participantOperationHandler;if(e){const n=this.getRnlParticipantIdsFromRoster(e,t);return i.getRnlMri(n,t)}return""}handleRemovedDeltaRosterParticipant(e,t,i,n){const r=e.id,s=this.getRnlMri(e,n);let a="";i.hasOwnProperty(r)?a=r:i.hasOwnProperty(s)&&(a=s),a&&this.handleRemovedParticipant(i,a,n),this.tombstoneSequence.set(r,t),this.latestRosterVersionForActiveParticipants.has(r)&&this.latestRosterVersionForActiveParticipants.delete(r)}handleRemovedParticipant(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession;!1!==e[t]&&(za(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][handleRemovedParticipant] ${De(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t))}getActiveParticipants(e){const t={};for(const i of Object.keys(e))"inactive"!==e[i].state&&(t[i]=e[i]);return t}handleRosterParticipant(e,t,i){if(!e)return void this.logger.info(`[handleRosterParticipant][${i}] rosterParticipant processing skipped because null.`);if(e.id===this.participantManager.localParticipant.id){this.updateLocalParticipant(e,i);const t=this.getLocalEndpoint(),n=!(!t?.stream&&!t?.streamLobby),r=0===this.participantManager.signalingSession.callMode;return this.logger.info(`[handleRosterParticipant][${i}] isStreaming:${n} isInitialMode:${r}`),void(n&&r?this.participantManager.signalingSession.configureStreamingMode(i):n||this.participantManager.signalingSession.setRealTimeState(1,i))}const n=this.participantManager.participantOperationHandler,r=this.participantManager.signalingSession,s=this.participantManager.signalingSessionCallback,a=e.id,o=this.getRnlMri(e,i),l=this.getRnlParticipantIdsFromRoster(e,i);r.remoteCaller&&-1!==l.indexOf(r.remoteCaller.participantId)&&(e.displayName=r.remoteCaller.displayName),qa(this.participantManager.connectedRemoteParticipantIds,e.id,!0);const c=t.hasOwnProperty(e.id),d=t.hasOwnProperty(o);(c||d)&&(t[e.id]=!1),n.hasPendingOperation(0,e.id,i)&&this.isParticipantInCall(e)?(this.logger.info(`participant ${De(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e.id),n.resolvePendingOperation(0,e.id,e,i)):o&&n.hasPendingOperation(0,o,i)&&this.isParticipantInCall(e)?(this.logger.info(`RNL participant ${De(o)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,o),n.resolvePendingOperation(0,o,e,i)):n.hasPendingOperation(1,e.id,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant: ${De(e.id)} appears in roster. Resolving AdmitParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),n.resolvePendingOperation(1,e.id,e,i));for(const t of e.endpointDetails)n.hasPendingOperation(0,t.participantId,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant ${De(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t.participantId),n.resolvePendingOperation(0,t.participantId,e,i));c?(this.logger.info(`participantIds=[${l}] updated ${De(e.id)}`),s.onParticipantUpdated(e,i),r.setParticipantCallLinks(e)):d?(this.logger.info(`RNL participant participantIds=[${l}] removed old ${De(o)} and added new ${De(a)}`),s.onParticipantRemoved({id:o},i,!0),r.clearParticipantCallLinks(o),s.onParticipantJoined(e,i),r.setParticipantCallLinks(e)):n.hasPendingOperation(3,e.id,i)?this.logger.info(`participantIds=[${l}] ignored ${De(e.id)}`):(this.logger.info(`participantIds=[${l}] joined ${De(e.id)}`),s.onParticipantJoined(e,i),r.setParticipantCallLinks(e))}getLocalEndpoint(){return bu.find(this.participantManager.localParticipant.endpointDetails,(e=>this.participantManager.localParticipant.endpointId===e.endpointId))}getRnlParticipantIdsFromRoster(e,t){const i=[];for(const t of e.endpointDetails)i.push(t.participantId);return this.logger.info(`[${t}][getRnlParticipantIdsFromRoster] ${JSON.stringify(i)}`),i}isParticipantInCall(e){return e.endpointDetails?.[0]&&!e.endpointDetails[0].isLobby}updateLocalParticipant(e,t){const i=this.participantManager.localParticipant,n=this.participantManager.signalingSession,r=this.participantManager.signalingSessionCallback;n.setParticipantCallLinks(e),this.logger.info(`[${t}][updateLocalParticipant]`);let s=!1;if(e?.endpointDetails){const a=bu.find(e.endpointDetails,(e=>i.endpointId===e.endpointId)),o=bu.find(i.endpointDetails,(e=>i.endpointId===e.endpointId));s=Fd(a),a?.isLobby&&!o?.isLobby?n.telemetryHelper.recordEvent("InLobby",{causeId:t}):!a||a.isLobby||o&&!o.isLobby||(s?n.telemetryHelper.recordEvent("Staging",{causeId:t}):n.telemetryHelper.recordEvent("Connected",{causeId:t})),a?.broadcastMeetingRole&&i&&i.broadcastMeetingRole!==a.broadcastMeetingRole&&(i.broadcastMeetingRole=a.broadcastMeetingRole,n.telemetryHelper.setBroadcastMeetingRole(a.broadcastMeetingRole)),r.onMeetingGroupDetailsUpdated(a?.meetingGroupDetails,t)}if(e?.meetingRole&&n.telemetryHelper.setMeetingRole(e.meetingRole),e?.advancedMeetingRole&&n.telemetryHelper.setAdvancedMeetingRole(e.advancedMeetingRole),e?.meetingRoles&&n.telemetryHelper.setMeetingRoles(e.meetingRoles),e?.participantType&&n.telemetryHelper.setParticipantType(e.participantType),e&&(i.endpointDetails=e.endpointDetails||[],i.acceptedBy=e.acceptedBy,i.role=e.role,i.meetingRole=e.meetingRole,i.advancedMeetingRole=e.advancedMeetingRole,i.meetingRoles=e.meetingRoles,i.participantType=e.participantType,i.tenantId=e.tenantId,i.isLobby=e.isLobby,i.publishedStates=e.publishedStates,i.isStaging=s,i.version=e.version,i.propertyBag=e.propertyBag,i.isIdentityMasked=e.isIdentityMasked,i.maskedIdSeqNumber=e.maskedIdSeqNumber,i.maskedId=e.maskedId,void 0!==e?.joinAsStreamingUser&&(i.joinAsStreamingUser=e.joinAsStreamingUser),void 0!==e?.enableCaptcha&&(i.enableCaptcha=e.enableCaptcha),void 0!==e?.otpIdentity&&(i.otpIdentity=e.otpIdentity),this.participantManager.localParticipant.fromRoster=!0,r.onSelfParticipantUpdated(i,t)),this.isParticipantInCall(e)){const i=this.participantManager.participantOperationHandler,r=this.getRnlMri(e,t);r&&i.hasPendingOperation(0,r,t)&&(this.logger.info(`RNL participant ${De(r)} appears in roster. Resolving AddParticipant request`),n.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,r),i.resolvePendingOperation(0,r,e,t))}}checkForRemovedParticipants(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession,s=this.participantManager.participantOperationHandler;this.logger.info(`[${i}][checkForRemovedParticipants]`);for(const t of Object.keys(e))e.hasOwnProperty(t)&&!1!==e[t]&&!s.hasPendingOperation(0,t,i)&&(za(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][checkForRemovedParticipants] ${De(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t));this.handleRemoveParticipantRequests(t,i)}handleRemoveParticipantRequests(e,t){const i=this.participantManager.signalingSession,n=this.participantManager.participantOperationHandler;this.logger.info(`handleRemoveParticipantRequests [${t}] dynamicRosterParticipants`);const r=[];Object.keys(e).forEach((t=>{const i=mo.fromRoster(e[t]);i&&i.endpointDetails&&i.endpointDetails.forEach((e=>{e.originalId&&r.push(e.originalId)}))}));const s=n.getAllPendingOperations(3,t);for(const a of Object.keys(s))-1!==r.indexOf(a)||e.hasOwnProperty(a)||(this.logger.info(`[${t}][handleRemoveParticipantRequests] ${De(a)} no longer appears in roster. Resolving RemoveParticipant request`),za(this.participantManager.connectedRemoteParticipantIds,a),i.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,a),n.resolvePendingOperation(3,a,{id:a},t))}},Iu=class{constructor(e,t,i,n){this.connectedRemoteParticipantIds={},this.disposed=!1,this.unmuteApprovalLinks={},this._asyncMuteUnmuteDefers=new Map,this.muteAsyncEnabled=!1,this.unmuteAsyncEnabled=!1,this.setLocalParticipantId=(e,t)=>{e&&(this.logger.info(`[${t}][setLocalParticipantId][participantId=${e}]`),this.localParticipant.participantId=e,this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId))},this.setEnableMuteAsync=e=>{this.muteAsyncEnabled=e},this.setEnableUnmuteAsync=e=>{this.unmuteAsyncEnabled=e},this.admitParticipantAsync=(e,t,i)=>{const n=`[${i}][admitParticipantAsync]`;this.logger.info(`${n}${this.piiUtils.scrubMriOrOmit(e.id)}`);const r=to();return this.participantOperationHandler.hasPendingOperation(1,e.id,i)?(this.logger.info(`${n}there is an existing pending request to admit the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),r.reject(new Error("there is an existing pending request to admit the participant"))):(this.participantOperationHandler.setPendingOperation(1,e.id,{participant:e,promise:r,causeId:i},i),this.sendNetworkRequestForAdmittingParticipant(e,t,i)),r.promise},this.addParticipantsAsync=(e,t,i,n,r)=>{const s=`[${r}][addParticipantsAsync]`,a=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${s} remoteParticipantsIds: ${a}`);const o=[],l=[];return e.forEach((e=>{const t=to(),i=3===n.replacementType?e.participantId:e.id;this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`${s}the given participant is already connected to the call ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(0,i,r)?(this.logger.info(`${s}there is an existing pending request to add the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to add the participant"))):(e.participantId||(e.participantId=La(),this.logger.info(`participantId created ${e.participantId}`)),this.participantOperationHandler.setPendingOperation(0,i,{participant:e,promise:t,causeId:r},r),o.push(e)),l.push(t.promise)})),i&&this.sendNetworkRequestForAddingParticipant(o,t,n,r),l},this.nudgeParticipantsAsync=(e,t,i,n,r,s,a,o)=>(this.logger.info(`[${n}][nudgeParticipantAsync] ${this.piiUtils.scrubParticipantsList(e)}`),i?this.sendNetworkRequestForNudgingParticipants(e,t,n,r,s,a,o):Promise.reject(`[${n}][nudgeParticipantAsync] Call not started`)),this.updateMeetingRolesAsync=(e,t,i,n=Na())=>{const r=to();if(!e||e.length<1){const e=`[${n}][updateMeetingRolesAsync] participantsInfo cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else if(t)if(i){let s;"attendee"===t?s=Zo.UPDATE_MEETING_ROLE_ATTENDEE.name:"presenter"===t?s=Zo.UPDATE_MEETING_ROLE_PRESENTER.name:"organizer"===t?s=Zo.UPDATE_MEETING_ROLE_ORGANIZER.name:r.reject(new Error(`[${n}] Invalid meetingRole value(${t})`)),this.logger.info(`[${n}][updateMeetingRolesAsync][meetingRole=${t}]`),this.signalingSession.ensureMessageChannelReady(s).then((()=>{this.sendNetworkRequestForUpdatingMeetingRoles(e,t,i,s,n,r)})).catch((e=>{const t=je(e);this.logger.info(`[${n}][updateMeetingRolesAsync][failed][reason=${t}]`);const i={...Ka(e,this.signalingSession.signalingAgentConfig).error};r.reject(i)}))}else{const e=`[${n}][updateMeetingRolesAsync] updateMeetingRoleUrl cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else{const e=`[${n}][updateMeetingRolesAsync] meetingRole cannot be empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}return r.promise},this.updateParticipantInterpretationStateAsync=(e,t,i)=>{const n=`[${i}][updateParticipantInterpretationStateAsync]`,r=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${n} remoteParticipantsIds: ${r}`);const s=[],a=[];return e.forEach((e=>{const t=to();this.participantOperationHandler.hasPendingOperation(5,e.id,i)?(this.logger.info(`${n}there is an existing pending request to update the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to update the participant"))):(this.participantOperationHandler.setPendingOperation(5,e.id,{option:e,promise:t,causeId:i},i),s.push(e)),a.push(t.promise)})),this.sendNetworkRequestToUpdateParticipantInterpretationState(s,t,e,i),a},this.callMeBackAsync=(e,t,i)=>{this.logger.info(`[${i}][callMeBackAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`);const n=to();return this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`the given participant is already connected to the call : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(2,e.id,i)?(this.logger.info(`there is an existing pending request to call back the participant : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to call back the participant"))):(this.participantOperationHandler.setPendingOperation(2,e.id,{participant:e,promise:n},i),this.sendNetworkRequestForCallMeBack(e,t,i)),n.promise},this.isRosterStale=(e,t)=>this.rosterManager.isRosterStale(e,t),this.removeParticipantAsync=(e,t,i)=>{this.logger.info(`[${i}][removeParticipantAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`),Fa(t,"correct removeParticipantUrl is not provided");const n=to();if(this.participantOperationHandler.hasPendingOperation(3,e.id,i))this.logger.info(`there is an existing pending request to remove the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to remove the participant"));else{this.participantOperationHandler.setPendingOperation(3,e.id,{participant:e,promise:n},i);const r=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession.telemetryHelper.recordEvent(Eo),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,"timed out waiting for participant to not show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},i)}),wa.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:Tu(this.signalingSession,e),requestName:Zo.REMOVE_PARTICIPANT_NONE.name,onceTrouterReady:r,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][removeParticipantAsync][failed][reason=${je(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,t,n.error,i))}))}return n.promise},this.removeParticipantEndpointAsync=(e,t,i,n)=>{this.logger.info(`[${n}][removeParticipantEndpointAsync] ${qe(e.endpointId,8)} [endPointScope] ${i}`),Fa(t,"correct removeParticipantUrl is not provided");const r=to();let s="";switch(i){case"all":s=Zo.REMOVE_PARTICIPANT_OTHERS.name;break;case"specified":s=Zo.REMOVE_PARTICIPANT_SPECIFIED.name;break;default:return Promise.reject(`invalid scope ${i} removeParticipantEndpointAsync`)}return this.participantOperationHandler.setPendingOperation(4,e.endpointId,{participant:e,promise:r,scope:i},n),this.signalingSession.http.sendPostRequest({url:t,payload:Cu(this.signalingSession,e,i),requestName:s,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(Eo),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,"timed out waiting for participant endpoint sync response from service",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},n))}),wa.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.endpointId)},causeId:n}).then((e=>{if(e.response?.code)if(-1!==[wa.HTTP_STATUS_CODES.OK,wa.HTTP_STATUS_CODES.CREATED].indexOf(e.response.code))this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [passed][reason=${je(e.response)}]`),r.resolve(e.response);else{const t=new Error("invalid service response for removeParticipantEndpoint");t.endCode={code:e.response.code,subCode:e.response.subcode,phrase:e.response.reason},this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${je(e.response)}]`),r.reject(t)}r.resolve()})).catch((t=>{const r=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${je(r)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,je(t),r.error,n))})),r.promise},this.getParticipantsToInitiateCallWith=()=>{this.logger.info("getParticipantsToInitiateCallWith");const e=[],t=this.participantOperationHandler.getAllPendingOperations(0,Na());for(const i of Object.keys(t))t.hasOwnProperty(i)&&t[i]&&e.push(t[i].participant);return e},this.initializeForIncomingCall=e=>{this.logger.info("initializeForIncomingCall"),this.participantOperationHandler.dispose("incoming calls cannot add/remove participants until call is connected",null,Na())},this.handleAddParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddParticipantSuccess(${t.participantInfos?"new format":"old format"})]${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(bo,e),this.internalHandleCallMeBackSuccess(t,i)||this.signalingSession.telemetryHelper.recordEvent(bo),this.signalingSession.signalingAgentConfig.enableAddParticipantEnhancements&&this.internalHandleAcceptedByParticipants(t,i)},this.handleAddParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddParticipantFailure(${t.participantInfos?"new format":"old format"})][${je(t)}]`),t.modalityFailure?(this.logger.info(`[${i}][handleAddParticipantFailure][modalityFailure=${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAddParticipantModalityFailure",e)):this.internalHandleAddParticipantFailure(e,i)},this.handleAdmitParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAdmitParticipantSuccess][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAdmitParticipantSuccess",e),t.participants&&this.internalHandleAdmitParticipantSuccess(e,i)},this.handleAdmitParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAdmitParticipantFailure][${je(t)}]`),t.participants&&this.internalHandleAdmitParticipantFailure(e,i)},this.handleRemoveParticipantFailure=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleRemoveParticipantFailure][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRemoveParticipantFailure",e);for(const e of Object.keys(t.participants))t.participants.hasOwnProperty(e)&&this.internalHandleRemoveParticipantFailure(e,t.participants[e],i)},this.handleRemoveParticipantSuccess=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleRemoveParticipantSuccess][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleRemoveParticipantSuccess",e)},this.handleUnmuteConfirmRequest=e=>{const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleUnmuteConfirmRequest][${je(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleUnmuteConfirm",e),this.unmuteApprovalLinks[t.from.id]={approve:t.links.approveUnmute,reject:t.links.rejectUnmute},this.signalingSessionCallback.onUnmuteRequested(t.from.id,i)},this.approveUnmuteRequestAsync=(e,t)=>{this.logger.info(`[${t}][approveUnmuteRequestAsync]`);const i=to();return this.unmuteApprovalLinks.hasOwnProperty(e)?(this.signalingSession.ensureMessageChannelReady(Zo.APPROVE_UNMUTE.name).then((()=>{this.muteUnmute(Zo.APPROVE_UNMUTE.name,function(e){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]}}}(this.signalingSession),i,this.unmuteApprovalLinks[e].approve,t)})).catch((e=>{const n=je(e);this.logger.info(`[${t}][approveUnmuteRequestAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise):(i.reject(new Error("no unmute links found for given participant")),i.promise)},this.rejectUnmuteRequestAsync=(e,t,i)=>{this.logger.info(`[${t}][rejectUnmuteRequestAsync]`);const n=to();if(!this.unmuteApprovalLinks.hasOwnProperty(e))return n.reject(new Error("no unmute links found for given participant")),n.promise;const r=i||{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UNMUTE_REQUEST_REJECTED,phrase:wa.CALL_END_PHRASE.UNMUTE_REQUEST_REJECTED};return this.signalingSession.ensureMessageChannelReady(Zo.REJECT_UNMUTE.name).then((()=>{this.muteUnmute(Zo.REJECT_UNMUTE.name,function(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{transactionEnd:t}}}(this.signalingSession,r),n,this.unmuteApprovalLinks[e].reject,t)})).catch((e=>{const i=je(e);this.logger.info(`[${t}][rejectUnmuteRequestAsync][failed][reason=${i}]`),n.reject(new Error(e))})),n.promise},this.handleRosterUpdate=(e,t,i)=>{const n=this.getCurrentParticipantsInCallModality(!1);this.rosterManager.handleRosterUpdate(e,n,t,i)},this.updateLocalParticipantFromSubscribe=(e,t)=>{this.localParticipant.fromRoster||this.rosterManager.updateLocalParticipantFromSubscribe(e,t)},this.muteAsync=(e,t,i,n)=>{this.logger.info(`[${n}][muteAsync][muteScope=${t}]`);let r="specified";const s=[];let a=Zo.MUTE_SPECIFIED;switch(t){case wa.MUTE_SCOPE.MYSELF:a=Zo.MUTE_MYSELF,s.push({id:this.localParticipant.id});break;case wa.MUTE_SCOPE.EVERYONE_ELSE:a=Zo.MUTE_ALL_SYNC,r="all",i.forEach((e=>{s.push({id:e})}));break;case wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS:Fa(i,`[${n}]array of participantIds must be specified for SPECIFIED_PARTICIPANTS mute scope`),a=Zo.MUTE_SPECIFIED_SYNC,i.forEach((e=>{s.push({id:e})}));break;default:xa(!1,`[${n}]muteScope is a required param. please pass in a valid value.`)}const o=to();if(t===wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS){const e=this.areParticipantsConnectedToCall(i);if(!e.result)return o.reject(new Error(`[${n}]specified participant is not connected to call yet. Id = ${e.participant}`)),o.promise}const l=this.muteAsyncEnabled&&(t===wa.MUTE_SCOPE.SPECIFIED_PARTICIPANTS||t===wa.MUTE_SCOPE.EVERYONE_ELSE);return this.signalingSession.ensureMessageChannelReady(a.name).then((()=>{this.muteUnmute(a.name,function(e,t,i,n=!1,r=null){Ua(e,"signalingSession cannot be null"),Ua(t,"muteScope be null"),Ua(i,"participantList cannot be null");const s={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t,muteParticipants:i,mediaTypes:["audio"]};return n&&(s.links={clientCallback:Ra(e,ra.MUTE_UNMUTE_ASYNC,r)},s.operationId=r),{payload:s}}(this.signalingSession,r,s,l,n),o,e,n,!1,l)})).catch((e=>{const t=je(e),i=Ka(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][muteAsync][failed][reason=${t}]`),o.reject(i)})),o.promise},this.unmuteAsync=(e,t)=>{this.logger.info(`[${t}][unmuteAsync]`);const i=to();return this.signalingSession.ensureMessageChannelReady(Zo.UNMUTE_SYNC.name).then((()=>{this.muteUnmute(Zo.UNMUTE_SYNC.name,function(e,t=!1,i=null){Ua(e,"signalingSession cannot be null");const n={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]};return t&&(n.links={clientCallback:Ra(e,ra.MUTE_UNMUTE_ASYNC,i)},n.operationId=i),{payload:n}}(this.signalingSession,this.unmuteAsyncEnabled,t),i,e,t,!0,this.unmuteAsyncEnabled)})).catch((e=>{const n=je(e);this.logger.info(`[${t}][unmuteAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise},this.dispose=(e,t)=>{this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.participantOperationHandler.dispose("call ended",e,t),this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId),this._asyncMuteUnmuteDefers.forEach(((t,i)=>{t.reject(e)})),this._asyncMuteUnmuteDefers.clear()},this.handleMuteUnmuteAsyncResponse=e=>{const t=Qa(e),i=this.logger.createFnLogger("handleMuteUnmuteAsyncResponse",t);if(!e.body)return void i.error("ignored. Empty message body.");const n={info:e.body.muteUnmuteResponseAsync,operationId:e.body.operationId};if(i.info(`Received async response for mute/unmute operation, operation id = ${n.operationId}.`),this.disposed)return void i.info("ignored. Call disposed.");if(!n.operationId)return void i.error("operationId is undefined.");const r=this._asyncMuteUnmuteDefers.get(n.operationId);r?(r.resolve(n),this._asyncMuteUnmuteDefers.delete(n.operationId)):i.warn(`cannot find deferred promise for operation id [${n.operationId}].`)},this.internalHandleAcceptedByParticipants=(e,t)=>{if(e?.participantInfos){const i=e.participantInfos,n=this.getCurrentParticipantsInCallModality(!1);this.logger.info(`[${t}][internalHandleAcceptedByParticipants] handling participants with acceptedBy blob.`);for(const e of i)if(e?.acceptedBy){const i=e.id;this.participantOperationHandler.hasPendingOperation(0,i,t)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,i),this.logger.info(`[${t}][internalHandleAcceptedByParticipants] ${this.piiUtils.scrubMriOrOmit(i)} added using a different MRI. Resolving operation.`),this.participantOperationHandler.resolvePendingOperation(0,i,void 0,t)),this.rosterManager.handleParticipantAcceptedBy(e,n,t)}}},this.internalHandleCallMeBackSuccess=(e,t)=>{let i=!1;if(e?.participantInfos){const n=e.participantInfos;for(const e of n){const n=e.id;this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0)}}else if(e?.participants)for(const n of e.participants)this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0);return i},this.signalingSession=e,this.signalingSessionCallback=t,this.localParticipant=i,this.localParticipant.endpointId||(this.localParticipant.endpointId=this.signalingSession.getEndpointId());const r=qe(this.localParticipant.endpointId,8);this.logger=n.createChild((()=>`[PM][${r}]`)),this.piiUtils=e.piiUtils,this.participantOperationHandler=new vu(e.logger.createChild((()=>`[ParticipantOperationHandler][${r}]`))),this.rosterManager=new _u(this,e.logger.createChild((()=>`[RosterManager][${r}]`))),this.localParticipant.participantId||(this.localParticipant.participantId=La()),"string"==typeof e.signalingAgentConfig.languageCode?this.localParticipant.languageId=e.signalingAgentConfig.languageCode:"function"==typeof e.signalingAgentConfig.languageCode&&(this.localParticipant.languageId=e.signalingAgentConfig.languageCode()),e.telemetryHelper.setParticipantId(this.localParticipant.participantId),e.telemetryHelper.setEndPointId(this.localParticipant.endpointId)}handleUpdateParticipantInterpretationStateCompletion(e){const t=e.body,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateParticipantInterpretationStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] starts`);const r=e.body;if(r.participantInfos)for(const t of r.participantInfos)if(this.logger.info(t),this.participantOperationHandler.hasPendingOperation(5,t.participant.id,i))if(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,t.participant.id),t.transactionEnd.code===wa.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}]Update participant interpretation state succeeded for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)}`),this.signalingSession.telemetryHelper.recordIncomingEvent("UpdateParticipantInterpretationStateResponseCompleted",e),this.participantOperationHandler.resolvePendingOperation(5,t.participant.id,void 0,i);else{const n=t.transactionEnd.reason;this.logger.info(`[${i}]Update participant interpretation state failed for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)} reason : ${je(n)}`);const r=this.getCallEndGivenParticipantFailure(n);this.signalingSession.telemetryHelper.recordIncomingEvent("UpdateParticipantInterpretationStateResponseFailed",e,r),this.participantOperationHandler.rejectPendingOperation(5,t.participant.id,r.phrase,r,i)}}setEnableCaptcha(e,t){this.logger.info(`[${t}][setEnableCaptcha] value:${e}`),this.localParticipant.enableCaptcha=e,this.signalingSessionCallback.onSelfParticipantUpdated(this.localParticipant,t)}areParticipantsConnectedToCall(e){this.logger.info(`areParticipantsConnectedToCall : ${je(e)}`);const t=this.getCurrentParticipantsInCallModality(!0);for(const i of e)if(!t.hasOwnProperty(i))return this.logger.info(`areParticipantsConnectedToCall : returning false for :${this.piiUtils.scrubMriOrOmit(i)}`),{result:!1,participant:i};return this.logger.info("areParticipantsConnectedToCall : returning true"),{result:!0}}muteUnmute(e,t,i,n,r,s,a=!1){const o=this.logger.createFnLogger("muteUnmute",r);xa(2!==this.signalingSession.callMode,"mute/unmute operations are not allowed in streaming mode"),o.info(`operation=${e}, isAsync=${a}`),n?(s&&this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UNMUTE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent("UnmuteTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNMUTE);const e=new Error("timed out waiting for response to request");e.endCode={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UNMUTE_REQUEST_TIMEOUT,phrase:wa.CALL_END_PHRASE.UNMUTE_REQUEST_TIMEOUT},i.reject(e)}}),wa.TIMEOUT_VALUES_IN_SECONDS.UNMUTE_TIMEOUT),a&&this._asyncMuteUnmuteDefers.set(r,i),this.signalingSession.http.sendPostRequest({url:n,payload:t,requestName:e,withoutTrouter:!0,causeId:r}).then((t=>{if(!this.disposed)if(a)o.info(`Inline response received for async operation, operation id: ${r}.`);else{if(t.response?.muteUnmuteResponse){const n={info:t.response.muteUnmuteResponse,operationId:t.response.operationId};switch(e){case Zo.UNMUTE_SYNC.name:case Zo.MUTE_ALL_SYNC.name:case Zo.MUTE_SPECIFIED_SYNC.name:i.resolve(n)}}i.resolve()}})).catch((e=>{const t=Ka(e,this.signalingSession.signalingAgentConfig);o.info(`operation failed, reason=${je(t)}`),this.disposed||(s&&this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNMUTE),i.reject(t.error))}))):i.reject(new Error(`[${r}][muteUnmute] cannot be performed now, the link is not yet available`))}sendNetworkRequestForUpdatingMeetingRoles(e,t,i,n,r,s){if(!i){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because correct updateMeetingRoleUrl is not provided`;new Error(e).endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),s.reject()}if(!e){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because participants list is empty or null`,t=new Error(e);t.endCode={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),s.reject(t)}this.signalingSession.http.sendPostRequest({url:i,payload:Eu(this.signalingSession,e,"specified",t),requestName:n,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent("UpdateMeetingRole",{causeId:r}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE);const e=new Error(`[${r}] Timed out waiting for response to request`);e.endCode={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_ROLE_TIMEOUT},s.reject(e)}}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_ROLE_TIMEOUT)},causeId:r}).then((e=>{s.resolve(e.response)})).catch((e=>{const t=je(e);this.logger.info(`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed: ${t}`);const i=new Error(`[${r}][CS response] Forbidden request`),n=Ka(e,this.signalingSession.signalingAgentConfig);i.code=n.error.code,i.subCode=n.error.subCode,i.phrase=n.error.phrase,this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE),s.reject(i))}))}sendNetworkRequestForNudgingParticipants(e,t,i,n,r,s,a){if(t){const o=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("NudgeParticipantTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""))}),wa.TIMEOUT_VALUES_IN_SECONDS.NUDGE_PARTICIPANT_TIMEOUT,e?e.join():"")},l=s||r?function(e,t,i,n,r,s){Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const a=e.groupId?{id:e.groupId}:null,o=n?{threadId:n,messageId:r||null}:null,l=[];return t.forEach((e=>{const t={id:e};l.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:wa.INVITATION_TYPE.NUDGE,to:l},participantInvitationData:s,groupContext:a,groupChat:o,links:{nudgeParticipantSuccess:Ra(e,ra.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Ra(e,ra.CONV_NUDGE_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,0,s,a,n):function(e,t,i){Ua(e,"signalingSession cannot be null"),Ua(t,"participantsIds cannot be null");const n=[];return t.forEach((e=>{const t={id:e};n.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:wa.INVITATION_TYPE.NUDGE,to:n},participantInvitationData:i,links:{nudgeParticipantSuccess:Ra(e,ra.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Ra(e,ra.CONV_NUDGE_PARTICIPANT_FAILURE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,n);return this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:Zo.NUDGE_PARTICIPANT.name,onceTrouterReady:o,causeId:i}).then((()=>{})).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant][failed][reason=${je(n)}]`),this.disposed||this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""),Promise.reject(n.error)}))}return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant] failed because correct nudgeParticipantUrl is not provided`),Promise.reject("Missing nudgeParticipant url")}sendNetworkRequestForAddingParticipant(e,t,i,n=Na()){if(t){let r=Zo.ADD_PARTICIPANT.name,s=yo,a={};switch(i.replacementType){case 2:r=Zo.ADD_PARTICIPANT_WITH_PICKUP_CODE.name,s="AddParticipantWithPickupCodeTimeout",a.unparkContent={pickupCode:i.pickupCode};break;case 1:r=Zo.ADD_PARTICIPANT_WITH_REPLACES.name,s=Co,a=this.signalingSession.getCallReplacementDetailsForCall(i.callIdToReplace,n);break;case 3:r=Zo.ADD_PARTICIPANT_WITH_REPLACES.name,s=Co,a=this.signalingSession.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,e[0].id,e[0].replacementParticipantId,n);break;default:r=Zo.ADD_PARTICIPANT.name,s=yo,a=null}const o=()=>{e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(s,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t),this.participantOperationHandler.rejectPendingOperation(0,t,"timed out waiting for participant to show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},n))}),wa.TIMEOUT_VALUES_IN_SECONDS.ADD_PARTICIPANT_TIMEOUT,t)}))},l=i.threadId||i.groupId?Su(this.signalingSession,e,i,a):function(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=t.map((e=>(Ua(e,"remoteParticipant cannot be null"),{id:e.id,assertedId:e.assertedId,displayName:e.displayName,participantId:e.participantId})));return{payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,alternateId:i?i.alternateId:null,callingLineIdentity:i?i.callingLineIdentity:null},to:r},participantInvitationData:go(i),replacementDetails:n,links:{addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE)},debugContent:{clientScenario:i.clientScenario}}}}(this.signalingSession,e,i,a);this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:r,onceTrouterReady:o,causeId:n}).catch((t=>{const r=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestForAddingParticipant] failed:${je(t)}`),this.disposed||e.forEach((e=>{const s=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,s),this.participantOperationHandler.rejectPendingOperation(0,s,t,r.error,n)}))}))}else this.logger.info(`[${n}][sendNetworkRequestForAddingParticipants] failed because correct addParticipantUrl is not provided`),e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.participantOperationHandler.rejectPendingOperation(0,t,"correct addParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},n)}))}sendNetworkRequestToUpdateParticipantInterpretationState(e,t,i,n=Na()){if(t){const r=Zo.UPDATE_PARTICIPANT_INTERPRETATION_STATE.name,s="UpdateParticipantInterpretationStateTimeout",a=()=>{const t={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT};e.forEach((e=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] timed out`),this.signalingSession.telemetryHelper.recordEvent(s,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,"timed out waiting to update particiant interpretation state",t,n))}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT,e.id)}))},o=function(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(t,"options cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id},to:t,links:{updateParticipantInterpretationStateStatus:Ra(e,ra.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS)},operationId:i}}}(this.signalingSession,i,n);this.signalingSession.http.sendPostRequest({url:t,payload:o,requestName:r,onceTrouterReady:a,causeId:n}).catch((t=>{const i=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed:${je(t)}`),this.disposed||e.forEach((e=>{this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,t,i.error,n)}))}))}else{this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed because correct updateParticipantUrl is not provided`);const t={code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING};e.forEach((e=>{this.participantOperationHandler.rejectPendingOperation(5,e.id,"correct updateParticipantUrl is not provided",t,n)}))}}sendNetworkRequestForCallMeBack(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("CallMeBackTimeout",{causeId:i}),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,"timed out waiting for call me back success response",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),wa.TIMEOUT_VALUES_IN_SECONDS.CALL_ME_BACK_TIMEOUT,e.id)},r={groupId:this.signalingSession.groupId,threadId:this.signalingSession.threadId,messageId:this.signalingSession.teamsMessageId};this.signalingSession.http.sendPostRequest({url:t,payload:Su(this.signalingSession,[e],r),requestName:Zo.CALL_ME_BACK.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed: ${je(n)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed because correct addParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(2,e.id,"correct addParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},i)}sendNetworkRequestForAdmittingParticipant(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent("AdmitParticipantTimeout"),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,"timed out waiting for participant to show up in roster",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),wa.TIMEOUT_VALUES_IN_SECONDS.ADMIT_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:yu(this.signalingSession,e,i),requestName:Zo.ADMIT_PARTICIPANT.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=Ka(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant][failed][reason=${je(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant] failed because correct admitParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(1,e.id,"correct admitParticipantUrl is not provided",{code:wa.CALL_END_CODE.LOCAL_ERROR,subCode:wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:wa.CALL_END_PHRASE.ADMIT_PARTICIPANT_URL_MISSING},i)}getCurrentParticipantsInCallModality(e){const t={},i=[wa.PARTICIPANT_AUDIO_STATE.CONNECTED];return e||i.push(wa.PARTICIPANT_AUDIO_STATE.CONNECTING,wa.PARTICIPANT_AUDIO_STATE.RINGING),this.signalingSessionCallback.getRemoteParticipantCollection()?.forEach((e=>{i.some((t=>t===e.audioState))&&(t[e.mri]=!0)})),t}internalHandleRemoveParticipantFailure(e,t,i){if(this.participantOperationHandler.hasPendingOperation(3,e,i)){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e),this.logger.info(`[${i}][internalHandleRemoveParticipantFailure] failed for ${this.piiUtils.scrubMriOrOmit(e)} reason ${je(t)}`);const n=this.getCallEndGivenParticipantFailure(t);this.participantOperationHandler.rejectPendingOperation(3,e,n.phrase,n,i)}}internalHandleCallMeBackSuccessHelper(e,t){if(this.participantOperationHandler.hasPendingOperation(2,e,t)){const i={id:e};return this.logger.info(`participant : ${this.piiUtils.scrubMriOrOmit(e)} was successfully added. Resolving CallMeBack request`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.participantOperationHandler.resolvePendingOperation(2,i.id,i,t),!0}return!1}internalHandleAddParticipantFailure(e,t=Na()){const i=e.body;if(i.participantInfos)i.participantInfos.forEach((i=>{const n=[i.participant.participantId],r=this.participantOperationHandler.getRnlMri(n,t)||i.participant.id;this.rejectAddParticipantFailure(r,i.transactionEnd,e,t)}));else if(i.participants)for(const n of Object.keys(i.participants))this.rejectAddParticipantFailure(n,i.participants[n],e,t)}rejectAddParticipantFailure(e,t,i,n){const r=this.getCallEndGivenParticipantFailure(t);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAddParticipantFailure",i,r),this.participantOperationHandler.hasPendingOperation(0,e,n)?(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e),this.logger.info(`participantAdd failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${je(t)}`),this.participantOperationHandler.rejectPendingOperation(0,e,r.phrase,r,n)):this.participantOperationHandler.hasPendingOperation(2,e,n)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.logger.info(`callMeBack failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${je(t)}`),this.participantOperationHandler.rejectPendingOperation(2,e,r.phrase,r,n))}internalHandleAdmitParticipantSuccess(e,t){const i=e.body;for(const e of i.participants)this.participantOperationHandler.hasPendingOperation(1,e,t)&&(this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e),this.logger.info(`Admit participant success for : ${this.piiUtils.scrubMriOrOmit(e)}`),this.participantOperationHandler.resolvePendingOperation(1,e,void 0,t))}internalHandleAdmitParticipantFailure(e,t){const i=e.body;for(const n of Object.keys(i.participants))if(this.participantOperationHandler.hasPendingOperation(1,n,t)){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,n);const r=i.participants[n];this.logger.info(`Admit participant failed for : ${this.piiUtils.scrubMriOrOmit(n)} reason : ${je(r)}`);const s=this.getCallEndGivenParticipantFailure(r);this.signalingSession.telemetryHelper.recordIncomingEvent("HandleAdmitParticipantFailure",e,s),this.participantOperationHandler.rejectPendingOperation(1,n,s.phrase,s,t)}}getCallEndGivenParticipantFailure(e){let t={code:e.code,subCode:e.subCode,phrase:e.phrase,resultCategories:e.resultCategories};return e.code===wa.CALL_END_CODE.CALL_MODALITY_FAILURE&&e.callControllerTransactionEnd?t={...e.callControllerTransactionEnd}:e.code===wa.CALL_END_CODE.ATC_CONTROLLER_FAILURE&&e.atcControllerTransactionEnd?t={...e.atcControllerTransactionEnd}:e.code===wa.CALL_END_CODE.CVA_CONTROLLER_FAILURE&&e.cvaControllerTransactionEnd&&(t={...e.cvaControllerTransactionEnd}),t}};function wu(e,t){return`${e}-${t}`}function Au(e,t){return`${e}-${t}`}function Pu(e,t,i){return`${e}_${t}_${i}`}var Ru=class{constructor(e){this.signalingSession=e,this.scopeAllOperations=new Map,this.mriOperations=new Map,this.legOperations=new Map,this.logger=e.logger.createChild((()=>"[ProxiedMessageNotificationManager]"))}sendProxiedMessageAsync(e,t,i){this.logger.createChild("sendProxiedMessageAsync",e).info(`Url: ${i}`);const n=[],r=[];for(const i of t)if(0!==i.scope){if(1===i.scope)for(const t in i.to)if("participant"===i.to[t].level){const s=wu(t,i.operationId),a=to();this.mriOperations.set(s,a),n.push(a.promise),r.push(s),this.startTimeout(e,"participant",s)}else if("endpoint"===i.to[t].level)for(const s in i.to[t].participantLegIdMap){const t=Au(s,i.operationId),a=to();this.legOperations.set(t,a),n.push(a.promise),r.push(t),this.startTimeout(e,"endpoint",t)}}else{const t=to();this.scopeAllOperations.set(i.operationId,t),n.push(t.promise),r.push(i.operationId),this.startTimeout(e,"all",i.operationId)}return this.sendProxiedMessageNetworkRequest(e,t,i,r),n}sendProxiedMessageNetworkRequest(e,t,i,n){const r=function(e,t){Ua(e,"signalingSession cannot be null"),Fa(t,"sendMessageOptions cannot be null or empty");const i=[];for(const n of t){const t=0===n.scope?"all":"specified",r=[];n.to&&Object.keys(n.to).forEach((e=>{n.to[e].participantLegIdMap?Object.keys(n.to[e].participantLegIdMap).forEach((t=>{r.push({id:e,level:n.to[e].level,endpointId:n.to[e].participantLegIdMap[t].endpointId,participantId:t})})):r.push({id:e,level:n.to[e].level})})),i.push({links:{sendMessageStatus:Ra(e,ra.SEND_MESSAGE_STATUS)},operationId:n.operationId,payload:n.payload,scope:t,to:r,type:n.type})}return{payload:{from:{displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,id:e.participantManager.localParticipant.id,languageId:e.participantManager.localParticipant.languageId??"",participantId:e.participantManager.localParticipant.participantId},messageContent:i}}}(this.signalingSession,t),s=this.logger.createChild("sendProxiedMessageNetworkRequest",e);s.info(`Url: ${i}`),this.signalingSession.http.sendPostRequest({url:i,requestName:Zo.SEND_PROXIED_MESSAGE.name,payload:r,causeId:e}).catch((t=>{const i=Ka(t,this.signalingSession.signalingAgentConfig);if(s.info(`failed:${je(t)}`),this.signalingSession.disposed)s.info("signaling session is already disposed.");else for(const t of n){this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,t);let n=null;this.scopeAllOperations.has(t)?(n=this.scopeAllOperations.get(t),this.scopeAllOperations.delete(t)):this.mriOperations.has(t)?(n=this.mriOperations.get(t),this.mriOperations.delete(t)):this.legOperations.get(t)?(n=this.legOperations.get(t),this.legOperations.delete(t)):s.warn(`could not find resolveString:${t} to reject it.`),null!==n&&n.reject({transactionEnd:i.error,causeId:e,resolveString:t})}}))}startTimeout(e,t,i){const n=this.logger.createChild("startTimeout",e);n.info(`Creating timeout for level ${t} message with resolveString ${i}`),this.signalingSession.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,(()=>{this.signalingSession.telemetryHelper.recordEvent("SendMessageTimeout",{causeId:e,resolveString:i}),n.info(`timed out waiting for level [${t}] message with resolveString [${i}]`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,i);const r="all"===t?this.scopeAllOperations:"participant"===t?this.mriOperations:"endpoint"===t?this.legOperations:null;null!==r?r.has(i)?(r.get(i).reject({transactionEnd:{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.CONVERSATION_NOTIFICATION_TIMEOUT,phrase:wa.CALL_END_PHRASE.CONVERSATION_NOTIFICATION_TIMEOUT},causeId:e,resolveString:i}),r.delete(i)):n.warn(`Could not find resolveString [${i}] on map for ${t}. Will not reject promise.`):n.warn(`Could not find a operations map for ${t}. Will not reject promise.`)}),wa.TIMEOUT_VALUES_IN_SECONDS.SEND_MESSAGE_COMPLETION_TIMEOUT,i)}handleProxiedMessageNotificationItem(e,t,i){if(t.info(`Message contains ${e.participantInfos?.length} participantInfos.`),0===this.scopeAllOperations.size&&0===this.mriOperations.size&&0===this.legOperations.size)return void t.info("Received statusMessage but there is no pending operation.");const n=e.operationId;if(this.scopeAllOperations.has(n)){t.info(`Scope all resolveString:${n}`),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,n);const e={transactionEnd:{code:0,subCode:0,phrase:""},causeId:i,resolveString:n};return this.scopeAllOperations.get(n).resolve(e),this.scopeAllOperations.delete(n),void this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"all"})}for(const r of e.participantInfos){const e=0===r.transactionEnd?.code,s=wu(r.participant.id,n),a=Au(r.participant.participantId,n);if(s&&this.mriOperations.has(s)){t.info(`Scope mri resolveString:${s}`);const a={transactionEnd:r.transactionEnd,causeId:i,resolveString:s};e?this.mriOperations.get(s).resolve(a):this.mriOperations.get(s).reject(a),this.mriOperations.delete(s),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,s),this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"mri"})}else if(a&&this.legOperations.has(a)){t.info(`Scope legId resolveString:${a}`);const s={transactionEnd:r.transactionEnd,causeId:i,resolveString:a};e?this.legOperations.get(a).resolve(s):this.legOperations.get(a).reject(s),this.legOperations.delete(a),this.signalingSession.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,a),this.signalingSession.telemetryHelper.recordEvent(Ko,{causeId:i,operationId:n,level:"leg"})}else t.warn(`Could not map this participantInfo to any pending operation operationId:${n}`)}}handleProxiedMessageNotification(e){const t=Qa(e),i=this.logger.createChild("handleProxiedMessageNotification",t);let n;n=Array.isArray(e.body?.statuses)?e.body.statuses:[e.body],i.info(`Received ${n.length} proxied message notification(s).`);for(const e of n)this.handleProxiedMessageNotificationItem(e,i,t)}};function Mu(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{admitAllStatus:Ra(e,ra.CONV_ADMIT_ALL_STATUS)},operationId:t,debugContent:{causeId:t}}}}function Du(e,t,i=!0){Ua(e,"signalingSession cannot be null"),Ua(t,"joinUrl cannot be null");const n={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},r=e.getEndpointCapabilities(),s={payload:{attach:{requireMediaContent:i,links:{end:Ra(e,ra.END)},locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent(),...e?.signalingAgent?.accountConfig?.applicationType?{applicationType:e.signalingAgent.accountConfig.applicationType}:{}},capabilities:null,endpointCapabilities:r,additionalActions:[{input:{capabilities:null,endpointCapabilities:r,conversationRequest:{applicationType:e.participantManager.localParticipant.applicationType,roster:n,links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},endpointMetadata:e.endpointMetadata,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}},name:"join",url:t,waitForResponse:!0}]}};return e.signalingAgentConfig.ecsEtag&&(s.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),s.payload.additionalActions.length>0&&e.deviceType&&"default"!==e.deviceType&&(s.payload.additionalActions[0].input.conversationRequest.deviceType=e.deviceType),s}function ku(e){return Ua(e,"signalingSession cannot be null"),{payload:{callAcceptanceAcknowledgement:{links:{mediaRenegotiation:Ra(e,ra.MEDIA_RENEGOTIATION),transfer:Ra(e,ra.TRANSFER),replacement:Ra(e,ra.REPLACE),balanceUpdate:Ra(e,ra.BALANCE_UPDATE),retargetCompletion:Ra(e,ra.RETARGET_COMPLETION),controlVideoStreaming:Ra(e,ra.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Ra(e,ra.UPDATE_MEDIA_DESCRIPTIONS)}}}}}function Ou(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=Ha(i);e.telemetryHelper.addOutgoingModalities(r);const s=e.getEndpointCapabilities();return{payload:{callAcceptance:{acceptedBy:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},acceptedCallModalities:r,capabilities:null,endpointCapabilities:s,clientEndpointCapabilities:0!==n?n:null,links:{mediaRenegotiation:Ra(e,ra.MEDIA_RENEGOTIATION),transfer:Ra(e,ra.TRANSFER),replacement:Ra(e,ra.REPLACE),balanceUpdate:Ra(e,ra.BALANCE_UPDATE),retargetCompletion:Ra(e,ra.RETARGET_COMPLETION),controlVideoStreaming:Ra(e,ra.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Ra(e,ra.UPDATE_MEDIA_DESCRIPTIONS)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,callKeepAliveInterval:null,...e?.signalingAgent?.accountConfig?.applicationType?{applicationType:e.signalingAgent.accountConfig.applicationType}:{}}}}}function Nu(e){return Ua(e,"signalingSession cannot be null"),{payload:{callProgress:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},status:"ringing",phrase:"ringing"}}}}function Lu(e,t,i){Ua(e,"signalingSession cannot be null"),Ba(t);const n={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===wa.CALL_END_CODE.CANCEL&&(n.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),n}function xu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED},callTransactionEnd:t}}}function Fu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t}}}function Uu(e,t,i,n,r){Ua(e,"signalingSession cannot be null");const s={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},a=e.getEndpointCapabilities(),o=e.groupId?{id:e.groupId}:null,l=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,c={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,scenario:n.scenario,applicationType:n.applicationType,roster:s,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?n.subscribe?ra.CONV_END_SUBSCRIBE:ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},groupContext:o,groupChat:l,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin}},capabilities:null,endpointCapabilities:a,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("joinConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),c.payload.publishedStates=t}if(n?.applyServerMute&&(c.payload.participants.from.applyServerMute=n.applyServerMute.value,n.applyServerMute.mediaTypes&&(c.payload.participants.from.mediaTypes=n.applyServerMute.mediaTypes)),e.deviceType&&"default"!==e.deviceType&&(c.payload.conversationRequest.deviceType=e.deviceType),!n.subscribe){const r=Ha(i);e.telemetryHelper.addOutgoingModalities(r),c.payload.callInvitation={callModalities:r,replaces:null,transferor:null,links:{progress:Ra(e,ra.PROGRESS),mediaAnswer:Ra(e,ra.MEDIA_ANSWER),acceptance:Ra(e,ra.ACCEPT),redirection:Ra(e,ra.REDIRECTION),end:Ra(e,ra.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent(),sharedLineCallInvitationContent:n.sharedLineCallInvitationContent,invitationData:n.invitationData,callQueueContext:n.callQueueContext}}if(e.signalingAgentConfig.ecsEtag&&(c.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),r&&(c.payload.debugContent||(c.payload.debugContent={}),c.payload.debugContent.causeId=r),n.clientEndpointDebugContent){c.payload.debugContent||(c.payload.debugContent={});try{c.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){xa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{c.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){xa(!1,`Failed to parse ${n.captchaContentJson}`)}return n.callQueueContext&&(c.payload.conversationRequest.callQueueContext=n.callQueueContext),n.participationPreferences&&(c.payload.participationPreferences=n.participationPreferences),n.participantPropertyBag&&(c.payload.participantPropertyBag=n.participantPropertyBag),c}function Bu(e,t,i,n){Ua(e,"signalingSession cannot be null"),Ba(t);const r={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:n&&"all"!==n?void 0:n},conversationTransactionEnd:{reason:"noError",code:wa.CALL_END_CODE.SUCCESS,phrase:wa.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===wa.CALL_END_CODE.CANCEL&&(r.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),r}function Vu(e,t,i){return Ua(e,"signalingSession cannot be null"),Ua(i,"newOfferLink cannot be null"),{payload:{mediaOfferRequirements:{compatibleContentTypes:t,links:{offerReady:Ra(e,ra.NEW_MEDIA_OFFER)}}}}}function Hu(e,t){return Ua(t,"signalingSession cannot be null"),{payload:{callTransfer:{target:{id:t.participantManager.localParticipant.id},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},parkType:e,links:{transferAcceptance:Ra(t,ra.TRANSFER_ACCEPTANCE),transferCompletion:Ra(t,ra.TRANSFER_COMPLETION)}}}}}function $u(e,t,i){Ua(e,"ParkRequestPayload: signalingSession cannot be null");const n={payload:{hold:{holdType:t,links:{holdCompletion:Ra(e,ra.PARK_COMPLETION)}}}};return i&&(n.payload.debugContent=i),n}function ju(e,t,i,n,r,s){const a={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},publishedState:{content:n,level:i,stateType:t,sequenceNumber:e.getPublishStateSequenceNumber()},scope:r}};if(s&&s.length>0){const e=s.map((e=>({id:e})));a.payload.to=e}return a}function Gu(e,t){return Ua(e,"signalingSession cannot be null"),Ba(t),{payload:{callEnd:t}}}function qu(e,t,i,n){const r={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},sequenceNumber:e.getPublishStateSequenceNumber(),scope:t};return"specified"===t?r.stateIds=i:r.stateType=n,{payload:r}}function zu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},searchOptions:t}}}function Wu(e,t,i,n,r){return Ua(t,"signalingSession cannot be null"),Fa(e,"transferTarget cannot be null OR empty"),{payload:{callTransfer:{target:{id:e,endpointType:"TransferTypeVoicemail"===n?"voicemail":void 0},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},links:{transferAcceptance:Ra(t,ra.TRANSFER_ACCEPTANCE),transferCompletion:Ra(t,ra.TRANSFER_COMPLETION)},replacementDetails:i,disableForwardingAndUnanswered:r&&r.disableForwardingAndUnanswered,transferContext:r&&r.clientTransferContext}}}}function Ku(e){return{payload:{transferCompletion:e}}}function Ju(e,t){Ua(e,"ResumePayload: signalingSession cannot be null");const i={payload:{resume:{links:{resumeCompletion:Ra(e,ra.UNPARK_COMPLETION)}}}};return t&&(i.payload.debugContent=t),i}function Yu(e,t){return Ua(t,"clientMetadataJson cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},endpointMetadata:t}}}function Qu(e,t,i,n,r){Ua(t,"clientStateJson cannot be null");const s={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},endpointState:t}};if(r)try{s.payload.captchaContent=JSON.parse(r)}catch(t){e.logger.warn("updateEndpointState getPayload() failed to parse captchaContentJson")}if(i?.publishedStates.length>0){let t=[];t=i.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("updateEndpointState getPayload() failed to parse stateType.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),s.payload.publishedStates=t}return n&&(s.payload.links={updateEndpointStateStatus:Ra(e,ra.DISABLE_PREHEAT_ASYNC_STATUS)}),s}function Zu(e,t){const i={};return void 0!==t.allowRaiseHands&&(i.allowRaiseHands=t.allowRaiseHands),void 0!==t.attendeeRestrictions&&(i.attendeeRestrictions=t.attendeeRestrictions),void 0!==t.lockMeeting&&(i.lockMeeting=t.lockMeeting),void 0!==t.breakoutRoomsEnabled&&(i.breakoutRoomsEnabled=t.breakoutRoomsEnabled),void 0!==t.allowPresentersToManageBreakoutRooms&&(i.allowPresentersToManageBreakoutRooms=t.allowPresentersToManageBreakoutRooms),void 0!==t.disableMdpClientAudioRecording&&(i.disableMdpClientAudioRecording=t.disableMdpClientAudioRecording),void 0!==t.refreshSettings&&(i.refreshSettings=t.refreshSettings),void 0!==t.aiInterpretationEnabled&&(i.aiInterpretationEnabled=t.aiInterpretationEnabled),void 0!==t.groupCopilotDetails&&(i.groupCopilotDetails=t.groupCopilotDetails),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingSettings:i,sequenceNumber:e.getPublishStateSequenceNumber()}}}function Xu(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{mediaAnswer:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaContent:t,pstnContent:e.pstnContent}}}}function eh(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{UpdateMediaDescriptions:{mediaDescriptions:t}}}}var th=p(Z),ih=p(ge()),nh=["CorrelationId","SignalingSessionId","Region","ParticipantId","ClientInformation","ResultCode","ResultDetail","ResultValue","Direction","ClientType","MeetingRoles"],rh=class{constructor(e,t){this.signalingSession=e,this.logger=t,this.logConversationCallModalityEvent=e=>{const t=this.createCallModalityEvent(e);this.logger.info("sending modality telemetry:",this.getStringifiedEventData(t)),t.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(tl,t)},this.logConversationContentSharingEvent=e=>{e[Kc]=this.signalingSession.correlationId,e[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,this.logger.info("sending content sharing telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(il,e)},this.logHttpTelemetryEvent=e=>{e[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,e[Mc]=this.getSignalingAgentConfig(),this.logger.info("sending http telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(nl,e)},this.getHostDomainInfo=()=>"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>",this.getSignalingAgentConfig=()=>{const e=[],t=this.signalingSession.signalingAgentConfig;return t.supportsCompressedServicePayload&&e.push(Lc),t.brokerEnabledOutgoing&&e.push(Dc),t.brokerEnabledIncoming&&e.push(kc),t.brokerRequestBatching&&e.push(Oc),t.brokerExclusively&&e.push(Nc),t.supportsSynchronousTrouterResponse&&e.push(xc),t.handleMediaOfferFromPushNotification&&e.push(Uc),t.handleNewOfferRequest&&e.push(Bc),t.sendProgressFromCC&&e.push(Vc),t.useInternalHttpDispatcher&&e.push(Hc),t.enableTokenCache&&e.push($c),t.enableTokenPrefetch&&e.push(jc),t.supportMediaRetargetWhileIncomingRenegotiation&&e.push(Gc),t.enableCallEstablishmentTimeoutsForStartJoinCall&&e.push(qc),t.enableTokenCacheForGenericTokenAPI&&e.push(zc),t.enableLongOutgoing1To1SetupTimeoutForWeb&&e.push(Wc),e.push(Fc),e.join(",")},this.getStringifiedEventData=e=>{try{return JSON.stringify(e,nh,4)}catch(e){return"invalid data"}},this.telemetryLogger=this.signalingSession.signalingAgentConfig.oneDsTelemetryLogger??this.signalingSession.signalingAgentConfig.telemetryManager}createCallModalityEvent(e){const t={};t.Type=el;const i=(i,n=!1)=>{t[i]=n?JSON.stringify(e[i]):e[i]},n=(t,n=!1)=>{e.hasOwnProperty(t)&&i(t,n)};if(t.ResultDetail=e[Fl],t.ResultValue=e[xl],t.ResultCode=e[wl],t.ResultCauseId=e[Ul],t[Mc]=this.getSignalingAgentConfig(),t[Kc]=this.signalingSession.correlationId,t[Yc]=this.signalingSession.sessionId,i(td),i(id),t[rc]=this.signalingSession.signalingAgentConfig.ecsEtag,i(kl),i(vl,!0),i(Sl,!0),i(Xl,!0),t[yl]=this.signalingSession.multiParty?"true":"false",t[Cl]=this.signalingSession.isHostLessCall?"true":"false",t[Tl]=this.signalingSession.isCastCall?"true":"false",t[El]=this.signalingSession.isHuddleGroupCall?"true":"false",t[_l]=this.signalingSession.onBehalfOf?"true":"false",i(nc),i(Il),i(hl),i(wl,!0),i(Al,!0),n(Jc),n(sl),n(Vl),n(ol,!0),n(ul,!0),n(pl),n(gl),n(ml),n(ec),n(tc),n(ic),n(fl),n(Bl),n(zl),n(Wl),n(Kl),n(Jl),n(Yl),n($l),n(jl),n(Hl),n(ll),n(cl),n(dl),n(cc),n(Rl),n(sc),n(ac),n(dc),n(uc),n(Ll),n(mc),n(pc),n(lc),n(fc),n(vc),n(Sc),n(yc,!0),n(Cc),n(Tc),n(Ec),n(_c),n(Ic),n(wc),n(Dl),this.signalingSession.callType&&(t[Gl]=this.signalingSession.callType),this.signalingSession.signalingAgentConfig.testCall&&(t[ql]="Test"),this.signalingSession.groupId&&(t[Qc]=De(this.signalingSession.groupId)),this.signalingSession.threadId&&(t[Zc]=xe(this.signalingSession.threadId)),this.signalingSession.teamsMessageId&&(t[Xc]=this.signalingSession.teamsMessageId),this.signalingSession.getMeetingInfo()){const e={...this.signalingSession.getMeetingInfo()};e.hasOwnProperty("organizerId")&&(e.organizerId=De(e.organizerId)),t[ed]=JSON.stringify(e)}return this.signalingSession.multiParty&&0===this.signalingSession.numberOfOriginalInvitees&&e.hasOwnProperty(Vl)&&e[Vl]===ud&&(t[bl]="true"),t}},sh=class{constructor(e,t,i){this.signalingSession=e,this.callStartTime=i,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(Rc)},this.addTrouterChannel=()=>{this.setMessagingChannel(Pc)},this.addTrouterWaitOperation=e=>{this.trouterWaitOperations.push(this.recordOperation(e))},this.recordIncomingEvent=(e,t,i)=>{const n=Qa(t),r={origin:t.origin,causeId:n,data:i};i||delete r.data,this.recordEvent(e,r)},this.recordIncomingEventCount=e=>{this.localOperationsPerformed.push(this.recordOperation(e));const t=this.recordedEvents.findIndex((t=>t[e]));if(-1!==t)this.recordedEvents[t][e]+=1;else{const t={};t[e]=1,this.recordedEvents.push(t)}},this.recordEvent=(e,t)=>{this.logger.debug("Event:",e,t),this.localOperationsPerformed.push(this.recordOperation(e));const i={};i[e]=this.timeSinceCallStart(),t&&(i.data=t),this.recordedEvents.push(i)},this.recordRosterEvent=(e,t,i)=>{this.localOperationsPerformed.push(this.recordOperation(t));const n={data:e,causeId:i},r={eventName:this.timeSinceCallStart(),data:n};this.rosterUpdates.push(r)},this.addOutgoingModalities=e=>{e&&this.outgoingModalities.push(e)},this.addIncomingModalities=e=>{e&&this.incomingModalities.push(e)},this.setOfferedModalities=(e,t)=>{this.offeredModalities=this.sdpTelemetryFormat(e,t)},this.setAnsweredModalities=(e,t)=>{this.answeredModalities=this.sdpTelemetryFormat(e,t)},this.setIsSdpInCallNotification=e=>{this.isSdpInCallNotification=e},this.addVbssOperations=e=>{e&&(this.vbssStarted=e===fd,this.vbssOperations.push(this.recordOperation(e)))},this.addNetworkOperationStarted=e=>{qa(this.networkRequestsStarted,e,this.recordOperation(e))},this.addNetworkOperationCompleted=(e,t,i)=>{const n=t?od:ld,r=i?`${e}:${n}:${i}`:`${e}:${n}`;this.networkRequestsCompleted.push(this.recordOperation(r)),za(this.networkRequestsStarted,e)},this.updateNetworkRequest=e=>{this.networkRequests[e.uid]?th.assign(this.networkRequests[e.uid],e):this.networkRequests[e.uid]=e},this.deleteNetworkRequest=e=>{delete this.networkRequests[e.uid]},this.addContentSharingOperation=(e,t,i)=>{this.contentSharingOperationsPerformed[e]||(this.contentSharingOperationsPerformed[e]=[]);const n={[t]:this.timeSinceCallStart()};this.contentSharingOperationsPerformed[e].push(n);const r=this.contentSharingOperationsPerformed[e].length-1;return i&&this.updateContentSharingOperation(e,r,i),r},this.updateContentSharingOperation=(e,t,i)=>{if(!this.contentSharingOperationsPerformed[e])return;const n=this.contentSharingOperationsPerformed[e][t],r=[];for(const e of Object.keys(i))r.push(`${e}: ${i[e]}`);n.data=r.join(", ")},this.setDirection=e=>{this.telemetryData[sl]=e},this.setEndPointId=e=>{this.telemetryData[td]=e,this.contentSharingBaseTelemetryData[td]=e,this.httpRequestTelemetryData[td]=e},this.setParticipantId=e=>{this.telemetryData[id]=e,this.contentSharingBaseTelemetryData[id]=e,this.httpRequestTelemetryData[id]=e},this.addTokenTelemetry=(e,t)=>{e?this.networkRequests?.[e]?(this.networkRequests[e].tokenTelemetries||(this.networkRequests[e].tokenTelemetries=[]),this.networkRequests[e].tokenTelemetries.push(t)):this.logger.info(`[addTokenTelemtry] httprequest: ${e} is not found in networkRequests`):this.logger.error("[addTokenTelemetry] httprequest uid is undefined")},this.setConversationServiceUrl=e=>{this.telemetryData[kl]=e},this.setMeetingInfo=e=>{e||(this.telemetryData[Nl]=e)},this.setJoinedFrom=e=>{this.telemetryData[Ll]=e},this.setMeetingCode=e=>{this.telemetryData[pc]=e},this.setMeetingUrl=e=>{this.telemetryData[mc]=e},this.setBroadcastMeetingRole=e=>{this.telemetryData[fc]=e},this.setMeetingRole=e=>{this.telemetryData[vc]=e},this.setAdvancedMeetingRole=e=>{this.telemetryData[Sc]=e},this.setParticipantType=e=>{this.telemetryData[Cc]=e},this.setSelfParticipantRole=e=>{this.telemetryData[Vl]=e},this.setDisplayName=e=>{const t=new Re(e,1);this.telemetryData[Tc]=t},this.setAudioOnlyWatermark=e=>{this.telemetryData[Ec]=e},this.setWatermarkSupport=e=>{this.telemetryData[bc]=e},this.setClientSupportsPreventScreenCapture=e=>{this.telemetryData[Ac]=e},this.setScenario=e=>{this.telemetryData[Hl]=e},this.setTargetApplicationType=e=>{e&&(this.telemetryData[_c]=e)},this.setCallerType=e=>{e&&(this.telemetryData[$l]=e.split(":",1)[0])},this.setCalleeType=e=>{e&&(this.telemetryData[jl]=e.split(":",1)[0])},this.setTerminatingData=e=>{this.telemetryData[hl]=e.terminatingEnd,this.telemetryData[wl]=e.endCode||wa.CALL_END_CODE.SUCCESS,this.telemetryData[Al]=e.endSubCode||wa.CALL_END_SUB_CODE.SUCCESS,this.telemetryData[Pl]=e.phrase||wa.CALL_END_PHRASE.UNKNOWN,this.telemetryData[xl]=e.resultValue||od,this.telemetryData[Fl]=e.resultDetail||"Call gracefully hungup",this.telemetryData[Ul]=e.causeId||"unknown",this.telemetryData[Rl]=e.resultCategories||[],this.telemetryData[hc]=e.clientReasonSubCode,this.telemetryData[gc]=e.clientReasonPhrase},this.startCallInitializationWatch=e=>{this.timeToRingStopWatch=tu(),e&&(this.timeToRingStopWatch.msElapsed+=e)},this.startCallConnectedWatch=()=>{this.connectedStopWatch=tu()},this.setIsPreheated=()=>{this.isPreheated=1},this.startPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch=tu()},this.stopPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch.pause()},this.startCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=tu()},this.stopCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch&&this.callCancelationDurationWatch.pause()},this.getCallCancelationDuration=()=>this.callCancelationDurationWatch?this.callCancelationDurationWatch.durationInSeconds():0,this.resetCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=null},this.setOfferAnswerGenerationTimestamps=e=>{this.localOfferAnswerGenerationTimestamps.push(this.recordOperation(e))},this.setTimeToRingDuration=()=>{this.timeToRingStopWatch&&(this.telemetryData[ul]=this.timeToRingStopWatch.duration(),this.timeToRingStopWatch=null)},this.dispose=()=>{this.sendCallModalityTelemetryData()},this.setMessagingChannel=e=>{this.telemetryData[Xl]||(this.telemetryData[Xl]=[]),this.telemetryData[Xl].some((t=>-1!==t.indexOf(e)))||this.telemetryData[Xl].push(this.recordOperation(e))},this.sendHttpTelemetryData=e=>{const t={...this.httpRequestTelemetryData};t[Kc]=this.signalingSession.correlationId,t[Yc]=this.signalingSession.sessionId,t[nc]=this.signalingSession.signalingAgentConfig.clientInformation;const i=JSON.stringify({eventStart:this.callStartTime,events:this.networkRequests[e]});za(this.networkRequests,e),t[ic]=i,this.telemetryLogger.logHttpTelemetryEvent(t)},this.sdpTelemetryFormat=(e,t)=>{if(!e)return"";const i=e=>{switch(e){case"main-audio":return"Audio";case"main-video":return"Video";case"applicationsharing-video":return"AppSharing";default:return}},n=e=>{switch(e){case"inactive":return"Inactive";case"sendonly":return t?"ReceiveFromPeer":"SendToPeer";case"recvonly":return t?"SendToPeer":"ReceiveFromPeer";default:return"Bidirectional"}},r={"main-audio":0,"main-video":0,"applicationsharing-video":0},s=[],a=ih.parse(e);for(const e of a.media){const t=i(e.label);if(!t)continue;const a=r[e.label]++,o=n(e.direction);s.push(`${t}[${a}] = ${o}`)}return s.join(", ")},this.setReinviteless=e=>{this.isReinviteless=e?1:0},this.logger=e.logger,this.telemetryLogger=function(e,t){return new rh(e,t)}(e,this.logger),this.telemetryData[vl]=this.callStartTime,this.telemetryData[kl]=e.signalingAgentConfig.conversationServiceUrl,this.fillCommonData(t,this.telemetryData),this.fillCommonData(t,this.httpRequestTelemetryData),this.fillCommonData(t,this.contentSharingBaseTelemetryData)}fillCommonData(e,t){t[sc]=e.applicationType,t[ac]=e.ring,t[oc]=e.tenantId,t[lc]=e.userHexCID,t[cc]=e.acsResourceId,t[dc]=e.region,t[uc]=e.partition,t[wc]=e.clientType}addChangingCorrelationId(e,t){this.telemetryData[Zl]=e,this.telemetryData[Ql]=t}addSharedCorrelationId(e){this.telemetryData[Jc]=e}setMeetingRoles(e){this.telemetryData[yc]=e}setConflictingCallId(e){this.telemetryData[Dl]=e}sendContentSharingTelemetryData(e,t,i,n,r,s){const a={...this.contentSharingBaseTelemetryData},o=this.contentSharingOperationsPerformed[e];o&&(a[ec]=JSON.stringify(o)),a[rd]=e,a[Yc]=t,a[nd]=s||"",a[Ol]=r,a[al]=i?dd:cd,a[wl]=n.code,a[Al]=n.subCode,a[Pl]=n.phrase,a[Rl]=this.getResultCategoryString(n.resultCategories),a[Ml]=n.causeId,a[nc]=this.signalingSession.signalingAgentConfig.clientInformation,delete this.contentSharingOperationsPerformed[e],this.telemetryLogger.logConversationContentSharingEvent(a)}recordOperation(e){return`${e}:${this.timeSinceCallStart()}`}timeSinceCallStart(){return(new Date).getTime()-this.callStartTime}sendCallModalityTelemetryData(){this.vbssStarted&&this.addVbssOperations(Td);const e=e=>"number"==typeof e?e/1e3:0;if(this.telemetryData[nc]=this.signalingSession.signalingAgentConfig.clientInformation,this.telemetryData[Sl]=(new Date).getTime(),this.connectedStopWatch&&(this.telemetryData[ol]=this.connectedStopWatch.duration()),this.telemetryData[dl]=this.isPreheated,this.preheatedCallSetupDurationWatch&&(this.telemetryData[ll]=e(this.preheatedCallSetupDurationWatch.duration())),this.callCancelationDurationWatch&&(this.telemetryData[cl]=e(this.callCancelationDurationWatch.duration())),this.networkRequestsCompleted.length&&(this.telemetryData[pl]=JSON.stringify(this.networkRequestsCompleted)),this.localOperationsPerformed.length&&(this.telemetryData[ml]=JSON.stringify(this.localOperationsPerformed)),this.trouterWaitOperations.length&&(this.telemetryData[fl]=JSON.stringify(this.trouterWaitOperations)),this.localOfferAnswerGenerationTimestamps.length&&(this.telemetryData[Bl]=JSON.stringify(this.localOfferAnswerGenerationTimestamps)),this.incomingModalities.length&&(this.telemetryData[Wl]=JSON.stringify(this.incomingModalities)),this.outgoingModalities.length&&(this.telemetryData[zl]=JSON.stringify(this.outgoingModalities)),this.offeredModalities.length&&(this.telemetryData[Kl]=this.offeredModalities),this.answeredModalities.length&&(this.telemetryData[Jl]=this.answeredModalities),this.telemetryData[Rl]=this.getResultCategoryString(this.telemetryData[Rl]),this.telemetryData[Il]=this.isSdpInCallNotification.toString(),this.vbssOperations.length&&(this.telemetryData[Yl]=JSON.stringify(this.vbssOperations)),this.recordedEvents.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.recordedEvents});this.telemetryData[ec]=e}if(this.rosterUpdates.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.rosterUpdates});this.telemetryData[tc]=e}const t=[];for(const e of Object.keys(this.networkRequestsStarted))t.push(this.networkRequestsStarted[e]);t.length>0&&(this.telemetryData[gl]=JSON.stringify(t)),this.telemetryData[Ic]=this.isReinviteless,this.telemetryLogger.logConversationCallModalityEvent(this.telemetryData)}getResultCategoryString(e){return e&&Array.isArray(e)?e.join(","):""}},ah=class{constructor(e,t){this.disposed=!1,this.lastSeenSeqNumbers={},this.isDominantSpeakerInfoLinkEnabled=!0,this.clientUrlsGenerated=!1,this.getClientUrls=()=>{this.clientUrlsGenerated=!0;let e=null;return this.isWebRtcCall&&(e={controlVideoStreaming:Ra(this.signalingSession,ra.CONTROL_VIDEO_STREAMING),csrcInfo:Ra(this.signalingSession,ra.CSRC_INFO)},this.isDominantSpeakerInfoLinkEnabled&&(e.dominantSpeakerInfo=Ra(this.signalingSession,ra.DOMINANT_SPEAKER_INFO))),e},this.handleDominantSpeakerInfo=e=>{const t=e.body;this.logger.debug("handleDominantSpeakerInfo : ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEventCount("HandleDominantSpeakerChangedCount"),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO,t.dominantSpeakerInformation)},this.handleControlVideoStreaming=e=>{const t=e.body;this.logger.debug("handleControlVideoStreaming: ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleControlVideoStreaming",e),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING,t.controlVideoStreaming,!1)},this.handleCsrcInfo=e=>{const t=e.body;this.logger.debug("handleCsrcInfo : ",je(t)),this.signalingSession.telemetryHelper.recordIncomingEvent("HandleCsrcInfo",e),this.handleWebRtcNotification(wa.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO,t.csrcInfo)},this.sendWebRtcMediaNotificationAsync=({operation:e,requestUrl:t,requestBody:i,stackRetry:n=!0},r)=>{this.logger.info("sendWebRtcMediaNotificationAsync"),xa(this.isWebRtcCall,"this is not a webrtc call"),Fa(t,"correct media notification requestUrl is not provided"),Fa(i,"media notification requestBody cannot be null or empty");const s=to(),a={url:t,payload:{payload:i},requestName:e,withoutTrouter:!0,causeId:r};return n||(a.disableRetry=!0),this.signalingSession.http.sendPostRequest(a).then((()=>{this.disposed||s.resolve()})).catch((e=>{const t=je(e);if(this.logger.error(`sendWebRtcMediaNotificationAsync failed because : ${t}`),!this.disposed){const t=new Error(e);t.endCode=wa.CALL_END_NETWORK_ERROR,s.reject(t)}})),s.promise},this.dispose=()=>{this.logger.info("WebRtcSignalingManager :: dispose"),this.disposed=!0},this.signalingSession=e,this.signalingSessionCallback=t,this.isWebRtcCall=e.signalingAgentConfig.isWebRtcEnabled,this.logger=e.logger,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING]=-1,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO]=-1,this.lastSeenSeqNumbers[wa.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO]=-1}areClientURLsGenerated(){return this.clientUrlsGenerated}getIsDominantSpeakerInfoLinkEnabled(){return this.isDominantSpeakerInfoLinkEnabled}setIsDominantSpeakerInfoLinkEnabled(e){this.isDominantSpeakerInfoLinkEnabled=e}handleWebRtcNotification(e,t,i=!0){xa(this.isWebRtcCall,"ignoring message in non-webrtc call");const n=this.lastSeenSeqNumbers[e];i&&t.sequenceNumber<=n?this.logger.info(`ignoring ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`):(t.sequenceNumber<=n&&this.logger.info(`let listener to handle older ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`),this.lastSeenSeqNumbers[e]=Math.max(t.sequenceNumber,this.lastSeenSeqNumbers[e]),this.signalingSessionCallback.onWebRtcMediaNotification(e,t))}},oh=class{constructor(e,t,i,n,r,s){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=La(),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.meetingLayoutDetails=null,this.compositionServiceDetails=null,this.realTimeState=0,this.disposing=!1,this.links={},this.provisionalMediaAnswersSeenSoFar=[],this.incomingTrouterMessagesSeenSoFar=[],this.incomingBrokerMessagesSeenSoFar=[],this.currentCallStatus=null,this.fsmState=wa.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=to(),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=(e,t=Na(),i,n)=>{this.logger.info(`[${t}][requestedEndpointState=${je(e,!0)}][captchaContentJson=${n}]`);const r=this.links[wa.LINKS.UPDATE_ENDPOINT_STATE],s=this.getEndpointState();this.logger.info(`[${t}][currentEndpointState=${je(s,!0)}] startOrJoinConvResponseReceived=${this.startOrJoinConvResponseReceived}`);const a={...s,...e,endpointStateSequenceNumber:++this.endpointStateSequenceNumber};this.telemetryHelper.recordEvent("UpdateEndpointState",{newEndpointState:a,causeId:t});const o=0===a?.endpointProperties?.preheatProperties&&this.isPreheatOnly;if(o&&(this.telemetryHelper.recordEvent("DisablingPreheat",{causeId:t}),this.telemetryHelper.startPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallCancelationDurationWatch()),2===this.callMode&&o)return this.logger.info(`[${t}][updateEndpointState skipped as mode is streaming]`),this.handleEndpointStateUpdated(t,!0),Promise.resolve();if(!this.startOrJoinConvResponseReceived)return this.logger.info(`[${t}][updateEndpointState will be queued as we don't have a link yet]`),this.requestedEndpointStateWhileConnecting=e,this.requestedPublishedStatesWhileConnecting=i,o?this.disablePreheatDefer.promise:Promise.resolve();if(!this.shouldUpdateEndpointState(s,a)&&!this.http.hasPendingRequest(Zo.UPDATE_ENDPOINT_STATE.name))return this.logger.info(`[${t}][updateEndpointState will ignore current update as there is nothing new to send]`),Promise.resolve();if(!r)return this.logger.info(`[${t}][updateEndpointState operation cannot be performed now, the link is not yet available]`),Promise.reject("No link");this.latestEndpointState=a;const l=this.signalingAgentConfig.enableAsyncDisablePreheat&&o;l&&this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT,(()=>{const e={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.DISABLE_PREHEAT_TIMEOUT,phrase:wa.CALL_END_PHRASE.DISABLE_PREHEAT_TIMEOUT};this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject({response:e})}),wa.TIMEOUT_VALUES_IN_SECONDS.DISABLE_PREHEAT_TIMEOUT);const c=this.http.sendPostRequest({url:r,requestName:Zo.UPDATE_ENDPOINT_STATE.name,payload:Qu(this,a,i,l,n),causeId:t}).then((()=>(l&&(this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: true`),this.telemetryHelper.recordEvent("DisablePreheatResponseReceived",{causeId:t})),Promise.resolve()))).catch((e=>{if(!l)throw e;this.disablePreheatDefer.reject(e)}));return(l?this.disablePreheatDefer.promise:c).then((()=>{this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: ${l}`),this.telemetryHelper.recordEvent(l?"AsyncDisablePreheatSucceeded":"DiablePreheatSucceeded",{causeId:t}),this.disposed||this.handleEndpointStateUpdated(t,o)})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointState] error: ${je(i)}`),o&&(this.handleDisablePreheatError(i.error,l?"AsyncDiablePreheatFailed":"DiablePreheatFailed",t),this.stopCallPreheatTimer(),this.terminateEstablishedCall({code:i.error.code,subCode:i.error.subCode,phrase:i.error.phrase},{forEveryone:!1,causeId:t})),Promise.reject(i.error)}))},this.setParticipantCallLinks=e=>{e&&e.endpointDetails&&(this.participantReplacementDetails[e.id]={},e.endpointDetails.forEach((t=>{t&&t.callLinks&&(this.participantReplacementDetails[e.id][t.participantId]=t.callLinks)})))},this.clearParticipantCallLinks=e=>{this.participantReplacementDetails?.hasOwnProperty(e)&&delete this.participantReplacementDetails[e]},this.getReplacementDetailsByParticipantLeg=(e,t,i=Na())=>(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: participantMri ${this.piiUtils.scrubMriOrOmit(e)} participantLegId ${t}`),this.participantReplacementDetails?.hasOwnProperty(e)&&this.participantReplacementDetails[e].hasOwnProperty(t)?{replaces:this.participantReplacementDetails[e][t].replacement,replacementTargetParticipantId:t}:(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: unable to find replacement details for participantLegId ${t}`),{})),this.getReplacementDetailsByParticipantLegOfCall=(e,t,i,n=Na())=>{this.logger.info(`[${n}]getReplacementDetailsByParticipantLegOfCall: callId ${e} participantMri ${this.piiUtils.scrubMriOrOmit(t)} participantLegId ${i}`);const r=this.signalingAgent.getSignalingSession(e);return r?r.getReplacementDetailsByParticipantLeg(t,i,n):{}},this.getMriByParticipantLegOfCall=(e,t,i)=>{this.logger.info(`[${i}]getMriByParticipantLegOfCall: callId: ${e} participantLegId ${t}`);const n=this.signalingAgent.getSignalingSession(e);return n?n.getMriByParticipantLeg(t,i):""},this.getMriByParticipantLeg=(e,t)=>{this.logger.info(`getMriByParticipantLeg[${t}] participantLegId ${e}`);for(const t of Object.keys(this.participantReplacementDetails))if(t&&this.participantReplacementDetails.hasOwnProperty(t)&&this.participantReplacementDetails[t]?.hasOwnProperty(e))return t;return""},this.handleEndpointStateUpdated=(e,t)=>{this.requestedEndpointStateWhileConnecting=null,this.requestedPublishedStatesWhileConnecting=null,t&&this.handlePreheatDisabled(e)},this.handlePreheatDisabled=e=>{this.isPreheatOnly=!1,this.telemetryHelper.setSelfParticipantRole(this.originalRoleBeforePreheat),this.telemetryHelper.recordEvent("PreheatDisabled",{causeId:e}),this.telemetryHelper.resetCallCancelationDurationWatch(),this.telemetryHelper.stopPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallConnectedWatch(),this.stopCallPreheatTimer(),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.resolve()},this.shouldUpdateEndpointState=(e,t)=>{if(!t)return!1;const i=t.state&&t.state.isMuted?1:0,n=t.endpointProperties&&1===t.endpointProperties.preheatProperties?1:0,r=e&&e.state&&e.state.isMuted?1:0,s=e&&e.endpointProperties&&1===e.endpointProperties.preheatProperties?1:0,a=e?.endpointProperties?.additionalEndpointProperties,o=t?.endpointProperties?.additionalEndpointProperties;return!!(i^r||n^s||o!==a)},this.setInitialTelemetry=(e,t)=>{let i,n;switch(e){case"Subscribe":this.telemetryHelper.recordEvent("JoinConversationWithoutCallModality",{causeId:t.causeId,correlationId:t.correlationId}),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(pd),this.telemetryHelper.setConversationServiceUrl(t.conversationServiceUrl||this.signalingAgentConfig.conversationServiceUrl),this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);break;case"Acknowledge":this.telemetryHelper.recordEvent("HandleIncomingCall",{causeId:t.causeId}),this.telemetryHelper.setDirection(cd),this.telemetryHelper.setSelfParticipantRole(hd),this.telemetryHelper.setCalleeType(this.participantManager.localParticipant.id);break;case"JoinCall":i=this.gatherTelemetryForStartOrJoin(t.joinCallOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent("JoinCall",i),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(gd);break;case"StartCall":case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":n=this.gatherTelemetryForStartOrJoin(t.callStartOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent("StartCall",n),this.telemetryHelper.setDirection(dd),this.telemetryHelper.setSelfParticipantRole(ud),this.telemetryHelper.startCallInitializationWatch(t.offerGenerationTime),this.telemetryHelper.setMeetingInfo(this.getMeetingInfo())}},this.getParticipantIdForOfferAnswer=e=>{Ua(e,"mediaContent should be a non null value"),this.logger.info("getParticipantIdForOfferAnswer");let t=null;return!this.remoteUser||this.groupId||this.threadId||e.newOffer||e.escalationOccurring||(t=this.remoteUser.id),t},this.getMeetingInfo=()=>this.meetingInfo,this.getEmergencyContent=()=>(this.telemetryHelper.recordEvent("GetEmergencyContent"),this.emergencyContent),this.getEndpointId=()=>this.signalingAgent.endpointId,this.getConversationUrl=()=>this.links[wa.LINKS.CONVERSATION_CONTROLLER],this.setJoinedFrom=e=>{!this.disposed&&e&&(this.telemetryHelper.recordEvent("SetJoinedFrom"),this.telemetryHelper.setJoinedFrom(e))},this.setMeetingCode=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingCode(e)},this.setMeetingUrl=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingUrl(e)},this.setSubject=e=>{this.disposed||(this.telemetryHelper.recordEvent("SetSubject"),Ua(e,"subject should be a non null value"),this.convSubject=e)},this.setDeviceType=e=>{this.disposed||(this.telemetryHelper.recordEvent("SetDeviceType"),e&&(this.deviceType=e,this.logger.info("setDeviceType",this.deviceType)))},this.setOfferAnswerGenerationTimestamps=e=>{this.disposed||this.telemetryHelper.setOfferAnswerGenerationTimestamps(e)},this.setTimeToRingDuration=()=>{this.disposed||this.telemetryHelper.setTimeToRingDuration()},this.setGroupId=e=>{this.telemetryHelper.recordEvent("SetGroupId"),this.groupId!==e&&e&&(xa(!this.groupId,"conversation groupId has already been set. It cannot be overwritten"),this.groupId=e)},this.setThreadId=e=>{this.telemetryHelper.recordEvent("SetThreadId"),Ua(e,"threadId should be a non null value"),this.threadId!==e&&(xa(!this.threadId,"conversation threadId has already been set. It cannot be overwritten"),this.threadId=e)},this.setDisplayName=e=>{!this.disposed&&e&&this.telemetryHelper.setDisplayName(e)},this.setCallOptions=e=>{if(Ua(e,"callOptions should be a non null value"),this.logger.info("setCallOptions",je(e)),this.telemetryHelper.recordEvent("SetCallOptions"),e){this.teamsMessageId=e.teamsMessageId,this.meetingInfo=e.meetingInfo||null,this.emergencyContent=e.emergencyContent||null,this.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration||!1,e.broadcastContext&&(this.broadcastSession=new jd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e.broadcastContext));try{this.endpointMetadata=JSON.parse(e.endpointMetadata)}catch(e){this.logger.warn("Unable to parse endpoint metadata")}}},this.setTransferContext=e=>{Ua(e,"transferContext should not be null"),this.logger.info("Transfer: setTransferContext",ke(e)),this.telemetryHelper.recordEvent("SetTransferContext"),this.transferContext=e},this.muteAsync=(e,t,i=Na())=>(xa(2!==this.callMode||e!==wa.MUTE_SCOPE.MYSELF,"mute self operation is not allowed in streaming mode"),this.logger.info(`[${i}][muteAsync][scope=${e}]`),this.telemetryHelper.recordEvent("Mute",{causeId:i}),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,`[${i}]mute operation for all or specified only allowed in a connected call`),this.participantManager.muteAsync(this.links[wa.LINKS.MUTE],e,t,i)),this.unmuteAsync=(e=Na())=>(xa(2!==this.callMode,"unmute operation is not allowed in streaming mode"),this.logger.info(`[${e}][unmuteAsync]`),this.telemetryHelper.recordEvent("Unmute",{causeId:e}),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"unmute operation only allowed in a connected call"),this.participantManager.unmuteAsync(this.links[wa.LINKS.UNMUTE],e)),this.recordTelemetryForStartAudio=(e,t)=>(this.telemetryHelper.recordEvent("StartAudio",{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.recordTelemetryForStopAudio=(e,t)=>(this.telemetryHelper.recordEvent("StopAudio",{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.rejectUnmuteRequestAsync=(e,t=Na(),i)=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"rejectUnmute operation only allowed in a connected call"),Fa(e,"requestor must be specified"),this.logger.info(`[${t}][rejectUnmuteRequestAsync][rejectionReason=${i}]`),this.telemetryHelper.recordEvent("RejectUnmute",{causeId:t,rejectionReason:i}),this.participantManager.rejectUnmuteRequestAsync(e,t,i)),this.approveUnmuteRequestAsync=(e,t=Na())=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"approveUnmute operation only allowed in a connected call"),Fa(e,"requestor must be specified"),this.logger.info(`[${t}][approveUnmuteRequestAsync]`),this.telemetryHelper.recordEvent("ApproveUnmute",{causeId:t}),this.participantManager.approveUnmuteRequestAsync(e,t)),this.sendWebRtcMediaNotificationAsync=(e,t,i=Na())=>(xa(2!==this.callMode,"sendWebRtcMediaNotification operation is not allowed in streaming mode"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"webRtc media notification can only be sent in a connected call"),this.telemetryHelper.recordEvent("SendWebRtcMediaNotification",{causeId:i}),0===e?this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:Zo.SEND_APPLY_CHANNEL_PARAMETERS.name,requestUrl:this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS],requestBody:t,stackRetry:!1},i):this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:Zo.SEND_CONTROL_VIDEO_STREAMING.name,requestUrl:this.links[wa.LINKS.CONTROL_VIDEO_STREAMING],requestBody:t},i)),this.addParticipantsAsync=(e,t,i=Na())=>{Fa(e,"remoteParticipants should be a non null value"),xa(this.isCallOngoing()||this.isCallNotConnected(),"remoteParticipants can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${i}][addParticipantsAsync][addParticipantOptions=${je(t)}]\n [remoteParticipantId=${e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)))}]`);let n=So;switch(t.replacementType){case 2:n="AddParticipantWithPickupCode";break;case 1:case 3:n="AddParticipantWithReplaces";break;default:n=So}this.telemetryHelper.recordEvent(n,{causeId:i}),t.groupId=this.groupId||t.groupId,t.threadId=this.threadId||t.threadId;const r=t.threadId||t.groupId?this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[wa.LINKS.ADD_PARTICIPANT],s=this.participantManager.addParticipantsAsync(e,r,this.isCallConnectedOrConnectedForRoster(),t,i);return this.currentCallStatus||this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i),s},this.addGroupModalityAsync=(e,t)=>{xa(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addGroupModalityAsync][addGroupModalityOptions=${je(e)}]`);this.telemetryHelper.recordEvent("AddParticipantsAndModality",{causeId:t});const i=Su(this,null,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY],payload:i,requestName:Zo.ADD_PARTICIPANTS_AND_MODALITY.name,causeId:t}).then((()=>{kd.noop()})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);throw this.logger.info(`[${t}][sendNetworkRequestForAddingParticipant] failed:${je(i)}`),i.error}))},this.addModalityAsync=(e,t)=>{xa(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addModalityAsync][modalityContext=${je(e)}]`),this.telemetryHelper.recordEvent("AddModality",{causeId:t});const i=function(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"broadcastContext cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},groupContext:t.groupContext?{id:t.groupContext.groupId}:null,groupChat:t.groupChat?{threadId:t.groupChat.threadId,messageId:t.groupChat.messageId}:null,links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}(this,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_MODALITY],payload:i,requestName:Zo.ADD_MODALITY.name,causeId:t}).then((e=>(this.logger.info(`[${t}][addModalityAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForAddModalityCompletion",{causeId:t}),wa.SUCCESS_TRANSACTION_END))).catch((e=>{const i=Ka(e);return this.logger.info(`[${t}][sendNetworkRequestForAddModalityAsync] failed:${je(i)}`),Promise.reject(i.error)}))},this.addBroadcastModalityAsync=(e,t)=>{if(xa(this.isCallOngoing(),"BroadcastModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addBroadcastModalityAsync][addBroadcastContext=${je(this.addBroadcastModalityAsync)}]`),this.telemetryHelper.recordEvent("AddBroadcastModality",{causeId:t}),this.broadcastSession){const e="There is already a broadcast session";return this.logger.info(e),Promise.resolve(wa.SUCCESS_TRANSACTION_END)}this.broadcastSession=new jd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e);const i=function(e,t){return Ua(e,"signalingSession cannot be null"),Ua(t,"broadcastContext cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},broadcast:t,links:{addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE)}}}}(this,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.ADD_MODALITY],payload:i,requestName:Zo.ADD_BROADCAST_MODALITY.name,causeId:t}).then((e=>(this.logger.info(`[${t}][addBroadcastModalityAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForAddBroadcastModalityCompletion",{causeId:t}),wa.SUCCESS_TRANSACTION_END))).catch((e=>{const i=Ka(e);return this.logger.info(`[${t}][sendNetworkRequestForAddBroadcastModalityAsync] failed:${je(i)}`),this.endBroadcastMeeting(t),Promise.reject(i.error)}))},this.nudgeParticipantsAsync=e=>{if(Ua(e.participantsIds,"ParticipantsIds should be a non null value"),xa(this.isCallOngoing(),"Participants can only be nudged before starting an outgoing call or to an ongoing call"),this.logger.info(`[${e.causeId}][nudgeParticipantsAsync][participantsIds=${this.piiUtils.scrubParticipantsList(e.participantsIds)}][invitationData=${e.invitationData}]`),void 0===e.participantsIds||e.participantsIds.length<1)return Promise.reject("List of participants to nudge is empty");this.telemetryHelper.recordEvent(So,{withNudge:wa.INVITATION_TYPE.NUDGE,causeId:e.causeId});const t=this.groupId||e.newGroupId,i=this.threadId||e.newThreadId,n=this.teamsMessageId||e.newMessageId,r=i||t?this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[wa.LINKS.ADD_PARTICIPANT];return this.participantManager.nudgeParticipantsAsync(e.participantsIds,r,this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,e.causeId,e.invitationData,t,i,n)},this.callMeBackAsync=(e,t=Na())=>(Ua(e,"remoteParticipant should be a non null value"),this.logger.info(`[${t}][callMeBackAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent("CallMeBack",{causeId:t}),this.hasGroupModality()||xa(!1,"threadId/groupId must be set before using call me back"),this.participantManager.callMeBackAsync(e,this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY],t)),this.removeParticipantAsync=(e,t=Na(),i="none")=>{switch(Ua(e,"remoteParticipant should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"participants can only be removed from an ongoing call"),this.logger.info(`[${t}][removeParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}] [removeEndpointScope] ${i}`),i){case"all":this.telemetryHelper.recordEvent("RemoveParticipantOthers",{causeId:t});break;case"specified":this.telemetryHelper.recordEvent("RemoveParticipantSpecified",{causeId:t});break;default:this.telemetryHelper.recordEvent("RemoveParticipant",{causeId:t})}return"none"!==i&&e.endpointId?this.participantManager.removeParticipantEndpointAsync(e,this.links[wa.LINKS.REMOVE_PARTICIPANT],i,t):this.participantManager.removeParticipantAsync(e,this.links[wa.LINKS.REMOVE_PARTICIPANT],t)},this.admitParticipantAsync=(e,t=Na())=>(Ua(e,"remoteParticipant should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"remoteParticipants can only be admitted to an ongoing call"),this.hasGroupModality()||xa(!1,"threadId/groupId must be set before admitting more participants to connected call"),this.logger.info(`[${t}][admitParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent("AdmitParticipant",{causeId:t}),this.participantManager.admitParticipantAsync(e,this.links[wa.LINKS.ADMIT],t)),this.admitAsync=e=>{if(this.logger.info(`[${e}][admitAsync]`),this.telemetryHelper.recordEvent("Admit",{causeId:e}),!this.links[wa.LINKS.ADMIT_ALL]){const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.ADMIT_ALL_LINK_MISSING,phrase:wa.CALL_END_PHRASE.ADMIT_ALL_URL_MISSING};return this.telemetryHelper.recordEvent(To,{causeId:e,transactionEnd:t}),this.logger.warn(`admitAsync error ${je(t)}`),Promise.reject(t)}const t=to();return this.callOperationHandler.setPendingOperation(0,e,{promise:t,causeId:e},e),this.sendNetworkRequestForAdmit(e),t.promise},this.updateMeetingRolesAsync=(e,t,i=Na())=>(Ua(e,"participants array should be a non null value"),Ua(t,"meetingRole should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"remote participant roles can only be updated in an ongoing call"),this.logger.info(`[${i}][updateMeetingRolesAsync][participants=${this.piiUtils.scrubMriOrOmit(e)}]`),this.participantManager.updateMeetingRolesAsync(e,t,this.links[wa.LINKS.UPDATE_PARTICIPANT_ROLE],i)),this.startContentSharingAsync=(e,t,i,n,r=Na())=>(Ua(e,"contentIdentifier should be a non null value"),xa(this.isCallOngoing(),"contentSharing can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${r}][startContentSharingAsync]`),this.telemetryHelper.recordEvent("AddContentSharingModality",{causeId:r}),this.contentSharingManager.startContentSharingAsync(e,t,i,this.links[wa.LINKS.ADD_MODALITY],this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,r,n)),this.deleteContentSharingAsync=(e,t=Na())=>(this.logger.info(`[${t}][deleteContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent("DeleteContentSharing",{causeId:t,correlationId:e}),this.contentSharingManager.deleteContentSharingAsync(e,t)),this.joinContentSharingAsync=(e,t=Na())=>(this.logger.info(`[${t}][joinContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent("JoinContentSharing",{causeId:t,correlationId:e}),this.contentSharingManager.joinContentSharingAsync(e,t)),this.updateContentSharingSessionStateAsync=(e,t,i=Na())=>(Ua(t,"sessionState should be a non null value"),this.telemetryHelper.recordEvent("UpdateSessionStateContentSharing",{causeId:i,correlationId:e}),this.logger.info(`[${i}][updateContentSharingSessionStateAsync][correlationId=${e}][sessionState=${t}]`),this.contentSharingManager.updateContentSharingSessionStateAsync(e,t,i)),this.takeContentSharingControlAsync=(e,t=Na())=>(this.telemetryHelper.recordEvent("TakeControlContentSharing",{causeId:t,correlationId:e}),this.logger.info(`[${t}][takeContentSharingControlAsync][correlationId=${e}]`),this.contentSharingManager.takeContentSharingControlAsync(e,t)),this.updateContentSharingParticipantStateAsync=(e,t=Na())=>(this.telemetryHelper.recordEvent("UpdateParticipantStateContentSharing",{causeId:t}),this.logger.info(`[${t}][updateContentSharingParticipantStateAsync][correlationId=${e}]`),this.contentSharingManager.updateContentSharingParticipantStateAsync(e,t)),this.configureEndpointStateForStartOrJoin=e=>{const t={endpointStateSequenceNumber:this.endpointStateSequenceNumber};let i=!1;if(e&&(e.muted&&(i=!0,Object.assign(t,{state:{isMuted:e.muted}})),e.isPreheatOnly||e.additionalEndpointProperties)){const n={};i=!0,e.isPreheatOnly&&(n.preheatProperties=1),e.additionalEndpointProperties&&(n.additionalEndpointProperties=e.additionalEndpointProperties),Object.assign(t,{endpointProperties:n})}if(i)return t},this.gatherTelemetryForStartOrJoin=(e,t,i)=>{const n={causeId:t};return e&&(e.invitationType===wa.INVITATION_TYPE.NUDGE&&(n.withNudge=e.invitationType===wa.INVITATION_TYPE.NUDGE),e.parkContext&&(n.unpark=!0,n.context=e.parkContext),e.isPreheatOnly&&(n.isPreheatOnly=!0),e.targetApplicationType&&(n.targetApplicationType=e.targetApplicationType,this.telemetryHelper.setTargetApplicationType(e.targetApplicationType))),n},this.startOutgoingCall=(e,t,i,n,r=Na())=>{if(Ua(e,"mediaContent should be a non null value"),Ua(e.blob,"outgoingSdp should be a non null value"),xa(this.isCallNotConnected(),"a call is already in progress"),this.logger.info(`[${r}][startOutgoingCall][start] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${r}][startOutgoingCall][failed][reason=Session disposed]`);this.lastUsedJoinCallOptions={muted:i?i.muted:null,scenario:i?i.scenario:null,isPreheatOnly:i?i.isPreheatOnly:null,clientEndpointCapabilities:i?i.clientEndpointCapabilities:null,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null},this.originalRoleBeforePreheat=ud,i&&i.scenario&&this.telemetryHelper.setScenario(i.scenario),this.logger.info(`[${r}][startOutgoingCall]options=${je(this.gatherTelemetryForStartOrJoin(i,r,n))}`),this.isBrokerEnabledForOutgoingCall()&&this.setupBrokerChannel(),this.callUsesMixer=!(!i||!i.callUsesMixer),this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING,this.meetingData=i?.meetingData,this.meetingPreferences=i?.meetingPreferences;const s={newCall:!0,suppressDialout:i&&i.suppressDialout||!1,conversationServiceUrl:this.signalingAgentConfig.conversationServiceUrl,onBehalfOf:i?i.onBehalfOf:null,onBehalfOfUserDisplayName:i?i.onBehalfOfUserDisplayName:null,callQueueContext:i?i.callQueueContext:null,callToVoicemail:!!i&&i.callToVoicemail,voicemailResourcePath:i?i.voicemailResourcePath:null,voicemailItemId:i?i.voicemailItemId:null,endpointState:this.configureEndpointStateForStartOrJoin(i),invitationType:i&&i.invitationType?i.invitationType:null,participantsToNudge:i&&Array.isArray(i.participantsToNudge)?i.participantsToNudge:null,routingFlags:i?i.routingFlags:null,parkContext:i?i.parkContext:null,pickupCode:i?i.pickupCode:null,scenario:i?i.scenario:null,isPreheatOnly:!!i&&i.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:i?i.clientEndpointCapabilities:0,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null,invitationData:i?i.invitationData:null,conversationType:i?this.getConversationType(i.isEmergency,i.castCall,i.isHuddleGroupCall):null,meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,alternateId:i?i.alternateId:null,meetingRegistrationId:i?i.meetingRegistrationId:null,participantPin:i?i.participantPin:null,publishedStates:i?i.publishedStates:null,targetApplicationType:i?i.targetApplicationType:null,captchaContentJson:i?i.captchaContentJson:null,customHeaderContext:i?i.customHeaderContext:null,participationPreferences:i?i.participationPreferences:null,participantPropertyBag:i?i.participantPropertyBag:null};this.isCastCall=i&&i.castCall,this.isHuddleGroupCall=i&&i.isHuddleGroupCall,this.onBehalfOf=s.onBehalfOf,this.onBehalfOfUserDisplayName=s.onBehalfOfUserDisplayName,this.callQueueContext=s.callQueueContext,this.startOrJoinCall(s,Zo.START_CALL.name,r,e,t)},this.joinGivenConversation=(e,t,i,n,r,s={},a=Na())=>{if(Ua(t,"correlationId should be a non null value"),Fa(e||this.getConversationUrl(),"conversationUrl should be a non null value"),Ua(i,"mediaContent should be a non null value"),Ua(i.blob,"outgoingSdp should be a non null value"),this.isPromotingToRealtime=2===this.callMode,xa(this.isCallNotConnected()||this.isPromotingToRealtime,"a call is already in progress"),this.logger.info(`[${a}][joinGivenConversation][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${a}][joinGivenConversation][failed][reason=Session disposed]`);const o=this.gatherTelemetryForStartOrJoin(s,a,r);this.lastUsedJoinCallOptions=s,this.originalRoleBeforePreheat=gd,this.telemetryHelper.startCallInitializationWatch(r),s&&s.scenario&&this.telemetryHelper.setScenario(s.scenario),this.logger.info(`[${a}][joinGivenConversation]options=${je(o)}`),this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING,this.updateCorrelationId(t,a),this.meetingData=s?.meetingData,this.meetingPreferences=s?.meetingPreferences;const l={newCall:!1,suppressDialout:!0,conversationServiceUrl:e,endpointState:this.configureEndpointStateForStartOrJoin(s),scenario:s?s.scenario:null,isPreheatOnly:!!s&&s.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:s?s.clientEndpointCapabilities:0,clientEndpointDebugContent:s?s.clientEndpointDebugContent:null,conversationType:s?this.getConversationType(s.isEmergency,!1):null,meetingPreferences:this.meetingPreferences,meetingData:this.meetingData,meetingRegistrationId:s?.meetingRegistrationId,participantPin:s?.participantPin,sharedLineCallInvitationContent:s?.sharedLineCallInvitationContent,applyServerMute:s?.applyServerMute,publishedStates:s?.publishedStates,invitationData:s?.invitationData,captchaContentJson:s?.captchaContentJson,callQueueContext:s?.callQueueContext,participationPreferences:s?.participationPreferences,participantPropertyBag:s?.participantPropertyBag};this.isCastCall=!1,this.startOrJoinCall(l,Zo.JOIN_CONVERSATION.name,a,i,n)},this.subscribeToCall=(e,t,i=0,n,r=Na())=>{Ua(t,"correlationId should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.IDLE,"a call is already in progress");let s=e;return s||(s=this.signalingAgentConfig.conversationServiceUrl,this.logger.info(`conversationServiceUrl passed is empty. so it is set to ${s}`)),Fa(s,"conversationUrl should be a non null value"),this.logger.info(`[${r}][subscribeToCall][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed?(this.logger.warn(`[${r}][subscribeToCall][failed][reason=Session disposed]`),Promise.reject(wa.CALL_END_CODE.CALL_DOES_NOT_EXIST)):(this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.lastUsedJoinCallOptions=n||{},this.lastUsedJoinCallOptions.clientEndpointCapabilities=i||this.lastUsedJoinCallOptions?.clientEndpointCapabilities,this.meetingData=n?.meetingData,this.meetingPreferences=n?.meetingPreferences,this.fsmState=wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY,this.updateCorrelationId(t,r),this.http.sendPostRequest({url:s,requestName:Zo.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,operationType:"CallSetup",payload:Uu(this,null,null,{subscribe:!0,clientEndpointCapabilities:i,...n,applicationType:this.participantManager.localParticipant.applicationType,endpointState:this.configureEndpointStateForStartOrJoin({additionalEndpointProperties:n?.additionalEndpointProperties})},r),causeId:r}).then((e=>{this.disposed||(this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.processConversationServiceResponseHeaders(e,r),this.processConversationServiceResponse(e.response,r,1),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY,r))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return Promise.resolve();const t=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${r}][subscribeToCall] error: ${je(e)} xhrError: ${je(t)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:t.telemetryEndSubCode,endSubCode:t.error.subCode,resultCategories:t.error.resultCategories,resultDetail:t.error.phrase||"SubscribeFailure",causeId:r}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,r,t.error),Promise.reject(t.error))})))},this.getCallReplacementDetailsForCall=(e,t=Na())=>{this.logger.info(`[${t}] getCallReplacementDetailsForCall callId ${e}`);const i=this.signalingAgent.getSignalingSession(e);return i?i.getCallReplacementDetails(t):{replaces:""}},this.getCallReplacementDetails=(e=Na())=>(this.logger.info(`[${e}] getCallReplacementDetails`),{replaces:this.links[wa.LINKS.REPLACE]}),this.transferCallAsync=(e,t,i,n,r=Na())=>{this.logger.info(`[${r}] transferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(e)} transferType ${t} callTransferOptions: ${Ge(n)}`),this.transferHelper(e,t,i,n,r)},this.redirectCall=(e,t=Na(),i)=>{const{id:n,endpointType:r,type:s}=e.redirectOptions;if(this.logger.info(`[${t}] redirectCall: targetId: ${this.piiUtils.scrubMriOrOmit(n)} targetEndpointType ${r}`),!this.isRedirectAllowed){const e={code:wa.CALL_END_CODE.REJECT,phrase:wa.CALL_END_PHRASE.CALL_REDIRECT_IS_NOT_ALLOWED};return Promise.reject(e)}this.telemetryHelper.recordEvent("CallRedirect",{causeId:t});const a=function(e,t,i,n){Ua(e,"signalingSession cannot be null");const r=e.participantManager.localParticipant;return{payload:{invitationRedirection:{target:{type:t,endpointType:n,id:i},sender:{id:r.id,endpointId:r.endpointId,participantId:r.participantId,languageId:r.languageId}}}}}(this,s,n,r);return this.http.sendPostRequest({url:this.links[wa.LINKS.REDIRECT],requestName:Zo.SEND_CALL_REDIRECT_REQUEST.name,payload:a,causeId:t}).then((n=>(this.logger.info(`[${t}][redirectCall] succeeds. Leaving the call...`),this.telemetryHelper.recordEvent("CallRedirectRequestSent",{causeId:t,targetEndpointType:r}),this.terminateEstablishedCall(i,e)))).catch((e=>{const n=Ka(e);this.logger.info(`[${t}][redirectCall] error: ${je(n)}`);const s=n.error;return this.telemetryHelper.recordEvent("CallRedirectRequestFailed",{causeId:t,transactionEnd:s,endpointType:r}),this.disposed||(this.telemetryHelper.setTerminatingData({terminatingEnd:sd,endCode:i.code,endSubCode:i.subCode,clientReasonSubCode:i.clientReasonSubCode,clientReasonPhrase:i.clientReasonPhrase,resultDetail:i.phrase||"RedirectCall",resultCategories:i.resultCategories,causeId:t}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,i),this.dispose(i,t)),Promise.reject(s)}))},this.transferHelper=(e,t,i,n,r=Na())=>{xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet");let s=!1;this.logger.info(`[${r}][transferHelper][replacementDetails=${je(i)}] disableForwardingAndUnanswered=${n&&n.disableForwardingAndUnanswered}`),this.telemetryHelper.recordEvent("TransferCall",{causeId:r}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(r,s)}),wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER],requestName:Zo.SEND_TRANSFER_REQUEST.name,payload:Wu(e,this,i,t,n),causeId:r}).then((()=>{this.telemetryHelper.recordEvent("WaitingForTransferAcceptance",{causeId:r}),s=!0})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${r}][transferCallAsync] error: ${je(t)}`),this.disposed||(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.NETWORK_ERROR,reason:je(e)}},r),this.telemetryHelper.recordEvent(Vo,{causeId:r,...t.error}))})),this.telemetryHelper.recordEvent(Bo,{causeId:r,transferType:t})},this.consultTransferCallAsync=(e,t,i,n,r)=>{let s,a;if(this.logger.info(`[${n}] consultTransferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(t)} transferTargetParticipantLegId: ${i}`),i?(a=this.getMriByParticipantLegOfCall(e,i,n),s=this.getReplacementDetailsByParticipantLegOfCall(e,t,i,n)):(a=t,s=this.getCallReplacementDetailsForCall(e,n)),!a||!s){const r=s?"target mri corresponding not found":`unable to retrieve replacementDetails for transferTargetCallId: ${e}, transferTargetMri: ${t}, transferTargetParticipantLegId: ${i}`;return this.logger.info(`[${n}] consultTransferCallAsync: error: ${r}`),void this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.BAD_REQUEST,reason:r}},n)}this.transferHelper(a,"TransferTypeStandard",s,r,n)},this.isParkByTransfer=(e,t)=>{const i=["serverHold","sharedLinePark","teamPark"].indexOf(e)>-1;return this.logger.info(`[${t}][isParkByTransfer][context=${e}] result = ${i}`),i},this.parkCallAsync=(e,t=Na())=>{if(e&&"none"===e)throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};return xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet"),this.logger.info(`[${t}][parkCallAsync][context=${e}]`),this.telemetryHelper.recordEvent("ParkCall",{causeId:t,parkType:co(e)}),this.isParkByTransfer(e,t)?this.parkByTransfer(e,t):this.park(e,t)},this.unparkAsync=(e,t=Na())=>{if(e&&"none"===e)throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};if(!this.links[wa.LINKS.UNPARK])throw{code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark link not available"};this.logger.info(`[${t}][unparkAsync][context=${e}]`),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION,(()=>{this.handleUnparkError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UNPARK_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UNPARK_COMPLETION_TIMEOUT},"WaitingForUnparkCompletionTimeout",t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.UNPARK_COMPLETION_TIMEOUT);const i={causeId:t};return this.http.sendPostRequest({url:this.links[wa.LINKS.UNPARK],requestName:Zo.SEND_UNPARK_REQUEST.name,payload:Ju(this,i),causeId:t}).then((e=>(this.logger.info(`[${t}][unparkAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForUnparkCompletion",{causeId:t}),Promise.resolve()))).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][unparkAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUnparkError(n.error,"UnparkRequestFailed",t,e),Promise.reject(n.error))}))},this.handleUpdateParticipantsPropertiesCompletion=e=>{const t=e.body,i=Qa(e),n=this.logger.createChild(`[${i}][handleUpdateParticipantsPropertiesCompletion]`,this.correlationId),r={};if(this.disposed)n.info("ignored. Call disposed.");else{if(t.operationId||n.warn("operationId is undefined."),n.info("starts"),t.participantInfos)for(const e of t.participantInfos){if(!e.participant.id){n.warn("participant id is undefined."),this.telemetryHelper.recordEvent(qo,"participant id is undefined in response, property");continue}if(!e.participant.key){n.warn("property name (key) is undefined."),this.telemetryHelper.recordEvent(qo,"property name (key) is undefined in response");continue}const s=Pu(e.participant.id,t.operationId,e.participant.key),a={code:e.transactionEnd.code,subCode:e.transactionEnd.subCode,phrase:e.transactionEnd.phrase,resultCategories:e.transactionEnd.resultCategories};n.info(`Update participants properties completed for: ${this.piiUtils.scrubMriOrOmit(e.participant.id)} with transactionEnd ${je(a)}`),this.telemetryHelper.recordEvent("UpdateParticipantsPropertiesResponseCompleted",{causeId:i,resolveId:this.piiUtils.scrubMriOrOmit(s),property:e.participant.key,result:je(a)}),r[s]=a,this.updateParticipantsPromises[t.operationId].delete(s)}this.checkAndCleanupPromisesForOperationId(t.operationId),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(r,t.operationId,i)}},this.getCallStatus=()=>this.currentCallStatus,this.processIncomingCallRequest=(e,t,i=Na())=>{Ua(e,"request should be a non null value"),Fa(e.body,"request should have a valid body"),Fa(e.body.gp||e.body.cp,"request body should have payload"),xa(this.isCallNotConnected(),"a call is already in progress");const n=this.logger.createChild(`[${i}][processIncomingCallRequest]`);if(this.callUsesMixer=e.fromMixer,n.info("[start]"),this.disposed)return void n.warn("processIncomingCallRequest canceled");this.telemetryHelper.startCallInitializationWatch(),this.isIncomingCall=!0,this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=wa.SIGNALING_FSM_STATE.INCOMING,this.participantManager.initializeForIncomingCall();let r={};try{t&&(r=JSON.parse(t))}catch(e){n.warn("Unable to parse endpoint metadata")}this.endpointMetadata=r;try{let t;if(e?.body?.gp&&!Xe(e.body.gp))n.info("unencoded payload, skipping decoding."),t=e.body.gp;else{const i=e.body.gp?atob(e.body.gp):eo(e.body.cp);t=JSON.parse(i)}if(!t.callNotification)throw n.info("[failed][reason=CallNotification missing]"),new Error("CallNotification is missing");n.info(`incoming call payload: ${Ge(ke(t))}`),this.processIncomingCallPayload(t,i),this.incomingCallPayload=t}catch(e){this.endIncomingCallBecauseOfInvalidPayload(i)}},this.sendAttachToCall=(e=Na())=>(this.logger.info(`[${e}][sendAttachToCall]`),this.incomingCallPayload?(this.onCallStatusChanged(wa.CALL_STATUS.IDLE,e),this.sendAttachToCallInternal(e)):(this.endIncomingCallBecauseOfInvalidPayload(e),Promise.reject(wa.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD))),this.supportsNewOfferRequest=()=>this.signalingAgentConfig.handleNewOfferRequest,this.requestNewOffer=(e,t=Na())=>(this.telemetryHelper.recordEvent("RequestNewOffer",{compatibleContentTypes:e,causeId:t}),this.signalingAgentConfig.handleNewOfferRequest?(Fa(this.links[wa.LINKS.NEW_OFFER],"newOffer link should be a non null value"),this.http.sendPostRequest({url:this.links[wa.LINKS.NEW_OFFER],requestName:Zo.REQUEST_NEW_OFFER.name,payload:Vu(this,e,this.links[wa.LINKS.NEW_OFFER]),causeId:t}).then((e=>this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):Promise.resolve(e))).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[requestNewOffer][${t}] error ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||"RequestNewOfferFailure",causeId:t}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,i.error),this.dispose(i.error,t),Promise.reject(i.error))}))):Promise.reject("Disabled")),this.endAsync=(e,t={})=>{t.causeId=t.causeId||Na();const i=t.causeId;if(this.logger.info(`[${i}][endAsync][rejectionData=${e&&je(e)}][endCallForAll=${t.forEveryone}]`),this.disposed)return this.logger.warn(`[${i}][endAsync] canceled but session already disposed`),Promise.resolve(null);if(this.disposing=!0,this.telemetryHelper.recordEvent("EndCall",e?{code:e.code,subCode:e.subCode,causeId:i,callEndClientSubCode:e.clientReasonSubCode,callEndClientPhrase:e.clientReasonPhrase}:{causeId:i}),t.preventAllCallbacks){const e=Object.keys(this.signalingSessionCallback);for(const t of e)this.signalingSessionCallback[t]=kd.noop}const n=this.mediaRenegotiationManager?.isIncomingRenegotiationInProgress()||this.mediaRenegotiationManager?.isOutgoingRenegotiationInProgress();if(this.telemetryHelper.stopCallCancelationDurationWatch(),this.fsmState===wa.SIGNALING_FSM_STATE.INCOMING)return e.code===wa.CALL_END_CODE.CALL_REDIRECTED?this.redirectCall(t,i,e):this.rejectIncomingCall(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY)return this.cancelOutgoingCall(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK)return this.rejectIncomingCall(e,i);if((this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||n)&&t.forEveryone)return this.deleteConversation(e,i);if(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||n)return this.terminateEstablishedCall(e,t);{this.logger.info(`[${i}][endAsync] there is no call to cancel or end or reject in current state`);const t={code:isNaN(e?.code)?wa.CALL_END_CODE.NOT_FOUND:e.code,subCode:isNaN(e?.subCode)?wa.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED:e.subCode,phrase:e?.phrase||wa.CALL_END_PHRASE.CALL_DOES_NOT_EXIST,resultCategories:e?.resultCategories||[Zs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};return this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultDetail:t.phrase||"CallDoesNotExist",endCode:t.code,endSubCode:t.subCode,resultCategories:t.resultCategories,causeId:i,clientReasonSubCode:t.clientReasonSubCode,clientReasonPhrase:t.clientReasonPhrase}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,t),this.dispose(t,i),Promise.resolve(null)}},this.handleIncomingMsgAsync=(e,t=wa.INCOMING_MESSAGE_ORIGIN.TROUTER)=>{Ua(e,"incoming message should be a non null value");const i=Ya(e),n=to(),r=e.body,s=e.url,a={...e,origin:t},o=Qa(a);if(this.logger.info(`[${o}][handleIncomingMsgAsync][url=${s}][messageId=${i}]`),!r)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(xo,{origin:t,messageId:i,causeId:o}),n.reject(new Error("received message with no body")),n.promise;if(this.disposed)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=call is disposed]`),n.reject(this.getCallNotFoundTransactionEnd()),n.promise;if(this.isDuplicatedIncomingMessage(a))return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=duplicate]`),this.telemetryHelper.recordEvent(No,{origin:t,messageId:i,causeId:o}),n.resolve(new Error("Message was already handled")),n.promise;this.checkCorrelationIdChange(e,o);const l={[sa]:e=>{this.handleCallNotification(e)},[aa]:e=>{this.handleMediaAnswer(e)},[oa]:e=>{this.handleMediaAcknowledgement(e)},[la]:e=>{this.handleCallAcceptance(e)},[ca]:e=>{this.handleCallEnd(e,!1)},[da]:e=>{this.handleCallProgress(e)},[ua]:e=>{this.handleCallAcceptanceAck(e)},[ha]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationOffer(e)},[ga]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationFailure(e)},[pa]:e=>{this.handlePSTNBalanceUpdate(e)},[ma]:e=>{this.mediaRenegotiationManager?.handleRetargetCompleted(e)},[fa]:e=>{this.handleTransferRequested(e)},[va]:e=>{this.handleTransferCompletion(e)},[Sa]:e=>{this.handleTransferAcceptance(e)},[ya]:e=>{this.handleParkCompletion(e)},[Ca]:e=>{this.handleUnparkCompletion(e)},[Ta]:e=>{this.handleUpdateMeetingLiveStateCompletion(e)},[Ea]:e=>{this.handleUpdateMeetingGroupsCompletion(e)},[ba]:e=>{this.handleSetMeetingLayoutCompletion(e)},[_a]:e=>{this.handleUpdateMeetingStatesCompletion(e)},[Ia]:e=>{this.handleUpdateMonitorSessionCompletion(e)}},c={[ra.CONTROL_VIDEO_STREAMING]:e=>{this.webRtcSignalingManager.handleControlVideoStreaming(e)},[ra.DOMINANT_SPEAKER_INFO]:e=>{this.webRtcSignalingManager.handleDominantSpeakerInfo(e)},[ra.CSRC_INFO]:e=>{this.webRtcSignalingManager.handleCsrcInfo(e)},[ra.CONV_ROSTER_UPDATE]:e=>{this.handleRosterUpdate(e,!1)},[ra.NEW_MEDIA_OFFER]:e=>{this.handleNewMediaOffer(e)},[ra.CONV_ADD_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAddParticipantSuccess(e)},[ra.CONV_ADD_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAddParticipantFailure(e)},[ra.CONV_ADMIT_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAdmitParticipantSuccess(e)},[ra.CONV_ADMIT_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAdmitParticipantFailure(e)},[ra.CONV_ADMIT_ALL_STATUS]:e=>{this.handleAdmitAllStatus(e)},[ra.CONV_REMOVE_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleRemoveParticipantSuccess(e)},[ra.CONV_REMOVE_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleRemoveParticipantFailure(e)},[ra.CONV_CONFIRM_UNMUTE]:e=>{this.participantManager.handleUnmuteConfirmRequest(e)},[ra.CONV_UPDATE]:e=>{this.handleConversationUpdate(e)},[ra.CONV_LOCAL_PARTICIPANT_UPDATE]:e=>{this.handleLocalParticipantUpdate(e)},[ra.CONV_ADD_MODALITY_SUCCESS]:e=>{this.handleAddModalitySuccess(e)},[ra.CONV_ADD_MODALITY_FAILURE]:e=>{this.handleAddModalityFailure(e)},[ra.CONV_BROADCAST_UPDATE]:e=>{this.broadcastSession.handleBroadcastStateChanged(e)},[ra.CONV_CONTENT_SHARING_UPDATE]:e=>{this.contentSharingManager?.handleContentSharingUpdate(e)},[ra.CONV_CONTENT_SHARING_END]:e=>{this.contentSharingManager?.handleContentSharingEnd(e)},[ra.CONV_END]:e=>{this.handleCallEnd(e,!1)},[ra.CONV_END_JOIN]:e=>{this.handleCallEnd(e,!1)},[ra.CONV_END_SUBSCRIBE]:e=>{this.handleCallEnd(e,!0)},[ra.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS]:e=>{this.participantManager.handleUpdateParticipantInterpretationStateCompletion(e)},[ra.UPDATE_PARTICIPANT_PROPERTIES_STATUS]:e=>{this.handleUpdateParticipantsPropertiesCompletion(e)},[ra.JOIN_MEETING_GROUP_STATUS]:e=>{this.handleJoinMeetingGroupCompletion(e)},[ra.LEAVE_MEETING_GROUP_STATUS]:e=>{this.handleLeaveMeetingGroupCompletion(e)},[ra.RECEIVE_MESSAGE]:e=>{this.handleReceiveMessage(e)},[ra.SEND_MESSAGE_STATUS]:e=>{this.proxiedMessageNotificationManager.handleProxiedMessageNotification(e)},[ra.DISABLE_PREHEAT_ASYNC_STATUS]:e=>{this.handleDisablePreheatCompletion(e)},[ra.MUTE_UNMUTE_ASYNC]:e=>{this.participantManager.handleMuteUnmuteAsyncResponse(e)},[ra.SET_MEETING_LAYOUT_STATUS]:e=>{this.handleSetMeetingLayoutCompletion(e)}};try{const e=Object.keys(l).filter((e=>r.hasOwnProperty(e)))[0],t=this.signalingAgentConfig.enableSplitConversationEndUrl&&(ja(a.url,ra.CONV_END_JOIN)||ja(a.url,ra.CONV_END_SUBSCRIBE))?Object.keys(c).filter((e=>a.url&&ja(a.url,e)))[1]:Object.keys(c).filter((e=>a.url&&ja(a.url,e)))[0];e?l[e](a):t?c[t](a):(this.telemetryHelper.recordEvent("UnkownMessageType",{messageId:i}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received unknown message]`)),n.resolve(!0)}catch(e){this.telemetryHelper.recordEvent(Lo,{messageId:i,error:je(e)}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=${e.message}]`),n.reject(new Error(e.message))}return n.promise},this.canHandleIncomingMsgSync=e=>{if(this.signalingAgentConfig.supportsSynchronousTrouterResponse){const t=e.body;return Boolean(t.callAcceptance)}return!1},this.handleIncomingMsgSync=e=>{const t=Ya(e),i=e.body,n=e.url,r=wa.INCOMING_MESSAGE_ORIGIN.TROUTER,s={...e,origin:r},a=Qa(s);this.logger.info(`[${a}][handleIncomingMsgSync][url=${n}][messageId=${t}]`);const o=s.headers;let l=wa.HTTP_STATUS_CODES.OK,c="";const d=new Pa;if(Ja(o,this.incomingTrouterMessagesSeenSoFar)){this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=duplicate]`);const e=function(e,t){return e&&t[e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(wa.HEADERS.MESSAGE_ID)||null]||null}(o,this.incomingMessageSyncResponseCache);if(e)return this.logger.info(`[${a}][handleIncomingMsgSync][cachedResponse]`),e;this.telemetryHelper.recordEvent(No,{origin:r,messageId:t,causeId:a}),this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=cachedResponseNotFound]`),l=wa.HTTP_STATUS_CODES.BAD_REQUEST}else if(i){if(i.callAcceptance)try{c=Ge(this.handleCallAcceptanceSync(s))}catch(e){this.telemetryHelper.recordEvent(Lo,{messageId:t,origin:r,causeId:a,error:je(e)}),this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=${e?.message}]`),l=wa.HTTP_STATUS_CODES.BAD_REQUEST}}else this.logger.info(`[${a}][handleIncomingMsgSync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(xo,{origin:r,messageId:t,causeId:a}),l=wa.HTTP_STATUS_CODES.BAD_REQUEST;o&&(o.get(wa.HEADERS.CORRELATION_ID)&&d.set(wa.HEADERS.CORRELATION_ID,o.get(wa.HEADERS.CORRELATION_ID)),o.get(wa.HEADERS.MESSAGE_ID)&&d.set(wa.HEADERS.MESSAGE_ID,o.get(wa.HEADERS.MESSAGE_ID)));const u={resultCode:l,responseBody:c,responseHeaders:d.getAll()};return function(e,t,i){if(e&&t){const n=e.get(wa.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(wa.HEADERS.MESSAGE_ID)||null;n&&(t[n]=i)}}(o,this.incomingMessageSyncResponseCache,u),this.logger.info(`[${a}][handleIncomingMsgSync][success][resultCode=${l}]`),u},this.acceptRenegotiationAsync=(e,t,i=Na())=>(Ua(e.blob,"finalSdp should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.mediaRenegotiationManager.acceptRenegotiationAsync(e,t,i)),this.setProvisionalAnswerAsync=(e,t=Na())=>{Ua(e.blob,"sdp should be a non null value"),this.telemetryHelper.recordEvent("SetProvisionalAnswer",{causeId:t});const i=to();return this.fsmState!==wa.SIGNALING_FSM_STATE.INCOMING?(this.logger.info(`[setProvisionalAnswerAsync][${t}] there is no incoming call to set provisional answer on.`),i.reject(new Error("there is no incoming call to set provisional answer on.")),i.promise):(this.http.sendPostRequest({url:this.links[wa.LINKS.MEDIA_ANSWER],requestName:Zo.SEND_MEDIA_ANSWER.name,payload:Xu(this,e),causeId:t}).then((e=>{this.disposed||this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,t),i.resolve(null),this.disposed||(this.telemetryHelper.recordEvent(fo,{causeId:t}),this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,t),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!1,t))})).catch((e=>{const n=Ka(e,this.signalingAgentConfig);this.logger.info(`[setProvisionalAnswerAsync][${t}] error: ${je(n)}`),this.disposed?i.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent("SetProvisionalAnswerFailed",{causeId:t}),i.reject(n.error))})),i.promise)},this.startRenegotiationAsync=(e,t,i=Na())=>(Ua(e,"mediaContent should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][startRenegotiationAsync]`),this.mediaRenegotiationManager.startRenegotiationAsync(e,this.links[wa.LINKS.MEDIA_RENEGOTIATION],t,i)),this.updateMediaDescriptionsAsync=(e=Na(),t)=>{Ua(t,"mediaDescriptions should be a non null value"),xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"updateMediaDescriptions operations are only allowed when the call is connected");const i=this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS];return Ua(i,"updateMediaDescriptionsUrl should be a non null value"),this.telemetryHelper.recordEvent("UpdateMediaDescriptions",{causeId:e}),this.http.sendPostRequest({url:i,requestName:Zo.UPDATE_MEDIA_DESCRIPTIONS.name,payload:eh(this,t),causeId:e}).catch((t=>{const i=Ka(t,this.signalingAgentConfig);return this.logger.info(`[updateMediaDescriptionsAsync][${e}] error: ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent("UpdateMediaDescriptionsFailed",{causeId:e}),Promise.reject(i.error))}))},this.acceptAsync=(e,t,i,n=Na())=>{Ua(e,"mediaContent should be a non null value"),Ua(e.blob,"outgoingSdp should be a non null value"),this.logger.info(`[${n}][acceptAsync][mediaTypes=${t}]`),this.telemetryHelper.recordEvent("AcceptCall",{causeId:n}),this.telemetryHelper.setAnsweredModalities(e.blob);const r=to();return this.fsmState!==wa.SIGNALING_FSM_STATE.INCOMING?(this.logger.warn("acceptAsync, there is no incoming call to accept"),r.reject(new Error("there is no incoming call to accept")),r.promise):(this.fsmState=wa.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK,this.http.sendPostRequest({url:this.links[wa.LINKS.ACCEPT],requestName:Zo.SEND_ACCEPTANCE.name,payload:Ou(this,e,t,i),causeId:n}).then((e=>{this.disposed||(this.currentCallStatus===wa.CALL_STATUS.IDLE&&(this.telemetryHelper.setTimeToRingDuration(),this.telemetryHelper.recordEvent("AcceptedBeforeRinging",{causeId:n}),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,n)),e.response.callAcceptanceAcknowledgement&&(this.logger.info("acceptAsync, handling inlined callAcceptanceAcknowledgement"),this.internalHandleCallAcceptanceAck(e.response,n))),r.resolve(null)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[acceptAsync][${n}] error: ${je(t)}`),this.disposed?r.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=wa.SIGNALING_FSM_STATE.INCOMING,this.telemetryHelper.recordEvent("AcceptCallFailed",{causeId:n,xhrError:t}),r.reject(t.error))})),r.promise)},this.rejectRenegotiationAsync=(e,t=Na())=>(xa(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${t}][rejectRenegotiationAsync][rejectionData=${e}]`),this.mediaRenegotiationManager.rejectRenegotiationAsync(e,t)),this.saveMediaControllerLinksIfAny=e=>{e.links&&(this.links[wa.LINKS.CONTROL_VIDEO_STREAMING]=e.links.controlVideoStreaming||this.links[wa.LINKS.CONTROL_VIDEO_STREAMING],this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS]=e.links.applyChannelParameters||this.links[wa.LINKS.APPLY_CHANNEL_PARAMETERS])},this.getInitialMediaOfferFromIncomingCallPayload=(e=Na())=>{if(!this.signalingAgentConfig.handleMediaOfferFromPushNotification)return null;const t=this.incomingCallPayload?.callNotification?.mediaContent?this.incomingCallPayload.callNotification.mediaContent:null;return this.telemetryHelper.setIsSdpInCallNotification(!!t),t},this.updateCorrelationId=(e,t=Na())=>{if(this.logger.info(`[${t}][updateCorrelationId][old=${this.correlationId}][new=${e}]`),this.correlationId!==e&&!this.disposed){const i=this.correlationId;this.correlationId=e,this.telemetryHelper&&this.telemetryHelper.recordEvent&&this.telemetryHelper.recordEvent("CorrelationIdUpdated",{newId:this.correlationId,oldId:i,causeId:t}),this.signalingSessionCallback&&this.signalingSessionCallback.onCorrelationIdUpdated&&this.signalingSessionCallback.onCorrelationIdUpdated(this.correlationId,t)}},this.endIncomingCallBecauseOfInvalidPayload=e=>{this.logger.info(`[${e}][endIncomingCallBecauseOfInvalidPayload]`),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const t={code:wa.CALL_END_CODE.BAD_REQUEST,subCode:wa.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD,phrase:wa.CALL_END_PHRASE.BAD_NOTIFICATION_PAYLOAD,resultCategories:["UnexpectedServerError"]};this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:t.code,endSubCode:t.subCode,resultDetail:t.phrase||"EndIncomingCall",resultCategories:t.resultCategories,causeId:e}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,t),this.dispose(t,e)},this.isDuplicatedIncomingMessage=e=>e.origin===wa.INCOMING_MESSAGE_ORIGIN.BROKER&&Ja(e.headers,this.incomingBrokerMessagesSeenSoFar)||e.origin===wa.INCOMING_MESSAGE_ORIGIN.TROUTER&&Ja(e.headers,this.incomingTrouterMessagesSeenSoFar),this.getEndpointState=()=>{let e;return e=this.startOrJoinConvResponseReceived?{...this.latestEndpointState}:{...this.requestedEndpointStateWhileConnecting},e},this.setMultiParty=(e,t)=>{const i=!!e;this.multiParty!==i&&(this.telemetryHelper.recordEvent("SetMultiparty",{isMultiparty:i,causeId:t}),this.multiParty=i)},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 e=e=>{e&&"string"==typeof e&&e.trim()&&(this.baseMessagingChannelUrl=this.previousTrouterUrl=this.currentTrouterUrl=e.trim(),this.telemetryHelper.addTrouterChannel())};this.brokerExclusiveEnabled()||(this.signalingAgentConfig.trouterServiceProvider?(2===this.signalingAgentConfig.trouterServiceProvider.state()&&this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync().then(e),this.signalingAgentConfig.trouterServiceProvider.onStateChanged(this.onTrouterStateChanged)):(e(this.signalingAgentConfig.trouterUrlGetter.trouterUrl()),this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed(this.onTrouterUrlChanged)))},this.isTrouterDisconnected=()=>{try{return 3===this.signalingAgentConfig.trouterServiceProvider.state()}catch(e){return!1}},this.forceTrouterConnectionCheck=()=>{try{return void this.signalingAgentConfig.trouterServiceProvider.checkConnection(!1)}catch(e){return}},this.navigatorOnlineCallback=()=>{this.disposed||(this.reportConnectivityStatus(),this.isTrouterDisconnected()&&this.signalingAgentConfig.forceTrouterReconnectOnNetworkOnline&&this.forceTrouterConnectionCheck())},this.navigatorOfflineCallback=()=>{this.reportConnectivityStatus()},this.reportConnectivityStatus=()=>{if(!this.disposed){const e=io(this.signalingAgentConfig.trouterServiceProvider);this.logger.info(`[Connectivity] status=${e}`),this.telemetryHelper.recordEvent("ConnectivityChanged",{status:e})}},this.onTrouterStateChanged=(e,t)=>{const i=Na();this.logger.info(`[${i}][onTrouterStateChanged][state=${e}]`),this.disposed?this.logger.info("onTrouterStateChanged ignored"):(this.reportConnectivityStatus(),2===e&&(this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter("TrouterStateChanged",i)))},this.setupConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.addEventListener&&(window.addEventListener("online",this.navigatorOnlineCallback),window.addEventListener("offline",this.navigatorOfflineCallback))}catch(e){return}},this.tearDownConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.removeEventListener&&(window.removeEventListener("online",this.navigatorOnlineCallback),window.removeEventListener("offline",this.navigatorOfflineCallback))}catch(e){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 Gd(this),this.brokerService.onBrokerMessage((e=>{this.logger.info("setupBrokerChannel, message from broker",function(e){try{const t=ke(e,["id","groupCallInitiator"]);return Ze(t,"body.participants"),Ge(t)}catch(e){return"failed to return safe response"}}(e)),this.handleIncomingMsgAsync(e,wa.INCOMING_MESSAGE_ORIGIN.BROKER).catch((e=>{this.telemetryHelper.recordEvent("FailedToHandleBrokerMessage"),this.logger.info("setupBrokerChannel, Failed to handle message from broker",e)}))})),this.baseMessagingChannelUrl||(this.telemetryHelper.addBrokerChannel(),this.baseMessagingChannelUrl=this.brokerService.baseUrl))},this.onTrouterUrlChanged=()=>{const e=Na();this.logger.info(`[${e}][onTrouterUrlChanged]`),this.disposed?this.logger.info("onTrouterUrlChanged ignored"):this.getTrouterUrlAsync().then((t=>{this.telemetryHelper.recordEvent(Ao,{url:t}),this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(Ao,e)})).catch((e=>{this.logger.info(`Failed to update links to trouter: ${e}`)}))},this.updateLinksToTrouter=(e,t)=>{this.logger.info(`[${t}][updateLinksToTrouter][tag=${e}]`),this.ensureLatestTrouterUrl(e).then((()=>{this.previousTrouterUrl!==this.currentTrouterUrl?(this.previousTrouterUrl=this.currentTrouterUrl,this.updateConversationLinks(),this.updateKeepAliveUrl(),this.contentSharingManager?.updateContentSharingNotificationLinksAsync(t),this.broadcastSession&&this.broadcastSession.updateBroadcastCallbackUrl(t)):this.logger.info(`[${t}][updateLinksToTrouter]skip updating links, url did not change`)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Po,{causeId:t}),this.logger.info(`[${t}][updateLinksToTrouter][failed][reason=${je(e)}]`)}))},this.updateLinks=(e,t)=>{this.ensureLatestTrouterUrl(Ao).then((()=>{e(t)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Po,{causeId:t}),this.logger.warn("Failed to update links")}))},this.startCallPreheatTimer=e=>{this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT,(()=>{this.handleCallEstablishmentTimeout(e,wa.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,"Preheat timed out!"),this.terminateEstablishedCall({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,phrase:"Preheat timed out!"},{forEveryone:!1,causeId:e})}),wa.TIMEOUT_VALUES_IN_SECONDS.MAX_PREAHEATED_TIMEOUT)},this.stopCallPreheatTimer=()=>{this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT)},this.updateKeepAliveUrl=()=>{this.logger.info("updateKeepAliveUrl"),this.links.hasOwnProperty(wa.LINKS.KEEPALIVE)?(this.linkUpdateRequested.keepAliveLinks=!1,this.logger.info("updateKeepAliveUrl, sending request"),this.sendToKeepAliveUrl(function(e){return Ua(e,"signalingSession cannot be null"),{payload:{callParticipantUpdate:{links:$a(e,ia),clientContentForMediaController:e.webRtcSignalingManager.getClientUrls()}}}}(this))):this.linkUpdateRequested.keepAliveLinks=!0},this.updateConversationLinks=(e=Na())=>{this.logger.info(`[${e}][updateConversationLinks]`),this.telemetryHelper.recordEvent("UpdateConversationLinks",{causeId:e}),this.links.hasOwnProperty(wa.LINKS.NOTIFICATION_LINKS)?(this.linkUpdateRequested.conversationLinks=!1,this.logger.info("updateConversationLinks, sending request"),this.sendToUpdateConversationLinks(!0)):this.linkUpdateRequested.conversationLinks=!0},this.sendAttachToCallInternal=(e=Na())=>{this.telemetryHelper.recordEvent("SendAttach",{causeId:e}),this.logger.info(`[${e}][sendAttachToCallInternal]`);const t=new Pa;return this.signalingAgentConfig.sendProgressFromCC&&t.set(wa.HEADERS.CACHE_SKYPE_TOKEN,"1"),this.http.sendPostRequest({url:this.incomingCallPayload.callNotification.links.attach,customHeaders:t,requestName:Zo.SEND_CALL_ATTACH.name,payload:Du(this,this.incomingCallPayload.conversationInvitation.conversationController,!this.getInitialMediaOfferFromIncomingCallPayload()),causeId:e}).then((t=>{if(!this.disposed){this.processAttachResponse(this.incomingCallPayload,t,e);const i=t.response.additionalActionResponses;i&&i.length>0&&this.processConversationServiceResponse(i[0].output,e,0),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,e),this.telemetryHelper.setTimeToRingDuration(),this.handleBrokerSubscription(t.response.callInvitation,e)}})).catch((t=>{const i=Ka(t,this.signalingAgentConfig);if(this.logger.info(`[${e}][sendAttachToCallInternal] error: ${je(t)} xhrError: ${je(i)}`),!this.disposed)throw this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||"SendAttachtoCallFailure",causeId:e}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,i.error),this.dispose(i.error,e),{code:i.telemetryEndSubCode,subCode:i.error.subCode,resultCategories:i.error.resultCategories}}))},this._processCallAcceptance=(e,t)=>{if(this.logger.info(`[${t}][_processCallAcceptance]`),this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING){this.processCallAcceptance(e.body,t),this.telemetryHelper.setTimeToRingDuration();try{this.multiParty||this.callUsesMixer||this.participantManager.handleRosterUpdate(this.getFakeRoster(e.body),!0,t)}catch(i){const n={code:wa.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:wa.CALL_END_SUB_CODE.CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE,phrase:i?.toString()};throw this.logger.info(`[${t}][_processCallAcceptance] ${Ge(n)}`),this.telemetryHelper.recordRosterEvent(e,_o,t),n}}},this.restartKeepAliveInterval=(e,t=!1,i)=>{this.disposed||(window.clearInterval(this.keepAliveTimer),t&&(this.telemetryHelper.recordEvent("SendKeepAliveFailed",i),i?.code===wa.RESOURCE_NOT_FOUND_ERROR.code)?this.logger.info(`[${e}][restartKeepAliveInterval] keepAlive stopped since last request returned NOT_FOUND.`):this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval))},this.isCallOngoing=()=>this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.IDLE,this.isCallNotConnected=()=>{const e=this.signalingAgentConfig.enableSplitConversationEndUrl&&this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING;return this.fsmState===wa.SIGNALING_FSM_STATE.IDLE||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||e},this.isCallConnectedOrConnectedForRoster=()=>this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,s&&(this.callStartTime=s),this.signalingSessionCallback=t,this.signalingAgentConfig=i,this.signalingAgent=r,this.urlIdentifier=n,this.piiUtils=new Dd(i.piiScrubber),this.isHostLessCall=i.doHostlessCalling||!1,this.logger=i.logger.createChild((()=>`CSA[${this.correlationId}][${this.fsmState}]`),this.correlationId,!0),this.updateCorrelationId(n),this.logger.info(`[endpointId=${qe(this.signalingAgent.endpointId,8)}]`),this.logger.info(`[participantId=${e.participantId}]`),this.callOperationHandler=new zd(this.logger.createChild((()=>`[CallOperationHandler][${e.participantId}]`))),this.http=new uu(this,this.callStartTime),this.telemetryHelper=new sh(this,e,this.callStartTime),this.mediaRenegotiationManager=new mu(this,t,this.telemetryHelper),this.participantManager=new Iu(this,t,e,new ct(this.logger)),this.proxiedMessageNotificationManager=new Ru(this),this.timeoutManager=new Rd(this.logger),this.contentSharingManager=new nu(this,t),this.webRtcSignalingManager=new ah(this,t),this.pstnContent={emergencyCallCountry:i.emergencyCallCountry||"",platformName:i.clientInformation,publicApiCall:!1},this.setupTrouterChannel(),this.setupConnectionCheck()}onPromotionCompleted(e,t,i){this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} error=${je(t)}]`),this.isPromotingToRealtime=!1,this.signalingSessionCallback.onPromotionCompleted(e,t,i)}setRealTimeState(e,t){let i=e;(2===e&&1===this.realTimeState||1===e&&2===this.realTimeState)&&(i=3),i!==this.realTimeState&&(this.logger.info(`[${t}][setRealTimeState] changed: input=${e} old=${this.realTimeState}, new=${i}`),this.realTimeState=i,3===i?this.setCallMode(1,t):0!==this.callMode||2!==i&&(this.signalingAgentConfig.disableRealTimeModeFromRoster||1!==i)||this.setCallMode(1,t))}setCallMode(e,t){this.callMode!==e&&(this.logger.info(`[${t}][setCallMode] oldMode=${this.callMode}, newMode=${e}`),this.callMode=e,this.signalingSessionCallback.onCallModeChanged(this.callMode,t))}configureStreamingMode(e){2!==this.callMode?(this.logger.info(`[${e}][configureStreamingMode]`),this.setCallMode(2,e),this.cleanUpDueToStreaming(e),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,e)):this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT)}updateDominantSpeakerHistoryMessageSubscription(e){this.webRtcSignalingManager.getIsDominantSpeakerInfoLinkEnabled()!==e&&(this.logger.info(`Signaling dominant speaker history subscription updated: ${e}`),this.webRtcSignalingManager.setIsDominantSpeakerInfoLinkEnabled(e),this.webRtcSignalingManager.areClientURLsGenerated()&&this.updateKeepAliveUrl())}cleanUpDueToStreaming(e){this.setRealTimeState(0,e),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.isPromotingToRealtime=!1,this.provisionalMediaAnswersSeenSoFar=[],this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=new mu(this,this.signalingSessionCallback,this.telemetryHelper),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const t={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.DOWNGRADE_TO_STREAMING_CLIENT,phrase:wa.CALL_END_PHRASE.DOWNGRADE_TO_STREAMING_CLIENT},i=Zo;for(const n of Object.keys(i))0!==i[n].controller&&4!==i[n].controller&&3!==i[n].controller||this.http.cancelRequestIfPending(i[n].name,e,void 0,t)}updateEndpointMetadata(e,t=Na()){let i={};try{i=JSON.parse(e)}catch(e){return Promise.reject("Invalid metadata")}return this.http.sendPutRequest({url:this.links[wa.LINKS.UPDATE_ENDPOINT_METADATA],requestName:Zo.UPDATE_ENDPOINT_METADATA.name,payload:Yu(this,i),causeId:t}).then((()=>{this.telemetryHelper.recordEvent("UpdateEndpointMetadataSuccess",{causeId:t})})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointMetadata] error: ${je(i)}`),this.telemetryHelper.recordEvent("UpdateEndpointMetadataFailure",{...i.error}),Promise.reject(i.error)}))}isOneToOnePSTNCall(){return this.signalingSessionCallback.isOneToOnePstnCall()}getLocationContent(){return this.isOneToOnePSTNCall()?Wa(this.locationInfoContent):null}getNetworkContent(){return this.isOneToOnePSTNCall()?Wa(this.networkInfoContent):null}getAreaContent(){return this.isOneToOnePSTNCall()?Wa(this.areaContent):null}setLocationInfo(e,t,i){this.locationInfoContent=e,this.networkInfoContent=t,this.areaContent=i}setStreamInformationReceived(){this.disposed||this.streamInformationReceived||(this.streamInformationReceived=!0,this.telemetryHelper.recordEvent("StreamInformationReceived"))}getEndpointCapabilities(){let e=0;return this.signalingAgentConfig.brokerEnabledIncoming&&(e|=16),this.signalingAgentConfig.isGVCJoiningEnabled&&(e|=1),"disabled"!==this.signalingAgentConfig.cloudScreenSharingFlag&&(e|=2),this.signalingAgentConfig.supportsHostlessGroupCalls&&(e|=4),this.signalingAgentConfig.autoJoinOnConflict&&(e|=32),this.signalingAgentConfig.supportsCompressedServicePayload&&(e|=128),this.signalingAgentConfig.enableAutoPromotion&&(e|=65536),this.signalingAgentConfig.enableBatchedSendMessageStatus&&(e|=16384),this.signalingAgentConfig.enableBatchedReceiveMessage&&(e|=8192),e|=64,e|=1024,this.signalingAgent?.accountConfig?.clientSupportsAudioOnlyWatermark&&(e|=4096,this.telemetryHelper.setAudioOnlyWatermark(!0)),this.signalingAgent?.accountConfig?.clientSupportsWatermark&&(e|=2048,this.telemetryHelper.setWatermarkSupport(!0)),this.signalingAgent?.accountConfig?.clientSupportsPreventScreenCapture&&(e|=131072,this.telemetryHelper.setClientSupportsPreventScreenCapture(!0)),(this.getMaxReinvitelessMediaForVBSSForWeb()||this.getMaxReinvitelessMediaForVideoForWeb())&&(this.telemetryHelper.setReinviteless(this.callUsesMixer),e|=512),e}handleAdmitAllStatus(e){const t=e.body?.transactionResponse,i=Qa(e);this.logger.info(`[${i}][handleAdmitAllStatus][${je(t)}]`);const n=t?.operationId;if(n&&this.callOperationHandler.hasPendingOperation(0,n,i)){this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,n);const e=t?.result?.code,r=t?.result?.subCode,s=t?.result?.resultCategories,a=t?.additionalDetail;if(0===e||e>=200&&e<300){const t={code:e,subCode:r,resultCategories:s,result:Ge(a)};this.telemetryHelper.recordEvent("AdmitSuccess",{causeId:n,transactionEnd:t}),this.callOperationHandler.resolvePendingOperation(0,n,t,i)}else{const a={code:e||wa.CALL_END_CODE.BAD_REQUEST,subCode:r||0,resultCategories:s,result:t,phrase:wa.CALL_END_PHRASE.BAD_SERVICE_RESPONSE};this.telemetryHelper.recordEvent(To,{causeId:n,transactionEnd:a}),this.callOperationHandler.rejectPendingOperation(0,n,"AdmitAllStatus response contains failure",a,i)}}else this.logger.warn(`[${i}][handleAdmitAllStatus] invalid admitAllStatus response or no pending operation. operationId=${n}`)}sendNetworkRequestForAdmit(e){this.http.sendPostRequest({url:this.links[wa.LINKS.ADMIT_ALL],requestName:Zo.ADMIT.name,payload:Mu(this,e),causeId:e,onceTrouterReady:()=>{this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.ADMIT,(()=>{this.telemetryHelper.recordEvent("AdmitTimeout",{causeId:e}),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,"timed out waiting for admit operation",{code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.ADMIT_TIMEOUT,phrase:wa.CALL_END_PHRASE.ADMIT_TIMEOUT},e)}),wa.TIMEOUT_VALUES_IN_SECONDS.ADMIT_TIMEOUT,e)}}).catch((t=>{const i=Ka(t,this.signalingAgentConfig);this.telemetryHelper.recordEvent(To,{causeId:e,...i.error}),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,t,i.error,e)}))}getConversationType(e,t,i){return e?"emergencyGroupCall":t?"cast":i?"huddleGroupCall":null}getMaxReinvitelessMediaForVideoForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVideoForWeb}getMaxReinvitelessMediaForVBSSForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVBSSForWeb}convertParkType(e){return"teamPark"===e?"TransferTypeTeamPark":"sharedLinePark"===e?"TransferTypeSharedLinePark":"serverHold"===e?"TransferTypeServerHold":(this.logger.info(`convertParkType, parkType: ${e} is unknown`),"none")}parkByTransfer(e,t){this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(t)}),wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT);const i=this.getNetworkRequestName(e);return this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER],requestName:i,payload:Hu(e,this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[${t}][parkByTransfer] error: ${je(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:wa.CALL_END_CODE.NETWORK_ERROR,reason:je(e)}},t),this.telemetryHelper.recordEvent(Vo,{causeId:t,...i.error}),Promise.reject(i.error))})),this.telemetryHelper.recordEvent(Bo,{causeId:t,transferType:this.convertParkType(e)}),Promise.resolve()}park(e,t){this.logger.info(`[${t}][park] context ${e}`),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.PARK_COMPLETION,(()=>{this.handleParkError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.PARK_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.PARK_COMPLETION_TIMEOUT},"WaitingForParkCompletionTimeout",t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.PARK_COMPLETION_TIMEOUT);const i=this.getHoldTypeInRequest(e),n={causeId:t};return this.http.sendPostRequest({url:this.links[wa.LINKS.PARK],requestName:Zo.PARK_REQUEST.name,payload:$u(this,i,n),causeId:t}).then((e=>{this.logger.info(`[${t}][park] response: ${je(e)}`),this.telemetryHelper.recordEvent("WaitingForParkCompletion",{causeId:t}),Ua(e.response.holdResponse.links,"server response does not include park links"),this.links[wa.LINKS.UNPARK]=e.response.holdResponse.links.resume})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][park] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleParkError(n.error,"ParkRequestFailed",t,e),Promise.reject(n.error))})),Promise.resolve()}getHoldTypeInRequest(e){switch(e){case"serverHoldV2":return"musicOnHold";case"sharedLineParkV2":return"sharedLineAppearance";case"callPark":return"callPark";default:return null}}handleParkError(e,t,i,n){this.disposed?this.logger.info("handleParkError ignored"):(this.logger.info(`[${i}] handleParkError reject reason: ${je(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.PARK_COMPLETION),this.signalingSessionCallback.onParkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onParkCompleted(e,i)),this.links[wa.LINKS.UNPARK]=void 0)}handleParkCompletion(e){const t=e.body,i=Qa(e),n=t.holdCompletion;this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleParkCompletion",wa.TIMEOUT_OPERATIONS.PARK_COMPLETION,"ParkCompleted","ParkFailed",this.signalingSessionCallback.onParkCompleted,this.handleParkError.bind(this))}handleUnparkError(e,t,i,n){this.disposed?this.logger.info("handleUnparkError ignored"):(this.logger.info(`[${i}] handleUnparkError reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.signalingSessionCallback.onUnparkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(e,i)),this.links[wa.LINKS.UNPARK]=void 0)}handleUnparkCompletion(e){const t=e.body,i=Qa(e);if(this.disposed)return void this.logger.info(`[${i}]handleUnparkCompletion ignored`);this.logger.info(`[${i}][handleUnparkCompletion] body ${je(t)}`);const n=t.resumeCompletion;n.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.telemetryHelper.recordEvent("UnparkCompleted",{...n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(n,i),this.links[wa.LINKS.UNPARK]=void 0):this.handleUnparkError(n,"UnparkFailed",i)}getNetworkRequestName(e){return{none:null,teamPark:Zo.SEND_PARK_REQUEST.name,sharedLinePark:Zo.SEND_SHARED_LINE_PARK_REQUEST.name,serverHold:Zo.SEND_SERVER_HOLD_REQUEST.name}[e]}updateMeetingsGroupsAsync(e,t){this.logger.info(`[${e}][updateMeetingsGroupsAsync] scope=${t.scope}`),this.telemetryHelper.recordEvent("UpdateMeetingGroups",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION,(()=>{this.handleUpdateMeetingGroupsError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT},jo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT);const i=function(e,t,i){Ua(e,"signalingSession cannot be null");const{scope:n,toGroup:r,fromGroup:s,participants:a}=t;"specified"===n&&Ua(a,"participantsIds cannot be null");const o={from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},scope:n,fromGroup:s,toGroup:r,links:{updateMeetingGroupsStatus:Ra(e,ra.UPDATE_MEETING_GROUPS_STATUS)},operationId:i};return a&&(o.to=a.map((e=>({id:e.mri,endpointId:e.endpointId,participantId:e.participantId})))),{payload:o}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_GROUPS],requestName:Zo.UPDATE_MEETING_GROUPS.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingsGroupsAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(jo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingsGroupsAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingGroupsError(n.error,"UpdateMeetingGroupsRequestFailed",e,e,t),Promise.reject(n.error))}))}updateMonitorSessionAsync(e,t){this.logger.info(`[${t}][updateMonitorSessionAsync]`),this.telemetryHelper.recordEvent("UpdateMonitorSession",{causeId:t,options:e}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,(()=>{this.handleUpdateMonitorSessionError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT},Qo,t,e)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT);const i=function(e,t,i,n){return Ua(e,"signalingSession cannot be null"),{payload:{monitorContent:{sequenceId:e.getMonitorSequenceId(),monitorActionType:t,monitorData:i??{},links:{monitorCompletion:Ra(e,ra.MONITOR_COMPLETION)}},debugContent:{causeId:n}}}}(this,e.monitorActionType,e.monitorData,t);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MONITOR_SESSION],requestName:Zo.UPDATE_MONITOR_SESSION.name,payload:i,causeId:t}).then((e=>{this.logger.info(`[${t}][updateMonitorSessionAsync] response: ${je(e)}`),this.telemetryHelper.recordEvent(Qo,{causeId:t})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${t}][updateMonitorSessionAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMonitorSessionError(n.error,"UpdateMonitorSessionRequestFailed",t,e),Promise.reject(n.error))}))}updateParticipantInterpretationStateAsync(e,t){return Fa(t,"options should be a non null value"),this.logger.info(`[${e}][updateParticipantInterpretationStateAsync]`),this.telemetryHelper.recordEvent("UpdateParticipantInterpretationState",{causeId:e,options:t}),this.participantManager.updateParticipantInterpretationStateAsync(t,this.links[wa.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE],e)}async sendProxiedMessageAsync(e,t){return t&&0!==t.length?this.links[wa.LINKS.SEND_MESSAGE]?this.proxiedMessageNotificationManager.sendProxiedMessageAsync(e,t,this.links[wa.LINKS.SEND_MESSAGE]):Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"missing url for CONSTANTS.LINKS.SEND_MESSAGE"}):Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"options should be a non empty array"})}async updateParticipantsPropertiesAsync(e,t,i,n){this.telemetryHelper.recordEvent("UpdateParticipantsProperties",{causeId:n,updateParticipantsPropertiesContext:e});const r=this.links[wa.LINKS.UPDATE_PARTICIPANTS_PROPERTIES],s=[],a=e.scope;if("self"===a){const t={id:this.participantManager.localParticipant.id,propertyBag:e.propertyBag};s.push(t)}else{if("specified"!==a)return Promise.reject("This scope is not Supported");{const t=e.participants;for(const e of t){const t={id:e.id,propertyBag:e.propertyBag};s.push(t)}}}return this.sendNetworkRequestForUpdateParticipantsProperties(s,t,r,i,n)}sendNetworkRequestForUpdateParticipantsProperties(e,t,i,n,r){const s=this.logger.createChild(`[${r}][sendNetworkRequestForUpdateParticipantsProperties]`,this.correlationId);if(i){const a=()=>{const e={code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT};this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,(()=>{this.handleUpdateParticipantsPropertiesOnTimeout(t,e,"UpdateParticipantsPropertiesTimeout",n,r)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT,n)},o=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId},to:t,links:{updateParticipantPropertiesStatus:Ra(e,ra.UPDATE_PARTICIPANT_PROPERTIES_STATUS)},operationId:i}}}(this,e,n);return this.updateParticipantsPromises[n]=t,this.http.sendPostRequest({url:i,payload:o,requestName:Zo.UPDATE_PARTICIPANTS_PROPERTIES.name,onceTrouterReady:a,causeId:r}).then((e=>{s.info(`response: ${je(e)}`)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);s.info(`failed: ${je(t)}`);const i={...t.error};return this.disposed||(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,n),delete this.updateParticipantsPromises[n]),this.telemetryHelper.recordEvent(qo,{causeId:r,transactionEnd:i}),Promise.reject(i)}))}{const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING,phrase:"updateParticipantsProperties link is missing"};return s.warn(e),this.telemetryHelper.recordEvent(qo,{causeId:r,error:e}),Promise.reject(e)}}checkAndCleanupPromisesForOperationId(e){this.updateParticipantsPromises[e]&&(0===this.updateParticipantsPromises[e].size?(delete this.updateParticipantsPromises[e],this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,e)):this.logger.info(`remaining promises for the operation ${e} (count: ${this.updateParticipantsPromises[e].size}):\n ${this.piiUtils.scrubMriOrOmit(Ge(this.updateParticipantsPromises[e]))}`))}handleUpdateParticipantsPropertiesOnTimeout(e,t,i,n,r){if(this.disposed)return void this.logger.info("handleUpdateParticipantsPropertiesOnTimeout ignored");this.logger.createChild(`[${r}][handleUpdateParticipantsPropertiesOnTimeout]`,this.correlationId).info(`reason: ${t}`),this.telemetryHelper.recordEvent(i,{...t,causeId:r});const s={};e.forEach((e=>{s[e]=t,this.updateParticipantsPromises[n].delete(e)})),this.checkAndCleanupPromisesForOperationId(n),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(s,n,r)}joinMeetingGroupAsync(e,t){this.logger.info(`[${e}][joinMeetingGroupAsync]`),this.telemetryHelper.recordEvent("JoinMeetingGroup",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION,(()=>{this.handleJoinMeetingGroupError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.JOIN_MEETING_GROUP_TIMEOUT,phrase:wa.CALL_END_PHRASE.JOIN_MEETING_GROUP_TIMEOUT},zo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.JOIN_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},..."meetingGroupId"in t&&{meetingGroup:t.meetingGroupId},..."meetingGroupLabel"in t&&{meetingGroupLabel:t.meetingGroupLabel},...t.groupPreferences&&{groupPreferences:t.groupPreferences},links:{joinMeetingGroupStatus:Ra(e,ra.JOIN_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.JOIN_MEETING_GROUP],requestName:Zo.JOIN_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][joinMeetingGroupAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(zo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][joinMeetingGroupAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleJoinMeetingGroupError(n.error,"JoinMeetingGroupRequestFailed",e,e,t),Promise.reject(n.error))}))}leaveMeetingGroupAsync(e,t){this.logger.info(`[${e}][leaveMeetingGroupAsync]`),this.telemetryHelper.recordEvent("LeaveMeetingGroup",{causeId:e,options:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION,(()=>{this.handleLeaveMeetingGroupError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.LEAVE_MEETING_GROUP_TIMEOUT,phrase:wa.CALL_END_PHRASE.LEAVE_MEETING_GROUP_TIMEOUT},Wo,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){Ua(e,"signalingSession cannot be null");const{meetingGroupId:n}=t;return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingGroup:n,links:{leaveMeetingGroupStatus:Ra(e,ra.LEAVE_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE_MEETING_GROUP],requestName:Zo.LEAVE_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][leaveMeetingGroupAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(Wo,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][leaveMeetingGroupAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleLeaveMeetingGroupError(n.error,"LeaveMeetingGroupRequestFailed",e,e,t),Promise.reject(n.error))}))}handleUpdateMeetingGroupsError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingGroupsError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingGroupsError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(e,i,n))}handleUpdateMeetingGroupsCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingGroupsResponse.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateMeetingGroupsCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] starts`);const{updateMeetingGroupsResponse:r}=t,s=$d(r);s.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group succeeded`),this.telemetryHelper.recordEvent("UpdateMeetingGroupsResponseSuccess",{...s,causeId:i})):(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group failed code=${s.code} subCode=${s.subCode}`),this.telemetryHelper.recordEvent("UpdateMeetingGroupsResponseFailure",{...s,causeId:i})),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] completes`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(s,i,n)}handleJoinMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleJoinedMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleJoinedMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,joinMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onJoinMeetingGroupCompleted(e,i,n))}handleJoinMeetingGroupCompletion(e){const t=e.body.joinMeetingGroupResponse,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleJoinMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] starts`);const r=$d(t);r.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group succeeded`),this.telemetryHelper.recordEvent("JoinMeetingGroupRequestCompleted",{...r,causeId:i})):(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent("JoinMeetingGroupRequestFailed",{...r,causeId:i})),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onJoinMeetingGroupCompleted(r,i,n)}handleLeaveMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleLeaveMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleLeaveMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,leaveMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(e,i,n))}handleLeaveMeetingGroupCompletion(e){const t=e.body.leaveMeetingGroupResponse,i=Qa(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleLeaveMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] starts`);const r=$d(t);r.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group succeeded`),this.telemetryHelper.recordEvent("LeaveMeetingGroupRequestCompleted",{...r,causeId:i})):(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent("LeaveMeetingGroupRequestFailed",{...r,causeId:i})),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(r,i,n)}handleDisablePreheatError(e,t,i){this.disposed?this.logger.info(`[${i}][handleDisablePreheatError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleDisablePreheatError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject(e))}handleDisablePreheatCompletion(e){const t=e.body,i=Qa(e),n=t.transactionEnd;if(this.disposed)this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Call disposed.`);else if(this.disablePreheatDefer.isPending()){if(this.logger.info(`[${i}][handleDisablePreheatCompletion] starts`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),n.code===wa.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state succeeded`),this.handleEndpointStateUpdated(i,!0);else if(this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state failed code=${n.code} subCode=${n.subCode}`),this.disablePreheatDefer.isPending()){const e={response:n};this.disablePreheatDefer.reject(e)}}else this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Disable preheat promise is resolved/rejected.`)}handleReceiveMessage(e){const t=Qa(e);if(this.disposed)return void this.logger.info(`[${t}][handleReceiveMessage] ignored. Call disposed.`);let i;i=Array.isArray(e.body?.messageContent)?e.body.messageContent:[e.body];let n="";const r=[];for(let e=0;e<i.length;e++){const t=i[e];n+=t?.operationId,e<i.length-1&&(n+=","),r.push({operationId:t.operationId,messageType:t.type,payload:t.payload,from:{[t.from.id]:{participantLegIdMap:{[t.from.participantId]:{...t.from.endpointId&&{endpointId:t.from.endpointId}}},level:"endpoint"}}})}this.logger.info(`[${t}][handleReceiveMessage] complete. OperationIds:${n}`),this.telemetryHelper.recordEvent("incomingProxiedMessages",{causeId:t,operationIds:n}),this.signalingSessionCallback.onIncomingProxiedMessages(r,t)}publishStateAsync(e,t,i,n,r,s){this.logger.info(`[${i}][publishStateAsync][publishType=${e} publishLevel=${t}]`),this.telemetryHelper.recordEvent("PublishState",{causeId:i,publishType:e,publishLevel:t});const a=this.links[wa.LINKS.PUBLISH_STATE];if(!a){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_LINK_MISSING,phrase:"publish state link is missing"};return this.logger.warn(e),Promise.reject(e)}let o={};try{o=JSON.parse(n)}catch(e){const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_CONTENT,phrase:"publish state content is invalid"};return this.logger.warn(t),Promise.reject(t)}return this.http.sendPostRequest({url:a,requestName:Zo.PUBLISH_STATE.name,payload:ju(this,e,t,o,r,s),causeId:i,requestId:i}).then((e=>{if(e?.response?.publishStateResponse)return this.parsePublishStateResult(e,i);{const t=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${i}][publishStateAsync] error: ${je(t)}`);const n=t.error;return this.telemetryHelper.recordEvent("PublishStateFailure",{causeId:i,transactionEnd:n}),Promise.reject(n)}))}getPublishStateSequenceNumber(){return++this.publishStateSequenceNumber}getMonitorSequenceId(){return++this.monitorSequenceId}parsePublishStateResult(e,t){let i={};if(e?.response?.publishStateResponse){if(e.response.publishStateResponse.stateId)return e.response.publishStateResponse.stateId;if(e.response.publishStateResponse.results){if(1===e.response.publishStateResponse.results.length){if(e.response.publishStateResponse.results[0].stateId)return e.response.publishStateResponse.results[0].stateId;this.logger.warn("invalid response format")}return e.response.publishStateResponse.results.forEach((e=>{i[e.participantId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})),JSON.stringify(i)}if(e.response.publishStateResponse.result)return i={code:e.response.publishStateResponse.result.code,phrase:e.response.publishStateResponse.result.phrase,subCode:e.response.publishStateResponse.result.subCode,result:e.response.publishStateResponse.additionalDetail},JSON.stringify(i)}const n=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(n),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:n}}}removeStateAsync(e,t,i,n){if(this.logger.info(`[${e}][removeStateAsync][scope=${t} publishType=${i} stateIds=${n}]`),this.telemetryHelper.recordEvent("RemoveState",{causeId:e,scope:t,publishType:i,stateIds:n}),!i&&!n){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.REMOVE_STATE_MISSING_ARGUMENTS,phrase:"remove state operation miss arguments"};return this.logger.warn(e),Promise.reject(e)}const r=this.links[wa.LINKS.REMOVE_STATE];if(!r){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.REMOVE_STATE_LINK_MISSING,phrase:"remove state link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:r,requestName:Zo.REMOVE_STATE.name,payload:qu(this,t,n,i),causeId:e,requestId:e}).then((t=>this.parseRemoveStateResult(t,e))).catch((t=>{const i=Ka(t,this.signalingAgentConfig);this.logger.info(`[${e}][removeStateAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("RemoveStateFailure",{causeId:e,transactionEnd:n}),Promise.reject(n)}))}parseRemoveStateResult(e,t){let i={};return e?.response?.removeStateResponse&&(e.response.removeStateResponse.results?e.response.removeStateResponse.results.forEach((e=>{i[e.stateId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})):e.response.removeStateResponse.result&&(i={code:e.response.removeStateResponse.result.code,phrase:e.response.removeStateResponse.result.phrase,subCode:e.response.removeStateResponse.result.subCode,result:e.response.removeStateResponse.additionalDetail})),JSON.stringify(i)}updateMeetingSettingsAsync(e,t){this.telemetryHelper.recordEvent("UpdateMeetingSettings",{causeId:t,meetingSettings:e});const i=this.links[wa.LINKS.UPDATE_MEETING_SETTINGS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_LINK_MISSING,phrase:"update meeting settings link is missing"};return this.logger.warn(e),Promise.reject(e)}if(!Object.keys(e).length){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS,phrase:"update meeting settings missing arguments"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPutRequest({url:i,requestName:Zo.UPDATE_MEETING_SETTINGS.name,payload:Zu(this,e),causeId:t,requestId:t}).then((()=>{kd.noop()})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][updateMeetingSettingsAsync] error: ${je(i)}`);const n=i.error;throw this.telemetryHelper.recordEvent("UpdateMeetingSettingsFailure",{causeId:t,transactionEnd:n}),n}))}searchParticipantsAsync(e,t){this.logger.info(`[${t}][searchParticipantsAsync][queryOptions=${e}]`),this.telemetryHelper.recordEvent("SearchParticipants",{causeId:t,queryOptions:e});const i=this.links[wa.LINKS.SEARCH_PARTICIPANTS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_LINK_MISSING,phrase:"search participants link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:Zo.SEARCH_PARTICIPANTS.name,payload:zu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response?.participants)return this.parseSearchParticipantsResult(e,t);{const t=`Invalid CS response which does not contain proper search results. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][searchParticipantsAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("SearchParticipantsFailure",{causeId:t,transactionEnd:n}),Promise.reject(n)}))}parseSearchParticipantsResult(e,t){const i=[];if(e?.response){const t=e.response.participants;if(t)for(const n of Object.keys(t))i.push(mo.fromRosterSearchResults(e.response.participants[n]))}return{participants:i}}getAllParticipantsAsync(e,t){this.logger.info(`[${t}][getAllParticipantsAsync][scope=${e}]`),this.telemetryHelper.recordEvent("GetAllParticipants",{causeId:t,scope:e});const i=this.links[wa.LINKS.GET_ALL_PARTICIPANTS];if(!i){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_LINK_MISSING,phrase:"get all participants link is missing"};return this.logger.warn(e),Promise.reject(e)}if("lobby"!==e){const e={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SCOPE,phrase:"get all participants scope is invalid"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:Zo.GET_ALL_PARTICIPANTS.name,payload:Fu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response)return{participants:e.response.participants};{const e="Invalid CS response which does not contain results.";throw this.logger.warn(e),{response:{code:wa.CALL_END_CODE.DECODING_FAILED,subCode:wa.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:e}}}})).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][getAllParticipantsAsync] error: ${je(i)}`);const n=i.error;return this.telemetryHelper.recordEvent("GetAllParticipantsFailure",{causeId:t,transactionEnd:n}),Promise.reject(n)}))}resetState(){this.currentCallStatus=null,this.fsmState=wa.SIGNALING_FSM_STATE.IDLE}saveUpdatedCallLinksIfAny(e){e.links&&(this.logger.info(`saveUpdatedCallLinksIfAny, updated call links found, update to new links ${je(e)}`),this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.links.mediaRenegotiation||this.links[wa.LINKS.MEDIA_RENEGOTIATION],this.links[wa.LINKS.TRANSFER]=e.links.transfer||this.links[wa.LINKS.TRANSFER],this.links[wa.LINKS.REPLACE]=e.links.replacement||this.links[wa.LINKS.REPLACE],this.links[wa.LINKS.HANGUP]=e.links.callLeg||this.links[wa.LINKS.HANGUP],this.links[wa.LINKS.KEEPALIVE]=e.links.callLeg||this.links[wa.LINKS.KEEPALIVE],this.links[wa.LINKS.PARK]=e.links.hold||this.links[wa.LINKS.PARK],this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.links.updateMediaDescriptions||this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS],this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.links.monitor||this.links[wa.LINKS.UPDATE_MONITOR_SESSION])}ensureMessageChannelReady(e){return this.disposed?(this.logger.info("ensureMessageChannelReady: error: call already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):this.brokerService?(this.telemetryHelper.addTrouterWaitOperation(`${Ed}:${e}`),this.telemetryHelper.addTrouterWaitOperation(`${bd}:${e}`),Promise.resolve()):this.ensureLatestTrouterUrl(e)}ensureLatestTrouterUrl(e){return this.telemetryHelper.addTrouterWaitOperation(`${Ed}:${e}`),this.getTrouterUrlAsync().then((t=>!t||"string"==typeof t&&!t.trim()?(this.telemetryHelper.recordEvent("TrouterUrlChangedToInvalid"),this.telemetryHelper.addTrouterWaitOperation(`${bd}:${e}`),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(`${bd}:${e}`),this.baseMessagingChannelUrl=this.currentTrouterUrl=t,Promise.resolve()))).catch((t=>(this.disposed||this.telemetryHelper.addTrouterWaitOperation(`${_d}:${e}`),this.logger.info(`ensureLatestTrouterUrl, failed because:${t}`),Promise.reject(t))))}signalTransferAcceptedAsync(e,t=Na()){return this.logger.info(`[signalTransferAcceptedAsync][${t}] transferType ${e}`),this.disposed?(this.logger.info(`[signalTransferAcceptedAsync][${t}] Call already ended, skip acceptance request`),Promise.reject({code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(this.telemetryHelper.recordEvent("SendAcceptTransfer",{causeId:t,transferType:e}),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER_ACCEPTANCE],requestName:Zo.TRANSFER_ACCEPTANCE.name,payload:{payload:{transferAcceptance:{}}},causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferAcceptedAsync][${t}] error: ${je(i)}`),this.telemetryHelper.recordEvent("SendAcceptTransferFail",{causeId:t}),Promise.reject(i.error)})))}signalTransferCompletedAsync(e,t=Na()){return this.logger.info(`[signalTransferCompletedAsync][${t}] rejectReason ${e}`),this.disposed?(this.logger.info(`[signalTransferCompletedAsync][${t}] Call already ended by transferor, skip completion request`),Promise.reject({code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(0!==e.code?this.telemetryHelper.recordEvent(ko,{code:e.code,subcode:e.subCode,causeId:t}):this.telemetryHelper.recordEvent(Ho,{causeId:t}),this.telemetryHelper.recordEvent("SendCompleteTransfer",{causeId:t}),this.http.sendPostRequest({url:this.links[wa.LINKS.TRANSFER_COMPLETION],requestName:Zo.TRANSFER_COMPLETION.name,payload:Ku(e),causeId:t}).catch((e=>{this.telemetryHelper.recordEvent("SendCompleteTransferFailed",{causeId:t});const i=Ka(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferCompletedAsync][${t}] error: ${je(i)}`),Promise.reject(i.error)})))}async rejectCallWithFetchAndKeepAlive(e){this.telemetryHelper.recordEvent("RejectWithFetchKeepAlive",{causeId:e});const t={code:wa.CALL_END_CODE.REJECT,subCode:wa.CALL_END_SUB_CODE.BEACON,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:[Qs]};await this.http.sendDeleteRequest({url:this.links[wa.LINKS.REJECT],requestName:Zo.REJECT_CALL.name,payload:Gu(this,t),causeId:e??Na(),requestId:La(),useFetch:!0,fetchUseKeepAlive:!0})}async endCallWithFetchAndKeepAlive(e,t,i,n){this.telemetryHelper.recordEvent("EndWithFetchKeepAlive",{causeId:n}),await this.http.sendPostRequest({url:e,requestName:Zo.END_CALL.name,payload:t,causeId:n??Na(),requestId:La(),useFetch:!0,fetchUseKeepAlive:!0})}endWithBeacon(e){if(this.disposed)return!1;const t=()=>{this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,i),this.dispose(i,e)};if(this.signalingAgentConfig.enableFetchRequestWithKeepAlive&&window.Request?.prototype?.hasOwnProperty("keepalive")&&this.currentCallStatus===wa.CALL_STATUS.RINGING)return this.rejectCallWithFetchAndKeepAlive(e),t(),!0;const i={code:wa.CALL_END_CODE.SUCCESS,subCode:wa.CALL_END_SUB_CODE.BEACON,phrase:wa.CALL_END_PHRASE.LOCAL_USER_INITIATED},n=JSON.stringify(Bu(this,i).payload),r=-1===this.links[wa.LINKS.LEAVE].indexOf("?")?"?":"&",s=this.signalingAgent?.authTokenManager?.getLastTokenType(e),a=this.signalingAgent?.authTokenManager?.getLastToken(e);let o="";switch(s){case 4:case 8:this.logger.info(`[endWithBeacon] with tokenType:${s},token size:${a.length},query parameter:access_token`),o=`${this.links[wa.LINKS.LEAVE]}${r}access_token=${a}`;break;default:this.logger.info(`[endWithBeacon] with tokenType:${s},token size:${a.length},query parameter:skypeToken`),o=`${this.links[wa.LINKS.LEAVE]}${r}skypeToken=${a}`}return this.signalingAgentConfig.enableFetchApiForBeacon&&window.Request?.prototype?.hasOwnProperty("keepalive")?(this.endCallWithFetchAndKeepAlive(o,n,i,e),t(),!0):!!navigator?.sendBeacon&&(this.telemetryHelper.recordEvent("EndWithBeacon",{causeId:e}),navigator.sendBeacon(o,n))}setFsmState(e){this.fsmState=e}setIsHostless(e,t){const i=!!e;this.isHostLessCall!==i&&(this.logger.info(`[${t}][setIsHostless] isHostless=${i}`),this.isHostLessCall=i)}hasGroupModality(){return this.threadId||this.groupId}processConversationServiceResponseHeaders(e,t){this.logger.info(`[${t}][processConversationServiceResponseHeaders]`);try{const i=e.request.headers[wa.HEADERS.CORRELATION_ID]||e.request.headers[wa.HEADERS.CORRELATION_ID.toLowerCase()];this.updateCorrelationId(i,t)}catch(e){this.logger.info(`[${t}][processConversationServiceResponseHeaders] failed, reason=${je(e)}`)}}processConversationServiceResponse(e,t,i){const n=this.logger.createChild(`[${t}][processConversationServiceResponse]`);if(n.info(`responseType :${i}`),this.processConversationServiceUpdate(e,t),e.subscriptionDetails?.selfParticipant){const i=mo.fromRoster(e.subscriptionDetails.selfParticipant,!0);n.info("converted selfParticipant to Participant type"),this.participantManager.updateLocalParticipantFromSubscribe(i,t)}e.selfParticipant?.enableCaptcha&&this.participantManager.setEnableCaptcha(!0,t),this.handleBrokerSubscription(e,t),e.roster&&this.internalHandleRosterUpdate(e.roster,!0,t),0===i&&(this.startOrJoinConvResponseReceived=!0,this.handlePendingEndpointState(t))}processConversationServiceUpdate(e,t){const i=this.logger.createChild(`[${t}][processConversationServiceUpdate]`);i.info(),this.convJoined=!0;const n=e.sequenceNumber>=0?e.sequenceNumber:-1;n<this.updateSequenceNumber?i.info(`seqNum=${n} is less than latest seqNum=${this.updateSequenceNumber}`):(this.updateSequenceNumber=n,this.links[wa.LINKS.CONVERSATION_CONTROLLER]=e.conversationController,this.links[wa.LINKS.ADD_PARTICIPANT]=e.links.addParticipant,this.links[wa.LINKS.ADD_PARTICIPANTS_AND_MODALITY]=e.links.addParticipantAndModality,this.links[wa.LINKS.LEAVE]=e.links.leave,this.links[wa.LINKS.NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[wa.LINKS.REMOVE_PARTICIPANT]=e.links.removeParticipant,this.links[wa.LINKS.ADD_MODALITY]=e.links.addModality,this.links[wa.LINKS.REMOVE_MODALITY]=e.links.removeModality,this.links[wa.LINKS.MUTE]=e.links.mute||null,this.links[wa.LINKS.UNMUTE]=e.links.unmute||null,this.links[wa.LINKS.ADMIT]=e.links.admit||null,this.links[wa.LINKS.ADMIT_ALL]=e.links.admitAll||null,this.links[wa.LINKS.UPDATE_ENDPOINT_STATE]=e.links.updateEndpointState||null,this.links[wa.LINKS.UPDATE_ENDPOINT_METADATA]=e.links.updateEndpointMetadata||null,this.links[wa.LINKS.UPDATE_PARTICIPANT_ROLE]=e.links.updateParticipantRole||null,this.links[wa.LINKS.PUBLISH_STATE]=e.links.publishState||null,this.links[wa.LINKS.REMOVE_STATE]=e.links.removeState||null,this.links[wa.LINKS.UPDATE_MEETING_SETTINGS]=e.links.updateMeetingSettings||null,this.links[wa.LINKS.SEARCH_PARTICIPANTS]=e.links.searchParticipants||null,this.links[wa.LINKS.GET_ALL_PARTICIPANTS]=e.links.getAllParticipants||null,this.links[wa.LINKS.UPDATE_MEETING_LIVE_STATE]=e.links.updateMeetingLiveState||null,this.links[wa.LINKS.UPDATE_MEETING_GROUPS]=e.links.updateMeetingGroups||null,this.links[wa.LINKS.SET_MEETING_LAYOUT]=e.links.setMeetingLayout||null,this.links[wa.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE]=e.links.updateParticipantInterpretationState||null,this.links[wa.LINKS.UPDATE_PARTICIPANTS_PROPERTIES]=e.links.updateParticipantProperties||null,this.links[wa.LINKS.JOIN_MEETING_GROUP]=e.links.joinMeetingGroup||null,this.links[wa.LINKS.LEAVE_MEETING_GROUP]=e.links.leaveMeetingGroup||null,this.links[wa.LINKS.SEND_MESSAGE]=e.links.sendMessage||null,this.links[wa.LINKS.UPDATE_MEETING_STATES]=e.links.updateMeetingStates||null,this.convSubject=e.subject,e.state&&(this.setMultiParty(e.state.isMultiParty,t),this.setIsHostless(e.state.isHostless||!1,t),this.conversationType=e.state.conversationType,this.isCastCall="cast"===e.state.conversationType,this.isHuddleGroupCall="huddleGroupCall"===e.state.conversationType),e.activeModalities&&e.activeModalities.groupChat&&this.updateGroupChatIds(e.activeModalities.groupChat,t),e.activeModalities&&e.activeModalities.broadcast&&(this.broadcastSession||(this.broadcastSession=new jd(this,this.signalingSessionCallback)),this.broadcastSession.handleBroadcastDetailsChanged(e,t)),this.handleMeetingDetailsChanged(e,t),this.handleMeetingStatesChanged(e,t),this.linkUpdateRequested.conversationLinks?(i.info("Updating CS links as requested"),this.updateLinks(this.updateConversationLinks,t)):this.scheduleConversationKeepAlive(),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo),e.region&&(this.region=e.region),e.callLimits&&(this.callLimits=e.callLimits),e.complianceRecordingContent&&(this.complianceRecordingContent=e.complianceRecordingContent),e.conversationStartTime&&(this.conversationStartTime=e.conversationStartTime),e.layoutDetails&&(this.meetingLayoutDetails=e.layoutDetails),e.compositionServiceDetails&&(this.compositionServiceDetails=e.compositionServiceDetails),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,meetingLayoutDetails:this.meetingLayoutDetails,compositionServiceDetails:this.compositionServiceDetails},t))}processLocalParticipantUpdateResponse(e,t){this.logger.info(`[${t}][processLocalParticipantUpdateResponse]`),e.sequenceNumber&&e.sequenceNumber<this.localParticipantUpdateSequenceNumber||(this.breakoutDetails=e.breakoutDetails||{},this.signalingSessionCallback.onBreakoutDetailsUpdated(this.breakoutDetails,t),!0===e.nudgeToJoinAsRealtime&&(this.telemetryHelper.recordEvent("NudgeToJoinAsRealtime",{causeId:t}),this.signalingSessionCallback.onNudgeToJoinRealtime(t)))}handlePendingEndpointState(e){this.requestedEndpointStateWhileConnecting&&(this.logger.info(`[${e}][handlePendingEndpointState]sending pending endpoint state now that we are connected.`),this.updateEndpointState(this.requestedEndpointStateWhileConnecting,e,this.requestedPublishedStatesWhileConnecting).catch((e=>{this.isPreheatOnly&&this.disablePreheatDefer.isPending()&&(this.logger.info("handlePendingEndpointState failed"),this.disablePreheatDefer.reject(e))})))}handleMeetingDetailsChanged(e,t){this.logger.info(`[${t}][handleMeetingDetailsChanged]`),e.meetingDetails&&!kd.isEqual(e.meetingDetails,this.meetingDetails)&&this.signalingSessionCallback.onMeetingDetailsUpdated&&(this.meetingDetails=e.meetingDetails,this.meetingDetails.meetingCapability?.meetingLiveState&&(this.meetingLiveStateSequenceNumber=this.meetingDetails.meetingCapability.meetingLiveState.seqNum,this.logger.info(`[${t}][handleMeetingDetailsChanged] update meeting seqNum as ${this.meetingLiveStateSequenceNumber}`)),this.signalingSessionCallback.onMeetingDetailsUpdated(this.meetingDetails,t))}handleMeetingStatesChanged(e,t){this.logger.info(`[${t}][handleMeetingStatesChanged]`),this.signalingSessionCallback.onMeetingStatesUpdated&&this.signalingSessionCallback.onMeetingStatesUpdated(e.meetingStates,t)}handleBrokerSubscription(e,t){this.logger.info(`[${t}][handleBrokerSubscription]`),e.links.subscribe?(this.telemetryHelper.recordEvent("SubscribeUrlFound",t),this.brokerService&&!kd.isEqual(e.links.subscribe,this.brokerService.currentSubscriptionUrl)?this.brokerService.subscribeToBroker(e.links.subscribe):(this.logger.info(`[${t}][handleBrokerSubscription] broker subscribe ignored. Broker is disabled or subscribe url is same.`),this.telemetryHelper.recordEvent("BrokerDisabledSubscribeUrlPresent",t))):this.telemetryHelper.recordEvent("SubscribeUrlMissing",t)}cancelOutgoingCall(e,t){const i=to();this.logger.info(`[${t}][cancelOutgoingCall][rejectionData=${e&&je(e)}]`);const n={code:isNaN(e?.code)?wa.CALL_END_CODE.CANCEL:e.code,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories||[Qs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};if(this.signalingAgentConfig.enableSpecificErrorCodesForCallEnd&&(n.code=wa.CALL_END_CODE.CANCEL,n.subCode=wa.CALL_END_SUB_CODE.SUCCESS,n.phrase=wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,n.resultCategories=[Qs]),this.links.hasOwnProperty(wa.LINKS.LEAVE)){this.logger.info(`[${t}][cancelOutgoingCall] cancelling outgoing call`),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const e={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()},r={terminatingEnd:sd,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE],requestName:Zo.CANCEL_CALL.name,payload:Lu(this,n,e),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const s=Ka(e,this.signalingAgentConfig);this.logger.info(`[cancelOutgoingCall][${t}] error: ${je(e)} xhrError: ${je(s)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)}))}else this.logger.info(`[${t}][cancelOutgoingCall] Conversation Service Leave Url is not yet set. Cannot leave conversation. Disposing anyways.`),n.subCode=wa.CALL_END_SUB_CODE.CONV_URL_NOT_SET,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t),i.resolve(null);return i.promise}terminateEstablishedCall(e,t){const i=t.causeId||Na();this.logger.info(`[${i}][terminateEstablishedCall]`);const n=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const r=this.convJoined?Zo.LEAVE_CONVERSATION.name:Zo.END_CALL.name,s=tu(),a={code:e?.code||wa.CALL_END_CODE.SUCCESS,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};a.resultCategories=a.resultCategories||[Qs];const o={terminatingEnd:sd,endCode:a.code,endSubCode:a.subCode,resultDetail:a.phrase||"TerminateEstablishedCall",causeId:i,clientReasonSubCode:a.clientReasonSubCode,clientReasonPhrase:a.clientReasonPhrase,resultCategories:a.resultCategories};return this.leaveConversation(a,t).then((()=>{this.logger.info(`[${i}][terminateEstablishedCall]success`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!0,s.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,a),this.dispose(a,i)),n.resolve(null)})).catch((e=>{const t=Ka(e,this.signalingAgentConfig);this.logger.info(`[${i}][terminateEstablishedCall][failed] error: ${je(e)} xhrError: ${je(t)}]`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!1,s.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,a),this.dispose(a,i)),n.resolve(null)})),n.promise}deleteConversation(e,t){this.logger.info(`[${t}][deleteConversation]`);const i=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const n=Zo.DELETE_CONVERSATION.name,r=tu(),s={code:e?.code||wa.CALL_END_CODE.SUCCESS,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED,resultCategories:e?.resultCategories||[Qs],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase},a={terminatingEnd:sd,endCode:s.code,endSubCode:s.subCode,resultDetail:s.phrase,causeId:t,clientReasonSubCode:s.clientReasonSubCode,clientReasonPhrase:s.clientReasonPhrase,resultCategories:s.resultCategories};return this.deleteConversationController(s,t).then((()=>{this.logger.info(`[${t}][deleteConversation]success`),this.disposed||(this.telemetryHelper.setTerminatingData(a),this.telemetryHelper.addNetworkOperationCompleted(n,!0,r.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,s),this.dispose(s,t)),i.resolve(null)})).catch((e=>{const o=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][deleteConversation][failed] error: ${je(e)} xhrError: ${je(o)}`),this.disposed||(this.telemetryHelper.setTerminatingData(a),this.telemetryHelper.addNetworkOperationCompleted(n,!1,r.duration()),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,s),this.dispose(s,t)),i.resolve(null)})),i.promise}leaveConversation(e,t){const i=t.causeId||Na();if(this.convJoined){this.logger.info(`[${i}][leaveConversation]`);const n={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()};return this.http.sendPostRequest({url:this.links[wa.LINKS.LEAVE],requestName:Zo.LEAVE_CONVERSATION.name,payload:Bu(this,e,n,t.scope),withoutTrouter:!0,causeId:i})}return this.logger.info(`[${i}][leaveConversation] ignore, not joined to conversation`),Promise.resolve(void 0)}deleteConversationController(e,t){return this.convJoined?(this.logger.info(`[${t}][deleteConversationController]`),this.http.sendDeleteRequest({url:this.links[wa.LINKS.CONVERSATION_CONTROLLER],requestName:Zo.DELETE_CONVERSATION.name,payload:xu(this,e),withoutTrouter:!0,causeId:t})):(this.logger.info(`[${t}][deleteConversationController]ignored, not joined to conversation`),Promise.resolve(void 0))}rejectIncomingCall(e,t){this.telemetryHelper.recordEvent("RejectIncomingCall",t),this.logger.info(`[${t}][rejectIncomingCall]`);const i=to();this.fsmState=wa.SIGNALING_FSM_STATE.IDLE;const n={code:isNaN(e?.code)?wa.CALL_END_CODE.REJECT:e.code,subCode:e?.subCode||wa.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||wa.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase,...this.signalingAgent?.accountConfig?.applicationType?{applicationType:this.signalingAgent.accountConfig.applicationType}:{}};n.resultCategories=n.resultCategories||[Qs];const r={terminatingEnd:sd,endCode:n.code,endSubCode:n.subCode,resultDetail:n.phrase||"RejectCall",causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};return this.http.sendDeleteRequest({url:this.links[wa.LINKS.REJECT],requestName:Zo.REJECT_CALL.name,payload:Gu(this,n),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const s=Ka(e,this.signalingAgentConfig);this.logger.info(`[rejectIncomingCall][${t}] error: ${je(e)} xhrError: ${je(s)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})),i.promise}onCallStatusChanged(e,t,i){const n=`[${t}][onCallStatusChanged]`;if(this.logger.info(`${n}${this.currentCallStatus}=>${e}]`),this.disposed)this.logger.info(`${n}Call is already disposed!!`);else if(i&&this.logger.info(`${n}[statusCode=${je(i)}]`),this.isPromotingToRealtime)e===wa.CALL_STATUS.CONNECTED&&this.onPromotionCompleted(!1,void 0,t);else if(this.isValidStateTransitions(e)){this.currentCallStatus=e;const n={callStatus:e,statusCode:i,causeId:t};this.isPreheatOnly&&(n.isPreheatOnly=!0),this.telemetryHelper.recordEvent("UpdateCallStatus",n),this.signalingSessionCallback.onCallStatusChanged(e,i,t),this.currentCallStatus===wa.CALL_STATUS.CONNECTED&&(this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.telemetryHelper.resetCallCancelationDurationWatch(),this.isPreheatOnly&&this.startCallPreheatTimer(t))}}updateMeetingLiveStateAsync(e,t){this.logger.info(`[${e}][updateMeetingLiveStateAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent("UpdateMeetingLiveState",{causeId:e,meetingLiveStateOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,(()=>{this.handleUpdateMeetingLiveStateError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT},$o,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT);const i=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingLiveState:t,links:{updateMeetingLiveStateStatus:Ra(e,ra.UPDATE_MEETING_LIVE_STATE_STATUS)},operationId:i}}}(this,{...t,sequenceNumber:this.meetingLiveStateSequenceNumber},e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_LIVE_STATE],requestName:Zo.UPDATE_MEETING_LIVE_STATE.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingLiveStateAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent($o,{causeId:e})})).catch((i=>{const n=Ka(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingLiveStateAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingLiveStateError(n.error,"UpdateMeetingLiveStateRequestFailed",e,e,t),Promise.reject(n.error))}))}updateMeetingStatesAsync(e,t){const i=this.logger.createChild(`[${e}][updateMeetingStatesAsync]`,this.correlationId);if(i.info(`meetingStatesOptions: ${JSON.stringify(t)}`),!t)return Promise.reject({code:wa.VALIDATION.VALIDATION_FAILED,subCode:wa.VALIDATION.NULL_OR_EMPTY,phrase:"meetingStatesOptions should be a non empty object"});this.telemetryHelper.recordEvent("UpdateMeetingStates",{causeId:e,meetingStatesOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,(()=>{for(const i in t.meetingStates)this.handleUpdateMeetingStatesError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT},Jo,e,t.operationId+"_"+i)}),wa.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT);const n=function(e,t,i){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingStates:t,updateMeetingStatesStatus:Ra(e,ra.UPDATE_MEETING_STATES_STATUS),operationId:i}}}(this,{...t.meetingStates},e);return this.http.sendPostRequest({url:this.links[wa.LINKS.UPDATE_MEETING_STATES],requestName:Zo.UPDATE_MEETING_STATES.name,payload:n,causeId:e}).then((t=>{i.info(`response: ${je(t)}`),this.telemetryHelper.recordEvent(Jo,{causeId:e})})).catch((n=>{const r=Ka(n,this.signalingAgentConfig);if(i.error(`error: ${je(r)}`),!this.disposed){for(const i in t.meetingStates)this.handleUpdateMeetingStatesError(r.error,Yo,e,t.operationId+"_"+i);return Promise.reject(r.error)}return Promise.reject(this.getCallNotFoundTransactionEnd())}))}handleUpdateMeetingLiveStateError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted&&this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted(e,i,n))}handleUpdateMeetingLiveStateCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingLiveStateResponse.result,r=t.updateMeetingLiveStateResponse.operationId;r||this.logger.warn(`[${i}][handleUpdateMeetingLiveStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingLiveStateCompletion] meetingLiveUpdate completes with operationId=${r}`),this.handleOperationCompletionCommon(n,i,r,je(t),"handleUpdateMeetingLiveStateCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,"UpdateMeetingLiveStateResponseSuccess","UpdateMeetingLiveStateResponseFailure",this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted,this.handleUpdateMeetingLiveStateError.bind(this))}handleUpdateMeetingStatesError(e,t,i,n){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingStatesError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingStatesError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.signalingSessionCallback.onUpdateMeetingStatesCompleted&&this.signalingSessionCallback.onUpdateMeetingStatesCompleted(e,i,n))}handleUpdateMeetingStatesCompletion(e){const t=e.body,i=Qa(e),n=t.updateMeetingStatesResponse,r=t.operationId,s=this.logger.createChild(`[${i}][handleUpdateMeetingStatesCompletion]`,this.correlationId);r||s.warn("operationId is undefined.");for(const e of n)s.info(`UpdateMeetingStates completes with operationId=${r}.`),this.handleOperationCompletionCommon(e.transactionEnd,i,r+"_"+e.meetingStateName,je(t),"handleUpdateMeetingStatesCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,"UpdateMeetingStatesResponseSuccess",Yo,this.signalingSessionCallback.onUpdateMeetingStatesCompleted,this.handleUpdateMeetingStatesError.bind(this))}handleUpdateMonitorSessionCompletion(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleUpdateMeetingStatesCompletion]`,this.correlationId);const n=t.monitorCompletion;this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleUpdateMonitorSessionCompletion",wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,"UpdateMonitorSessionResponseCompleted","UpdateMonitorSessionResponseFailed",this.signalingSessionCallback.onUpdateMonitorSessionCompleted,this.handleUpdateMonitorSessionError.bind(this))}handleUpdateMonitorSessionError(e,t,i,n){this.disposed?this.logger.info(`[${i}][handleUpdateMonitorSessionError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMonitorSessionError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,monitorOptions:n,causeId:i}),this.signalingSessionCallback.onUpdateMonitorSessionCompleted(e,i))}setMeetingLayoutAsync(e,t){this.logger.info(`[${e}][setMeetingLayoutAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent("SetMeetingLayout",{causeId:e,setMeetingLayoutOptions:t}),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,(()=>{this.handleSetMeetingLayoutError({code:wa.CALL_END_CODE.TIMEOUT,subCode:wa.CALL_END_SUB_CODE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT,phrase:wa.CALL_END_PHRASE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT},Go,e,e,t)}),wa.TIMEOUT_VALUES_IN_SECONDS.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT);const i=function(e,t){return Ua(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},...t,links:{setMeetingLayoutStatus:Ra(e,ra.SET_MEETING_LAYOUT_STATUS)}}}}(this,{...t,sequenceNumber:this.meetingLayoutSequenceNumber});return this.http.sendPostRequest({url:this.links[wa.LINKS.SET_MEETING_LAYOUT],requestName:Zo.SET_MEETING_LAYOUT.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][setMeetingLayoutAsync] response: ${je(t)}`),this.telemetryHelper.recordEvent(Go,{causeId:e})})).catch((i=>{const n=Ka(i);return this.logger.info(`[${e}][setMeetingLayoutAsync] error: ${je(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleSetMeetingLayoutError(n.error,"SetMeetingLayoutRequestFailed",e,e,t),Promise.reject(n.error))}))}handleSetMeetingLayoutError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleSetMeetingLayoutError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleSetMeetingLayoutError] reject reason: ${e}`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onSetMeetingLayoutCompleted&&this.signalingSessionCallback.onSetMeetingLayoutCompleted(e,i,n))}handleSetMeetingLayoutCompletion(e){const t=e.body,i=Qa(e),n=t.transactionEnd,r=t.operationId;n.result=t.layoutDetails,r||this.logger.warn(`[${i}][handleSetMeetingLayoutCompletion] operationId is undefined.`),this.handleOperationCompletionCommon(n,i,void 0,je(t),"handleSetMeetingLayoutCompletion",wa.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,"SetMeetingLayoutResponseSuccess","SetMeetingLayoutResponseFailure",this.signalingSessionCallback.onSetMeetingLayoutCompleted,this.handleSetMeetingLayoutError.bind(this))}handleOperationCompletionCommon(e,t,i,n,r,s,a,o,l,c){this.disposed?this.logger.info(`[${t}][${r}] ignored. Call disposed.`):(this.logger.info(`[${t}][${r}] body ${n}`),e.code===wa.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(s),this.telemetryHelper.recordEvent(a,{...e,causeId:t}),l&&l(e,t,i)):c&&c(e,o,t,i))}isValidStateTransitions(e){if(this.currentCallStatus===wa.CALL_STATUS.LOCAL_TERMINATED&&e===wa.CALL_STATUS.CONNECTING)return!0;const t=e=>{switch(e){case wa.CALL_STATUS.IDLE:case wa.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY:return 0;case wa.CALL_STATUS.CONNECTING:return 1;case wa.CALL_STATUS.RINGING:return 2;case wa.CALL_STATUS.CONNECTED:return 3;case wa.CALL_STATUS.LOCAL_TERMINATED:case wa.CALL_STATUS.REMOTE_TERMINATED:return 4;default:return-1}};return t(e)>t(this.currentCallStatus)}handlePSTNBalanceUpdate(e){const t=e.body.balanceUpdate,i=Qa(e);this.logger.info(`[${i}][handlePSTNBalanceUpdate]`),this.telemetryHelper.recordIncomingEvent(Fo,e),t.updateBalance?this.signalingSessionCallback.onPSTNBalanceUpdate(t):this.logger.info(Fo,"this was a pstn keepAlive message - ignore")}handleCallAcceptanceAck(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleCallAcceptanceAck]`),this.telemetryHelper.recordIncomingEvent("HandleCallAcceptanceAck",e),this.internalHandleCallAcceptanceAck(t,i)}internalHandleCallAcceptanceAck(e,t){this.logger.info(`[${t}][internalHandleCallAcceptanceAck] ${je(e)}`),this.fsmState!==wa.SIGNALING_FSM_STATE.CONNECTED&&(this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptanceAcknowledgement.links.mediaRenegotiation,this.links[wa.LINKS.TRANSFER]=e.callAcceptanceAcknowledgement.links.transfer,this.links[wa.LINKS.REPLACE]=e.callAcceptanceAcknowledgement.links.replacement,this.links[wa.LINKS.HANGUP]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[wa.LINKS.KEEPALIVE]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[wa.LINKS.PARK]=e.callAcceptanceAcknowledgement.links.hold,this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptanceAcknowledgement.links.updateMediaDescriptions,this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.callAcceptanceAcknowledgement.links.monitor,this.saveMediaControllerLinksIfAny(e.callAcceptanceAcknowledgement),this.scheduleKeepAlives(e.callAcceptanceAcknowledgement.callKeepAliveInterval),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptanceAcknowledgement.callProperties?.isSharedLineAppearanceV2Activated),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.INCOMING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][internalHandleCallAcceptanceAck] updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t)))}isFatalException(e){let t=!0;try{JSON.parse(e.message).code===wa.CALL_END_CODE.CONFLICT&&(t=!1,this.logger.info("isFatalException: received non-fatal 409 error"))}catch(e){this.logger.error("isFatalException: failed to parse error")}return t}startOrJoinCall(e,t,i,n,r){if(this.logger.info(`[${i}]startOrJoinCall[${t}]`),this.disposed)return void this.logger.info(`[${i}][${t}] session already disposed, ignore`);this.telemetryHelper.recordEvent("StartOrJoinCall",{causeId:i,requestName:t}),this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i);const s=this.getConversationUrl()?this.getConversationUrl():e.conversationServiceUrl;this.telemetryHelper.setConversationServiceUrl(s),this.logger.info(`options.conversationServiceUrl ${e.conversationServiceUrl} conversationServiceUrl ${s}`),e.isPreheatOnly?(this.isPreheatOnly=!0,this.telemetryHelper.recordEvent("EnablingPreheat",{causeId:i}),this.telemetryHelper.setSelfParticipantRole(md),this.telemetryHelper.setIsPreheated()):this.telemetryHelper.startCallCancelationDurationWatch(),this.mediaTypesToUse=r,this.lastUsedOutgoingMediaContent=n,this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);const a=!this.multiParty&&this.signalingAgentConfig.enableLongOutgoing1To1SetupTimeoutForWeb,o=a?wa.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`[${i}][${t}]target endpointType = ${this.transferContext&&this.transferContext.target?this.transferContext.target.endpointType:"default"} timeout = ${o} LongerTimeout = ${a}`);const l=e.newCall?function(e,t,i,n){Ua(e,"signalingSession cannot be null");let r=[];r=n.invitationType===wa.INVITATION_TYPE.NUDGE&&Array.isArray(n.participantsToNudge)?n.participantsToNudge.map((e=>({id:e}))):e.participantManager.getParticipantsToInitiateCallWith(),e.signalingAgentConfig.doHostlessCalling||xa(r.length>0,"remoteParticipants need to be set before a call can be made");const s={type:"Delta",rosterUpdate:Ra(e,ra.CONV_ROSTER_UPDATE)},a=e.groupId?{id:e.groupId}:null,o=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,l=e.contentSharingManager.getContentSharingInfoToStartSharing(),c=null===l?null:{identifier:l.contentIdentifier,subject:l.subject,sessionState:l.sessionState,sessionUpdateSequenceNumber:l.sequenceNumber,links:{sessionUpdate:Ra(e,ra.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Ra(e,ra.CONV_CONTENT_SHARING_END)}},d=e.broadcastSession?.getContext(),u=e.getEndpointCapabilities();1===r.length&&e.telemetryHelper.setCalleeType(r[0].id),e.numberOfOriginalInvitees=r.length;const h=[];r.forEach((t=>{const i={id:t.id};t.displayName&&(i.displayName=t.displayName),t.participantId&&(i.participantId=t.participantId),(n.callToVoicemail||e.transferContext&&e.transferContext.target&&"voicemail"===e.transferContext.target.endpointType)&&(i.endpointType="voicemail"),h.push(i)}));const g=e.transferContext?e.transferContext.transferor:null,p=e.transferContext?e.transferContext.transferContext:null,m={};n.callToVoicemail&&(n.voicemailResourcePath&&(m.localResourcePath=n.voicemailResourcePath),n.voicemailItemId&&(m.voicemailItemId=n.voicemailItemId));const f={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,applicationType:n.applicationType,targetApplicationType:n.targetApplicationType,roster:s,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Ra(e,e.signalingAgentConfig.enableSplitConversationEndUrl?n.subscribe?ra.CONV_END_SUBSCRIBE:ra.CONV_END_JOIN:ra.CONV_END),conversationUpdate:Ra(e,ra.CONV_UPDATE),localParticipantUpdate:Ra(e,ra.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Ra(e,ra.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Ra(e,ra.CONV_ADD_PARTICIPANT_FAILURE),addModalitySuccess:Ra(e,ra.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Ra(e,ra.CONV_ADD_MODALITY_FAILURE),confirmUnmute:Ra(e,ra.CONV_CONFIRM_UNMUTE),receiveMessage:Ra(e,ra.RECEIVE_MESSAGE)}},broadcast:d,contentSharing:c,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin},to:h},capabilities:null,endpointCapabilities:u,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,groupContext:a,groupChat:o,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("createConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),f.payload.publishedStates=t}e.deviceType&&"default"!==e.deviceType&&(f.payload.conversationRequest.deviceType=e.deviceType);const v=Ha(i);if(e.telemetryHelper.addOutgoingModalities(v),f.payload.callInvitation={callModalities:v,replaces:null,transferor:g||null,clientTransferContext:p,customContext:n.customHeaderContext||null,links:{progress:Ra(e,ra.PROGRESS),mediaAnswer:Ra(e,ra.MEDIA_ANSWER),acceptance:Ra(e,ra.ACCEPT),redirection:Ra(e,ra.REDIRECTION),end:Ra(e,ra.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),pstnContent:e.pstnContent,emergencyContent:e.getEmergencyContent(),mediaContent:t,voicemailSettings:m,routingFlags:n.routingFlags,invitationData:n.invitationData,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent()},n.pickupCode&&(f.payload.callInvitation.unparkContent={pickupCode:parseInt(n.pickupCode,10)}),n.onBehalfOf&&(f.payload.callInvitation.onBehalfOf={id:n.onBehalfOf},n.onBehalfOfUserDisplayName&&(f.payload.callInvitation.onBehalfOf.displayName=n.onBehalfOfUserDisplayName)),n.callQueueContext&&(f.payload.callInvitation.callQueueContext=n.callQueueContext),n.scenario&&(f.payload.conversationRequest.scenario=n.scenario),n.alternateId&&(f.payload.participants.from.alternateId=n.alternateId),n.callingLineIdentity&&(f.payload.participants.from.callingLineIdentity=n.callingLineIdentity),n.invitationType===wa.INVITATION_TYPE.NUDGE&&(f.payload.participants.invitationType=n.invitationType),e.signalingAgentConfig.ecsEtag&&(f.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),n.clientEndpointDebugContent){f.payload.debugContent||(f.payload.debugContent={});try{f.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){xa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{f.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){xa(!1,`Failed to parse ${n.captchaContentJson}`)}return n.participationPreferences&&(f.payload.participationPreferences=n.participationPreferences),n.participantPropertyBag&&(f.payload.participantPropertyBag=n.participantPropertyBag),f}(this,n,r,e):Uu(this,n,r,e,i);this.signalingAgentConfig.enableCallEstablishmentTimeoutsForStartJoinCall&&this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(i)}),o),this.signalingSessionCallback.onTransferredCallAcceptance(i),e.endpointState&&(this.latestEndpointState=e.endpointState),this.http.sendPostRequest({url:s,requestName:t,operationType:"CallSetup",payload:l,causeId:i}).then((e=>{this.disposed||(this.processConversationServiceResponseHeaders(e,i),this.processConversationServiceResponse(e.response,i,0),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTING,i))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return;const n=Ka(e,this.signalingAgentConfig);if(this.logger.info(`[startOrJoinCall][${i}][${t}] error: ${je(e)} xhrError: ${je(n)}`),!this.disposed){if(this.isPromotingToRealtime)return void this.onPromotionCompleted(!0,n.error,i);this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,endCode:n.telemetryEndSubCode,endSubCode:n.error.subCode,resultCategories:n.error.resultCategories,resultDetail:n.error.phrase||"StartOrJoinCallFailure",causeId:i}),this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,i,n.error),this.dispose(n.error,i)}}))}processIncomingCallPayload(e,t){this.remoteUser=mo.fromWireParticipant(e.callNotification.from),this.participantManager.setLocalParticipantId(e.callNotification.to.participantId,t),e?(e.conversationInvitation&&(this.links[wa.LINKS.CONVERSATION_CONTROLLER]=e.conversationInvitation.conversationController,this.setMultiParty(e.conversationInvitation.isMultiParty,t),this.setIsHostless(!!e.conversationInvitation.isHostless,t)),e.callNotification&&(this.links[wa.LINKS.ATTACH]=e.callNotification.links?.attach,this.links[wa.LINKS.REDIRECT]=e.callNotification.links?.redirection,this.onBehalfOf=e.callNotification.onBehalfOf?.id,this.onBehalfOfUserDisplayName=e.callNotification.onBehalfOf?.displayName,this.callQueueContext=e.callNotification.callQueueContext,this.callPhoneLineType=e.callNotification.callPhoneLineType,this.callType=e.callNotification.callType,this.incomingCallCallerId=e.callNotification.from?.id,this.callUsesMixer=!!e.callNotification.mediaContent?.fromMixer,this.isRedirectAllowed=!!e.callNotification.redirectionProperties?.isRedirectAllowed,this.callQueueSupervisorContent=e.callNotification.callQueueSupervisorContent,this.bannerContent=e.callNotification.bannerContent),e.debugContent&&this.updateCorrelationId(e.debugContent.callId,t),e.callNotification.transferor&&(this.transferor=e.callNotification.transferor.details?e.callNotification.transferor.details.id:null),e.groupChat&&this.updateGroupChatIds(e.groupChat,t),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo)):this.logger.info(`[${t}][processIncomingCallPayload] empty incoming payload content`)}processAttachResponse(e,t,i){this.telemetryHelper.recordEvent("ProcessInitialOffer",{causeId:i}),this.links[wa.LINKS.MEDIA_ANSWER]=t.response.callInvitation.links.mediaAnswer,this.links[wa.LINKS.ACCEPT]=t.response.callInvitation.links.acceptance,this.links[wa.LINKS.REJECT]=t.response.callInvitation.links.callLeg,this.links[wa.LINKS.REDIRECT]=t.response.callInvitation.links.redirection,this.links[wa.LINKS.NEW_OFFER]=t.response.callInvitation.links.newOffer,this.signalingAgentConfig.sendProgressFromCC||this.sendProgress(t),this.remoteCaller=t.response.participants.from;const n=this.getInitialMediaOfferFromIncomingCallPayload()||t.response.callInvitation.mediaContent;this.telemetryHelper.setCallerType(this.getParticipantIdForOfferAnswer(n));const r=Ha(t.response.callInvitation.callModalities);this.telemetryHelper.addIncomingModalities(r),this.telemetryHelper.setOfferedModalities(n.blob,!0),this.callUsesMixer=n.fromMixer,this.isRedirectAllowed=!(!t.response.callInvitation.redirectionProperties||!t.response.callInvitation.redirectionProperties.isRedirectAllowed),this.signalingSessionCallback.onOffer({subject:e.conversationInvitation.subject,remoteParticipantId:this.getParticipantIdForOfferAnswer(n),remoteEndpointId:t.response.participants.from.endpointId,transferor:t.response.callInvitation.transferor,clientTransferContext:e.callNotification.transferContext,customHeaderContext:t.response.callInvitation.customContext,mediaTypes:r,mediaContent:n,renegotiation:!1,invitationData:t.response.callInvitation.invitationData,riskLevel:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.riskLevel,stirAttestation:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.stirAttestation,isRedirectAllowed:this.isRedirectAllowed},i)}sendProgress(e,t=Na()){this.logger.info(`[${t}][sendProgress]`),this.telemetryHelper.recordEvent("SendProgress",{causeId:t}),this.http.sendPostRequest({url:e.response.callInvitation.links.progress,requestName:Zo.SEND_CALL_PROGRESS.name,payload:Nu(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][sendProgress] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent("SendProgressFailed",{causeId:t,...i.error})}))}handleCallNotification(e){const t=Qa(e);if(this.logger.info(`[${t}][handleCallNotification]`),this.telemetryHelper.recordIncomingEvent("HandleCallNotification",e),!ja(e.url,ra.REPLACE))throw new Error(`[${t}][handleCallNotification]IncomingCallNotification should not be received in handleIncomingMsg`);this.telemetryHelper.recordIncomingEvent("HandleIncomingCallReplacement",e),this.logger.info(`[${t}][handleCallNotification]replacementCallNotification`),this.signalingSessionCallback&&this.signalingSessionCallback.onIncomingCallReplacement(e.body,t)}handleMediaAnswer(e){this.telemetryHelper.recordIncomingEvent(vo,e);const t=e.body,i=Qa(e);if(this.logger.info(`[${i}][handleMediaAnswer]`),this.mediaRenegotiationManager.isOutgoingRenegotiationInProgress())this.mediaRenegotiationManager.handleMediaAnswer(t,i);else if(this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED);else if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING){if(Ja(e.headers,this.provisionalMediaAnswersSeenSoFar))return void this.logger.info(`[${i}][handleMediaAnswer] ignoring provisional answer retried by service`);t.mediaAnswer.sender&&(this.remoteUser=t.mediaAnswer.sender),this.resetCallEstablishmentTimeout(i),t.mediaAnswer.noRingBack||(this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,i));const n=t.mediaAnswer.mediaContent;this.signalingSessionCallback.onAnswer({provisional:!0,renegotiation:!1,remoteEndpointId:t.mediaAnswer.sender?t.mediaAnswer.sender.endpointId:La(),remoteParticipantId:this.getParticipantIdForOfferAnswer(n),mediaContent:n},i)}}async _sendCallAcceptanceAcknowledgement(e,t){this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][_sendCallAcceptanceAcknowledgement] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent(Io,{causeId:t,...i.error})}))}handleCallAcceptance(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleCallAcceptance",e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptance]enableQuickSendAcceptanceAck:\n ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?(this._sendCallAcceptanceAcknowledgement(e,t),this._processCallAcceptance(e,t)):(this._processCallAcceptance(e,t),this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=Ka(e,this.signalingAgentConfig);this.logger.info(`[${t}][handleCallAcceptance] error: ${je(i)}`),this.disposed||this.telemetryHelper.recordEvent(Io,{causeId:t,...i.error})})))}handleCallAcceptanceSync(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleCallAcceptanceSync",e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptanceSync] enableQuickSendAcceptanceAck:\n ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?kd.defer(this._processCallAcceptance,e,t):this._processCallAcceptance(e,t);const i=ku(this).payload;return this.telemetryHelper.addNetworkOperationCompleted(Zo.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,!0),i}getFakeRoster(e){const t=this.participantManager.getParticipantsToInitiateCallWith();let i;i=1===t.length?t[0].id:e.callAcceptance.acceptedBy.id;const n={id:i,displayName:e.callAcceptance.acceptedBy.id===i?e.callAcceptance.acceptedBy.displayName:"",languageId:e.callAcceptance.acceptedBy.languageId},r=e.callAcceptance.acceptedBy.endpointId;return{type:"MultiPartyEndpoint",participants:{[i]:{acceptedBy:e.callAcceptance.acceptedBy.id,details:n,endpoints:{[r]:{call:{},contentSharing:{},capabilities:e.callAcceptance.capabilities,participantId:e.callAcceptance.acceptedBy.participantId}}}}}}processCallAcceptance(e,t){this.logger.info(`[${t}][processCallAcceptance] ${je(e)}`),this.telemetryHelper.recordEvent("ProcessCallAcceptance",{causeId:t}),this.fsmState=wa.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t);let i=!1;e.callAcceptance.controllerName===wa.MISC.LOBBY_CALL_CONTROLLER&&(this.logger.info(`[${t}][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}),i=!0,this.telemetryHelper.recordEvent("AcceptanceUserInLobby",{causeId:t})),this.participantManager.localParticipant.isStaging=Fd(e.callAcceptance),this.signalingSessionCallback.onMeetingGroupDetailsUpdated(e.callAcceptance.meetingGroupDetails,t),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptance.callProperties?.isSharedLineAppearanceV2Activated),this.logger.info(`[${t}][processCallAcceptance] for localParticipant, isStaging is set to ${this.participantManager.localParticipant.isStaging}`);let n=this.mediaTypesToUse,r=La();e.callAcceptance.acceptedBy&&(this.remoteUser=mo.fromWireParticipant(e.callAcceptance.acceptedBy),r=e.callAcceptance.acceptedBy.endpointId),e.callAcceptance.acceptedCallModalities&&e.callAcceptance.acceptedCallModalities.length>0&&(n=e.callAcceptance.acceptedCallModalities);const s=e.callAcceptance.mediaContent;this.callUsesMixer=s.fromMixer;const a=Ha(n);this.telemetryHelper.addIncomingModalities(a),this.telemetryHelper.setAnsweredModalities(s.blob,!0),this.links[wa.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptance.links.mediaRenegotiation,this.links[wa.LINKS.TRANSFER]=e.callAcceptance.links.transfer,this.links[wa.LINKS.REPLACE]=e.callAcceptance.links.replacement,this.links[wa.LINKS.HANGUP]=e.callAcceptance.links.callLeg,this.links[wa.LINKS.KEEPALIVE]=e.callAcceptance.links.callLeg,this.links[wa.LINKS.PARK]=e.callAcceptance.links.hold,this.links[wa.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptance.links.updateMediaDescriptions,this.links[wa.LINKS.UPDATE_MONITOR_SESSION]=e.callAcceptance.links.monitor,this.saveMediaControllerLinksIfAny(e.callAcceptance),this.scheduleKeepAlives(e.callAcceptance.callKeepAliveInterval);const o=this.getParticipantIdForOfferAnswer(s);this.signalingSessionCallback.onAnswer({provisional:!1,renegotiation:!1,remoteEndpointId:r,remoteParticipantId:o,callAcceptedByNGCVoicemail:o===wa.KNOWN_BOTS.VOICEMAIL_BOT_ID,mediaTypes:a,mediaContent:s},t),this.setRealTimeState(2,t),this.onCallStatusChanged(wa.CALL_STATUS.CONNECTED,t),i&&this.signalingSessionCallback.onSelfParticipantUpdated(this.participantManager.localParticipant,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][processCallAcceptance] Updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t))}updateGroupChatIds(e,t){const i=this.groupId,n=this.threadId,r=this.teamsMessageId,s=this.backroomThreadId,a=this.streamThreadId,o=this.lobbyThreadId;this.groupId=e.groupId,this.threadId=e.threadId,this.teamsMessageId=e.messageId,this.backroomThreadId=e.backroomThreadId,this.streamThreadId=e.streamThreadId,this.lobbyThreadId=e.lobbyThreadId,this.groupId===i&&this.threadId===n&&this.teamsMessageId===r&&this.backroomThreadId===s&&this.streamThreadId===a&&this.lobbyThreadId===o||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},t)}handleCallEnd(e,t){let i=e.body.callEnd||e.body;const n=Qa(e);if(this.logger.info(`[${n}][handleCallEnd][content=${je(i)}]`),this.telemetryHelper.recordEvent(wo,{origin:e.origin,code:i?i.code:"unknown",subCode:i?i.subCode:"unknown",resultCategories:i?i.resultCategories:[],causeId:n}),this.signalingAgentConfig.enableConversationTypeUpdateOnCallEnd&&(this.conversationType=i?.conversationType||this.conversationType,this.signalingSessionCallback.onConversationTypeUpdated(this.conversationType,n)),this.fsmState!==wa.SIGNALING_FSM_STATE.IDLE)if(i.code===wa.CALL_END_CODE.CONFLICT&&this.multiParty&&i.conversationUrl?.Location)this.handleConversationResolutionConflict(i,n);else{this.disposing=!0,i.callControllerTransactionEnd&&(this.logger.info("handleCallEnd: using CC end details specified in CS end"),i=i.callControllerTransactionEnd),i.broadcastOperationFailure&&(this.logger.info("handleCallEnd: using broadcastOperationFailure end details specified in CS end"),i=i.broadcastOperationFailure);const e=i.code===wa.CALL_END_CODE.SUCCESS||i.code===wa.CALL_END_CODE.CANCEL||i.code===wa.CALL_END_CODE.REJECT;this.telemetryHelper.setTerminatingData({terminatingEnd:ad,resultDetail:i.phrase,resultValue:e?od:ld,endCode:i.code,endSubCode:i.subCode,resultCategories:i?i.resultCategories:[],causeId:n});const r={code:i.code,subCode:i.subCode,phrase:i.phrase,resultCategories:i.resultCategories,pickupCode:""},s=this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY;i.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:i.acceptedElsewhereBy.id,displayName:i.acceptedElsewhereBy.displayName}),i.unparkContent&&(i.unparkContent.CallParkAdditionalContext&&(this.parkAdditionalContextJson=JSON.stringify(i.unparkContent.CallParkAdditionalContext),this.serverHoldLocation=i.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),i.unparkContent.pickupCode&&(r.pickupCode=i.unparkContent.pickupCode));const a=this.signalingAgentConfig.enableSplitConversationEndUrl;a&&s===t?(this.logger.info("fsmstate = SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY or OUTGOING_FOR_ROSTER_ONLY"),this.onCallStatusChanged(wa.CALL_STATUS.REMOTE_TERMINATED,n,r),this.dispose(r,n)):a||(this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(wa.CALL_STATUS.REMOTE_TERMINATED,n,r),this.dispose(r,n))}else this.logger.info(`[${n}][handleCallEnd] not handling incoming callEnd since fsmstate = SIGNALING_FSM_STATE.IDLE`)}handleConversationResolutionConflict(e,t){this.logger.info(`[${t}][handleConversationResolutionConflict]`);const i={...e,phrase:e.phrase||"Conflict Resolution Error"};if(this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===wa.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY)this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.http.cancelRequestIfPending(Zo.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,t,void 0,i),this.subscribeToCall(e.conversationUrl.Location,e.correlationId,this.lastUsedJoinCallOptions?this.lastUsedJoinCallOptions.clientEndpointCapabilities:0,{meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,additionalEndpointProperties:this.lastUsedJoinCallOptions?.additionalEndpointProperties},t);else{this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const n={meetingData:this.meetingData,meetingPreferences:this.meetingPreferences};if(this.lastUsedJoinCallOptions){const e=this.lastUsedJoinCallOptions.scenario;n.muted=this.lastUsedJoinCallOptions.muted,n.scenario=`409Redirect${e||""}`,n.isPreheatOnly=this.lastUsedJoinCallOptions.isPreheatOnly,n.clientEndpointCapabilities=this.lastUsedJoinCallOptions.clientEndpointCapabilities,n.clientEndpointDebugContent=this.lastUsedJoinCallOptions.clientEndpointDebugContent,n.additionalEndpointProperties=this.lastUsedJoinCallOptions.additionalEndpointProperties}else n.scenario="409RedirectJoin";this.setInitialTelemetry("JoinCall",{correlationId:e.correlationId,causeId:t,conversationServiceUrl:e.conversationUrl.Location,joinCallOptions:n,offerGenerationTime:void 0}),this.http.cancelRequestIfPending(Zo.JOIN_CONVERSATION.name,t,void 0,i),this.http.cancelRequestIfPending(Zo.START_CALL.name,t,void 0,i),this.joinGivenConversation(e.conversationUrl.Location,e.correlationId,this.lastUsedOutgoingMediaContent,this.mediaTypesToUse,void 0,n,t)}}handleCallProgress(e){this.telemetryHelper.recordIncomingEvent("HandleCallProgress",e);const t=Qa(e);this.logger.info(`[${t}][handleCallProgress]`);const i=e.body.callProgress;this.fsmState===wa.SIGNALING_FSM_STATE.OUTGOING&&(this.telemetryHelper.setTimeToRingDuration(),this.resetCallEstablishmentTimeout(t),this.onCallStatusChanged(wa.CALL_STATUS.RINGING,t),"forwarded"===i.status&&this.signalingSessionCallback.onCallForwarded({destinationType:i.forwardingDestinationType||"user"},t))}resetCallEstablishmentTimeout(e){const t=this.isOneToOnePSTNCall()?wa.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:wa.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`resetCallEstablishmentTimeout: ${t}s`),this.timeoutManager.stopTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.timeoutManager.startTimer(wa.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(e)}),t)}handleMediaAcknowledgement(e){this.telemetryHelper.recordIncomingEvent("HandleMediaAck",e);const t=e.body,i=Qa(e);this.currentCallStatus!==wa.CALL_STATUS.CONNECTED?this.telemetryHelper.recordEvent("HandleMediaProvisionalAck",{causeId:i}):this.mediaRenegotiationManager.handleMediaAcknowledgment(t,i)}handleConversationUpdate(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleConversationUpdate]content=${je(t)}`),this.telemetryHelper.recordIncomingEvent("HandleConversationUpdate",e),this.processConversationServiceResponse(t,i,2)}endBroadcastMeeting(e){this.logger.info(`[${e}][endBroadcastMeeting]`),this.broadcastSession=null}handleLocalParticipantUpdate(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleLocalParticipantUpdate]content=${je(t)}`),this.telemetryHelper.recordIncomingEvent("HandleLocalParticipantUpdate",e),this.processLocalParticipantUpdateResponse(t,i)}handleAddModalityFailure(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddModalityFailure]`),this.telemetryHelper.recordIncomingEvent(Do,e),t.modalityFailure.contentSharing?this.contentSharingManager?.handleAddModalityFailure(t,i):t.modalityFailure.groupChat?this.signalingSessionCallback.onChatModalitySetupFailed({code:t.modalityFailure.groupChat.code,subCode:t.modalityFailure.groupChat.subCode,phrase:t.modalityFailure.groupChat.phrase,resultCategories:t.modalityFailure.groupChat.resultCategories},i):t.modalityFailure.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalityFailure(t,i)}handleAddModalitySuccess(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleAddModalitySuccess]`),this.telemetryHelper.recordIncomingEvent(Mo,e),t.modalitySuccess.contentSharing?this.contentSharingManager?.handleAddModalitySuccess(t,i):t.modalitySuccess.groupChat?this.logger.info(`[${i}][handleAddModalitySuccess] group modality ${je(t.modalitySuccess.groupChat)}`):t.modalitySuccess.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalitySuccess(t,i)}handleTransferRequested(e){const t=e.body.callTransfer,i=Qa(e);this.logger.info(`[${i}][handleTransferRequested]`),t.parkType?(this.telemetryHelper.recordIncomingEvent("HandleParkRequested",e,{type:t.parkType}),this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId)):"voicemail"===t.target.endpointType?(this.logger.info(`[${i}][handleTransferRequested] target endpointType = ${t.target.endpointType}`),this.telemetryHelper.recordIncomingEvent(Oo,e)):this.telemetryHelper.recordIncomingEvent(Oo,e),this.links[wa.LINKS.TRANSFER_ACCEPTANCE]=t.links.transferAcceptance,this.links[wa.LINKS.TRANSFER_COMPLETION]=t.links.transferCompletion,this.signalingSessionCallback.onTransferRequested?this.signalingSessionCallback.onTransferRequested(t,i):this.logger.info(`[${i}][handleTransferRequested] failed, no callback defined`)}handleTransferAcceptance(e){const t=Qa(e);this.logger.info(`[${t}][handleTransferAcceptance]`),this.telemetryHelper.recordIncomingEvent("WaitingForTransferCompletion",e),this.signalingSessionCallback.onTransferAccepted?this.signalingSessionCallback.onTransferAccepted(t):this.logger.info(`[${t}][handleTransferAcceptance]failed, no callback defined`)}handleTransferCompletion(e){const t=e.body,i=Qa(e);this.logger.info(`[${i}][handleTransferCompletion]`),t.sharedCorrelationId&&this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId),void 0!==t.unparkContent?.pickupCode&&(t.unparkContent.pickupCode=t.unparkContent.pickupCode.toString(),this.telemetryHelper.recordIncomingEvent("PickupCodeSet",e)),this.signalingSessionCallback.onTransferCompleted?(e.body.transferCompletion&&(0===e.body.transferCompletion.code?this.telemetryHelper.recordIncomingEvent(Ho,e):(this.logger.info(`[${i}][handleTransferCompletion]-1-code: ${t.transferCompletion.code}, message: ${je(e)}`),this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories}))),this.signalingSessionCallback.onTransferCompleted(t,i)):(e.body.transferCompletion&&(e.body.transferCompletion.code===wa.CALL_END_CODE.NETWORK_ERROR?this.telemetryHelper.recordIncomingEvent("WaitingForTransferCompletionFail",e):this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories})),this.logger.info(`[${i}][handleTransferCompletion]failed, no callback defined`))}handleRosterUpdate(e,t){const i=e.body,n=Qa(e);this.disposing||this.disposed?this.logger.info(`[${n}][handleRosterUpdate]failed=ignore call ending or ended`):this.internalHandleRosterUpdate(i,t,n)}handleNewMediaOffer(e){const t=Qa(e);this.telemetryHelper.recordIncomingEvent("HandleNewOffer",e);const i=e.body.mediaOfferReady.mediaContent;this.callUsesMixer=i.fromMixer,this.signalingSessionCallback.onNewOffer({mediaContent:i,renegotiation:!1},t)}internalHandleRosterUpdate(e,t,i){if(e&&"Delta"!==e.type&&"MultiPartyEndpoint"!==e.type)this.logger.warn(`[${i}][internalHandleRosterUpdate] roster.type=${e.type} is invalid`);else{this.logger.info(`[${i}][internalHandleRosterUpdate]`);try{this.participantManager.handleRosterUpdate(e,t,i),this.contentSharingManager?.handleIncomingContentSharingFromRoster(e,t,i)}catch(t){const n={code:wa.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:wa.CALL_END_SUB_CODE.ROSTER_HANDLING_INVALID_SERVICE_RESPONSE,phrase:t?.toString()};throw this.logger.info(`[${i}][internalHandleRosterUpdate] ${Ge(n)}`),this.telemetryHelper.recordRosterEvent(e,_o,i),n}}}scheduleKeepAlives(e){const t=.9*e*1e3;this.logger.info(`scheduleKeepAlives: every ${t} milliseconds`),this.keepAliveInterval=t,this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval)}scheduleConversationKeepAlive(){if(!this.conversationKeepAliveTimer&&!this.disposed){if(!this.conversationKeepAliveInterval){const e=function(e){const t=Math.floor(11*Math.random())+10;return Math.floor(e*(1-t/100))}(1e3*this.signalingAgentConfig.csaTimeoutConfiguration.conversationKeepAliveTimeoutSec);this.logger.info(`sendConversationKeepAlive: every ${e} milliseconds`),this.conversationKeepAliveInterval=e}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(e,t=Na()){if(this.disposed)return Promise.resolve();const i=this.logger.createChild(`[${t}][sendToUpdateConversationLinks]`,this.correlationId),n=e?function(e){Ua(e,"signalingSession cannot be null");const t={type:"Delta",rosterUpdate:Ra(e,na.CONV_ROSTER_UPDATE)};return{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},roster:t,links:$a(e,na)}}}(this):{},r=e?Zo.UPDATE_CONVERSATION_LINKS.name:Zo.SEND_CONVERSATION_KEEP_ALIVE.name,s=this.links[wa.LINKS.NOTIFICATION_LINKS];return i.info(`shouldUpdateUrl: ${e}, url: ${s}, payload: ${je(n)}`),s?(this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.http.sendPostRequest({url:s,payload:n,withoutTrouter:!0,requestName:r,causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.recordEvent("UpdateConversationLinksSuccess",{causeId:t}),this.processConversationServiceResponse(e.response,t,2))})).catch((e=>{const i=Ka(e,this.signalingAgentConfig),n=no(i.error.code);this.logger.info(`[${t}][updateConversationLinks] error: ${je(i)}, retryable: ${n}`),this.disposed||(this.telemetryHelper.recordEvent("UpdateConversationLinksFailed",{causeId:t,...i.error}),n?this.scheduleConversationKeepAlive():this.links[wa.LINKS.NOTIFICATION_LINKS]=null)}))):Promise.resolve()}sendToKeepAliveUrl(e,t=Na()){const i=this.logger.createChild(`[${t}][sendToKeepAliveUrl]`,this.correlationId);return i.info(`payload: ${je(e)}`),window.clearInterval(this.keepAliveTimer),this.disposed?Promise.resolve():(this.telemetryHelper.recordEvent("SendKeepAlive"),this.http.sendPostRequest({url:this.links[wa.LINKS.KEEPALIVE],payload:e,requestName:Zo.SEND_KEEP_ALIVE.name,withoutTrouter:!0,causeId:t}).then((()=>{this.restartKeepAliveInterval(t)})).catch((e=>{const n=Ka(e,this.signalingAgentConfig);i.info(`error: ${je(n)}`),this.restartKeepAliveInterval(t,!0,n.error)})))}handleCallEstablishmentTimeout(e,t,i){const n={code:wa.CALL_END_CODE.TIMEOUT,subCode:t||wa.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:i||wa.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT,resultCategories:[Xs]};this.isPromotingToRealtime?this.onPromotionCompleted(!0,n,e):(this.telemetryHelper.recordEvent("HandleCallEstablishmentTimeout"),this.telemetryHelper.setTerminatingData({terminatingEnd:sd,resultValue:ld,resultDetail:n.phrase,endCode:n.code,endSubCode:n.subCode,causeId:e,resultCategories:n.resultCategories}),this.fsmState=wa.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(wa.CALL_STATUS.LOCAL_TERMINATED,e,n),this.dispose(n,e))}handleCallTransferTimeout(e,t){if(this.disposed)return void this.logger.info("Transfer: handleCallTransferTimeout ignored");const i={code:wa.CALL_END_CODE.TIMEOUT,phrase:wa.CALL_END_PHRASE.TRANSFER_COMPLETION_TIMEOUT};this.signalingSessionCallback.onTransferCompleted&&(!1===t?this.telemetryHelper.recordEvent(ko,{code:wa.CALL_END_CODE.TIMEOUT,subcode:wa.CALL_END_SUB_CODE.TRANSFER_COMPLETE_TIMEOUT,causeId:e}):!0===t&&this.telemetryHelper.recordEvent("WaitingForTransferAcceptanceFail",{causeId:e}),this.signalingSessionCallback.onTransferCompleted({transferCompletion:i},e))}checkCorrelationIdChange(e,t){if(e&&e.headers){const i=e.headers.get(wa.HEADERS.CORRELATION_ID);if(i&&i.length){const n=[ra.CONV_CONTENT_SHARING_UPDATE,ra.CONV_CONTENT_SHARING_END].some((t=>e.url&&ja(e.url,t)));this.correlationId===i||n||(this.logger.info(`[${t}]checkCorrelationIdChange:${this.correlationId} => ${i}`),this.telemetryHelper.addChangingCorrelationId(this.correlationId,i),this.updateCorrelationId(i,t))}}}getCommandUrlPresence(){let e=0;return this.links[wa.LINKS.MUTE]&&(e|=1),this.links[wa.LINKS.UNMUTE]&&(e|=2),e}getCallNotFoundTransactionEnd(){return{code:wa.CALL_END_CODE.CALL_DOES_NOT_EXIST,subCode:0,phrase:wa.CALL_END_PHRASE.CALL_DOES_NOT_EXIST}}dispose(e,t){this.disposed||(this.logger.info(`[${t}][dispose] end reason ${je(e)}`),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(t).then((()=>{this.signalingAgent.onCallCompleted(this.sessionId,t),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(e,t),this.callOperationHandler.dispose("call ended",e,t),this.participantManager=null,this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=null,this.contentSharingManager?.dispose(e,t),this.contentSharingManager=null,this.telemetryHelper.dispose(),this.telemetryHelper=null,this.webRtcSignalingManager.dispose(),this.webRtcSignalingManager=null})))}},lh=class{constructor(e){this.endpointId=La(),this.signalingSessions={},this.clientSupportsGenericTokenAPI=!1,this.getNewSignalingSession=(e,t,i,n)=>{const r=Na();Ua(e,"selfParticipant should be a non null value"),Ua(t,"signalingSessionCallback should be a non null value");const s=i||La();Fa(s,"signalingSession id generated cannot be null or empty"),this.checkConfigChange(r);const a=function(e,t,i,n,r,s){return new oh(e,t,i,n,r,s)}(e,t,this.signalingAgentConfig,s,this,n),o=a.sessionId;return this.signalingSessions[o]=a,this.logger.info(`[${r}]Created new signalingSession with correlation ID ${s} and session ID ${o}`),a},this.resolvePotentialCallConflict=e=>{const t=Na();if(this.logger.info(`[${t}][resolvePotentialCallConflict]`),e.multiParty)return;const i=Object.values(this.signalingSessions).find((t=>this.isSessionInConflictingState(t,e)));if(!i)return;let n;if(n=e.isIncomingCall?this.getConflictingSessionToEnd(e,i):this.getConflictingSessionToEnd(i,e),!n)return;const r=n===e?i:e;return this.logger.info("Call conflict done.",` conflictingSession.correlationId=${i.correlationId}`,` conflictingSession.urlIdentifier=${i.urlIdentifier}`,` sessionToEnd.correlationId=${n.correlationId}`,` sessionToEnd.urlIdentifier=${n.urlIdentifier}`),n.telemetryHelper.setConflictingCallId(r.correlationId),n.telemetryHelper.recordEvent("ConflictedCall"),this.signalingAgentConfig.endConflictedCall?(this.endConflictedSession(n,t),n):void 0},this.handleIncomingNotification=e=>{if(Ua(e,"request should be a non null value"),this.logger.info(`handleIncomingNotification to : ${e.url}`),!e.body&&!e.rawBody)return this.logger.error("request has no body"),this.buildNotificationResponse(wa.HTTP_STATUS_CODES.BAD_REQUEST);let t=wa.HTTP_STATUS_CODES.OK;const i=function(e){const t=e.match(new RegExp(`/${function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(wa.URL_BASE.CALLAGENT)}/+([^/]+)`,"i"));return t?t[1]:null}(e.url);if(i){const n=this.signalingSessions.hasOwnProperty(i);if(this.logger.info(`Is session found:${n}`),n){const t=this.signalingSessions[i];if(e.headers=new Pa(e.headers),Za(e.headers))try{if(!Xa(e.headers))throw new Error("Unsupported encoding");const t=eo(e.rawBody),i=JSON.parse(t);e.body=i}catch(e){return t.telemetryHelper.recordEvent("TrouterDecodePayloadFailure"),this.buildNotificationResponse(wa.HTTP_STATUS_CODES.BAD_REQUEST)}if(t.canHandleIncomingMsgSync(e))return t.handleIncomingMsgSync(e);window.setTimeout((()=>{if(this.signalingSessions.hasOwnProperty(i)){const t=this.signalingSessions[i];t.handleIncomingMsgAsync(e).catch((e=>{t&&t.telemetryHelper&&t.telemetryHelper.recordEvent("FailedToHandleTrouterMessage"),this.logger.error(`handling IncomingMsg failed with error: ${e}`)}))}}),0)}else this.logger.info(`Incoming message for session ID ${i}, but session was not found!`),t=wa.HTTP_STATUS_CODES.NOT_FOUND}else this.logger.error(`Could not retrieve session ID from Url path. Path = ${e.url}`),t=wa.HTTP_STATUS_CODES.BAD_REQUEST;const n=this.buildNotificationResponse(t);return this.logger.info(`Result code:${je(n)}`),n},this.onCallCompleted=(e,t)=>{this.signalingSessions.hasOwnProperty(e)?(delete this.signalingSessions[e],this.logger.info(`[${t}][onCallCompleted] Session ID ${e} found. Deleted from signalingSession table`)):this.logger.info(`[${t}][onCallCompleted] Session ID ${e} not found. Could not delete from signalingSession table`)},this.applyAuthTokenCacheConfig=e=>{this.signalingAgentConfig.enableTokenCache?(this.authTokenManager.setTokenCaching(!0,e),this.signalingAgentConfig.enableTokenPrefetch&&this.authTokenManager.getToken(e).then((()=>{this.logger.info(`[${e}] token prefetch success`)})).catch((t=>{this.logger.info(`[${e}] token prefetch failure, error=${je(t)}`)}))):this.authTokenManager.setTokenCaching(!1,e),this.signalingAgentConfig.enableTokenCacheForGenericTokenAPI?this.authTokenManager.setTokenCachingForGenericTokenAPI(!0,e):this.authTokenManager.setTokenCachingForGenericTokenAPI(!1,e)},this.endConflictedSession=(e,t)=>{this.logger.info("Call conflict, ending signalingSession with callId=",e.correlationId,"urlIdentifier=",e.urlIdentifier),e.endAsync({code:wa.CALL_END_CODE.CONFLICT,subCode:wa.CALL_END_SUB_CODE.CONFLICT_IN_NG,phrase:wa.CALL_END_PHRASE.CONFLICT},{forEveryone:!1,causeId:t})},this.getConflictingSessionToEnd=(e,t)=>{if(!ka(e.incomingCallCallerId)||!ka(t.participantManager.localParticipant.id))return;const i=Oa(e.incomingCallCallerId),n=t.participantManager.getParticipantsToInitiateCallWith();if(0===n.length)return;const r=Oa(n[0].id),s=Oa(t.participantManager.localParticipant.id);return r===i?s>i?e:t:void 0},this.isSessionInConflictingState=(e,t)=>{if(!e)return this.logger.info("Call conflict, ignore, session already disposed"),!1;const i=[wa.CALL_STATUS.IDLE,wa.CALL_STATUS.CONNECTING,wa.CALL_STATUS.RINGING];return!e.multiParty&&i.indexOf(e.getCallStatus())>-1&&t.isIncomingCall!==e.isIncomingCall},this.buildNotificationResponse=(e,t)=>this.signalingAgentConfig.supportsSynchronousTrouterResponse?{resultCode:e,responseBody:t}:e,wd(e),this.signalingAgentConfig=e,this.logger=e.logger.createChild("SignalingAgent"),Ua(e,"signalingAgentConfig should be a non null value"),this.logger.info(e.isWebRtcEnabled?"webRTC enabled":"ORTC enabled");const t={aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds};this.authTokenManager=((e,t,i,n)=>new Md(e,t,i,n))(this.logger,e.skypeToken,t,e.telemetryManager),this.applyAuthTokenCacheConfig(Na()),Pa.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateSignalingAgentConfig(e){const t=Na(),i=JSON.stringify(e,((e,t)=>e?String(t):t));this.logger.info(`[${t}] updateSignalingAgentConfig, SignalingAgentConfig: ${i}`),this.logger.info(`[${t}] ecsEtag=${e.ecsEtag}`),wd(e),this.updatedSignalingAgentConfig=e,this.authTokenManager?.updateTokenSettings({aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds}),Pa.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateUrls(e,t,i){this.logger.info(`updateUrls: conversationServiceUrl: ${e}, uploadLogRequestUrl: ${t}, enforceUrls: ${i}`),this.updatedSignalingAgentConfig=this.updatedSignalingAgentConfig||this.signalingAgentConfig,i||!this.updatedSignalingAgentConfig.isConversationServiceUrlFromEcs?this.updatedSignalingAgentConfig.conversationServiceUrl=e||this.updatedSignalingAgentConfig.conversationServiceUrl:this.updatedSignalingAgentConfig.conversationServiceUrl=this.updatedSignalingAgentConfig.conversationServiceUrl||e,i||!this.updatedSignalingAgentConfig.isUploadLogRequestUrlFromEcs?this.updatedSignalingAgentConfig.uploadLogRequestUrl=t||this.updatedSignalingAgentConfig.uploadLogRequestUrl:this.updatedSignalingAgentConfig.uploadLogRequestUrl=this.updatedSignalingAgentConfig.uploadLogRequestUrl||t}update(e){this.logger.info(`update accountConfiguration ${JSON.stringify(e)}`),e&&e.clientSupportsGenericTokenAPI!==this.clientSupportsGenericTokenAPI&&(this.clientSupportsGenericTokenAPI=e.clientSupportsGenericTokenAPI,this.authTokenManager.updateTokenSettings({clientSupportsGenericTokenAPI:this.clientSupportsGenericTokenAPI})),this.accountConfig=e}sendPushAsync(e,t,i,n,r=Na()){const s=new Dd(this.signalingAgentConfig.piiScrubber),a=`sendPush[local participant mri = ${s.scrubMriOrOmit(e)}][recipientList = ${s.scrubMriOrOmit(t)}][headers = ${i})][causeId = ${r}]`;if(!e?.id)return this.logger.info(`${a} Empty localParticipantId`),Promise.reject("invalid localParticipantId");if(!t||0===t.length||t.every((e=>e&&""===e.id)))return this.logger.info(`${a} Empty recipientList`),Promise.reject("invalid recipientList");if(!i)return this.logger.info(`${a} Empty headers`),Promise.reject("invalid headers");if(!n||null===Wa(n))return this.logger.info(`${a} Invalid body.`),Promise.reject("invalid body");const o={...Wa(n),To:Array.from(t,(e=>e.id)),From:e.id},l=new Pa(i);l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CORRELATION_ID)||l.set(wa.HEADERS.CORRELATION_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.MESSAGE_ID)||l.set(wa.HEADERS.MESSAGE_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.PARTICIPANT_ID)||l.set(wa.HEADERS.PARTICIPANT_ID,mi()),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CONTENT_TYPE)||l.set(wa.HEADERS.CONTENT_TYPE,"application/json"),l.hasOwnPropertyCaseInsensitive(wa.HEADERS.CLIENT_USER_AGENT)&&l.set(wa.HEADERS.CLIENT_USER_AGENT,l.get(wa.HEADERS.CLIENT_USER_AGENT)+"/TsCallingVersion=2025.07.01.15/Ovb=8962f6ae8324f6a345d7997ae8f276ff81198956");const c=this.signalingAgentConfig.httpRequestDispatcher.getRequestOptions("POST",l?.getAll(),JSON.stringify(o),3e4);return c.useFetch=this.signalingAgentConfig.enableFetchApi,new Promise(((e,t)=>{this.signalingAgentConfig.httpRequestDispatcher.postAsync(this.signalingAgentConfig.uploadLogRequestUrl||wa.URL_DEFAULTS.UPLOAD_LOG_URL,c).then((()=>{e()})).catch((e=>{t(e)}))}))}getSignalingSession(e){for(const t of Object.keys(this.signalingSessions)){const i=this.signalingSessions[t];if(i.correlationId===e)return i}return null}updateToken(e,t,i,n,r){this.authTokenManager.updateToken(e,t,i,n,r)}setTokenRequiredCallBack(e){this.authTokenManager.setTokenRequiredCallBack(e)}resetAuthTokenManager(){this.setTokenRequiredCallBack(null),this.authTokenManager.setDisableTimerFlag(!0),this.authTokenManager.dispose()}checkConfigChange(e){this.updatedSignalingAgentConfig&&this.updatedSignalingAgentConfig!==this.signalingAgentConfig&&(this.signalingAgentConfig=this.updatedSignalingAgentConfig,this.updatedSignalingAgentConfig=null,this.applyAuthTokenCacheConfig(e))}},ch=/;aliases=.*$/i,dh="8:";function uh(e){return e?e.replace(ch,""):e}function hh(e,t){let i=e;return t&&(i+=";aliases=2:"+t),i}var gh=(e,t)=>t&&void 0!==t.phase&&!!e[t.phase],ph=(e,t)=>t&&void 0!==t.phase&&t.phase===e;function mh(e){const t={},i=e=>{t[e]={status:"Pending"}},n=(e,i)=>{t[e].t=i,delete t[e].status},r=(e,i,n)=>{t[e].status="Failed",t[e].t=i,t[e].reason=je(n)};return{execute:async(s,a)=>{const o=e.createChild(`[phase=${s}]`);i(s),o.info("started");const l=(new Date).getTime();try{const e=await a(),t=+new Date-l;return o.logSuccess(`done, time=${t}`),n(s,t),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${je(e)}`),r(s,i,e),{phase:s,error:e,phases:t}}},executeSync:(s,a)=>{const o=e.createChild(`[phase=${s}]`);o.info("started"),i(s);const l=(new Date).getTime();try{const e=a(),t=+new Date-l;return n(s,t),o.logSuccess(`done, time=${t}`),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${je(e)}`),r(s,i,e),{phase:s,error:e,phases:t}}},getTelemetryData:()=>t}}function fh(e,t){return-1!==t.indexOf(e)}var vh,Sh,yh,Ch={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:[]};(e=>{let t;var i;let n;var r;let s;var a;let o;var l;(i=t=e.VideoEffectType||(e.VideoEffectType={})).Off="off",i.BackgroundBlur="blur",i.BackgroundReplacement="replacement",i.PresenterMode="presenterMode",i.None="none",(r=n=e.PowerPreference||(e.PowerPreference={})).Default="default",r.HighPerformance="high-performance",r.LowPower="low-power",(a=s=e.ProcessorType||(e.ProcessorType={})).Wasm="Wasm",a.Webgl2="Webgl2",(l=o=e.EffectQualityChangeReason||(e.EffectQualityChangeReason={}))[l.ExternalParam=0]="ExternalParam",l[l.Performance=1]="Performance",l[l.RendererSize=2]="RendererSize"})(vh||(vh={})),(e=>{let t;var i;let n;var r;let s;var a;let o;var l;let c;var d;(i=t=e.CallType||(e.CallType={}))[i.P2P=0]="P2P",i[i.Conference=1]="Conference",i[i.PSTN=2]="PSTN",i[i.BroadcastingConf=3]="BroadcastingConf",(r=n=e.AudioUsageMode||(e.AudioUsageMode={}))[r.Default=0]="Default",r[r.LongRangeSpeaker=1]="LongRangeSpeaker",r[r.Auditorium=2]="Auditorium",(a=s=e.AecPerfProfile||(e.AecPerfProfile={}))[a.Normal=0]="Normal",a[a.Soc=1]="Soc",a[a.Mobile=2]="Mobile",a[a.NoisyTimestamps=3]="NoisyTimestamps",(l=o=e.VqeMode||(e.VqeMode={}))[l.Off=0]="Off",l[l.SkypeNS=1]="SkypeNS",l[l.SkypeAEC=2]="SkypeAEC",l[l.SkypeVQE=3]="SkypeVQE",l[l.DeepNS=4]="DeepNS",l[l.DeepVQE=5]="DeepVQE",(d=c=e.AudioEffectType||(e.AudioEffectType={})).Off="Off",d.NoiseSuppressionDeep="Deep NS",d.NoiseSuppressionClassic="Classic NS",d.EchoCancellationClassic="Classic AEC",d.VoiceQualityEnhancementClassic="Classic VQE",d.VoiceQualityEnhancementDeep="Deep VQE"})(Sh||(Sh={})),(e=>{let t;var i;let n;var r;(i=t=e.FrameType||(e.FrameType={}))[i.None=0]="None",i[i.Software=1]="Software",i[i.Hardware=2]="Hardware",(r=n=e.LogLevel||(e.LogLevel={}))[r.Default=0]="Default",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warning=3]="Warning",r[r.Error=4]="Error"})(yh||(yh={}));var Th=Z,Eh=(e=>(e[e.CallStateChanged=0]="CallStateChanged",e[e.TrouterStateChanged=1]="TrouterStateChanged",e[e.MultiPartyModeSet=2]="MultiPartyModeSet",e[e.MediaRetargetSucceeded=3]="MediaRetargetSucceeded",e[e.MediaRetargetFailed=4]="MediaRetargetFailed",e))(Eh||{}),bh=(e=>(e[e.StartModality=0]="StartModality",e[e.StopModality=1]="StopModality",e[e.StreamStateChanged=2]="StreamStateChanged",e[e.NegotiationStateChanged=3]="NegotiationStateChanged",e))(bh||{}),_h=(e=>(e[e.SelectSource=0]="SelectSource",e[e.AttachSource=1]="AttachSource",e[e.DetachSource=2]="DetachSource",e))(_h||{}),Ih=(e=>(e[e.Available=0]="Available",e[e.Subscribe=1]="Subscribe",e[e.Subscribed=2]="Subscribed",e[e.Unsubscribe=3]="Unsubscribe",e[e.Unsubscribed=4]="Unsubscribed",e[e.RenderingStarted=5]="RenderingStarted",e[e.RenderingStopped=6]="RenderingStopped",e))(Ih||{}),wh=class{};wh.agentEnvironmentId="agent_environment_id",wh.correlationId="CorrelationId",wh.participantId="participant_id",wh.displayName="display_name",wh.tenantId="TenantId",wh.userHexCID="UserHexCID",wh.acsResourceId="AcsResourceId",wh.endpointId="endpoint_id",wh.mediaLegId="media_leg_id",wh.webMediaConfigIds="web_media_config_ids",wh.tsCallingVersion="ts_calling_version",wh.rpcSessionId="rpc_session_id";var Ah=class{};Ah.diagnostics="MediaDiagnostic",Ah.qoeStats="QoE",Ah.webrtcSession="webrtc_session",Ah.webrtcSessionInitial="webrtc_session_initial",Ah.realtimeTelemetry="realtimetelemetry",Ah.webrtcMediaSession="webrtc_call_session",Ah.mediaSession="pluginless_modality_session",Ah.callSession="pluginless_call_session";var Ph=class{constructor(e){this.eventName=e,this.ended=!1,this.events=[]}setLocalUserId(e){this.localUserId=e}start(){this.ended||(this.startTime=Date.now())}end(e=0){this.ended||(this.ended=!0,this.resultCode=e)}asStatsRecord(e={}){if((0,Th.isEmpty)(this.events))return null;const t=(0,Th.uniqBy)(this.events,(e=>JSON.stringify(e))).map((e=>{const t={[e.type]:e.timestamp-this.startTime};return(0,Th.isEmpty)(e.data)||(t.data=e.data),t}));return{name:this.eventName,record:(0,Th.assign)({LocalUser:this.localUserId,ResultCode:String(this.resultCode),EventTimestampBag:JSON.stringify({eventStart:this.startTime,events:t})},e)}}add(e){!this.ended&&e.type&&((0,Th.isUndefined)(this.startTime)&&(this.startTime=Date.now()),(0,Th.isUndefined)(e.timestamp)&&(e.timestamp=Date.now()),this.events.push(e))}},Rh=class e extends Ph{constructor(){super(Ah.callSession)}callStateChanged(t){super.add({type:Eh[0],data:e.callStateToString[t]||t})}event(e){super.add({type:Eh[e]})}};Rh.callStateToString={0:"None",1:"Notified",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",6:"Disconnecting",7:"Disconnected",8:"Observing",10:"Lobby"};var Mh=Rh,Dh=class e extends Ph{constructor(t,i){super(Ah.mediaSession),this.mediaType=t,this.mediaDirection=i,this.streamDirection=e.mediaDirectionToStream[this.mediaDirection]}addEvent(e,t){super.add({type:e,data:t})}lifecycle(e){this.addEvent(bh[e])}streamStateChanged(t,i=this.streamDirection){const n=bh[2];this.addEvent(n,{state:e.streamStateToString[t],direction:e.streamDirectionToString[i]})}negotiationStateChanged(t,i,n=this.streamDirection){const r=bh[3];this.addEvent(r,{state:e.negotiationStateToString[t],reason:i})}asStatsRecord(t={}){return super.asStatsRecord((0,Th.assign)({MediaType:e.mediaTypeToString[this.mediaType],Role:e.mediaDirectionToRole[this.mediaDirection]},t))}};Dh.negotiationStateToString={started:"NegotiationStarted",rejected:"NegotiationRejected",completed:"NegotiationCompleted"},Dh.streamStateToString={created:"StreamCreated",started:"StreamStarted",active:"StreamActive",inactive:"StreamInactive",stopped:"StreamStopped",removed:"StreamRemoved",failed:"StreamFailed",cancelled:"StreamCancelled"},Dh.streamDirectionToString={send:"Send",receive:"Receive"},Dh.mediaTypeToString={0:"Audio",1:"Video",2:"ScreenShare",3:"Data"},Dh.mediaDirectionToRole={1:"Receiver",2:"Sender",4:"Bidirectional"},Dh.mediaDirectionToStream={1:"receive",2:"send"};var kh=Dh,Oh=class extends kh{constructor(){super(0,4)}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}},Nh=class extends kh{constructor(e){super(e,2),this.mediaType=e}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}event(e){super.addEvent(_h[e])}},Lh=class extends kh{constructor(e,t){super(e,1),this.mediaType=e,this.remoteParticipantId=t,this.rendererCounter=0}newRendererId(){return this.rendererCounter+=1,String(this.rendererCounter)}event(e,t,i){super.addEvent(Ih[e],(0,Th.isUndefined)(i)?{rendererId:t}:{rendererId:t,sourceId:i})}asStatsRecord(){return super.asStatsRecord({TargetUser:this.remoteParticipantId})}},xh=class{constructor(){this.allStats=[],this.ended=!1}setLocalUserId(e){this.localUserId=e}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(e,t){let i=this.renderingStats[t];return i||(i=this.renderingStats[t]=this.receive(e,t)),i}startCall(){return this.callStats?this.callStats:(this.callStats=new Mh,this.callStats.start(),this.addStats(this.callStats))}endCall(e=0){this.ended=!0,this.call.end(e),this.allStats.forEach((e=>e.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(e){let t;switch(e){case 0:t=this.audioStats=new Oh;break;case 1:t=this.videoStats=new Nh(e);break;case 2:t=this.sharingStats=new Nh(e)}return this.addStats(t)}receive(e,t){const i=new Lh(e,t);return i.start(),this.addStats(i)}buildStatsRecords(){return this.allStats.map((e=>e.asStatsRecord())).filter((e=>!!e))}addStats(e){return this.ended||(this.allStats.push(e),e.setLocalUserId(this.localUserId)),e}},Fh=class e{constructor(){this.startTime=Date.now(),this.localStats=new xh,this.tsCallingVersion="2025.07.01.15"}setRpcSessionId(e){this.rpcSessionId=e}setCallId(e){this.callId=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setParticipantId(e){this.participantId=e}setDisplayName(e){this.displayName=e}setEndpointId(e){this.endpointId=e}setMediaLegId(e){this.mediaLegId=e}setMediaStats(e){this.mediaStats=e}setAcsResourceId(e){this.acsResourceId=e}appendDataChannelInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.DataHandlers=e)}appendSharingControlInfo(e){this.mediaStats?.data&&(this.mediaStats.data.SharingControlEnabled=e?"true":"false")}appendMediaControlPlaneInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.MediaControlPlane=e)}appendTerminationInfo(e,t){this.mediaStats?.data&&(this.mediaStats.data.TerminatedReason=`${e}`,this.mediaStats.data.TerminatedState=`${t}`)}appendPictureInPictureInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.PictureInPicture=e)}appendCallDeviceManagerInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.CallDeviceManager=e)}async buildVDItelemetryReport(e){const{transport:t,rpc:i,rpcRemote:n,transportRemote:r}=await e.getStats(this.startTime);return{CallId:this.callId,ParticipantId:this.participantId,Transport:JSON.stringify(t),Rpc:JSON.stringify(i),Rpc_Remote:JSON.stringify(n),Transport_Remote:JSON.stringify(r)}}buildFromMediaStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,Ah.webrtcSession)]:[]}buildShortCallEvent(e){const t={};return t[wh.correlationId]=this.callId||"",t[wh.participantId]=this.participantId||"",t[wh.displayName]=new Re(this.displayName||"",1),t[wh.tenantId]=this.tenantId||"",t[wh.tsCallingVersion]=this.tsCallingVersion||"",t[wh.rpcSessionId]=this.rpcSessionId||"",t.metrics_TerminationReason_code=new Re(e.data.metrics.TerminationReason_code,0),t.metrics_TerminationReason_subCode=new Re(e.data.metrics.TerminationReason_subCode,0),t.metrics_eventType=new Re(e.eventType,0),[{eventName:Ah.webrtcMediaSession,props:this.buildProps(e.data,null,t)}]}buildMediaTelemetry(){if(!this.mediaStats)return;const e=this.buildEvent(this.mediaStats.data,null).props,t={};return Object.keys(e).forEach((i=>{void 0===e[i].piiKind?t[i]=e[i]:t[i]=e[i].value})),t}buildMidCallTelemetry(e){if(!this.mediaStats)return[];const t=this.buildEvent(this.mediaStats.data,Ah.webrtcSession),i=t.props,n=e.reduce(((e,t)=>(i[t]&&(e[t]=i[t]),e)),{});return[{eventName:t.eventName,props:n}]}buildFromCallSetupStats(e){return"WebRtcMediaStats"===this.mediaStats?.type?(this.mediaStats.data.trouterUrl=e,[this.buildEvent(this.mediaStats.data,Ah.webrtcSessionInitial)]):[]}buildFromLocalStats(){return this.localStats.buildStatsRecords().map((e=>this.buildEvent(e.record,e.name)))}buildEvent(t,i){const n={};return n[wh.agentEnvironmentId]=e.agentEnvironmentId,n[wh.correlationId]=this.callId||"",n[wh.tenantId]=this.tenantId||"",n[wh.userHexCID]=this.userHexCID||"",n[wh.participantId]=this.participantId||"",n[wh.displayName]=new Re(this.displayName||"",1),n[wh.endpointId]=this.endpointId||"",n[wh.mediaLegId]=this.mediaLegId||"",n[wh.webMediaConfigIds]=this.webMediaConfigIds||"",n[wh.tsCallingVersion]=this.tsCallingVersion||"",n[wh.acsResourceId]=this.acsResourceId||"",n[wh.rpcSessionId]=this.rpcSessionId||"",{eventName:i,props:this.buildProps(t,null,n)}}normalizeKey(e){return e.replace(/[^a-zA-Z0-9._]/g,"_")}buildProps(e,t,i){return Object.keys(e).forEach((n=>{const r=this.normalizeKey(n),s=t?`${t}_${r}`:r,a=e[n];if((0,Th.isString)(a))i[s]=this.getPiiAwareValue(n,a);else if((0,Th.isArray)(a)){if(a.length>0){const e=a,t=e.map((e=>e.value)).toString();i[s]=new Re(t,e[0].type)}}else if((0,Th.isObject)(a))if(a.__VALUE__){const e=a;(0,Th.isBoolean)(e.value)&&(e.value=e.value?"true":"false"),i[s]=new Re(e.value,e.type)}else this.buildProps(a,s,i)})),i}getPiiAwareValue(t,i){return e.piiProps.hasOwnProperty(t)?new Re(i,e.piiProps[t]):i}build(){return(0,Th.flatten)([this.buildFromMediaStats(),this.buildFromLocalStats()])}};Fh.agentEnvironmentId=mi(),Fh.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,[wh.displayName]:1};var Uh=Fh,Bh=Z;function Vh(e){return e?$h(e.code,e.subCode):0}function Hh(e,t){const i={clientVersion:e.clientVersion,participantId:e.participantId,endpointId:e.endpointId,endpointType:e.endpointType,endpointMetadata:e.endpointMetadata,originalId:e.originalId,capabilities:e.capabilities,clientEndpointCapabilities:e.clientEndpointCapabilities,mappedTo:e.mappedTo,meetingGroupDetails:e.meetingGroupDetails,endpointMeetingRoles:e.endpointMeetingRoles};return e.mediaStreams&&(i.mediaStreams=e.mediaStreams),e.appliedInteractivityLevel&&(i.appliedInteractivityLevel=e.appliedInteractivityLevel),e.deviceType&&(i.deviceType=e.deviceType),e.streamInformation&&32&t&&(i.streamInformation=e.streamInformation),e.propertyBag&&(i.propertyBag=e.propertyBag),e.negotiationTag&&(i.negotiationTag=e.negotiationTag),i}function $h(e,t=null){if(0===e)switch(t){case 5e3:case 5300:return 44;case 5854:return 55;case 5855:return 56;default:return 1}if(null!==t&&t>=2e5&&t<=299999){const e=t-2e5;return Fs[e]?Fs[e]:0}return null!==t&&t>=4e5&&t<=499999?Us[e]?Us[e]:43:403===e?10005===t?64:5448===t?62:5723===t?66:5354===t?67:5810===t?68:10193===t?70:5724===t?71:8:412===e&&5204===t?63:503===e?800100===t?69:48:500===e?7:413===e?5807===t?73:59:xs[e]?xs[e]:e}function jh(e){if(1===e)return 0;const t=Object.keys(xs).filter((t=>xs[t]===e));if(t.length>=1)for(const i of t){const t=parseInt(i);if(t&&xs[t]===e)return t}return Ds}function Gh(e,t){if(void 0!==t&&3!==t&&1!==t)return{mediaType:e,isDisabled:0===t,label:Od(e)}}function qh(e){if(e.sendMediaModalities)return e;const t={mediaStates:[]};let i=Gh(0,e.audioDirection?e.audioDirection:4);return i&&t.mediaStates.push(i),i=Gh(1,e.withVideo?4:e.videoDirection),i&&t.mediaStates.push(i),i=Gh(2,e.screenshareDirection?e.screenshareDirection:1),i&&t.mediaStates.push(i),e.sendMediaModalities=t,e}function zh(e){const t=function(e){if("mri"===e)return"mri";throw"Unknown RedirectionTargetIdType"}(e.type),i=function(e){switch(e){case"voicemail":return"voicemail";case"default":return"default";default:throw"Unknown RedirectionEndpointType"}}(e.endpointType);return{type:t,id:e.id,endpointType:i}}var Wh=class{constructor(e){this.mediaStateConfiguration=e}isDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!!t&&!!t.isDisabled}return!1}isInactiveOrDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!t||!!t.isDisabled}return!1}isSending(e){return!!this.mediaStateConfiguration?.mediaStates&&!!this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e&&!t.isDisabled))}disableModality(e){this.setModality(e,!0)}enableModality(e){this.setModality(e,!1)}removeModality(e){this.mediaStateConfiguration?.mediaStates&&(0,Bh.remove)(this.mediaStateConfiguration.mediaStates,(t=>t.mediaType===e))}setCallAcceptOptions(e){const t=this.isDisabled(1),i=this.isDisabled(2),n=this.isSending(3);if(e.sendMediaModalities)this.mediaStateConfiguration=e.sendMediaModalities;else{void 0===e.answerMediaType&&(e.answerMediaType=e.withVideo?1:0);const t={mediaStates:[]};switch(e.answerMediaType){case 0:t.mediaStates.push(Gh(0,4));break;case 1:t.mediaStates.push(Gh(0,4)),t.mediaStates.push(Gh(1,4));break;case 2:t.mediaStates.push(Gh(1,0))}this.mediaStateConfiguration=t}t&&this.setModality(1,!0),i&&this.setModality(2,!0),n&&this.setModality(3,!1),e.sendMediaModalities=this.mediaStateConfiguration}setModality(e,t){if(this.mediaStateConfiguration?.mediaStates){const i=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));i?i.isDisabled=t:this.mediaStateConfiguration.mediaStates.push({mediaType:e,isDisabled:t,label:Od(e)})}}};function Kh(e){return e||!1===e||""===e||0===e}function Jh(e){switch(e){case 0:return"Audio";case 1:return"Video";case 2:return"ScreenShare"}throw new Error("MediaType required")}function Yh(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2}throw new Error("MediaType required")}var Qh={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"},Zh={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"},Xh=class{constructor(e,t){this.mediaSession=e,this.signalingSession=t,this.operationNames=Qh,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(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_STARTED),this.mediaSession.processOfferAsync(e,t).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_ENDED),e)))}createAnswerAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_STARTED),this.mediaSession.createAnswerAsync(e,t).then((t=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_ENDED),e||(this.operationNames=Zh),t)))}createOfferAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_STARTED),this.mediaSession.createOfferAsync(e,t).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_ENDED),e)))}processAnswerAsync(e,t,i,n=!1){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_STARTED),this.mediaSession.processAnswerAsync(e,t,i,n).then((()=>{this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_ENDED),this.operationNames=Zh}))}completeNegotiationAsync(e){return this.mediaSession.completeNegotiationAsync(e).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps("NegotiationCompleted"),e)))}sendDtmf(e){return this.mediaSession.sendDtmf?this.mediaSession.sendDtmf(e):Promise.reject("Not Implemented")}reconnectAsync(e,t=!1,i){return this.mediaSession.reconnectAsync(e,t,i)}completeEscalationAsync(e){return this.mediaSession.completeEscalationAsync(e)}rejectEscalationAsync(e,t){return this.mediaSession.rejectEscalationAsync(e,t)}getAcceptedTypes(){return this.mediaSession.getAcceptedTypes()}getLocalMediaTrackId(e){return this.mediaSession.getLocalMediaTrackId?this.mediaSession.getLocalMediaTrackId(e):null}getAudioSenderStats(){return this.mediaSession.getAudioSenderStats()}processNotification(e,t){this.mediaSession.processNotification(e,t)}};function eg(e,t,i){if(void 0===t?.serverMuteVersion||void 0===i?.serverMuteVersion||i.serverMuteVersion>=t.serverMuteVersion)return;const n=i&&i.mediaStreams,r=n&&n.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),s=t&&t.mediaStreams,a=s&&s.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));r&&r.length&&(i.serverMuteVersion=t.serverMuteVersion,r[0].serverMuted=a[0].serverMuted,e.info(`handleServerMutedVersion: patching server muted state in audio streams updated:${JSON.stringify(r[0])} as we encountered stale muteServerVersion. Updated to ${t.serverMuteVersion}`))}function tg(e,t,i,n){if("success"!==i.reason||void 0===t||i.serverMuteVersion<=t.serverMuteVersion)return e.info(`handleMuteUnmuteParticipantInfo: ignoring updating since we encountered invalid state: ${i.reason} serverMuteVersion: ${i.serverMuteVersion}`),!1;const r=t&&t.mediaStreams,s=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));return!!s&&(s[0].serverMuted=n,t.serverMuteVersion=i.serverMuteVersion,e.info(`handleMuteUnmuteParticipantInfo: updating since we encountered valid state serverMuteVersion: ${i.serverMuteVersion} to: ${n} streams: ${s[0].sourceId}`),!0)}var ig=Q;function ng(e,t,i,n){i?.forEach((i=>{e[i]&&(t[i]=n(e[i]))}))}function rg(e){return`id=${ig.pii.Mri(e.id)}, participantId=${e.participantId}`}var sg=Z,ag=r.setImmediate?e=>{r.setImmediate(e)}:e=>{(0,sg.defer)(e)},og=class e{constructor(){this.deferredOperations=new Map,this.deferredOperationsNames=[],this.isRunning=!1}setLogger(e){this._logger=e.createChild("[DeferHandler]")}setDeferToQueueMicrotask(t){t&&r.queueMicrotask?e.defer=e=>r.queueMicrotask(e):e.defer=ag}createDeferRunner(e){const t={};return i=>this.runDeferred(t,i,e)}runDeferredWithoutDedup(e,t){this.runDeferred({},e,t)}runDeferred(t,i,n){this.deferredOperations.has(t)||(this.deferredOperations.set(t,i),n&&this.deferredOperationsNames.push(" "+n),this.isRunning||(this.isRunning=!0,this._startDeferalTime=Date.now(),this.causeId=be(),this._logger?.info(`[${this.causeId}]Deferring operations`),e.defer((()=>{this._timeToRun=Date.now()-this._startDeferalTime,this.deferredOperations.forEach((t=>{e.runWithTryCatch(t)})),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(e){try{e&&e()}catch(e){}}};og.defer=ag;var lg=og,cg=class{};cg.instance=new lg;var dg=Z,ug="sendonly",hg="recvonly",gg="sendrecv",pg="audio",mg="video",fg="applicationsharing-video",vg="audio-teleconferencing",Sg="xapplicationsharing-video",yg=class extends gt{constructor(e,t,i){super(t),this.mediaSession=e,this.isAvailable=!1,this.mediaSessionInitPromise=new Kt,this.currentIsStreaming=!1,e&&this.mediaSessionInitPromise.resolve(),this.id=i,this.logger=t.createChild(`Stream[${this.id}]`)}set isStreaming(e){this.currentIsStreaming=e,this.logger.info(`isStreaming has changed to ${this.currentIsStreaming}`),this.raiseChanged()}get isStreaming(){return this.currentIsStreaming}update({sourceId:e=null,direction:t=hg,participantId:i=null,endpointId:n=null}={},r,s){this.logger.info(`[${r}][update before] sourceId=${e}, direction=${t}, isAvailable=${this.isAvailable}, participantId=${i}, endpointId=${qe(n,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.id=e;const a=t===gg||t===ug;this.isAvailable!==a&&(this.negotiationTag=s?.get(n)),this.isAvailable=a,this.mediaSession?.getSessionConfig().config.streamAvailabilityConsiderModalities&&this.getIsModalityDisabled()&&(this.logger.info(`Disabling current modality, disabled: ${JSON.stringify(this.mediaSession?.getDisabledModalities?.()||"")}`),this.isAvailable=!1),this.participantId=i,this.endpointId=n,this.logger.info(`[${r}][update after] sourceId=${e}, direction=${t}, isAvailable=${this.isAvailable}, participantId=${i}, endpointId=${qe(n,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.raiseChanged()}setMediaSession(e,t){const i=e?.getAllowedModalities?.()||{};this.logger.info(`[${t}][setMediaSession] ${JSON.stringify(i)}`),this.mediaSession=e,e?this.mediaSessionInitPromise.resolve():this.mediaSessionInitPromise.reject(new Error("MediaSession is null"))}isActive(){return this.isAvailable&&this.isStreaming}getIsModalityDisabled(){return!1}},Cg=class extends yg{},Tg=Z,Eg=class extends yg{constructor(e,t,i,n,r,s){super(void 0,e,t),this.configProvider=i,this.streamOptions=n,this.telemetryLogger=r,this.callInfo=s,this.type=2,this.finalTelemetrySent=!1,this.player=new Di(e.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 e=this.player.getSnapshotTelemetryReport(),t={isAvailable:this.isAvailable,isStreaming:this.isStreaming,...e};return(0,Tg.isEqual)(this.lastStreamStats,t)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=t),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,rank:this.rank,...this.lastStreamStats}}stop(){return Promise.resolve(void 0)}async start(e){if(this.logger.info("[start]: Starting UMS stream"),!this.renderer){if(await this.player.configure(this.streamOptions),!(await this.player.loadPlayer(e)).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 e=this.player.getSnapshotTelemetryReport();this.logger.debug(`[sendSnapshotTelemetry] sending snapshot telemetry report: ${JSON.stringify(e)}`);const t={...this.callInfo,...e};this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}sendTelemetry(e){if(this.finalTelemetrySent)return;e&&(this.finalTelemetrySent=!0);const t=this.player.getTelemetryReport();this.logger.debug(`[sendTelemetry] sending telemetry report: ${JSON.stringify(t)}`);const i={...this.callInfo,...t};this.telemetryLogger.sendEvent({eventName:"live_events",props:i})}},bg=class extends gt{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(e){this.renderer.setScalingMode(function(e){switch(e){case 1:return"crop";case 0:return"stretch";default:return"fit"}}(e))}async cameraAutoControl(e){throw new Error("Not implemented")}async getCameraManualControlStates(e){throw new Error("Not implemented")}async setCameraManualControlStates(e){throw new Error("Not implemented")}async enumerateCameraManualControls(){throw new Error("Not implemented")}async isCameraAdvancedControlCapable(){throw new Error("Not implemented")}onVideoSizeChanged(e,t){this.streamSize={width:e,height:t},this.event("videoSizeChanged").raise(e,t),this.raiseChanged()}},_g=class extends bg{constructor(){super(),this.disposed=!1}initialize(e,t,i){this.disposed||this.renderer||(this.renderer=t.createPreviewRenderer(e,i),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t))))}onVideoSizeChanged(e,t){this.isRendering=e>0&&t>0,super.onVideoSizeChanged(e,t)}setVideoMirroring(e){this.renderer.setVideoMirroring(e)}startVideoAsync(){return this.renderer.startVideoAsync()}dispose(){this.disposed=!0,this.renderer&&(this.renderer.dispose(),this.renderer=null)}},Ig=class extends bg{constructor(e,t,i,n,r){super(),this.logger=e,this.target=t,this.rendererStats=n,this.configProvider=r,this.subscriptionActive=!1,this.firstFrameRendered=!1,this.rendererId=n.newRendererId(),this.renderer=i.createRemoteRenderer(t),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t))),this.renderer.on("onVideoStateChanged",(e=>this.onVideoStateChanged(e))),this.renderer.on("onIsRenderingChanged",(e=>this.onIsRenderingChanged(e)))}toString(){return`rvr:${this.rendererId}`}onVideoStateChanged(e){this.rendererStats.streamStateChanged(e.stream)}onVideoSizeChanged(e,t){this.configProvider.config.videoIsRenderingCheck&&this.setIsRendering(e>0&&t>0),super.onVideoSizeChanged(e,t)}setIsRendering(e){this.isRendering!==e&&(this.isRendering=e,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(e){this.setIsRendering(e),this.raiseChanged()}subscribeVideoAsync(e){this.currentVideoStream=e,this.rendererStats.event(1,this.rendererId,e.id);const t=this.renderer.subscribeVideoAsync(e.id,1===e.type);return this.subscriptionActive=!0,t.then((()=>{this.rendererStats.event(2,this.rendererId,e.id),this.watchStream(e)})),t}watchStream(e){this.changeSub&&this.changeSub.dispose(),this.changeSub=e.changed((()=>{e.isAvailable?this.subscriptionActive||this.subscribeVideoAsync(e):(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)}},wg=class extends gt{constructor(e,t,i){super(i),this.getRawStream=e,this.disposeStream=t,this.logger=i,this.isClientDisposed=!1,this.clientId=sn()}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")}},Ag=class{constructor(e,t){this.stream=e,this.rawBaseClient=new wg((async()=>this.stream),(()=>this.dispose()),t)}client(){return this.rawBaseClient}updateAndNotifyClient(e){this.rawBaseClient&&(this.stream=e,this.rawBaseClient.notifyStreamChange())}dispose(){this.rawBaseClient=null,this.stream=null}},Pg=class{constructor(e,t,i){this.videoStream=e,this.subscriptionManager=t,this.logger=i,this.subscriptionActive=!1,this.modality=0===e.type?Gi.MODALITY.video:Gi.MODALITY.sharing,this.createSubscription(),this.rawBaseClient=new wg((async()=>this.subscriptionClient?.subscribedStream),(()=>this.unsubscribeVideo()),i),this.videoStream.changed((()=>{this.rawBaseClient?.isDisposed||(this.logger.info(`isAvailable: ${e.isAvailable}, subscriptionActive: ${this.subscriptionActive}`),e.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()))}},Rg=class{constructor(e){this.logger=e,this.handlerMap=new Map}dispose(){this.logger.info("dispose"),this.handlerMap.forEach((e=>e.client().dispose())),this.handlerMap.clear()}handlerAdded(e){const t=e.client();t.on("clientDisposed",(()=>this.deleteRawStreamManagerById(t.clientId))),this.handlerMap.set(t.clientId,e)}deleteRawStreamManagerById(e){this.handlerMap.delete(e)}},Mg=class extends Rg{constructor(e){super(e)}streamChanged(e){this.handlerMap.forEach((t=>t.updateAndNotifyClient(e)))}createIRawStreamClient(e,t){const i=new Ag(e,this.logger);super.handlerAdded(i);const n=i.client();return this.logger.info(`[${t}] - clientId:${n.clientId}, client created`),n}updateHandlers(e){e.forEach(((e,t)=>{this.handlerMap.has(t)||this.handlerMap.set(t,e)}))}},Dg=class extends Rg{constructor(e){super(e)}createIRawStreamClient(e,t,i){const n=new Pg(e,t,this.logger);super.handlerAdded(n);const r=n.client();return this.logger.info(`[${i}] - clientId:${r.clientId}, client created`),r}},kg=Z,Og=class extends yg{constructor(e,t,i,n){super(e,i,n),this.rendererStats=t,this.rawIncomingVideoStreamManager=new Dg(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 e={isAvailable:this.isAvailable,isStreaming:this.isStreaming};return(0,kg.isEqual)(this.lastStreamStats,e)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=e),{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(e=be()){return this.logger.info(`[${e}] - getRawStream called for incoming video stream`),this.rawIncomingVideoStreamManager.createIRawStreamClient(this,this.mediaSession.getSubscriptionManager(),e)}start(e,t){return this.logger.info(`video start: target=${e}, options=${JSON.stringify(t)}`),this.mediaSessionInitPromise.promise.then((()=>new Ig(this.logger.createChild("RemoteVideoRenderer"),e,this.mediaSession,this.rendererStats,this.mediaSession?.getSessionConfig()))).then((e=>(t&&e.setScalingMode(t.scalingMode),this.logger.info(`subscribeVideoAsync: videoRenderer=${e}, id=${this.id}`),e.subscribeVideoAsync(this).catch((t=>{throw e.dispose(),t})).then((()=>(this.isStreaming=!0,e))))))}update(e,t,i){this.logger.info(`[${t}][update] stream=${JSON.stringify(e)}`);const n=this.isAvailable;super.update(e,t,i),this.isAvailable&&this.isAvailable!==n&&this.rendererStats.event(0)}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().video}},Ng=class extends Og{constructor(e,t,i,n){super(e,t,i,n),this.type=1}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().sharing}},Lg=class e extends gt{constructor(e,t,i,n){super(),this.participantId=e,this.mediaSession=t,this.localStats=i,this.audioSourceIds=[],this.streams={},this.lastUmsStreamId=1;const r=i.receive(1,e),s=i.receive(2,e);this.audio=new Cg(t,n,1);const a=new Og(t,r,n,2),o=new Ng(t,s,n,3),l=this.mediaSession?.getSessionConfig()?.config.participantStreamInitialSubscriptions;l&&(a.changed((()=>this.event("streamChanged").raise())),o.changed((()=>this.event("streamChanged").raise()))),this.streams[0]=[a],this.streams[1]=[o],this.streams[2]=[],this.logger=n.createChild("PluginlessCallStreamManager")}setMediaSession(e,t){this.logger.info(`[${t}][setMediaSession]`),this.mediaSession=e,[[this.audio],this.streams[0],this.streams[1]].forEach((i=>i.forEach((i=>i.setMediaSession(e,t)))))}updateStreams(t,i,n,r){this.logger.info(`[${i}][updateStreams]`);const s=i=>t.filter((e=>i.includes(e.type))).sort(e.compareStreams);let a=s([pg]);0===a.length&&(a=s([vg])),a.length>0&&(this.audioSourceIds=a.map((e=>e.sourceId)));const o=a[0];o&&this.audio.update(o,i),this.updateMediaStreams(s([mg]),0,i,n),r?this.updateMediaStreams(s([fg,Sg]),1,i,n):this.updateMediaStreams(s([fg]),1,i,n)}hasAudioSource(e){return this.audioSourceIds.some((t=>t===e))||this.audio.id===e}useUmsStream(t,i,n,r,s,a){this.logger.info(`[${a}][useUmsStream] Updating ums streams`);const o=this.getUmsInformation(t,r),l=this.streams[2],c=l.filter((t=>!o.some((i=>e.compareUmsStreams(t,i)))));c.forEach((e=>(0,dg.remove)(l,e))),c.length&&this.logger.info(`[${a}][useUmsStream] Removing ${c.length} ums streams`),o.forEach((t=>{let r=l.find((i=>e.compareUmsStreams(i,t)));r||(r=new Eg(this.logger.createChild("UmsStream"),this.lastUmsStreamId++,i,t,s,n),this.logger.info(`[${a}][useUmsStream] Adding ums stream with metadata: ${JSON.stringify(t)}`),l.push(r))}))}getUmsStreamMetadata(e,t){let i=null,n=null;if(i=e.find((function(e){return"MiddleLaneUltraLowLatency"===e.deliveryPipelineType&&t===e.isPrimary})),i){const e=i.urls;if(e&&e.length>0){i.identifier||this.logger.warn(`[getUmsStreamMetadata]: no ums stream identifier found, isPrimary: ${t}`);const r=i.decryptionKey?.id,s=i.decryptionKey?.value;r&&s||this.logger.warn(`[getUmsStreamMetadata]: no valid ums stream decryption key found, isPrimary: ${t}`);const a=i.deliveryPipelineType||void 0;n={url:e[0],streamDeliveryPipeline:a,decryptionKey:r&&s?{id:r,value:s}:null}}else this.logger.info(`[getUmsStreamMetadata]: no ums URLs found, isPrimary: ${t}`)}else this.logger.info(`[getUmsStreamMetadata]: no ums stream information found, isPrimary: ${t}`);return n}getUmsInformation(e,t){const i=[];let n=null,r=null;for(const t in e){const i=e[t].streams;if(i){if(n)this.logger.info(`[getUmsInformation]: primary ums stream already found, skipping finding primary stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!0);e?n=e:this.logger.info(`[getUmsInformation]: no primary ums stream found for participant: ${t}`)}if(r)this.logger.info(`[getUmsInformation]: alternate ums stream already found, skipping finding alternate stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!1);e?r=e:this.logger.info(`[getUmsInformation]: no alternate ums stream found for participant: ${t}`)}}else this.logger.warn(`[getUmsInformation]: no stream information found for participant: ${t}`)}return(n||r)&&i.push({stream:n,altStream:r,threadId:t}),i}static compareStreams(e,t){const i="sendonly"===e.direction||"sendrecv"===e.direction,n="sendonly"===t.direction||"sendrecv"===t.direction;return i&&!n?-1:n&&!i?1:t.sourceId-e.sourceId}static compareUmsStreams(t,i){const n=t.getStreamOptions();return e.compareUmsStreamMetadata(n.stream,i.stream)&&e.compareUmsStreamMetadata(n.altStream,i.altStream)}static compareUmsStreamMetadata(e,t){return!e&&!t||!(!e&&t||e&&!t)&&e.decryptionKey.id===t.decryptionKey.id&&e.decryptionKey.value===t.decryptionKey.value&&e.url===t.url}updateMediaStreams(e,t,i,n){const r=this.streams[t],s=r.filter((t=>!e.some((e=>e.sourceId===t.id))));s.forEach((e=>(0,dg.remove)(r,e))),s.length&&this.logger.info(`[${i}][updateMediaStreams] Removing ${s.length} streams of type ${t}`),e.forEach(((s,a)=>{let o=r.find((e=>e.id===s.sourceId));o||(0===t?o=new Og(this.mediaSession,this.localStats.receive(1,this.participantId),this.logger,s.sourceId):1===t&&(o=new Ng(this.mediaSession,this.localStats.receive(2,this.participantId),this.logger,s.sourceId)),this.logger.info(`[${i}][updateMediaStreams] Adding stream ${s.sourceId} of type ${t}`),r.push(o),o.changed((()=>this.event("streamChanged").raise()))),o.update(s,i,n),o.rank=e.length-a}))}},xg={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]},Fg={0:"Disconnected",1:"Connecting",2:"Ringing",3:"Connected",5:"Connected",4:"Disconnected",7:"Connecting"},Ug=class extends gt{constructor(e,t,i,n,r,s=be(),a=[]){super(i),this.mri=e,this.callTelemetry=r,this.cachedMediaStreams=a,this.state=0,this.voiceLevel=0,this.isServerMuted=!1,this.endpointType="default",this.balanceUpdates={},this._raiseChangeDeferRunner=cg.instance.createDeferRunner("CallParticipant.RaiseChange"),this.filteredParticipantEndpointDetails={},this.recordTelemetryForStateChange=(e,t,i,n)=>{if(n){const n="_SetParticipantStateInvalid",r={state:t,reason:i,endpoints:[]};this.endpoints?.endpointDetails?.length&&(r.endpoints=Er(this.endpoints.endpointDetails)),this.callTelemetry.recordEvent(n,r,e)}},this.checkIfIncomingServerMutedIsUpdated=e=>{e.endpointDetails.forEach((e=>{const t=this.filteredParticipantEndpointDetails[e.participantId];void 0!==t&&eg(this.logger,t,e)}))},this.handleServerMutedInfoUpdate=e=>{let t=!1;for(const i of e){const e=this.filteredParticipantEndpointDetails[i.participantId];tg(this.logger,e,i,!0)&&(t=!0)}t&&this.updateIsServerMuted()},this.id=this.mri,this.logger=i.createChild((()=>`ICallParticipant[${De(this.id)}][${this.state}]`)),this.logger.info(`[${s}]created`),this.streamManager=new Lg(this.id,t,n,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:De(this.id),state:this.state,isServerMuted:this.isServerMuted})}async getDiagnosticDataAsync(){return this.getDiagnosticData()}isSameParticipantsMri(e){return this.id===e}setMediaSession(e,t=be()){this.streamManager.setMediaSession(e,t)}applyCachedMediaStreams(e=be()){const t=this.logger.createFnLogger("applyCachedMediaStreams",e);this.cachedMediaStreams?.length?(t.info("applying cachedMediaStreams"),this.updateStreams(this.cachedMediaStreams,e,!1)):t.info("cachedMediaStreams is empty")}updateStreams(e,t=be(),i=!1,n,r=!1){this.logger.createFnLogger("updateStreams",t).info(`isStreamingMode=${i} mediaStreams=${Ge(e)}`),e?.length&&(this.cachedMediaStreams=e),i||(this.streamManager.updateStreams(e,t,n,r),this.raiseChangedDeferred())}hasAudioSource(e){return this.streamManager.hasAudioSource(e)}raiseChangedDeferred(){this._raiseChangeDeferRunner((()=>this.raiseChanged()))}updateIsServerMuted(){if(!Object.values(this.filteredParticipantEndpointDetails).length)return void this._updateIsServerMuted(!1);let e=!1;Object.values(this.filteredParticipantEndpointDetails).forEach((t=>{const i=e=>t.mediaStreams?.filter((t=>t.type===e)).sort(Lg.compareStreams);let n=i(pg)?.[0];n||(n=i(vg)?.[0]);const r=!!n?.serverMuted,s=t.endpointState?.state;!1!==r||0!=!!s?.isMuted||(e=!0)}));const t=!e;this._updateIsServerMuted(t)}_updateIsServerMuted(e){e!==this.isServerMuted&&(this.isServerMuted=e,this.logger.info(`_updateIsServerMuted updating to: ${this.isServerMuted}`),this.raiseChanged())}updateVoiceLevel(e){this.voiceLevel!==e&&(this.voiceLevel=e,this.raiseChanged())}setState(e,t,i){if(this.state===e)return;const n=this.logger.createFnLogger("setState",i);if(3===this.state&&6===e)return void n.info("Ignore Connected->EarlyMedia transition, it is a race between media and signaling");const r=xg[this.state].indexOf(e)>=0;this.recordTelemetryForStateChange(i,e,t,!r),r?(n.info(`state=${this.state}->${e} reason=${this.stateReason}->${t}`),this.state=e,this.stateReason=t,this.raiseChangedDeferred()):n.logFailure(`Invalid state transition ${this.state}->${e} attempted`)}processParticipantDetails(e,t,i){const n=this.logger.createFnLogger("processParticipantDetails","");this.role=e.role,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.meetingRoles=e.meetingRoles,this.participantType=e.participantType,this.displayName=e.displayName,this.tenantId=e.tenantId,this.propertyBag=e.propertyBag,this.version=e.version,this.otpIdentity=e.otpIdentity,this.isIdentityMasked=!!e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,e.endpointDetails?.length&&(this.endpoints={endpointDetails:[]},this.participantCapabilities={canConference:!1,canShareScreen:!1,canMerge:!0},this.checkIfIncomingServerMutedIsUpdated(e),this.filteredParticipantEndpointDetails={},e.endpointDetails.forEach((e=>{const n=Hh(e,t);if(this.endpoints.endpointDetails.push(n),!n.mappedTo){if(this.filteredParticipantEndpointDetails[e.participantId]={endpointId:e.endpointId,serverMuteVersion:e.serverMuteVersion,endpointState:e.endpointState,mediaStreams:e.mediaStreams},e.capabilities&&(this.participantCapabilities.canConference||"enabled"!==e.capabilities.cloudAudioVideoConference||(this.participantCapabilities.canConference=!0),this.participantCapabilities.canShareScreen||"enabled"!==e.capabilities.cloudScreenSharing||(this.participantCapabilities.canShareScreen=!0),this.participantCapabilities.canMerge||"enabled"!==e.capabilities.cloudMerge||(this.participantCapabilities.canMerge=!0)),this.contentSharingRole=0,e.contentSharing&&e.contentSharing.sessionInformation){const t=e.contentSharing.sessionInformation;"attendee"===t.role?this.contentSharingRole=1:"presenter"===t.role&&(this.contentSharingRole=2)}n.streamInformation&&i&&i()}})),this.updateIsServerMuted(),n.info(`endpointDetails=${Qe(this.endpoints)}`),this.raiseChangedDeferred())}toCafeParticipant(){return{audioState:Fg[this.state],mri:this.mri}}getSourceIdForMediaType(e){const t=Ud(this,e);return-1===t&&this.logger.warn("getSourceIdForMediaType failed"),t}useUmsStream(e,t,i,n,r,s){this.streamManager.useUmsStream(e,t,i,n,r,s),this.raiseChangedDeferred()}hasSourceId(e,t){return void 0!==Bd(this,e,t)}},Bg=class extends gt{constructor(e,t,i,n,r,s="",a,o){super(),this.callTelemetry=e,this.signalingSession=i,this.contentSharingGuid=n,this.contentSharingIdentity=r,this.state=s,this.subject=a,this.handleOperationFailure=(e,t,i)=>{i.logFailure(e);const n=this.getTerminatedReasonFromError(e);return t.updateStatusTo&&(this.contentSharingStatus=t.updateStatusTo,this.rejectContentSharing(n)),Promise.reject(n)},this._logger=t.createChild((()=>`[ContentSharingSession][${this.contentSharingGuid}]`)),this.contentSharingStatus=0,this.contentSharingTerminationReason=null,this.contentSharingState=s,this._callOperationHandler=new as(this._logger,this.callTelemetry),o&&(this.sessionId=o)}get contentSharingStatus(){return this.status}set contentSharingStatus(e){if(this._logger.info(`[set contentSharingStatus][currentStatus=${this.status}][newStatus=${e}]`),this.callTelemetry.recordEvent("_SetContentSharingStatus",{newStatus:e,oldStatus:this.status}),this.status!==e&&7!==this.status&&8!==this.status){if(this._logger.info(`[set contentSharingStatus] Changing content sharing status to: ${e}`),this.status=e,7===this.status){const e={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[set contentSharingStatus] Content sharing is disconnected"};this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(e)}if(2===this.status||5===this.status){const e={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Content sharing cannot be ended when not presenting"};this._callOperationHandler.maybeRejectOperation("StopContentSharing",e)}3===this.status&&(this._callOperationHandler.maybeResolveOperation("StartContentSharing"),this._callOperationHandler.maybeResolveOperation("TakeContentSharingControl")),this.raiseChanged()}}get contentSharingState(){return this.state}set contentSharingState(e){this.state!==e&&(this.state=e,this.raiseChanged())}startContentSharing(e=be()){const t=this._logger.createFnLogger("StartContentSharing",e);if(0!==this.contentSharingStatus){const i=`[${e}][startContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.startContentSharingAsync(this.contentSharingIdentity,this.contentSharingState,this.subject,this.contentSharingGuid,e).then((e=>{this.sessionId=e.sessionId,this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StartContentSharing",updateStatusTo:8},t))),this._callOperationHandler.waitForOperation("StartContentSharing")}joinContentSharing(e=be()){const t=this._logger.createFnLogger("JoinContentSharing",e);if(2!==this.contentSharingStatus){const i=`[${e}][joinContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.joinContentSharingAsync(this.contentSharingGuid,e).then((e=>(this.contentSharingStatus=4,this.contentSharingState=e.sessionState,this.presenterId=e.presenter,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"JoinContentSharing",updateStatusTo:8},t)))}updateContentSharingSessionState(e,t,i=be()){const n=this._logger.createFnLogger("UpdateContentSharingSessionState",i);if(3!==this.contentSharingStatus){const e=`[${i}][updateContentSharingSessionState][failed][reason=InvalidState]`,t={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:e};return n.logFailure(`state=${this.contentSharingStatus}, reason=${e}`),Promise.reject(t)}return this.signalingSession.updateContentSharingSessionStateAsync(this.contentSharingGuid,t,i).then((()=>Promise.resolve())).catch((t=>this.handleOperationFailure(t,{causeId:i,operation:"UpdateContentSharingSessionState",operationId:e},n)))}takeContentSharingControl(e=be()){const t=this._logger.createFnLogger("TakeContentSharingControl",e);if(5!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.takeContentSharingControlAsync(this.contentSharingGuid,e).then((()=>{this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"TakeContentSharingControl"},t))),this._callOperationHandler.waitForOperation("TakeContentSharingControl")}updateContentSharingParticipantStateToViewer(e=be()){const t=this._logger.createFnLogger("UpdateParticipantState",e);if(4!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.updateContentSharingParticipantStateAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=this.presenterId===this.signalingSession.participantManager.localParticipant.id?3:5,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"UpdateParticipantState"},t)))}stopContentSharing(e=be()){const t=this._logger.createFnLogger("StopContentSharing",e);if(2===this.contentSharingStatus||4===this.contentSharingStatus||5===this.contentSharingStatus){const i=`[${e}][stopContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.deleteContentSharingAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=7,this._callOperationHandler.waitForOperation("StopContentSharing")))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StopContentSharing"},t)))}dispose(e=be()){this._callOperationHandler.rejectPendingOperations({terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Call ended"},e),this.contentSharingStatus=7,this.contentSharingState="",super.dispose()}rejectContentSharing(e={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(e)}getTerminatedReasonFromError(e){const t=e?.endCode?.code||0,i={terminatedReason:32,terminatedReasonCode:t,terminatedReasonSubCode:e?.endCode?.subCode||0,errorMessage:e};switch(t){case 404:i.terminatedReason=34,i.errorMessage="Active session not found on server";break;case 403:i.terminatedReason=8,i.errorMessage="Failed due to insufficient permissions"}return i}};m([Gr("StartContentSharing"),f(0,Wr)],Bg.prototype,"startContentSharing",1),m([Gr("JoinContentSharing"),f(0,Wr)],Bg.prototype,"joinContentSharing",1),m([Gr("UpdateContentSharingSessionState"),f(0,zr),f(2,Wr)],Bg.prototype,"updateContentSharingSessionState",1),m([Gr("TakeContentSharingControl"),f(0,Wr)],Bg.prototype,"takeContentSharingControl",1),m([Gr("UpdateParticipantState"),f(0,Wr)],Bg.prototype,"updateContentSharingParticipantStateToViewer",1),m([Gr("StopContentSharing",{waitFor:"StartContentSharing"}),f(0,Wr)],Bg.prototype,"stopContentSharing",1);var Vg,Hg=class{constructor(e){this.value=e,this.next=void 0}},$g=class{constructor(){this.length=0}enqueue(e){const t=new Hg(e);this.front?(this.rear.next=t,this.rear=t):(this.front=t,this.rear=t),this.length++}dequeue(){if(!this.front)return;const e=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,e.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}},jg=Z,Gg=class{constructor(e){this.comparator=e,this.heap=[]}enqueue(e){this.heap.push(e),this.bubbleUp()}dequeue(){const e=this.peek();if(void 0!==e){const e=this.heap.pop();this.size()>0&&(this.heap[0]=e,this.bubbleDown())}return e}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(){let e=this.size()-1,t=this.getParentIndex(e);for(;!this.isRoot(e)&&this.comparator(this.heap[e],this.heap[t]);)[this.heap[t],this.heap[e]]=[this.heap[e],this.heap[t]],e=t,t=this.getParentIndex(e)}bubbleDown(){if(this.size()<=1)return;let e=this.getRootIndex(),t=this.getLeftIndex(e),i=this.getRightIndex(e);for(;this.heap[t]&&this.comparator(this.heap[t],this.heap[e])||this.heap[i]&&this.comparator(this.heap[i],this.heap[e]);)!this.heap[i]||this.comparator(this.heap[t],this.heap[i])?([this.heap[e],this.heap[t]]=[this.heap[t],this.heap[e]],e=t):([this.heap[e],this.heap[i]]=[this.heap[i],this.heap[e]],e=i),t=this.getLeftIndex(e),i=this.getRightIndex(e)}getRootIndex(){return 0}isRoot(e){return 0===e}getLeftIndex(e){return 2*e+1}getRightIndex(e){return 2*e+2}getParentIndex(e){return Math.floor((e-1)/2)}},qg=class{constructor(e,t,i){this.maxPacketRate=t,this.rateLimiterCheckInterval=i,this.maxDataRate=0,this.packetsEndTimeForPacketRate=0,this.packetsEndTimeForBitrate=0,this.maxDataRate=e/8}canSend(e){if(0===this.maxDataRate&&0===this.maxPacketRate)return!0;const t=_n();if(this.maxPacketRate&&this.packetsEndTimeForPacketRate>t+this.rateLimiterCheckInterval)return!1;if(this.maxDataRate&&this.packetsEndTimeForBitrate>t+this.rateLimiterCheckInterval)return!1;const i=this.maxPacketRate?1e3/this.maxPacketRate:0,n=this.maxDataRate?e.length/this.maxDataRate*1e3:0;return this.packetsEndTimeForPacketRate=Math.max(this.packetsEndTimeForPacketRate,t)+i,this.packetsEndTimeForBitrate=Math.max(this.packetsEndTimeForBitrate,t)+n,!0}},zg=class{constructor(e){this.dataIds=new Map,this.maxBitrate=e.config.webrtcDataChannel.maxBitrate,this.maxPacketRate=e.config.webrtcDataChannel.maxPacketRate,this.maxQueueSize=e.config.webrtcDataChannel.maxQueueSize,e.config.webrtcDataChannel.dataIds.forEach((e=>{this.dataIds.set(e.dataId,e)}))}getMaxBitrate(e){return this.dataIds.get(e)?.maxBitrate??this.maxBitrate}getMaxPacketRate(e){return this.dataIds.get(e)?.maxPacketRate??this.maxPacketRate}getMaxQueueSize(e){return this.dataIds.get(e)?.maxQueueSize??this.maxQueueSize}getConfig(e){const t=this.dataIds.get(e)||{dataId:e};return t.maxBitrate=t.maxBitrate??this.maxBitrate,t.maxPacketRate=t.maxPacketRate??this.maxPacketRate,t.maxQueueSize=t.maxQueueSize??this.maxQueueSize,t.priorityWeight=t.priorityWeight??1,t}},Wg=class{constructor(e,t,i){this.dataIdConfig=t,this.rateLimiterCheckInterval=i,this.timeOffset=0,this.packets=new $g,this.startTime=e(),this.finishTime=this.startTime,this.rateLimiter=new qg(t.maxBitrate,t.maxPacketRate,this.rateLimiterCheckInterval),this.getCurrentTime=e,this.stats={bufferSize:t.maxQueueSize,remainingBytes:0,remainingPackets:0}}enqueue(e){if(0===e.length)return 0;const t=(0,jg.sumBy)(e,(e=>e.length)),i=this.dataIdConfig.maxQueueSize;if(i&&this.stats.remainingBytes+t>i)throw new Error(`dataId ${this.dataIdConfig.dataId} send queue is full`);const n=this.getCurrentTime();let r=0;return 0===this.packets.size()?(this.startTime=n,this.finishTime=n,this.timeOffset=0,r=n):r=this.finishTime,e.forEach((e=>{r+=e.length*this.dataIdConfig.priorityWeight,this.packets.enqueue({finishTime:r,packet:e}),this.stats.remainingBytes+=e.length,this.stats.remainingPackets++})),this.finishTime=r,t}dequeue(){const e=this.peek();if(void 0!==e){if(!this.rateLimiter.canSend(e.packet))return;this.packets.dequeue(),this.stats.remainingBytes-=e.packet.length,this.stats.remainingPackets--}return e}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 e=this.packets.peek();return{finishTime:e.finishTime+this.timeOffset,packet:e.packet}}getConfig(){return this.dataIdConfig}getStats(){return(0,jg.clone)(this.stats)}},Kg=class{constructor(e){this.senders=new Map,this.currentVirtualClock=0,this.dataIdConfigManager=new zg(e),this.virtualTimeQueue=new Gg(((e,t)=>e.minTime<t.minTime)),this.sendStats={bufferSize:0,remainingBytes:0,remainingPackets:0},this.rateLimiterCheckInterval=e.config.webrtcDataChannel.rateLimiterCheckInterval}getPacketsToSend(e){if(0===this.virtualTimeQueue.size())return[];const t=[],i=[];for(;e>=0&&this.virtualTimeQueue.size();){const n=this.virtualTimeQueue.peek();if(n.size>e)break;this.virtualTimeQueue.dequeue();const r=n.dataId,s=this.senders.get(r);if(void 0!==s.peek()){const n=s.dequeue();if(void 0!==n){t.push(n.packet),this.sendStats.remainingBytes-=n.packet.length,e-=n.packet.length,this.sendStats.remainingPackets--,this.currentVirtualClock=Math.max(this.currentVirtualClock,n.finishTime);const i=s.peek();i&&this.virtualTimeQueue.enqueue({dataId:r,minTime:i.finishTime,size:i.packet.length})}else i.push(r)}}return i.forEach((e=>{const t=this.senders.get(e);t.updateTimeOffset();const i=t.peek();i&&this.virtualTimeQueue.enqueue({dataId:e,minTime:i.finishTime,size:i.packet.length})})),t}appendPackets(e,t){let i=this.senders.get(e);void 0===i&&(i=new Wg((()=>this.currentVirtualClock),this.dataIdConfigManager.getConfig(e),this.rateLimiterCheckInterval),this.senders.set(e,i));const n=i.getStats(),r=i.enqueue(t);if(this.sendStats.remainingBytes+=r,this.sendStats.remainingPackets+=t.length,0===n.remainingPackets){const t=i.peek();void 0!==t&&this.virtualTimeQueue.enqueue({dataId:e,minTime:t.finishTime,size:t.packet.length})}}getStats(e){if(void 0===e)return(0,jg.clone)(this.sendStats);const t=this.senders.get(e);return void 0===t?{bufferSize:this.dataIdConfigManager.getMaxQueueSize(e),remainingBytes:0,remainingPackets:0}:t.getStats()}},Jg=class{constructor(e){this.data={protocolCounters:{},id:void 0,label:void 0,ordered:void 0,negotiated:void 0},this.data.id=e.id,this.data.label=e.label,this.data.ordered=e.ordered,this.data.negotiated=e.negotiated,this.data.protocol=e.protocol||void 0,this.data.maxPacketLifeTime=e.maxPacketLifeTime??void 0,this.data.maxRetransmits=e.maxRetransmits??void 0}recordProtocolEvent(e,t,i){this.data.protocolCounters[i]||(this.data.protocolCounters[i]={});const n=this.data.protocolCounters[i];switch(n[e]||(n[e]={successful:0,failed:0,fragmented:0,dismissed:0}),t){case 0:n[e].successful++;break;case 1:n[e].failed++;break;case 2:n[e].fragmented++;break;case 3:n[e].dismissed++}}recordError(e){this.data.error=e}getObjectRef(){return this.data}},Yg=class{constructor(e,t,i){this.dataId=e,this.diagnostics=t,this.logger=i,this.pendingFragments=[]}depacketize(e){const t=new DataView(e.buffer),i=63&t.getUint8(2);if(i!==this.dataId)throw new Error(`Invalid packet dataId: ${this.dataId} !== ${i}`);const n=((15&t.getUint8(0))<<8)+t.getUint8(1),r=128&t.getUint8(2),s=t.getUint16(3),a=t.getUint8(5),o=t.getUint32(6),l=t.getUint8(10);if(r){this.pendingFragments.length&&this.logger.warn(`Unfinished message: dataId: ${this.dataId} seqNum: ${s}`),this.remainingPackets=a,0!==a&&this.diagnostics.recordProtocolEvent("recv",2,i),this.pendingFragments=[],this.sourceId=o,this.recipients=[];for(let e=0;e<l;e++){const i=t.getUint32(11+4*e);this.recipients.push(i)}}else{if(0===this.pendingFragments.length)return this.logger.safe.error(`No start flag dataId: ${this.dataId} seqNum: ${s}`),this.diagnostics.recordProtocolEvent("recv",3,i),null;if(this.nextSeqNum!==s)return this.logger.safe.error(`Invalid sequence number: dataId: ${this.dataId} seqNum: ${s}`),this.diagnostics.recordProtocolEvent("recv",3,i),null;this.remainingPackets-=1}if(this.nextSeqNum=s+1&65535,this.pendingFragments.push(e.slice(n)),0===this.remainingPackets){const e=this.pendingFragments.reduce(((e,t)=>e+t.length),0),t=new Uint8Array(e);let i=0;for(const e of this.pendingFragments)t.set(e,i),i+=e.length;return this.pendingFragments=[],{dataId:this.dataId,sourceId:this.sourceId,data:t,recipients:this.recipients}}return null}},Qg=class{constructor(e){this.dataId=e,this.seqNum=0}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=new Uint8Array(e.data.length+t),n=new DataView(i.buffer);n.setUint8(0,16+(t>>8)),n.setUint8(1,255&t),n.setUint8(2,128|63&e.dataId),n.setUint16(3,this.seqNum),n.setUint8(5,0),n.setUint32(6,e.sourceId),n.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)n.setUint32(11+4*t,e.recipients[t]);return i.set(e.data,t),this.seqNum+=1,[i]}},Zg=class{constructor(e,t,i){this.dataId=e,this.fragmentationSize=t,this.diagnostics=i,this.seqNum=0}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=[],n=this.fragmentationSize-t;if(n<0)throw new Error(`message dataId: ${this.dataId} payload size: ${t} exceeds limit`);let r=e.data.length?Math.ceil(e.data.length/n):1;const s=r-1;s>0&&this.diagnostics.recordProtocolEvent("send",2,this.dataId);let a=e.data.length,o=!0,l=0;for(;r>0;){const c=Math.min(a,n),d=new Uint8Array(c+t),u=new DataView(d.buffer);u.setUint8(0,16+(t>>8)),u.setUint8(1,255&t),o?(o=!1,u.setUint8(2,128|63&e.dataId)):u.setUint8(2,63&e.dataId),u.setUint16(3,this.seqNum),u.setUint8(5,s),u.setUint32(6,e.sourceId),u.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)u.setUint32(11+4*t,e.recipients[t]);d.set(e.data.slice(l,l+c),t),l+=c,i.push(d),this.seqNum+=1,r-=1,a-=c}return i}},Xg=class extends Vi{constructor(e,t,i,n){super(),this.dataChannel=e,this.sessionDiagnostics=t,this.stateInternal="Created",this.packetizers=new Map,this.depacketizers=new Map,this.sendScheduleTimer=0,this.pendingPackets=new $g,this.sourceIdInternal=Ur,this.label=e.label,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(e),this.logger=i.createChild(`[WebRtcDataChannel ${this.label}]`),this.logger.safe.info(`Created with settings ${tt(this.getDataChannelSettings(e))}`),this.bufferedAmountLowThreshold=n.config.webrtcDataChannel.bufferedAmountLowThreshold,this.bufferedAmountHighThreshold=n.config.webrtcDataChannel.bufferedAmountHighThreshold,this.fragmentationSize=n.config.webrtcDataChannel.enableFragmentation?n.config.webrtcDataChannel.fragmentationSize:0,n.config.webrtcDataChannel.enableSendScheduler&&(this.sendScheduler=new Kg(n)),this.rateLimiterCheckInterval=n.config.webrtcDataChannel.rateLimiterCheckInterval,this.discardOnSendFailure=n.config.webrtcDataChannel.discardOnSendFailure,this.subscribeOnDataChannelEvents()}getDataIdStats(e){return this.sendScheduler?.getStats(e)}get state(){return this.stateInternal}set sourceId(e){this.sourceIdInternal=e}setDataChannel(e){this.dataChannel&&(this.logger.info(`Replacing internal data channel ${this.label}:${this.dataChannel.id} with ${e.label}:${e.id} with settings ${tt(this.getDataChannelSettings(e))}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close()),this.dataChannel=e,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(e),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(e,t=this.sourceIdInternal,i,n=[]){try{this.packetizers.has(e)||(this.fragmentationSize?this.packetizers.set(e,new Zg(e,this.fragmentationSize,this.diagnostics)):this.packetizers.set(e,new Qg(e)));const r=this.packetizers.get(e).packetize({dataId:e,sourceId:t,data:i,recipients:n});void 0!==this.sendScheduler?(this.sendScheduler.appendPackets(e,r),this.scheduleSend()):r.forEach((e=>{this.dataChannel.send(e)})),this.diagnostics.recordProtocolEvent("send",0,e)}catch(t){throw this.logger.unsafe.warn(`Failed to construct protocol message: ${tt(t)}`),this.diagnostics.recordProtocolEvent("send",1,e),t}}scheduleSend(){if("Connected"!==this.state)return;const e=e=>{try{this.dataChannel.send(e)}catch(e){return this.logger.unsafe.warn(`Failed to send message: ${tt(e)}`),!1}return!0};if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){const t=Date.now();let i=this.bufferedAmountHighThreshold-this.dataChannel.bufferedAmount;for(;this.pendingPackets.size();){const t=this.pendingPackets.peek();if(t.length>i)break;if(!e(t))break;this.pendingPackets.dequeue(),i-=t.length}if(0===this.pendingPackets.size()&&i>0){const t=this.sendScheduler.getPacketsToSend(i);for(const i of t)if(!1===e(i)&&!1===this.discardOnSendFailure){this.pendingPackets.enqueue(i);break}}if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){if(this.sendScheduleTimer)return;if(this.sendScheduler.getStats().remainingPackets>0){const e=Math.max(t+this.rateLimiterCheckInterval-Date.now(),20);this.sendScheduleTimer=window.setTimeout((()=>{this.sendScheduleTimer=0,this.scheduleSend()}),e)}}}}subscribeOnDataChannelEvents(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=e=>{const t=new Uint8Array(e.data),i=63&t[2];try{this.depacketizers.has(i)||this.depacketizers.set(i,new Yg(i,this.diagnostics,this.logger));const e=this.depacketizers.get(i).depacketize(t);e&&(this.diagnostics.recordProtocolEvent("recv",0,i),this.event("onmessage").raise(i,e.sourceId,e.data))}catch(e){this.logger.unsafe.warn(`Failed to parse incoming message: ${tt(e)}`),this.diagnostics.recordProtocolEvent("recv",1,i)}},this.dataChannel.onerror=e=>{const t=e?.target,i=tt(e?.error??e);this.logger.safe.warn(`onerror: label:${t.label} id:${t.id} ${i} `),this.diagnostics.recordError(i)},"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=e=>{const t=e.target;this.logger.safe.info(`onopen label:${t.label} id:${t.id}`),t.id%2==0&&this.setState("Connected")},this.dataChannel.onclose=e=>{const t=e.target;this.logger.safe.info(`onclose label:${t.label} id:${t.id}`),this.setState("Closed")},this.dataChannel.onclosing=e=>{const t=e.target;this.logger.safe.debug(`onclosing label:${t.label} id:${t.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(e){this.stateInternal=e,this.event("onStateChanged").raise(),"Connected"===e&&void 0!==this.sendScheduler&&this.scheduleSend()}getDataChannelSettings(e){return{ordered:e.ordered,maxRetransmits:e.maxRetransmits,maxPacketLifeTime:e.maxPacketLifeTime}}},ep=class extends Vi{constructor(e,t,i,n){const r=i.createChild("PluginlessDataChannel");super(r),this.pc=e,this.diagnostics=t,this.configProvider=n,this._state="Inactive",this.logger=r,this.subscribeOnDatachannel()}get state(){return this._state}getDataChannel(e){if(!this.dataChannel){this.logger.safe.info(`[${e}] creating new dataChannel`);try{const e=this.configProvider.config.dataChannelDebugInitSettings||{};this.dataChannel=new Xg(this.pc.createDataChannel("main-channel",e),this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()}catch(t){const i=tt(t);return this.logger.safe.error(`[${e}] createDataChannel failed: ${i}`),this.diagnostics.createChannelFailReason=i,this.setState("Failed"),null}}return this.dataChannel}updateDataModalityState(e){"Failed"!==this._state&&"Disabled"!==this._state&&(e===Gi.MEDIA_STATE.sendReceive?this.setState("Active"):e===Gi.MEDIA_STATE.inactive&&this.setState("Inactive"))}disable(){this.setState("Disabled")}dispose(){this.stopDataChannel(),this.pc=null,super.dispose()}subscribeOnDatachannel(){this.pc.ondatachannel=e=>{this.onDataChannel(e.channel)}}onDataChannel(e){this.logger.safe.info(`onDataChannel id=${e.id} label=${e.label}`),e.id%2==0?this.dataChannel?(this.logger.safe.info("Found existing data channel, replacing"),this.dataChannel.setDataChannel(e)):(this.dataChannel=new Xg(e,this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()):this.logger.safe.info(`onDataChannel ignoring id ${e.id}`)}subscribeForDataChannelEvents(){this.dataChannel.on("onStateChanged",(()=>{"Closed"===this.dataChannel.state&&(this.stopDataChannel(),this.setState("Inactive"))}))}setState(e){if(this._state!==e){this.diagnostics.dataChannelSessionState=e;const t=be();this._state=e,this.logger.safe.info(`[${t}] SessionDataChannelState changed, state=${this._state}`),"Inactive"===this._state||"Disabled"===this._state?this.stopDataChannel():"Active"===this._state&&this.getDataChannel(t),this.event("onStateChanged").raise(this._state)}}stopDataChannel(){this.dataChannel&&(this.logger.safe.info("stopDataChannel"),this.dataChannel.dispose(),this.dataChannel=null)}},tp=class extends gt{constructor(e){super(),this.mainChannel=null,this.sourceId=Ur,this._state="Inactive",this.dataHandlers=new Map,this.dataHandlerTelemetry=new Map,this.startTime=Date.now(),this.sendMessage=async(e,t,i)=>{if(!this.mainChannel||"Connected"!==this.mainChannel.state||"Active"!==this.state)throw new Error("No active data channel to send data from");this.mainChannel.sendMessage(e,this.sourceId,t,i)},this.logger=e.createChild("PluginlessDataChannel")}get state(){return this._state}registerSessionDataChannel(e,t){this.sessionDataChannel&&this.stop(t),this.sessionDataChannel=e,this.subscribeForSessionDataChannelEvents()}setDataChannelSourceId(e){this.logger.debug(`setDataChannelSourceId ${e}`),this.mainChannel&&(this.mainChannel.sourceId=e),this.sourceId=e}requestDataChannelHandler(e){return this.sessionDataChannel.getDataChannel(e)}async sendUserEvents(e,t){if(!this.mainChannel)throw this.logger.info("sendUserEvents() no data channel available"),new Error("Main DataChannel is not active");{const i=t?t.map((e=>parseInt(e,10))):[];this.mainChannel.sendMessage(0,this.sourceId,(new TextEncoder).encode(e),i)}}async addHandler(e,t){if(this.logger.info(`Adding handler with dataId ${e}`),this.dataHandlers.get(e))throw new Error(`Data Id ${e} is already registered`);const i={isStarted:!1,handler:t};this.dataHandlers.set(e,i),this.recordDataHandlerEvent(e,"added"),"Connected"===this.mainChannel?.state&&this.startHandler(e,i)}async removeHandler(e){if(this.logger.info(`Removing handler with dataId ${e}`),!this.dataHandlers.has(e))throw new Error(`Handler associated with Data Id ${e} is not attached`);const t=this.dataHandlers.get(e);t.isStarted&&this.stopHandler(e,t),this.dataHandlers.delete(e)}async updateNegotiationTag(e){}getTelemetry(){if(!this.dataHandlerTelemetry.size)return"";const e={};for(const[t,i]of this.dataHandlerTelemetry)e[t]=i;return JSON.stringify(e)}start(e){this.mainChannel?this.logger.info(`[${e}] already started`):(this.logger.info(`[${e}] starting`),this.mainChannel=this.sessionDataChannel.getDataChannel(e),this.subscribeForMainDataChannelEvents())}stop(e){this.mainChannel&&(this.logger.info(`[${e}] stopping`),this.mainChannel.dispose(),this.mainChannel=null)}dispose(){this.stop(void 0),this.sessionDataChannel=null,super.dispose()}setConfigProviderView(e){this.configProviderView=e}subscribeForMainDataChannelEvents(){this.mainChannel.on("onmessage",((e,t,i)=>{this.dataHandlers.has(e)&&(this.recordDataHandlerEvent(e,"recvd"),this.dataHandlers.get(e).handler.onDataReceived(e,i,t)),this.event("remoteUserEventsReceived").raise(e.toString(),(new TextDecoder).decode(i))})),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[e,t]of this.dataHandlers.entries())t.isStarted||this.startHandler(e,t)}stopHandlers(){for(const[e,t]of this.dataHandlers.entries())t.isStarted&&this.stopHandler(e,t)}startHandler(e,t){this.logger.info(`Starting dataHandler id: ${e}`),t.handler.onStarted(e,((t,i)=>(this.recordDataHandlerEvent(e,"sent"),this.sendMessage(e,t,i))),(()=>{const t=this.mainChannel?.getDataIdStats(e);if(void 0!==t){const e={bufferSize:t.bufferSize,remainingBytes:t.remainingBytes,remainingPackets:t.remainingPackets};return Promise.resolve(e)}return Promise.reject(new Error(`Stats of dataId ${e} is not available`))})),t.isStarted=!0,this.recordDataHandlerEvent(e,"started")}stopHandler(e,t){this.logger.info(`Stopping dataHandler id: ${e}`),t.handler.onStopped(e),t.isStarted=!1,this.recordDataHandlerEvent(e,"removed")}subscribeForSessionDataChannelEvents(){this.sessionDataChannel.on("onStateChanged",(e=>{const t=be();switch(e){case"Active":this.start(t),this.setState("Active");break;case"Inactive":this.stop(t),this.setState("Inactive");break;case"Failed":this.stop(t),this.setState("Failed");break;case"Disabled":this.stop(t),this.setState("Disabled");break;default:this.logger.warn(`[${t}] unhandled SessionDataChannelState ${e}`)}}))}recordDataHandlerEvent(e,t){this.dataHandlerTelemetry.has(e)||this.dataHandlerTelemetry.set(e,[{}]);const i=this.dataHandlerTelemetry.get(e);let n=i[i.length-1];if("added"===t&&void 0!==n.added){n={},i.push(n);const e=this.configProviderView?.config.maxStoredDataChannelValues??15;i.length>e&&i.shift()}switch(t){case"added":case"started":case"removed":n[t]=Date.now()-this.startTime;break;case"recvd":case"sent":n[t]=isNaN(n[t])?1:n[t]+1}}setState(e){this._state!==e&&(this._state=e,this.logger.info(`PluginlessDataChannelState changed, state=${this._state}`),this.event("onDataChannelStateUpdated").raise(this._state))}},ip=p(pe());(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,s=(e.buttonDown?1:0)<<5,a=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|s|a),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,s=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|s),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(Vg||(Vg={}));var np=Z,rp=Q,sp=1e4,ap="",op=class extends yr{constructor(e,t,i,n,r,s,a,o,l){super(e,n,(()=>this.recordedEvents.length>100)),this.auditLogger=t,this.config=i,this.negotiationTag=r,this.callId=s,this.participantId=a,this.endpointId=o,this.dataSourceId=l,this.messagesFromUnknownSender={},this.tsCallingVersion="2025.07.01.15"}setCallId(e){this.callId=e}setParticipantId(e){this.participantId=e}setDataSourceId(e){this.dataSourceId=e}callStateChanged(e){this.recordEvent("CallState",{state:e})}dataChannelAvailable(e){e?this.recordEvent("DataChannelAvailable"):this.recordEvent("DataChannelUnavailable")}shutdownSession(e){this.negotiationTag&&this.negotiationTag!==e?this.recordEvent("ShutdownByOtherSession",null,e):this.recordEvent("Shutdown")}recordProtocolMessage(e,t){e||(t in this.messagesFromUnknownSender||(this.messagesFromUnknownSender[t]=0),this.messagesFromUnknownSender[t]++)}sendAuditEvent(e,t,i,n,r){if(!this.auditLogger)return void this.logger.warn("AuditLogger is not set");const s=e=>e??"",a={TenantId:s(this.tenantId),CorrelationId:s(this.callId),ParticipantId:s(this.participantId),EndpointId:s(this.endpointId),TsCallingVersion:s(this.tsCallingVersion),sharingNegotiationTag:s(this.negotiationTag),timestamp:Date.now(),eventType:t,role:mp(this.role),initiator:mp(i),controlCauseId:e,viewerParticipantId:s(r.participantId),viewerEndpointId:s(r.endpointId),viewerDataSourceId:s(r.dataSourceId),sharerParticipantId:s(n.participantId),sharerEndpointId:s(n.endpointId),sharerDataSourceId:s(n.dataSourceId)};try{this.auditLogger.sendEvent({eventName:"mdsc_gtc_audit",props:a})}catch(e){this.logger.error("Failed to send audit event",e)}}},lp=class extends op{constructor(e,t,i,n,r,s,a,o,l,c){super(e,t,i,n,r,s,a,o,l),this.role=2;const d=Hd(c);if(d){this.sharerParticipantId=d;const e=(0,np.find)(c.endpoints.endpointDetails,(e=>e.participantId===d));e&&(this.sharerEndpointId=e.endpointId,this.sharerClientVersion=e.clientVersion)}}startHandshake(e){this.recordOperation("AvailableHandshake",e)}delayHandshakeSending(e,t,i){const n={delay:t,maxDelay:i};this.updateOperationData("AvailableHandshake",n,e)}handshakeSucceeded(e,t){const i={retries:t};this.recordOperationSuccess("AvailableHandshake",i,null,e)}handshakeFailed(e,t,i){const n={retries:t,reason:up(i)};this.recordOperationFailure("AvailableHandshake",n,null,e)}requestControl(e,t){this.recordOperation("ControlRequest",e,e),this.recordAuditEvent(e,2,"ControlRequest",t)}requestControlAccepted(e,t){this.recordOperationSuccess("ControlRequest",e,e),this.recordAuditEvent(e,1,"ControlRequestAccepted",t),this.recordAuditEvent(e,2,"ControlStarted",t)}requestControlRejected(e,t,i){const n={reason:pp(t)};2===t?this.recordOperationTimeout("ControlRequest",n,e,e):this.recordOperationFailure("ControlRequest",n,e,e),this.recordAuditEvent(e,1,"ControlRequestDeclined",i)}controlGiven(e,t){this.recordEvent("ControlGiven",{sharerSourceId:t},e),this.recordAuditEvent(e,1,"ControlGiven",t),this.recordAuditEvent(e,2,"ControlStarted",t)}controlTerminated(e,t,i,n){const r={sharerSourceId:i,reason:pp(t)};this.recordEvent("ControlTerminated",r,e);const s=n?1:2;this.recordAuditEvent(e,s,"ControlTerminated",i)}recordAuditEvent(e,t,i,n){if(this.config.disableAudit)return;const r={participantId:this.sharerParticipantId,endpointId:this.sharerEndpointId,dataSourceId:n},s={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(e,i,t,r,s)}getEvent(e,t){const i=e=>e??"";return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),SharerParticipantId:i(this.sharerParticipantId),SharerClientVersion:i(this.sharerClientVersion),EventTimestampBag:super.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},cp=class extends op{constructor(e,t,i,n,r,s,a,o,l){super(e,t,i,n,r,s,a,o,l),this.role=1}availableAckChanged(e){e?this.recordEvent("AvailableAckEnabled"):this.recordEvent("AvailableAckDisabled")}controlRequest(e,t,i){this.recordOperation("ControlRequest",e,e),this.recordAuditEvent(e,2,"ControlRequest",t,i)}controlRequestAccept(e,t,i){const n={status:"accepting",participantId:i};this.updateOperationData("ControlRequest",n,e,e),this.recordAuditEvent(e,1,"ControlRequestAccepted",t,i)}controlRequestAccepted(e,t,i){const n={participantId:i};this.recordOperationSuccess("ControlRequest",n,e,e),this.recordAuditEvent(e,2,"ControlStarted",t,i)}controlRequestRejected(e,t,i,n){const r={reason:pp(t),participantId:n};4===t?this.recordOperationTimeout("ControlRequest",r,e,e):this.recordOperationFailure("ControlRequest",r,e,e),this.recordAuditEvent(e,1,"ControlRequestDeclined",i,n)}giveControl(e,t,i){this.recordOperation("GiveControl",e,e),this.recordAuditEvent(e,1,"ControlGiven",t,i)}giveControlSucceeded(e,t,i){const n={participantId:i};this.recordOperationSuccess("GiveControl",n,e,e),this.recordAuditEvent(e,2,"ControlStarted",t,i)}giveControlFailed(e,t,i,n){const r={reason:pp(t)};this.recordOperationTimeout("GiveControl",r,e,e),this.recordAuditEvent(e,1,"ControlGiveFailed",i,n)}controlTerminated(e,t,i,n,r){const s={controllerSourceId:n,reason:pp(t)};this.recordEvent("ControlTerminated",s,e);const a=r?2:1;this.recordAuditEvent(e,a,"ControlTerminated",i,n)}recordAuditEvent(e,t,i,n,r){if(this.config.disableAudit)return;const s=function(e,t){return e.endpoints?.endpointDetails?.find((e=>e.mediaStreams?.find((e=>e.sourceId===t))))}(n,r)??n.endpoints?.endpointDetails?.[0],a={participantId:s?.participantId,endpointId:s?.endpointId,dataSourceId:r},o={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(e,i,t,o,a)}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),EventTimestampBag:this.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},dp=class extends gt{constructor(e,t,i,n){super(e),this._logger=e,this._call=t,this._telemetryLoggers=i,this._config=n,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",(e=>{this._callId=e,this._recordSessionTelemetry((t=>t.setCallId(e)))})),this._participantId=this._call.participantId,this._call.on("callLegIdChanged",(e=>{this._participantId=e,this._recordSessionTelemetry((t=>{t.setParticipantId(e),t.setDataSourceId(this.getLocalEndpointDataSourceId())}))})),this._endpointId=this._call.endpointId}get role(){return this._role}setAdapters(e,t,i){this._controlInjector=e,this._rendererAdapter=t,this._dataChannelAdapter=i,this._dataChannelAdapter.on("stateChange",(e=>{this._onDataChannelStatusChanged(e),this._recordSessionTelemetry((t=>t.dataChannelAvailable(e)))})),this._dataChannelAdapter.on("protocolMessage",((e,t,i,n)=>this.processProtocolMessage(e,t,i,n))),this._dataChannelAdapter.on("controlMessage",((e,t)=>this.processControlMessage(e,t)))}testSetControlInjector(e){}enableScreenSharingControl(e,t,i,n){if(this._logger.info(`enableScreenSharingControl() enabled=${e} disabledReason=${t}`),this._availableAckEnabled!==e||this._allowControlForUser!==n){if(this._allowControlForUser=n,e)this._raiseScreenSharingControlCapableEvent(!0,ap);else{if(0===t){const e={reason:2,detail:i};this.event("sharingControlError").raise(e)}this._raiseScreenSharingControlCapableEvent(!1,ap)}this._availableAckEnabled!==e&&this._recordSharerSessionTelemetry((t=>t.availableAckChanged(e)),!1),this._availableAckEnabled=e}}_canEnableGiveControl(){return this._controlInjector.canBeEnabled()}setRaiseRenderedAtViewer(e){this._raiseRenderedAtViewer=e}setScreenSharingControlFeatureFlag(e,t){this._logger.info(`setScreenSharingControlFeatureFlag() enabled=${e} clientConfiguration=${JSON.stringify(t)}`),this._enabled=e,this._availableAckEnabled=e,this._clientConfiguration={...t},this._enabled&&this._handleCallState(this._callState)}isScreenSharingControlEnabled(){return this._enabled}isInternalViewerControlEnabled(){return!this._clientConfiguration.externalViewerControlInitialization}isInternalSharerControlEnabled(){return!this._clientConfiguration.externalSharerControlInitialization}_disposeRenderer(e){this._disposeControlCapturer(e);for(const e of this._screenSharingVideoRendererSubscriptions)e.dispose();this._screenSharingVideoRendererSubscriptions=[],this._screenSharingVideoRenderer=null}setRenderer(e,t){this._logger.info("setRenderer");const i=be();if(this._disposeRenderer(i),!e)return Promise.resolve();const n=t||this._rendererAdapter.getTarget(e);return Wt((()=>{this._setViewingRenderer(e,n)}))}_isDataChannelActive(){return this._dataChannelAdapter.isActive()&&this._dataChannelAvailable}_raiseScreenSharingControlCapableEvent(e,t,i){if(this._enabled&&this._isDataChannelActive()){this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=true, capable=${e}, role=${this._role}`);const n={capable:e,id:t,disabledBySharer:i};this.event("sharingControlCapable").raise(n)}else{this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=false, capable=${e}, role=${this._role}`);const i={capable:!1,id:t};this.event("sharingControlCapable").raise(i)}}initControlForSharer(e){this._logger.info(`initControlForSharer() negotiationTag: ${e}`),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(),ap),this._initiateSharerSessionTelemetry(e)}enableControlInjector(e){this._logger.info(`enableControlInjector() trackId: ${e}`),this._canEnableGiveControl()?this._controlInjector.enableInjector(e).catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})):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 e=this._getDataSourceIdForParticipantLeg(this._controlRequest),t=this._controlRequest;this._clearControlRequest(),this._raiseControlRequestCanceled(t),this._sendControlRejectRequest(t.causeId,5,t.participant,e)}if(this._controllerParticipant){const e={inControl:!1,id:this._controllerParticipant.participant.id,terminatedReason:5};this._recordSharerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerParticipant.participant,this._controllerSourceId))),this.event("sharingControlChanged").raise(e)}this._finalizeSharerSessionTelemetry(),this._teardownSharerRemoteControl(),this._controlInjector.disableInjector().catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})),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,np.each)(this._participantSubscriptions,(e=>{e.dispose()})),this._participantSubscriptions={}}_initiateViewerSessionTelemetry(e,t,i){if(!i&&!t)return null;if(!i&&(0,np.find)(this._completedViewerSessions,(e=>t===e)))return null;if(this._currentViewerSessionTelemetry){if(this._currentViewerSessionTelemetry.negotiationTag===t)return null;this._finalizeViewerSessionTelemetry(t)}return this._logger.info(`Initiating new viewer session telemetry for ${t}`),this._currentViewerSessionTelemetry=new lp(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),t,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId(),e),this._currentViewerSessionTelemetry.callStateChanged(this._callState),this._isDataChannelActive()&&this._currentViewerSessionTelemetry.dataChannelAvailable(!0),this._currentViewerSessionTelemetry}_recordViewerSessionTelemetry(e,t=!0){this._currentViewerSessionTelemetry?e&&e(this._currentViewerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeViewerSessionTelemetry(e){if(!this._currentViewerSessionTelemetry)return;this._currentViewerSessionTelemetry.shutdownSession(e);const t=this._currentViewerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_viewer_session",t),this._currentViewerSessionTelemetry.negotiationTag&&this._completedViewerSessions.push(this._currentViewerSessionTelemetry.negotiationTag),this._currentViewerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentViewerSessionTelemetry.messagesFromUnknownSender).length&&rp.RootToolsManager.logExternalForDDL("ScreenSharingControl_viewer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentViewerSessionTelemetry=null}_initiateSharerSessionTelemetry(e){if(this._currentSharerSessionTelemetry){if(this._currentSharerSessionTelemetry.negotiationTag===e)return null;this._finalizeSharerSessionTelemetry(this._currentSharerSessionTelemetry.negotiationTag)}this._logger.info(`Initiating new sharer session telemetry for ${e}`),this._currentSharerSessionTelemetry=new cp(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),e,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId()),this._isDataChannelActive()&&this._currentSharerSessionTelemetry.dataChannelAvailable(!0)}_recordSharerSessionTelemetry(e,t=!0){this._currentSharerSessionTelemetry?e&&e(this._currentSharerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeSharerSessionTelemetry(e){if(!this._currentSharerSessionTelemetry)return;this._currentSharerSessionTelemetry.shutdownSession(e);const t=this._currentSharerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_sharer_session",t),this._currentSharerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentSharerSessionTelemetry.messagesFromUnknownSender).length&&rp.RootToolsManager.logExternalForDDL("ScreenSharingControl_sharer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentSharerSessionTelemetry=null}_recordSessionTelemetry(e){e&&(this._currentSharerSessionTelemetry&&e(this._currentSharerSessionTelemetry),this._currentViewerSessionTelemetry&&e(this._currentViewerSessionTelemetry))}_sendTelemetryEvent(e,t){this._logger.info(`Sending event ${e}: `),Object.keys(t).forEach((e=>{this._logger.info(` ${e} => ${t[e]}`)})),this._telemetryLoggers?.media?.sendEvent({eventName:e,props:t})}reportSharingSessionChangeForViewer(e,t){t&&this._initiateViewerSessionTelemetry(e,t,!1)}initControlForViewer(e,t){if(this._logger.info(`initControlForViewer(${De(e?.id)}, ${t})`),e){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=t,void(this._pendingSharer=e);this._logger.info(`role is changing from=${this._role} to=2`),this._role=2,this._sharerParticipant?this._sharerParticipant.id!==e.id&&(this._logger.info(`initControlForViewer: sharer switched, new sharer id=${De(e.id)}`),this._availableHandshakeSent=!1,4===this.controlState&&this._terminateControl(!1)):(this._logger.info(`initControlForViewer: setting sharer to id=${De(e.id)}`),this._sharerParticipant=e,this._availableHandshakeSent=!1),this._initiateViewerSessionTelemetry(e,t,!0),this._enabled&&this._isDataChannelActive()&&!this._availableHandshakeSent&&(this._resetControlState(),this._sharerParticipant=e,this._logger.info("initControlForViewer: sending Available message to sharer"),this._startAvailableHandshake())}else this._logger.warn("initControlForViewer: Sharer undefined, ignoring")}shutdownControlForViewer(e){if(this._logger.info(`shutdownControlForViewer() isViewing: ${this._isViewing()}`),this._pendingSharer=null,(!e||e.id===this._sharerParticipant?.id)&&this._isViewing()){if(this._logger.info(`shutdownControlForViewer: sharerParticipant id=${e?De(e.id):null}`),1===this.controlState){if(this._sharerParticipant){const e=this._getSharerDataSourceId();this._sendRequest({action:2,terminatedReason:6,causeId:this._controlCauseId},e)}else this._logger.warn("shutdownControlForViewer: sharer participant is null");const e={inControl:!1,id:ap,terminatedReason:6};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:e,details:""}))):this._logger.error("shutdownControlForViewer: Unexpected, no promise could be resolved, controlState=RequestSent")}else if(4===this.controlState){const e={inControl:!1,id:ap,terminatedReason:6};this._recordViewerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerSourceId,!1))),this.event("sharingControlChanged").raise(e)}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=, isCapable=false`),this._raiseScreenSharingControlCapableEvent(!1,ap)):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(e){this._clearControlRequest(),this._controlRequest=e,this._registerParticipantListener(e),3===e.participantState&&(this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${De(e.participant.id)}`),this.event("sharingIncomingControlRequest").raise(e.participant.id))}_clearControlRequest(){this._logger.info("_clearControlRequest()"),this._stopListeningToParticipantChanges(this._controlRequest),this._controlRequest=null}_stopListeningToParticipantChanges(e){this._controlRequestSubscription&&(this._logger.info(`_stopListeningToParticipantChanges: stopping tracking changes for ${De(e.participant.id)}`),this._controlRequestSubscription.dispose(),this._controlRequestSubscription=null)}_registerParticipantListener(e){this._logger.info(`_registerParticipantListener: tracking changes for ${De(e.participant.id)}`),this._logger.info(`request.participantState: ${e.participantState} | request.participant.state: ${e.participant.state}`),this._controlRequestSubscription=e.participant.changed((()=>{if(e.participant.state!==e.participantState)switch(this._logger.info(`request.participantState about to changed from: ${e.participantState} to: ${e.participant.state}`),e.participantState=e.participant.state,e.participantState){case 3:this.event("sharingIncomingControlRequest").raise(e.participant.id),this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${De(e.participant.id)}`);break;case 0:case 5:case 4:this.denyControlRequest().catch((e=>{this._logger.info(`It is ok if denyControlRequest rejects here as screensharing may have just been stopped. Err: ${e}`)})),this._logger.info(`_registerParticipantListener: participant ${De(e.participant.id)} is no longer connected. resetting`),this._clearControlRequest(),this._raiseControlRequestCanceled(e);break;case 1:case 2:case 6:case 7:this._logger.info(`participantState: ${e.participantState}, participantId: ${De(e.participant.id)}`);break;default:this._logger.error(`_registerParticipantListener: Unexpected participantState ${e.participantState} unhandled`)}}))}_resetControllerParticipant(e){this._controllerParticipantSubscription&&(this._logger.info(`_resetControllerParticipant: stopping tracking changes for ${De(this._controllerParticipant.participant.id)}`),this._controllerParticipantSubscription.dispose(),this._controllerParticipantSubscription=null),e&&(this._logger.info(`_resetControllerParticipant: tracking changes for ${De(e.participant.id)}`),this._controllerParticipantSubscription=e.participant.changed((()=>{3!==e.participant.state&&this.handleParticipantRemoved(e.participant.id)}))),this._controlCauseId=e?.causeId??null,this._controllerParticipant=e}handleParticipantRemoved(e){if(this._participantSubscriptions[e]&&(this._logger.info(`handleParticipantRemoved(): Stopping tracking state changes for ${De(e)}`),this._participantSubscriptions[e].dispose(),delete this._participantSubscriptions[e]),this._isSharing()){if(this._controllerParticipant&&this._controllerParticipant.participant.id===e){this._logger.info("handleParticipantRemoved: controller left call, tearing down control session"),this._teardownSharerRemoteControl(),this.controlState=0;const t=5;this._recordSharerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,t,this._controllerParticipant.participant,this._controllerSourceId,!0))),this._resetControllerParticipant();const i={inControl:!1,id:e,terminatedReason:t};this.event("sharingControlChanged").raise(i)}this._raiseScreenSharingControlCapableEvent(!1,e)}else if(this._sharerParticipant&&this._sharerParticipant.id===e&&4===this.controlState){this._logger.info("handleParticipantRemoved: sharer left call, tearing down control session"),this._teardownViewerRemoteControl(),this.controlState=0;const e={inControl:!1,id:ap,terminatedReason:6};this.event("sharingControlChanged").raise(e)}}callStateChanged(e){this._callState=e,this._recordSessionTelemetry((t=>t.callStateChanged(e))),this.isScreenSharingControlEnabled()&&this._handleCallState(e)}setIsEscalationInProgress(e){this.isEscalationInProgress=e}_getHandshakeDelay(){if(!this._config.handshakeSendDelay?.minParticipantThreshold)return 0;let e=0;if(this._call.participants.length>=this._config.handshakeSendDelay.minParticipantThreshold)for(const t of this._call.participants)t.endpoints?.endpointDetails.some((e=>"interactive"===e.appliedInteractivityLevel))&&e++;if(e<=this._config.handshakeSendDelay.minParticipantThreshold)return 0;const t=Math.ceil((e-this._config.handshakeSendDelay.minParticipantThreshold)/this._config.handshakeSendDelay.increaseEveryN);return Math.min(this._config.handshakeSendDelay.maxDelay,t*this._config.handshakeSendDelay.delayPerN)}_handleCallState(e){switch(e){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(e,t){null!==this._controlCapturer&&this._controlCapturer.updateVideoSize(e,t)}_onRenderStarted(){const e={action:11,terminatedReason:0};if(this._sharerParticipant){const t=this._getSharerDataSourceId();this._sendRequest(e,t)}else this._logger.error("Attempted to send sharing rendered message to null sharerParticipant")}_setViewingRenderer(e,t){try{this._screenSharingVideoRenderer=e,this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeVideoSizeChangedEvent(this._screenSharingVideoRenderer,((e,t)=>{this._videoSizeChanged(e,t)}))),this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeRenderStartedEvent(this._screenSharingVideoRenderer,(()=>{this._onRenderStarted()})));let i=1;e.streamSize&&e.streamSize.width>0&&e.streamSize.height>0&&(i=e.streamSize.width/e.streamSize.height),this._controlCapturer=new ip.SlimCoreElectronControlCapturer(this._logger,t,!0,i),4===this.controlState?(this._logger.info("_setViewingRenderer: detected local state is controlling"),this._setupViewerRemoteControl()):this._teardownViewerRemoteControl()}catch(e){this._logger.error(`_setViewingRenderer: unable to set _screenSharingVideoRenderer error=${e}`)}}_onDataChannelStatusChanged(e){this._logger.info(`_onDataChannelStatusChanged(): Data channel status=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e?this._dataChannelAvailable||(this._dataChannelAvailable=!0,this._recordSessionTelemetry((e=>e.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,ap)))):this._dataChannelAvailable&&(this._recordSessionTelemetry((e=>e.dataChannelAvailable(!1))),this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(3),this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!1,ap))}_isSharing(){return 1===this._role}_isViewing(){return 2===this._role}_handleAvailableRequest(e,t,i){if(this._isSharing())return this._enabled&&this._availableAckEnabled&&this._canEnableGiveControl()?t?.id?void(this._allowControlForUser&&"function"==typeof this._allowControlForUser?this._allowControlForUser(t).then((n=>{n?this._acceptAvailableRequest(e.handshakeId,t,i):this._rejectAvailableRequest(e.handshakeId,i,1)})):this._acceptAvailableRequest(e.handshakeId,t,i)):(this._logger.info("Unknown sender. Rejecting available ack"),void this._rejectAvailableRequest(e.handshakeId,i,10)):(this._logger.info(`Rejecting available ack - enabled=${this._enabled}, availableAck=${this._availableAckEnabled}, controlInjector=${this._canEnableGiveControl()}`),void this._rejectAvailableRequest(e.handshakeId,i,9));this._logger.warn(`Ignoring available request since role=${this._role} is not sharing. Expecting for viewer side retries`)}_acceptAvailableRequest(e,t,i){this._raiseScreenSharingControlCapableEvent(!0,t.id),this._participantSubscriptions[t.id]||(this._logger.info(`Tracking participant status for ${De(t.id)}`),this._participantSubscriptions[t.id]=t.changed((()=>{3!==t.state&&(this._logger.info(`Participant ${De(t.id)} is not connected. removing`),this.handleParticipantRemoved(t.id))}))),this._logger.info(`Acking Available for handShake:${i}:${e}`),this.event("controlAvailableHandshake").raise(e,i,3),this._sendRequest({action:9,terminatedReason:0,handshakeId:e},i)}_rejectAvailableRequest(e,t,i){this._logger.info(`Rejecting Available for handShake:${t}:${e}`),this.event("controlAvailableHandshake").raise(e,t,7,this._getAvailableHandshakeTerminatedFromControlTerminated(i)),this._sendRequest({action:10,terminatedReason:i,handshakeId:e},t)}processProtocolMessage(e,t,i,n){return Wt((()=>{this._processProtocolMessage(e,t,i,n)}))}_raiseControlRequestCanceled(e){this.event("sharingIncomingControlRequestCancelled").raise(e.participant.id)}_handleControlRequest(e,t,i,n){this._recordSharerSessionTelemetry((i=>i.controlRequest(n,e,t))),this._enabled?this._controlRequest?(this._logger.warn("Sharer is already processing a control request...rejecting new requests"),this._sendControlRejectRequest(n,3,e,t)):this._controllerParticipant&&this._controllerParticipant.participant===e?this._controllerParticipant.participantId&&this._controllerParticipant.participantId!==i?(this._logger.warn(`rejecting control request from second endpoint. participantId: ${i}`),this._sendControlRejectRequest(n,3,e,t)):(this._logger.warn("Got control request for someone already in control"),this._resetControllerParticipant(),this._resetControlRequest({participant:e,participantState:e.state,participantId:i,causeId:n})):e?(this._logger.info(`resetControlRequest for participantId: ${i}`),this._resetControlRequest({participant:e,participantState:e.state,participantId:i,causeId:n})):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(n,9,e,t))}_handleAcceptRequest(e,t){if(1===this.controlState){const i=this._sendRequest({action:5,terminatedReason:0},t);this._logger.info(`_handleAcceptRequest controlMessage.action: ${hp(e.action)} _sendRequest isSent: ${i}`),i?(this._setupViewerRemoteControl(),this.controlState=4,this._requestControlPromise?this._requestControlPromise.resolve():this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${hp(e.action)}`),this._recordViewerSessionTelemetry((e=>e.requestControlAccepted(this._controlCauseId,t)))):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=${gp(this.controlState)} action=${hp(e.action)}`),this._cancelRequestControlTimer()}else this._logger.warn(`AcceptRequest message received in controlState=${gp(this.controlState)}`)}_handleRejectRequest(e,t){if(1===this.controlState){this._logger.info(`_handleRejectRequest: controlState: ${gp(this.controlState)}, about to be changed to: ${gp(0)}`),this.controlState=0;const i={inControl:!1,id:ap,terminatedReason:e.terminatedReason};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:i,details:""}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${hp(e.action)}`),this._recordViewerSessionTelemetry((i=>i.requestControlRejected(this._controlCauseId,e.terminatedReason,t))),this._cancelRequestControlTimer(),this._controlCauseId=null}else this._logger.warn(`RejectRequest message received in controlState=${gp(this.controlState)} reason=${e.terminatedReason}`)}_handleCancelControlRequest(e,t){if(this._logger.info(`_handleCancelControlRequest action=${hp(e.action)} sender=${t}, controlRequest participantId: ${this._controlRequest.participantId}, controlRequest participantState: ${this._controlRequest.participantState}:`),this._controlRequest){const i=this._controlRequest;this._logger.info(`_handleCancelControlRequest action=${hp(e.action)} sender=${t}, about to raise: _raiseControlRequestCanceled state: ${this._controlRequest.participantState} `),this._recordSharerSessionTelemetry((n=>n.controlRequestRejected(e.causeId,e.terminatedReason,i.participant,t))),this._clearControlRequest(),this._raiseControlRequestCanceled(i)}}_handleGiveControl(e,t,i){const n=this._sendRequest({action:5,terminatedReason:0},t);if(this._logger.info(`_handleGiveControl: controlMessage.action: ${hp(e.action)} _sendRequest isSent: ${n}`),this._controlCauseId=e.causeId,n){this._setupViewerRemoteControl(),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(4)}`),this.controlState=4,this._recordViewerSessionTelemetry((e=>e.controlGiven(this._controlCauseId,t)));const i={inControl:!0,id:ap,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(i)}}_handleAck(e,t,i){if(2===this.controlState)if(this._controllerParticipant&&this._controllerParticipant.participant.id===t.id){const t=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);i!==t&&this._logger.warn(`acknowledging source id: ${i} does not match requesting source id: ${t}`),this._logger.info(`Setting up remote control for controller source id=${t}`),this._setupSharerRemoteControl(t),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(3)}`),this.controlState=3;const n={inControl:!0,id:this._controllerParticipant.participant.id,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(n),this._grantControlPromise?(this._grantControlPromise.resolve(),this._cancelGrantControlTimer(),this._recordSharerSessionTelemetry((e=>e.giveControlSucceeded(this._controlCauseId,this._controllerParticipant.participant,t)))):this._acceptControlPromise?(this._acceptControlPromise.resolve(),this._cancelAcceptControlTimer(),this._recordSharerSessionTelemetry((e=>e.controlRequestAccepted(this._controlCauseId,this._controllerParticipant.participant,t)))):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForControlAck action=${hp(e.action)}`)}else t?this._logger.warn(`Ignoring ack from participant that does not match controller id=${De(t.id)}`):this._logger.warn(`Ignoring ack from null participant source id=${i}`);else 5===this.controlState?(this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(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=${hp(e.action)}`)):this._logger.warn(`Unexpected ack in control controlState=${gp(this.controlState)}`)}_handleTerminate(e,t,i){let n;this._isViewing()?(this._teardownViewerRemoteControl(),n=ap,this._recordViewerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,i,!0)))):(this._teardownSharerRemoteControl(),t?n=t.id:this._logger.error("Got terminate message but could not find a sender participant!"),this._recordSharerSessionTelemetry((t=>t.controlTerminated(this._controlCauseId,e.terminatedReason,this._controllerParticipant.participant,i,!0)))),this._logger.info(`controlMessage action: ${hp(e.action)}, controllerId: ${n}`),this._logger.info(`controlState: ${gp(this.controlState)}, about to be changed to: ${gp(0)}`),this.controlState=0,this._resetControllerParticipant();const r={inControl:!1,id:n,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(r),8===e.action&&this._sendRequest({action:5,terminatedReason:0},i)}_handleAvailableAck(e){this._terminateAvailableHandshake&&(this._logger.info(`_handleAvailableAck: terminate available handshake reason: 1,handshakeId: ${e.handshakeId}`),this._terminateAvailableHandshake(1,e.handshakeId)),2===this._role?this._raiseScreenSharingControlCapableEvent(!0,ap):this._logger.info(`Ignoring AvailableAck as viewer session is not initialized, role: ${this._role}`)}_handleAvailableNack(e){this._logger.info(`_handleAvailableNack: action=${hp(e.action)} terminate reason: ${pp(e.terminatedReason)}`),this._viewerSessionLastTerminatedReason=e.terminatedReason,10!==e.terminatedReason?(this._terminateAvailableHandshake&&(this._terminateAvailableHandshake(this._getAvailableHandshakeTerminatedFromControlTerminated(e.terminatedReason),e.handshakeId),this._logger.info(`_handleAvailableNack: terminateAvailableHandshake reason=${pp(e.terminatedReason)}`)),1===e.terminatedReason?(this._logger.warn("_handleAvailableNack: control terminate reason: SharerDenied"),this._raiseScreenSharingControlCapableEvent(!0,ap,!0)):this._raiseScreenSharingControlCapableEvent(!1,ap)):this._logger.warn("_handleAvailableNack: control terminate reason: UnknownSender")}_handleRenderedAtViewer(e,t){this._raiseRenderedAtViewer&&(t?(this._logger.info(`raiseRenderedAtViewer senderId=${De(t.id)}, action=${hp(e.action)}`),this._raiseRenderedAtViewer(t.id)):this._logger.error("Got RenderedAtViewer message but could not find a sender participant!"))}_processProtocolMessage(e,t,i,n){let r;this._recordSessionTelemetry((e=>e.recordProtocolMessage(t,n)));try{r=JSON.parse(e)}catch(e){return void this._logger.error("Error parsing controlMessage")}switch(t||this._logger.warn(`protocol message from unknown sender with sourceId=${n}`),this._logger.info(`_processProtocolMessage action=${hp(r.action)}, sourceId=${n}`),r.action){case 0:this._handleAvailableRequest(r,t,n);break;case 1:this._handleControlRequest(t,n,i,r.causeId);break;case 3:this._handleAcceptRequest(r,n);break;case 4:this._handleRejectRequest(r,n);break;case 2:this._handleCancelControlRequest(r,n);break;case 6:this._handleGiveControl(r,n,t);break;case 5:this._handleAck(r,t,n);break;case 8:case 7:this._handleTerminate(r,t,n);break;case 9:this._handleAvailableAck(r);break;case 10:this._handleAvailableNack(r);break;case 11:this._handleRenderedAtViewer(r,t);break;default:this._logger.error(`Unknown request action received on control protocol data sink, action=${hp(r.action)}`)}}_getAvailableHandshakeTerminatedFromControlTerminated(e){switch(e){case 10:return 6;case 1:return 7;default:return 0}}_sendRequest(e,t){if(t<0)return this._logger.warn(`Unexpected: invalid sourceID=${t}`),!1;this._logger.info(`_sendRequest() action=${hp(e.action)} recipient sourceid=${t}`);const i={type:0,message:JSON.stringify(e)},n=[t];return this._dataChannelAdapter.sendProtocolMessage(function(e){const t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}(JSON.stringify(i)),n),!0}async processControlMessage(e,t){if(t===this._controllerSourceId){if(3===this.controlState)return this._processControlMessage(e,t);this._logger.debug(`Ignoring control message, wrong controlState. Expected: RemoteControlling, got: ${gp(this.controlState)}`)}else this._logger.debug(`Ignoring control message, wrong sourceId. Expected: ${t}, got: ${this._controllerSourceId}`)}_processControlMessage(e,t){return this._controlInjector.injectRawInput(e,t)}_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(e){this._logger.info(`_setupSharerRemoteControl() sourceId=${e}`),this._controllerSourceId=e,this._controlInjector.showVirtualCursor(e).catch((t=>{const i={reason:3,detail:JSON.stringify({sourceId:e,errorMsg:t})};this.event("sharingControlError").raise(i)}))}_teardownSharerRemoteControl(){this._logger.info("_teardownSharerRemoteControl()"),this._controllerSourceId=null,this._controlInjector.showVirtualCursor(0).catch((e=>{const t={reason:3,detail:JSON.stringify({sourceId:0,errorMsg:e})};this.event("sharingControlError").raise(t)}))}_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(e,t){if(t)switch(e){case"mouseControlEvent":this._sendControlEvent(Vg.encodeMouseEvent(t));break;case"keyboardControlEvent":this._sendControlEvent(Vg.encodeKeyboardEvent(t));break;default:return void this._logger.error("sendRemoteControlEvent: Invalid type=",e)}else this._logger.error("sendRemoteControlEvent: Invalid argument.")}_sendControlEvent(e){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: ${gp(this.controlState)})`);const t=[this._getSharerDataSourceId()];this._dataChannelAdapter.sendControlMessage(e,t)}_setCapturerMode(e){this._logger.info(`_setCapturerMode() capturerMode=${e}`),this._controlCapturer?(this._controlCapturer.setCaptureMode(e),this._clearCapturerEventSubscriptions(),1===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{0===e&&this.event("sharingRendererClicked").raise()})):2===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})):3===e&&(this._mouseControlEventSubscription=this._controlCapturer.on("mouseControlEvent",(e=>{this._sendControlEvent(Vg.encodeMouseEvent(e))})),this._keyboardControlEventSubscription=this._controlCapturer.on("keyboardControlEvent",(e=>{this._sendControlEvent(Vg.encodeKeyboardEvent(e))})),this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})))):this._logger.info("_controlCapturer not set, relying on external controlCapturer")}setPointerImage(e,t){return this._logger.warn("setPointerImage is deprecated. Use setLocalPointerImage or setRemotePointerImage"),e?this.setRemotePointerImage(e,t):this.setLocalPointerImage(t)}setLocalPointerImage(e){return 0===e.length?Promise.reject(new Error("setLocalPointerImage invalid image length")):this._setPointerImage(0,e)}async setRemotePointerImage(e,t){if(!e)throw new Error("setRemotePointerImage participant is null");if(0===t.length)throw new Error("setRemotePointerImage invalid image length");const i=this._getParticipantsDataSourceIds(e);if(0===i.length)throw new Error("setRemotePointerImage unable to map participant to sourceIds");this._logger.info(`set pointer image for ${i.length} sources`);for(const e of i)await this._setPointerImage(e,t)}_setPointerImage(e,t){return this._isSharing()||this._logger.warn("_setPointerImage called when not sharing"),this._controlInjector.setPointerImage(e,t)}startPointerMode(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`startPointerMode called in bad control controlState=${gp(this.controlState)}`)):this._isViewing()?Wt((()=>{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=${gp(this.controlState)}`)):this._isViewing()?Wt((()=>{this._setCapturerMode(1)})):Promise.reject(new Error("stopPointerMode when not viewing"))}_startAvailableHandshake(){const e=this._getSharerDataSourceId(),t=mi(),i=this._getHandshakeDelay(),n=Math.floor(Math.random()*i);if(this._logger.info(`_startAvailableHandshake() - handshakeId: ${e}:${t} ${n>0?`delay: ${n}ms maxDelay: ${i}ms`:""}}`),this._terminateAvailableHandshake&&(this._logger.warn("Replacing existing availble handshake"),this._terminateAvailableHandshake(4)),this._recordViewerSessionTelemetry((e=>e.startHandshake(t))),e<0)this._logger.warn(`_startAvailableHandshake() - sharer: ${De(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(t);else{const r=()=>{this.event("controlAvailableHandshake").raise(t,e,1),this._sendRequest({action:0,terminatedReason:0,handshakeId:t},e)||this._logger.error("Failed to send Available message to sharer, will retry after backoff"),this._waitForAvailableAck(t)};n>0?(this._delayedSendHandshakeTimer=window.setTimeout(r,n),this._recordViewerSessionTelemetry((e=>e.delayHandshakeSending(t,n,i)))):r()}this._availableHandshakeSent=!0,this._terminateAvailableHandshake=(i=0,n)=>{this._logger.info(`_terminateAvailableHandshake() - handshakeId: ${e}:${t}, status: ${i}`),1===i?this._recordViewerSessionTelemetry((e=>e.handshakeSucceeded(t,this._retryAttempt))):(this._logger.error(`GTC handshake terminated with code ${i}, last terminated reason: ${pp(this._viewerSessionLastTerminatedReason)}`),rp.RootToolsManager.logExternalForDDL(`GTC handshake terminated with code ${i},`,this._viewerSessionLastTerminatedReason.toString()),this._recordViewerSessionTelemetry((e=>e.handshakeFailed(t,this._retryAttempt,i)))),this._terminateAvailableHandshake=null,this.event("controlAvailableHandshake").raise(t,e,1===i?5:6,i),n&&n!==t&&this._logger.warn(`AvailableSeries: Got handshake from another series - expected: ${t}, received: ${n}`),this._availableAckTimer&&(clearTimeout(this._availableAckTimer),this._availableAckTimer=null),this._delayedSendHandshakeTimer&&(clearTimeout(this._delayedSendHandshakeTimer),this._delayedSendHandshakeTimer=null),this._retryAttempt=0}}_waitForAvailableAck(e){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 t=this._getSharerDataSourceId();if(this._retryAttempt<=6)t>=0?(this._logger.info(`Re-sending Available message handshakeId: ${t}:${e}`),this.event("controlAvailableHandshake").raise(e,t,2),this._sendRequest({action:0,terminatedReason:0,handshakeId:e},t)):this._logger.warn(`_waitForAvailableAck() - sharer: ${De(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(e);else{if(this._logger.error("Reached Available retry limit! Control capability will be false"),this._terminateAvailableHandshake)this._terminateAvailableHandshake(5);else{const e={reason:4,detail:JSON.stringify({sourceId:t,errorMsg:`Timed out after ${this._retryAttempt} tries`})};this.event("sharingControlError").raise(e)}this._raiseScreenSharingControlCapableEvent(!1,ap)}}),2e3*++this._retryAttempt)}requestControl(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`requestControl called in bad controlState=${gp(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 e=this._controlCauseId=be();this._logger.info(`_requestControl(), controlState: ${this.controlState}, controlCauseId: ${e}`),this._requestControlPromise=new Kt;const t=()=>{this._requestControlPromise=null};this._requestControlPromise.promise.then(t,t);const i=this._getSharerDataSourceId();if(!this._sendRequest({action:1,terminatedReason:0,causeId:e},i)){const e={inControl:!1,id:ap,terminatedReason:7};return this._requestControlPromise.reject(new Error),this._logger.error("_requestControl(): failed to send the request."),Promise.reject(new Error(JSON.stringify({controlInfo:e,details:""})))}return this._recordViewerSessionTelemetry((t=>t.requestControl(e,i))),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:e},i)||this._logger.error("Failed to send the cancel control request");const t={inControl:!1,id:ap,terminatedReason:2};this._recordViewerSessionTelemetry((n=>n.requestControlRejected(e,t.terminatedReason,i))),this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:t,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=${gp(this.controlState)}`);this._requestControlTimer=null}),3e4),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=${gp(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 e=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},e))return Promise.reject(new Error("Failed to send cancel control request"));{const t={inControl:!1,id:ap,terminatedReason:8};this._recordViewerSessionTelemetry((i=>i.requestControlRejected(this._controlCauseId,t.terminatedReason,e))),this._controlCauseId=null,this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:t,details:""})))}return new Promise(((e,t)=>{e()}))}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 Kt;const e=()=>{this._acceptControlPromise=null};if(this._acceptControlPromise.promise.then(e,e),this._controllerParticipant){this._logger.warn("_acceptControlRequest called while another participant already has control - terminating control");try{await this._terminateControl(!1)}catch(t){this._logger.error("_acceptControlRequest: failed to gracefully terminate control of previous controller",t)}this._resetControllerParticipant()}const t=this._getDataSourceIdForParticipantLeg(this._controlRequest),i=this._controlRequest.participant.id,n=this._controlRequest.causeId,r=this._controlRequest.participant;return this._sendControlAcceptRequest(n,r,t)?(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:n},t)||this._logger.error("Failed to send the TerminateNoAck request");const e={inControl:!1,id:i,terminatedReason:4};this._recordSharerSessionTelemetry((i=>i.controlRequestRejected(n,e.terminatedReason,r,t))),this.event("sharingControlChanged").raise(e),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=${gp(this.controlState)}`);this._acceptControlTimer=null}),sp),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(e,t,i){const n=this._sendRequest({action:3,terminatedReason:0,causeId:e},i);return this._recordSharerSessionTelemetry((n=>n.controlRequestAccept(e,t,i))),n}_sendControlRejectRequest(e,t,i,n){const r=this._sendRequest({action:4,terminatedReason:t},n);return this._recordSharerSessionTelemetry((r=>r.controlRequestRejected(e,t,i,n))),r}_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 e=this._getDataSourceIdForParticipantLeg(this._controlRequest),t=this._sendControlRejectRequest(this._controlRequest.causeId,1,this._controlRequest.participant,e);return this._clearControlRequest(),t?Promise.resolve():Promise.reject(new Error("Failed to send the deny control requst"))}grantControl(e){return this._enabled?this._isDataChannelActive()?this._controlRequest?Promise.reject(new Error("grantControl called while control request pending")):this._isSharing()?e?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(e):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(e){this._logger.info("_grantControl()"),this._grantControlPromise=new Kt;const t=()=>{this._grantControlPromise=null};if(this._grantControlPromise.promise.then(t,t),3===this.controlState){if(this._controllerParticipant.participant?.id===e.id)return this._logger.warn("_grantControl called for participant who already has control"),this._grantControlPromise.resolve(),new Promise(((e,t)=>{e()}));{this._logger.warn("_grantControl called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const e=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},e)||this._logger.error("Failed to send the terminateNoAck request")}}const i=this._mapParticipantToSourceId(e),n=be(),r=this._sendRequest({action:6,terminatedReason:0,causeId:n},i);if(this._recordSharerSessionTelemetry((t=>t.giveControl(n,e,i))),!r)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 s=this._getParticipantIdForDataSourceId(e,i);return this._resetControllerParticipant({participant:e,participantState:e.state,participantId:s,causeId:n}),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},i)||this._logger.error("Failed to send the terminateNoAck request"),this._recordSharerSessionTelemetry((t=>t.giveControlFailed(n,4,e,i))),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=${gp(this.controlState)}`),this._grantControlTimer=null}),sp),this._grantControlPromise.promise}_cancelGrantControlTimer(){this._grantControlTimer&&(this._grantControlPromise&&this._grantControlPromise.reject(new Error("cancelled by _cancelGrantControlTimer")),clearTimeout(this._grantControlTimer),this._grantControlTimer=null)}_mapParticipantToSourceId(e){return this._dataChannelAdapter.isActive()?Ud(e,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getParticipantsDataSourceIds(e){const t=[];try{if(e?.endpoints?.endpointDetails){if(1===e.endpoints.endpointDetails.length){const i=e.endpoints.endpointDetails[0];if(!i?.mediaStreams)return t.push(Ur),t}for(const i of e.endpoints.endpointDetails)if(i?.mediaStreams)for(const e of i.mediaStreams)if(3===Nd(e.type)){if(t.push(e.sourceId),t.length>=8)return this._logger.error("Excessive amount of data streams"),t;break}}}catch(e){this._logger.error(`_getParticipantsDataSourceIds caught exception error=${e}`)}return t}_getParticipantIdForDataSourceId(e,t){return Bd(e,3,t)}_getDataSourceIdForParticipantId(e,t){return this._dataChannelAdapter.isActive()?function(e,t){if(!e?.endpoints)return-1;const i=e.endpoints.endpointDetails.find((e=>e?.participantId===t));if(!i?.mediaStreams)return Ud(e,3);const n=i.mediaStreams.find((({type:e})=>3===Nd(e)));return n?n.sourceId:-1}(e,t):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getDataSourceIdForParticipantLeg(e){return this._getDataSourceIdForParticipantId(e.participant,e.participantId)}_getSharerDataSourceId(){const e=Hd(this._sharerParticipant);return e?this._getDataSourceIdForParticipantId(this._sharerParticipant,e):(this._logger.warn("Unable to identify the sharer participantId, falling back to first data channel"),this._mapParticipantToSourceId(this._sharerParticipant))}getLocalEndpointDataSourceId(){const e=Ld(this._call,this._participantId);if(e?.mediaStreams){const t=e.mediaStreams.find((({type:e})=>3===Nd(e)));return t?.sourceId??-1}return-1}terminateControl(e){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,e)}_terminateControl(e,t){this._logger.info("_terminateControl()"),this._terminateControlPromise=new Kt;const i=()=>{this._terminateControlPromise=null};this._terminateControlPromise.promise.then(i,i);let n=0;const r=e?8:7;let s,a;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(),n=t??6,s=this._getSharerDataSourceId(),this._recordViewerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,n,s))),a=ap,this._logger.info(`Terminating remote control reason: ${pp(n)}, recipient: ${s}, controllerId: ${a}`)}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(),n=t??5,s=this._getDataSourceIdForParticipantLeg(this._controllerParticipant),this._recordSharerSessionTelemetry((e=>e.controlTerminated(this._controlCauseId,n,this._controllerParticipant.participant,s))),a=De(this._controllerParticipant.participant.id),this._logger.info(`Terminating control on the sharer side, reason: ${pp(n)}, recipient: ${s}, controllerId: ${a}`)}const o={action:r,terminatedReason:n};if(!this._sendRequest(o,s)){if(e)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=e?5:0;const l={inControl:!1,id:a,terminatedReason:o.terminatedReason};return this._logger.info(`raising event sharingControlChanged reason=${pp(l.terminatedReason)} controlState=${gp(this.controlState)}`),this.event("sharingControlChanged").raise(l),e?(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},s)||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=${gp(this.controlState)}`),this._terminateControlTimer=null}),sp),this._terminateControlPromise.promise):(this._terminateControlPromise.resolve(),new Promise(((e,t)=>{e()})))}_cancelTerminateControlTimer(){this._terminateControlTimer&&(this._terminateControlPromise&&this._terminateControlPromise.reject(new Error("cancelled by _cancelTerminateControlTimer")),clearTimeout(this._terminateControlTimer),this._terminateControlTimer=null,this._logger.info("_cancelTerminateControlTimer()"))}_disposeControlCapturer(e=be()){this._logger.info(`_disposeControlCapturer causeId: ${e}`),this._clearCapturerEventSubscriptions(),this._controlCapturer&&(this._controlCapturer.dispose(e),this._controlCapturer=null)}dispose(e){this._logger.info(`dispose causeId: ${e}`),this._dataChannelAdapter.dispose(e),this._resetControlState(),this._disposeRenderer(e),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer(),this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._call=null,this._resetParticipantSubscriptions(),this._finalizeViewerSessionTelemetry(),this._finalizeSharerSessionTelemetry(),super.dispose(e)}};function up(e){switch(e){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 hp(e){switch(e){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 gp(e){switch(e){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 pp(e){switch(e){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 mp(e){switch(e){case 1:return"Sharer";case 2:return"Viewer";default:return"Unknown"}}var fp=(e=>(e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT",e[e.MIDDLE=2]="MIDDLE",e[e.BACK=3]="BACK",e[e.FORWARD=4]="FORWARD",e))(fp||{}),vp=(e=>(e[e.SCAN_CODE=0]="SCAN_CODE",e[e.VIRTUAL_KEY=1]="VIRTUAL_KEY",e[e.RECOGNITION_INPUT=2]="RECOGNITION_INPUT",e))(vp||{}),Sp=class{constructor(e){this.logger=e}toEdgeControlMouseEvent(e){let t;switch(e.type){case 0:return{event:this.toMouseMoveEvent(e),apiName:"injectMouseMoveEvent"};case 1:return{event:this.toMouseWheelEvent(e),apiName:"injectMouseWheelEvent"};case 2:return{event:this.toMouseButtonPressedEvent(e),apiName:"injectMouseButtonEvent"};default:throw t=`Uncovered mouse control event type. Event: ${e}`,this.logger.error(t),Error(t)}}toEdgeControlKeyboardEvent(e){return{event:{repeat:e.repeat,keyUp:e.keyUp,codeType:vp[e.codeType],keyCode:e.code},apiName:"injectKeyEvent"}}toMouseMoveEvent(e){return{xPos:e.xPos,yPos:e.yPos}}toMouseWheelEvent(e){return{wheelButtonDown:e.wheelButtonDown,wheelRotation:e.wheelRotation}}toMouseButtonPressedEvent(e){return{xPos:e.xPos,yPos:e.yPos,button:fp[e.buttonType],buttonDown:e.buttonDown}}};async function yp(e,t,i){return new Promise(((n,r)=>{const s=Buffer.from(e,"base64"),a=document.createElement("canvas").getContext("2d"),o=new Blob([s],{type:"image/png"});let l=new Image;l.onload=()=>{a.drawImage(l,0,0,l.width,l.height,0,0,t,i);const e=a.getImageData(0,0,t,i);window.URL.revokeObjectURL(l.src),l=null,n(Array.from(e.data))},l.onerror=e=>{r(e)},l.src=window.URL.createObjectURL(o)}))}var Cp,Tp,Ep="ncbjelpjchkpbikbpkcchkhkblodoama",bp=class{constructor(e){this.logger=e}async sendInjectInputEventMessage(e,t){return this.logger.info("EdgeControlInjectorApi - sendInjectInputEventMessage"),new Promise(((i,n)=>{window.top.chrome.runtime.sendMessage(Ep,{api:e,deviceId:this.virtualInputDeviceId,event:t},(e=>{e.error?n(e.error.message):i(0)}))}))}async createInputDeviceId(e,t,i){this.virtualInputDeviceId&&this.logger.warn("EdgeControlInjectorApi - createInputDeviceId virtual input already exists.");try{this.virtualInputDeviceId=await this.sendCreateInputDeviceMessage(e,i)}catch(e){this.logger.error(`EdgeControlInjectorApi - createInputDevice failed, error: ${JSON.stringify(e)}`),t()}}async sendSetLocalUserAvatarMessage(e){const t=await this.generateAvatarBitmap(e);return new Promise(((e,i)=>{const n=window.top;t&&n.chrome.runtime.sendMessage(Ep,{api:"setLocalUserAvatar",avatarBitmap:t},(t=>{t.error?i(t.error.message):e()}))}))}async sendCloseVirtualInputDeviceMessage(){const e=this.virtualInputDeviceId;return e?(this.logger.info("EdgeControlInjectorApi - sendCloseVirtualInputDeviceMessage called"),new Promise(((t,i)=>{const n=window.top;n.chrome.runtime.sendMessage(Ep,{api:"closeInputDevice",deviceId:e},(e=>{e?e.error?i(e.error.message):(this.virtualInputDeviceId=null,t(e.deviceId)):i(n.chrome.runtime.lastError.message)}))}))):(this.logger.info("EdgeControlInjectorApi - VirtualInputDevice does not exists, nothing to close."),Promise.resolve())}async sendCreateInputDeviceMessage(e,t){this.logger.info("EdgeControlInjectorApi - sendCreateInputDeviceMessage called");const i=await this.generateAvatarBitmap(t);return new Promise(((t,n)=>{const r=window.top,s=e=>{e?e.deviceId?t(e.deviceId):e.error?n(e.error.message):n("Error: Unexpected response from API"):n(r.chrome.runtime.lastError.message)};i?r.chrome.runtime.sendMessage(Ep,{api:"createInputDevice",mediaStreamTrackId:e,avatarBitmap:i},s):r.chrome.runtime.sendMessage(Ep,{api:"createInputDevice",mediaStreamTrackId:e},s)}))}async generateAvatarBitmap(e){if(!e)return null;try{const t=32;return{width:t,height:t,data:await yp(e,t,t)}}catch(e){return this.logger.error(`EdgeControlInjectorApi - generateAvatarBitmap error: ${JSON.stringify(e)}, continue without avatar.`),null}}},_p=class{constructor(e,t,i){this.logger=e,this.sharingTrackId=t,this.onInitErrorCallback=i,this.images=new Map,this.controlEventConverter=new Sp(e),this.edgeApi=new bp(this.logger)}showVirtualCursor(e,t){if(this.logger.info(`EdgeControlInjector - showVirtualCursor, id: ${e} sharingTrackId: ${this.sharingTrackId}`),t){this.edgeApi.createInputDeviceId(this.sharingTrackId,this.onInitErrorCallback,this.images[e]);const t=this.images[0];t?this.edgeApi.sendSetLocalUserAvatarMessage(t):this.logger.error("EdgeControllerInjector - local avatar is missing, continue without local avatar")}else this.edgeApi.sendCloseVirtualInputDeviceMessage()}setAvatar(e,t){this.logger.info(`${e} EdgeControlInjector - setAvatar, id: ${e}, data: ${JSON.stringify(t)}`),this.images[e]=t}async injectMouseEvent(e,t){this.logger.info(`${e} EdgeControlInjector - injectMouseEvent ${JSON.stringify(t)}`);const i=this.controlEventConverter.toEdgeControlMouseEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}async injectKeyboardEvent(e,t){const i=this.controlEventConverter.toEdgeControlKeyboardEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}injectClipboardText(e,t){return this.logger.info(`${e} EdgeControlInjector - injectClipboardText is unimplemented`),Promise.resolve(0)}dispose(e){this.logger.info("EdgeControlInjector - dispose"),this.edgeApi.sendCloseVirtualInputDeviceMessage()}},Ip="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?.getUserMedia,wp=(e=>(e.AVD="43",e.Citrix="44",e.VMware="45",e))(wp||{});function Ap(){return!!Tp}function Pp(){return Tp}function Rp(){navigator.getUserMedia=function(e,t,i){return navigator.mediaDevices.getUserMedia(e).then(t).catch(i)}}"undefined"!=typeof window&&"undefined"!=typeof navigator&&(Cp=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 Mp={window:Cp},Dp=class{constructor(e){this.logger=e,this.activeSourceId=0,this.pendingPointerImages=new Map}static create(e,t){return e.config.enableGiveControl?Ap()||window.ControlInjector?new Op(t):Ot.isBrowser("EdgeAnaheim")?new kp(t):new Np(t):new Np(t)}async enableInjector(e){this.injector&&this.logger.warn("Control injector already present when enabling injector");try{this.injector=this.createInjector(e)}catch(e){throw this.logger.error(`Control injector creation failed: ${e}`),e}this.pendingPointerImages.forEach(((e,t)=>{this.injector.setAvatar(t,e)})),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(e,t){this.injector?this.injector.setAvatar(e,t):this.pendingPointerImages.set(e,t)}async showVirtualCursor(e){if(this.logger.info(`showVirtualCursor ${e} ${this.activeSourceId}`),!this.injector)throw new Error("Control injector not present");e?(this.activeSourceId&&this.injector.showVirtualCursor(this.activeSourceId,!1),this.injector.showVirtualCursor(e,!0),this.activeSourceId=e):this.activeSourceId&&(this.injector.showVirtualCursor(this.activeSourceId,!1),this.activeSourceId=0)}async injectRawInput(e,t){if(!this.injector)throw new Error("Control injector not present");const i=this.injector;return new Promise(((n,r)=>{let s,a;const o=Vg.decodeEventType(e);switch(o){case 1:s=Vg.decodeMouseEvent(e),i.injectMouseEvent(t,s).then((e=>0===e?n():r()));break;case 0:a=Vg.decodeKeyboardEvent(e),i.injectKeyboardEvent(t,a).then((e=>0===e?n():r()));break;default:this.logger.error(`Invalid event type in raw input: ${o}`),r()}}))}},kp=class extends Dp{constructor(e){super(e.createChild("EdgeControlInjector")),this.edgeVirtualInputSupported=!1,async function(e){return new Promise(((t,i)=>{e.info("EdgeControlInjectorApi - sendIsVirtualInputSupportedMessage");const n=window.top;n.chrome.runtime.sendMessage(Ep,{api:"isVirtualInputSupported"},(e=>{e?e.error?t(e.error.message):t(e):i(n.chrome.runtime.lastError?.message)}))}))}(e).then((t=>{this.edgeVirtualInputSupported=t,e.info(`Edge supports virtual input device: ${JSON.stringify(this.edgeVirtualInputSupported)}`)})).catch((t=>{e.info(`Edge IsVirtualInputSupported: ${JSON.stringify(t)}`)}))}canBeEnabled(){return this.edgeVirtualInputSupported}createInjector(e){if(!this.edgeVirtualInputSupported)return void this.logger.info("Edge doesn't support give control");const t=new _p(this.logger,e,(()=>{this.logger.error("An error occured, disabling control injector."),this.disableInjector()}));return this.logger.info("Edge ControlInjector created"),t}},Op=class extends Dp{constructor(e){super(e.createChild("WindowControlInjector"))}canBeEnabled(){return!!window.ControlInjector}createInjector(e){const t=window.ControlInjector(e);return this.logger.info("Window ControlInjector created"),t}},Np=class extends Dp{constructor(e){super(e.createChild("NoopControlInjector"))}canBeEnabled(){return!1}createInjector(){throw new Error("Control injector creation is disabled")}},Lp=class{constructor(e){this.logger=e,this.logger.info("RendererAdapter")}getTarget(e){return e.target}subscribeVideoSizeChangedEvent(e,t){const i=e;return i.streamSize&&t(i.streamSize.width,i.streamSize.height),i.renderer.on("onVideoSizeChanged",t)}subscribeRenderStartedEvent(e,t){return e.renderer.on("onVideoStarted",((e,i)=>t()))}},xp=class extends gt{constructor(e,t){super(e),this.logger=e,this._call=t}isActive(){return!(!this.protocolSendFunc||!this.controlSendFunc)}sendProtocolMessage(e,t){return this.protocolSendFunc?this.protocolSendFunc(e,t):(this.logger.error("Cannot send protocol message, ProtocolHandler hasn't started"),Promise.resolve())}sendControlMessage(e,t){return this.controlSendFunc?this.controlSendFunc(e,t):(this.logger.error("Cannot send control message, ControlHandler hasn't started"),Promise.resolve())}getProtocolHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ProtocolHandler started for ${e}`),this.protocolSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ProtocolHandler stopped for ${e}`);const t=this.isActive();this.protocolSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(1===e){const e=JSON.parse(function(e){return String.fromCharCode.apply(null,e)}(t)),n=this._call.mapDataChannelSourceIdToParticipant(i);let r;return n&&(r=Bd(n,3,i)),this.event("protocolMessage").raise(e.message,n,r,i)}}}}getControlHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ControlHandler started for ${e}`),this.controlSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ControlHandler stopped for ${e}`);const t=this.isActive();this.controlSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(2===e)return this.event("controlMessage").raise(t,i)}}}},Fp=class extends dp{constructor(e,t,i,n,r,s){const a={disableAudit:r.getEcsConfig("SkypeCalling","gtcAuditDisabled")??!1},o=r.getEcsConfig("SkypeCalling","gtcHandshakeSendDelay");if(o)try{a.handshakeSendDelay=JSON.parse(o)}catch(t){e.error(`Failed to parse ecs config gtcAvailableAckDelay: ${tt(t)}`)}super(e.createChild("ScreenSharingControl"),i,n,a),this.dataChannel=t;const l=Dp.create(s,e),c=new Lp(this._logger),d=new xp(this._logger,i);this.setAdapters(l,c,d)}setupDataHandlers(){this.dataChannel.addHandler(1,this.getProtocolHandler()),this.dataChannel.addHandler(2,this.getControlHandler())}startOrStopControlForViewer(e,t,i){if(e&&"nonInteractive"!==i?.appliedInteractivityLevel){if(t&&0===this.role){const e=t.streams[1].find((e=>e.isAvailable))?.negotiationTag;this.initControlForViewer(t,e)}}else 2===this.role&&this.shutdownControlForViewer()}getProtocolHandler(){return this._dataChannelAdapter.getProtocolHandler()}getControlHandler(){return this._dataChannelAdapter.getControlHandler()}};function Up(e){switch(e){case 1:return"specified";case 0:return"all";case 3:return"attendees";case 2:return"presenters";case 4:return"self";default:return"none"}}var Bp={};h(Bp,{addReceiveDirectionality:()=>Jp,allowDataChannel:()=>mm,areNegotiatedDirectionsAcceptable:()=>Xp,areNegotiatedDirectionsFulfilled:()=>em,areSendDirectionsFulfilled:()=>tm,canUseWebrtc1_0:()=>pm,convertToCodecInfo:()=>vm,getAllowedCodecs:()=>fm,getSrtpInfo:()=>im,hasReceiveDirectionality:()=>Kp,hasSendDirectionality:()=>Wp,invertModalities:()=>qp,ipAddressConverter:()=>ym,ipV4RegExp:()=>Hp,ipV6RegExp:()=>$p,ipv4AddressConverter:()=>Tm,ipv6AddressConverter:()=>Cm,isOnHold:()=>Yp,mediaTypeToModality:()=>am,modalityToMediaType:()=>sm,negotiateDirectionality:()=>Gp,negotiateModalities:()=>Qp,parseCandidateString:()=>rm,preferSdesSrtp:()=>gm,printMediaStream:()=>Sm,removeChangedSendDirection:()=>nm,removeSendDirectionality:()=>zp,scrubConstraints:()=>hm,scrubDevices:()=>um,scrubObjectExcludingFields:()=>cm,scrubObjectFields:()=>lm,scrubSelectedDevices:()=>dm,sendStreamsToModalities:()=>om,shouldDisableAudioSendersTroughSetParams:()=>bm,shouldDisableVideoSendersTroughSetParams:()=>Em});var Vp=class e extends Vi{constructor(e){super(),this.isAudioOutputSelectionSupportedValue=!1,e.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===Gi.MEDIA_ERROR.webGlRendererError?void 0:this.renderer;try{const e=document.createElement("canvas").getContext("webgl"),t=e?.getExtension("WEBGL_debug_renderer_info"),i=t&&e.getParameter(t.UNMASKED_RENDERER_WEBGL);return this.renderer=i,i}catch{return void(this.renderer=Gi.MEDIA_ERROR.webGlRendererError)}}async isRollbackSupported(){let e;try{if(e=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection({sdpSemantics:"unified-plan"}),e){const t=await e.createOffer();await e.setLocalDescription(t),await e.setLocalDescription({type:"rollback"}),this.isRollbackSupportedValue=!0}}catch(e){this.isRollbackSupportedValue=!1}finally{e?.close()}}static async isCodecsSupported(e){const t={format:"annexb"},i=["no-preference","prefer-software","prefer-hardware"],n=[];for(const r of e)for(const e of i){const i=await(window.VideoEncoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t,width:1280,height:720})),s=await(window.VideoDecoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t}));if(i||s){const e={name:r,mode:i?.config.hardwareAcceleration,encode:i?.supported,decode:s?.supported};n.push(e)}}return n}static async hasH264CodecSupport(e){const t="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",i=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection;if(!i)return!1;try{return await i.setRemoteDescription({sdp:"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",type:"offer"}),!0}catch(t){return e.error("H264 not supported",t),!1}finally{try{i.close()}catch(e){}}}static hasMediaApi(){return navigator.getUserMedia&&"undefined"!=typeof RTCPeerConnection}static hasCapabilitiesApi(){return!!Mp.window.RTCRtpReceiver?.getCapabilities}static isAudioOutputSelectionSupportedByBrowser(){return!!Mp.window?.HTMLAudioElement?.prototype.setSinkId}updateConfig(){const t=e.isAudioOutputSelectionSupportedByBrowser();t!==this.isAudioOutputSelectionSupportedValue&&(this.isAudioOutputSelectionSupportedValue=t,this.event("isAudioOutputSelectionSupportedChanged").raise())}static hasUnifiedPlanSupport(){let e;try{e=Mp.window.RTCPeerConnection&&new Mp.window.RTCPeerConnection({sdpSemantics:"unified-plan"})}catch(e){return!1}let t=!1;return e&&(t=!!e.addTransceiver,e.close()),t}static hasEncodedStreamsApi(){return!!RTCRtpReceiver.prototype.createEncodedStreams||e.hasScriptTransformApi()}static hasScriptTransformApi(){return!!window.RTCRtpScriptTransform}static isWakeLockSupported(){return!!window.navigator.wakeLock}},Hp=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})?$/),$p=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 jp(e){switch(e){case Gi.MEDIA_STATE.send:return Gi.MEDIA_STATE.receive;case Gi.MEDIA_STATE.receive:return Gi.MEDIA_STATE.send;default:return e}}function Gp(e,t){const i=Wp(e)&&Wp(t),n=Kp(e)&&Kp(t);return i&&n?Gi.MEDIA_STATE.sendReceive:i?Gi.MEDIA_STATE.send:n?Gi.MEDIA_STATE.receive:e===Gi.MEDIA_STATE.inactive&&t||e&&t===Gi.MEDIA_STATE.inactive?Gi.MEDIA_STATE.inactive:void 0}function qp(e){const t={},i=jp(e.audio);i&&(t.audio=i);const n=jp(e.video);n&&(t.video=n);const r=jp(e.sharing);r&&(t.sharing=r);const s=jp(e.data);return s&&(t.data=s),t}function zp(e){return e===Gi.MEDIA_STATE.sendReceive?Gi.MEDIA_STATE.receive:void 0}function Wp(e){return e===Gi.MEDIA_STATE.send||e===Gi.MEDIA_STATE.sendReceive}function Kp(e){return e===Gi.MEDIA_STATE.receive||e===Gi.MEDIA_STATE.sendReceive}function Jp(e){return Kp(e)?e:e===Gi.MEDIA_STATE.send?Gi.MEDIA_STATE.sendReceive:Gi.MEDIA_STATE.receive}function Yp(e){return!(e.audio!==Gi.MEDIA_STATE.inactive||e.video&&e.video!==Gi.MEDIA_STATE.inactive||e.sharing&&e.sharing!==Gi.MEDIA_STATE.inactive)}function Qp(e,t){const i={},n=Gp(e.audio,t.audio);n&&(i.audio=n);const r=Gp(e.video,t.video);r&&(i.video=r);const s=Gp(e.sharing,t.sharing);s&&(i.sharing=s);const a=Gp(e.data,t.data);return a&&(i.data=a),i}function Zp(e,t,i,n){const r=Wp(t)&&Wp(i)||!Wp(t)&&!Wp(n);let s=!n||Kp(t)&&Kp(i)||!Kp(t)&&!Kp(n);return e.config.fixExtraNegotiation&&(s=s||Kp(t)&&!Kp(i)&&!Kp(n)),r&&s}function Xp(e,t,i,n){return Zp(e,t.audio,i.audio,n.audio)&&Zp(e,t.video,i.video,n.video)&&Zp(e,t.sharing,i.sharing,n.sharing)&&Zp(e,t.data,i.data,n.data)}function em(e,t){function i(e,t){const i=Wp(e)===Wp(t),n=Kp(e)===Kp(t)||Kp(e)&&!t;return i&&n}return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function tm(e,t){const i=(e,t)=>Wp(e)===Wp(t);return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function im(e){const t={dtls:!1,sdes:!1};return t.dtls=!!e.fingerprint,e.media.forEach((e=>{t.dtls=t.dtls||!!e.fingerprint,t.sdes=t.sdes||!!e.crypto})),t}function nm(e,t){if(!t||Xi(t))return e;const i={};return qi(e,((e,n)=>{n===Gi.MODALITY.data?i[n]=function(e,t){return Wp(e)&&!Wp(t)?t:e}(e,t[n]):i[n]=function(e,t){return Wp(e)&&!Wp(t)?zp(e)||t:e}(e,t[n])})),i}function rm(e){const t=(e||"").split(" ");return{component:t[1],protocol:t[2],priority:t[3],ip:t[4],port:t[5],type:t[7]}}function sm(e){switch(e){case"audio":return"Audio";case"video":return"Video";case"sharing":return"ScreenShare";default:return null}}function am(e){switch(e){case"Audio":return"audio";case"Video":return"video";case"ScreenShare":return"sharing";default:return null}}function om(e){const t={};return en(e).forEach((i=>t[i]=!!e[i])),t}function lm(e,t,i){if(!e)return e;const n={...e};for(const[r,s]of Object.entries(e))"object"==typeof s?n[r]=lm(s,t):s&&t.includes(r)&&(n[r]=i?i(s):De(s));return n}function cm(e,t,i){if(!e)return e;const n={...e};for(const[r,s]of Object.entries(e))"object"==typeof s?n[r]=cm(s,t):s&&!t.includes(r)&&(n[r]=i?i(s):De(s));return n}function dm(e){return e?cm(e,[]):e}function um(e,t){if(!e)return e;const i=lm(e,["deviceId","groupId","guid"]);return lm(i,["label"],(e=>fn(e,t)))}function hm(e){return lm(e,["sourceId","deviceId"])}function gm(e,t){return!(!e.config.webrtcForceSdesForS1||!e.config.checkSupportForWebrtc_1_0||e.mediaConfig.simulcastSessionEnabled)||(t?e.config.preferSdesSrtpPstn:e.config.preferSdesSrtp)}function pm(e){return!e||Vp.hasUnifiedPlanSupport()}function mm(e){return!!e.configProvider.mediaConfig.simulcastSessionEnabled&&(e.config.isPstnCall?e.configProvider.config.enableDataChannelPstn:e.configProvider.config.enableDataChannel)}function fm(e,t){switch(t){case Gi.MEDIA_TYPE.audio:return e.config.allowedAudioCodecs;case Gi.MEDIA_TYPE.video:return e.config.allowedVideoCodecs;default:return[]}}function vm(e){return e.map((e=>{const t={codec:e.mimeType.split("/").pop(),rate:e.clockRate};return e.channels&&(t.encoding=e.channels),e.sdpFmtpLine&&(t.fmtpLine=e.sdpFmtpLine),t}))}function Sm(e){return`${e?.id}:${JSON.stringify(e?.getTracks().map((e=>e.id)))}}`}function ym(e){try{if(Hp.test(e))return Tm(e);if($p.test(e))return Cm(e)}catch(t){return e}return e}function Cm(e){let t,i=e.lastIndexOf("]")+1,n="",r="";i>0?(t=e.substring(0,i),r=e.substring(i)):(t=e,i=t.length);const s=t.lastIndexOf(":");if(t.includes(".")){const e=Tm(t.substring(s+1,i-1-s));n=t.substring(0,s+1)+e}else s<t.length-1||":"===t[s-1]&&t.match(/:/g).length<7?n=t.substring(0,s+1)+"x":7===t.match(/:/g).length&&(n=t.substring(0,s)+"0:x");return n?r?n+"]"+r:"["===e.substring(0,1)?(n=n.substring(1),n):n:e}function Tm(e){const t=e.substring(0,e.lastIndexOf(".")+1)+"x",i=e.lastIndexOf(":");return i>0?t+e.substring(i):t}function Em(e,t,i){return!(!t&&!i)&&(i?e.config.disableSendersTroughSetParametersVideo&&(i===Gi.MODALITY.sharing||i===Gi.MODALITY.video):e.config.disableSendersTroughSetParametersVideo&&("Video"===t.mediaType||"ScreenShare"===t.mediaType))}function bm(e,t){return e.config.disableSendersTroughSetParametersAudio&&"Audio"===t.mediaType}var _m=Z,Im=Z,wm={maxOutgoingResolution:({settings:e})=>Mm(e),maxParticipantResolutions:({settings:e})=>Rm(e),maxIncomingStreams:({settings:e})=>km(e),maxSimulcastLayers:({settings:e})=>Om(e),outgoingVideoLimit:({settings:e,constraints:t})=>Dm(e,t)},Am=(e,t,i)=>(e.info(`Converting settings to constraints and mapping, [requestedConstraints=${JSON.stringify(i)}], [settings=${JSON.stringify(t)}]`),Pm((0,Im.cloneDeep)(i),(0,Im.cloneDeep)(t))),Pm=(e,t)=>Object.keys(e).reduce(((i,n)=>{const r=wm[n]?wm[n]({constraints:e,settings:t}):void 0;return r&&(i[n]=r),i}),{}),Rm=e=>e.multiviewResolutionLimits,Mm=e=>e.outgoingVideoLimit?.maxResolution,Dm=(e,t)=>{const i=t?.outgoingVideoLimit;if(!i)return;const{outgoingVideoLimit:n={}}=nn(e);if("number"==typeof i)return n?.maxResolution;const r=Object.keys(i).reduce(((e,t)=>{const i=n?.[t];return i&&(e[t]=i),e}),{});return Object.keys(r).length?r:void 0},km=e=>e.numVideoChannelsGvc,Om=e=>{const t=e.specCompliantSimulcast,i=t.video?.layerScaleFactors,n=t.sharing?.layerScaleFactors,r=i?.length?Math.max(...i):1,s=n?.length?Math.max(...i):1;return Math.min(r,s)},Nm=Z,Lm={maxIncomingStreams:Nm.isNumber,maxSimulcastLayers:Nm.isNumber,maxOutgoingResolution:Nm.isNumber,maxParticipantResolutions:e=>!!Wi(e)&&(!!(0,Nm.isNumber)(e)||"more"in e&&Object.values(e).every((e=>(0,Nm.isNumber)(e)))),outgoingVideoLimit:e=>!!Wi(e)&&(e=>!!(0,Nm.isNumber)(e)||!!(e=>{const t=["maxResolution","maxBitrate","maxFramerate"],i=e=>t.includes(e),n=Object.entries(e);return 0!==n.length&&n.every((([e,t])=>(0,Nm.isNumber)(t)&&i(e)))})(e)&&!Xi(e))(e)};function xm(e,t){if(Array.isArray(e))return t.slice()}var Fm=(e,t)=>{for(const i in t){const n=e[i],r=t[i];e[i]="object"==typeof r?Fm({...n},r):Ki(n,r)}return e},Um=class{constructor(e,t,i,n,r,s,a){this.logger=e,this.defaultSettings=t,this._mediaConfig=i,this._userAgentConfig=n,this._countryCode=r,this.platformCallConstraintsProvider=s,this.currentCallConstraints=a,this.mergedConstraints={},this.callConstraintsTelemetry=[],this.iceTransportPolicy=Gi.ICE_TRANSPORT_POLICY.all,this.validIceTransportPolicies=[Gi.ICE_TRANSPORT_POLICY.all,Gi.ICE_TRANSPORT_POLICY.relay],this.mergeConstraintsTelemetryWithGlobal(),this.mergedConstraints=this.mergeConstraintsWithGlobal(this.currentCallConstraints),this.settings=this.mergeSettings((0,_m.cloneDeep)(this.defaultSettings))}get config(){return this.settings}get mediaConfig(){return this._mediaConfig}get userAgentConfig(){return this._userAgentConfig}get countryCode(){return this._countryCode}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};Sn(this.callConstraintsTelemetry,i,this.config.numCallConstraintsEvents)}getCallConstraintsTelemetry(){return this.callConstraintsTelemetry}getCallConstraints(){return this.mergedConstraints}setCallConstraints(e={}){this.addCallConstraintsTelemetryEvent(e,"requested"),this.logger.safe.debug("Saving new call constraints",JSON.stringify(e));const t=this.transformConstraints((e=>(e=JSON.parse(JSON.stringify(e)),Object.entries(Lm).reduce(((t,[i,n])=>(n(e[i])&&(t[i]=e[i]),t)),{})))(e));return this.logger.safe.debug("Validated call constraints",JSON.stringify(t)),this.mergedConstraints=this.mergeConstraintsWithGlobal(t),this.settings=this.mergeSettings((0,_m.cloneDeep)(this.defaultSettings)),Am(this.logger,this.settings,t)}getIceTransportPolicy(){return this.settings.iceTransportPolicyForced||this.iceTransportPolicy}setIceTransportPolicy(e){this.validIceTransportPolicies.includes(e)?(this.logger.info(`Setting transport policy to ${this.iceTransportPolicy}`),this.iceTransportPolicy=e):this.logger.debug(`Unknown incoming transport policy, using ${this.iceTransportPolicy}`)}overrideMaxSessionBandwidth(e){return this.defaultSettings.maxBandwidthInKbps!==e&&(this.defaultSettings.maxBandwidthInKbps=e,this.settings.maxBandwidthInKbps=e,this.mediaConfig.maxBandwidthInKbps=e,!0)}transformConstraints(e){const t=(0,_m.cloneDeep)(e);return"maxOutgoingResolution"in t&&(t.outgoingVideoLimit={maxResolution:t.maxOutgoingResolution},delete t.maxOutgoingResolution),"number"==typeof t.outgoingVideoLimit&&(t.outgoingVideoLimit={maxResolution:t.outgoingVideoLimit}),t}mergeConstraintsTelemetryWithGlobal(){this.platformCallConstraintsProvider.callConstraintsTelemetry.forEach((e=>Sn(this.callConstraintsTelemetry,e,this.defaultSettings.numCallConstraintsEvents)))}mergeConstraintsWithGlobal(e={}){const t=this.transformConstraints(this.platformCallConstraintsProvider.constraints);if(!Object.keys(t).length)return e;const i=(0,_m.cloneDeep)(e);return Fm(i,t),this.logger.safe.debug(`Merging call constraints ${JSON.stringify(e)} and global constraints ${JSON.stringify(t)}. Result: ${JSON.stringify(i)}`),i}mergeSettings(e){if(!e.enablePlatformCallConstraints||!e.enablePlatformCallConstraintsPerCall)return e;const t=qn(this.logger,e,this.mergedConstraints);return this.logger.safe.info(`Merging settings with platform call constraints: ${tt(t)}`),(0,_m.assign)({},e,t,xm)}},Bm=Z,Vm=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing],Hm=class{constructor(e,t,i,n,r){this.peerConnection=t,this.mediaManager=i,this.reinvitelessContext=r,this.entityTransceiverMap=new Map,this.logger=e.createChild("TM"),this.configProvider=n.configProvider,this.isMultiparty=n.config.isConference,this.isPstnCall=n.config.isPstnCall,this.isParkedCall=n.config.isParkedCall,this.numVideoChannels=this.isMultiparty&&this.configProvider.config.numVideoChannelsGvc||1,n.configProvider.config.enableRollbackHandler&&this.mediaManager.setRollbackUpdateHandler(this.handleMediaEntitiesRollback.bind(this))}getTransceivers(){return this.peerConnection.getTransceivers().filter(Gm)}assureTransceivers(e){this.assureNegotiatedOrder(),this.addModalities(e),this.logTransceiversInfo("assureTransceivers"),this.setDirections(e)}syncTransceivers(e){this.syncWithMediaEntities(),this.setDirections(e)}assureNegotiatedOrder(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{-1!==Vm.indexOf(t.getModality())&&(qm(this.entityTransceiverMap.get(t),e)||this.createTransceiverForEntity(t))}))}addModalities(e){const t=this.mediaManager.isEmpty();this.isMultiparty||!t||this.isPstnCall||(e.video=e.video||"inactive",e.sharing=e.sharing||"inactive"),this.configProvider.config.webrctRemoveVideoModalitiesForPstn&&this.isPstnCall&&!this.isParkedCall&&(delete e.video,delete e.sharing);for(const i of Vm){if(this.mediaManager.getMediaEntitiesByModality(i)[0]||!e[i])continue;const n=i===Gi.MODALITY.video?this.numVideoChannels:1;(0,Bm.times)(n,(e=>{const n=this.mediaManager.createMediaEntity(i);n.setExtension("reinviteless",t&&this.reinvitelessContext.maxStreamsForModality[i]>e),this.createTransceiverForEntity(n)}))}}createTransceiverForEntity(e){const t=e.getModality();this.logger.safe.info(`createTransceiver: modality=${t}`);const i=t===Gi.MODALITY.audio?Gi.MEDIA_TYPE.audio:Gi.MEDIA_TYPE.video,n=e.getSimulcastContext(),r=this.createTransceiver(i,n);this.setCodecPreferences(r,i,!0),this.setExtensionPreferences(r,t),this.entityTransceiverMap.set(e,r),e.setExtension("unnegotiatedModality",!0)}setCodecPreferences(e,t,i){const n=fm(this.configProvider,t);if(!n?.length||!Vp.hasCapabilitiesApi()||this.configProvider.config.filterCodecsInSdp)return;const r=Mp.window.RTCRtpReceiver.getCapabilities(t);if(!r)return;const s=[];if(i)for(const e of n){const t=r.codecs.filter((t=>$m(e,t)));s.push(...t)}else for(const e of r.codecs)n.some((t=>$m(t,e)))&&s.push(e);s.length&&e.setCodecPreferences&&e.setCodecPreferences(s)}setExtensionPreferences(e,t){if(!this.configProvider.config.headerExtensionsToUpdate?.[t])return;if(!e.getHeaderExtensionsToNegotiate||!e.setHeaderExtensionsToNegotiate)return void this.logger.safe.debug("setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate is not supported");const i=this.configProvider.config.headerExtensionsToUpdate[t],n=e.getHeaderExtensionsToNegotiate();for(const e of n){const t=i.find((t=>t.uri===e.uri));t&&(e.direction=t.direction)}try{e.setHeaderExtensionsToNegotiate(n)}catch(e){this.logger.safe.error(`setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate failed, err ${tt(e)}`)}}async createSender(e,t,i){const n=await this.associateTrackWithTransceiver(e,t,i);if(!n)throw new Error(`Transceiver for modality=${i} is not found`);const r=this.findEntityForTransceiver(n),s=i!==Gi.MODALITY.sharing||r?.getExtension("reinviteless")?Gi.MEDIA_STATE.sendReceive:Gi.MEDIA_STATE.send;return n.direction=s,this.logger.safe.info(`Replace track completed direction:${n.direction} for transceiver mid=${n.mid}`),n.sender}removeSender(e){this.removeSenderInternal(e,!1)}async removeSenderAsync(e){return this.removeSenderInternal(e,!0)}removeSenderInternal(e,t){if("closed"===(this.peerConnection.connectionState||this.peerConnection.iceConnectionState))return void this.logger.safe.info("Not removing sender from pc, connection is closed");const i=this.getTransceivers().find((t=>t.sender===e));if(!i)throw new Error(`Transceiver for sender with track=${e.track?.id} is not found`);const n=this.findEntityForTransceiver(i),r=!!n?.getExtension("reinviteless");this.logger.safe.info(`Remove sender with track=${e.track?.id} for transceiver mid=${i.mid}, reinviteless=${r}, doAsync=${t}`);let s=Promise.resolve();return r&&t?s=i.sender.replaceTrack(null):this.peerConnection.removeTrack(e),t?s:void 0}createTransceiver(e,t){const i={direction:"inactive"};return this.addSimulcastEnvelopeIfNeeded(i,t),this.peerConnection.addTransceiver(e,i)}addSimulcastEnvelopeIfNeeded(e,t){t?.shouldUseSimulcast()&&(e.sendEncodings=(0,Bm.times)(t.config.layerScaleFactors.length,(e=>{const i={rid:`${t.ridList[e]}`,scaleResolutionDownBy:t.config.layerScaleFactors[e]};if(this.configProvider.config.specCompliantSimulcast?.disableTilde&&(i.active=!1),t.config.layerScalabilityModes?.length>0){const n=t.config.layerScalabilityModes[e];void 0!==n&&n.length>0?i.scalabilityMode=n:this.logger.safe.warn(`Scalability mode was not set for rid: ${i.rid}`)}return this.logger.safe.debug(`Added layer ${e} with rid: ${i.rid} SF: ${i.scaleResolutionDownBy} SM: ${i.scalabilityMode}`),i})))}async associateTrackWithTransceiver(e,t,i){const n=this.findAvailableTransceiverToSend(i);if(n){this.logger.safe.info(`Associate track=${e?.id} (${i}) with existing transceiver mid=${n.mid}`);try{if(this.isMultiparty&&Em(this.configProvider,void 0,i)){this.logger.safe.info(`Disabling encodings for transceiver mid=${n.mid}`);const e=n.sender.getParameters();e.encodings.forEach((e=>e.active=!1)),await n.sender.setParameters(e)}await n.sender.replaceTrack(e),this.configProvider.config.useSetStreamsForSender&&n.sender.setStreams&&n.sender.setStreams(t)}catch(e){throw this.logger.safe.error(`replaceTrack failed, err ${JSON.stringify(e)}`),e}return n}return null}syncWithMediaEntities(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{let i=this.entityTransceiverMap.get(t);i=qm(i,e)?i:e.find((e=>e.mid===t.getMid())),this.entityTransceiverMap.set(t,i)})),this.logTransceiversInfo("syncWithMediaEntities")}getTransceiversByModality(e){return this.mediaManager.getMediaEntitiesByModality(e).map((e=>this.entityTransceiverMap.get(e))).filter(Gm)}setDirections(e){const t=!Yp(e);for(const i of Vm)for(const[n,r]of this.getTransceiversByModality(i).entries()){const s=this.findEntityForTransceiver(r);if(s?.getExtension("reinviteless")&&t){r.direction="sendrecv";continue}const a=e[i]||Gi.MEDIA_STATE.inactive;r.direction=0===n&&r.currentDirection?a:jm(a)}this.logTransceiversInfo("setDirections")}handleMediaEntitiesRollback(e,t){e.forEach((e=>{const i=this.entityTransceiverMap.get(e),n=t.find((t=>t.getMid()===e.getMid()));this.entityTransceiverMap.set(n,i)})),this.logTransceiversInfo("handleMediaEntitiesRollback")}findAvailableTransceiverToSend(e){const t=this.mediaManager.getMediaEntitiesByModality(e)[0];return this.entityTransceiverMap.get(t)}findEntityForTransceiver(e){for(const[t,i]of this.entityTransceiverMap)if(i===e)return t}logTransceiversInfo(e){let t=`${e}: transceivers details:`;for(const e of Vm){const i=this.getTransceiversByModality(e);t+=` ${e}(${i.length}) [${i.map((e=>`mid=${e.mid}, direction=${e.direction}`)).join(";")}]`}this.logger.safe.debug(t)}};function $m(e,t){return!(!(0,Bm.isUndefined)(e.channels)&&e.channels!==t.channels||!(0,Bm.isUndefined)(e.clockRate)&&e.clockRate!==t.clockRate||!(0,Bm.isUndefined)(e.mimeType)&&e.mimeType.toLowerCase()!==t.mimeType.toLowerCase()||!(0,Bm.isUndefined)(e.sdpFmtpLine)&&-1===t.sdpFmtpLine.toLowerCase().indexOf(e.sdpFmtpLine.toLowerCase()))}function jm(e){let t=e;return Wp(e)&&(t=zp(e)),t||Gi.MEDIA_STATE.inactive}function Gm(e){return e&&"stopped"!==e.direction&&!e.stopped}function qm(e,t){return Gm(e)&&-1!==t.indexOf(e)}var zm=class extends Vi{constructor(e,t,i){super(),this.configProvider=e,this.workerProvider=t,this.logger=i,this.transformsCollections=new Map}async initialize(){return this.configProvider.config.useInsertableStreams&&this.workerProvider&&Vp.hasEncodedStreamsApi()&&(this.worker=new mf(this.workerProvider,this.logger)),this.worker?this.worker.initialize():Promise.resolve()}initTransformsCollection(e,t,i){const n=Vp.hasScriptTransformApi()||this.workerProvider;if(!this.configProvider.config.useInsertableStreams||!Vp.hasEncodedStreamsApi()||n&&!this.isWorkerLoaded()||null===e.track)return null;if(!this.transformsCollections.has(e)){const n=this.worker?new Km(this.worker,e):new Wm(e);this.transformsCollections.set(e,{collection:n,mediaType:i,objType:t})}const r=this.transformsCollections.get(e);return this.event("onTransformsCollectionCreated").raise(r),r.collection}clearTransformsCollection(e){const t=this.transformsCollections.get(e);t&&(this.event("onTransformsCollectionCleared").raise(t),t.collection.clearTransforms())}dispose(){for(const e of this.transformsCollections.values())this.event("onTransformsCollectionCleared").raise(e),e.collection.clearTransforms();this.transformsCollections.clear(),this.worker?.dispose(),super.dispose()}isWorkerLoaded(){return!!this.worker?.isWorkerLoaded()}},Wm=class{constructor(e){const{readable:t,writable:i}=e.createEncodedStreams();this.streamTransformer=new Ef(t,i)}addTransform(e){e.createBaseInstance(this.streamTransformer)}clearTransforms(){this.streamTransformer.clearTransforms()}},Km=class{constructor(e,t){if(this.workerHandler=e,this.clientId=t.track.id,Vp.hasScriptTransformApi())return void(t.transform=new RTCRtpScriptTransform(this.workerHandler.worker,{clientId:this.clientId}));const{readable:i,writable:n}=t.createEncodedStreams(),r=[i,n];this.workerHandler.sendTransformCommand(this.clientId,{operation:"init",readable:i,writable:n},r)}addTransform(e){e.createWorkerInstance(this.workerHandler,this.clientId)}clearTransforms(){this.workerHandler.sendTransformCommand(this.clientId,{operation:"clear"})}},Jm=class{constructor(e,t=!1){this.logger=e,this.disabled=t,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(e){this.disabled=!1,this.mixerImp?.setupMixer(this.audioContext,this.destination,e)}setMixerType(e,t){this.mixerImp?.mixerType!==e&&(this.mixerImp?.reset(),this.mixerImp=this.createMixer(e),this.disabled||this.mixerImp.setupMixer(this.audioContext,this.destination,t))}setStreamSources(e){this.disabled||this.mixerImp.setStreamSources?.(e)}setParticipantSpatialAudioPositions(e){this.mixerImp.setParticipantSpatialAudioPositions?.(e)}createMixer(e){switch(e){case 0:return new Qm;case 1:return new Zm(this.logger.createChild("MixingStreamsMixer"));case-1:return new Ym;default:throw new Error(`unknown mixer type: ${e}`)}}},Ym=class{constructor(){this.mixerType=-1}reset(){}setupMixer(e,t,i){}},Qm=class{constructor(){this.mixerType=0}reset(){this.sourceNode.disconnect()}setupMixer(e,t,i){this.sourceNode=e.createMediaStreamSource(i[0]),this.sourceNode.connect(t)}},Zm=class{constructor(e){this.logger=e,this.sourcePositions=new Map,this.sourceNodes=[],this.pannerNodes=[],this.mixerType=1}reset(){this.logger.safe.info("resetting SpatialMultiStreamMixer");for(const e of this.sourceNodes)e.disconnect();this.sourceNodes=[];for(const e of this.pannerNodes)e.disconnect();this.pannerNodes=[]}setupMixer(e,t,i){(this.sourceNodes.length||this.pannerNodes.length)&&this.reset();for(const n of i){const i=e.createMediaStreamSource(n),r=new PannerNode(e,{panningModel:"HRTF"});i.connect(r),r.connect(t),this.sourceNodes.push(i),this.pannerNodes.push(r)}this.logger.safe.info(`setupMixer is done for ${i.length} streams.`)}setStreamSources(e){for(let t=0;t<e.length;t++)this.setStreamPosition(t,e[t])}setParticipantSpatialAudioPositions(e){this.sourcePositions=new Map(e.map((e=>[e.sourceId,e])))}setStreamPosition(e,t){const i=this.sourcePositions.get(t)??{sourceId:t,x:0,y:0},n=this.pannerNodes[e];n?(n.positionX.value=i.x,n.positionY.value=i.y):this.logger.warn(`panner node for stream ${e} is not found`)}},Xm=class extends Vi{constructor(e){super(),this.logger=e,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(e,t){this.logger.safe.debug(`setup ${e} streams with extra Comfort Noise stream: ${t}`),this.mediaStreams=[];const i=[];for(;e--;){const e=new MediaStreamTrackGenerator({kind:"audio"});i.push(e),this.streams.push(new MediaStream([e]))}const n=t?new MediaStreamTrackGenerator({kind:"audio"}):null;return this.cnStream=n?new MediaStream([n]):null,this.event("onStreamsChanged").raise(),{streams:i.map((e=>e.writable)),cnStream:n?.writable}}setStreamSources(e){this.isNegotiated&&this.event("onStreamSourcesUpdated").raise(e)}setConfiguredState(e){this.isConfigured!==e&&(this.isConfigured=e,this.event("onConfiguredStateChanged").raise(this.isConfigured))}setNegotiatedState(e){this.isNegotiated!==e&&(this.isNegotiated=e,this.event("onActiveStateChanged").raise(this.isNegotiated))}setDetectedCodec(e){this.activeCodec!==e&&(this.activeCodec=e,this.event("onActiveCodecChanged").raise(this.activeCodec))}},ef=class e{constructor(){this.context=new AudioContext({sampleRate:5e4})}dispose(){this.context.close()}createTimerPort(){return new AudioWorkletNode(this.context,"encodedStreamsWorklet",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[1]}).port}static async create(t){const i=new e;return await i.context.audioWorklet.addModule(t),i}},tf={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}},nf=class{constructor(e,t,i,n){this.worker=e,this.clientId=t,this.transformType=i,this.listener=n,this.worker.subscribeClient(this.clientId,this.transformType,(e=>this.processMsg(e))),this.worker.sendTransformCommand(this.clientId,{operation:"add",transformType:this.transformType})}dispose(){this.worker.unsubscribeClient(this.clientId),this.worker.sendTransformCommand(this.clientId,{operation:"clear"})}processMsg(e){if(this.listener&&e.name in this.listener)return this.listener[e.name].apply(this.listener,e.args);throw`unexpected message received for transform type ${this.transformType}: ${JSON.stringify(e)}`}},rf=class extends nf{constructor(e,t,i){super(e,t,2,i)}init(e,t){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e,t]}})}setTimerWorkletPort(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setTimerWorkletPort",args:[e]}},[e])}setCodec(e,t){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e,t]}})}passWriteableStreams(e,t){const i=e.concat(t);this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"passWriteableStreams",args:[e,t]}},i)}setAvailableStreams(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setAvailableStreams",args:[e]}})}setRecvPayloads(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setRecvPayloads",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}sendApiRecordingData(){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"sendApiRecordingData",args:[]}})}},sf=class extends Vi{constructor(e,t,i,n){super(),this.logger=e,this.maxNumOfStreamsFactor=i,this.statsProvider=new af,this.contributingSources=[],this.unmixedAudioProvider=new Xm(this.logger),this.codec="None",this.recvPayloads=[],this.initCompleted=!1,this.enabledApiRecording=!1,this.timerWorkletNode=null;try{this.enabledApiRecording="true"===localStorage.getItem("enableApiRecording")}catch{}this.streamMixer=new Jm(this.logger,n),this.unmixedAudioProvider.setConfiguredState(!!t.mediaConfig.spatialAudioEnabled),this.wasmHealerPullStrategy=t.config.useInsertableStreams?.audioWasmCodec?.wasmHealerPullStrategy||-1,this.injectWebMA()}get stream(){return this.streamMixer.stream}dispose(){super.dispose(),this.streamMixer.dispose(),this.imp?.dispose(),this.timerWorkletNode?.then((e=>e.dispose())),this.timerWorkletNode=null,this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM decoder transform"),e.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(e){this.logger.warn("WASM decoder could only be instantiated in worker")}createWorkerInstance(e,t){this.logger.info(`Creating TimerWorkletNode from url: ${e.timerWorkletUrl}`),this.timerWorkletNode=ef.create(e.timerWorkletUrl),this.imp=function(e,t,i){return new rf(e,t,i)}(e,t,this),this.imp.init(this.enabledApiRecording,this.wasmHealerPullStrategy)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.initCompleted)return this.logger.safe.debug("Decoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}setRecvPayloads(e){this.recvPayloads=e,this.initCompleted?this.imp.setRecvPayloads(e):this.logger.safe.debug("Decoder is not initialized yet, postponing Recv payload setting")}negotiationCompleted(e){this.logger.safe.debug(`Negotiation completed, negotiated=${e}`),this.unmixedAudioProvider.setNegotiatedState(e),e||(this.codec="None",this.imp?.setCodec(this.codec,this.streamMixer.isSingleInputStream()))}setParticipantSpatialAudioPositions(e){this.streamMixer.setParticipantSpatialAudioPositions(e)}disableStreamsMixer(e){e?this.streamMixer.stopMixing():this.streamMixer.startMixing(this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[]))}getStatsProvider(){return this.statsProvider}getUnmixedAudioProvider(){return this.unmixedAudioProvider}configureSpatialAudio(e){this.unmixedAudioProvider.setConfiguredState(e)}async storeApiRecording(){if(this.enabledApiRecording&&this.initCompleted)return this.recordingCompletePromise?.resolve(),this.recordingCompletePromise=new Kt,this.imp.sendApiRecordingData(),this.recordingCompletePromise.promise}initDone(e,t){if(this.healerCapabilities=t,this.logger.safe.info(`Init done, errorCode=${e}`),0!==e)return void this.event("initFailed").raise(e);this.logger.safe.info(`healerCapabilities=${JSON.stringify(t)}`),this.initCompleted=!0;const i=Math.floor(this.healerCapabilities.maxNumStreamsPerPacket*this.maxNumOfStreamsFactor),n=this.unmixedAudioProvider.setupStreams(i,!0);this.imp.passWriteableStreams(n.streams,n.cnStream),this.setCodecInternal(),this.imp.setRecvPayloads(this.recvPayloads)}requestTimerWorkletPort(){this.timerWorkletNode?.then((e=>this.imp?.setTimerWorkletPort(e.createTimerPort())))}usedDecoderChanged(e){this.logger.safe.info(`Used decoder changed to custom=${e}, configured codec=${this.codec}`),this.event("usedDecoderChanged").raise(e),this.unmixedAudioProvider.setDetectedCodec(this.codec)}packetReceived(e,t,i,n){this.statsProvider.ssrc=t,this.statsProvider.addPushStats(e,n),this.contributingSources.length===i.length&&this.contributingSources.every(((e,t)=>e===i[t]))||(this.contributingSources=i,this.event("contributingSourcesChanged").raise(i))}newDataWrittenToStreams(e){const t=Array.from(new Int32Array(e));this.unmixedAudioProvider.setStreamSources(t),this.streamMixer.setStreamSources(t);const i=t.reduce(((e,t,i)=>(0===t&&e.push(i),e)),[]);this.imp?.setAvailableStreams(i)}packetDecoded(e,t,i){this.statsProvider.addPullStats(e,t,i,i.extra.samplingRatekHz*this.healerCapabilities.frameLengthMs)}apiRecordingAvailable(e,t,i){if(this.logger.safe.debug(`API recording available: errorCode=${e}, name=${t}, buffer length=${i.byteLength}`),this.recordingCompletePromise?.resolve(),0===i.byteLength)return;const n=new Blob([i],{type:"application/octet-stream"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=t,s.click()}setCodecInternal(){this.streamMixer.setMixerType(function(e){switch(e){case"SatinFB":return 0;case"MUCHv2":return 1;case"None":return-1;default:throw new Error(`unknown codec: ${e}`)}}(this.codec),this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[])),this.imp.setCodec(this.codec,this.streamMixer.isSingleInputStream()),this.statsProvider.codecName=this.codec}injectWebMA(){const e=window.webMA;e&&(e.wasmDecoder={debugLogging:e=>this.imp?.debugLogging(e),sendApiRecordingData:()=>this.imp?.sendApiRecordingData()})}removeWebMA(){const e=window.webMA;e&&delete e.wasmDecoder}},af=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 of(0,1e3),this.packetPullProccesingTimes=new of(0,1e3),this.numOfStreamsCounter=new of(0,10),this.pullProcessingTimePerStreamNumber={},this.packetPullTimings=new of(0,1e3)}get codecName(){return this.codec}set codecName(e){this.codec=e}addPushStats(e,t){this.decoderStats.pushCount++,this.decoderStats.pushErrCount+=0!==e?1:0,this.inboudStats.jitterBufferDelay+=t.webrtc.jitterBufferDelay,this.customHealerStats.packetDurationInMs=t.extra.packetDurationInMs,this.packetPushProccesingTimes.addSample(t.extra.processingTime),this.customHealerStats.cnpPushCount=t.extra.totalCountCNPackets,this.customHealerStats.redPacketsCount+=0!==t.extra.redundancyTimestampOffset?1:0}addPullStats(e,t,i,n){var r;this.decoderStats.pullCount++,this.decoderStats.pullErrCount+=0!==e?1:0,this.inboudStats.audioLevel=i.webrtc.audioLevel,this.inboudStats.totalAudioEnergy=i.webrtc.totalAudioEnergy,this.inboudStats.jitterBufferEmittedCount=i.webrtc.jitterBufferEmittedCount,this.inboudStats.totalSamplesReceived=i.webrtc.totalSamplesReceived,this.inboudStats.concealedSamples=i.webrtc.concealedSamples,this.inboudStats.silentConcealedSamples=i.webrtc.silentConcealedSamples,this.numOfStreamsCounter.addSample(t),this.customHealerStats.FECPayloadDecodedSamples=i.extra.FECPayloadDecodedSamples,this.customHealerStats.numSamplesPerFrame=n,this.customHealerStats.pullAdspPayloadType=i.extra.pullAdspPayloadType,this.customHealerStats.concealSamples=i.extra.concealSamples,this.customHealerStats.stretchSamples=i.extra.stretchSamples,this.customHealerStats.healedSamples=i.extra.healedSamples,this.customHealerStats.decodedSamples=i.extra.decodeSamples,this.packetPullProccesingTimes.addSample(i.extra.processingTime),this.customHealerStats.cnpPullCount=i.extra.totalCountCNGeneratedFrames,this.customHealerStats.cngSamples=i.extra.cngSamples,(r=this.pullProcessingTimePerStreamNumber)[t]??(r[t]=new of(0,200)),this.pullProcessingTimePerStreamNumber[t].addSample(i.extra.processingTime),this.packetPullTimings.addSample(i.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 e of Object.keys(this.pullProcessingTimePerStreamNumber))this.customHealerStats.pullProcessingTimePerStreamNumber[e]=this.pullProcessingTimePerStreamNumber[e].getFrequencies();return this.customHealerStats}getDecoderStats(){return this.decoderStats}},of=class{constructor(e,t){this.minSample=e,this.maxSample=t,this.frequencyDict={}}addSample(e){if(void 0===e)return;const t=Math.min(this.maxSample,Math.max(this.minSample,e));this.frequencyDict[t]=(this.frequencyDict[t]??0)+1}getFrequencies(){return{...this.frequencyDict}}},lf=class extends nf{constructor(e,t,i){super(e,t,3,i)}init(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e]}})}setCodec(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}},cf=["SatinFB"],df=class extends Vi{constructor(e){super(),this.logger=e,this.codec="None",this.injectWebMA()}getCodecName(){return this.codec}dispose(){super.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM encoder transform"),e.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(e){this.logger.warn("WASM encoder could only be instantiated in worker")}createWorkerInstance(e,t){this.imp=function(e,t,i){return new lf(e,t,i)}(e,t,this),this.imp.init(cf)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.encodersInitCodes)return this.logger.safe.debug("Encoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}isCodecAllowed(e){return cf.includes(e)}negotiationCompleted(e){e||(this.codec="None",this.imp?.setCodec(this.codec))}initDone(e){this.logger.safe.info(`initDone: ${JSON.stringify(e)}`),this.encodersInitCodes=e,this.setCodecInternal()}packetEncoded(e){0!==e&&this.logger.safe.info(`encode failed: ${e}`)}setCodecInternal(){const e=this.encodersInitCodes[this.codec]??-2147024809;if("None"!==this.codec&&0!==e)return this.logger.safe.error(`WASM encoder is failed to init codec ${this.codec}, err code: ${e}`),void this.event("initCodecFailed").raise(e);this.event("codecChanged").raise(this.codec),this.imp.setCodec(this.codec)}injectWebMA(){const e=window.webMA;e&&(e.wasmEncoder={debugLogging:e=>this.imp?.debugLogging(e)})}removeWebMA(){const e=window.webMA;e&&delete e.wasmEncoder}},uf=Z,hf=class extends Vi{constructor(e,t,i){super(),this.encStreamsManager=e,this.logger=t,this.configProvider=i,this.isEnabled=!1,this.sessionStats=new pf,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(e,t){if(!e||!this.codecContext||!this.codecConfig?.enable)return;this.isEnabled=!0;const i=this.codecConfig.maxNumOfStreamsFactor||1;this.decoderImp=new sf(this.logger.createChild("AudioWasmDecoder"),this.configProvider,i,t),this.codecConfig.enableSend&&(this.encoderImp=new df(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(e){if(!this.isEnabled)return;const t=this.decoderImp?.getUnmixedAudioProvider()?.configured?"MUCHv2":this.codecConfig.codec||"None";this.codecContext.codec!==t&&(this.codecContext.initSendFailed=!1),this.codecContext.lastUsedCodec=this.codecContext.codec,this.codecContext.codec=t,this.codecContext.enabledLocally=!this.codecContext.initFailed&&"None"!==t,this.codecContext.enabledForSend=this.codecContext.enabledLocally&&!this.codecContext.initSendFailed&&!!this.codecConfig?.enableSend&&this.encoder?.isCodecAllowed(t),this.logger.safe.info(`Audio codec state: context=${JSON.stringify(this.codecContext)}`),this.codecContext.initFailed||!e&&this.codecContext.disabledRemotely||(this.sessionStats.toggleState("None"!==t),this.decoderImp?.setCodec(t),this.encoderImp?.setCodec(this.codecContext.enabledForSend?t:"None"))}negotiationCompleted(){if(!this.isEnabled)return!1;const e=this.codecContext.enabledLocally&&!this.codecContext.disabledRemotely;return this.decoderImp?.negotiationCompleted(e),this.encoderImp?.negotiationCompleted(e),this.sessionStats.negotiationCompleted(e,this.codecContext.enabledForSend),e}configureSpatialAudio(e,t){return!!this.isEnabled&&(this.decoderImp?.configureSpatialAudio(e),(e&&"MUCHv2"!==this.codecContext.codec||!e&&"MUCHv2"===this.codecContext.codec)&&this.event("negotiationNeeded").raise(t),!0)}subscribeToStreamManagerEvents(e){this.subs.push(e.on("onTransformsCollectionCreated",(e=>this.handleTransformsCollectionCreated(e))),e.on("onTransformsCollectionCleared",(e=>this.handleTransformsCollectionCleared(e))))}handleTransformsCollectionCreated(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.activateTransform(e.collection):this.encoderImp&&"Sender"===e.objType&&this.encoderImp.activateTransform(e.collection))}handleTransformsCollectionCleared(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.deactivateTransform():this.encoderImp&&"Sender"===e.objType&&this.encoderImp.deactivateTransform())}subscribeToCodecsEvents(){this.decoderImp&&this.subs.push(this.decoderImp.on("initFailed",(e=>this.handleCodecInitFailed("decoder",e)))),this.encoderImp&&this.subs.push(this.encoderImp.on("initCodecFailed",(e=>this.handleCodecInitFailed("encoder",e))))}unsubscribeFromEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}handleCodecInitFailed(e,t){"decoder"===e?this.codecContext.initFailed=!0:this.codecContext.initSendFailed=!0;const i=be();this.logger.safe.warn(`[${i}] Audio ${e} init failed ${t}`),this.sessionStats.initFailed(t,e),this.event("negotiationNeeded").raise(i)}},gf=class e{constructor(){this.sessionEvents={negotiationAttempts:[],toggleCount:0,negotiatedCount:0,failedNegotiationCount:0,decoderInitError:0,encoderInitError:0}}toggleState(t){this.sessionEvents.toggleCount++,this.inProgressNegotiation={ts:Date.now(),enabled:t,negotiated:!1,sendEnabled:!1},Sn(this.sessionEvents.negotiationAttempts,this.inProgressNegotiation,e.maxStoreNegotiations)}negotiationCompleted(e,t){this.inProgressNegotiation&&(this.sessionEvents.negotiatedCount+=e?1:0,this.sessionEvents.failedNegotiationCount+=this.inProgressNegotiation.enabled&&!e?1:0,this.inProgressNegotiation.negotiated=e,this.inProgressNegotiation.sendEnabled=t,this.inProgressNegotiation=void 0)}initFailed(e,t){"decoder"===t?this.sessionEvents.decoderInitError=e:this.sessionEvents.encoderInitError=e}getSessionEvents(){return(0,uf.clone)(this.sessionEvents)}};gf.maxStoreNegotiations=5;var pf=gf,mf=class{constructor(e,t){this.workerProvider=e,this.logger=t,this.clientsMap=new Map,this.loaded=!1,this.initDefer=new Kt;try{this.worker=e.getWorker(this.logger),this.worker.onmessage=e=>this.handleEvent(e.data),this.worker.onerror=e=>{this.logger.safe.error(`error inside worker: ${e.message}`),this.initDefer.resolve()}}catch(e){this.logger.safe.error("failed to create worker"),this.initDefer.resolve()}}get timerWorkletUrl(){return this.workerProvider.getTimerWorkletUrl()}initialize(){return Promise.race([this.initDefer.promise,Yt(5e3).then((()=>{this.loaded??this.logger.safe.warn("worker initialization timeout")}))])}isWorkerLoaded(){return this.loaded}sendTransformCommand(e,t,i=[]){const n={type:"transform",clientId:e,payload:t};this.worker?.postMessage(n,i)}subscribeClient(e,t,i){const n=this.clientsMap.get(e)??new Map;n.set(t,i),this.clientsMap.set(e,n)}unsubscribeClient(e){this.clientsMap.delete(e)}dispose(){this.worker?.postMessage({type:"generic",payload:{operation:"dispose"}}),this.worker?.terminate()}handleEvent(e){switch(e.type){case"init":this.initDefer.resolve(),this.loaded=!0,this.logger.safe.info("worker initialized");break;case"transform":{const t=this.clientsMap.get(e.payload.clientId),i=t?.get(e.payload.event.transformType);i?i(e.payload.event):this.logger.safe.error(`received event for unknown Client ${e.payload.clientId} or transformType ${e.payload.event.transformType}: ${e.payload.event.name}`)}break;case"log":switch(e.level){case"debug":this.logger.safe.debug(e.msg);break;case"info":this.logger.safe.info(e.msg);break;case"warn":this.logger.safe.warn(e.msg);break;case"error":this.logger.safe.error(e.msg);break;default:this.logger.safe.error(`unknown log level ${e.level}`)}break;default:this.logger.safe.error(`received unsupported event from worker ${e.type}`)}}},ff=class{constructor(e){this.logger=e,this.transformType=0}transform(e){return this.processChunk(e),e}dispose(){}getStartCodeSize(e){const t=e.getUint32(0);return 1===t?4:256==(4294967040&t)?3:0}processChunk(e){if("key"!==e.type)return;const t=this.isH264KeyFrame(e.data)?`${this.getH264Profile(e.data)}(H264)`:"unknown";this.logger.info(`keyframe metadata: ${JSON.stringify(e.getMetadata())}, profile=${t}`)}isH264KeyFrame(e){if(e.byteLength<7)return!1;const t=new DataView(e),i=this.getStartCodeSize(t);return!!i&&7==(31&t.getUint8(i))}getH264Profile(e){const t=new DataView(e),i=this.getStartCodeSize(t);return(16777215&t.getUint32(i)).toString(16)}},vf=class extends nf{constructor(e,t){super(e,t,0,void 0)}},Sf=class{constructor(e){this.logger=e}createBaseInstance(e){this.imp=new ff(this.logger.safe),e.addTransform(this.imp)}createWorkerInstance(e,t){this.imp=new vf(e,t)}},yf=class{constructor(){this.transformType=1,this.muted=!1}transform(e){return this.muted?null:e}mute(e){this.muted=e}dispose(){}},Cf=class extends nf{constructor(e,t){super(e,t,1,void 0)}mute(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"mute",args:[e]}})}},Tf=class{constructor(e){this.logger=e}createBaseInstance(e){this.imp=new yf,e.addTransform(this.imp)}createWorkerInstance(e,t){this.imp=new Cf(e,t)}mute(e){this.logger.safe.info(`Dropping audio chunks: ${e}`),this.imp.mute(e)}},Ef=class{constructor(e,t){this.transforms=[];const i=new TransformStream({transform:(e,t)=>{let i=e;for(const e of this.transforms)if(i=e.transform(i),!i)return;t.enqueue(i)}});e.pipeThrough(i).pipeTo(t)}clearTransforms(){for(const e of this.transforms)e.dispose();this.transforms=[]}addTransform(e){this.transforms.push(e)}getTransform(e){return this.transforms.find((t=>t.transformType===e))}},bf=class extends gt{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(e){this.unsubscribeFromStreamEvents(),this.sessionAudioProvider=e,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",(e=>this.event("onStreamSourcesUpdated").raise(e))),this.sessionAudioProvider.on("onConfiguredStateChanged",(e=>this.event("onConfiguredStateChanged").raise(e))),this.sessionAudioProvider.on("onActiveStateChanged",(e=>this.event("onActiveStateChanged").raise(e))),this.sessionAudioProvider.on("onActiveCodecChanged",(e=>this.event("onActiveCodecChanged").raise(e))))}unsubscribeFromStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},_f=class extends gt{constructor(e,t,i,n,r){super(),this.allowVirtualDeviceInCall=e,this.defaultDeviceManager=t,this.logger=i,this.callStats=n,this.isMediaSending=r,this.stats=[],this.selectedVirtualDevice={camera:void 0,screenshare:void 0},this.subs=[this.defaultDeviceManager.on("onVirtualDevicesChanged",(()=>this.handleRegisteredDeviceChange()))],this.logger.info(`allowVirtualDeviceInCall: ${e}`)}get isVirtualDeviceEnabled(){return this.allowVirtualDeviceInCall}selectDevices(e){const t=this.defaultDeviceManager.getRegisteredDevices(),i=t.find((t=>t.id===e.camera)),n=t.find((t=>t.id===e.screenshare));this.logger.info(`Selecting virtual devices, camera: ${i?.id}, screenshare: ${n?.id}`);const r={camera:this.selectedVirtualDevice.camera?.id,screenshare:this.selectedVirtualDevice.screenshare?.id};e.camera!==r.camera||e.screenshare!==r.screenshare?(this.selectedVirtualDevice={camera:i,screenshare:n},this.addToCallStat({type:"VirtualDeviceSelected",payload:this.selectedVirtualDevice}),this.event("onSelectedVirtualDevicesChanged").raise(e,r)):this.logger.info("Virtual Device did not change.")}getSelectedDevices(){return Object.entries(this.selectedVirtualDevice).reduce(((e,[t,i])=>(e[t]=i?.id,e)),{})}getDeviceManager(e){return this.allowVirtualDeviceInCall?this.getDeviceManagersForVirtualDevice(e)[0]:this.defaultDeviceManager}getDeviceManagersForVirtualDevice(e){return"Video"===e&&this.selectedVirtualDevice.camera?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.camera.getDeviceManagers()):"ScreenShare"===e&&this.selectedVirtualDevice.screenshare?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.screenshare.getDeviceManagers()):(this.logger.info(`Using default DM, type: ${e}`),[this.defaultDeviceManager])}getDefaultDeviceManager(){return this.defaultDeviceManager}dispose(){this.stats=[],this.subs.forEach((e=>e.dispose())),super.dispose()}hasDevice(e){return this.defaultDeviceManager.id===e||[...this.selectedVirtualDevice.camera?.getDeviceManagers()??[],...this.selectedVirtualDevice.screenshare?.getDeviceManagers()??[]].some((t=>t?.id===e))}addToCallStat(e){const t=this.stats.push(e);this.callStats.appendCallDeviceManagerInfo({events:JSON.stringify(t)})}handleRegisteredDeviceChange(){const e=this.defaultDeviceManager.getRegisteredDevices(),{camera:t,screenshare:i}=this.selectedVirtualDevice;let n=!1,r=!1;t&&(n=e.some((e=>e.id===t.id)),this.logger.info(`Selected camera(${t.id}) in call, isCameraValid:${n}`)),i&&(r=e.some((e=>e.id===i.id)),this.logger.info(`Selected SS(${i.id}) in call, isScreenShareValid:${r}`)),this.selectDevices({camera:n?t.id:void 0,screenshare:r?i.id:void 0})}isModalityEnabled(e){return this.isMediaSending(Yh(e))}},If=class{constructor(e,t){this.logger=e,this.configProvider=t,this.debounceMap=new Map,this.enabledViaApi=!1,this.configProvider.config.remoteUFD?.enabledViaApi&&this.init()}init(){this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&(this.enabledViaApi=!0,this.logger.info(`Remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`))}raiseIfNeeded(e,t,i){if(this.shouldBeRaised(e,t))if(this.configProvider.config.localUFDDebounceTime)i(this.getState(e));else{clearTimeout(this.debounceMap.get(e.type));const t=setTimeout(i,this.configProvider.config.remoteUFD.debounceTime,this.getState(e));this.debounceMap.set(e.type,t)}}dispose(){for(const e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.enabledViaApi=!1}shouldBeRaised(e,t){return!(!this.configProvider.config.remoteUFD?.enabled||!this.enabledViaApi||t>this.configProvider.config.remoteUFD.maxParticipantNumber||!this.configProvider.config.remoteUFD.list[e.type])}getState(e){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify([e])}}},wf={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:Gi.MEDIA_EVENT_FIELDS,lowBattery:Gi.MEDIA_EVENT_FIELDS},Af=class extends gt{constructor(e){super(),this.configProvider=e}setDiagnosticsReport(e){this.diagnosticsReport=e}setEventType(e){if(!this.configProvider.config.smallCallTelemetry.enable)return;const t=Object.keys(this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary),i=this.getLastKnownMediaSessionStats();if(i&&(t?.forEach((t=>{if(t===e){const n=this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary[t],r={eventType:e,data:this.buildFromDictionary(i,n)};this.setTerminationCodeAndSubCodeToSuccess(r.data),this.event("sendSmallCallTelemetry").raise(r)}})),"reconnect"===e||"rejectNegotiation"===e||"visibilityHidden"===e||"lowBattery"===e)){const t={eventType:e,data:this.buildFromDictionary(i,wf[e])};void 0===t.data.metrics.TerminationReason_code&&this.setTerminationCodeAndSubCodeToSuccess(t.data),this.event("sendSmallCallTelemetry").raise(t)}}getEndCallSmallTelemetry(e){const t=this.getLastKnownMediaSessionStats(),i=this.buildFromDictionary(t,Gi.MEDIA_EVENT_FIELDS);return e&&(i.metrics.TerminationReason_code=Ar,i.metrics.TerminationReason_subCode=xr),{eventType:e?"tabClosed":"endCall",data:i}}getSmallTelemetryOnBatteryLow(){const e=this.getLastKnownMediaSessionStats(),t=this.buildFromDictionary(e,Gi.MEDIA_EVENT_FIELDS);return this.setTerminationCodeAndSubCodeToSuccess(t),{eventType:"lowBattery",data:t}}getLastKnownMediaSessionStats(){if(!this.diagnosticsReport)return;const e=this.diagnosticsReport.rawRootRef.sessions.length;return this.diagnosticsReport.getSessionTelemetry(this.diagnosticsReport.rawRootRef.sessions[e-1]?.sessionId)}buildFromDictionary(e,t){const i={Extensions:{},metrics:{}};if(!e)return i;for(const n in t)e[n]&&(i[n]={},t[n].forEach((t=>{void 0!==e[n][t]&&(i[n][t]=e[n][t])})));return i}setTerminationCodeAndSubCodeToSuccess(e){void 0===e.metrics.TerminationReason_code&&(e.metrics.TerminationReason_code=Ar,e.metrics.TerminationReason_subCode=Ar)}},Pf=class extends gt{constructor(e,t){super(),this.diagnostics=e,this.configProvider=t,this.hasSentLowBatteryEvent=!1,navigator?.getBattery?.().then((e=>{this.batteryManager=e,e.addEventListener("levelchange",this.onLevelChange.bind(this))}))}dispose(){this.batteryManager&&this.batteryManager.removeEventListener("levelchange",this.onLevelChange)}onLevelChange(e){const t=100*e.level;this.diagnostics.setBatteryLevel(t),t<=this.configProvider.config.lowBatteryThreshold&&!this.hasSentLowBatteryEvent&&(this.event("batteryStatusChanged").raise(t),this.hasSentLowBatteryEvent=!0)}},Rf=e=>`${e.type}:${e.mediaType}`,Mf=class{constructor(e,t){this.logger=e,this.configProvider=t,this.timestamps={},this.lastSentUFDValues=new Map,this.disabledUFDs=new Set}shouldRaise(e,t,i){if(!this.isEnabled(e,t,i))return!1;const n=Rf(e);if("Good"!==e.value&&this.shouldUFDBeDisabled(n)&&!this.disabledUFDs.has(n)&&(this.logger.info(`Disabling remote UFD: ${JSON.stringify(e)}`),this.disabledUFDs.add(n),setTimeout((()=>{this.disabledUFDs.delete(n)}),this.configProvider.config.remoteUFD.disableInterval)),this.disabledUFDs.has(n)&&"Good"!==e.value)return!1;const r=this.lastSentUFDValues.get(n);return!(this.disabledUFDs.has(n)&&"Good"===e.value&&(!r||"Good"===r))}registerSentUFDs(e){e.forEach((e=>{const t=Rf(e);this.lastSentUFDValues.set(t,e.value)}))}shouldUFDBeDisabled(e){var t;const i=this.configProvider.config.remoteUFD.maxNumberOfBadUFDsForThrottling;(t=this.timestamps)[e]??(t[e]=[]);const n=this.timestamps[e];return rt(n,Date.now(),i),!(n.length<i)&&n[i-1]-n[0]<this.configProvider.config.remoteUFD.throttlingTimeInterval}isEnabled(e,t,i){return!(!this.configProvider.config.remoteUFD?.enabled||!i||t>this.configProvider.config.remoteUFD.maxParticipantNumber||!this.configProvider.config.remoteUFD.list[e.type])}},Df=class{constructor(e,t,i){this.logger=e,this.configProvider=t,this.publishState=i,this.bundledUFDs=new Map,this.sentBundleWindow=[],this.enabledViaApi=!1,this.configProvider.config.remoteUFD?.enabledViaApi&&this.init()}raiseIfNeeded(e,t){const i=Rf(e);if(!this.remoteUFDFilter?.shouldRaise(e,t,this.enabledViaApi))return;const n=this.bundledUFDs.get(i);"Good"===e.value&&n&&"Good"!==n.value?this.bundledUFDs.delete(i):this.bundledUFDs.set(i,e)}dispose(){this.enabledViaApi=!1,this.bundledUFDs.clear(),clearTimeout(this.bundleInterval)}init(){!this.enabledViaApi&&this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&(this.enabledViaApi=!0,this.logger.info(`Initialized with remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`),this.remoteUFDFilter=new Mf(this.logger,this.configProvider),this.bundleInterval=window.setInterval((()=>this.sendUfdBundle()),this.configProvider.config.remoteUFD.bundlingInterval))}sendUfdBundle(){if(!this.bundledUFDs.size)return;if(this.sentBundleWindow.length>=this.configProvider.config.remoteUFD.maxNumberOfBundles){if(this.sentBundleWindow[0]+this.configProvider.config.remoteUFD.bundlingWindowInterval>Date.now())return;this.sentBundleWindow.shift()}const e=this.getState();this.logger.info(`Sending remote UFDs: ${e.content}`),this.remoteUFDFilter.registerSentUFDs(Array.from(this.bundledUFDs.values())),this.publishState(e),this.bundledUFDs.clear(),this.sentBundleWindow.push(Date.now())}getState(){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify(Array.from(this.bundledUFDs.values()))}}},kf=[1,2,9,10,11,12,30,27,28],Of="remote",Nf=class extends gt{constructor(e,t){super(),this.isStreaming=e,this.mediaType=t}},Lf=class e extends gt{constructor(t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S){super(n),this.signalingAgent=t,this.mediaAgent=i,this.logger=n,this.telemetryLoggers=r,this.currentUserSkypeIdentity=s,this.groupId=a,this.threadId=o,this.ecsProvider=d,this.trouterService=u,this.accountConfiguration=h,this.vdi3diagnostics=S,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 Wh({mediaStates:[Gh(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=e.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=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,{voicemailResourcePath:t.callVoicemailStartOptions.voicemailResourcePath,voicemailItemId:t.callVoicemailStartOptions.voicemailItemId,callToVoicemail:!0},Date.now()-r,e),this.getSignalingSessionCallOptions=e=>{const t={suppressDialout:!e.callStartOptions.ringOthers,isPreheatOnly:!(1&~e.callStartOptions.preheatFlags),onBehalfOf:this.onBehalfOfMri,onBehalfOfUserDisplayName:this.onBehalfOfUserDisplayName,callQueueContext:e.callStartOptions?.callQueueContext,muted:!(1&~e.callStartOptions.muteFlags),invitationType:e.invitationType,participantsToNudge:e.participantsToNudge,routingFlags:e.callStartOptions&&e.callStartOptions.routingFlags,parkContext:e.parkContext,pickupCode:e.pickupCode,scenario:e.callStartOptions&&e.callStartOptions.scenario,callUsesMixer:this.callUsesMixer,clientEndpointCapabilities:e.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:e.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:e.meetingPreferences,alternateId:e.callStartOptions?e.callStartOptions.alternateId:null,meetingRegistrationId:e.callStartOptions?e.callStartOptions.meetingRegistrationId:"",participantPin:e.callStartOptions?e.callStartOptions.participantPin:"",additionalEndpointProperties:e.callStartOptions?.additionalEndpointProperties||null,publishedStates:e.callStartOptions?.publishedStates||null,targetApplicationType:e.callStartOptions?.targetApplicationType,isHuddleGroupCall:e.callStartOptions?.isHuddleGroupCall,captchaContentJson:e.callStartOptions?.captchaContentJson,customHeaderContext:e.callStartOptions?.customHeaderContext,participationPreferences:e.callStartOptions?.participationPreferences,callingLineIdentity:e.callStartOptions?e.callStartOptions.callingLineIdentity:null,participantPropertyBag:e.callStartOptions?e.callStartOptions.participantPropertyBag:null},i=e.callStartOptions?.invitationDataJson;if(i)try{t.invitationData=JSON.parse(i)}catch(e){throw new Error(`Invalid JSON in invitationData: ${i}`)}return t},this.startOutgoingCall=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,this.getSignalingSessionCallOptions(t),Date.now()-r,e),this.joinGivenConversation=(e,t,i,n,r,s)=>{const a=!(1&~t.callStartOptions.muteFlags),o=!(1&~t.callStartOptions.preheatFlags),l=t.callStartOptions?.invitationDataJson,c=t.callStartOptions?.sharedLineCallInvitationContentJson;this.logger.info(`[${e}][joinGivenConversation] muted=${a}, isPreheatOnly=${o},\n sharedLineCallInvitationContentJson=${c}, invitationDataJson=${l},\n captchaContentJson=${!!t?.callStartOptions?.captchaContentJson}`);const d={muted:a,isPreheatOnly:o,clientEndpointCapabilities:t.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:t.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:t.meetingPreferences,meetingRegistrationId:t.callStartOptions?t.callStartOptions.meetingRegistrationId:"",participantPin:t.callStartOptions?t.callStartOptions.participantPin:"",additionalEndpointProperties:t?.callStartOptions?.additionalEndpointProperties,applyServerMute:t?.applyServerMute,publishedStates:t?.callStartOptions.publishedStates,invitationData:t?.callStartOptions.invitationDataJson,captchaContentJson:t?.callStartOptions.captchaContentJson,callQueueContext:t?.callStartOptions.callQueueContext,participationPreferences:t?.callStartOptions.participationPreferences,participantPropertyBag:t?.callStartOptions.participantPropertyBag};if(c)try{d.sharedLineCallInvitationContent=JSON.parse(c)}catch(e){throw new Error(`Invalid JSON in sharedLineCallInvitationContent: ${c}`)}if(l)try{d.invitationData=JSON.parse(l)}catch(e){throw new Error(`Invalid JSON in invitationDataJson: ${l}`)}return this.signalingSession.joinGivenConversation(s,this.callId,i,n,Date.now()-r,d,e)},this.getParticipantByLegId=(e,t,i)=>{this.logger.info(`getMriByParticipantLegId[${i}] participantLegId ${e}`);for(const i of t.participants)for(const t of i.endpoints.endpointDetails)if(t&&t.participantId&&t.participantId===e)return i;return null},this.executeCallTransfer=(e,t,i,n)=>{this._setTransferState(1);const r=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return 0===i?this.signalingSession.transferCallAsync(e,"TransferTypeStandard",void 0,n,t):2===i&&this.signalingSession.transferCallAsync(e,"TransferTypeVoicemail",void 0,n,t),r},this.executeConsultCallTransfer=(e,t,i,n,r)=>{this._setTransferState(1);const s=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,n,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return this.signalingSession.consultTransferCallAsync(e,t,i,n,r),s},this.createUpdateParticipantPromise=(e,t)=>this._callOperationHandler.createPendingOperation("UpdateParticipantsProperties",e,t),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=(e,t,i,n)=>{i.logFailure(e);let r,s={code:2,success:!1,fatal:!0},a=7;throw ph("SendAttach",e)&&(r={code:500,subCode:4105,phrase:"CallEndReasonAttachFailed"}),ph("ProcessIncomingCallRequest",e)&&(r={code:406,subCode:4103,phrase:"CallEndReasonBadNotificationPayload"},s={code:0,success:!1,fatal:!0}),gh(zs,e)&&(a=47),e?.error&&e.error.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer&&(r={code:ys,subCode:3111,phrase:"CallEndReasonIncompatibleOffer"}),this.callTelemetry.updateOperationData("Acknowledge",{phases:n,error:$e(e)},t),this._callOperationHandler.maybeRejectOperation("Acknowledge",s,void 0,t),this.stopInternal({rejectReason:r,causeId:t,terminatedReason:a}),s},this._onAcknowledgeSuccess=(e,t,i)=>(e.logSuccess("success"),this.callTelemetry.updateOperationData("Acknowledge",{phases:t},i),{code:1,success:!0}),this._processOfferedModalities=(e,t)=>{this.handleOfferedModalities(e,t);const i=this.callUsesMixer?void 0:{modalityOverride:e};return this.updateMediaModalities(i,t)},this._handleOfferProcessingError=(e,t,i)=>(i.logFailure(`handleOfferProcessingError=${e}`),e?.error?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer?(this.callTelemetry.recordEvent("IncompatibleOffer",void 0,t),this.signalingSession.supportsNewOfferRequest()?(this.newOfferRequestDeferred=new Kt,this.attachToCallAndGetOffer.promise.then((()=>this.mediaSession.rejectNegotiationAsync(e.error,t))).then((()=>this.signalingSession.requestNewOffer(this.mediaSession.getAcceptedTypes(),t))).then((()=>this.newOfferRequestDeferred.promise)).then((e=>this.mediaSession.processOfferAsync(e,t))).catch((e=>(this.callTelemetry.recordEvent("NewOfferFailed",je(e),t),Promise.reject(e))))):Promise.reject(e)):Promise.reject(e)),this._trySendProvisionalMediaAnswer=e=>Promise.resolve(void 0).then((()=>this.mediaSession.createAnswerAsync(!0,e))).then((e=>e.blob?(this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",void 0,be(),{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.signalingSession.setProvisionalAnswerAsync(e).then((()=>this.mediaAcknowledgmentOperation))):Promise.resolve(void 0))),this.checkForCallIdUpdate=(e,t)=>{if(this.callId!==e){this.logger.info(`[${t}][checkForCallIdUpdate] old=${this.callId}, new=${e}`),this.setCallId(e);try{this.event("callIdChanged").raise(this.callId)}catch(e){this.logger.error(`Error raising call ID change: ${e}`)}this.raiseChanged()}},this.handleRemoteParticipantStateInOneToOneCall=e=>{if(!this.callUsesMixer&&3===this.state){const t=this.participants[0];t&&t.setState(3,void 0,e)}},this.handleRemoteParticipantJoinedInOneToOneCall=(e,t)=>{if(!this.callUsesMixer&&3===this.state){const i=this.participants.filter((t=>t.id===e.id))[0];i?i.setState(3,void 0,t):this.logger.logFailure(`[${t}][handleRemoteParticipantJoinedInOneToOneCall]unable to find particpant ${De(e.id)}`)}},this.handleRemoteParticipantStateInObservingCall=(e,t,i)=>{const n=t.isLobby;if(8===this.state){const t=n?7:3;e.setState(t,void 0,i)}},this.getTelemetryFromPhaseExecution=e=>{const t={phase:e.phase,phases:e.phases,code:e.error&&e.error.code,subCode:e.error&&e.error.subCode,message:e.error&&e.error.message,error:e.error};return(t.code||t.message)&&delete t.error,t},this._setTransferState=e=>{this.transferState!==e&&(this.logger.info(`Transfer: state set: ${e}`),this._transferState=e,this.callTelemetry.recordEvent("_SetTransferState",{state:e}),this.raiseChanged())},this._setParkState=e=>{this.parkState!==e&&(this.logger.info(`Parking: state set: ${e}`),this._parkState=e,this.callTelemetry.recordEvent("_SetParkState",{state:e}),this.raiseChanged())},this.prepareNegotiationResultForTelemtry=e=>({isComplete:e.isComplete,activeModalities:e.activeModalities,configuredModalities:e.configuredModalities,initiator:De(e.initiator),attemptedModalities:e.attemptedModalities,offeredModalities:e.offeredModalities}),this.prepareTelemetryForOfferAnswer=e=>e&&e.mediaContent&&{isRenegotiation:!!e.renegotiation,isEscalation:!!e.mediaContent.isTwoPartyToMultiPartyEscalation,mediaTypes:e.mediaTypes,newOffer:e.mediaContent.newOffer},this.updateLocalParticipantEndpoints=e=>{const t=this.logger.createFnLogger("updateLocalParticipantEndpoints",""),i=[];(0,Ws.forEach)(e,(e=>{const t=Hh(e,this.getSelfClientEndpointCapabilities());i.push(t)})),this.endpoints.endpointDetails=i;const n=this.getDataChannelSourceId();-1!==n&&this.dataChannel&&this.dataChannel.setDataChannelSourceId(n),t.info(`selfEndpointDetails=${Qe(this.endpoints)}`)},this.handleParticipantsMutedUpdated=(e,t)=>{const i=this.logger.createFnLogger("handleParticipantsMutedUpdated",t);if(void 0!==e?.info){this.logger.info(`handleParticipantsMutedUpdated: number of infos: ${Object.keys(e.info).length}`);for(const t of Object.keys(e.info)){const n=this.getParticipant(t);n?n.handleServerMutedInfoUpdate(e.info[t]):i.info(`Cannot find local participant ${De(t)}`)}}else i.info("Ignored, no mute participant info.")},this.handleSelfUnmuteUpdatedInfo=(e,t)=>{const i=this.logger.createFnLogger("handleSelfUnmuteUpdatedInfo",t);if(void 0!==e?.info)for(const n of Object.keys(e.info)){const r=e.info[n];if(n===this.localSignalingParticipant.id){const e=(0,Ws.find)(r,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===e){i.info(`Cannot find local participant ${De(n)}`);continue}const s=(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(t=>t.participantId===e.participantId));tg(this.logger,s,e,!1)&&this.handleSelfServerMutedState(t)}}else i.info("Ignored, no unmute participant info.")},this.state=0,this.terminatedReason=0,this.callStats=new Uh,this.callDeviceManager=this.createCallDeviceManager(),this.callTelemetry=new Tr(this.logger,this._callCreationTime),this.collectMediaStatsDeferred=new Kt,this.setCallId(l),this.setGroupId(a),this.setThreadId(o),this.setMessageId(g),this.setSkypeId(this.currentUserSkypeIdentity.id),this.setParticipantId(c),this.setCallOrigin(0),this.vdi3diagnostics&&this.callStats.setRpcSessionId(this.vdi3diagnostics.getRPCSessionId()),this.logger=this.logger.createChild((()=>{const e=(this.endpointId||"").substr(0,8),t=(this.participantId||"").substr(0,8);return`Web/${this.instanceNumber}[${this.callId}][${e}][${t}][${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(c),this.signalingSession.setLocationInfo(p,m,v),this.streamManager=new Lg(this.participantId,null,this.callStats.localStats,this.logger),this.mediaAgent&&(this.dataChannel=new tp(this.logger),this.dataChannel.on("remoteUserEventsReceived",((e,t)=>this.event("remoteUserEventsReceived").raise(e,t))),this.dataChannel.on("onDataChannelStateUpdated",(e=>{"Failed"===e&&(this.logger.error("onDataChannelStateUpdated: datachannel creation failed, will remove data modality"),this.mediaStateConfigurationHelper.removeModality(3),this.updateSignalingDSHMessageSubscription(!0),this.updateMediaModalities())})),this.screenSharingControl=new Fp(this.logger,this.dataChannel,this,this.telemetryLoggers,this.ecsProvider,this.mediaAgent.getConfigProvider()),this.mediaAgent.handleSendMidCallTelemetry(this.sendMidCallTelemetry.bind(this)),this.remoteUFDHandler=this.mediaAgent.getConfigProvider().config.remoteUFD?.remoteUFDHandlerV2?new Df(this.logger.createChild("remoteUFDHandlerV2"),this.mediaAgent.getConfigProvider(),this.publishState.bind(this)):new If(this.logger.createChild("remoteUFDHandler"),this.mediaAgent.getConfigProvider()),this.smallCallTelemetry=new Af(this.mediaAgent.getConfigProvider()),this.smallCallTelemetry.on("sendSmallCallTelemetry",(e=>this.reportSmallCallEvent(e))));const y={enableErrorConversion:this.ecsProvider.getEcsConfig("SkypeCalling","enableErrorConversion")};this._deferUsingMicrotask=this.ecsProvider.getEcsConfig("SkypeCalling","deferUsingMicrotask"),cg.instance.setDeferToQueueMicrotask(this._deferUsingMicrotask),cg.instance.setLogger(n),this.logger.info(`operationHandlerEcsConfig: ${JSON.stringify(y)}`),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 as(this.logger,this.callTelemetry,y,void 0,((e,t)=>{this.preconditions(e,t)})),this._participantOperationHandler=new as(this.logger,this.callTelemetry,y),this.setMeetingData(f),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 e=this.signalingSession?.participantManager?.localParticipant?.participantId;this._participantId=e||this._participantId}catch(e){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(e){this._isAudioStreamConnected!==e&&(this._isAudioStreamConnected=e,this._wasAudioStreamConnected=this._wasAudioStreamConnected||e,this.raiseChanged())}setMeetingRole(e){e!==this.localSignalingParticipant.meetingRole&&(this.logger.info(`changing self role to [${e}]`),this.localSignalingParticipant.meetingRole=e,this.event("meetingRoleUpdated").raise(e))}setAdvancedMeetingRole(e){e!==this.localSignalingParticipant.advancedMeetingRole&&(this.logger.info(`changing self advanced meeting role to [${e}]`),this.localSignalingParticipant.advancedMeetingRole=e,this.event("advancedMeetingRoleUpdated").raise(e))}setMeetingRoles(e){(0,Ws.isEqual)(e,this.localSignalingParticipant.meetingRoles)||(this.logger.info(`changing self meeting roles to [${e}]`),this.localSignalingParticipant.meetingRoles=e,this.event("meetingRolesUpdated").raise(e))}setParticipantType(e){e!==this.localSignalingParticipant.participantType&&(this.logger.info(`changing self participant user type to [${e}]`),this.localSignalingParticipant.participantType=e,this.event("participantTypeUpdated").raise(e))}setPropertyBag(e){e&&!(0,Ws.isEqual)(e,this.localSignalingParticipant.propertyBag)&&(this.logger.info(`changing self participant property bag to [${e}]`),this.localSignalingParticipant.propertyBag=e,this.event("propertyBagUpdated").raise(e))}setPropertyRosterVersion(e){e!==this.localSignalingParticipant.version&&(this.logger.info(`changing self participant property version to [${e}]`),this.localSignalingParticipant.version=e,this.event("propertyRosterVersionUpdated").raise(e))}setMaskedIdentityDetails(e=!1,t,i){this.localSignalingParticipant.isIdentityMasked===e&&this.localSignalingParticipant.maskedIdSeqNumber===t&&this.localSignalingParticipant.maskedId===i||(this.localSignalingParticipant.isIdentityMasked=e,this.localSignalingParticipant.maskedIdSeqNumber=t,this.localSignalingParticipant.maskedId=i,this.logger.info(`self participant masked identity details updated to [${JSON.stringify(this.maskedIdentityDetails)}]`),this.event("maskedIdentityDetailsUpdated").raise(this.maskedIdentityDetails))}setIsSomeoneStreamingVideo(e){this.logger.debug(`setting isSomeoneStreamingVideo to [${e}]`),this.isSomeoneStreamingVideo=e}setJoinAsStreamingUser(e){e!==this.joinAsStreamingUser&&(this.logger.info(`setting self join as streaming user to [${e}]`),this.joinAsStreamingUser=e)}setOtpIdentity(e){e!==this.otpIdentity&&(this.logger.info("setting self participant optIdentity"),this.otpIdentity=e)}get spamRiskLevel(){return this._spamRiskLevel}set spamRiskLevel(e){e&&(this._spamRiskLevel=e)}isMultiVBSSEnabled(){return this.maxVbssChannels>=1}get spamStirAttestation(){return this._spamStirAttestation}set spamStirAttestation(e){e&&(this._spamStirAttestation=e)}getScreenHandle(e){if(!this.sharedScreenHandle){const t=!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled,i=!!this.mediaSession&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&!this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing,n=this.mediaStateConfigurationHelper.isSending(0)&&i&&t,r=3===e?.getType()?e?.getDeviceId():void 0,s=this.callDeviceManager.getDeviceManager(Jh(2));s.setAudioSharingRequested(n),this.sharedScreenHandle=s.createDevicesHandle({audio:n,sharing:!0},"pluginlessCall:getScreenHandle()",r),this.sharedScreenHandle.on("onStreamStateChanged",((e,t)=>this.onSharingStreamStateChanged(e)))}return this.sharedScreenHandle}setCallOrigin(e){this.logger.info(`Set call origin to ${e}`),this._origin=e,this.callTelemetry.setCallOrigin(e),this.callTelemetry.recordEvent("_SetCallOrigin",{origin:e})}setMediaLegId(e){this._mediaLegId=e,this.callStats.setMediaLegId(e)}setCallId(e){this.callTelemetry.setCallId(e),this.callStats.setCallId(e),this._callId=e}setEndpointId(e){this._endpointId=e,this.logger.info(`[endpointId=${qe(this._endpointId,8)}]`),this.callTelemetry.setEndpointId(e),this.callStats.setEndpointId(e)}setFailureType(e){this.callTelemetry.setFailureType(e),this.failureType=e}setParticipantId(e){this._participantId!==e&&(this._participantId=e,this.logger.info(`[participantId=${this._participantId}]`),this.callTelemetry.setParticipantId(this.participantId),this.event("callLegIdChanged").raise(this.participantId))}setDisplayName(e,t=be()){this.logger.info(`[${t}][setDisplayName] displayName=${qe(e,4)}`),this.localSignalingParticipant.displayName=e,"anonymous"===this.participantType&&(this.callStats.setDisplayName(e),this.callTelemetry.setDisplayName(e),this.signalingSession.setDisplayName(e))}setCallerMri(e){this.callerMri=e,this.logger.info(`[callerMri=${De(this.callerMri)}]`)}setDisplayNameSource(e){this.displayNameSource=e,this.logger.info(`[displayNameSource=${this.displayNameSource}]`)}setTransferorMri(e){const t=uh(e);t!==this.transferorMri&&(this.transferorMri=t,this.logger.info(`transferorMri: ${De(this.transferorMri)}`),this.raiseChanged())}setGroupId(e,t=be()){this.logger.info(`[${t}][setGroupId] groupId=${De(e)}`),this.groupId!==e&&(this.groupId=e,this.callTelemetry.setGroupId(e),this.event("groupIdChanged").raise(e))}setMeetingData(e){if(e){if(e.meetingCode&&(!this.meetingData||this.meetingData&&e.meetingCode!==this.meetingData.meetingCode)){const t=e.meetingCode;this.logger.info(`[setMeetingData] meetingCode=${!!t}`),this.callTelemetry.setMeetingCode(t),this.signalingSession.setMeetingCode(t)}if(e.meetingUrl&&(!this.meetingData||this.meetingData&&e.meetingUrl!==this.meetingData.meetingUrl)){const t=e.meetingUrl.split("?")[0];this.logger.info(`[setMeetingData] meetingUrl=${!!e.meetingUrl}`),this.callTelemetry.setMeetingUrl(t),this.signalingSession.setMeetingUrl(t)}}this.meetingData=e}setHuddleGroupCall(e){this.isHuddleGroupCall!==!!e&&(this.logger.info(`[setHuddleGroupCall] new isHuddleGroupCall=${e}`),this.isHuddleGroupCall=e,this.callTelemetry.setIsHuddleGroupCall(!0))}onConversationStartTimeChanged(e,t=be()){if(this.logger.info(`onConversationStartTimeChanged: Conv start time=${e}`),e&&this._rawConversationStartTime!==e){this.logger.info(`[${t}][onConversationStartTimeChanged] rawConvStartTime=${e}`);try{this.conversationStartTime=new Date(e),this._rawConversationStartTime=e,this.callTelemetry.setConversationStartTime(e)}catch(t){this.logger.warn(`Failed to parse the raw conv start timestamp. Error: ${t}, rawConvStartTime: ${e}`)}}}setComplianceRecordingContent(e,t){try{if(!(0,Ws.isEqual)(this.complianceRecordingContent,t)){this.complianceRecordingContent=t;const i=t?JSON.stringify(t):"";this.callTelemetry.setComplianceRecordingContentLength(i.length),this.logger.info(`[${e}][setComplianceRecordingContent] complianceRecordingContentLength=${i.length}`)}}catch(t){this.logger.error(`[${e}][setComplianceRecordingContent] ${t}`)}}setThreadId(e,t=be()){this.threadId!==e&&(this.logger.info(`[${t}][setThreadId] threadId=${xe(e)}`),this.threadId=e,this.callTelemetry.setThreadId(e))}setBackroomThreadId(e,t=be()){this.backroomThreadId!==e&&(this.logger.info(`[${t}][setBackroomThreadId] backroomThreadId=${xe(e)}`),this.backroomThreadId=e,this.callTelemetry.setBackroomThreadId(e))}setStreamThreadId(e,t=be()){this.streamThreadId!==e&&(this.logger.info(`[${t}][setStreamThreadId] streamThreadId=${xe(e)}`),this.streamThreadId=e,this.callTelemetry.setStreamThreadId(e))}setLobbyThreadId(e,t=be()){this.lobbyThreadId!==e&&(this.logger.info(`[${t}][setLobbyThreadId] lobbyThreadId=${xe(e)}`),this.lobbyThreadId=e,this.callTelemetry.setLobbyThreadId(e))}setMeetingLayoutDetails(e,t=be()){(0,Ws.isEqual)(this.meetingLayoutDetails,e)||(this.logger.info(`[${t}][meetingLayoutDetails updated]`),this.meetingLayoutDetails=e,this.event("meetingLayoutChanged").raise(this.meetingLayoutDetails))}setCompositionServiceDetails(e,t=be()){(0,Ws.isEqual)(this.compositionServiceDetails,e)||(this.logger.info(`[${t}][compositionServiceDetails updated]`),this.compositionServiceDetails=e,this.event("compositionServiceDetailsChanged").raise(this.compositionServiceDetails),this.callTelemetry.setCompositionServiceState(e?.state))}setMessageId(e,t=be()){this.logger.info(`[${t}][setMessageId] messageId=${De(e)}`),this.messageId=e,this.callTelemetry.setMessageId(e)}setSkypeId(e,t=be()){this.skypeId!==e&&(this.logger.info(`[${t}][setSkypeId]`),this.skypeId=e,this.callTelemetry.setSkypeId(e))}setCallType(e,t){const i=this.logger.createFnLogger("setCallType",t);i.info(`current=${this.callType}, newValue: ${e}`),2!==this.callType||1!==e?e!==this.callType&&(this.callType=e,this.callTelemetry.setCallType(e),2===e&&this.callStats.localStats.call.event(2),this.raiseChanged()):i.logFailure("De-escalating to P2P should not happen!")}setConversationType(e,t){this.logger.createFnLogger("setConversationType",t).info(`current=${this.conversationType}, newValue=${e}`),e!==this.conversationType&&(this.conversationType=e,this.callTelemetry.setConversationType(e),this.raiseChanged())}setCallUsesMixer(e,t){this.callUsesMixer!==!!e&&(this.logger.info(`[${t}][setCallUsesMixer] new value=${e}`),this.callUsesMixer=e,this.callTelemetry.recordEvent("_CallUsesMixer",{newValue:e},t),this.dataChannel.setConfigProviderView(this.mediaSession?.getSessionConfig()))}_setMaxVbssChannels(e,t){this.logger.createFnLogger("MaxVbssChannels",t).info(`current=${this.maxVbssChannels}, newValue=${e}`),e!==this.maxVbssChannels&&(this.maxVbssChannels=e,this.callTelemetry.recordEvent("_setMaxVbssChannels",{MaxVbssChannels:e},t),this.raiseChanged())}setIsEscalationInProgress(e,t){this.logger.info(`[${t}][setIsEscalationInProgress] currentValue=${this.isEscalationInProgress}, newValue=${e}`),this.isEscalationInProgress=e,this.allowScreenSharingControl()&&this.screenSharingControl.setIsEscalationInProgress(e),this.callTelemetry.recordEvent("_EscalationInProgress",void 0,t)}setFromApplicationType(e,t){e&&(this.fromApplicationType=e,this.callTelemetry.recordEvent("_SetFromApplicationType",{fromApplicationType:e},t))}setCalleeAlternateId(e,t){e&&(this.calleeAlternateId=e,this.callTelemetry.recordEvent("_SetCalleeAlternateId",{hasCalleeAlternateId:!!e},t))}setEnableCaptcha(e){e!==this.localSignalingParticipant.enableCaptcha&&(this.logger.info(`setting self participant to enable captcha to [${e}]`),this.localSignalingParticipant.enableCaptcha=e,this.enableCaptcha=e)}processCallStartOptions(e,t){const i=this.logger.createFnLogger("_ProcessCallStartOptions",t);try{1&e.preheatFlags&&(this.isPreheatEnabled=!0)}catch(e){i.logFailure(e)}}getlocalScreenShareStream(){return(0,Ws.find)(this.localMediaStreams,(e=>2===e.mediaType))}setRoutingTimeout(e){this.routingTimeout=e,this.logger.info(`[routingTimeout=${this.routingTimeout}]`)}setMeetingLayout(e,t){const i=this.logger.createFnLogger("SetMeetingLayout",e);return Promise.resolve().then((()=>this.signalingSession.setMeetingLayoutAsync(e,t))).catch((e=>(i.logFailure(je(e)),Promise.reject(ns(e))))).then((()=>this._callOperationHandler.waitForOperation("SetMeetingLayout",e))).catch((t=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:$e(t)},e),i.logFailure(t),t}))}async selectDevices(e){this.callDeviceManager.isVirtualDeviceEnabled?this.callDeviceManager.selectDevices(e):this.logger.error("allowVirtualDeviceInCall not enabled.")}async getSelectDevices(){return this.callDeviceManager.getSelectedDevices()}createStage(e){throw new Error("Method not implemented.")}updateDisplayName(e){this.logger.info("updating displayName"),this.setDisplayName(e),this.signalingSession.participantManager.localParticipant.displayName=e}init(e){if(this.logger.info(`init callInitOptions:${function(e){const t={mediaPeerType:e.mediaPeerType,threadId:xe(e.threadId)};return ze(e.messageId)&&(t.messageId=e.messageId),ze(e.enableGroupCallMeetupGeneration)&&(t.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration),ze(e.endpointMetadata)&&(t.endpointMetadata=e.endpointMetadata),ze(e.onBehalfOf)&&(t.onBehalfOf=De(e.onBehalfOf)),ze(e.onBehalfOfUserDisplayName)&&(t.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName),ze(e.emergencyContent)&&(t.emergencyContent=e.emergencyContent),ze(e.isEmergency)&&(t.isEmergency=e.isEmergency),ze(e.broadcastContext)&&(t.broadcastContext=e.broadcastContext),e.meetingInfo&&(t.meetingInfo={tenantId:e.meetingInfo.tenantId,organizerId:De(e.meetingInfo.organizerId)},ze(e.meetingInfo.meetingType)&&(t.meetingInfo.meetingType=e.meetingInfo.meetingType),ze(e.meetingInfo.replyChainMessageId)&&(t.meetingInfo.replyChainMessageId=e.meetingInfo.replyChainMessageId)),e.transferContext&&(t.transferContext={transferorMri:De(e.transferContext.transferorMri),targetMri:De(e.transferContext.targetMri),context:ke(e.transferContext.context)},ze(e.transferContext.transferType)&&(t.transferContext.transferType=e.transferContext.transferType)),Ge(t)}(e)}`),this.signalingSessionCallOptions={teamsMessageId:e.messageId,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration,meetingInfo:e.meetingInfo,emergencyContent:e.emergencyContent?JSON.parse(e.emergencyContent):void 0,broadcastContext:e.broadcastContext,endpointMetadata:e.endpointMetadata},this.setMessageId(e.messageId),this.onBehalfOfMri=e.onBehalfOf,this.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName,e.threadId&&(this.setThreadId(e.threadId),this.signalingSession.setThreadId(e.threadId)),this.groupId&&this.signalingSession.setGroupId(this.groupId),this.signalingSession.setCallOptions(this.signalingSessionCallOptions),e.transferContext){switch(this.logger.info("Transfer: Call.init, set transferContext",function(e){return function(e){const t=JSON.stringify(e),i=JSON.parse(t);return i&&(ng(e,i,[],ig.pii.Omit),ng(e,i,["transferorMri","targetMri"],ig.pii.Mri),ng(e,i,void 0,ig.pii.UserName)),JSON.stringify(i)}(ke(e))}(e.transferContext)),this.signalingSession.setTransferContext(e.transferContext.context),e.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: ${e.transferContext.transferType} doesn't have a switch option`)}e.transferContext.context.callAcceptanceCallback?this._transferredCallAcceptanceCallback=e.transferContext.context.callAcceptanceCallback:this.logger.info("[failed]Transfer: Missing transferred call acceptance callback"),e.transferContext.transferorMri&&this.setTransferorMri(e.transferContext.transferorMri)}this.setIsEmergency(!!e.isEmergency),this.raiseChanged()}async initAsync(e){return this.init(e)}getIncomingRawAudioStream(e=be()){if(!this.mediaSession)throw this.logger.error("can not execute getIncomingRawAudioStream as there is no mediaSession"),new Error("NoMediaSession");return this.mediaSession.getIncomingRawAudioStream(e)}getUnmixedAudioProvider(){return this.unmixedAudioProvider?Promise.resolve(this.unmixedAudioProvider):Promise.reject("No audio provider available")}setDeviceManager(e){}async startVideo(e,t=be()){return this.startStopVideo(!0,t,e)}async stopVideo(e,t=be()){return this.startStopVideo(!1,t,e)}async dumpVideoSourceImages(){return Promise.reject(60)}async hold(e,t=be(),i,n){const r=this.logger.createFnLogger("Hold",t);return r.info(`[Hold][${t}] negotiationTag ${e} hold options: ${Ge(i)}`),4===this.state?(r.logFailure("Trying to put a call on hold which is already held state, early resolving the promise"),Promise.resolve(void 0)):i?.isLocal?this.localHold(t,i,n):this.holdWithRenegotiate(t,i)}async holdWithRenegotiate(e,t){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t):(this.logger.logFailure(`[Hold][${e}] 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(e,t,i){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t,i):(this.logger.logFailure(`[LocalHold][${e}] 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(e,t=be()){const i=this.logger.createFnLogger("Unhold",t);return 3===this.state?(i.logFailure("Trying to resume a call which is already in connected state, early resolving the promise"),Promise.resolve(void 0)):4===this.state?(i.info(`current hold state ${this.requestedHoldState}`),this.setHold(!1,t)):(i.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(e,t){const i=e.isOneToOneCall(),n=3===this.state,r=4===e.state,s=i&&n&&r;return this.logger.info(`[${t}][canMerge] Call ${e.callId} isOneToOne ${i} isCallConnected ${n} call.state ${this.state} isMergeOnHold ${r} mergeCall.state ${e.state} CanMerge result: ${s}`),s}async updateEndpointMetadata(e,t=be()){return this.signalingSession.updateEndpointMetadata(e,t)}async sendDtmfTone(e){if(this.mediaSession){const t=this.toneToString(e);return t?(this.logger.info(`[${Wr}][sendDtmfTone]DtmfTone: <omitted>`),Promise.resolve(this.mediaSession.sendDtmf(t))):Promise.reject(new Error("Unsupported DtmfTone"))}return Promise.reject(new Error("no mediaSession"))}async setAudioUsageMode(e){return Promise.reject(60)}async setAudioMidcallConfig(e,t){return Promise.reject(60)}async setAudioMidcallConfigJson(e,t=be()){if(!e)return Promise.reject(60);Wi(e.enableSpatialAudio)&&this.mediaSession?.configureSpatialAudio(e.enableSpatialAudio,t),e.noiseSuppressionMode&&await this.setNoiseSuppressionMode(e.noiseSuppressionMode,e.enableAEC)}async setParticipantSpatialAudioPositions(e,t=be()){const i=e.map((e=>({sourceId:this.participants.find((t=>t.id===e.participantId))?.audio.id,x:e.x,y:e.y})));return this.mediaSession?.setParticipantSpatialAudioPositions(i,t)}async setNoiseSuppressionMode(e,t){return this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe||this.mediaSession.getSessionConfig().config.wasmdns.enableNoiseSuppression?"Auto"===e?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,t))):this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,this.mediaSession.getSessionConfig().config.wasmvqe.enableAec))):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,t))):Promise.resolve()}setInitialTelemetry(e,t,i,n){let r,s,a,o,l;switch(e){case"Subscribe":case"SubscribeWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("SUBSCRIBE"),i||this.callTelemetry.setOperationVariant(e,"CCWM"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i});break;case"Acknowledge":0!==this.state&&8!==this.state&&this.callTelemetry.maybeRecordOperationSuccess(e,{code:4}),this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("callee"),this.signalingSession.setInitialTelemetry(e,{causeId:n});break;case"JoinCall":case"JoinWithMeetingData":this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("join"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),s=!(1&~t.callStartOptions.muteFlags),a=!(1&~t.callStartOptions.preheatFlags),o={muted:s,isPreheatOnly:a},this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,joinCallOptions:o,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCall":case"StartWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),l=t.callStartOptions,this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,callStartOptions:l,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,startCallOptions:t.callStartOptions,offerGenerationTime:Date.now()-t.callStartTime})}}async setHold(e,t,i,n){const r=this.logger.createFnLogger("setHold",t,`hold=${e}`);if(!this.canToggleAudio||this.callHoldResumeDeferred)return Promise.reject(new Error("can not set hold as it is already in progress"));this.callHoldResumeDeferred=new Kt,this.isHoldInProgress=e,this.canToggleAudio=!1,this.canToggleVideo=!1,this.canToggleScreenSharing=!1,this.requestedHoldState=e;const s=()=>{this.canToggleAudio=!0,this.canToggleScreenSharing=!0,this.canToggleVideo=!0};r.info(`start, holdOptions: ${JSON.stringify(i)}`);const a=this.callHoldResumeDeferred.promise,o=e?"Hold":"Unhold",l={debugContent:{clientScenario:this.convertClientScenario(n)}};try{if(e?this.isMuteOnHold=i&&i.isLocal&&5!==this.state:this.prepareModalitiesForResume(t),!this.isMuteOnHold){const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t),this.updateScreenSharingState(e,t)}e&&(this.prepareModalitiesForHold(t),5===this.state&&this.finishCallHoldResume(),this.setCallState(4,t)),this.isMuteOnHold&&this.setMuteOnHold(e,t),s();const n={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(o,n,null,t,l)}catch(i){this.callTelemetry.recordOperationFailure(o,{error:$e(i)},null,t,l),r.logFailure(i),s(),this.callHoldResumeDeferred?.reject(new Error(`Failed setting hold state to ${e}`)),this.callHoldResumeDeferred=null}return a}transferCall(e){return this.logger.warn("transferCall is deprecated, please use callBlindTransfer instead"),this.callBlindTransfer(e)}callBlindTransfer(e,t=be(),i){return this.executeCallTransfer(e,t,0,i)}callSafeTransfer(e,t=be(),i){return this.executeCallTransfer(e,t,0,i)}transferCallToVoicemail(e,t=be()){return this.executeCallTransfer(e.transferTargetMri,t,2,void 0)}callConsultativeTransfer(e,t=be(),i,n){const r=this.logger.createFnLogger("ConsultativeTransfer",t);let s;e.participants.length>1?(s=this.getParticipantByLegId(i,e),s||(r.warn("getParticipantByLegId did not find a match in the participants list, defaulting to first participant"),s=e.participants[0])):s=e.participants[0];const a=s&&s.acceptedBy||s&&s.id;return r.info(`transferTargetParticipantLegId: ${i} targetMri: ${De(a)}`),this.executeConsultCallTransfer(e.callId,a,i,t,n)}async consultativeTransferWithPickupCode(e,t){const i=this.logger.createFnLogger("ConsultativeTransferWithPickupCode",t);if(i.info(`pickup code: ${e}`),!e||isNaN(Number(e)))return i.info("pickup code cannot be empty"),Promise.reject(ns("TransactionDisallowed"));const n=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),r=`4:${mr}`,s={unparkContent:{pickupCode:Number(e)}};return this.signalingSession.transferCallAsync(r,"TransferTypeStandard",s,{disableForwardingAndUnanswered:!1},t),n}callRedirect(e,t=be()){return this.logger.createFnLogger("CallRedirect",t).info(`redirectOptions: ${JSON.stringify(e)}`),this.stopInternal({terminatedReason:75,redirectOptions:e,causeId:t}).then((()=>({code:302,subCode:3020,phrase:js,resultCategories:["Success"]})))}convertParkContext(e){switch(e){case 1:return"sharedLinePark";case 4:return"sharedLineParkV2";case 0:return"teamPark";case 3:return"serverHoldV2";case 5:return"callPark";default:return"serverHold"}}convertClientScenario(e){switch(e){case 0:return"breakoutRoom";case 1:return"musicOnHoldV2";case 2:return"sharedLineAppearanceV2";default:return}}park(e,t=be()){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [ParkCall] start - context ${e} parkType ${i}`),5===e?(this.callTelemetry.recordOperation(`${co(i)}`,t),this._pendingParkPromise=this._callOperationHandler.createPendingOperation("CallParkV2",void 0,t)):this._pendingParkPromise=this._callOperationHandler.waitForOperation("ParkCall"),"serverHoldV2"!==i&&"callPark"!==i&&this._setParkState(1),this.signalingSession.parkCallAsync(i,t).catch((e=>{this.logger.info(`[${t}] [ParkCall] error in parkCallAsync (synchronous error) : ${$e(e)}. Hold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("ParkCall",{error:$e(e)},t)})),this._pendingParkPromise}async unpark(e,t){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [UnparkCall] start - context ${e} parkType ${i}`),this._pendingUnparkPromise=this._callOperationHandler.waitForOperation("UnparkCall"),this.signalingSession.unparkAsync(i,t).catch((e=>{this.logger.info(`[${t}] [UnparkCall] error in unparkAsync (synchronous error) : ${$e(e)}. Unhold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UnparkCall",{error:$e(e)},t)})),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(e=!1){if(e){const e=(this.state,[0,1]);return 1===this.callType&&e.includes(this.participants.length)}return 1===this.callType&&1===this.participants.length}setMuteOnHold(e,t){this.mediaSession.muteHold(e,t),e||(this.computeCallState(t),this.isMuteOnHold=!1),this.finishCallHoldResume()}finishCallHoldResume(e){e?this.callHoldResumeDeferred?.reject(e):this.callHoldResumeDeferred?.resolve(),this.isHoldInProgress=!1,this.callHoldResumeDeferred=null}computeCallState(e){let t=3;this._callInLobby?t=10:this.signalingSession.participantManager.localParticipant.isStaging&&(t=13),this.logger.info(`[${e}][computeCallState] the call state will be set to ${t}`),this.setCallState(t,e)}async prepareModalitiesForResume(e){this.mediaStateConfigurationHelper.isSending(1)&&await this.turnOnLocalVideoPreview(e)}async prepareModalitiesForHold(e){await this.turnOffLocalVideoPreview(e)}updateMediaState(e,t){this.setVideoOn(e.video===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.video===this.mediaAgent.constants.MEDIA_STATE.send,t),this.setAudioOn(e.audio===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.audio===this.mediaAgent.constants.MEDIA_STATE.send,t)}updateScreenSharingState(e,t){this.setScreenSharingOn(e.sharing===this.mediaAgent.constants.MEDIA_STATE.send,t)}onSharingStreamStateChanged(t){const i=be();this.logger.info(`[${i}] Sharing stream state moved to ${t}`);const n={mediaType:2,mediaDirection:1,mediaStreamState:e.streamingStatetoMediaStreamState(t)};this.event("mediaStreamStateChanged").raise(n),this.callStats.localStats.screenShare.streamStateChanged(t),"stopped"===t&&(this.canToggleScreenSharing=!0,this.stopScreenSharing(),"screenSharingCall"!==this.conversationType||this.participants.some((e=>3===e.state))||this.stop(!0,i))}async startScreenSharing(e,t,i,n=be()){this.allowScreenSharingControl()&&(this.screenSharingControl.isInternalViewerControlEnabled()&&this.screenSharingControl.shutdownControlForViewer(),this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(i));const r=this.logger.createFnLogger("StartScreenSharing",n);return r.info(`started. negotiationTag is ${i}`),this.canToggleScreenSharing?this.isScreenSharingOn?(r.logSuccess("Resolving early because screen sharing is already on"),Promise.resolve()):(this.screenSharingRenegotiationDeferred&&(r.logFailure("called before the renegotiation deferred for the previous one has been closed"),this.screenSharingRenegotiationDeferred.resolve()),this.screenSharingRenegotiationDeferred=new Kt,this.callStats.localStats.newSession(2),this.callStats.localStats.screenShare.start(),this.mediaStateConfigurationHelper.isDisabled(2)&&r.info("sharing modality was skipped till now. Adding it now"),this.canToggleScreenSharing=!1,this.callStats.localStats.screenShare.event(0),this.getScreenHandle(e).acquire().then((()=>(r.logSuccess("sharing stream acquired"),this.mediaStateConfigurationHelper.enableModality(2),this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this._delayedElevationPending&&!this._delayedElevationQueued?this.triggerDelayedReconnectIfNeeded(n):Promise.resolve()))).then((()=>this.updateMediaModalities(void 0,n,i))).then((()=>(r.logSuccess("updateMediaModalities done"),this.callStats.localStats.screenShare.negotiationStateChanged("started"),this.setScreenSharingOn(!0,n),this.canToggleScreenSharing=!0,this.screenSharingRenegotiationDeferred.promise))).then((()=>{this.enableControlInjector(),this.callStats.localStats.screenShare.negotiationStateChanged("completed")})).catch((e=>{this.callTelemetry.updateOperationData("StartScreenSharing",{error:$e(e)},n),this.setScreenSharingOn(!1,n),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!0,this.disposeSharingScreenHandle();const t=e.error;throw t&&491===t.code?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),r.logFailure("starting screen sharing failure with reason glare")):"ScreenSharingStopped"===e.reason?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","sharingStopped"),r.logFailure("expected starting screen sharing failure with reason stopped")):(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","other"),r.logFailure(e)),e}))):Promise.reject(new Error("cannot start screen sharing"))}async stopScreenSharing(e,t,i=be()){const n=this.logger.createFnLogger("StopScreenSharing",i);if(n.info(`started. negotiationTag is ${t}`),!this.canToggleScreenSharing)throw n.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,i,t),this.canToggleScreenSharing=!0,this.callStats.localStats.screenShare.stop(),this.disposeSharingScreenHandle(),this.mediaAgent.getDeviceManager().shareSystemSound(!1),this.mediaAgent.getDeviceManager().setAudioSharingRequested(!1);try{this.setScreenSharingOn(!1,i)}catch(e){throw n.logFailure(e),this.callTelemetry.updateOperationData("StopScreenSharing",{error:$e(e)},i),e}}else n.logFailure("screensharing is not on, ignore this operation")}async startDataChannel(e,t=be()){if(!this.allowDataChannel())throw new Error("startDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.enableModality(3),await this.updateMediaModalities({},t)}async stopDataChannel(e,t=be()){if(!this.allowDataChannel())throw new Error("stopDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.removeModality(3),await this.updateMediaModalities({},t)}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 e=this.mediaSession?.getSessionConfig()?.config;return e?!this.allowDataChannel()||e.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(e){this.signalingSession.updateDominantSpeakerHistoryMessageSubscription(e),e&&this.mediaSession?.getDiagnostics?.().dshDiagnostics.setCurrentActiveStrategy("signaling")}async sendUserEvents(e,t){return this.dataChannel.sendUserEvents(e,t)}async shareSystemSound(e,t=be()){const i=this.logger.createFnLogger("ShareSystemSounds",t,`shareSystemSound=${e}`);if(!(this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing))return i.error("shareSystemSound not allowed"),Promise.reject(60);try{return void this.mediaAgent.getDeviceManager().shareSystemSound(e)}catch{return i.error("shareSystemSound failed with device error"),Promise.reject(58)}}async mute(e=mi()){return this.isMuted?Promise.reject(ns("TransactionDisallowed")):this.muteUnmute(!0,e)}async unmute(e=mi()){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")&&await this._callOperationHandler.waitForOperation("_PromotionToRealtime"),this.muteUnmute(!1,e)}async muteSpeaker(e=be()){return this.muteUnmuteSpeaker(!0,e)}async unmuteSpeaker(e=be()){return this.muteUnmuteSpeaker(!1,e)}async getSpeakerVolume(e=be()){return await this.mediaSession.getSpeakerVolume(e)}async setSpeakerVolume(e,t=be()){return this.mediaSession.setSpeakerVolume(e,t)}async muteParticipants(t,i,n=mi()){const r=this.logger.createFnLogger("MuteParticipants",n,`muteScope=${t}`);r.info(`callParticipants count=${i.length}`);const s=e.convertMuteScope(t);if(void 0===s)return r.logFailure(`Unrecognized ${t}`),Promise.reject(new Error("Unrecognized muteScope"));if(fh(this.state,[11,12]))return r.logFailure("Can not mute/unmute during preheat call"),Promise.reject(60);const a=[];return i.forEach((e=>{a.push(e.id)})),this.signalingSession.muteAsync(s,a,n).then((e=>this.handleParticipantsMutedUpdated(e,n))).catch((e=>(this.callTelemetry.updateOperationData("MuteParticipants",{error:$e(e)},n),r.logFailure(e),e?.endCode?Promise.reject(e.endCode):Promise.reject(e))))}async startAudio(e,t=be()){const i=this.logger.createFnLogger("StartAudio",t);if(this.receiveOnlyAudioOnCallStart=!1,3!==this.state)return i.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(t)}catch(e){return i.logFailure(e),Promise.reject(25)}const n=await this.startStopAudio(!0,t);return await this.signalingSession.recordTelemetryForStartAudio(n),{code:n}}async stopAudio(e,t=be()){const i=this.logger.createFnLogger("StopAudio",t);if(3!==this.state)return i.logFailure("Cannot stopAudio when call is not connected"),Promise.reject(60);this.mediaStateConfigurationHelper.removeModality(0);const n=await this.startStopAudio(!1,t);return await this.turnOffLocalVideoPreview(t),await this.signalingSession.recordTelemetryForStopAudio(n),{code:n}}assimilate(e,t,i,n=be()){return Promise.reject(new Error("Not implemented"))}async merge(e,t,i=be()){const n=this.logger.createFnLogger("MergeCall",i);n.error(`merge callId ${e.callId} callMergeOptions ${JSON.stringify(t)}`);const r=this.canMerge(e,i);if(!r)return n.info(`Error. ${je(r)}`),Promise.reject(ns("TransactionDisallowed"));const s=[];return e.participants.forEach((e=>{s.push(this._callOperationHandler.createPendingOperation("MergeCall",e.id,i))})),(await this.mergeCallByAddParticipantWithReplaces(t,e.participants,e,1,"MergeCall",i,s,void 0))[0]}async mergeParticipants(e,t,i,n,r){const s=this.logger.createFnLogger("MergeParticipants",n),a=[];if(!e)return Promise.reject(ns("Invalid callToMerge"));if(0===t.length)return Promise.reject(ns("Invalid participantIds"));const o=[];for(const i of t){let t=xd(e,i);if(!t&&Ld(e,i)&&(s.info("found self endpoint, use localSignalingParticipant"),t=this.localSignalingParticipant),t){const e=mi(),r={id:t.id,participantId:e,replacementParticipantId:i,nonMaskedId:t.nonMaskedId};a.push(r),o.push(this._callOperationHandler.createPendingOperation("MergeParticipant",e,n))}else{const e={code:406,subCode:5201,phrase:`participantLegId ${i} is invalid!`};o.push(Promise.reject(ns(e)))}}return this.mergeCallByAddParticipantWithReplaces(i,a,e,3,"MergeParticipant",n,o,r)}async mergeWithPickupCode(e,t,i=be()){const n=this.logger.createFnLogger("MergeWithPickupCode",i);if(n.info(`mergeWithPickupCode: pickup code: ${e}, groupId: ${De(t.groupId)}, threadId: ${xe(t.threadId)} messageId: ${t.messageId}`),!e||isNaN(Number(e)))return n.info("mergeWithPickupCode: pickup code cannot be empty"),Promise.reject(ns("mergeWithPickupCode: pickup code cannot be empty"));const r={additionalData:t.additionalData,groupId:t.groupId,threadId:t.threadId,messageId:t.messageId,replacementType:2,pickupCode:Number(e)},s={id:`4:${mr}`};return Promise.resolve().then((()=>Promise.all(this.signalingSession.addParticipantsAsync([s],r,i)))).then((e=>(e.length>0&&this.signalingNotifications.onParticipantJoined(e[0],i),Promise.resolve({code:0,subCode:0,phrase:"TransactionComplete"})))).catch((e=>{n.logFailure(`Participant was not added to call, error=${je(e)}`);const t=this._handleParticipantOperationFailure("MergeWithPickupCode",e,i,null,!0).reason;return Promise.reject(e?e.endCode:t||0)}))}async setMaxVideoChannels(e){return Promise.reject(60)}async setMaxVbssChannels(e){return Promise.reject(60)}async stop(e=!1,t=be(),i,n){const r=this.logger.createFnLogger("StopAudio",t);if(6===this.state)return r.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 r.logFailure("Trying to stop a call which is already Disconnected"),Promise.reject(new Error("cannot stop call in Disconnected state"));if(this.disposedPromise)return r.logFailure("Call already ended"),Promise.reject("Call already ended");let s=0;1===this.state&&(s=10);const a=n?{clientReasonSubCode:n.clientSubCode,clientReasonPhrase:n.clientPhrase}:{};n?.clientSubCode===Dr&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.enabled&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.clientPhrases.includes(n?.clientPhrase)&&(a.code=Pr,a.subCode=Dr,a.phrase="CallEndReasonVDIdisconnect",a.resultCategories=["UnexpectedClientError"],s=4);const o={terminatedReason:s,forEveryone:e,causeId:t,...i,rejectReason:a};return this.stopInternal(o)}publishState(e,t){const i=ho(e.type),n=this.getPluginlessPublishLevel(e.level),r=e.participantIds&&e.participantIds.length>0?"specified":void 0;return this.callTelemetry.setOperationVariant("PublishState","specified"===r?`${i}Specified`:`${i}None`,t),this.signalingSession.publishStateAsync(i,n,t,e.content,r,e.participantIds)}publishStatesForEveryone(e,t){const i=ho(e.type),n=this.getPluginlessPublishLevel(e.level);return this.callTelemetry.setOperationVariant("PublishState",`${i}All`),this.signalingSession.publishStateAsync(i,n,t,e.content,"all")}removeState(e,t){return this.signalingSession.removeStateAsync(t,"specified",void 0,e.stateIds).then((e=>Promise.resolve()))}removeStatesForEveryone(e,t){const i=ho(e.type);return this.signalingSession.removeStateAsync(t,"all",i,void 0).then((e=>Promise.resolve()))}updateMeetingSettings(e,t){return this.signalingSession.updateMeetingSettingsAsync({allowRaiseHands:e.allowRaiseHands,attendeeRestrictions:e.attendeeRestrictions,lockMeeting:e.lockMeeting,breakoutRoomsEnabled:e.breakoutRoomsEnabled,allowPresentersToManageBreakoutRooms:e.allowPresentersToManageBreakoutRooms,disableMdpClientAudioRecording:e.disableMdpClientAudioRecording,refreshSettings:e.refreshSettings,aiInterpretationEnabled:e.aiInterpretationEnabled,groupCopilotDetails:e.groupCopilotDetails},t)}updateMeetingGroups(e,t){this.logger.info(`[UpdateMeetingGroups][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("UpdateMeetingGroups",e),n={fromGroup:t.fromGroup,toGroup:t.toGroup,scope:Up(t.scope)};return t.participants&&(n.participants=function(e){const t=[];for(const i in e)if(e[i].participantLegIdMap)for(const n in e[i].participantLegIdMap){const r=e[i].participantLegIdMap[n].endpointId;t.push({id:i,mri:i,participantId:n,...r&&{endpointId:r}})}else t.push({id:i,mri:i});return t}(t.participants)),this.signalingSession.updateMeetingsGroupsAsync(e,n).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingGroups] error in updateMeetingGroups (synchronous error) : ${$e(t)}. updateMeetingGroupsPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingGroups",{error:$e(t)},e)})),i}updateMeetingLiveState(e,t){return this.logger.info(`[UpdateMeetingLiveState][${e}] options ${Ge(t)}`),this.signalingSession.updateMeetingLiveStateAsync(e,t).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingLiveState] error in updateMeetingLiveState (synchronous error) : ${$e(t)}. promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingLiveState",{error:$e(t)},e)})),this._callOperationHandler.waitForOperation("UpdateMeetingLiveState",e)}updateMeetingStates(e,t=be()){var i;this.logger.info(`[UpdateMeetingStates][${t}]`);const n={},r=[];e.operationId=e.operationId||t;for(const s of Object.keys(e.meetingStates)){const a=e.operationId+"_"+s;r.push(a);const o=this._callOperationHandler.createPendingOperation("UpdateMeetingStates",a,t);n[i=e.operationId]??(n[i]={}),n[e.operationId][s]=o,this.callTelemetry.recordOperation("UpdateMeetingStates",t,a)}return Promise.resolve().then((()=>this.signalingSession.updateMeetingStatesAsync(t,e))).then((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{data:$e(e)},t,i)})).catch((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{error:$e(e)},t,i);this.logger.logFailure(e)})).then((()=>n))}async updateParticipantInterpretationState(e,t){if(this.logger.info(`[UpdateParticipantInterpretationState][${e}] options ${Ge(t)}`),0===t.length)return Promise.reject(ns("Invalid UpdateParticipantInterpretationState options"));const i=this.signalingSession.updateParticipantInterpretationStateAsync(e,t),n=[];t.forEach((t=>{n.push(this._callOperationHandler.createPendingOperation("UpdateParticipantInterpretationState",t.id,e))}));for(let n=0;n<i.length;n++){const r=i[n],s=t[n];r.then((()=>{this.logger.logSuccess(`updateParticipantInterpretationState succeeded for [id=${De(s.id)}]`);const t={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("UpdateParticipantInterpretationState",t,s.id,e),this._callOperationHandler.maybeResolveOperation("UpdateParticipantInterpretationState",t,s.id,e)})).catch((t=>{this.logger.error(`[${e}] [UpdateParticipantInterpretationState] error in updateParticipantInterpretationState (synchronous error) : ${$e(t)}. updateParticipantInterpretationStatePromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateParticipantInterpretationState",{error:$e(t)},e);const i=this._handleParticipantOperationFailure("UpdateParticipantInterpretationState",t,e,s.id).reason,n=t?.endCode||i||0;this._callOperationHandler.maybeRejectOperation("UpdateParticipantInterpretationState",n,s.id,e)}))}return Promise.resolve(n)}async updateParticipantsProperties(e,t){const i=this.logger.createFnLogger("UpdateParticipantsProperties",t);if(i.info(`options ${De(Ge(e))}`),!e)return Promise.reject(ns("Invalid input: UpdateParticipantsPropertiesContext"));const n={},r=e.scope,s=e.operationId,a=new Set;if("self"===r){const i=this.signalingSession.participantManager.localParticipant.id;for(const r in e.propertyBag){const e=Pu(i,s,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},a.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,De(e))}}else{if("specified"!==r||!this._isUpdatePropertiesSpecifiedAllowedByEcs)return Promise.reject("This scope is not supported.");{const i=e.participants;for(const e of i){const i=e.id;for(const r in e.propertyBag){const e=Pu(i,s,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},a.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,De(e))}}}}return i.info(`promises created: ${De(Ge(n))}`),this.signalingSession.updateParticipantsPropertiesAsync(e,a,s,t).catch((e=>{const r=je(e);i.info(`[failed][reason=${r}]`);const s={...e};this.callTelemetry.updateOperationData("UpdateParticipantsProperties",{error:$e(r)},t);for(const e of Object.keys(n))this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",s,e,t)})),Promise.resolve().then((()=>n))}joinMeetingGroup(e,t){this.logger.info(`[JoinMeetingGroup][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("JoinMeetingGroup",e),n={..."meetingGroupId"in t&&{meetingGroupId:t.meetingGroupId},..."meetingGroupLabel"in t&&{meetingGroupLabel:t.meetingGroupLabel},...t.groupPreferences&&{groupPreferences:t.groupPreferences}};return this.signalingSession.joinMeetingGroupAsync(e,n).catch((t=>{const i=$e(t);this.logger.info(`[${e}] [JoinMeetingGroup] error in joinMeetingGroup (synchronous error) : ${i}. joinMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("JoinMeetingGroup",{error:i},e)})),i}leaveMeetingGroup(e,t){this.logger.info(`[LeaveMeetingGroup][${e}] options ${Ge(t)}`);const i=this._callOperationHandler.waitForOperation("LeaveMeetingGroup",e),n={meetingGroupId:t.meetingGroupId};return this.signalingSession.leaveMeetingGroupAsync(e,n).catch((t=>{const i=$e(t);this.logger.info(`[${e}] [LeaveMeetingGroup] error in leaveMeetingGroup (synchronous error) : ${i}. leaveMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("LeaveMeetingGroup",{error:i},e)})),i}sendMessages(e,t){var i,n;this.logger.info(`[SendMessages][${e}]`);const r={};for(const s of t)if(0===s.scope){const t=this._callOperationHandler.createPendingOperation("SendMessages",s.operationId,e);r[s.operationId]={all:t},this.callTelemetry.recordOperation("SendMessages",e,s.operationId)}else if(1===s.scope)for(const t in s.to)if("participant"===s.to[t].level){const n=wu(t,s.operationId),a=this._callOperationHandler.createPendingOperation("SendMessages",n,e);r[i=s.operationId]??(r[i]={}),r[s.operationId][t]=a,this.callTelemetry.recordOperation("SendMessages",e,n)}else if("endpoint"===s.to[t].level)for(const i in s.to[t].participantLegIdMap){const t=Au(i,s.operationId),a=this._callOperationHandler.createPendingOperation("SendMessages",t,e);r[n=s.operationId]??(r[n]={}),r[s.operationId][i]=a,this.callTelemetry.recordOperation("SendMessages",e,t)}return this.signalingSession.sendProxiedMessageAsync(e,t).then((e=>{for(const t of e)t.then((e=>{this._callOperationHandler.maybeResolveOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)})).catch((e=>{this._callOperationHandler.maybeRejectOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)}));return r}))}async updateMonitorSession(e,t=be()){this.logger.info(`updateMonitorSession: monitorActionType: ${e.monitorActionType}, monitorData: ${e.monitorData}`);const i=function(e){switch(e){case 0:return"Monitor";case 1:return"Whisper";case 2:return"Barge";case 3:return"Takeover";default:return}}(e.monitorActionType);if(void 0===i){const t={code:Rr,subCode:Or,phrase:`Invalid monitor action type ${e.monitorActionType}`};return Promise.reject(t)}const n={monitorActionType:i,monitorData:e.monitorData},r=this._callOperationHandler.waitForOperation("UpdateMonitorSession","",t);return this.signalingSession.updateMonitorSessionAsync(n,t).catch((e=>{const i=$e(e);this.logger.info(`[${t}] [UpdateMonitorSession] error in updateMonitorSession (synchronous error): ${JSON.stringify(i)}. updateMonitorSessionPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMonitorSession",{error:i},t)})),r}switchInterpreterGroup(e){return Promise.reject(new Error("Not implemented"))}setLiveInterpretationAttributes(e,t){return Promise.reject(new Error("Not implemented"))}async updateMeetingRoles(e,t,i=be()){return 3===this.state&&this.signalingSession.hasOwnProperty("updateMeetingRolesAsync")?this.signalingSession.updateMeetingRolesAsync(e,t,i):Promise.reject({code:Rr,subCode:kr,phrase:"ActionNotAllowed"})}stopInternal(e){const t=this.logger.createFnLogger("stopInternal",e.causeId),i=e.terminatedReason||0;let n=e.rejectReason&&(e.rejectReason.code||e.rejectReason.subCode)?e.rejectReason:this.getRejectionInfoFromTerminatedReason(i);if(e.rejectReason&&(n||(n={}),n.clientReasonSubCode=e.rejectReason.clientReasonSubCode,n.clientReasonPhrase=e.rejectReason.clientReasonPhrase),t.info(`started, terminatedReason=${i}, rejectReason=${Ge(n)}`),6===this.state)return t.logFailure("Trying to stop a call which is already Disconnecting"),this.disconnectingPromise;if(7===this.state)return t.logFailure("Trying to stop a call which is already Disconnected"),this.disconnectingPromise;this.setCallState(6,e.causeId,i);const r={causeId:e.causeId,forEveryone:e.forEveryone,scope:this.mapEndpointScope(e.scope),redirectOptions:e.redirectOptions&&zh(e.redirectOptions)};return 1===e.scope&&(n.code=Ar,n.subCode=Lr,n.phrase="EndedByRemoteEndpoint"),this.disconnectingPromise=Promise.all([this.cleanUpMedia(e.causeId,n).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((i=>{throw t.logFailure(`cleanUpMedia failed with reason=${je(i)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(i)},e.causeId),i})),this.signalingSession.endAsync(n,r).catch((e=>{throw t.logFailure(`endAsync failed with reason=${je(e)}`),e}))]).catch((i=>{throw t.logFailure(i),this.cleanUp(e.causeId,n),i})).then((()=>this.cleanUp(e.causeId,n))).catch((t=>{throw this.callTelemetry.updateOperationData("StopCall",{error:$e(t)},e.causeId),this.setCallState(7,e.causeId,i),t})),this.disconnectingPromise}async cleanUp(e,t){return this.logger.info(`[${e}][cleanup]start`),this.disposedPromise||(this.disposedPromise=this.cleanUpFinalize(e,t),this._getCallEndOperation().catch(wr).then((()=>{const t={code:Rr,subCode:Nr};this._callOperationHandler.rejectPendingOperations(61,e,t),this._participantOperationHandler.rejectPendingOperations(47,e,t)}))),this.disposedPromise}async cleanUpMedia(e,t){return this.mediaDisposedPromise||(this.callTelemetry.recordOperation("_MediaCleanUp",e),this.mediaDisposedPromise=(async()=>{this.callDeviceManager?.dispose(),this.callDeviceManager=null,this.turnOffLocalVideoPreview(e),this.localVideoContainer=null,this.disposeContentSharingSessions(),this.disposeSharingScreenHandle();const i=this.mediaSession;if(this.reportMediaStats=!!i,!i)return;this.unmixedAudioProvider.dispose(),this.dataChannel.dispose(),this.screenSharingControl.dispose(e),this.remoteUFDHandler.dispose(),this.mediaSession=null,this.streamManager.setMediaSession(null,e),this.participants?.forEach((t=>{t.setMediaSession(null,e)}));const n=i.terminate(e,t);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(t),this.screenSharingRenegotiationDeferred=null,this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.removeModality(0),this.mediaStateConfigurationHelper.removeModality(3),this.mediaStateConfigurationHelper.removeModality(2),this.batteryStatus?.dispose(),i?.getSessionConfig()?.config?.useOneDsLogger&&i.getSessionConfig().config.addTelemetryReportingCallback&&window.removeEventListener("beforeunload",this.beforeUnloadTelemetrySender);try{await n}finally{await this.collectCallStats(i),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(i.getMediaControlPlaneInstance()?.getTelemetryReport()))}})()),this.mediaDisposedPromise}async cleanUpFinalize(e,t){try{await this.cleanUpMedia(e,t)}catch(t){this.logger.info(`[${e}][cleanUpMedia] failure: ${je(t)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(t)},e)}this.callTelemetry.recordOperationSuccess("_MediaCleanUp");const i=this.reportCallEndStats(this.reportMediaStats);this.mediaSession?.getSessionConfig().config.waitReportStatsAtCallStop&&await i}async createContentSharingSession(e,t,i,n,r=be()){if(this.signalingSession.signalingAgentConfig.checkAttendeeRoleInCreateContentSharing&&"attendee"===(this.advancedMeetingRole||this.meetingRole)){const e={terminatedReason:8,terminatedReasonCode:403,terminatedReasonSubCode:0,errorMessage:"Failed due to insufficient permissions"};return Promise.reject(e)}const s=new Bg(this.callTelemetry,this.logger,this.signalingSession,e,t,n,i);return this.contentSharingSessions.push(s),s.changed((()=>this.removeContentSessionIfEnded(s))),this.event("contentSharingChanged").raise(),Promise.resolve(s)}stopWithBeacon(e=be()){if(6===this.state||7===this.state)return!0;this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&(this.callEndDiagnosticsInfo={callControllerCode:Ar,callControllerSubCode:xr},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.setCallState(6,e,1));const t=this.signalingSession.endWithBeacon(e);return this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&this.setCallState(7,e,1),t}disposeContentSharingSessions(){this.contentSharingSessions.forEach((e=>{e.dispose(),this.removeContentSessionIfEnded(e)})),this.event("contentSharingChanged").raise()}isPreheatedOnly(){return!!(12===this.state||2===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall")||9===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))}removeContentSessionIfEnded(e){7!==e.contentSharingStatus&&8!==e.contentSharingStatus||(this.logger.info("stopping the content sharing session."),(0,Ws.remove)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.contentSharingGuid)).length&&this.event("contentSharingChanged").raise())}getRejectionInfoFromTerminatedReason(e){switch(e){case 53:return{code:ys,subCode:3112,phrase:"MediaWhitelistingIssue"};case 4:return{code:ys,subCode:this._wasAudioStreamConnected?3101:3100,phrase:this._wasAudioStreamConnected?"CallEndReasonMediaDropAfterConnectError":"CallEndReasonMediaDropDuringConnectError"};case 47:return{code:ys,subCode:3111,phrase:"CallEndReasonMediaOfferProcessingError"};case 38:return{code:ys,subCode:3108,phrase:"RetargetNotSupported"};case 10:return{code:603,subCode:0,phrase:$s};case 25:return{code:Ds,subCode:3110,phrase:"CallEndReasonMediaError"};case 58:return{code:ys,subCode:Ls,phrase:"CallEndReasonMediaPermissionError"};case 7:return{code:Ds,subCode:0,phrase:"CallEndReasonUnknown"};case 0:case 1:return{code:0,subCode:0,phrase:$s};case 75:return{code:302,subCode:3020,phrase:js,resultCategories:["Success"]};case 77:return{code:0,subCode:58e4,phrase:"CallEndReasonSuspended"}}return null}async acknowledge(e,t,i=be()){const n=this.logger.createFnLogger("Acknowledge",i),r=Date.now();if(this.setInitialTelemetry("Acknowledge",{callStartTime:r},"",i),0!==this.state&&8!==this.state)throw new Error(`Trying to acknowledge a call that has already been acted on ${this.state}`);n.info(`isMultiParty=${e.isMultiParty}`),n.info(`fromMixer=${e.fromMixer}`),n.info(`participantId=${e.participantId}`),n.info(`callType=${e.callType}`),this.attachToCallAndGetOffer=new Kt,this.setCallType(e.isMultiParty?2:1,i),this.setCallUsesMixer(!!e.fromMixer,i),this.setCallerMri(uh(e.callerId)),this.setDisplayNameSource(e.displayNameSource),this.setTransferorMri(e.transferorId),this.transferorType=e.transferorType,this.transferorDisplayName=e.transferorDisplayName,this.incomingCallType=e.callType,this.consultativeCallId=e.consultativeCallId,this.callQueueInfo=e.callQueueInfo,this.setFromApplicationType(e.fromApplicationType,i),this.setCalleeAlternateId(e.calleeAlternateId,i),this.setRoutingTimeout(e.routingTimeout),this.callStats.localStats.startCall();const s=mh(n);try{if(s.executeSync("ProcessIncomingCallRequest",(()=>this.signalingSession.processIncomingCallRequest(e,t,i))),this.setParticipantId(this.participantId),s.executeSync("ResolvePotentialConflict",(()=>this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)))===this.signalingSession)return Promise.reject({code:7,success:!1});const r=async()=>{s.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(i))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled());const e=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 t=await s.execute("WaitForMediaOffer",(()=>e?Promise.resolve(e):this.attachToCallAndGetOffer.promise));let r;try{r=await s.execute("ProcessOffer",(()=>this.mediaSession.processOfferAsync(t,i)))}catch(e){r=await this._handleOfferProcessingError(e,i,n)}await s.execute("ProcessOfferedModalities",(()=>this._processOfferedModalities(r,i)))},a=(()=>s.execute("SendAttach",(()=>this.signalingSession.sendAttachToCall(i))).then((()=>this.setCallState(1,i))))();return await Promise.all([a,r()]).catch((async e=>{throw await a,e})),await s.execute("TrySendingProvisionalAnswer",(()=>this._trySendProvisionalMediaAnswer(i))),s.executeSync("OnAcknowledgeSuccess",(()=>this._onAcknowledgeSuccess(n,s.getTelemetryData(),i)))}catch(e){return this._onAcknowledgeError(e,i,n,s.getTelemetryData())}}_onMessageIdChanged(e,t){e&&this.messageId!==e&&this.setMessageId(e,t)}async accept(e,t=be()){const i=this.logger.createFnLogger("Accept",t);if(i.info(`accept, answerMediaType: ${e.answerMediaType},\n withVideo: ${e.withVideo},\n muted: ${e.muted},\n getSendMediaModalities: ${JSON.stringify(e.sendMediaModalities)},\n clientEndpointCapabilities: ${e.clientEndpointCapabilities},\n muteFlags: ${e.muteFlags}`),1!==this.state)throw new Error("Only calls in Notified state can be accepted");this.setCallOptions({callStartOptions:e,callStartTime:Date.now()}),this.setSessionIceTransportPolicy(e?.mediaConfiguration);const n=this._callOperationHandler.createPendingOperation("_ConnectCall",void 0,t);this.callStats.localStats.audio.start();const r=mh(i);this.mediaSession.createAudioElement(t);const s=e.muted||!(1&~e.muteFlags),a=!(2&~e.muteFlags);this.setMuted(s?2:this.isServerMuted?1:0,t),this.setSpeakerMuted(a,t),this.setCallState(2,t),this.connectCallPromise=this._callOperationHandler.waitForOperation("Accept");try{e.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient(),this.mediaStateConfigurationHelper.setCallAcceptOptions(e),this.mediaStateConfigurationHelper.isSending(1)&&await r.execute("StartVideoSafe",(()=>this.startVideoSafe(t))),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,t);const s=await r.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,t))),a=r.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(s))),o=await r.execute("evaluateEndpointStatesForAccept",(()=>this.evaluateEndpointStatesForAccept(2===this._muteState,e?.additionalEndpointProperties,t)));await r.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,t)));const l=r.execute("handleEndpointStatesForAccept",(()=>this.handleEndpointStatesForAccept(o,t)));i.info("Queued the handleEndpointStatesForAccept");const c=await r.execute("CreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t)));await r.execute("Accept",(()=>this.signalingSession.acceptAsync(c,a,e.clientEndpointCapabilities,t))),await r.execute("WaitForConnect",(()=>n)),this.handleRemoteParticipantStateInOneToOneCall(t),await r.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t))),await l,this.callTelemetry.updateOperationData("Accept",{phases:r.getTelemetryData()},t)}catch(e){let n=7,r={};throw this.callTelemetry.updateOperationData("Accept",this.getTelemetryFromPhaseExecution(e),t),e?.error&&(r={...e.error}),gh(qs,e)&&(n=47),this.mediaSession?.getSessionConfig().config.stopCallOnAcceptFailure&&this.stopInternal({terminatedReason:n,causeId:t,rejectReason:r}),e.terminatedReason=n,i.logFailure(e),e}}async reject(e=be(),t){const i=t?{clientReasonSubCode:t.clientSubCode,clientReasonPhrase:t.clientPhrase}:{};return 1!==this.state?Promise.reject(60):this.stopInternal({terminatedReason:10,causeId:e,rejectReason:i})}async join(e,t={},i=be()){const n=Date.now();return this.setInitialTelemetry("JoinCall",{callStartOptions:t,callStartTime:n},e.conversationUrl,i),this.setCallerMri(uh(e.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinCall"),this.signalingSession.signalingAgentConfig.enableSplitConversationEndUrl&&this.signalingSession.setFsmState(wa.SIGNALING_FSM_STATE.OUTGOING),this.joinOrStartCall({callStartOptions:qh(t),callStartTime:n},this.joinGivenConversation,i,e.conversationUrl)}async joinPreheatedCall(e,t){const i=this.logger.createFnLogger("JoinPreheatedCall",t),n=this.isServerMuted||!(1&~e.muteFlags),r=!(2&~e.muteFlags),s=mh(i);this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinPreheatedCall");try{const a={endpointProperties:{preheatProperties:0}};this.setCallState(2,t),!this.isCallModeStreaming()&&n&&(a.state={isMuted:!0}),i.info(`captchaContentJson=${!!e.captchaContentJson} publishedStates=${!!e.publishedStates} muteFlags=${e.muteFlags}}`),await this.signalingSession.updateEndpointState(a,t,e.publishedStates,e.captchaContentJson),this.computeCallState(t),this.isCallModeStreaming()||(n||(await s.execute("UnmuteInput",(()=>this.mediaSession.unmuteInputAsync(t))),this.setMuted(0,t)),r||(await s.execute("UnmuteOutput",(()=>this.mediaSession.unmuteOutputAsync(t))),this.setSpeakerMuted(!1,t)))}catch(e){const n=7;let r;return i.logFailure(`error: ${n} ${je(e)}`),is(e)?r=e:(ph("UnmuteInput",e)||ph("UnmuteOutput",e))&&(r={code:ks,subCode:3115,phrase:je(e),causeId:t}),this.callTelemetry.updateOperationData("JoinPreheatedCall",{phases:s.getTelemetryData(),error:$e(e)},t),this.stopInternal({causeId:t,terminatedReason:n,rejectReason:r}),Promise.reject(r)}}async start(e={},t=be()){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCall",{callStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCall"),this.signalingSession.signalingAgentConfig.enableSplitConversationEndUrl&&this.signalingSession.setFsmState(wa.SIGNALING_FSM_STATE.OUTGOING),this.joinOrStartCall({callStartOptions:qh(e),callStartTime:i},this.startOutgoingCall,t)}async startCallToVoicemail(e,t=be()){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCallToVoiceMail",{callVoicemailStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallToVoiceMail"),this.joinOrStartCall({callVoicemailStartOptions:e,callStartTime:i},this.startVM,t)}async joinCallWithoutCallModality(e,t={},i=be()){const n=Date.now();this.setCallerMri(e.groupCallInitiator),this.setCallType(2,i);const r={callStartOptions:qh(t),callStartTime:n};return this.setInitialTelemetry("Subscribe",r,e.conversationUrl,i),0!==this.state?(this.logger.info(`[${i}][joinCallWithoutCallModality]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,i),this.signalingSession.subscribeToCall(e.conversationUrl,this.callId,t.clientEndpointCapabilities,{meetingRegistrationId:t.meetingRegistrationId,participantPin:t.participantPin,clientEndpointDebugContent:t.clientEndpointDebugContent,additionalEndpointProperties:t.additionalEndpointProperties},i).catch((e=>is(e)?(this.logger.info(`[${i}][joinCallWithoutCallModality] ${je(e)}`),Promise.reject(e)):Promise.reject(Vh(e)))),this._callOperationHandler.waitForOperation("Subscribe",void 0,i))}startWithMeetingData(e,t){const i=Date.now();return this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartWithMeetingData",{callStartOptions:t,callStartTime:i},"",e),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartWithMeetingData"),this.joinOrStartCall({callStartOptions:qh(t),callStartTime:i,meetingPreferences:{shouldResurrect:t.shouldResurrect}},this.startOutgoingCall,e)}joinWithMeetingData(e,t,i){const n=Date.now();return this.setInitialTelemetry("JoinWithMeetingData",{callStartOptions:i,callStartTime:n},t.conversationUrl,e),this.setCallerMri(uh(t.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinWithMeetingData"),this.joinOrStartCall({callStartOptions:qh(i),callStartTime:n,meetingPreferences:{shouldResurrect:i.shouldResurrect}},this.joinGivenConversation,e,t.conversationUrl)}subscribeWithMeetingData(e,t,i){const n=Date.now();this.setCallerMri(t.groupCallInitiator),this.setCallType(2,e);const r={callStartOptions:qh(i),callStartTime:n};return this.setInitialTelemetry("SubscribeWithMeetingData",r,t.conversationUrl,e),0!==this.state?(this.logger.info(`[${e}][subscribeWithMeetingData]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,e),this.signalingSession.subscribeToCall(t.conversationUrl,this.callId,i.clientEndpointCapabilities,{meetingPreferences:{shouldResurrect:i.shouldResurrect},meetingData:this.meetingData,meetingRegistrationId:i.meetingRegistrationId,participantPin:i.participantPin,additionalEndpointProperties:i.additionalEndpointProperties},e).catch((t=>is(t)?(this.logger.info(`[${e}][subscribeWithMeetingData] ${je(t)}`),Promise.reject(t)):Promise.reject(Vh(t)))),this._callOperationHandler.waitForOperation("SubscribeWithMeetingData",void 0,e))}async startCallWithNudge(e,t={},i=be()){this.setCallerMri(dh+this.currentUserSkypeIdentity.id),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallWithNudge");const n=Date.now();if(this.logger.info(`[${i}][startCallWithNudge]startCallWithNudge for participants: ${function(e){try{return e.map(De)}catch(e){return[]}}(e)}`),this.participants.length)return Promise.reject(48);if(t.isCast&&t.isHuddleGroupCall)return this.logger.logFailure(`isCast: ${t.isCast} isHuddleGroupCall: ${t.isHuddleGroupCall}`),Promise.reject(new Error("isCast or isHuddleGroupCall can only be set exclusively."));const r={};return r.callStartOptions=qh(t),r.invitationType=wa.INVITATION_TYPE.NUDGE,r.participantsToNudge=e,r.callStartTime=n,this.setInitialTelemetry("StartCallWithNudge",r,"",i),this.joinOrStartCall(r,this.startOutgoingCall,i)}async startAndUnpark(e,t,i={},n=be()){this.setCallerMri(dh+this.currentUserSkypeIdentity.id);const r=this.logger.createFnLogger("StartCallAndUnpark",n),s=Date.now();this.setInitialTelemetry("StartCallAndUnpark",{callStartTime:s},"",n),r.info(`startAndUnpark for context: ${e}, pickupCode :${t}`),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallAndUnpark");const a={};switch(a.callStartOptions=qh(i),a.pickupCode=t,a.parkContext=mr,e){case 0:a.parkContext="*11";break;case 1:a.parkContext="*12";break;case 5:a.parkContext="*14";break;case 2:a.parkContext=mr;break;default:throw new Error(`[startAndUnpark] unsupported ParkContext name: ${e}`)}return this.addParticipant(`4:${a.parkContext}`).catch((e=>r.logFailure("Failed to add participant to unparked call"))),this.joinOrStartCall(a,this.startOutgoingCall,n)}async admitParticipant(e,t=be()){const i=hh(e),n=this.getParticipant(i),r=this._getParticipantLegId(n),s=r?{participantLegId:r}:{};if(n&&7!==n.state){const i={code:0,subCode:3552,phrase:"Participant is not in lobby state"};return this.callTelemetry.maybeRecordOperationSuccess("AdmitParticipant",i,e,t,s),Promise.reject(i)}return this.admitParticipantToCall(i,t,r)}admit(e,t){return this.signalingSession.admitAsync(t)}async callMeBack(e,t,i=be()){const n=hh(`${dh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri);return this.addCallMeBackParticipant(e,t||n,i)}async addParticipant(e,t={},i=be()){return(await this.addParticipantsImpl([e],t,i,"addParticipant"))[0]}async addParticipants(e,t={},i=be()){return this.addParticipantsImpl(e,t,i,"addParticipants")}async addParticipantsImpl(e,t={},i=be(),n){if(this.logger.info(`[${i}][${n}] start`),this.isEmergency&&0===this.state&&(0!==this.participants.length||1!==e.length))return Promise.reject(new Error("Only 1 participant (the emergency operator) may be added to unstarted emergency calls"));if(t.participantInvitationData)try{JSON.stringify(t.participantInvitationData)}catch(e){throw this.logger.info(`[${i}][${n}] ${e}`),e}const r=[],s=[];if(e.forEach((e=>{const t=this.getOrCreateParticipant(e,i,!0);0===t.state||4===t.state?(s.push(t),r.push(this._participantOperationHandler.createPendingOperation("AddParticipant",t.id,i))):3===t.state?r.push(Promise.resolve(t)):this._participantOperationHandler.hasPendingOperationWithOperationId("AddParticipant",t.id)&&r.push(this._participantOperationHandler.waitForOperation("AddParticipant",t.id))})),0===s.length)return Promise.resolve(r);const a=!!t.disableUnmute,o=this.addParticipantsToCall(s,i,t.participantInvitationData,t.groupId,t.threadId,t.messageId,a,t.alternateId,t.customHeaderContext,t.callingLineIdentity);return(0,Ws.zip)(o,s).forEach((async([e,t])=>{try{await e;const n=this._getParticipantLegId(this.getParticipant(t.id)),r=n?{participantLegId:n}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},t.id,i,r),this._participantOperationHandler.maybeResolveOperation("AddParticipant",t,t.id,i)}catch(e){this._participantOperationHandler.maybeRejectOperation("AddParticipant",e,t.id,i)}})),this.raiseChanged(this._participantChangedEventSkipConfig),Promise.resolve(r)}async nudgeParticipants(e,t,i={},n=be()){return 2!==this.state&&3!==this.state?Promise.reject(48):this.signalingSession.nudgeParticipantsAsync({participantsIds:t,causeId:n,invitationData:i.participantInvitationData,newGroupId:i.groupId,newThreadId:i.threadId,newMessageId:i.messageId})}mapRemoveEndpointScope(e){switch(e){case 0:return"specified";case 1:return"all";default:return"none"}}mapEndpointScope(e){return 1===e?"all":"none"}async removeParticipant(e,t=be(),i,n){const r=this.logger.createFnLogger("removeParticipant",t);r.info("start");const s=this.mapRemoveEndpointScope(n);return this.signalingSession.removeParticipantAsync({id:e,endpointId:i},t,s).catch((i=>{r.logFailure(`Participant was not removed from call, error=${i}`);const n=this._handleParticipantOperationFailure("RemoveParticipant",i,t,e).reason;return Promise.reject(n||38)}))}async cancelNudge(e,t){throw new Error("Method not implemented.")}async searchParticipants(e,t){return this.signalingSession.searchParticipantsAsync(e.searchQueryOptions,t)}async getAllParticipants(e,t){return this.signalingSession.getAllParticipantsAsync(e.scope,t)}set dominantSpeakerInfo(e){this.internalDominantSpeakerInfo=e}get dominantSpeakerInfo(){return this.internalDominantSpeakerInfo?this.internalDominantSpeakerInfo:this.mediaSession?.getSessionConfig().config.emptyInitialDSH?{speakerList:[],timestamp:null,noCurrentDominantSpeaker:!1}:{speakerList:this.participants.filter((e=>3===e.state)).map((e=>e.id)),timestamp:null,noCurrentDominantSpeaker:!1}}set slowedDownActiveTalkerInfo(e){(0,Ws.isEqual)(this.internalSlowedDownActiveTalkerInfo?.speakerList,e.speakerList)||(this.internalSlowedDownActiveTalkerInfo=e,this.raiseChanged())}get slowedDownActiveTalkerInfo(){return this.internalSlowedDownActiveTalkerInfo}startVideoSafe(e){return this.startVideo(e).catch((t=>{this.logger.info(JSON.stringify(t),"startVideoSafe",e)}))}async joinOrStartCall(e,t,i,n){const r=this.logger.createFnLogger("joinOrStartCall",i);if(0!==this.state&&8!==this.state&&!e.isPromotingToRealtime){const e="Trying to start a call that has already been acted on";return r.logFailure(e),Promise.reject(60)}if(this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)===this.signalingSession)return Promise.reject(57);this.callStats.localStats.startCall();const s=8===this.state||1!==this.participants.length;r.info(`isMultiparty=${s}, reason: participants.length=${this.participants.length}`),this.setCallType(s?2:1,i),this.setCallUsesMixer(s,i),this._setMaxVbssChannels(e?.callStartOptions?.maxVbssChannels,i),this.setCallOptions(e);const a=e.callStartOptions||{};if(1&~a.preheatFlags){const e=!!a&&(a.muted||!(1&~a.muteFlags)),t=a?.muteFlags?!(2&~a.muteFlags):this.isSpeakerMuted;this.setMuted(e?2:this.isServerMuted?1:0,i),this.setSpeakerMuted(t,i),this.setCallState(2,i)}else this.setMuted(2,i),this.setSpeakerMuted(!0,i),this.setCallState(11,i);const o=((e,t,i,n,r)=>{if(e){if(e.meetingUrl)return"MeetingUrl";if(e.meetingCode)return"MeetingCode"}return t||i?"ThreadContext":n?"GroupId":r?"Awareness":""})(this.meetingData,this.threadId,this.messageId,this.groupId,!!n);this.callTelemetry.setJoinedFrom(o),this.signalingSession.setJoinedFrom(o),this.setHuddleGroupCall(!!e.callStartOptions?.isHuddleGroupCall);const l=this._callOperationHandler.createPendingOperation("_ConnectCall","",i);return l.catch(wr),await this.joinOrStartWithMedia(e,t,e.callStartTime,l,i,n),e.callStartOptions?.meetingRegistrationId&&this.callTelemetry.setHasMeetingRegistrationId(!0),e.callStartOptions?.participantPin&&this.callTelemetry.setHasParticipantPin(!0),l}setSessionIceTransportPolicy(e){const t=e?.connectionType;let i=Gi.ICE_TRANSPORT_POLICY.all;switch(t){case"AllSupported":i=Gi.ICE_TRANSPORT_POLICY.all;break;case"NoDirectConnection":i=Gi.ICE_TRANSPORT_POLICY.relay}this.mediaSession?.getSessionConfig().setIceTransportPolicy?.(i)}async joinOrStartWithMedia(e,t,i,n,r,s){const a=this.logger.createFnLogger("joinOrStartWithMedia",r);this.callStats.localStats.audio.start();const o=e.callStartOptions,l=o&&1&o.preheatFlags;if(this._startCallPhase=mh(a),e.callStartOptions?.sendMediaModalities&&(this.mediaStateConfigurationHelper=new Wh(e.callStartOptions.sendMediaModalities)),this._preferredMpLocation){e.callStartOptions=e.callStartOptions||{};const t=e.callStartOptions.clientEndpointDebugContent?JSON.parse(e.callStartOptions.clientEndpointDebugContent):{};e.callStartOptions.clientEndpointDebugContent=JSON.stringify({preferredMpLocation:this._preferredMpLocation,...t})}try{o&&!l&&this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)&&this.mediaStateConfigurationHelper.isSending(2)&&(this.setCallUsesMixer(!0,r),await this.getScreenHandle().acquire()),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,r),this.callUsesMixer||this.mediaStateConfigurationHelper.disableModality(2),a.info(`skipSharingModality=${!this.callUsesMixer}`),this._startCallPhase.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(r,o?.mediaConfiguration))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.getSessionConfig().config.alwaysNegotiateDataChannel&&this.mediaStateConfigurationHelper.enableModality(3),this.setSessionIceTransportPolicy(e?.callStartOptions?.mediaConfiguration),this.mediaSession.createAudioElement(r),this.callUsesMixer||s||this.isOneToOnePSTNCall()||e.callVoicemailStartOptions||this.setIsSomeoneStreamingVideo(!0);const c=this._callOperationHandler.createPendingOperation("_WaitForAnswer","",r,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});c.catch(wr);let d=!1;e.isPromotingToRealtime?(this.isSpeakerMuted=!0,d=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r)))):o&&(l?(d=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r))),this.setMuted(2,r),this.setCallUsesMixer(!0,r)):this.mediaStateConfigurationHelper.isSending(1)&&await this._startCallPhase.execute("StartVideoSafe",(()=>this.startVideoSafe(r)))),o?.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient();const u=await this._startCallPhase.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,r)));if(!this.mediaSession?.createOfferAsync)throw{error:"NoMediaSession",phase:"CreateOffer"};const h=await this._startCallPhase.execute("CreateOffer",(()=>this.mediaSession.createOfferAsync(r))),g=this._startCallPhase.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(this.calculateModalityDirections({},r))));if(this.mediaStateConfigurationHelper.isSending(2)&&this.updateScreenSharingState(u,r),d||(await this._startCallPhase.execute("MuteUnmute",(()=>this.muteUnmute(2===this._muteState,r))),await this._startCallPhase.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,r)))),this._startCallPhase.executeSync("CallStart",(()=>t(r,e,h,g,i,s))),await this._startCallPhase.execute("WaitForConnect",(()=>n)),!this.isCallModeStreaming()||e.isPromotingToRealtime){const e=await this._startCallPhase.execute("WaitForAnswer",(()=>c));if(!this.mediaSession?.processAnswerAsync)throw{error:"NoMediaSession",phase:"ProcessAnswer"};await this._startCallPhase.execute("ProcessAnswer",(()=>this.mediaSession.processAnswerAsync(e,r,!1))),await this._startCallPhase.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(r)))}this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},r),this._startCallPhase=void 0,2!==o?.screenshareDirection&&4!==o?.screenshareDirection||(this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(""),this.enableControlInjector())}catch(e){this.catchJoinOrStartCallError(e,r,a)}}catchJoinOrStartCallError(e,t,i){let n,r=0;throw i.logFailure(je(e)),e?.error&&(n={...e.error}),ph("MuteInput",e)?(r=7,n={code:ks,subCode:3113,phrase:je(e),causeId:t}):ph("MuteOutput",e)?(r=7,n={code:ks,subCode:3114,phrase:je(e),causeId:t}):e?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer||gh(qs,e)?r=47:e?.type===this.mediaAgent.constants.MEDIA_ERROR.permissionDeniedError?(r=58,n={code:ys,subCode:Ls,phrase:je(e),causeId:t}):ph("WaitForAnswer",e)||ph("WaitForConnect",e)?r=e.error:gh(Gs,e)&&(r=7),this.callTelemetry.updateOperationData("_ConnectCall",this.getTelemetryFromPhaseExecution(e),t),this._startCallPhase=void 0,this.callSetupFailed=!0,Promise.all([this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",r,"",t),this._callOperationHandler.maybeRejectOperation("_ConnectCall",r,"",t)]).then((()=>{this.isPromotingToRealtime()||this.stopInternal({causeId:t,terminatedReason:r,rejectReason:n})})).catch(wr),r}addCallMeBackParticipant(e,t,i){const n=this._participantOperationHandler.waitForOperation("CallMeBack",e),r=this.logger.createFnLogger("CallMeBack",i),s={id:e,assertedId:t};return this.signalingSession.callMeBackAsync(s).then((()=>{r.logSuccess(`successfully executed call me back, participantId = ${De(e)}`),this._participantOperationHandler.resolveOperation("CallMeBack",0,e)})).catch((n=>{r.logFailure(`Call me back failed, participantId = ${De(e)}, error = ${n}`),this._handleParticipantOperationFailure("CallMeBack",n,i,t,!1);const s=this._processError(n);let a={};s&&(a={...s}),a.failureReason=s.reason?s.reason:11,this._participantOperationHandler.rejectOperation("CallMeBack",a,e)})),n}addParticipantsToCall(e,t,i,n,r,s,a,o,l,c){const d=this.logger.createFnLogger("addParticipantsToCall",t);e.forEach((e=>{e.setState(1,void 0,t)}));const u=e.map((e=>({id:e.mri})));d.info(`participantIds=${e.map((e=>De(e.id)))}, disableUnmute=${a}`);const h={additionalData:i,groupId:n,threadId:r,messageId:s,disableUnmute:a,alternateId:o,customHeaderContext:l,callingLineIdentity:c};try{const e=this.signalingSession.addParticipantsAsync(u,h,t);return(0,Ws.zip)(e,u).map((async([e,i])=>{try{const n=await e;this.signalingNotifications.onParticipantJoined(n,t);const r=this._getParticipantLegId(this.getParticipant(i.id)),s=r?{participantLegId:r}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},n.id,t,s)}catch(e){const n=this._handleParticipantOperationFailure("AddParticipant",e,t,i.id).reason;throw this._removeParticipant(i,t,n),n}}))}catch(e){return d.logFailure(`Participants was not added to call, error=${e}`),(0,Ws.range)(u.length).map((()=>Promise.reject(1)))}}async mergeCallByAddParticipantWithReplaces(e,t,i,n,r,s,a,o){const l=this.logger.createFnLogger("mergeCallByAddParticipantWithReplaces",s),c=this.convertClientScenario(o),d={additionalData:e.additionalData,groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,callIdToReplace:i.callId,replacementType:n,clientScenario:c},u=await this.signalingSession.addParticipantsAsync(t,d,s);for(let e=0;e<u.length;e++){const i=3===n?t[e].participantId:t[e].id;try{await u[e],l.logSuccess(` [participantInfos id =${De(t[e].id)}]`);const n={debugContent:{replacementParticipantLegId:t[e].replacementParticipantId||void 0,clientScenario:c},participantLegId:t[e].participantId},a={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(r,a,i,s,n),this._callOperationHandler.maybeResolveOperation(r,a,i,s)}catch(n){l.logFailure(`Participant was not added to call, error=${$e(n)}`);const a=this._handleParticipantOperationFailure(r,n,s,i,!0,c).reason;this._removeParticipant(t[e],s,a);const o=n?n.endCode:a||0;this._callOperationHandler.maybeRejectOperation(r,o,i,s)}}return Promise.resolve(a)}admitParticipantToCall(e,t,i){const n=this.logger.createFnLogger("admitParticipantToCall",t),r={id:e};return n.info("start"),this.signalingSession.admitParticipantAsync(r,t).then((r=>{n.info(`successfully admitted participant to call, participantId = ${De(e)}`);const s=i?{participantLegId:i}:{};this.callTelemetry.recordOperationSuccess("AdmitParticipant",{code:0,subCode:0,phrase:""},e,t,s)})).catch((i=>{n.logFailure(`Participant was not admitted to call, error=${i}`);const r=this._handleParticipantOperationFailure("AdmitParticipant",i,t,e);return Promise.reject(r)}))}_processError(t){let i;const n={reason:i};if(t?.endCode){const r=$h(t.endCode.code,t.endCode.subCode);i=e.getParticipantReasonFromTerminatedReason(r),n.reason=i,n.code=t.endCode.code,n.subCode=t.endCode.subCode,n.resultCategories=t.endCode.resultCategories,n.phrase=t.endCode.phrase}else n.phrase=`${t}`;return this.logger.info(`_processError error=${t} telemetryData=${JSON.stringify(n)}`),n}_handleParticipantOperationFailure(e,t,i,n,r=!0,s){this.callTelemetry.updateOperationData(e,{error:$e(t)},i,n);const a=this._processError(t),o=this.getParticipant(n);a.code&&o&&(o.callEndDiagnosticsInfo={callControllerCode:a.code,callControllerSubCode:a.subCode,phrase:a.phrase,resultCategories:a.resultCategories});try{if(r){const t={debugContent:{clientScenario:s},participantLegId:this._getParticipantLegId(o)||void 0};this.callTelemetry.recordOperationFailure(e,a,n,i,t)}}catch(e){this.logger.info(`_handleParticipantOperationFailure error during recordOperationFailure ${e}`)}return a}_getParticipantLegId(e){return(0,Ws.has)(e,"endpoints.endpointDetails")&&e.endpoints.endpointDetails.length&&e.endpoints.endpointDetails[0].participantId?e.endpoints.endpointDetails[0].participantId:null}isOneToOnePSTNCall(e=!1){const t=this.signalingSession.isIncomingCall?this.callerMri:this.participants.length>0?this.participants[0].id:"";return this.isOneToOneCall(e)&&(0,Ws.startsWith)(t,"4:")&&(!this.incomingCallType||!this.callUsesMixer)}isParkedCall(){return this.isOneToOnePSTNCall()&&!!this.callOptions?.parkContext}async updateMediaModalities(e={},t=be(),i){let n;const r=this.logger.createFnLogger("updateMediaModalities",t);return r.info(`callUsesMixer=${this.callUsesMixer},isSomeoneSharing=${this.isSomeoneSharing},isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),r.info(`options=${Ge(e)},requestHoldState=${this.requestedHoldState},requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}`),n=e.modalityOverride?e.modalityOverride:this.requestedHoldState&&!this.isMuteOnHold?this.getMediaModalitiesForHold(t):this.calculateModalityDirections(e?.offered,t),r.info(`modalities=${Ge(n)}`),await this.mediaSession.configureModalitiesAsync(n,t,i),n}calculateModalityDirections(e={},t){const i=this.logger.createFnLogger("calculateModalityDirections",t);i.info(`callUsesMixer=${this.callUsesMixer}, isEscalationInProgress=${this.isEscalationInProgress}`);const n={audio:this.calculateAudioDirection(e.audio,i),video:this.calculateVideoDirection(e.video,i),sharing:this.calculateSharingDirection(e.sharing,i),data:this.calculateDataDirection(e.data,i)};return i.info(`done, modalities=${Ge(n)}`),this.deleteExtraneousModalities(n,t),n}calculateAudioDirection(e,t){return t.info(`calculateAudioDirection, offer=${e}, requestedAudioState=${this.mediaStateConfigurationHelper.isSending(0)}`),this.receiveOnlyAudioOnCallStart?(t.info("calculateAudioDirection, direction=recvonly, receiveOnlyAudioOnCallStart=true"),"recvonly"):this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)||"inactive"===e?"inactive":this.mediaSession.getAllowedModalities().audio.some((e=>e===ug||e===gg))?"sendrecv":"sendonly"===e?"inactive":"recvonly"}calculateVideoDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(1);if(t.info(`calculateVideoDirection, offer=${e}, requestedVideoState=${i}, isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),this.mediaStateConfigurationHelper.isInactiveOrDisabled(0))return"inactive";let n=i,r=this.isSomeoneStreamingVideo||this.callUsesMixer||this.isEscalationInProgress;return e&&(n=n&&("sendrecv"===e||"sendonly"===e),r=r&&("sendrecv"===e||"recvonly"===e)),n?"sendrecv":r?"recvonly":"inactive"}calculateSharingDirection(e,t){return t.info(`calculateSharingDirection, offer=${e}, requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}, isSomeoneSharing=${this.isSomeoneSharing}`),"inactive"===e?"inactive":this.mediaStateConfigurationHelper.isSending(2)?"sendonly":this.isSomeoneSharing||this.callUsesMixer||this.isEscalationInProgress?"recvonly":void 0}calculateDataDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(3);if(t.info(`calculateDataDirection, offer=${e}, dataEnabled=${i}`),this.allowDataChannel())return i?"inactive"===e?"inactive":"sendrecv":void 0;t.info("calculateDataDirection, disabling data since ECS flag prohibits it")}getMediaModalitiesForHold(e){this.logger.info(`[${e}][getMediaModalitiesForHold]`);const t="inactive",i={audio:t,video:t,data:this.allowDataChannel()?t:void 0,sharing:t};return this.deleteExtraneousModalities(i,e),i}deleteExtraneousModalities(e,t){!Wp(e.video)&&this.mediaStateConfigurationHelper.isDisabled(1)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping videoModality`),delete e.video),!Wp(e.sharing)&&this.mediaStateConfigurationHelper.isDisabled(2)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping sharingModality`),delete e.sharing)}getSignalingMediaTypes(e){const t=[];return e.audio&&e.audio!==this.mediaAgent.constants.MEDIA_STATE.inactive&&t.push("Audio"),(e=>e===this.mediaAgent.constants.MEDIA_STATE.send||e===this.mediaAgent.constants.MEDIA_STATE.sendReceive)(e.video)&&t.push("Video"),e.sharing===this.mediaAgent.constants.MEDIA_STATE.send?t.push("ScreenSharer"):e.sharing===this.mediaAgent.constants.MEDIA_STATE.receive&&t.push("ScreenViewer"),t}enableControlInjector(){if(this.allowScreenSharingControl())if(this.getlocalScreenShareStream()){const e=this.mediaSession?.getLocalMediaTrackId("ScreenShare")??"";this.screenSharingControl.enableControlInjector(e)}else this.logger.warn("enableControlInjector: no local screenshare stream found")}createCallDeviceManager(){return new _f(this.mediaAgent.getConfigProvider().config.allowVirtualDeviceInCall,this.mediaAgent.getDeviceManager(),this.logger.createChild("CallDeviceManager"),this.callStats,(e=>this.isMediaSending(e)))}initializeSignalingSession(t){if(this.signalingSession)return void this.logger.info("Session already exists!");const i=wa.CALL_STATUS;if(this.localSignalingParticipant={id:hh(`${dh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri),displayName:this.currentUserSkypeIdentity.displayName,endpointDetails:[],languageId:null,participantId:t,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 e=this.accountConfiguration.serviceUrls.calling_conversationServiceUrl,t=this.accountConfiguration.serviceUrls.calling_uploadLogRequestUrl;this.signalingAgent.updateUrls(e,t,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:(e,t,i)=>{this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} reason=${Ge(t)} callMode=${this.callMode}`);const n=e?t:{code:0,subCode:0};if(this.callTelemetry.recordEvent("PromotionCompleted",{reason:n},i),e){const e=Vh(t);this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",e,"",i),this._callOperationHandler.maybeRejectOperation("_CallStartOrJoinInitiated",e,"",i),this._callOperationHandler.maybeRejectOperation("_ConnectCall",e,"",i),this.promotionCompletedDeferred?.reject(e)}else this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,i),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,i);this.participants.forEach((e=>{e.applyCachedMediaStreams(i)}))},onCallStatusChanged:(e,t,n=be())=>{const r=this.logger.createFnLogger("onCallStatusChanged",n);let s=`[status=${e}]`;if(t&&(s+=`[reason=${Ge(t)}]`,void 0!==t.code&&(this.callEndDiagnosticsInfo={callControllerCode:t.code,callControllerSubCode:t.subCode,phrase:t.phrase,resultCategories:t.resultCategories},(t.overflowJoinInformation||t.registrationInformation)&&(this.callEndDiagnosticsInfo.additionalDiagnostics={overflowInformation:t.overflowJoinInformation,registrationInformation:t.registrationInformation}))),r.info(s),this.callTelemetry.recordEvent("_SignalingStateChanged",{status:e,reason:t},n),e===i.CONNECTING)this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n);else if(e===i.RINGING)2===this.audioStreamState?(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n)))):this.participants.forEach((e=>e.setState(2,void 0,n))),this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n);else if(e===i.CONNECTED_FOR_ROSTER_ONLY)this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("SubscribeWithMeetingData",void 0,void 0,n);else if(e===i.CONNECTED){this._callIsSetupComplete=!0;const e=this.getLocalSignalingEndpointDetails();(e?.isLobby||e?.streamLobby)&&(this._callInLobby=!0,this.updateCapabilities(n,!0));const t=this.signalingSession.participantManager.localParticipant.isStaging;if(11===this.state)this.setCallState(12,n);else if(this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))r.info("wait for joinPreheatedCall to resolved");else if(this._callInLobby)r.info("[inLobby] Override Connected state from signaling agent"),this.setCallState(10,n);else if(t)this.setCallState(13,n);else{if(3===this.state&&!this._callOperationHandler.hasPendingOperation("_CallStartOrJoinInitiated")&&!this._callOperationHandler.hasPendingOperation("_ConnectCall"))return void r.info("Return: Don't re-send setup telemetry if call was already connected and operations are completed");this.setCallState(3,n),this.handleRemoteParticipantStateInOneToOneCall(n)}this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,n),this.reportTsCallingTelemetry(!0)}else if(e===i.LOCAL_TERMINATED||e===i.REMOTE_TERMINATED){let s=this.callSetupFailed?7:Vh(t);if(8===this.state&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData"]))return this.signalingSession.resetState(),this._callOperationHandler.maybeRejectOperation("Subscribe",s,void 0,n),this._callOperationHandler.maybeRejectOperation("SubscribeWithMeetingData",s,void 0,n),void r.info("Subscribe failed, there is pending start/join operation, ignore call end message");if(1!==s&&t?.code===ys&&t?.subCode===Ls&&(s=58,r.info(`[terminated][reason=${Ge(t)}]`)),(2===this.state||6===this.state||8===this.state)&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData","Subscribe","SubscribeWithMeetingData"])){const e={code:this.callEndDiagnosticsInfo.callControllerCode,subCode:this.callEndDiagnosticsInfo.callControllerSubCode,phrase:this.callEndDiagnosticsInfo.phrase,reason:s};this._callOperationHandler.maybeRejectOperations(["Accept","JoinCall","JoinWithMeetingData","JoinPreheatedCall","StartCall","StartCallAndUnpark","StartCallToVoiceMail","StartCallWithNudge","StartWithMeetingData","Subscribe","SubscribeWithMeetingData"],s,void 0,n,e)}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")&&t.pickupCode&&0===t.code&&this._callOperationHandler.resolveOperation("CallParkV2",""+t.pickupCode,void 0,n),1!==s&&this.mediaRelayWhiteListingIssue&&(s=53,r.info(`[terminated][reason=${Ge(t)}]`)),this._callOperationHandler.maybeRejectOperation("CallParkV2",s,"",n),this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",s,"",n),this._callOperationHandler.maybeRejectOperation("_ConnectCall",s,"",n);const a=this.mediaSession?.getSessionConfig().config.setDisconnectAfterCleanUp;if(a?this.setTerminatedReason(s):this.setCallState(7,n,s),this.participants.forEach((e=>e.setState(4,void 0,n))),!this.disconnectingPromise){const s={...t,remoteTerminated:e===i.REMOTE_TERMINATED};this.disconnectingPromise=this.cleanUp(n,s).catch((e=>{r.logFailure(`Error when cleaning up the call, callId = ${this.callId}, error = ${e}`)}))}a&&this.disconnectingPromise.finally((()=>{7!==this.state&&this.setCallState(7,n,s)}))}},onOffer:(e,t=be())=>{const i=this.logger.createFnLogger("onOffer",t);i.info(`${Ge((0,Ws.omit)(ke(e),"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnOffer",this.prepareTelemetryForOfferAnswer(e),t),e.transferor?.details?.id&&this.setTransferorMri(e.transferor.details.id),e.transferor?.transferorType&&(this.transferorType=e.transferor.transferorType),e.transferor?.details?.displayName&&(this.transferorDisplayName=e.transferor.details.displayName),this.clientTransferContext=e.clientTransferContext,this.customHeaderContext=e.customHeaderContext,this.invitationData=e.invitationData,this.spamRiskLevel=e.riskLevel,this.spamStirAttestation=e.stirAttestation,e.mediaContent.isTwoPartyToMultiPartyEscalation&&this.setIsEscalationInProgress(!0,t),e.renegotiation?this.requestedHoldState&&this._pendingParkPromise?this.renegotiateIncoming(e.mediaContent,t):this._delayedElevationPending||this._delayedElevationQueued?(this.signalingSession.rejectRenegotiationAsync({},t),this.triggerDelayedReconnectIfNeeded(t,"onOffer")):this._callOperationHandler.executeChained((()=>this.renegotiateIncoming(e.mediaContent,t)),"_RenegotiateIncoming",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}):(i.info("resolving attach / offer promise"),this.attachToCallAndGetOffer.resolve(e.mediaContent))},onNewOffer:(e,t=be())=>{const i=this.logger.createFnLogger("onNewOffer",t);this.newOfferRequestDeferred?(i.info("onNewOffer"),this.newOfferRequestDeferred.resolve(e.mediaContent)):i.info("callback received but new offer was not requested")},onAnswer:(e,t=be())=>{const i=this.logger.createFnLogger("onAnswer",t);if(i.info(`${Ge((0,Ws.omit)(e,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnAnswer",this.prepareTelemetryForOfferAnswer(e),t),e.renegotiation)i.info("resolving previous renegotiation promise"),this.renegotiationAnswerDeferred.resolve(e.mediaContent);else if(i.info("resolving final answer promise"),e.provisional){const i=this.isOneToOnePSTNCall()&&(0,Ws.startsWith)(e.remoteParticipantId,"4:");this.mediaSession.processAnswerAsync(e.mediaContent,t,!0,i)}else this._callOperationHandler.maybeResolveOperation("_WaitForAnswer",e.mediaContent,void 0,t),this.handleRemoteParticipantStateInOneToOneCall(t);e.provisional||!e.mediaContent.fromMixer||this.callUsesMixer||this._callOperationHandler.executeChained((async()=>{this.setCallUsesMixer(!0,t),this.mediaStateConfigurationHelper.isDisabled(2)&&this.mediaStateConfigurationHelper.removeModality(2),await this.updateMediaModalities(void 0,t);const e=!(this.isSomeoneSharing||this.isScreenSharingOn||this.isVideoOn);return(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.callElevationDelayReconnectPSTN:this.mediaSession.getSessionConfig().config.callElevationDelayReconnect)&&e?(i.info("Delayed elevation: pending"),this._delayedElevationPending=!0,Promise.resolve()):this.mediaSession.reconnectAsync(t,!0)}),"_CallEscalatedToConference",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})},onMediaAcknowledgementSuccess:(e,t=be())=>{this.logger.info(`isRenegotiation: ${e}`,"onMediaAcknowledgementSuccess",t),this._callOperationHandler.resolveOperation("_MediaAcknowledgment",void 0,void 0,t)},onMediaAcknowledgementFailure:(e,t,i=be())=>{this.logger.createFnLogger("onMediaAcknowledgementFailure",i).logFailure(Ge(t)),this._callOperationHandler.rejectOperation("_MediaAcknowledgment",t,i)},onMediaRenegotiationRejection:(e,t=be())=>{this.logger.createFnLogger("onMediaRenegotiationRejection",t).logFailure(Ge(e)),this.renegotiationAnswerDeferred.reject(e)},onRosterHandlingComplete:()=>{this.logger.info(`[onRosterHandlingComplete] ${this._publishedStatesModified}`),0!==this._publishedStatesModified&&(this.processPublishedStates(),this._publishedStatesModified=0)},onMeetingGroupDetailsUpdated:(e,t=be())=>{this.meetingGroupDetails!==e&&(this.callTelemetry.recordEvent("_UpdateMeetingGroupDetails",e,t),this.logger.info(`[${t}][onMeetingGroupDetailsUpdated] update meetingGroupDetails from ${JSON.stringify(this.meetingGroupDetails)} to ${JSON.stringify(e)}`),this.meetingGroupDetails=e,this.raiseChanged())},onSelfParticipantUpdated:(e,t=be())=>{this.logger.info(`[${t}][onSelfParticipantUpdated]`),this.updateLocalParticipant(e,t),this.raiseChanged()},onParticipantMriUpdated:(e,t,i=be())=>{this.logger.info(`[${i}][onParticipantMriUpdated]`);const n=this.getParticipant(e);n&&(n.id=t,this.raiseChangedDeferred())},onParticipantUpdated:(t,i=be())=>{this.logger.info(`[${i}][onParticipantUpdated]: ${rg(t)}`);const n=this.getOrCreateParticipant(t.id,i,!0);n.displayName=t.displayName;const r=e.getStreamsFromEndpoints(t.endpointDetails,this.isMultiVBSSEnabled()),s=(0,Ws.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||r.length>0||s?(this.updateParticipantStreams(n,t,r,i),this.updateCallParticipantFromSignalingParticipant(n,t,i)):n.setState(3,void 0,i),n.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),this.calculateIsSomeoneStreaming(i),this.raiseChangedDeferred()},onParticipantRemoved:(e,t=be(),i=!1)=>{if(this.logger.info(`[${t}][onParticipantRemoved]`),i){const i=this.getParticipant(e.id);this.callTelemetry.recordOperationSuccess("_ParticipantJoined",null,i?.id,t,{participantJoinedButReplaced:"Participant joined with original MRI and replaced with participant of RNL MRI"})}else this.callTelemetry.recordOperationSuccess("RemoveParticipant",null,e.id,t),this._participantOperationHandler.maybeRejectOperation("AddParticipant",1,e.id,t);this._removeParticipant(e,t),this.removePublishedStatesByParticipant(e.id),this.calculateIsSomeoneStreaming(t)},onParticipantJoined:(t,i=be())=>{this.logger.info(`[${i}][onParticipantJoined]`);const n=!this.getParticipant(t.id),r=this.getOrCreateParticipant(t.id,i,!1);r.displayName=t.displayName,0===r.state&&r.setState(1,void 0,i);const s=e.filterVirtualEndpoints(t.endpointDetails),a=e.getStreamsFromEndpoints(s,this.isMultiVBSSEnabled()),o=(0,Ws.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||a.length>0||o?(this.updateParticipantStreams(r,t,a,i),this.updateCallParticipantFromSignalingParticipant(r,t,i),this.calculateIsSomeoneStreaming(i)):(this.handleRemoteParticipantJoinedInOneToOneCall(t,i),this.handleRemoteParticipantStateInObservingCall(r,t,i),t.acceptedBy&&t.acceptedBy!==t.id&&(r.acceptedBy=t.acceptedBy)),this.callTelemetry.recordOperationSuccess("_ParticipantJoined",Er(t.endpointDetails),r.id,i),r.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),n&&this.event("participantAdded").raise(r),this.raiseChangedDeferred()},onCallModeChanged:(e,t)=>{this.callTelemetry.recordEvent("_CallModeChanged",{newCallMode:e,oldCallMode:this._callMode},t),this.logger.info(`onCallModeChanged[${t}]: new=${e} old=${this._callMode} `),e&&this._callMode!==e&&(this._callMode=e,this.isCallModeStreaming()&&this.cleanUpDueToStreaming(t),1===this._callMode&&(this.participants.forEach((e=>{e.applyCachedMediaStreams(t)})),this.promotionCompletedDeferred?.resolve()),this.monitorCallStart(),this.updateCapabilities(t),this.raiseChanged())},getRemoteParticipantCollection:()=>this.participants.map((e=>e.toCafeParticipant())),onReTargetCompletedSuccess:e=>{const t=this.logger.createFnLogger("onReTargetCompletedSuccess",e);t.info(`started, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetSuccess",void 0,e),this.callStats.localStats.call.event(3);const i=this.isEscalationInProgress;this.screenSharingControl&&this.screenSharingControl.shutdownControlForViewer(),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.completeEscalationAsync(e).then((()=>(t.logSuccess("completeEscalationAsync"),this.callTelemetry.recordEvent("_WebOnEscalationSuccess",void 0,e),this.handleCallEscalation(i,e),this.updateMediaStatus(e)))).catch((i=>{t.logFailure(`completeEscalationAsync, error=${je(i)}`),this.setIsEscalationInProgress(!1,e),this.callTelemetry.recordEvent("_WebOnEscalationFailure",$e(i),e),this.stopInternal({causeId:e,terminatedReason:47})}))},onReTargetCompletedFailure:(e,t)=>{this.logger.createFnLogger("onReTargetCompletedFailure",t).logFailure(`reason=${je(e)}, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetFailure",$e(e),t),this.isEscalationInProgress&&(this.setIsEscalationInProgress(!1,t),this.setCallUsesMixer(!1,t),this.updateMediaStatus(t)),this.callStats.localStats.call.event(4),this.mediaSession.rejectEscalationAsync(e,t)},onChatModalitySetupFailed:e=>{this.logger.debug(`onChatModalitySetupFailed: ${e}`)},onConversationUpdated:(e,t)=>{this.logger.info(`onConversationUpdated[${t}]: ${JSON.stringify(ke(e,["organizerId","meetingData"]))}`),this.setConversationType(e.conversationType,t),this._onMessageIdChanged(e.teamsMessageId,t),this.setGroupId(e.groupId,t),this.setThreadId(e.threadId,t),this.setBackroomThreadId(e.backroomThreadId,t),this.setStreamThreadId(e.streamThreadId,t),this.setLobbyThreadId(e.lobbyThreadId,t),this.setCallType(e.isMultiParty?2:1,t),this.setMeetingLayoutDetails(e.meetingLayoutDetails,t),this.setCompositionServiceDetails(e.compositionServiceDetails,t),this._commandUrlPresence=e.commandUrlPresence,this.updateCapabilities(t),this.region=e.region,this.setMeetingData(e.meetingData),this.meetingInfo=e.meetingInfo,this.callLimits=e.callLimits,this.setComplianceRecordingContent(t,e.complianceRecordingContent),this.setHuddleGroupCall(e.isHuddleGroupCall),this.onConversationStartTimeChanged(e.conversationStartTime,t),this.raiseChanged()},onMeetingDetailsUpdated:e=>{this.meetingDetails=e,this.mediaSession&&!this.enableRealtimeTelemetry&&this.meetingDetails.meetingCapability?.enableRealtimeTelemetry&&(this.mediaSession.enableTeamsRealTimeTelemetry(),this.enableRealtimeTelemetry=!0),this.raiseChanged()},onMeetingStatesUpdated:e=>{(0,Ws.isEqual)(e,this.meetingStates)||(this.meetingStates=e,this.logger.info(`[onMeetingStatesUpdated] meetingStates updated to ${JSON.stringify(this.meetingStates)}`),this.raiseChanged())},onParticipantCountsUpdated:e=>{(0,Ws.isEqual)(e,this.participantCounts)||(this.participantCounts={...fr,...e},this.event("participantCountsUpdated").raise(this.participantCounts),this.mediaSession?.processNotification("ParticipantCountChanged",{count:e.totalParticipants}))},updateIsSharedLineAppearanceV2Activated:e=>{this.isSharedLineAppearanceV2Activated!==e&&(this.logger.info(`_updateIsSharedLineAppearanceV2Activated: new value is ${e}`),this.isSharedLineAppearanceV2Activated=e,this.event("sharedLineAppearanceV2ActivatedChanged").raise(this.isSharedLineAppearanceV2Activated))},onBroadcastMeetingUpdated:e=>{e&&(this.broadcastMeeting&&this.broadcastMeeting.metadataChanged(JSON.stringify(e)),this.broadcastMetadata=e,this.raiseChanged())},onBroadcastMeetingConnected:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingConnected]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&(0===e.code?this._callOperationHandler.resolveOperation("AddBroadcastModality",e,t):this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t))},onBroadcastMeetingEnded:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingEnded]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t),this.signalingSession.endBroadcastMeeting(t)},onTransferRequested:(e,t)=>{const i=this.logger.createFnLogger("onTransferRequested",t);i.info("Transfer: onTransferRequested, target participant",rg(e.target));let n="",r="",s=0;"voicemail"===e.target.endpointType&&(s=2);try{n=e.target.id,r=e.transferor.details.id,e&&e.parkType&&"none"!==e.parkType&&(s=1)}catch(e){return i.logFailure(e),this.callTelemetry.recordEvent("_OnTransferRequestedInvalid"),void this.signalingSession.signalTransferCompletedAsync({code:jh(7)})}const a=this.convertToTransferType(s,e.parkType),o={transferContext:{transferorMri:r,targetMri:n,transferType:s,context:{target:e.target,transferor:e.transferor,transferContext:e.transferContext,newCallModalities:e.newCallModalities,links:e.links,replacementDetails:e.replacementDetails,isConsultative:e.isConsultative,callAcceptanceCallback:()=>{i.logSuccess("Transfer: callAcceptanceCallback called"),this.signalingSession.signalTransferAcceptedAsync(a)}}},onCompleted:e=>{i.logSuccess("Transfer: onCompleted called"),this.signalingSession.signalTransferCompletedAsync({code:jh(e)})}};this.callTelemetry.recordEvent("_OnTransferRequested",{transferType:s}),this.event("transferRequested").raise(o)},onTransferredCallAcceptance:e=>{const t=this.logger.createFnLogger("onTransferredCallAcceptance",e);this._transferredCallAcceptanceCallback&&(t.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback())},onTransferAccepted:e=>{this.logger.info("Transfer: onTransferAccepted"),this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&this._setTransferState(2),this._callOperationHandler.hasPendingOperation("BlindTransfer")&&this._callOperationHandler.maybeResolveOperation("_CallTransferInProgress",void 0,void 0,e),this._callOperationHandler.hasPendingOperation("ParkCall")&&this._setParkState(2)},onTransferCompleted:(e,t)=>{const i=this.logger.createFnLogger("onTransferCompleted",t);i.info("Transfer: onTransferCompleted");const n=e.transferCompletion,r=Vh(n);if(n&&(i.info(`Transfer: Call Transfer Code: ${n.code}`),0===n.code)){if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.resolveOperation("_CallTransferInProgress",void 0,void 0,t),this._setTransferState(3)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:0,subCode:0,phrase:"TransactionComplete"};this._callOperationHandler.resolveOperation("ConsultativeTransferWithPickupCode",e,void 0,t),this._setTransferState(3)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation&&(this.serverHoldLocation=e.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("ParkCall",e.unparkContent.pickupCode,void 0,t),i.logSuccess(`pickupCode=${e.unparkContent.pickupCode}`),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",32,t),i.logFailure(`terminatedReason=${r}`),this._setParkState(4)))}else{if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.rejectOperation("_CallTransferInProgress",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setTransferState(4)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:n.code,subCode:n.subCode,resultCategories:n.resultCategories};this._callOperationHandler.rejectOperation("ConsultativeTransferWithPickupCode",e,void 0,t)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(this._callOperationHandler.rejectOperation("ParkCall",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setParkState(4))}},onParkCompleted:(e,t)=>{this.logger.createFnLogger("onParkCompleted",t).info(`transactionEnd ${je(e)}`),this._callOperationHandler.hasPendingOperation("CallParkV2")?0===e.code&&void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("CallParkV2",""+e.unparkContent?.pickupCode,void 0,t),this.callTelemetry.maybeRecordOperationSuccess("CallParkV2"),this.serverHoldLocation=e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation,this.parkAdditionalContextJson=JSON.stringify(e.unparkContent.CallParkAdditionalContext)):this._callOperationHandler.rejectOperation("CallParkV2",e,t):this._callOperationHandler.hasPendingOperation("ParkCall")&&(0===e.code?(this._callOperationHandler.resolveOperation("ParkCall","",void 0,t),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",e,t),this._setParkState(4)))},onUnparkCompleted:(e,t)=>{this.logger.createFnLogger("onUnparkCompleted",t).info(`transactionEnd ${je(e)}`),this._callOperationHandler.hasPendingOperation("UnparkCall")&&(0===e.code?this._callOperationHandler.resolveOperation("UnparkCall",e,void 0,t):this._callOperationHandler.rejectOperation("UnparkCall",e,t))},onIncomingCallReplacement:(e,t)=>{const i=this.logger.createFnLogger("onIncomingCallReplacement",t);this.callTelemetry.recordEvent("_onIncomingCallReplacement",{},t),e.callNotification.callType="replaces",e.callNotification.consultativeCallId=this.callId,i.info(`consultativeCallId=${this.callId}`),e.body={gp:e,evt:Bs.INCOMING_SKYPE_NGC_CALL,nsp:void 0},this.event("replacementRequested").raise(e)},onContentSharingStopped:e=>{this.logger.debug("ScreenSharing: onContentSharingStopped");for(const t of this.contentSharingSessions)t.contentSharingGuid===e.correlationId&&(t.contentSharingStatus=7)},onContentSharingStarted:e=>{this.logger.debug("ScreenSharing: onContentSharingStarted");const t=new Bg(this.callTelemetry,this.logger.createChild("ContentSharingSession"),this.signalingSession,e.correlationId||mi(),e.contentIdentifier,e.sessionState,e.subject,e.sessionId);t.contentSharingStatus=2,this.contentSharingSessions.push(t),t.changed((()=>this.removeContentSessionIfEnded(t))),this.event("contentSharingChanged").raise()},onContentSharingUpdated:e=>{this.logger.debug("ScreenSharing: onContentSharingUpdated");const t=(0,Ws.find)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.correlationId));t?(e.presenter&&(t.presenterId=e.presenter),e.subject&&t.subject!==e.subject&&(t.subject=e.subject),e.sessionState&&t.contentSharingState!==e.sessionState&&(t.contentSharingState=e.sessionState),3===t.contentSharingStatus&&this.localSignalingParticipant.id!==e.presenter?t.contentSharingStatus=5:5===t.contentSharingStatus&&this.localSignalingParticipant.id===e.presenter&&(t.contentSharingStatus=3)):this.logger.warn("onContentSharingUpdated: session not found")},onWebRtcMediaNotification:(e,t)=>{this.mediaSession?.processNotification(e,t)},onCorrelationIdUpdated:(e,t)=>this.checkForCallIdUpdate(e,t),onUnmuteRequested:e=>{},onCallForwarded:e=>{e&&e.destinationType!==this.forwardingDestinationType&&(this.forwardingDestinationType=e.destinationType,this.raiseChanged())},onPSTNBalanceUpdate:e=>{},isOneToOnePstnCall:()=>this.isOneToOnePSTNCall(),onUpdateMeetingLiveStateCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingLiveStateCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingLiveState",i)},onUpdateMeetingStatesCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingStatesCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingStates",i)},onUpdateMeetingGroupsCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingGroupsCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingGroups",i)},onSetMeetingLayoutCompleted:(e,t,i)=>{this.logger.info(`[onSetMeetingLayoutCompleted] causeId [${t}] operationId: ${i}`),this.onOperationCompleteCommonHandler(e,t,"SetMeetingLayout")},onJoinMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"JoinMeetingGroup",i)},onLeaveMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"LeaveMeetingGroup",i)},onBreakoutDetailsUpdated:(e,t)=>{this.logger.info(`[onBreakoutDetailsUpdated] [${t}]`),this.breakoutDetails=e,this.raiseChanged()},onIncomingProxiedMessages:(e,t)=>{this.logger.info(`[onIncomingProxiedMessages] [${t}] payload ${je(e,!0)}`),this.event("incomingProxiedMessages").raise(e)},onUpdateParticipantsPropertiesCompleted:(e,t,i)=>{this.logger.createFnLogger("onUpdateParticipantsPropertiesCompleted",i).info(`promisesToResolve ${De(Ge(e))}`);for(const t of Object.keys(e))e[t].code===Ar?this._callOperationHandler.maybeResolveOperation("UpdateParticipantsProperties",e[t],t,i):this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",e[t],t,i)},onUpdateMonitorSessionCompleted:(e,t)=>{this.logger.info(`[onUpdateMonitorSessionCompleted] [${t}] transactionEnd ${je(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMonitorSession")},onNudgeToJoinRealtime:e=>{this.logger.info("[onNudgeToJoinRealtime]",e),this.callTelemetry.recordEvent("NudgeToJoinRealTime",e),this.canPromoteToRealTime(1)&&this.promoteToRealtime(1,e).then((()=>this.logger.info(`[onNudgeToJoinRealtime][${e}] completed`))).catch((t=>this.logger.info(`[onNudgeToJoinRealtime][${e}] failed to auto promote: ${je(t)}`)))},onConversationTypeUpdated:(e,t)=>{this.logger.info(`[onConversationTypeUpdated] [${t}] conversationType ${e}`),this.setConversationType(e,t)}};const n=Object.create(this.localSignalingParticipant);this.signalingSession=this.signalingAgent.getNewSignalingSession(n,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(t,i,n,r){const s=e.getNegotiationTagsFromEndpoints(i.endpointDetails);t.updateStreams(n,r,this.isCallModeStreaming(),s,this.isMultiVBSSEnabled());const a=this.getStreamInformationMap(i);this.logger.info(`[updateParticipantStreams]: streaming mode with new streamInfoMap: ${Ge(a)}`);const o={callId:this.callId,participantId:this.participantId,endpointId:this.endpointId};this.meetingData&&(o.meetingId=this.meetingData.meetingCode);const l=this.telemetryLoggers?this.telemetryLoggers.tlePlayer:null;t.useUmsStream(a,this._liveStreamConfigProvider,o,this.threadId,l,r)}cleanUpDueToStreaming(e){this.logger.info(`cleanUpDueToStreaming[${e}]: cleaning streams and media and canceling cc operations`),this.cancelAllCallingOperationsDueToStreaming(e);const t={code:0,subCode:3099,phrase:"DowngradeToStreamingClient"};this.participants.forEach((t=>t.updateStreams([],e,this.isMultiVBSSEnabled()))),this.cleanUpMedia(e,t).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((t=>{this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:$e(t)},e)})).finally((()=>{this.mediaDisposedPromise=null})),this.finishCallHoldResume(t),this.renegotiationAnswerDeferred?.reject(t),this.newOfferRequestDeferred?.reject(t),this._parkState=0,this._transferState=0,this.isServerMuted||(this._muteState=0),this.isSpeakerMuted=!1,this.requestedHoldState=!1,this.isMuteOnHold=!1}cancelAllCallingOperationsDueToStreaming(e){this._callOperationHandler.maybeRejectPendingOperationsWithPredicate(74,e,((e,t)=>(0,Ws.some)(t?.preconditionTags,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))))}onOperationCompleteCommonHandler(e,t,i,n){0===e.code?this._callOperationHandler.maybeResolveOperation(i,e,n,t):this._callOperationHandler.maybeRejectOperation(i,e,n,t)}convertToTransferType(e,t){let i="none";return 1===e&&t&&"none"!==t?"teamPark"===t?i="TransferTypeTeamPark":"sharedLinePark"===t?i="TransferTypeSharedLinePark":"serverHold"===t&&(i="TransferTypeServerHold"):0===e?i="TransferTypeStandard":2===e?i="TransferTypeVoicemail":this.logger.info(`Irrelevant combination of transferTye: ${e} and parkType: ${t}`),i}raiseChangedDeferred(e){(!this.raiseChangedDefer||this.raiseChangedDefer.isSkippable&&!e)&&(cg.instance.runDeferredWithoutDedup((()=>{delete this.raiseChangedDefer,this.raiseChanged(e)}),"Call.raiseChanged"),this.raiseChangedDefer={isSkippable:!!e})}static getStreamsFromEndpoints(t,i){if(!t)return[];const n=e.filterVirtualEndpoints(t);return n.forEach((e=>{e.mediaStreams=i?e.mediaStreams:e.mediaStreams?.filter((e=>e.type!==Sg)),(0,Ws.forEach)(e.mediaStreams,(t=>{t.participantId=e.participantId,t.endpointId=e.endpointId}))})),(0,Ws.flatMap)(n,(e=>e&&e.mediaStreams||[]))}preconditions(e,t){this.logger.info(`check call mode currentMode is ${this.callMode} operationName is ${e}`),(0,Ws.some)(t,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))&&this.isCallModeStreaming(!0)}mapCallSetupIntent(e){switch(e){case 0:return"None";case 1:return"AutoPromotion";case 2:return"PromotionWithAudio";case 3:return"PromotionWithVideo";default:return"Unknown"}}async promoteToRealtime(e,t){this.logger.info(`[${t}][promoteToRealtime] started with intent=${e}`);const i=this.getPromoteToRealtimeCallOptions(e,this.callOptions);this.callTelemetry.updateOperationData("_PromotionToRealtime",{intent:e},t),this.callTelemetry.recordEvent("StartPromotion",{intent:this.mapCallSetupIntent(e)},t);try{this.promotionCompletedDeferred=new Kt,await Promise.all([this.joinOrStartCall(i,this.joinGivenConversation,t,void 0),this.promotionCompletedDeferred.promise])}catch(e){throw this.logger.logFailure(`[${t}][promoteToRealtime] failed with reason=${je(e)}`),this.cleanUpDueToStreaming(t),this.signalingSession.cleanUpDueToStreaming(t),e}}async promoteToRealtimeAndUnmute(e){return this.logger.info(`[${e}][promoteToRealtimeAndUnmute]`),this.isPromotingToRealtime()?(this.logger.info(`[${e}][promoteToRealtimeAndUnmute] already promoting to realtime.`),this._callOperationHandler.waitForOperation("_PromotionToRealtime").then((()=>this.muteUnmute(!1,e)))):this.canPromoteToRealTime(2)?(this.unmutePendingPromise=new Kt,setTimeout((()=>{this.unmutePendingPromise?.reject("promoteToRealtime unmute timed out")}),1e3*this.signalingSession.signalingAgentConfig.csaTimeoutConfiguration.promotionUnmuteTimeoutSec),Promise.all([this.promoteToRealtime(2,e),this.unmutePendingPromise.promise]).then((()=>{})).finally((()=>this.unmutePendingPromise=null))):Promise.reject("manual promotion with audio is not allowed")}isPromotingToRealtime(){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")}getPromoteToRealtimeCallOptions(e,t){let i,n=1;1===e?i={value:!0,mediaTypes:["audio"]}:3===e?(i={value:!0,mediaTypes:["audio"]},n=4):2===e&&(i={value:!1});const r={...t.callStartOptions,sendMediaModalities:{mediaStates:[Gh(0,4),Gh(1,n)].filter((e=>null!=e))},preheatFlags:0};return{...t,callStartOptions:r,applyServerMute:i,isPromotingToRealtime:!0,callStartTime:Date.now()}}canPromoteToRealTime(e){const t=this.logger.createChild("[canPromoteToRealTime]");return t.info(`[promoteType:${e}]`),this.isCallModeStreaming()?this.isPromotingToRealtime()?(t.info("already promoting to realtime"),!1):1===e||2===e:(t.info("cant promote since call mode is not streaming"),!1)}isCallModeStreaming(e=!1){if(2===this.callMode){if(!e)return!0;throw this.logger.info("reject check callmode"),{code:499,subCode:3551,phrase:"TransactionNotAllowedForStreamMode"}}return!1}setCallOptions(e){this.receiveOnlyAudioOnCallStart=!!e.callStartOptions?.receiveOnlyAudioOnCallStart,this.callOptions=e,this.logger.info(`callOptions: ${Ge(function(e){const t={};Kh(e.callStartTime)&&(t.callStartTime=e.callStartTime),Kh(e.callVoicemailStartOptions)&&(t.callVoicemailStartOptions=e.callVoicemailStartOptions),Kh(e.invitationType)&&(t.invitationType=e.invitationType),Kh(e.meetingPreferences)&&(t.meetingPreferences=e.meetingPreferences),Kh(e.parkContext)&&(t.parkContext=e.parkContext),Kh(e.pickupCode)&&(t.pickupCode=e.pickupCode),Kh(e.participantsToNudge)&&(t.participantsToNudgeSize=e.participantsToNudge.length);const i=e.callStartOptions;if(i){const e={};Kh(i.additionalEndpointProperties)&&(e.additionalEndpointProperties=i.additionalEndpointProperties),Kh(i.clientEndpointCapabilities)&&(e.clientEndpointCapabilities=i.clientEndpointCapabilities),Kh(i.connectionType)&&(e.connectionType=i.connectionType),Kh(i.invitationDataJson)&&(e.invitationDataJson=i.invitationDataJson),Kh(i.isCast)&&(e.isCast=i.isCast),Kh(i.isHuddleGroupCall)&&(e.isHuddleGroupCall=i.isHuddleGroupCall),Kh(i.label)&&(e.label=i.label),Kh(i.maxVideoChannels)&&(e.maxVideoChannels=i.maxVideoChannels),Kh(i.maxVbssChannels)&&(e.maxVbssChannels=i.maxVbssChannels),Kh(i.mediaConfiguration)&&(e.mediaConfiguration=i.mediaConfiguration),Kh(i.muteFlags)&&(e.muteFlags=i.muteFlags),Kh(i.muted)&&(e.muted=i.muted),Kh(i.negotiationTag)&&(e.negotiationTag=i.negotiationTag),Kh(i.preheatFlags)&&(e.preheatFlags=i.preheatFlags),Kh(i.ringOthers)&&(e.ringOthers=i.ringOthers),Kh(i.routingFlags)&&(e.routingFlags=i.routingFlags),Kh(i.scenario)&&(e.scenario=i.scenario),Kh(i.screenshareDirection)&&(e.screenshareDirection=i.screenshareDirection),Kh(i.sendMediaModalities)&&(e.sendMediaModalities=i.sendMediaModalities),Kh(i.sharedLineCallInvitationContentJson)&&(e.sharedLineCallInvitationContentJson=i.sharedLineCallInvitationContentJson),Kh(i.targetApplicationType)&&(e.targetApplicationType=i.targetApplicationType),Kh(i.captchaContentJson)&&(e.captchaContentJson=i.captchaContentJson),Kh(i.callQueueContext)&&(e.callQueueContext=i.callQueueContext),Kh(i.clientEndpointDebugContent)&&(e.clientEndpointDebugContentSize=i.clientEndpointDebugContent.length),Kh(i.alternateId)&&(e.alternateId=De(i.alternateId)),Kh(i.callKey)&&(e.callKeySize=i.callKey.length),Kh(i.encryptedKey)&&(e.encryptedKeySize=i.encryptedKey.length),t.callStartOptions=e}return t}(e))}`)}getSelfClientEndpointCapabilities(){return this.callOptions?.callStartOptions?.clientEndpointCapabilities}getLocalSignalingEndpointDetails(){return(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(e=>e?.endpointId===this._endpointId))}getStreamInformationMap(e){const t={};return e&&this.accountConfiguration?.clientSupportsUms&&(0,Ws.forEach)(e.endpointDetails,(e=>{e?.streamInformation&&e.participantId&&e.participantId!==this._participantId&&(t[e.participantId]=e.streamInformation)})),t}updateSATInfo(e=[]){const t=this.mediaSession?.getSessionConfig().config.slowedDownTalkerInfoAggregationTime;if(!t||t<0)return;const i=Date.now(),n=i-1e3*t;this.activeTalkersHistory=this.activeTalkersHistory.filter((({timestamp:e})=>e>n)).concat({speakers:e.map((e=>e.id)),timestamp:i});const r=Object.entries(this.activeTalkersHistory.reduce(((e,{speakers:t})=>{for(const i of t)e[i]??(e[i]=0),e[i]++;return e}),{})).sort((([,e],[,t])=>t-e)).map((([e])=>e));this.slowedDownActiveTalkerInfo={speakerList:r,timestamp:new Date(i)}}enableRemoteUFDs(e){this.logger.info((e?"Enabling":"Disabling")+" remote UFDs"),e?this.remoteUFDHandler.init():this.remoteUFDHandler.dispose()}setPlatformCallConstraints(e){this.setCallConstraints(e).catch((e=>{this.logger.error(e)}))}setCallConstraints(e){return this.mediaSession?(this.logger.info(`Applying platform constraints to current call ${JSON.stringify(e)}`),this.mediaSession.setCallConstraints(e,be())):(this.logger.info("Saving platform constraints until media session is created"),this.temporaryCallConstraints=e,new Promise(((e,t)=>{this.resolveTemporaryCallConstraints=e,this.rejectTemporaryCallConstraints=t})))}initializeMediaSession(t,i){if(this.mediaSession)return;const n=this.logger.createFnLogger("initializeMediaSession",t),r=((e,t)=>{const i={};return Object.keys(t).forEach((n=>{i[n]=(...i)=>t[n]&&e()&&t[n](...i)})),i})((()=>!this.isCallModeStreaming()||this.isPromotingToRealtime()),{onSessionErrorOccurred:(e,t=be())=>{n.error(`[${t}][onSessionErrorOccurred]: ${Ge(e)}`);const i=[this.mediaAgent.constants.MEDIA_ERROR.iceConnectionError,this.mediaAgent.constants.MEDIA_ERROR.internalError];(0,Ws.includes)(i,e.type)&&this.event("mediaConnectionFailed").raise(),this.callTelemetry.recordEvent("SessionError",{type:e.type},t)},onNegotiationRequired:(e=be(),t)=>{this.executeNegotiation(e,"onNegotiationRequired",!0,t)},onContributingSourcesChanged:e=>{const t=this.mediaSession?.getSessionConfig().config.contributingSourcesLogInterval,i=t&&Date.now()>=this.lastContributingSourceReport+t,r=i?new Map(e.map((e=>[e,"<unknown>"]))):new Map,s=[];for(const t of this.participants){const n=e.some((e=>t.hasAudioSource(e))),a=n?1:0;t.updateVoiceLevel(a),n&&(s.push(t),i&&r.set(t.audio.id,De(t.id)))}this.updateSATInfo(s),i&&(n.info(`[onContributingSourcesChanged], ${e.length?Array.from(r).join(";"):"none"}`),this.lastContributingSourceReport=Date.now())},onDominantSpeakerChanged:(e,t)=>{const i=be(),r=[],s=[];e.forEach((e=>{const t=(0,Ws.find)(this.participants,(t=>t.hasAudioSource(e)));t?(r.push(t.id),s.push(De(t.id))):s.push(this.streamManager.audio.id===e?"<self>":"<unknown>")})),n.info(`[${i}][onDominantSpeakerChanged], msidList = ${e} => speakerList = ${s}, timestamp = ${t}`),this.dominantSpeakerInfo={speakerList:r,timestamp:t,noCurrentDominantSpeaker:!1},this.event("dominantSpeakerChanged").raise(),this.raiseChanged(this._dominantSpeakerChangedEventSkipConfig)},onAudioStateChanged:(t,i)=>{const n=be(),r=this.logger.createFnLogger("onAudioStateChanged",n);r.info(Ge(t)),this.callStats.localStats.audio.streamStateChanged(t.stream,t.direction);const s=e.streamingStatetoMediaStreamState(t.stream);if(this.audioStreamState=s,!s)return;this.callTelemetry.recordEvent("AudioStateChanged",{state:t,reason:i},n),2===s&&2===this.state&&(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n))));const a={mediaType:0,mediaDirection:e.streamingDirectionToMediaDirectionMapping(t.direction),mediaStreamState:s};if(this.event("mediaStreamStateChanged").raise(a),!this.isCallSetupTelemetrySent&&this.mediaSession?.getSessionConfig().config.sendCallStartupTelemetry&&this.sendCallSetupTelemetry(),0===a.mediaDirection&&(this.isAudioStreamConnected=(0,Ws.includes)([2,1],a.mediaStreamState)),(0,Ws.includes)([3,4],a.mediaStreamState)&&(r.logFailure(`audio stream state changed to ${t.stream} with reason ${i}`),!i||["timeout","connection-dropped","connectivity-check-failure","suspended"].indexOf(i)>=0)){this.event("mediaConnectionFailed").raise();const e="suspended"===i?77:this.mediaRelayWhiteListingIssue?53:4;this.mediaRelayWhiteListingIssue&&this.callTelemetry.recordEvent("_MediaWhiteListingIssueDetected"),this.stopInternal({causeId:n,terminatedReason:e})}},onQualityChanged:t=>{const i={type:e.convertQualityEventType(t.type),value:e.convertQualityLevel(t.value),isLocalSource:t.isLocalSource,mediaType:e.convertMediaType(t.mediaType)};this.muteUnmuteWorkaround(i),32===i.type&&(this.mediaRelayWhiteListingIssue=3===i.value,this.mediaRelayWhiteListingIssue&&this.event("mediaConnectionWhitelistingWarning").raise()),5===i.type&&3===i.value&&this.trouterService.checkConnection(!0),this.callTelemetry.recordEvent("AudioQualityChanged",i),this.remoteUFDHandler.raiseIfNeeded(t,this.participantCounts?.totalParticipants,(e=>{this.publishState(e,be())})),this.event("callQualityChanged").raise(i)},onOptimalVideoReceiversCountChanged:e=>{n.debug(`onOptimalVideoReceiversCountChanged: ${e}`),this.optimalVideoCount!==e&&(this.optimalVideoCount=e,this.raiseChanged())},onDataChannelUpdated:e=>{const t=be();n.debug(`[${t}] onDataChannelUpdated`),this.dataChannel.registerSessionDataChannel(e,t)},onUpdateMediaDescriptionsRequired:(e,t)=>{this.executeNegotiation(e,"onUpdateMediaDescriptionsRequired",!1,t)},onRealtimeTelemetryReport:()=>{this.reportTelemetryEvents([{eventName:Ah.realtimeTelemetry,props:{user_object_id:{value:dh+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:e=>this.updateSignalingDSHMessageSubscription(e)});this.callTelemetry.recordEvent("CreatingConference","",t),this.callDeviceManager||(n.info(`[${t}][initializeMediaSession] Creating new callDeviceManager`),this.callDeviceManager=this.createCallDeviceManager());const s={maxReinvitelessMediaForVBSSMultiparty:this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb(),maxReinvitelessMediaForVideoMultiparty:this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()};this.callTelemetry.recordEvent("_ReinvitelessConfig",{reinvitelessConfig:s},t);const a=this.mediaAgent?.getConfigProvider().config.identifyOneToOneCallWithoutParticipants;this.mediaSession=new Xh(this.mediaAgent.createSession(r,this.signalingSession,{isConference:this.callUsesMixer,isPstnCall:this.isOneToOnePSTNCall(a),isParkedCall:this.isParkedCall(),reinvitelessConfig:s},this.callDeviceManager,this.smallCallTelemetry,i),this.signalingSession),this.batteryStatus=new Pf(this.mediaSession.getDiagnostics(),this.mediaAgent.getConfigProvider()),this.batteryStatus.on("batteryStatusChanged",(()=>this.reportSmallCallEvent(this.smallCallTelemetry?.getSmallTelemetryOnBatteryLow()))),this.temporaryCallConstraints&&(n.info(`Applying saved call constraints to current call ${JSON.stringify(this.temporaryCallConstraints)}`),this.mediaSession.setCallConstraints(this.temporaryCallConstraints,be()).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","",t),this.streamManager.setMediaSession(this.mediaSession,t),this.participants.forEach((e=>{e.setMediaSession(this.mediaSession,t)}));const o=this.mediaSession.getSessionConfig()?.config;o?.useOneDsLogger&&o?.addTelemetryReportingCallback&&(this.beforeUnloadTelemetrySender=()=>{this.sendLastKnownStats()},window.addEventListener("beforeunload",this.beforeUnloadTelemetrySender)),this.screenSharingControl&&this.allowDataChannel()&&this.screenSharingControl.setupDataHandlers(),this.unmixedAudioProvider=new bf}executeNegotiation(e,t,i,n){const r=this.logger.createFnLogger(t,e);if(this.isCallModeStreaming()||this.isEscalationInProgress)return void r.info(`ignored due to being in streaming=${this.isCallModeStreaming()},\n isEscalationInProgress=${this.isEscalationInProgress}`);const s=be();3===this.state||4===this.state||5===this.state||10===this.state||this.isPreheatedOnly()?(r.info(`started, state: ${this.state}, runNegotiation: ${i}`),i?(this.callTelemetry.recordEvent("NegotiationRequired","",e),this._callOperationHandler.executeChained((()=>this.renegotiateOutgoing(e,n)),"_RenegotiateOutgoing",s,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})):(this.callTelemetry.recordEvent("UpdateMediaDescriptions","",e),this._callOperationHandler.executeChained((()=>this.updateMediaDescriptions(e,n)),"_UpdateMediaDescriptions",void 0,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}))):r.info(`not started, state: ${this.state}`)}async muteUnmuteWorkaround(e){if(this.mediaSession?.getSessionConfig().config.enableMuteSpeakerUnmuteSpeakerWorkaround&&!this.isSpeakerMuted&&25===e.type&&3===e.value&&0===e.mediaType){this.logger.log("Performing muteSpeaker->unmuteSpeaker workaround");const e=be();await this.muteSpeaker(e),await this.unmuteSpeaker(e)}}sendLastKnownStats(){if(this.tsCallingTelemetryReported)return;this.callEndDiagnosticsInfo={callControllerCode:Ar,callControllerSubCode:xr},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo);const e=this.callTelemetry.getShortEvent();e.Code=this.callEndDiagnosticsInfo.callControllerCode,e.SubCode=this.callEndDiagnosticsInfo.callControllerSubCode;let t="csa_conversation_callmodality";if(this.reportTelemetryEvents([{eventName:t,props:e}],"signaling","skypecosi_concore_web"),t=this._callIsSetupComplete?"in_call_session":"call_setup_session",this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(!0)}],"signaling","skypecosi_concore_web_ts_calling"),this.mediaSession){const e=this.mediaSession.getLastKnownStats(!0);this.callStats.setMediaStats(e),this.reportSmallCallEvent(null,!0),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web")}this.reportVDITelemetryEvents()}reportSmallCallEvent(e,t){this.reportTelemetryEvents(this.callStats.buildShortCallEvent(e??this.smallCallTelemetry?.getEndCallSmallTelemetry(t)),"media","mdsc")}invertDirectionality(e){switch(e){case this.mediaAgent.constants.MEDIA_STATE.sendReceive:return gg;case this.mediaAgent.constants.MEDIA_STATE.send:return hg;case this.mediaAgent.constants.MEDIA_STATE.receive:return ug;default:return null}}completeNegotiationAsync(e){const t=this.logger.createFnLogger("completeNegotiationAsync",e),i=this.mediaSession.completeNegotiationAsync(e).then((i=>{t.info(`activeModalities=${i&&Object.keys(i.activeModalities)}`);const n=this.mediaSession.getSessionConfig().config.avoidFakeStreamsDuringEscalation&&this.isEscalationInProgress;if(!this.callUsesMixer&&!n){if(this.mediaStateConfigurationHelper.isSending(3)&&i.initiator){const t=i.offeredModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive,n=i.activeModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive;t&&!n&&(this.logger.info(`[${e}][completeNegotiationAsync] Disabling data modality as it was not wanted by remote`),this.mediaStateConfigurationHelper.removeModality(3))}const t=this.participants[0],n=t?.endpoints?.endpointDetails.length&&t.endpoints.endpointDetails[0].mediaStreams?.length;if(t&&!n){const n=(e,t,i)=>({participantId:Of,endpointId:"remote",type:e,direction:this.invertDirectionality(t),sourceId:i,serverMuted:!1}),r=[];r.push(n(pg,i.activeModalities.audio,1)),i.activeModalities.video&&r.push(n(mg,i.activeModalities.video,2)),i.activeModalities.sharing&&r.push(n(fg,i.activeModalities.sharing,3)),t.updateStreams(r,e,this.isMultiVBSSEnabled()),!this.callIsHeld()&&this.calculateIsSomeoneStreaming(e)}}if(t.logSuccess(Ge(i)),this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&i?.activeModalities?.audio){const t=i.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||i.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(t?2:this.isServerMuted?1:0,e)}return i}));return i.catch((i=>{t.logFailure(i),this.callTelemetry.recordEvent("_CompleteNegotiationFailed",{e:i},e)})),i}async renegotiateOutgoing(e,t){this.renegotiationAnswerDeferred=new Kt;const i=this.logger.createFnLogger("renegotiateOutgoing",e),n=this.inLocalHold()?this.getMediaModalitiesForHold(e):this.calculateModalityDirections({},e);if(this._delayedElevationPending&&!this._delayedElevationQueued){if(Wp(n.video)||Wp(n.sharing))return i.info("mediaModalities",n),void await this.triggerDelayedReconnectIfNeeded(e,"renegotiateOutgoing");i.info("Delayed elevation (renegotiateOutgoing): no outgoing video or sharing, skipping elevation for now")}i.info("start");const r=mh(i);try{try{const i=await r.execute("MediaCreateOffer",(()=>this.mediaSession.createOfferAsync(e,t))),s=this.getSignalingMediaTypes(n);await r.execute("SignalingStartNegotiation",(()=>this.signalingSession.startRenegotiationAsync(i,s,e)));const a=await r.execute("SignalingRenegotiationAnswer",(()=>this.renegotiationAnswerDeferred.promise));await r.execute("MediaProcessAnswer",(()=>this.mediaSession.processAnswerAsync(a,e,!1)));const o=await r.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(e)));this.onNegotiationCompletion(o,!0,n,e,r.getTelemetryData())}catch(t){if(i.logFailure(t),!t.phase)throw this.callTelemetry.recordEvent("OutgoingNegotiationFailure",t,e),t;let r="unknown";const s=this.mediaAgent.constants.RENEGOTIATION_ERROR;if(r=s.local,"SignalingRenegotiationAnswer"===t.phase||"SignalingStartNegotiation"===t.phase){const e=415;r=491===t.error.code?s.glare:t.error.code===e?s.media:s.signaling}else"MediaCreateOffer"===t.phase&&t.error.type===this.mediaAgent.constants.MEDIA_ERROR.noNetworkError&&(r=s.media);if(this.callTelemetry.recordEvent("OutgoingNegotiationFailure",this.getTelemetryFromPhaseExecution(t),e),t.error.message?.includes("The requested call does not exist"))throw new Error("Call drop due to remote replying with call not found");i.logFailure(r);const a={type:r,detail:t.error};await this.mediaSession.rejectNegotiationAsync(a,e),this.onNegotiationFailure(t.error,r,e,n)}}catch(t){i.logFailure(t),this.callTelemetry.recordEvent("NegotiationFatalError",$e(t),e),this.stopInternal({causeId:e,terminatedReason:47})}}async renegotiateIncoming(e,t){this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",null,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.mediaAcknowledgmentOperation.catch(wr);const i=this.logger.createFnLogger("renegotiateIncoming",t);if(i.info("start"),e.newOffer&&!this.mediaAgent.getCapabilities().retargeting)return i.logFailure("Retarget offer received, but pluginless has no support for retarget"),void this.stopInternal({causeId:t,terminatedReason:38});const n=mh(i);try{const i=await n.execute("MediaProcessOffer",(()=>this.mediaSession.processOfferAsync(e,t)));this.handleOfferedModalities(i,t),2===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForResume(t);const r=await this.updateMediaModalities({offered:i},t);1===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForHold(t),this.updateMediaState(r,t),this.isRenegotiationHoldOrResume(r)&&this.updateScreenSharingState(r,t);const s=await n.execute("MediaCreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t))),a=this.getSignalingMediaTypes(r);await n.execute("SignalingAcceptRenegotiation",(()=>this.signalingSession.acceptRenegotiationAsync(s,a,t))),await n.execute("SignalingMediaAcknowledgement",(()=>this.mediaAcknowledgmentOperation));const o=await n.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t)));this.onNegotiationCompletion(o,!1,i,t,n.getTelemetryData())}catch(e){try{if(!e.phase||"CompleteNegotiation"===e.phase)throw this.callTelemetry.recordEvent("IncomingNegotiationFailure",e,t),e;const n=e;this.callTelemetry.recordEvent("IncomingNegotiationFailure",this.getTelemetryFromPhaseExecution(e),t);const r={type:this.mediaAgent.constants.RENEGOTIATION_ERROR.local,detail:e.error};if("SignalingAcceptRenegotiation"===n.phase||"SignalingMediaAcknowledgement"===n.phase)return i.logFailure("Error in renegotiateIncoming() -> rejecting media negotiation"),r.type=this.mediaAgent.constants.RENEGOTIATION_ERROR.signaling,this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),void await this.mediaSession.rejectNegotiationAsync(r,t);this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),await this.mediaSession.rejectNegotiationAsync(r,t),await this.signalingSession.rejectRenegotiationAsync(void 0,t)}catch(e){i.logFailure(e),this.callTelemetry.recordEvent("NegotiationFatalError",$e(e),t),this.stopInternal({causeId:t,terminatedReason:47})}}}async updateMediaDescriptions(e,t){const i=this.logger.createFnLogger("updateMediaDescriptions",e);i.info("start");try{const n=await this.mediaSession.startMediaDescriptionsUpdateAsync(e,t);i.info(`send updateMediaDesriptions, descriptions=${Ge(n)}`),await this.signalingSession.updateMediaDescriptionsAsync(e,n);const r=await this.mediaSession.completeMediaDescriptionsUpdateAsync(e);if(this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&r?.appliedModalities?.audio){const t=r.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||r.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(t?2:this.isServerMuted?1:0,e)}this.onUpdateMediaDescriptionsCompletion(r,e)}catch(t){i.logFailure(t),this.callTelemetry.recordEvent("UpdateMediaDescriptionsFailure",t,e);const n=await this.mediaSession.rejectMediaDescriptionsUpdateAsync(e,!0);this.onUpdateMediaDescriptionsFailure(t,n,e)}}handleCallEscalation(e,t){const i=this.logger.createFnLogger("handleCallEscalation",t);if(i.info(`current callType=${this.callType}, escalationInProgress=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e){const e=this.participants[0];e&&e.audio.participantId===Of?e.updateStreams([{type:pg,direction:"inactive",sourceId:null,serverMuted:!1},{type:mg,direction:"inactive",sourceId:null,serverMuted:!1},{type:fg,direction:"inactive",sourceId:null,serverMuted:!1}],t,this.isMultiVBSSEnabled()):i.info("no 1-1 participant found, stream update ignored"),this.setCallType(2,t),this.setCallUsesMixer(!0,t),this.setIsEscalationInProgress(!1,t),this.callTelemetry.recordEvent("_EscalationCompleted",void 0,t),this.raiseChanged()}}async reportTsCallingTelemetry(e){if(this.tsCallingTelemetryReported)return;await this.connectCallPromise.catch(wr);const t=e?"call_setup_session":"in_call_session";this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(e)}],"signaling","skypecosi_concore_web_ts_calling"),e?this.callTelemetry.switchToInCallTelemetry():this.tsCallingTelemetryReported=!0}async sendMidCallTelemetry(e){this.mediaSession&&e?.length&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(!0)),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildMidCallTelemetry(e),"media","mdsc_mid_call_telemetry"))}sendCallSetupTelemetry(){this.mediaSession&&(this.collectCallStats(this.mediaSession),this.reportCallSetupStats(),this.isCallSetupTelemetrySent=!0)}collectCallStats(e){const t=()=>this.collectMediaStatsDeferred.resolve();return e.getStatsAsync(!1).then((e=>this.callStats.setMediaStats(e))).then(t,t)}reportCallSetupStats(){this.collectMediaStatsDeferred.promise.then((()=>{this.reportTelemetryEvents(this.callStats.buildFromCallSetupStats(this.signalingSession.baseMessagingChannelUrl),"media","mdsc"),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new Kt}))}async reportCallEndStats(e){this.callTelemetry.setTerminationState(this.state),this.callTelemetry.setTerminationReason(this.terminatedReason),this.callStats.localStats.endCall(this.terminatedReason),e&&this.mediaAgent.getConfigProvider().config?.smallCallTelemetry?.enable&&this.reportSmallCallEvent(null),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.reportTsCallingTelemetry(!this._callIsSetupComplete),e&&(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 Kt}async reportVDITelemetryEvents(){this.vdi3diagnostics&&this.reportTelemetryEvents([{eventName:"vdi_webrtc_session",props:await this.callStats.buildVDItelemetryReport(this.vdi3diagnostics)}],"media","mdsc")}reportTelemetryEvents(e,t,i){const n=this.telemetryLoggers?this.telemetryLoggers[t]:null;n?e.forEach((e=>n.sendEvent({eventName:`${i?`${i}_`:""}${e.eventName}`,props:e.props}))):this.logger.debug(`reportTelemetryEvents no logger for tenant ${t}`)}onLocalPreviewSizeChanged(e,t){this.logger.debug(`onLocalPreviewSizeChanged: ${e}x${t}`)}onLocalPreviewStateChanged(e){this.logger.debug(`onLocalPreviewStateChanged: ${e}`),this.callStats.localStats.video.streamStateChanged(e.stream)}async configureVideoModalitiesAsync(e,t,i){if(!this.mediaSession)return this.logger.warn("Tried to configure modalities after call end"),Promise.resolve();e&&this._delayedElevationPending&&!this._delayedElevationQueued&&await this.triggerDelayedReconnectIfNeeded(t,"configureVideoModalitiesAsync"),await this.updateMediaModalities(void 0,t,i),e||this.turnOffLocalVideoPreview(t),this.setVideoOn(e,t)}turnOffLocalVideoPreview(e){return this.localVideoRenderer&&(this.localVideoRenderer.dispose(),this.localVideoRenderer=null),this.disposeLocalVideoHandle(),Promise.resolve(void 0)}turnOnLocalVideoPreview(e){return this.mediaSession?.getSessionConfig().config.useDeviceHandleForLocalVideo?this.acquireLocalVideo(e):(this.localVideoContainer||(this.localVideoContainer=document.createElement("div")),this.turnOnLocalVideoPreviewUsingRenderer(e))}acquireLocalVideo(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e);if(!this.mediaStateConfigurationHelper.isSending(1))return Promise.reject("could not start video preview, not configured to send");try{this.disposeLocalVideoHandle();const e=this.callDeviceManager.getDeviceManager(Jh(1));return this.localVideoHandle=e.createDevicesHandle({video:!0},"pluginlessCall:acquireLocalVideo()"),this.localVideoHandle.on("onStreamStateChanged",(e=>this.onLocalPreviewStateChanged({stream:e}))),this.localVideoHandle.acquire()}catch(e){return t.logFailure(e),void this.disposeLocalVideoHandle()}}turnOnLocalVideoPreviewUsingRenderer(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e),i=this.mediaStateConfigurationHelper.isSending(1);if(!i||!this.localVideoContainer)return Promise.reject(`could not start video preview: requestedVideoState=${i}, localVideoContainer=${this.localVideoContainer}`);this.turnOffLocalVideoPreview(e);const n=Wt((()=>{this.localVideoRenderer=this.callDeviceManager.getDeviceManager(Jh(1)).createPreviewRenderer(this.localVideoContainer,"Video"),this.localVideoRenderer.on("onVideoSizeChanged",((e,t)=>this.onLocalPreviewSizeChanged(e,t))),this.localVideoRenderer.on("onVideoStateChanged",(e=>this.onLocalPreviewStateChanged(e)))})).then((()=>this.localVideoRenderer.startVideoAsync(e)));return n.catch((e=>t.logFailure(e))),n}async startStopVideo(e,t,i){const n=this.logger.createFnLogger(e?"startVideo":"stopVideo",t);return n.info("start"),this.canToggleVideo?(e?(this.callStats.localStats.newSession(1),this.callStats.localStats.video.start()):this.callStats.localStats.video.stop(),e&&this.mediaStateConfigurationHelper.isDisabled(1)&&n.info("Video modality was skipped till now. Adding it now."),e?this.mediaStateConfigurationHelper.enableModality(1):this.mediaStateConfigurationHelper.removeModality(1),this.canToggleVideo=!1,this.videoTogglePromise=(async()=>{try{let n=!1;e&&(await this.turnOnLocalVideoPreview(t),n=!0),await this.configureVideoModalitiesAsync(n,t,i)}catch(e){throw n.logFailure(e),this.mediaStateConfigurationHelper.removeModality(1),await this.configureVideoModalitiesAsync(!1,t,i),e}finally{this.canToggleVideo=!0}})(),this.videoTogglePromise):e===this.mediaStateConfigurationHelper.isSending(1)?(await this.videoTogglePromise,void this.turnOnLocalVideoPreview(t)):(n.logFailure(`video switching is in progress ${e}]`),Promise.reject({reason:1}))}async startStopAudio(e,t){const i=this.logger.createFnLogger(e?"startAudio":"stopAudio",t);try{const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t)}catch(e){return i.logFailure(e),9}return 0}updateEndpointStateForMute(e,t){try{this.signalingSession.updateEndpointState({state:{isMuted:e}},t).catch((e=>{this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}))}catch(e){this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}}async handleServerMutedState(e){const t=this.logger.createFnLogger(`handleServerMutedState, isServerMuted=${!!this.isServerMuted}`,e);if(!this.isServerMuted){const i=3===this._muteState;if(1===this._muteState||i)try{t.info("is unmuting, as we are no longer server muted"),await this.handleMuteUnmuteOnMediaSession(!1,e),this.setMuted(0,e),this.unmutePendingPromise?.resolve(),i&&this.updateEndpointStateForMute(!1,e)}catch(e){throw t.logFailure(e),e}}if(this.isServerMuted&&0===this._muteState){t.info("is muting, as we are unmuted");try{await this.handleMuteUnmuteOnMediaSession(!0,e),this.setMuted(1,e)}catch(e){throw t.logFailure(e),e}}}async handleMuteUnmuteOnMediaSession(e,t){const i=this.logger.createFnLogger(`handleMuteUnmuteOnMediaSession, value=${!!e}`,t);if(this.mediaSession?.getAllowedModalities&&!this.isServerMuted){const n=this.isMuted||this.isServerMuted,r=this.mediaSession.getAllowedModalities().audio.some((e=>e===ug||e===gg));(n&&r||!n&&!r)&&(i.info(`updating audio modalities: Muted ${n} -> ${e}; audioAllowed = ${r}`),await this.updateMediaModalities(void 0,t))}return e?(i.info("mediaSession.muteInputAsync"),await(this.mediaSession?.muteInputAsync(t))):e||(i.info("mediaSession.unmuteInputAsync"),await(this.mediaSession?.unmuteInputAsync(t))),Promise.resolve()}canMuteOthers(){const e=this._enableUserMeetingRolesCheckForClientCapability&&this.meetingRoles?.some((e=>"attendee"===e))||"attendee"===(this.advancedMeetingRole||this.meetingRole),t=this._enableEndpointMeetingRoleCheckForClientCapability&&!!this.endpoints?.endpointDetails.find((e=>this._endpointId===e.endpointId))?.endpointMeetingRoles?.some((e=>"attendee"===e));return!e&&!t}updateCapabilities(e,t=!1){let i=!1,n=!1;fh(this.state,[11,12])||(this.isServerMuted&&!this._callInLobby?2&this._commandUrlPresence&&(i=!0):this.isMuted&&(i=!0),n=!!(1&this._commandUrlPresence)&&this.canMuteOthers()),this._capabilities.canUnmuteSelf===i&&this._capabilities.canMuteOthers===n||(this._capabilities.canUnmuteSelf=i,this._capabilities.canMuteOthers=n,this.logger.info(`[${e}][updateCapabilities] Computed self capabilities: ${JSON.stringify(this._capabilities)}`),t&&this.raiseChanged())}async evaluateEndpointStatesForAccept(e,t,i){const n=this.logger.createFnLogger(`evaluateEndpointStatesForAccept, isMuted=${!!e}`,i),r={};try{await this.handleMuteUnmuteOnMediaSession(e,i),Object.assign(r,{state:{isMuted:e}}),n.info("is updating endpointState for mute"),t&&(Object.assign(r,{endpointProperties:{additionalEndpointProperties:t}}),n.info("is updating endpointState for additionalEndpointProperties"))}catch(e){throw n.logFailure(e),ns(e)}return r}async handleEndpointStatesForAccept(e,t){const i=this.logger.createFnLogger("handleEndpointStatesForAccept",t);try{await this.signalingSession.updateEndpointState(e,t)}catch(e){throw i.logFailure(e),ns(e)}}async muteUnmute(e,t){const i=this.logger.createFnLogger(`muteUnmute, value=${!!e} isServerMuted=${this.isServerMuted} inLobby=${this._callInLobby}`,t);if(fh(this.state,[11,12]))return i.logFailure("Can not mute/unmute during preheat call"),Promise.reject(ns("TransactionDisallowed"));const n=!e&&(!this.isServerMuted||this._callInLobby);try{if((e||n)&&await this.handleMuteUnmuteOnMediaSession(e,t),e)this.setMuted(2,t),i.info("is updating endpointState for mute"),this.updateEndpointStateForMute(!0,t);else{if(!n)return i.info("is unmuting on server"),2===this._muteState&&this.setMuted(3,t),this.isCallModeStreaming()?this.promoteToRealtimeAndUnmute(t):this.signalingSession.unmuteAsync(t).then((e=>{this.handleSelfUnmuteUpdatedInfo(e,t)}));i.info("is updating endpointState for unmute"),this.setMuted(0,t),this.updateEndpointStateForMute(!1,t)}}catch(e){throw i.logFailure(e),ns(e)}}async muteUnmuteSpeaker(e,t){this.setSpeakerMuted(e,t),this.mediaSession&&(e?await this.mediaSession.muteOutputAsync(t):await this.mediaSession.unmuteOutputAsync(t))}getParticipant(e){return this.participants.filter((t=>t.isSameParticipantsMri(e)))[0]}getOrCreateParticipant(e,t,i){let n=this.getParticipant(e);return n||(n=new Ug(e,this.mediaSession,this.logger,this.callStats.localStats,this.callTelemetry,t),n.changed((()=>this.onParticipantChanged(n))),this.participants.push(n),i&&this.event("participantAdded").raise(n),this.monitorCallStart(),n)}onParticipantChanged(e){this.event("participantUpdated").raise(e),this.raiseChangedDeferred(this._participantChangedEventSkipConfig)}setCallState(e,t,i=0){if(this.state===e)return;const n=this.logger.createFnLogger("setCallState",t);n.info(`currentState=${this.state}, newState=${e}, terminatedReason=${this.terminatedReason}`),(Ch[this.state].indexOf(e)>=0||(n.logFailure("invalid state transition"),7===e))&&(this.callTelemetry.recordEvent("_SetCallState",{state:e,reason:i},t),this.state=e,this.callStats.localStats.call.callStateChanged(e),6===e&&this._startCallPhase&&(this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},t),this._startCallPhase=void 0),7===e&&this.setTerminatedReason(i),3===e&&(this.callGotConnected=!0,this.callHeldAt=null),this.callIsHeld()&&!this.callHeldAt&&(this.callHeldAt=new Date),n.logSuccess(`changed to ${e}, terminatedReason: ${this.terminatedReason}, failureType=${this.failureType}`),this.screenSharingControl.callStateChanged(this.state),this.monitorCallStart(),this.event("callStateChanged").raise(),this.updateCapabilities(t),this.raiseChanged(),this.callTelemetry.recordEvent("_RaiseCallStateChangeEvent",{state:e,reason:i},t))}setTerminatedReason(e){if(this.terminatedReason=e,!(0,Ws.includes)(kf,e)){const e=44===this.terminatedReason,t=55===this.terminatedReason,i=56===this.terminatedReason;this.setFailureType(!this.callGotConnected||!this._wasAudioStreamConnected||e||t||i?0:1)}}setMediaStream(e,t,i){if(e){if(!(0,Ws.find)(this.localMediaStreams,(e=>e.mediaType===i))){const e=new Nf(t,i);this.logger.info(`setMediaStream ${JSON.stringify(e)}`),this.localMediaStreams.push(e)}}else this.logger.info(`setMediaStream removing ${i}`),(0,Ws.remove)(this.localMediaStreams,(e=>e.mediaType===i))}setVideoOn(e,t){this.logger.info(`[${t}]videoOn=${e}`),this.isVideoOn=e,this.setMediaStream(this.isVideoOn,!0,1),this.callTelemetry.recordEvent("_SetLocalVideo",{value:e},t),this.raiseChanged()}setAudioOn(e,t){this.logger.info(`[${t}]audioOn=${e}`),this.setMediaStream(e,!0,0),this.callTelemetry.recordEvent("_SetLocalAudio",{value:e},t)}setScreenSharingOn(e,t){this.logger.info(`[${t}]screenSharingOn=${e}`),this.isScreenSharingOn=e,this.setMediaStream(this.isScreenSharingOn,this.isScreenSharingOn,2),this.callTelemetry.recordEvent("_SetScreenSharing",{screenSharingOn:e},t),this.event("userActivityChanged").raise(),this.raiseChanged()}disposeSharingScreenHandle(){this.sharedScreenHandle&&(this.sharedScreenHandle.dispose(),this.sharedScreenHandle=null)}disposeLocalVideoHandle(){this.localVideoHandle?.dispose(),this.localVideoHandle=null}setMuted(e,t){this._muteState!==e&&(this._muteState=e,this.callTelemetry.recordEvent("_SetMuted",{isMuted:e},t),this.logger.info(`[${t}]participantMuteState:${e}, isMuted: ${this.isMuted}`),this.updateCapabilities(t),this.raiseChanged(),this.event("muteStateChanged").raise(this.isMuted,t))}setSpeakerMuted(e,t){this.logger.info(`[${t}]speakerMute=${e}]`),this.isSpeakerMuted=e,this.raiseChanged()}monitorCallStart(){3!==this.state||!this.participants.length&&2!==this.callMode||this.callStartedAt||(this.callStartedAt=new Date)}_removeParticipant(e,t,i=0){const n=this.logger.createFnLogger("removeParticipant",t);n.info(`mri=${rg(e)}`);const r=(0,Ws.remove)(this.participants,(t=>t.isSameParticipantsMri(e.id)))[0];r?(r.setState(4,i,t),this.event("participantRemoved").raise(r)):n.logFailure(`unable to remove participant ${De(e.id)}`),this.raiseChanged(this._participantChangedEventSkipConfig)}setIsSomeoneSharing(e,t){const i=this.isSomeoneSharing!==e&&!(e&&this.screenSharingRenegotiationDeferred&&this.callUsesMixer);i&&(this.isSomeoneSharing=e);let n=i;if(this.callUsesMixer&&this.mediaSession?.getSessionConfig().config.enableStopSharingWithIncomingOffer&&(n||(n=t)),!this.isMultiVBSSEnabled()&&n&&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 e=this.localSignalingParticipant.endpointDetails.find((e=>this._endpointId===e.endpointId)),t=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,t,e)}}handleOfferedModalities(e,t){const i=this.mediaAgent.constants.MEDIA_STATE,n=this.logger.createFnLogger("handleOfferedModalities",t);try{n.info(`offeredModalities=${Ge(e)}`)}catch(e){n.logFailure(e)}e.hasOwnProperty("video")||this.mediaStateConfigurationHelper.isSending(1)?e.hasOwnProperty("video")&&!this.mediaStateConfigurationHelper.isSending(1)&&this.mediaStateConfigurationHelper.removeModality(1):this.mediaStateConfigurationHelper.disableModality(1),e.hasOwnProperty("sharing")||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.disableModality(2),e.sharing!==i.receive||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.removeModality(2),e.data===i.sendReceive&&this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.isReivitelessEnabled()||(this.setIsSomeoneSharing(e.sharing===i.receive,!0),this.setIsSomeoneStreamingVideo(e.video===i.receive||e.video===i.sendReceive))}getRenegotiationOfferType(e){if(e)if(5===this.state){if("sendrecv"===e.audio)return 2}else if(this.modalitiesAreHold(e))return 1;return 0}isRenegotiationHoldOrResume(e){return 1===this.getRenegotiationOfferType(e)||2===this.getRenegotiationOfferType(e)}isReivitelessEnabled(){return(this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()>0||this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb()>0)&&this.callUsesMixer}isValidHoldResumeCallState(e){return[3,5,10,13].includes(e)}onNegotiationCompletion(e,t,i={},n,r){const s=this.logger.createFnLogger("onNegotiationCompletion",n);s.info(`byLocal=${t}, result=${Ge(e)}`),this.callTelemetry.recordEvent("NegotiationCompletion",{phaseTelemetryBag:r,...this.prepareNegotiationResultForTelemtry(e)},n);const a=this.isOneToOneCall();if(a&&!this.callUsesMixer){const t=this.modalitiesAreHold(e.activeModalities)?5:3;this.participants[0].setState(t,void 0,n),s.info(`isOneToOneCall: participant[0] state set to ${t}`)}const o=this.modalitiesAreHold(e.configuredModalities),l=this.modalitiesAreHold(e.activeModalities);let c;const d=this.signalingSession.participantManager.localParticipant.isStaging;s.info(`isStaging= ${d}`),this.requestedHoldState?(o&&l||s.info(`Not expected modalities when processing local hold: ${o} ${l}`),4!==this.state&&s.info(`Not expected state when processing local hold: ${this.state}, switching back to LocalHold`)):t||this.callHoldResumeDeferred?!o&&l?c=5:o||l||this._callInLobby||this.isPreheatedOnly()||(c=d?13:3):4===this.state||this._callInLobby||this.isPreheatedOnly()||(c=a&&5===this.participants[0].state?5:d?13:3),c&&this.setCallState(c,n),this.callHoldResumeDeferred&&(s.info(`isHoldInProgress=${this.isHoldInProgress}, state=${this.state}, completed=${l}`),this.isHoldInProgress?l&&this.finishCallHoldResume():this.inLocalHold()||this.finishCallHoldResume(this.isValidHoldResumeCallState(c)?void 0:new Error(`Call state changed to ${c} instead of Connected, Lobby, Staging or RemoteHold`))),this.requestedHoldState||(this.setIsSomeoneSharing((0,Ws.some)(this.participants,(e=>(0,Ws.some)(e.streams[1],(e=>e.isAvailable))))),this.setIsSomeoneStreamingVideo((0,Ws.some)(this.participants,(e=>(0,Ws.some)(e.streams[0],(e=>e.isAvailable))))));const u=i&&i.sharing===this.mediaAgent.constants.MEDIA_STATE.send,h=e?.activeModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(this.resolveScreenSharingRenegotiation(n,u,h,e.isComplete),this.retryOutgoingRenegotiation.retry){const e=this.retryOutgoingRenegotiation.causeId;this._callOperationHandler.executeChained((()=>this.updateMediaModalities(void 0,e)),"_Renegotiate",e,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.retryOutgoingRenegotiation.retry=!1}}onUpdateMediaDescriptionsFailure(e,t,i){const n=t?.requestedModalities.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.screenSharingRenegotiationDeferred&&n&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}onUpdateMediaDescriptionsCompletion(e,t){this.logger.createFnLogger("onUpdateMediaDescriptionsCompletion",t).info(`result=${Ge(e)}`),this.callTelemetry.recordEvent("UpdateMediaDescriptionsCompletion",e,t);const i=e?.requestedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send,n=e?.appliedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.resolveScreenSharingRenegotiation(t,i,n,!0)}resolveScreenSharingRenegotiation(e,t,i,n){const r=this.logger.createFnLogger("resolveScreenShareRenegotiation",e);if(r.info(`invoked with wasSharingOfferred: ${t}, isSharingActive: ${i}, isComplete: ${n}`),this.screenSharingRenegotiationDeferred)if(t&&i)r.info("resolving screenSharingRenegotiationDeferred"),this.screenSharingRenegotiationDeferred.resolve(),this.screenSharingRenegotiationDeferred=null;else if(this._enableResolveScreenSharingWhenNegotiationComplete&&n&&!this.retryOutgoingRenegotiation.retry&&this.canToggleScreenSharing){const e=new Error(`screenSharing error: wasSharingOfferred: ${t}, isSharingActive: ${i}`);r.info(`reject screenSharingRenegotiationDeferred ${e}`),this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null}}async updateMediaStatus(e){if(this.calculateIsSomeoneStreaming(e),this.mediaSession){const t=await this.updateMediaModalities(void 0,e);this.callTelemetry.updateOperationData("_UpdateLocalMediaStatus",t,e)}}calculateIsSomeoneStreaming(e){let t=!1,i=!1;for(const e of this.participants)if(t||(t=(0,Ws.some)(e.streams[1],(e=>e.isAvailable))),i||(i=(0,Ws.some)(e.streams[0],(e=>e.isAvailable))),t&&i)break;this._delayedElevationPending&&(t||i)&&this.triggerDelayedReconnectIfNeeded(e,"roster update"),this.setIsSomeoneSharing(t),this.setIsSomeoneStreamingVideo(i)}async triggerDelayedReconnectIfNeeded(e,t=""){this.logger.info(`Delayed elevation (${t}): 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(e,!0,(()=>{this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.mediaSession?.getDiagnostics()?.registerElevation("completed")}))):this.logger.info(`Delayed elevation: was not queued, pending=${this._delayedElevationPending} isQueued=${this._delayedElevationQueued}`)}onNegotiationFailure(e,t,i,n){const r=n&&n.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(t===this.mediaAgent.constants.RENEGOTIATION_ERROR.glare)return this.screenSharingRenegotiationDeferred&&r&&this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),void(this.retryOutgoingRenegotiation={retry:!0,causeId:i});this.finishCallHoldResume(e),this.screenSharingRenegotiationDeferred&&r&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}static getParticipantReasonFromTerminatedReason(e){switch(e){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(e){if(!e.endpointDetails)return!1;for(const t of e.endpointDetails)if(!Fd(t))return!1;return!0}updateCallParticipantFromSignalingParticipant(t,i,n){if((0,Ws.every)(i.endpointDetails,(e=>e?.isLobby||e?.streamLobby)))return void t.setState(7,void 0,n);const r=(0,Ws.some)(i.endpointDetails,(e=>e?.streamInformation)),s=i.endpointDetails&&(0,Ws.some)(i.endpointDetails,(e=>e.mappedTo)),a=e.filterVirtualEndpoints(i.endpointDetails),o=a&&a[0].mediaStreams,l=this.isRemoteParticipantInStaging(i);if(o&&o.length>0){const e=o.every((e=>"inactive"===e.direction));let i=e?5:l?8:3;1!==this.state||e||this.callUsesMixer||(i=2),this.logger.info(`[updateCallParticipantFromSignalingParticipant]: with mediaStreams is not empty, ParticipantState is set to ${i}`),t.setState(i,void 0,n)}else if(o||s||r){const e=l?8:3;this.logger.info(`[updateCallParticipantFromSignalingParticipant]: ParticipantState is set to ${e}, mediaStreams=${!!o}, hasMappedEndpoints=${s}, hasPlayerStreams=${r}`),t.setState(e,void 0,n)}}handleSelfServerMutedState(t){const i=e.filterVirtualEndpoints(this.localSignalingParticipant.endpointDetails),n=(0,Ws.find)(i,(e=>this._endpointId===e.endpointId)),r=n&&n.mediaStreams,s=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),a=n&&(n.stream||n.streamLobby);if(a){const e=a.serverMuted??!1;n.serverMuteVersion=0,e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.isServerMuted&&this.setMuted(1,t))}else if(s&&s.length>0){const e=s.some((e=>e.serverMuted));e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.handleServerMutedState(t))}}checkIfIncomingServerMutedIsUpdated(e){const t=(0,Ws.find)(this.localSignalingParticipant.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===t)return;const i=(0,Ws.find)(e.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));eg(this.logger,t,i)}convertWiredPublishedState(e){if(!e)return;const t=uo(e.stateType);return{content:e.content,stateType:t,typeRank:e.typeRank,stateId:e.stateId}}updatePublishedStateModified(e,t){e!==this.currentUserSkypeIdentity.id||t&&t!==this.participantId?this._publishedStatesModified=2|this._publishedStatesModified:this._publishedStatesModified=1|this._publishedStatesModified}updatePublishedStates(e){try{let t=[];(0,Ws.forEach)(e.publishedStates,(e=>{t.push(this.convertWiredPublishedState(e))})),(0,Ws.isEqual)(this._participantPublishedStatesMap[e.id],t)||(0!==t.length||void 0!==this._participantPublishedStatesMap[e.id]&&null!==this._participantPublishedStatesMap[e.id])&&(this._participantPublishedStatesMap[e.id]=t,this.updatePublishedStateModified(e.id));const i=[];(0,Ws.forEach)(e.endpointDetails,(n=>{i.push(n.participantId),t=[],(0,Ws.forEach)(n.publishedStates,(i=>{const r=this.convertWiredPublishedState(i);if(this._endpointPublishedStatesMap[e.id]||(this._endpointPublishedStatesMap[e.id]={},this._endpointPublishedStatesMap[e.id][n.participantId]=[]),"clientMediaUfd"===r.stateType)try{const e=JSON.parse(JSON.stringify(r.content));this.mediaSession.registerRemoteQualityStateChangedEvent(e,n.participantId)}catch(e){this.logger.error(`Error while parsing state.content for ClientMediaUFD: ${e}`)}t.push(r)})),this._endpointPublishedStatesMap[e.id]&&!(0,Ws.isEqual)(this._endpointPublishedStatesMap[e.id][n.participantId],t)&&(0!==t.length||null!==this._endpointPublishedStatesMap[e.id][n.participantId]&&void 0!==this._endpointPublishedStatesMap[e.id][n.participantId])&&(this._endpointPublishedStatesMap[e.id][n.participantId]=t,this.updatePublishedStateModified(e.id,n.participantId))})),this._endpointPublishedStatesMap[e.id]&&Object.keys(this._endpointPublishedStatesMap[e.id]).forEach((t=>{i.some((e=>e===t))||(delete this._endpointPublishedStatesMap[e.id][t],this.updatePublishedStateModified(e.id,t))}))}catch(e){this.logger.error(`updatePublishedStates ${JSON.stringify(e)}`)}this.logger.info(`updatePublishedStates ${Ne(this._participantPublishedStatesMap)}`),this.logger.info(`updatePublishedStates ${Ne(this._endpointPublishedStatesMap)}`)}removePublishedStatesByParticipant(e){this._endpointPublishedStatesMap[e]&&delete this._endpointPublishedStatesMap[e],this._participantPublishedStatesMap[e]&&delete this._participantPublishedStatesMap[e],this.updatePublishedStateModified(e)}findOrCreateTypeState(e){let t=this._publishedStates.typeStates.findIndex((t=>t.type===e));if(-1===t){const i={participantStates:[],type:e};this._publishedStates.typeStates.push(i),t=this._publishedStates.typeStates.length-1}return t}processPublishedStates(){this.logger.info(`processPublishedStates ${Ne(this._participantPublishedStatesMap)}`),this.logger.info(`processPublishedStates ${Ne(this._endpointPublishedStatesMap)}`);try{this._publishedStates||(this._publishedStates={typeStates:[]}),this._publishedStates.typeStates=[];for(const e of Object.keys(this._participantPublishedStatesMap)){const t=this._participantPublishedStatesMap[e];(0,Ws.forEach)(t,(t=>{const i=this.findOrCreateTypeState(t.stateType),n={id:e,publishedState:{content:t.content,stateId:t.stateId,typeRank:t.typeRank}};this._publishedStates.typeStates[i].participantStates.push(n)}))}for(const e of Object.keys(this._endpointPublishedStatesMap))for(const t of Object.keys(this._endpointPublishedStatesMap[e]))this._endpointPublishedStatesMap[e][t].forEach((i=>{const n=this.findOrCreateTypeState(i.stateType),r={id:t,publishedState:{content:i.content,stateId:i.stateId,typeRank:i.typeRank}},s={id:e,endpoints:[r]},a=this._publishedStates.typeStates[n].participantStates.filter((t=>t.id===e));a&&a.length>0?(a[0].endpoints||(a[0].endpoints=[]),a[0].endpoints.push(r)):this._publishedStates.typeStates[n].participantStates.push(s)}));this.event("publishedStatesChanged").raise(this._publishedStates),this.raiseChanged()}catch(e){this.logger.error(`processPublishedStates ${e}}`)}}updateLocalParticipant(t,i){const n=this.logger.createFnLogger("updateLocalParticipant",i);this.checkIfIncomingServerMutedIsUpdated(t),this.localSignalingParticipant.endpointDetails=t.endpointDetails,this.localSignalingParticipant.role=t.role,this.setMeetingRole(t.meetingRole),this.setAdvancedMeetingRole(t.advancedMeetingRole),this.setMeetingRoles(t.meetingRoles),this.setParticipantType(t.participantType),this.setDisplayName(t.displayName),this.setPropertyBag(t.propertyBag),this.setPropertyRosterVersion(t.version),this.setMaskedIdentityDetails(t.isIdentityMasked,t.maskedIdSeqNumber,t.maskedId),this.setOtpIdentity(t.otpIdentity),this.localSignalingParticipant.tenantId=t.tenantId,this.localSignalingParticipant.isLobby=t.isLobby,t.joinAsStreamingUser&&(this.localSignalingParticipant.joinAsStreamingUser=t.joinAsStreamingUser,this.setJoinAsStreamingUser(t.joinAsStreamingUser)),void 0!==t.enableCaptcha&&this.setEnableCaptcha(t.enableCaptcha),this.callTelemetry.setTenantId(t.tenantId),this.callStats.setTenantId(t.tenantId);const r=this.localSignalingParticipant.isLobby;t.endpointDetails&&this.updateLocalParticipantEndpoints(t.endpointDetails),this.updatePublishedStates(t),this.handleSelfServerMutedState(i);const s=this.getLocalSignalingEndpointDetails();this._callInLobby=r||!!s?.streamLobby,this.signalingSession.participantManager.localParticipant.isStaging=t.isStaging;const a=this.signalingSession.participantManager.localParticipant.isStaging;n.info(`callInLobby = ${r}, callSetupComplete = ${this._callIsSetupComplete}, callIsHeld = ${this.callIsHeld()}, isStaging = ${a}`),!this._callIsSetupComplete||this.callIsHeld()||fh(this.state,[11,12])||(r?this.setCallState(10,i):a&&fh(this.state,[3,13,10,9,2])?this.setCallState(13,i):this.setCallState(3,i));const o=e.getStreamsFromEndpoints(t.endpointDetails,this.isMultiVBSSEnabled());if(this.callTelemetry.recordEvent("_UpdateLocalParticipantStream",function(e){let t=[];return e.forEach((e=>{try{let i=t.find((t=>t.participantId===e.participantId&&t.endpointId===e.endpointId));i||(i={participantId:e.participantId,endpointId:e.endpointId},t.push(i)),"audio"!==e.type&&"audioteleconference"!==e.type||(i.serverMuted=e.serverMuted),i[e.type]=e.direction}catch(e){t=[]}})),t}(o),i),this.streamManager.updateStreams(o,i),this.updateCapabilities(i,!0),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const e=t.endpointDetails.find((e=>this._endpointId===e.endpointId)),i=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,i,e)}}modalitiesAreHold(e){return!(e.audio&&"inactive"!==e.audio||e.video&&"inactive"!==e.video||e.sharing&&"inactive"!==e.sharing)}toneToString(e){switch(e){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(e){switch(e){case"started":return 0;case"active":return 2;case"inactive":return 1;case"stopped":return 3;default:return 4}}static streamingDirectionToMediaDirectionMapping(e){switch(e){case"send":return 1;case"receive":return 0;default:return}}static convertMuteScope(e){switch(e){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(e){const t={};return e.muteFlags&&(t.muteMicrophone=!!(1&e.muteFlags),t.muteSpeaker=!!(2&e.muteFlags)),Object.keys(t).length?t:void 0}reconnect(){const e=be();return this.mediaSession.reconnectAsync(e)}async provideCallQualityFeedback(e,t,i,n){}async showCQFInfo(e,t){throw new Error("Not implemented")}async isCqfRendered(e){}async provideCallQualityFeedbackEx(e,t,i,n,r,s){}testTriggerMediaRelayWhiteListingIssue(){this.logger.info("Simulating media relay whitelisting issue for test purposes");const e=this.mediaSession.mediaSession.callback;e.onQualityChanged({type:"NetworkRelaysNotReachable",value:"Bad",isLocalSource:!0,mediaType:"Audio"}),e.onAudioStateChanged({direction:"send",stream:"failed",content:"audio"})}async getMediaTelemetry(e=!1){return this.mediaSession&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(e)),this.appendInfoToCallStats()),this.callStats.buildMediaTelemetry()}getMediaSessionStats(){return this.mediaSession?.getMediaStatsReport()}async getMediaSessionStatsAsync(){return this.mediaSession?.getMediaStatsReport()}async getAudioSendStats(){return this.mediaSession?.getAudioSenderStats()}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(e){this.logger.info(`Overwriting call state for test purposes: ${this.state} -> ${e} `),this.state=e}testSetCallType(e){this.logger.info(`Overwriting call state for test purposes: ${this.callType} -> ${e} `),this.callType=e}addGroupModality(e,t=be()){const i=this.logger.createFnLogger("AddGroupModality",t);if(!e.threadId&&!e.groupId)return Promise.reject(ns("No threadId/groupId was provided."));if(6===this.state||7===this.state)return i.info(`Not adding modality because CallState is ${this.state} groupId=${De(e.groupId)}, threadId = ${xe(e.threadId)} messageId = ${e.messageId}`),Promise.reject(ns("TransactionDisallowed"));let n;if(e.additionalData)try{n=JSON.stringify(e.additionalData)}catch(t){i.logFailure(`additionalData: ${e.additionalData} is not valid Json, error: ${t}`);const n={code:ps,subCode:0,phrase:`additionalData is not valid Json, error: ${t}`};return Promise.reject(n)}if(i.info(`groupId=${De(e.groupId)}, threadId = ${xe(e.threadId)} messageId = ${e.messageId} additionalData = ${De(n)}`),this._enableAddModalityGeneric){const n={groupContext:{id:e.groupId},groupChat:{threadId:e.threadId,messageId:e.messageId}};return this.signalingSession.addModalityAsync(n,t).catch((e=>(i.logFailure(je(e)),Promise.reject(e))))}{const r={groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,additionalData:n};return this.signalingSession.addGroupModalityAsync(r,t).catch((e=>(i.logFailure(je(e)),Promise.reject(e))))}}addBroadcastModality(e,t){const i=this.logger.createFnLogger("AddBroadcastModality",t);return Promise.resolve().then((()=>{this.signalingSession.addBroadcastModalityAsync(e,t)})).catch((e=>(i.logFailure(je(e)),Promise.reject(ns(e))))).then((()=>this._callOperationHandler.waitForOperation("AddBroadcastModality"))).catch((e=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:$e(e)},t),i.logFailure(e),e}))}static convertQualityEventType(e){switch(e){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(e){switch(e){case"Unknown":return 0;case"Good":return 1;case"Poor":return 2;case"Bad":return 3;default:return}}static convertMediaType(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2;case"Data":return 3;default:return}}getPluginlessPublishLevel(e){switch(e){case"user":return"user";case"endpoint":return"endpoint";default:throw"Invalid level type."}}setIsEmergency(e){this.logger.info(`Set isEmergency:${e}`),this.isEmergency=e,this.callTelemetry.setIsEmergency(e)}static filterVirtualEndpoints(e){return e&&(0,Ws.filter)(e,(e=>!e.mappedTo))}mapDataChannelSourceIdToParticipant(e){let t=null;return t=1===this.callType?this.participants[0]:(0,Ws.find)(this.participants,(t=>t.hasSourceId(3,e))),t?.id?this.logger.info(`ParticipantId: ${De(t.id)} to SourceId: ${e}`):this.logger.warn(`No Participant found for SourceId: ${e}`),t}getDataChannelSourceId(){const e=(0,Ws.find)(this.endpoints.endpointDetails,(e=>null!==e&&e.participantId===this._participantId));if(!e)return this.logger.warn(`No participantLeg found for participantId: ${this._participantId}`),-1;if(!e.mediaStreams)return this.logger.warn(`ParticipantLeg ${this._participantId} does not have valid mediaStreams`),-1;const t=(0,Ws.find)(e.mediaStreams,(e=>3===Nd(e.type)));return t?t.sourceId:(this.logger.warn(`participantLeg ${this._participantId} has no data channel`),-1)}initializeLiveStreamConfigProvider(){const e="MDN_MIDDLELANE_TEAMS",t=this.ecsProvider.getEcsConfig(e,"liveStream"),i=this.ecsProvider.getEcsConfig("ConfigIDs",e);this._liveStreamConfigProvider=new Ut(t,null,i,this.logger.createChild("LiveStreamConfigProvider"))}isMediaSending(e){return this.mediaStateConfigurationHelper.isSending(e)}async setAudioStreamConnectedAsync(e){this.isAudioStreamConnected=e}async setSpamRiskLevelAsync(e){this.spamRiskLevel=e}async setSpamStirAttestationAsync(e){this.spamStirAttestation=e}async setDominantSpeakerInfoAsync(e){this.dominantSpeakerInfo=e}async setSlowedDownActiveTalkerInfoAsync(e){this.slowedDownActiveTalkerInfo=e}};Lf.instanceCount=0,Lf.getNegotiationTagsFromEndpoints=e=>{if(!e)return;const t=new Map;return Lf.filterVirtualEndpoints(e).forEach((e=>{t.set(e.endpointId,e.negotiationTag)})),t},m([Gr("SetMeetingLayout"),f(0,Wr)],Lf.prototype,"setMeetingLayout",1),m([Gr("Initialize",{type:"Sync",convertError:!0,idempotencyLevel:"NoOp"})],Lf.prototype,"init",1),m([Gr("StartVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startVideo",1),m([Gr("StopVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopVideo",1),m([Gr("DumpVideoSourceImages")],Lf.prototype,"dumpVideoSourceImages",1),m([f(1,Wr)],Lf.prototype,"hold",1),m([Gr("Hold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"holdWithRenegotiate",1),m([Gr("LocalHold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"localHold",1),m([Gr("Unhold",{waitFor:["Hold","LocalHold"],preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"unhold",1),m([Gr("UpdateEndpointMetadata"),f(1,Wr)],Lf.prototype,"updateEndpointMetadata",1),m([Gr("SendDtmfTone",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"sendDtmfTone",1),m([Gr("SetAudioUsage")],Lf.prototype,"setAudioUsageMode",1),m([Gr("SetAudioMidcallConfig")],Lf.prototype,"setAudioMidcallConfig",1),m([Gr("SetAudioMidcallConfigJon",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setAudioMidcallConfigJson",1),m([Gr("SetParticipantSpatialAudioPositions",{waitFor:"_ElectronSlimcoreReady",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setParticipantSpatialAudioPositions",1),m([Gr("BlindTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callBlindTransfer",1),m([Gr("SafeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callSafeTransfer",1),m([Gr("TransferToVoicemail",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"transferCallToVoicemail",1),m([Gr("ConsultativeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callConsultativeTransfer",1),m([Gr("ConsultativeTransferWithPickupCode",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"consultativeTransferWithPickupCode",1),m([Gr("CallRedirect",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"callRedirect",1),m([Gr("ParkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"park",1),m([Gr("UnparkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"unpark",1),m([Gr("getTechnicalInformationJson",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Lf.prototype,"getTechnicalInformationJson",1),m([Gr("StartScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(3,Wr)],Lf.prototype,"startScreenSharing",1),m([Gr("StopScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Wr)],Lf.prototype,"stopScreenSharing",1),m([Gr("StartDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startDataChannel",1),m([Gr("StopDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopDataChannel",1),m([Gr("ShareSystemSounds",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"shareSystemSound",1),m([Gr("Mute",{waitFor:"JoinPreheatedCall",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Yr),f(0,Wr)],Lf.prototype,"mute",1),m([Gr("Unmute",{waitFor:["JoinPreheatedCall"]}),f(0,Yr),f(0,Wr)],Lf.prototype,"unmute",1),m([Gr("MuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"muteSpeaker",1),m([Gr("UnmuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"unmuteSpeaker",1),m([Gr("GetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr)],Lf.prototype,"getSpeakerVolume",1),m([Gr("SetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"setSpeakerVolume",1),m([Gr("MuteParticipants",void 0),f(2,Yr),f(2,Wr)],Lf.prototype,"muteParticipants",1),m([Gr("StartAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"startAudio",1),m([Gr("StopAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"stopAudio",1),m([Gr("Assimilate"),f(3,Wr)],Lf.prototype,"assimilate",1),m([f(2,Wr)],Lf.prototype,"merge",1),m([Gr("MergeParticipants"),f(1,zr),f(3,Wr)],Lf.prototype,"mergeParticipants",1),m([Gr("MergeWithPickupCode"),f(0,zr),f(2,Wr)],Lf.prototype,"mergeWithPickupCode",1),m([Gr("SetMaxVideoChannels")],Lf.prototype,"setMaxVideoChannels",1),m([Gr("SetMaxVbssChannels")],Lf.prototype,"setMaxVbssChannels",1),m([Gr("StopCall"),f(1,Wr),f(3,Jr)],Lf.prototype,"stop",1),m([Gr("PublishState"),f(1,zr)],Lf.prototype,"publishState",1),m([Gr("PublishState"),f(1,zr)],Lf.prototype,"publishStatesForEveryone",1),m([Gr("RemoveState"),f(1,zr)],Lf.prototype,"removeState",1),m([Gr("RemoveState"),f(1,zr)],Lf.prototype,"removeStatesForEveryone",1),m([Gr("UpdateMeetingSettings"),f(1,zr)],Lf.prototype,"updateMeetingSettings",1),m([Gr("UpdateMeetingGroups"),f(0,zr)],Lf.prototype,"updateMeetingGroups",1),m([Gr("UpdateMeetingLiveState"),f(0,zr)],Lf.prototype,"updateMeetingLiveState",1),m([Gr("UpdateMeetingStates"),f(1,zr)],Lf.prototype,"updateMeetingStates",1),m([Gr("UpdateParticipantInterpretationState"),f(0,zr)],Lf.prototype,"updateParticipantInterpretationState",1),m([Gr("UpdateParticipantsProperties")],Lf.prototype,"updateParticipantsProperties",1),m([Gr("JoinMeetingGroup"),f(0,zr)],Lf.prototype,"joinMeetingGroup",1),m([Gr("LeaveMeetingGroup"),f(0,zr)],Lf.prototype,"leaveMeetingGroup",1),m([Gr("SendMessages"),f(0,zr)],Lf.prototype,"sendMessages",1),m([Gr("UpdateMonitorSession"),f(1,Wr)],Lf.prototype,"updateMonitorSession",1),m([Gr("SwitchInterpreterGroup")],Lf.prototype,"switchInterpreterGroup",1),m([Gr("SetLiveInterpretationAttributes")],Lf.prototype,"setLiveInterpretationAttributes",1),m([Gr("UpdateMeetingRole")],Lf.prototype,"updateMeetingRoles",1),m([Gr("CreateContentSharingSession"),f(4,Wr)],Lf.prototype,"createContentSharingSession",1),m([Gr("StopCallWithBeacon",{type:"Sync"}),f(0,Wr)],Lf.prototype,"stopWithBeacon",1),m([Gr("Acknowledge",{type:"Chained",convertError:!0,idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Wr)],Lf.prototype,"acknowledge",1),m([Gr("Accept",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(1,Wr)],Lf.prototype,"accept",1),m([Gr("Reject",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(0,Wr),f(1,Jr)],Lf.prototype,"reject",1),m([Gr("JoinCall",{type:"Chained",idempotencyLevel:"Error"}),f(1,Kr),f(2,Wr)],Lf.prototype,"join",1),m([Gr("JoinPreheatedCall",{waitFor:"_CallStartOrJoinInitiated"})],Lf.prototype,"joinPreheatedCall",1),m([Gr("StartCall",{type:"Chained",idempotencyLevel:"Error"}),f(0,Kr),f(1,Wr)],Lf.prototype,"start",1),m([Gr("StartCallToVoiceMail",{type:"Chained",idempotencyLevel:"Error"}),f(1,Wr)],Lf.prototype,"startCallToVoicemail",1),m([Gr("Subscribe",{type:"Chained",idempotencyLevel:"Error"}),f(2,Wr)],Lf.prototype,"joinCallWithoutCallModality",1),m([Gr("StartWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"startWithMeetingData",1),m([Gr("JoinWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"joinWithMeetingData",1),m([Gr("SubscribeWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Lf.prototype,"subscribeWithMeetingData",1),m([Gr("StartCallWithNudge",{type:"Chained",idempotencyLevel:"Error"}),f(1,Kr),f(2,Wr)],Lf.prototype,"startCallWithNudge",1),m([Gr("StartCallAndUnpark",{type:"Chained",idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),f(2,Kr),f(3,Wr)],Lf.prototype,"startAndUnpark",1),m([qr("AdmitParticipant"),f(0,zr),f(1,Wr)],Lf.prototype,"admitParticipant",1),m([Gr("Admit")],Lf.prototype,"admit",1),m([qr("CallMeBack"),f(0,zr),f(2,Wr)],Lf.prototype,"callMeBack",1),m([f(0,zr),f(2,Wr)],Lf.prototype,"addParticipant",1),m([qr("AddParticipants"),f(0,zr),f(2,Wr)],Lf.prototype,"addParticipants",1),m([f(0,zr),f(2,Wr)],Lf.prototype,"addParticipantsImpl",1),m([qr("NudgeParticipants"),f(0,zr),f(3,Wr)],Lf.prototype,"nudgeParticipants",1),m([qr("RemoveParticipant"),f(0,zr),f(1,Wr)],Lf.prototype,"removeParticipant",1),m([qr("CancelNudge"),f(0,zr),f(0,Wr)],Lf.prototype,"cancelNudge",1),m([Gr("SearchParticipants"),f(1,zr),f(1,Wr)],Lf.prototype,"searchParticipants",1),m([Gr("GetAllParticipants"),f(1,zr),f(1,Wr)],Lf.prototype,"getAllParticipants",1),m([Gr("_PromotionToRealtime"),f(1,Wr)],Lf.prototype,"promoteToRealtime",1),m([f(0,Wr)],Lf.prototype,"turnOffLocalVideoPreview",1),m([Gr("_StartPreviewVideo"),f(0,Wr)],Lf.prototype,"turnOnLocalVideoPreview",1),m([f(0,Wr)],Lf.prototype,"acquireLocalVideo",1),m([f(0,Wr)],Lf.prototype,"turnOnLocalVideoPreviewUsingRenderer",1),m([Gr("_UpdateLocalMediaStatus",{type:"Chained"}),f(0,Wr)],Lf.prototype,"updateMediaStatus",1),m([f(0,Wr)],Lf.prototype,"calculateIsSomeoneStreaming",1),m([Gr("_Reconnect")],Lf.prototype,"reconnect",1),m([Gr("AddGroupModality"),f(1,Wr)],Lf.prototype,"addGroupModality",1),m([Gr("AddBroadcastModality")],Lf.prototype,"addBroadcastModality",1);var xf=Lf,Ff=p(ce()),Uf=new RegExp("/callAgent/","i"),Bf=class{constructor(e,t){this.signalingAgentProvider=e,this.callRegistry=t}handleMessage(e){if(!e.eventId){if(e.url.search(Uf)>-1){const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}if(e.eventId in Hs){this.callRegistry.logUploadNotification(e);const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}},Vf=class{constructor(e,t,i){this.callRegistry=e,this.recentInvitations=[],this.logger=t.createChild("IncomingCallMessageHandler"),this.ecsProvider=i}handleMessage(e){const t=this.handleIncomingCall(e);return t?{isHandled:t,resultCode:200}:{isHandled:t}}handleIncomingCall(e){const t=be(),i=this.logger.createFnLogger("handleIncomingCall",t);if(this.isProxiableNotification(e))return this.callRegistry.proxyPushNotification(e),!0;if(!this.isIncomingCallMessage(e))return!1;let n;this.callRegistry.pushHandlingStarted(t);try{if(e?.body?.gp&&!Xe(e.body.gp))i.info("unencoded payload, skipping decoding."),n=e.body.gp;else{const t=$f(e,i);n=JSON.parse(t)}n.body=e.body}catch(e){return this.callRegistry.pushHandlingEnded(t,{result:"Failed to parse incoming call notification payload",code:ps,subCode:3080,participantId:"",callId:"",resultCategories:["UnexpectedServerError"]}),i.logFailure(`Error parsing notification payload: ${e}`),!1}const r=this.isCallTransferNotification(e)?this.buildTransferCallPayload(n):this.buildNGCCallPayload(n);if(!r)return this.callRegistry.pushHandlingEnded(t,{result:"Failed to get incoming call notification payload",code:ps,subCode:3081,participantId:"",callId:"",resultCategories:["UnexpectedClientError"]}),!1;if(this.callRegistry.calls.some((e=>e.callId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the call registry, callId = ${r.convoCallId}, participantId = ${r.participantId}`),this.callRegistry.pushHandlingEnded(t,{result:"Failed due to duplicate call filtered because it was in the call registry",code:ks,subCode:3082,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["ExpectedError"]}),!1;const s=this.isCallReplacementNotification(e);if(i.log(`replacementCall=${s}`),!s&&this.recentInvitations.some((e=>e.convoCallId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the recent calls list, callId = ${r.convoCallId}, participantId = ${r.participantId}`),this.callRegistry.pushHandlingEnded(t,{result:"Failed due to duplicate call filtered because it was in the recent calls list",code:ks,subCode:3083,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["ExpectedError"]}),!1;5===this.recentInvitations.length&&this.recentInvitations.shift(),this.recentInvitations.push({convoCallId:r.convoCallId,participantId:r.participantId});let a=this.callRegistry.calls.find((e=>e.callId===r.convoCallId&&8===e.state));if(!a)if(r.groupId)try{a=this.callRegistry.createCallWithGroupId(r.groupId,r.convoCallId,r.participantId,t)}catch(e){this.callRegistry.pushHandlingEnded(t,{result:"Failed to create incoming call notification with groupId",code:ps,subCode:3084,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["UnexpectedClientError"]})}else try{a=this.callRegistry.createCall(r.conversationId,r.convoCallId,r.participantId,void 0,t)}catch(e){this.callRegistry.pushHandlingEnded(t,{result:"Failed to create incoming call notification",code:ps,subCode:3084,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["UnexpectedClientError"]})}a.init({threadId:r.conversationId,messageId:r.messageId,mediaPeerType:2});const o=()=>{this.callRegistry.pushHandlingEnded(t,{code:wa.HTTP_STATUS_CODES.OK,subCode:0,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:["Success"]})},l=e=>{const i=a.callEndDiagnosticsInfo,n=i?i.callControllerSubCode:3085+e.code;this.callRegistry.pushHandlingEnded(t,{result:"Failed to acknowledge incoming call notification",code:i?.callControllerCode||ks,subCode:n,participantId:r?.participantId,callId:r?.convoCallId,resultCategories:i?.resultCategories||["UnexpectedClientError"]})};return this.callRegistry.testEndpointMetadata?a.acknowledge(r,this.callRegistry.testEndpointMetadata,t).then(o).catch(l):a.acknowledge(r,void 0,t).then(o).catch(l),!0}isIncomingCallMessage(e){return Object.keys(Bs).some((t=>Bs[t]===e.eventId))?e.eventId!==Bs.INCOMING_TFL_TFW_CALL||this.ecsProvider?.getEcsConfig("SkypeCalling","enableTFWTFLOneToOneCall"):this.isCallTransferNotification(e)}isCallTransferNotification(e){return e.callNotification&&("transfer"===e.callNotification.callType||"replaces"===e.callNotification.callType)}isCallReplacementNotification(e){return e.callNotification&&"replaces"===e.callNotification.callType}isProxiableNotification(e){return Object.keys(Vs).some((t=>Vs[t]===e.eventId))}buildTransferCallPayload(e){const t={body:e.body,callerId:e.callNotification.from.id,displayNameSource:po(e.callNotification.from.displayNameSource),groupId:null,conversationId:null,convoCallId:e.debugContent.callId,isMultiParty:e.conversationInvitation?.isMultiParty,fromMixer:e.callNotification.fromMixer,ngcCall:!0,participantId:e.callNotification.to.participantId,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,consultativeCallId:e.callNotification.consultativeCallId,messageId:null,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,calleeAlternateId:e.callNotification.to?.calleeAlternateId};return this.logger.info("Incoming transfer paylod",We(t,["callerId","transferorId"])),t}buildNGCCallPayload(e){if(!e.callNotification)return this.logger.error("Missing callNotification in parsed incoming NGC call payload"),null;const t={groupId:e.groupContext?.id,conversationId:e.groupChat?.threadId,messageId:e.groupChat?.messageId,callerId:e.callNotification.from.id,displayNameSource:po(e.callNotification.from.displayNameSource),isMultiParty:e.conversationInvitation.isMultiParty,fromMixer:e.callNotification.fromMixer,convoCallId:e.debugContent.callId,participantId:e.debugContent.participantId,ngcCall:!0,body:e.body,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,fromApplicationType:e.callNotification.fromApplicationType,calleeAlternateId:e.callNotification.to?.calleeAlternateId,routingTimeout:e.callNotification.routingTimeout};return this.logger.info("Incoming NGC paylod",We(t,["callerId","transferorId"])),t}},Hf=class extends gt{constructor(e,t,i,n,r,s=null,a,o,l){super(),this.trouterService=e,this.signalingAgentProvider=t,this.mediaAgent=i,this.callingLogger=n,this.telemetryLoggers=r,this.ecsProvider=s,this.skypeIdentity=a,this.oneDsTelemetryLoggers=o,this.vdi3diagnostics=l,this.calls=[],this.isDisposing=!1,this._disposedPromise=new Kt,this.testEndpointMetadata=null,this._disconnectingPromiseDefers=new Map,this.skypeIdentity&&(this.identity=this.skypeIdentity.id),this.callSubscriptionsMap=new Map,this.logger=new ct(this.callingLogger).createChild(`CallRegistry/${be()}`),this.registryTelemetry=new Cr(this.logger,(new Date).getTime()),this._callOperationHandler||(this._callOperationHandler=new as(this.logger,this.registryTelemetry,{},(e=>{this._publishTelemetry(e)})));const c=this.mediaAgent.getConfig().disconnectOnPageHide;this._windowUninitEvent=c?"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(e,t,i=be()){return this.logger.createFnLogger("init",i).info("init"),this.login(e)}uninit(){return this.logout()}login(e,t=be()){return this.logger.createFnLogger("login",t).info("login"),this.skypeIdentity=e,this.identity=this.skypeIdentity.id,this.initialize(t)}initialize(e=be(),t){const i=this.logger.createFnLogger("initialize",e),n=t&&t.applicationType?t.applicationType:"null";i.info(`initialize with applicationType: ${n}`),this.accountConfiguration=t,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(t),this.incomingCallMessageHandler=new Vf(this,this.logger,this.ecsProvider),this.trouterService.registerMessageHandler(new Bf(this.signalingAgentProvider,this)),this.trouterService.registerMessageHandler(this.incomingCallMessageHandler),i.info("Call registry init, endpointMetadata",this.testEndpointMetadata);try{this.windowUninitListener=()=>{this._disregardWindowUninitEvents||this.stopCallsWithBeacon()},window.addEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){i.logFailure(`Not adding beforeunload listener: ${e}`)}return Promise.resolve(void 0)}logout(e=be()){const t=this.logger.createFnLogger("logout",e);t.info("logout");try{this.trouterService.clearMessageHandlers(),window.removeEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){t.info(`Not removing beforeunload listener: ${e}`)}return Promise.resolve(void 0)}_publishTelemetry(e){if(!this.telemetryLoggers?.signaling)return;this.registryTelemetry.setSkypeId(this.identity);try{const e=this.signalingAgentProvider.getSignalingAgent();this.registryTelemetry.setEndpointId(e.endpointId)}catch(e){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));this.telemetryLoggers.signaling.sendEvent({eventName:"skypecosi_concore_web_ts_calling_registry",props:this.registryTelemetry.getEvent(null,e)})}async dispose(e=be()){const t=this.logger.createFnLogger("dispose",e);if(t.info("dispose"),this.isDisposing)return t.warn("call registry is already in disposing stage!"),this._disposedPromise.promise;this.isDisposing=!0;const i=()=>{this.calls=[],this.event("disposed").raise(),super.dispose(),this._disposedPromise.resolve()},n=this.calls.map((e=>e.stop())),r=()=>this.logout();return this.clearCallSubscription(),this.signalingAgentProvider.getSignalingAgent().resetAuthTokenManager(),Promise.all(n).then(r,r).then(i,i),this._disposedPromise.promise}get disposePromise(){return this._disposedPromise.promise}createCallAsync(e){const t=this.logger.createFnLogger("createCallAsync",e.causeId),i=`callId:${e.callId}, localParticipantId: ${De(e.localParticipantId)},\n causeId:${e.causeId}, type:${e.type}, `;switch(e.type){case"MeetingData":i.concat(`meetingUrl:${!!e.meetingData?.meetingUrl}, meetingCode:${!!e.meetingData?.meetingCode}`);break;case"GroupId":i.concat(`groupId:${De(e.groupId)}`);break;case"ThreadId":i.concat(`threadId:${xe(e.threadId)}, messageId:${e.messageId}`);break;default:throw new Error("Invalid type in passing parameter.")}t.info(i);const n=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers,r=this._getCurrentCall(e,t);if(r){if(6===r.state){const e=new Kt;return this._disconnectingPromiseDefers.set(r.callId,e),e.promise}return Promise.resolve(r)}return Promise.resolve(this._createNewCall(e,n,t))}createCallWithMeetingData(e,t,i,n){const r=this.logger.createFnLogger("createCallWithMeetingData",n);if(r.info(`meetingData:${!!e}, callId:${t}, localParticipantId: ${De(i)}`),!e)return r.info("meetingData cannot be null"),null;const s=this._generateCreateCallOptions(n,t,i,null,null,null,e),a=this._getCurrentCall(s,r);if(a)return a;const o=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(s,o,r)}createCall(e,t,i,n,r=be()){return this._createCall(e,t,i,n,r)}createCallWithGroupId(e,t,i,n){return this._createCall("",t,i,void 0,n,e)}_createNewCall(e,t,i){let n=null,r=null,s=null,a=null;switch(e.type){case"MeetingData":a=e.meetingData;break;case"GroupId":n=e.groupId;break;case"ThreadId":r=e.threadId,s=e.messageId}const o=new xf(this.signalingAgentProvider.getSignalingAgent(),this.mediaAgent,new ct(this.callingLogger),t,this.skypeIdentity,n,r,e.callId,e.localParticipantId,this.ecsProvider,this.trouterService,this.accountConfiguration,s,this.locationInfoContent,this.networkInfoContent,a,this.areaContent,this.vdi3diagnostics);o.on("callStateChanged",(async()=>{if(7===o.state&&this._createNewCallInDisconnectedState){const n=this._disconnectingPromiseDefers.get(o.callId);n&&(this._disconnectingPromiseDefers.delete(o.callId),n.resolve(this._createNewCall(e,t,i))),this._invokeDeleteCallInDisconnectedState&&setTimeout((()=>{this.deleteCall(o)}),0)}})),this.calls.push(o),this.event("callAdded").raise(o),this.raiseChanged(),i.info(`Created new call with id ${o.callId}`);const l=o.on("replacementRequested",(e=>{this.incomingCallMessageHandler.handleMessage(e)}));return this.addCallSubscriptionToMap(o,l),o}_getCurrentCall(e,t){let i=null;return"MeetingData"===e.type&&(i=this.getCallUsingMeetingData(e.meetingData,e.callId,e.localParticipantId,void 0,void 0,e.causeId),i)?(t.info("Call Registry has an entry for this call's meeting data"),i):(i=this.getCall(e.callId,e.localParticipantId,e.causeId),i?(t.info("Call Registry has an entry for this callId, participantId"),i):"ThreadId"===e.type&&(i=this.getCallUsingThreadIdMessageId(e.threadId,e.callId,e.messageId,e.causeId),i)?(t.info("Call Registry has an entry for this threadId, messageId"),i):"GroupId"===e.type&&(i=this.calls.find((t=>t.groupId===e.groupId)),i)?(t.info("Call Registry has an entry for this groupId"),i):i)}_generateCreateCallOptions(e,t,i,n,r,s,a){let o=null;return o=n?{type:"GroupId",callId:t,localParticipantId:i,causeId:e,groupId:n}:r?{type:"ThreadId",callId:t,localParticipantId:i,causeId:e,threadId:r,messageId:s}:{type:"MeetingData",callId:t,localParticipantId:i,causeId:e,meetingData:a},o}_createCall(e,t,i,n,r=be(),s){const a=this.logger.createFnLogger("createCall",r);a.info(`threadId:${xe(e)}, callId:${t}, localParticipantId: ${De(i)}, messageId:${n}, groupId:${De(s)}`);const o=this._generateCreateCallOptions(r,t,i,s,e,n,null),l=this._getCurrentCall(o,a);if(l)return l;const c=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(o,c,a)}getCall(e,t,i=be()){const n=this.logger.createFnLogger(`getCall[callId=${e}][participantId=${De(t)}]`,i);if(!e)return n.logFailure("callId is undefined"),null;const r=this.calls.find((t=>t.callId===e));return r&&n.info("Call Registry already has an entry for this call"),r}async deleteCallAsync(e){return Wt((()=>this.deleteCall(e)))}deleteCall(e){const t=this.calls.indexOf(e);return-1!==t&&(this.callSubscriptionsMap.get(e).forEach((e=>{e.dispose()})),this.callSubscriptionsMap.delete(e),this.calls.splice(t,1),this.event("callRemoved").raise(e),this.raiseChanged(),!0)}async setConfiguration(e){this.accountConfiguration=e,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(e)}updateDisplayName(e){return this.skypeIdentity.displayName=e,this.calls.forEach((t=>{t.updateDisplayName(e)})),Promise.resolve()}fireIntent(e,t){return Promise.resolve()}getCallState(e,t){return Promise.reject("Not implemented")}getSetup(){}getEcsConfig(){return Promise.reject()}updateSkypeToken(e){this.logger.debug("CallRegistry.updateSkypeToken() called but not supported in the current set up.")}updateToken(e,t,i,n,r){this.logger.info(`[updateToken], causeId = ${n} tokenType = ${t.tokenType}, factorsJson = ${e}, tokenExpiredTime = ${r}`);try{return this.signalingAgentProvider.getSignalingAgent().updateToken(e,t,i,n,r),Promise.resolve({code:0})}catch(t){return this.logger.info(`Failed to update token with ${e}, error is ${t}`),Promise.reject(ns(`Failed to update token with ${e}, error is ${t}`))}}onTokenRequired(e){const{requestMetadataJson:t,factorsJson:i,tokenType:n,invalidToken:r}=e;this.logger.info(`[onTokenRequired], tokenType ${n}, factorsJson ${i}, requestMetadataJson ${JSON.stringify(t)}`),this.event("tokenRequired").raise(i,n,t,r)}pushHandlingStarted(e){this.logger.info(`handleIncomingCallStarted, causeId=${e}`),this.event("pushHandlingStarted").raise(e)}pushHandlingEnded(e,t){this.logger.info(`pushHandlingEnded, causeId=${e}`),this.event("pushHandlingEnded").raise(e,t)}debugInformation(e){const t=e?`CallInformation\n * CallId=${e.callId}`:void 0;return Promise.resolve(t)}setLocationInfo(e,t,i=be()){if(this.logger.info(`setLocationInfo, ${i}, infoType:${e}, contentJson ${t?"is set":"is undefined"}`),t)try{JSON.parse(t)}catch(e){return Promise.reject(`invalid contentJson: ${e}`)}return this.locationInfoType=e,1===this.locationInfoType&&(this.locationInfoContent=t,this.logger.info(`locationInfoContent set to ${this.locationInfoContent}`)),2===this.locationInfoType&&(this.networkInfoContent=t,this.logger.info(`networkInfoContent set to ${this.networkInfoContent}`)),3===this.locationInfoType&&(this.areaContent=t,this.logger.info(`areaContent set to ${this.areaContent}`)),this.event("locationInfoSet").raise(e,t),Promise.resolve()}createDownloader(){return null}async getUnassembledLocalRecordingSessions(e=be()){return Promise.reject("Not implemented")}submitBrbReport(e,t){return Promise.reject("Not implemented")}extendBrbFeedback(e,t){return Promise.reject("Not implemented")}proxyPushNotification(e){this.logger.info(`Proxying push notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:$f(e,this.logger)};this.event("proxiedPushNotification").raise(t)}catch(e){this.logger.error(`Error proxying push notification: ${e}`)}}logUploadNotification(e){this.logger.info(`Log upload notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:$f(e,this.logger)};this.event("logUploadNotification").raise(t)}catch(e){this.logger.error(`Error raising log upload notification: ${e}`)}}sendPush(e,t,i,n){const r={id:e},s=[];return t.forEach((e=>{s.push({id:e})})),this.signalingAgentProvider.getSignalingAgent().sendPushAsync(r,s,i,n)}enableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!1}disableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!0}async enableWindowUninitEventHandlerAsync(){this.enableWindowUninitEventHandler()}async disableWindowUninitEventHandlerAsync(){this.disableWindowUninitEventHandler()}getCallUsingThreadIdMessageId(e,t,i,n){this.logger.info(`[getCallUsingThreadIdMessageId][${n}] threadID: ${xe(e)} callId: ${t} messageId: ${i}`);let r=null;return e&&(r=this.calls.find((n=>n.threadId===e&&(t&&n.callId===t||null!=i&&n.messageId===i))),r)?(this.logger.logFailure(`[getCallUsingThreadIdMessageId][${n}]Call Registry already has an entry for threadId: ${xe(r.threadId)}, callId: ${r.callId}, messageId: ${r.messageId}`),r):r}getCallUsingMeetingData(e,t,i,n,r,s=be()){const a=this.logger.createFnLogger("getCallUsingMeetingData",s);if(a.info(`[callId=${t}][participantId=${De(i)}] meetingData: ${!!e} \n threadId: ${xe(n)} messageId: ${r}`),!t)return a.logFailure("callId is undefined"),null;let o;for(const i of this.calls){if(i.callId===t){o=i;break}if(Ir(i.meetingData,e,s,this.logger)){o=i;break}}return o}stopCallsWithBeacon(){for(const e of this.calls)e.stopWithBeacon()}addCallSubscriptionToMap(e,t){this.callSubscriptionsMap.set(e,(this.callSubscriptionsMap.get(e)||[]).concat(t))}clearCallSubscription(){this.callSubscriptionsMap.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.callSubscriptionsMap.clear()}};function $f(e,t){const i=t.createFnLogger("decodeNotificationPayload");let n="{}";if(e?.body?.gp)i.info("using notification.body.gp"),n=function(e){const t=new TextDecoder("utf-8"),i=atob(e),n=Uint8Array.from(i,(e=>e.charCodeAt(0)));return t.decode(n)}(e.body.gp);else if(e?.body?.cp){i.info("using notification.body.cp");const t=atob(e.body.cp);n=Ff.inflate(t,{to:"string"})}return n}m([Gr("Initialize",{enableInstantTelemetry:!0})],Hf.prototype,"initialize",1),m([Gr("Logout",{enableInstantTelemetry:!0})],Hf.prototype,"logout",1);var jf=Z,Gf=class{constructor(e){this.deviceManager=e}get childDeviceManagers(){return this.deviceManager.getRegisteredDevices()}createPreview(e,t){return this.executeOnVirtualDeviceManager((t=>e(t,"Video")),t)}getRawDeviceMediaStream(e,t,i){return this.executeOnVirtualDeviceManager((i=>i.getRawDeviceMediaStream(e,t)),i)}setDeviceEffectsAsync(e,t){return this.executeOnVirtualDeviceManager((e=>e.setVideoEffects(t)),e)}setRawMediaStream(e,t,i){this.executeOnVirtualDeviceManager((i=>i.setRawMediaStream(e,t)),i)}unsetRawMediaStream(e,t){this.executeOnVirtualDeviceManager((t=>t.unsetRawMediaStream(e)),t)}getVirtualDevice(e){return this.childDeviceManagers.find((t=>t.id===e))}executeOnVirtualDeviceManager(e,t){return this.getVirtualDevice(t).getDeviceManagers().map((t=>e(t)))}},qf=class e extends gt{constructor(e){super(),this._deviceManager=e,this.virtualDeviceAdapter=new Gf(this._deviceManager),e.on("onDevicesChanged",(e=>{const t=this._deviceManager.getDeviceDescriptions(e),i=this._mapDevices(t);this._raiseDevicesChanged(i)})),e.on("onSelectedDevicesChanged",(e=>this._raiseDevicesChanged())),e.on("onPermissionStateChanged",(()=>this.event("onPermissionStateChanged").raise())),e.on("onVideoEffectsEvent",((e,t)=>this.event("videoEffectsEvent").raise(e,t))),e.on("onVideoEffectApplied",(()=>this.event("videoEffectApplied").raise())),e.on("onEffectsError",((e,t,i)=>this.event("onEffectsError").raise(Yh(e),t,i)))}get isAudioOutputSelectionSupported(){return this._deviceManager.isAudioOutputSelectionSupported}getPermissionState(e){return"camera"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("camera")):"microphone"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("microphone")):"unknown"}async getPermissionStateAsync(e){return this.getPermissionState(e)}askDevicePermission(e){return this._deviceManager.askDevicePermission?this._deviceManager.askDevicePermission(e):Promise.resolve({audio:!0,video:!0})}enumerateDevicesAsync(){return this._deviceManager.enumerateDevicesAsync().then((e=>this._mapDevices(e)))}getPreferredCamera(){throw new Error("Not implemented")}selectDevices(e){if(Object.keys(e).some((e=>this.isVirtualDevice(e))))throw new Error("Virtual Device selection on DM is not supported");const t=(0,jf.assign)({},this._deviceManager.getSelectedDevices(),e);this._deviceManager.selectDevices(t)}selectDevicesAsync(e){return Wt((()=>this.selectDevices(e)))}getSelectedDevices(){return this._deviceManager.getSelectedDevices()}getSelectedDevicesAsync(){return Wt((()=>this.getSelectedDevices()))}getDeviceNameAsync(e){return this._deviceManager.getDeviceNameAsync(e)}getSpeakerDeviceDomIdAsync(e,t){return this._deviceManager.getSpeakerDeviceDomIdAsync(e)}mapBrowserDevices(e,t){return Promise.reject(new Error("Not implemented"))}async setDeviceEffectsAsync(e,t){if(!this.isVirtualDevice(e))return this._deviceManager.setVideoEffects(t);Promise.all(this.virtualDeviceAdapter.setDeviceEffectsAsync(e,t))}getDeviceEffectsCapabilityAsync(e,t){return this._deviceManager.effectsManager.getEffectsCapability("Video")}setBackgroundImageAsync(e,t,i){return this._deviceManager.effectsManager.configure("Video",{imagePath:t,headers:i})}getImagePropertyAsync(e){return Promise.reject(new Error("Not implemented"))}getMicrophoneGeometryArrayInfoAsync(e){return Promise.reject(new Error("Not implemented"))}transformImageAsync(e,t,i,n){return Promise.reject(new Error("Not implemented"))}setAudioProcessingFlags(e){return this._deviceManager.setAudioProcessingFlags(e)}async sendMessageDeviceVideoEffectsAsync(e,t){return await this._deviceManager.sendMessageDeviceVideoEffectsAsync(e,t)}sendMessageDeviceVideoExtensibilityAsync(e,t){return Promise.reject(new Error("Not implemented"))}setVideoCaptureConfigAsync(e,t){return Promise.reject(new Error("Not implemented"))}captureVideoFrameWithoutEffectsAsync(e,t,i){return Promise.reject(new Error("Not implemented"))}enableSignLanguageDetectionAsync(e,t){return Promise.reject(new Error("Not implemented"))}downloadAiModel(e,t){return Promise.reject(new Error("Not implemented"))}getSpeakerVolume(){return Promise.reject(new Error("Not implemented"))}getSpeakerSystemVolume(){return Promise.reject(new Error("Not implemented"))}setSpeakerVolume(e){return Promise.reject(new Error("Not implemented"))}setSpeakerSystemVolume(e){return Promise.reject(new Error("Not implemented"))}unmuteMicrophone(){return Promise.reject(new Error("Not implemented"))}unmuteSpeaker(){return Promise.reject(new Error("Not implemented"))}getNrgLevelsForDeviceTuner(e){return Promise.reject(new Error("Not implemented"))}async getNrgLevelPollerForDeviceTuner(e){return await this._deviceManager.getNrgLevelPollerForDeviceTuner()}setAudioEffectsAsync(e,t){return this._deviceManager.setAudioEffects(t)}getAudioFeatureCapability(e){return this._deviceManager.effectsManager.getEffectsCapability("Audio")}getAudioFeatureProviderName(){return Promise.resolve(this._deviceManager.effectsManager.getAudioEffectsProviderName())}getMicrophoneVolume(){return Promise.reject(new Error("Not implemented"))}setMicrophoneVolume(e){return Promise.reject(new Error("Not implemented"))}setDeviceTelemetryData(e,t,i,n=0){return Promise.reject(new Error("Not implemented"))}getSourceFormats(e){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(e,t){return Promise.reject(new Error("Not implemeted"))}unregisterDerivedSource(e){return Promise.reject(new Error("Not implemeted"))}startPreview(e,t,i){const n=new _g,r=(async()=>{if("camera"===t.kind&&this.isVirtualDevice(t.device))return this.virtualDeviceAdapter.createPreview(this.startRenderer.bind(this,n,e,i),t.device)[0];if("sharing"===t.kind)return this.startRenderer(n,e,i,this._deviceManager,"ScreenShare");if("camera"!==t.kind||!(0,jf.isUndefined)(t.device))throw new Error("Not yet supported");return this.startRenderer(n,e,i,this._deviceManager,"Video")})();return{instance:n,promise:r}}async createPreview(e,t,i){const{instance:n,promise:r}=this.startPreview(e,t,i);return await r,n}async createPreviewRenderer(e,t){return this.createPreview(e,{kind:"camera"},t)}async createScreenSharingPreviewRenderer(e,t){return this.createPreview(e,{kind:"sharing"},t)}getRawDeviceMediaStream(e,t,i){const n=Jh(e);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.getRawDeviceMediaStream(n,t,i)[0]:this._deviceManager.getRawDeviceMediaStream(n,t)}setRawMediaStream(e,t,i){const n=Jh(t);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.setRawMediaStream(e,n,i):this._deviceManager.setRawMediaStream(e,n)}unsetRawMediaStream(e,t){const i=Jh(e);return this.isVirtualDevice(t)?this.virtualDeviceAdapter.unsetRawMediaStream(i,t):this._deviceManager.unsetRawMediaStream(i)}createAudioRenderer(){return this._deviceManager.createAudioRenderer()}startAudioLoopbackDevice(e){return Promise.reject(new Error("Not implemented"))}async dispose(e){return this._deviceManager.dispose(e)}async registerCompositeVideoDevice(e,t,i){return this._deviceManager.registerVirtualDevice(e,t,i)}async unregisterCompositeVideoDevice(e){return this._deviceManager.unregisterVirtualDevice(e)}async createAudioPlayer(){return Promise.reject(new Error("Not implemented"))}_raiseDevicesChanged(e){(e?Promise.resolve(e):this.enumerateDevicesAsync()).then((e=>{this.raiseChanged(),this.event("devicesChanged").raise(e)}))}getPermissionStateHelper(e){switch(e){case"granted":return"granted";case"denied":return"denied";case"prompt":return"prompt";default:return"unknown"}}_mapDevices(e){return e?.map((e=>this._mapDeviceDesc(e)))}_mapDeviceDesc(t){const i=e._mapDeviceType(t.kind);return 6===i?{id:t.id,label:t.label,kind:i,position:0,defaultVideoId:t.id,devicesIds:[]}:1===i?{id:t.id,browserId:t.browserId,label:t.label,kind:i,position:e._mapCameraPosition(t.position)}:4===i?{id:null,browserId:null,label:t.label,kind:i,formFactor:t.formFactor,isPcInternalDevice:t.isPcInternalDevice,microphoneId:t.microphoneId,speakerId:t.speakerId}:{id:t.id,browserId:"default_output_device"===t.browserId?"default":t.browserId,label:t.label,kind:i,isSystemDefault:!!t.isSystemDefault}}static _mapDeviceType(e){switch(e){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 '${e}'`)}}static _mapCameraPosition(e){switch(e){case"front":return 1;case"back":return 2;case"external":return 3;default:return 0}}isVirtualDevice(e){return e&&this._deviceManager.getRegisteredDevices().some((t=>t.id===e))}async startRenderer(e,t,i,n,r){try{e.initialize(t,n,r),await e.startVideoAsync(),i&&(e.setScalingMode(i.scalingMode),e.setVideoMirroring(!i.ignoreMirroring))}catch(t){throw e.dispose(),t}}},zf=Q,Wf=Q,Kf=class extends Wf.AbstractLogAppender{constructor(e){super(new Wf.StandardLogFormatter(Wf.SLF_Flags.Component)),this._logger=e}log(e,t,i,n){if(!this._logger)return;const r=e.level<=Wf.LogLevel.Debug4?this._logger.debug:e.level<=Wf.LogLevel.Debug2?this._logger.log:e.level<=Wf.LogLevel.Debug1?this._logger.info:e.level<=Wf.LogLevel.Warning?this._logger.warn:this._logger.error;r&&r.apply(this._logger,[this.formatter().format(e,t,i,n)])}},Jf=Q,Yf=p(me()),Qf=["CorrelationId","agent_environment_id","UserInfo_TenantId","participant_id","endpoint_id","mediaLegId","metrics_ConfigIds","ts_calling_version","uiVersion"],Zf={video:[...Qf,"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:[...Qf,"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"]},Xf=class extends gt{constructor(){super(...arguments),this.stabilizationTimeInAvg=2e4}send(e){e&&setTimeout((()=>{this.event("sendMidCallTelemetry").raise(Zf[e])}),this.stabilizationTimeInAvg)}},ev=class extends gt{constructor(e,t){super(),this._telemetryService=e,this._ecsProvider=t,this._ecsProvider.on("OnECSChanged",(()=>Jf.RootToolsManager.OnEcsChange()))}fetchEcsConfig(e,t){return Yf.Resolved().then((()=>this._ecsProvider.getEcsConfig(e,t)))}sendTelemetry(e,t){this._telemetryService.getGenericTelemetryLogger&&e?this._telemetryService.getGenericTelemetryLogger(e).sendEvent({eventName:"rt_log",props:t}):this._telemetryService.sendEvents([{eventName:"rt_log",props:t}])}sendMidCallTelemetry(e){Object.keys(Zf).includes(e)&&this.event("onMidCallTelemetry").raise(e)}},tv=Z,iv=class e{constructor(t){this._prefix=t,this._children=[],this._useConsoleLogger=!1,this.createChild=(t,i)=>{const n="function"==typeof t?"":t,r=new e((this._prefix||"")+n);return this._children.push(r),this._useConsoleLogger&&r.useConsoleLogger(),r},this.createFnLogger=(t,i,...n)=>{const r=`[${i}][${t}]`,s=new e((this._prefix||"")+r);return this._children.push(s),this._useConsoleLogger&&s.useConsoleLogger(),s}}logInfo(){}logFailure(){}logSuccess(){}log(...e){}debug(...e){}info(...e){}warn(...e){}error(...e){}useConsoleLogger(){this._useConsoleLogger=!0;const e=(...e)=>{console.info(this._prefix||"",...e)};this.log=e,this.debug=e,this.info=e,this.warn=e,this.error=e,(0,tv.each)(this._children,(e=>e.useConsoleLogger()))}},nv=class{constructor(e){this.configProvider=e,this.window=Mp.window,this.updateCapabilityOverrides(),this.configProviderSub=e.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 e;this.configProvider.config.capabilities&&(e=this.configProvider.config.capabilities),this.overrides=e||{}}hasMediaCapture(){return!!this.window.navigator.getUserMedia}getCapability(e){return void 0!==this.overrides[e]?!!this.overrides[e]:this.hasMediaCapture()&&this.hasWebRtc()}hasWebRtc(){return void 0!==this.window.RTCPeerConnection}},rv=class e extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.diagnostics=i,this.eventStates=new Map,this.debounceMap=new Map,this.logger.safe.info("Initialized")}signalEvent(e,t,i="Audio",n=!0,r=be(),s,a){const o={type:e,value:t,isLocalSource:n,mediaType:i,deviceManagerId:s,diagnosticData:a};this.shouldRaiseEvent(o)&&this.diagnostics.registerQualityChangedEvent(o);const l=Rf(o),c=this.eventStates.get(l);if(this.configProvider.config.localUFDDebounceTime&&c){clearTimeout(this.debounceMap.get(l));const e=setTimeout(this.raiseEvent.bind(this),this.configProvider.config.localUFDDebounceTime,o,r);this.debounceMap.set(l,e)}else this.raiseEvent(o,r)}raiseEvent(e,t){const i=Rf(e);this.shouldRaiseEvent(e)&&(this.eventStates.set(i,e),this.logger.safe.info(`[${t}] Raising UFD ${e.type} for ${e.mediaType}: ${e.value}`),this.event("onQualityChanged").raise(e))}signalDeviceEvent(t,i,n,r){const s=e.getQualityEventType(t,n,this.configProvider);s?this.signalEvent(s,i,n,void 0,be(),r):this.logger.warn(`Unknown device quality event type: ${t}`)}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 e=Rf(this.lastWhitelistingUFD);this.eventStates.delete(e)}this.lastWhitelistingUFD=void 0}applyCurrentState(e){this.cancelPendingWhitelistingUFD();let t=0;for(const i of this.eventStates.values())"Good"!==i.value&&(e(i),t++);t>0&&this.logger.safe.info(`Applied ${t} UFDs`)}reset(){this.logger.safe.info("Resetting UFD states");for(const[t,i]of this.eventStates.entries())e.persistent.has(i.type)||this.eventStates.delete(t);this.lastWhitelistingUFD=void 0}shouldRaiseEvent(t){const i=Rf(t),n=this.eventStates.get(i);return n&&n.value===t.value?!(!this.configProvider.config.alwaysRaiseBadDeviceEvents||!e.deviceQualityEvents.has(t.type)||"Good"===t.value):!(!n&&"Good"===t.value||("NetworkRelaysNotReachable"===t.type?(this.lastWhitelistingUFD=t,1):"NetworkRecvQuality"===t.type&&!this.configProvider.config.webrtcStatNetworkDetectionEnabled))}static getQualityEventType(e,t,i){switch(e){case 0:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartFailed";case 1:return"DeviceRenderNotFunctioning";case 2:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartTimedOut";case 3:return"DeviceCaptureMute";case 4:switch(t){case"ScreenShare":return"ScreenshareRecordingDisabled";case"Audio":return i.config.enableSignalingAudioPermissionDeniedUFD?"AudioCapturePermissionDenied":"DeviceCaptureNotMuteButSilent";case"Video":return"VideoCapturePermissionDenied";default:return}default:return}}};rv.persistent=new Set(["ZeroCaptureDevicesEnumerated","ZeroRenderDevicesEnumerated"]),rv.deviceQualityEvents=new Set(["DeviceCaptureNotFunctioning","VideoCapturerDeviceStartFailed","VideoCapturerDeviceStartTimedOut","DeviceCaptureMute","ScreenshareRecordingDisabled","DeviceCaptureNotMuteButSilent","VideoCapturePermissionDenied"]);var sv=rv,av=Z,ov="object",lv="undefined",cv="prototype",dv=Object,uv=dv[cv];function hv(e,t){return e||t}function gv(e,t){return e[t]}var pv,mv=void 0,fv=null,vv="function",Sv="object",yv="prototype",Cv="__proto__",Tv="undefined",Ev="constructor",bv="Symbol",_v="length",Iv="name",wv="call",Av="toString",Pv=hv(Object),Rv=gv(Pv,yv),Mv=hv(String),Dv=gv(Mv,yv),kv=hv(Math),Ov=hv(Array),Nv=gv(Ov,yv),Lv=gv(Nv,"slice");function xv(e,t){try{return{v:e.apply(this,t)}}catch(e){return{e}}}function Fv(e){return function(t){return typeof t===e}}function Uv(e){var t="[object "+e+"]";return function(e){return!(!e||function(e){return Rv[Av].call(e)}(e)!==t)}}function Bv(e){return typeof e===Tv||e===Tv}function Vv(e){return e===fv||Bv(e)}function Hv(e){return!!e||e!==mv}function $v(e){return!pv&&(pv=["string","number","boolean",Tv,"symbol","bigint"]),e!==Sv&&-1!==pv.indexOf(e)}var jv=Fv("string"),Gv=Fv(vv);function qv(e){return!(!e&&Vv(e)||!e||typeof e!==Sv)}var zv=gv(Ov,"isArray"),Wv=Uv("Date"),Kv=Fv("number"),Jv=Fv("boolean"),Yv=Uv("Error");function Qv(e){return!!(e&&e.then&&Gv(e.then))}function Zv(e){return!(!e||function(e,t){var i=xv(e);return i.e?t:i.v}((function(){return!(e&&0+e)}),!e))}var Xv=gv(Pv,"getOwnPropertyDescriptor");function eS(e,t){return!!e&&Rv.hasOwnProperty[wv](e,t)}var tS=hv(gv(Pv,"hasOwn"),(function(e,t){return eS(e,t)||!!Xv(e,t)}));function iS(e,t,i){if(e&&qv(e))for(var n in e)if(tS(e,n)&&-1===t[wv](i||e,n,e[n]))break}var nS={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function rS(e){var t={};if(t[nS.c]=!0,t[nS.e]=!0,e.l){t.get=function(){return e.l.v};var i=Xv(e.l,"v");i&&i.set&&(t.set=function(t){e.l.v=t})}return iS(e,(function(e,i){t[nS[e]]=Bv(i)?t[nS[e]]:i})),t}var sS=gv(Pv,"defineProperty"),aS=gv(Pv,"defineProperties");function oS(e,t,i){return sS(e,t,rS(i))}function lS(e,t){var i={};return iS(t,(function(e,t){i[e]=rS(t)})),aS(e,i)}function cS(e,t,i,n,r){var s={};return iS(e,(function(e,n){dS(s,e,t?n:e,r),dS(s,n,i?n:e,r)})),n?n(s):s}function dS(e,t,i,n){sS(e,t,{value:i,enumerable:!0,writable:!!n})}var uS=hv(Mv);function hS(e,t){var i="",n=Rv[Av][wv](e);"[object Error]"===n&&(e={stack:uS(e.stack),message:uS(e.message),name:uS(e.name)});try{i=(i=JSON.stringify(e,fv,t?"number"==typeof t?t:4:mv))&&i.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||uS(e)}catch(e){i=" - "+hS(e,t)}return n+": "+i}function gS(e){throw new Error(e)}function pS(e){throw new TypeError(e)}var mS=gv(Pv,"freeze"),fS=gv(Pv,"assign"),vS=gv(Pv,"keys");function SS(e){return mS&&iS(e,(function(e,t){(zv(t)||qv(t))&&SS(t)})),CS(e)}var yS,CS=hv(mS,(function(e){return e})),TS=hv(gv(Pv,"getPrototypeOf"),(function(e){return e[Cv]||fv})),ES=cS({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},0,0,CS),bS="__tsUtils$gblCfg";function _S(){var e;return typeof globalThis!==Tv&&(e=globalThis),e||typeof self===Tv||(e=self),e||typeof window===Tv||(e=window),e||typeof r===Tv||(e=r),e}function IS(){if(!yS){var e=xv(_S).v||{};yS=e[bS]=e[bS]||{}}return yS}var wS=AS;function AS(e,t,i){var n=t&&t[e];return function(t){var r=t&&t[e]||n;if(r||i){var s=arguments;return(r||i).apply(t,r?Lv[wv](s,1):s)}pS('"'+uS(e)+'" not defined for '+hS(t))}}var PS=gv(kv,"max"),RS=wS("slice",Dv),MS=wS("substring",Dv),DS=AS("substr",Dv,(function(e,t,i){return Vv(e)&&pS("Invalid "+hS(e)),i<0?"":((t=t||0)<0&&(t=PS(t+e[_v],0)),Bv(i)?RS(e,t):RS(e,t,t+i))}));function kS(e,t){return MS(e,0,t)}var OS,NS,LS,xS="_urid";function FS(e){return{description:uS(e),toString:function(){return bv+"("+e+")"},_polyfill:!0}}function US(e){var t=function(){if(!OS){var e=IS();OS=e.gblSym=e.gblSym||{k:{},s:{}}}return OS}();if(!tS(t.k,e)){var i=FS(e),n=vS(t.s).length;i[xS]=function(){return n+"_"+i[Av]()},t.k[e]=i,t.s[i[xS]()]=uS(e)}return t.k[e]}function BS(){LS=IS()}function VS(e){return sS({toJSON:function(){return e}},"v",{value:e})}var HS,$S="window";function jS(e,t){var i;return function(){return!LS&&BS(),(!i||LS.lzy)&&(i=VS(xv(e,t).v)),i.v}}function GS(e){return!LS&&BS(),(!HS||!1===e||LS.lzy)&&(HS=VS(xv(_S).v||fv)),HS.v}function qS(e,t){var i=HS&&!1!==t?HS.v:GS(t);return i&&i[e]?i[e]:e===$S?QS():fv}function zS(){return!!YS()}var WS,KS,JS,YS=jS(qS,["document"]),QS=jS(qS,[$S]),ZS=jS(qS,["navigator"]),XS=jS((function(){return!!xv((function(){return process&&(process.versions||{}).node})).v}));function ey(){return WS=VS(xv(qS,[bv]).v)}function ty(e){var t=(LS.lzy?0:WS)||ey();return t.v?t.v[e]:mv}function iy(e,t){var i=ES[e];!LS&&BS();var n=(LS.lzy?0:WS)||ey();return n.v?n.v[i||e]:t?mv:function(e){var t;!NS&&(NS={});var i=ES[e];return i&&(t=NS[i]=NS[i]||FS(bv+"."+i)),t}(e)}function ny(e,t){!LS&&BS();var i=(LS.lzy?0:WS)||ey();return i.v?i.v(e):t?fv:FS(e)}function ry(e){return!LS&&BS(),((KS=(LS.lzy?0:KS)||VS(xv(ty,["for"]).v)).v||US)(e)}function sy(e){return!!e&&Gv(e.next)}function ay(e,t,i){if(e&&(sy(e)||(!JS&&(JS=VS(iy(3))),e=e[JS.v]?e[JS.v]():null),sy(e))){var n=mv,r=mv;try{for(var s=0;!(r=e.next()).done&&-1!==t[wv](i||e,r.value,s,e);)s++}catch(t){n={e:t},e.throw&&(r=fv,e.throw(n))}finally{try{r&&!r.done&&e.return&&e.return(r)}finally{if(n)throw n.e}}}}function oy(e,t,i){return e.apply(t,i)}function ly(e,t){return!Bv(t)&&e&&(zv(t)?oy(e.push,e,t):sy(t)||function(e){return!function(e){return e===fv||!Hv(e)}(e)&&Gv(e[iy(3)])}(t)?ay(t,(function(t){e.push(t)})):e.push(t)),e}function cy(e,t,i){if(e)for(var n=e[_v]>>>0,r=0;r<n&&(!(r in e)||-1!==t[wv](i||e,e[r],r,e));r++);}var dy=wS("indexOf",Nv);function uy(e,t,i){return(e&&e.slice||Lv).apply(e,Lv[wv](arguments,1))}var hy,gy=AS("includes",Nv,(function(e,t,i){return-1!==dy(e,t,i)})),py=hv(gv(Pv,"create"),(function(e){if(!e)return{};var t=typeof e;function i(){}return t!==Sv&&t!==vv&&pS("Prototype must be an Object or function: "+hS(e)),i[yv]=e,new i}));function my(e,t){return(Pv.setPrototypeOf||function(e,t){var i;!hy&&(hy=VS(((i={})[Cv]=[],i instanceof Array))),hy.v?e[Cv]=t:iS(t,(function(t,i){return e[t]=i}))})(e,t)}function fy(e,t){t&&(e[Iv]=t)}function vy(e,t,i){var n=i||Error,r=n[yv][Iv],s=Error.captureStackTrace;return function(e,t,i){function n(){this[Ev]=t,xv(oS,[this,Iv,{v:e,c:!0,e:!1}])}return xv(oS,[t,Iv,{v:e,c:!0,e:!1}]),(t=my(t,i))[yv]=i===fv?py(i):(n[yv]=i[yv],new n),t}(e,(function(){var i=this,a=arguments;try{xv(fy,[n,e]);var o=oy(n,i,Lv[wv](a))||i;if(o!==i){var l=TS(i);l!==TS(o)&&my(o,l)}return s&&s(o,i[Ev]),t&&t(o,a),o}finally{xv(fy,[n,r])}}),n)}function Sy(){return(Date.now||yy)()}function yy(){return(new Date).getTime()}var Cy,Ty,Ey,by=AS("trim",Dv,function(e){return function(t){return Vv(t)&&pS("strTrim called ["+hS(t)+"]"),t&&t.replace&&(t=t.replace(e,"")),t}}(/^\s+|(?=\s)\s+$/g));function _y(e){if(!e||typeof e!==Sv)return!1;Ey||(Ey=!QS()||QS());var t=!1;if(e!==Ey){Ty||(Cy=Function[yv][Av],Ty=Cy[wv](Pv));try{var i=TS(e);(t=!i)||(eS(i,Ev)&&(i=i[Ev]),t=i&&typeof i===vv&&Cy[wv](i)===Ty)}catch(e){}}return t}function Iy(e){return e.value&&Ry(e),!0}var wy=[function(e){var t=e.value;if(zv(t)){var i=e.result=[];return i.length=t.length,e.copyTo(i,t),!0}return!1},Ry,function(e){return e.type===vv},function(e){var t=e.value;return!!Wv(t)&&(e.result=new Date(t.getTime()),!0)}];function Ay(e,t,i,n){var r=i.handler,s=i.path?n?i.path.concat(n):i.path:[],a={handler:i.handler,src:i.src,path:s},o=typeof t,l=!1,c=!1;t&&o===Sv?l=_y(t):c=t===fv||$v(o);var d={type:o,isPrim:c,isPlain:l,value:t,result:t,path:s,origin:i.src,copy:function(t,n){return Ay(e,t,n?a:i,n)},copyTo:function(t,i){return Py(e,t,i,a)}};return d.isPrim?r&&r[wv](i,d)?d.result:t:function(e,t,i,n){var r;return cy(e,(function(e){if(e.k===t)return r=e,-1})),r||(r={k:t,v:t},e.push(r),n(r)),r.v}(e,t,0,(function(e){oS(d,"result",{g:function(){return e.v},s:function(t){e.v=t}});for(var t=0,n=r;!(n||(t<wy.length?wy[t++]:Iy))[wv](i,d);)n=fv}))}function Py(e,t,i,n){if(!Vv(i))for(var r in i)t[r]=Ay(e,i[r],n,r);return t}function Ry(e){var t=e.value;if(t&&e.isPlain){var i=e.result={};return e.copyTo(i,t),!0}return!1}function My(e,t,i,n,r,s,a){return function(e,t){return cy(t,(function(t){!function(e,t){Py([],e,t,{handler:void 0,src:t,path:[]})}(e,t)})),e}(function(e){return Ay([],e,{handler:void 0,src:e})}(e)||{},Lv[wv](arguments))}var Dy=function(e){return function(t){return t[e]}}(_v);function ky(){return Sy()}var Oy=AS("endsWith",Dv,(function(e,t,i){jv(e)||pS("'"+hS(e)+"' is not a string");var n=jv(t)?t:uS(t),r=!Bv(i)&&i<e[_v]?i:e[_v];return MS(e,r-n[_v],r)===n})),Ny=wS("indexOf",Dv),Ly=AS("startsWith",Dv,(function(e,t,i){jv(e)||pS("'"+hS(e)+"' is not a string");var n=jv(t)?t:uS(t),r=i>0?i:0;return MS(e,r,r+n[_v])===n})),xy="ref",Fy="unref",Uy="hasRef";function By(e,t,i){var n=zv(t),r=n?t.length:0,s=(r>0?t[0]:n?mv:t)||setTimeout,a=(r>1?t[1]:mv)||clearTimeout,o=i[0];i[0]=function(){l.dn(),oy(o,mv,Lv[wv](arguments))};var l=function(e,t){var i,n=!0,r=e?t(fv):fv;function s(){return n=!1,r&&r[Fy]&&r[Fy](),i}function o(){r&&function(e){oy(a,mv,[e])}(r),r=fv}function l(){return r=t(r),n||s(),i}return(i={cancel:o,refresh:l})[Uy]=function(){return r&&r[Uy]?r[Uy]():n},i[xy]=function(){return n=!0,r&&r[xy]&&r[xy](),i},i[Fy]=s,{h:i=sS(i,"enabled",{get:function(){return!!r},set:function(e){!e&&r&&o(),e&&!r&&l()}}),dn:function(){r=fv}}}(e,(function(e){if(e){if(e.refresh)return e.refresh(),e;oy(a,mv,[e])}return oy(s,mv,i)}));return l.h}function Vy(e,t){return By(!0,mv,Lv[wv](arguments))}(GS()||{}).Symbol,(GS()||{}).Reflect;var Hy,$y=function(e,t){return($y=dv.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)};function jy(e,t){function i(){this.constructor=e}"function"!=typeof t&&null!==t&&pS("Class extends value "+String(t)+" is not a constructor or null"),$y(e,t),e[cv]=null===t?py(t):(i[cv]=t[cv],new i)}function Gy(e,t){for(var i=0,n=t.length,r=e.length;i<n;i++,r++)e[r]=t[i];return e}var qy="constructor",zy="prototype",Wy="function",Ky="_dynInstFuncs",Jy="_isDynProxy",Yy="_dynClass",Qy="_dynInstChk",Zy=Qy,Xy="_dfOpts",eC="_unknown_",tC="__proto__",iC="_dyn"+tC,nC="__dynProto$Gbl",rC="_dynInstProto",sC="useBaseInst",aC="setInstFuncs",oC=Object,lC=oC.getPrototypeOf,cC=oC.getOwnPropertyNames,dC=GS(),uC=dC[nC]||(dC[nC]={o:(Hy={},Hy[aC]=!0,Hy[sC]=!0,Hy),n:1e3});function hC(e){return e&&(e===oC[zy]||e===Array[zy])}function gC(e){return hC(e)||e===Function[zy]}function pC(e){var t;if(e){if(lC)return lC(e);var i=e[tC]||e[zy]||(e[qy]?e[qy][zy]:null);t=e[iC]||i,eS(e,iC)||(delete e[rC],t=e[iC]=e[rC]||e[iC],e[rC]=i)}return t}function mC(e,t){var i=[];if(cC)i=cC(e);else for(var n in e)"string"==typeof n&&eS(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function fC(e,t,i){return t!==qy&&typeof e[t]===Wy&&(i||eS(e,t))&&t!==tC&&t!==zy}function vC(e){pS("DynamicProto: "+e)}function SC(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function yC(e,t,i,n,r){if(!hC(e)){var s=i[Ky]=i[Ky]||py(null);if(!hC(s)){var a=s[t]=s[t]||py(null);!1!==s[Zy]&&(s[Zy]=!!r),hC(a)||mC(i,(function(t){fC(i,t,!1)&&i[t]!==n[t]&&(a[t]=i[t],delete i[t],(!eS(e,t)||e[t]&&!e[t][Jy])&&(e[t]=function(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&eS(i,Yy)){var s=e[Ky]||py(null);if((r=(s[i[Yy]]||py(null))[t])||vC("Missing ["+t+"] "+Wy),!r[Qy]&&!1!==s[Zy]){for(var a=!eS(e,t),o=pC(e),l=[];a&&o&&!gC(o)&&!SC(l,o);){var c=o[t];if(c){a=c===n;break}l.push(o),o=pC(o)}try{a&&(e[t]=r),r[Qy]=1}catch(e){s[Zy]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=pC(t)[e]),typeof n!==Wy&&vC("["+e+"] is not a "+Wy),n}(t,e,i)).apply(this,arguments)};return i[Jy]=1,i}(e,t)))}))}}}function CC(e,t){return eS(e,zy)?e.name||t||eC:((e||{})[qy]||{}).name||t||eC}function TC(e,t,i,n){eS(e,zy)||vC("theClass is an invalid class definition.");var r=e[zy];(function(e,t){if(lC){for(var i=[],n=pC(t);n&&!gC(n)&&!SC(i,n);){if(n===e)return!0;i.push(n),n=pC(n)}return!1}return!0})(r,t)||vC("["+CC(e)+"] not in hierarchy of ["+CC(t)+"]");var s=null;eS(r,Yy)?s=r[Yy]:(s="_dynCls$"+CC(e,"_")+"$"+uC.n,uC.n++,r[Yy]=s);var a=TC[Xy],o=!!a[sC];o&&n&&void 0!==n[sC]&&(o=!!n[sC]);var l=function(e){var t=py(null);return mC(e,(function(i){!t[i]&&fC(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[Jy]&&n){var s=e[Ky]||{};!1!==s[Zy]&&(r=(s[t[Yy]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var s=py(null);mC(i,(function(e){s[e]=r(t,i,e)}));for(var a=pC(e),o=[];a&&!gC(a)&&!SC(o,a);)mC(a,(function(e){!s[e]&&fC(a,e,!lC)&&(s[e]=r(t,a,e))})),o.push(a),a=pC(a);return s}(r,t,l,o));var c=!!lC&&!!a[aC];c&&n&&(c=!!n[aC]),yC(r,s,t,l,!1!==c)}TC[Xy]=uC.o;var EC,bC=function(e){return cS(e,1,0,CS)},_C=function(e){return function(e){var t={};return iS(e,(function(e,i){dS(t,e,i[1]),dS(t,i[0],i[1])})),CS(t)}(e)},IC=bC({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),wC="toLowerCase",AC="blkVal",PC="length",RC="rdOnly",MC="notify",DC="warnToConsole",kC="throwInternal",OC="setDf",NC="watch",LC="logger",xC="apply",FC="push",UC="splice",BC="hdlr",VC="cancel",HC="initialize",$C="identifier",jC="removeNotificationListener",GC="addNotificationListener",qC="isInitialized",zC="getNotifyMgr",WC="getPlugin",KC="pollInternalLogs",JC="name",YC="time",QC="processNext",ZC="getProcessTelContext",XC="enabled",eT="stopPollingInternalLogs",tT="unload",iT="onComplete",nT="version",rT="loggingLevelConsole",sT="createNew",aT="teardown",oT="messageId",lT="message",cT="isAsync",dT="diagLog",uT="_doTeardown",hT="update",gT="getNext",pT="setNextPlugin",mT="protocol",fT="userAgent",vT="split",ST="nodeType",yT="replace",CT="type",TT="handler",ET="status",bT="getResponseHeader",_T="getAllResponseHeaders",IT="isChildEvt",wT="data",AT="getCtx",PT="setCtx",RT="complete",MT="urlString",DT="sendPOST",kT="headers",OT="timeout",NT="setRequestHeader",LT="traceId",xT="spanId",FT="traceFlags",UT="Promise",BT="rejected";function VT(e,t){return HT(e,(function(e){return t?t({status:"fulfilled",rejected:!1,value:e}):e}),(function(e){return t?t({status:BT,rejected:!0,reason:e}):e}))}function HT(e,t,i,n){var r=e;try{if(Qv(e))(t||i)&&(r=e.then(t,i));else try{t&&(r=t(e))}catch(e){if(!i)throw e;r=i(e)}}finally{n&&function(e,t){t&&(Qv(e)?e.finally?e.finally(t):e.then((function(e){return t(),e}),(function(e){throw t(),e})):t())}(r,n)}return r}var $T,jT=["pending","resolving","resolved",BT],GT="dispatchEvent";function qT(e){var t;return e&&e.createEvent&&(t=e.createEvent("Event")),!!t&&t.initEvent}var zT,WT="unhandledRejection",KT=WT.toLowerCase(),JT=[],YT=0;function QT(e){return Gv(e)?e.toString():hS(e)}function ZT(e,t,i){var n,r,s=uy(arguments,3),a=0,o=!1,l=[],c=YT++,d=!1,u=null;function h(t,i){try{return JT.push(c),d=!0,u&&u.cancel(),u=null,e((function(e,r){l.push((function(){try{var s=2===a?t:i,o=Bv(s)?n:Gv(s)?s(n):s;Qv(o)?o.then(e,r):s?e(o):3===a?r(o):e(o)}catch(e){r(e)}})),o&&p()}),s)}finally{JT.pop()}}function g(){return jT[a]}function p(){if(l.length>0){var e=l.slice();l=[],d=!0,u&&u.cancel(),u=null,t(e)}}function m(e,t){return function(i){if(a===t){if(2===e&&Qv(i))return a=1,void i.then(m(2,1),m(3,1));a=e,o=!0,n=i,p(),d||3!==e||u||(u=Vy(f,10))}}}function f(){if(!d)if(d=!0,XS())process.emit(WT,n,r);else{var e=QS()||GS();!zT&&(zT=VS(xv(qS,[UT+"RejectionEvent"]).v)),function(e,t,i,n){var r=YS();!$T&&($T=VS(!!xv(qT,[r]).v));var s=$T.v?r.createEvent("Event"):n?new Event(t):{};if(i&&i(s),$T.v&&s.initEvent(t,!1,!0),s&&e[GT])e[GT](s);else{var a=e["on"+t];if(a)a(s);else{var o=qS("console");o&&(o.error||o.log)(t,hS(s))}}}(e,KT,(function(e){return oS(e,"promise",{g:function(){return r}}),e.reason=n,e}),!!zT.v)}}return sS(r={then:h,catch:function(e){return h(void 0,e)},finally:function(e){var t=e,i=e;return Gv(e)&&(t=function(t){return e&&e(),t},i=function(t){throw e&&e(),t}),h(t,i)}},"state",{get:g}),!LS&&BS(),!!((LS.lzy?0:WS)||ey()).v&&(r[iy(11)]="IPromise"),r.toString=function(){return"IPromise "+g()+(o?" - "+QT(n):"")},function(){Gv(i)||pS(UT+": executor is not a function - "+QT(i));var e=m(3,0);try{i.call(r,m(2,0),e)}catch(t){e(t)}}(),r}function XT(e){return function(t){var i=uy(arguments,1);return e((function(e,i){try{var n=[],r=1;ay(t,(function(t,s){t&&(r++,HT(t,(function(t){n[s]=t,0==--r&&e(n)}),i))})),0==--r&&e(n)}catch(e){i(e)}}),i)}}function eE(e,t){return ZT(eE,function(e){var t=Kv(e)?e:0;return function(e){Vy((function(){!function(e){cy(e,(function(e){try{e()}catch(e){}}))}(e)}),t)}}(t),e,t)}var tE,iE,nE=XT(eE),rE=function(e){return function(t){var i=uy(arguments,1);return Qv(t)?t:e((function(e){e(t)}),i)}}(eE),sE=function(e){return function(t){var i=uy(arguments,1);return e((function(e,i){i(t)}),i)}}(eE);function aE(e,t){!tE&&(tE=VS(xv(qS,[UT]).v||null));var i=tE.v;if(!i)return eE(e);Gv(e)||pS(UT+": executor is not a function - "+hS(e));var n=0,r=new i((function(t,i){e((function(e){n=2,t(e)}),(function(e){n=3,i(e)}))}));return sS(r,"state",{get:function(){return jT[n]}}),r}function oE(e,t){return!iE&&(iE=VS(aE)),iE.v.call(this,e,t)}var lE,cE,dE=XT(oE),uE="reject",hE="Rejected",gE=0,pE={};function mE(){}function fE(e,t,i){!pE[e]&&(pE[e]=vy(e));var n=Sy();return new pE[e]("Task [".concat(t.id,"] ").concat(i||"","- ").concat(t.st?"Running":"Waiting",": ").concat(function(e,t){return(e-t||"0")+" ms"}(n,t.st||t.cr)))}function vE(e,t){var i=Sy()-t;cy(e,(function(e){(e&&!e.rj&&e.st&&e.st<i||!e.st&&e.cr&&e.cr<i)&&e&&e[uE](e.rj||fE("Aborted",e,"Stale "))}))}function SE(e,t){var i=dy(e,t);-1!==i&&e.splice(i,1)}function yE(e,t){var i,n,r=[],s=[],a=6e5,o=a/10,l=0,c=(t?t+".":"")+gE++;e=e||oE;var d=function(){var e=Dy(r)+Dy(s)>0;a>0&&(n||(n=Vy((function(){vE(r,a),vE(s,a),n&&(n.enabled=Dy(r)+Dy(s)>0)}),o)).unref(),n&&(n.enabled=e))},u=function(e,t){return e.st=Sy(),r.push(e),d(),function(i,n){var r=function(t){e.rj=e.rj||t||fE(hE,e),e[uE]=mE,g(e),i=null,n&&n(t),n=null},s=e.id;if(e.rj)r(e.rj);else{e[uE]=r;try{var a=t(s);e.to&&Qv(a)&&(e.t=Vy((function(){r(fE("Timeout",e))}),e.to)),HT(a,(function(t){g(e);try{i&&i(t)}catch(e){n&&n(e)}n=null,i=null}),r)}catch(e){r(e)}}}},h=function(t,i,n){return s.push(t),d(),e((function(e,r){VT(i.p,(function(){SE(s,t),u(t,n)(e,r)}))}))},g=function(e){SE(r,e),e.t&&e.t.cancel(),e.t=null,i&&i===e&&(i=null,Dy(r)+Dy(s)===0&&(n&&n.cancel(),n=null))},p={idle:!0,queue:function(t,n,r){var s,a=c+"."+l++;n&&(a+="-("+n+")");var o=((s={id:a,cr:Sy(),to:r})[uE]=function(e){o.rj=e||fE(hE,o),o[uE]=mE},s);return o.p=i?h(o,i,t):e(u(o,t)),i=o,o.p},setStaleTimeout:function(e,t){n&&n.cancel(),n=null,a=e,o=t||e/10,d()}};return oS(p,"idle",{g:function(){return Dy(r)+Dy(s)===0}}),function(e,t,i){cE=cE||{toString:function(){return"[[SchedulerState]]"}},sS(e,lE=lE||{toString:function(){return"[[SchedulerName]]"}},{get:function(){return c}}),sS(e,cE,{get:i})}(p,0,(function(){return{l:i,r,w:s}})),p}var CE=void 0,TE="",EE="channels",bE="core",_E="createPerfMgr",IE="disabled",wE="extensionConfig",AE="extensions",PE="processTelemetry",RE="priority",ME="eventsSent",DE="eventsDiscarded",kE="eventsSendRequest",OE="perfEvent",NE="offlineEventsStored",LE="offlineBatchSent",xE="offlineBatchDrop",FE="getPerfMgr",UE="domain",BE="path",VE=/-([a-z])/g,HE=/([^\w\d_$])/g,$E=/^(\d+[\w\d_$])/;function jE(e){return!Vv(e)}function GE(e){var t=e;return t&&jv(t)&&(t=(t=(t=t[yT](VE,(function(e,t){return t.toUpperCase()})))[yT](HE,"_"))[yT]($E,(function(e,t){return"_"+t}))),t}function qE(e,t){return!(!e||!t)&&-1!==Ny(e,t)}function zE(e){return e&&e.toISOString()||""}function WE(e){return Yv(e)?e[JC]:TE}function KE(e,t,i,n,r){var s=i;return e&&((s=e[t])===i||r&&!r(s)||n&&!n(i)||(s=i,e[t]=s)),s}function JE(e,t,i,n,r){e&&t&&i&&(!1!==r||Bv(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return Gv(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][xC](n,e)}}(i,n))}function YE(e,t,i,n){return e&&t&&qv(e)&&zv(i)&&cy(i,(function(i){jv(i)&&JE(e,i,t,i,n)})),e}function QE(e){return e&&fS&&(e=dv(fS({},e))),e}function ZE(e,t,i,n,r,s){var a=arguments,o=a[0]||{},l=a[PC],c=!1,d=1;for(l>0&&Jv(o)&&(c=o,o=a[d]||{},d++),qv(o)||(o={});d<l;d++){var u=a[d],h=zv(u),g=qv(u);for(var p in u)if(h&&p in u||g&&tS(u,p)){var m=u[p],f=void 0;if(c&&m&&((f=zv(m))||_y(m))){var v=o[p];f?zv(v)||(v=[]):_y(v)||(v={}),m=ZE(c,v,m)}void 0!==m&&(o[p]=m)}}return o}function XE(e){try{return e.responseText}catch(e){}return null}function eb(e,t){return e?"XMLHttpRequest,Status:"+e[ET]+",Response:"+XE(e)||0:t}function tb(e,t){return t&&(Kv(t)?e=[t].concat(e):zv(t)&&(e=t.concat(e))),e}var ib="withCredentials";function nb(e,t,i){if(!e[i]&&t&&t[bT]){var n=t[bT](i);n&&(e[i]=by(n))}return e}function rb(e,t){var i={};return e[_T]?i=function(e){var t={};return jv(e)&&cy(by(e)[vT](/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=by(e.substring(0,i))[wC](),r=by(e.substring(i+1));t[n]=r}else t[by(e)]=1}})),t}(e[_T]()):t&&(i=nb(i,e,"time-delta-millis"),i=nb(i,e,"kill-duration"),i=nb(i,e,"kill-duration-seconds")),i}var sb="JSON",ab="XMLHttpRequest",ob=null,lb=null,cb=null,db=null;function ub(e,t){var i=!1;if(e){try{if(!(i=t in e)){var n=e[cv];n&&(i=t in n)}}catch(e){}if(!i)try{i=!Bv((new e)[t])}catch(e){}}return i}function hb(e){return typeof location===ov&&location?location:qS("location")}function gb(){return Boolean(typeof JSON===ov&&JSON||null!==qS(sb))}function pb(){var e=ZS();return!(!e||!e.product)&&"ReactNative"===e.product}function mb(){var e=ZS();if(e&&(e[fT]!==lb||null===ob)){var t=((lb=e[fT])||TE)[wC]();ob=qE(t,"msie")||qE(t,"trident/")}return ob}function fb(e){return null!==db&&!1!==e||(db=!!ZS()&&Boolean(ZS().sendBeacon)),db}function vb(e){var t=!1;try{t=!!qS("fetch");var i=qS("Request");t&&e&&i&&(t=ub(i,"keepalive"))}catch(e){}return t}function Sb(){var e=!1;try{e=!!qS(ab)}catch(e){}return e}var yb=4294967296,Cb=4294967295,Tb=123456789,Eb=987654321,bb=!1,_b=Tb,Ib=Eb;function wb(e){var t=0,i=qS("crypto")||qS("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&Cb),0===t&&mb()&&(bb||function(){try{var e=2147483647&Sy();!function(e){e<0&&(e>>>=0),_b=Tb+e&Cb,Ib=Eb-e&Cb,bb=!0}((Math.random()*yb^e)+e)}catch(e){}}(),t=function(){var e=((Ib=36969*(65535&Ib)+(Ib>>16)&Cb)<<16)+(65535&(_b=18e3*(65535&_b)+(_b>>16)&Cb))>>>0&Cb;return e>>>=0}()&Cb),0===t&&(t=Math.floor(yb*Math.random()|0)),e||(t>>>=0),t}function Ab(e){void 0===e&&(e=22);for(var t=wb()>>>0,i=0,n=TE;n[PC]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(wb()<<2&4294967295|3&t)>>>0,i=0);return n}var Pb="3.2.1",Rb="."+Ab(6),Mb=0;function Db(e){return 1===e[ST]||9===e[ST]||!+e[ST]}function kb(e,t){return void 0===t&&(t=!1),GE(e+Mb+++(t?"."+Pb:TE)+Rb)}function Ob(e){var t={id:kb("_aiData-"+(e||TE)+"."+Pb),accept:function(e){return Db(e)},get:function(e,i,n,r){var s=e[t.id];return s?s[GE(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{Db(t)&&oS(t,e.id,{e:!1,v:i})}catch(e){}}return i}(t,e))[GE(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return t}function Nb(e){return e&&qv(e)&&(e.isVal||e.fb||tS(e,"v")||tS(e,"mrg")||tS(e,"ref")||e.set)}function Lb(e,t,i){var n,r=i.dfVal||Hv;if(t&&i.fb){var s=i.fb;zv(s)||(s=[s]);for(var a=0;a<s[PC];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,uS(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function xb(e,t,i){var n,r=i;return i&&Nb(i)&&(r=Lb(e,t,i)),r&&(Nb(r)&&(r=xb(e,t,r)),zv(r)?(n=[])[PC]=r[PC]:_y(r)&&(n={}),n&&(iS(r,(function(i,r){r&&Nb(r)&&(r=xb(e,t,r)),n[i]=r})),r=n)),r}function Fb(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;Nb(h)?(r=h.isVal,s=h.set,c=h[RC],d=h[AC],o=h.mrg,!(l=h.ref)&&Bv(l)&&(l=!!o),a=Lb(e,t,h)):a=n,d&&e[AC](t,i);var g=!0,p=t[i];!p&&Vv(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?xb(e,t,a):a:(_y(u)||zv(a))&&o&&a&&(_y(a)||zv(a))&&iS(a,(function(t,i){Fb(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[RC](t,i)}var Ub=ry("[[ai_dynCfg_1]]"),Bb=ry("[[ai_blkDynCfg_1]]"),Vb=ry("[[ai_frcDynCfg_1]]");function Hb(e){var t;return e&&(zv(e)?(t=[])[PC]=e[PC]:_y(e)&&(t={}),t)?(iS(e,(function(e,i){t[e]=Hb(i)})),t):e}function $b(e){if(e){var t=e[Ub]||e;if(t.cfg&&(t.cfg===e||t.cfg[Ub]===t))return t}return null}function jb(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[Vb])||i[Bb]||(n=_y(i)||zv(i))),n}function Gb(e){pS("InvalidAccess:"+e)}var qb=["push","pop","shift","unshift","splice"],zb=function(e,t,i,n){e&&e[kC](3,108,"".concat(i," [").concat(t,"] failed - ")+hS(n))};function Wb(e,t){var i=Xv(e,t);return i&&i.get}function Kb(e,t,i,n){if(t){var r=Wb(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===dy(r.h,t)&&r.h[FC](t),e.trk(t,r))},clr:function(e){var t=dy(r.h,e);-1!==t&&r.h[UC](t,1)}},s=!0,a=!1;function o(){s&&(a=a||jb(o,e,n),n&&!n[Ub]&&a&&(n=Yb(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},oS(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&Gb("["+i+"] is read-only:"+hS(t)),s&&(a=a||jb(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){iS(n,(function(e){n[e]=l?l[e]:CE}));try{iS(l,(function(t,i){Kb(e,n,t,i)})),l=n}catch(t){zb((e.hdlr||{})[LC],i,"Assigning",t),a=!1}}else n&&n[Ub]&&iS(n,(function(t){var i=Wb(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&jb(o,e,l);!c&&d&&(l=Yb(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function Jb(e,t,i,n){if(t){var r=Wb(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(_y(e)||zv(e)))try{e[Bb]=!0}catch(e){}}(t)}catch(t){zb((e.hdlr||{})[LC],i,"Blocking",t)}try{Kb(e,t,i,t[i]),r=Wb(t,i)}catch(t){zb((e.hdlr||{})[LC],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function Yb(e,t,i,n){try{iS(t,(function(i,n){Kb(e,t,i,n)})),t[Ub]||(sS(t,Ub,{get:function(){return e[BC]}}),function(e,t,i){zv(t)&&cy(qb,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[xC](this,n);return Yb(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){zb((e.hdlr||{})[LC],i,n,t)}return t}var Qb="[[ai_",Zb="]]";function Xb(e,t,i){var n,r=$b(t);if(r)return r;var s,a=kb("dyncfg",!0),o=t&&!1!==i?t:Hb(t),l=((n={uid:null,cfg:o})[LC]=e,n[MC]=function(){s[MC]()},n.set=function(t,i,n){try{t=Kb(s,t,i,n)}catch(t){zb(e,i,"Setting value",t)}return t[i]},n[OC]=function(e,t){return t&&iS(t,(function(t,i){Fb(l,e,t,i)})),e},n[NC]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return oS(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return Jb(s,e,t,(i={},i[0]=!0,i))[t]},n[RC]=function(e,t){var i;return Jb(s,e,t,(i={},i[1]=!0,i))[t]},n[AC]=function(e,t){var i;return Jb(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Bv(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return oS(l,"uid",{c:!1,e:!1,w:!1,v:a}),Yb(s=function(e){var t,i,n=ny(Qb+"get"+e.uid+Zb),r=ny(Qb+"ro"+e.uid+Zb),s=ny(Qb+"rf"+e.uid+Zb),a=ny(Qb+"blkVal"+e.uid+Zb),o=ny(Qb+"dtl"+e.uid+Zb),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(cy(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[OC].bind(e),ref:e.ref.bind(e),rdOnly:e[RC].bind(e)})}catch(t){var s=e[LC];throw s&&s[kC](1,107,hS(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c[VC](),c=null;var t=[];if(cy(e,(function(e){if(e&&(e[o]&&(cy(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[FC](e)}})),l)try{u()}catch(e){t[FC](e)}t[PC]>0&&function(e,t){EC||(EC=vy("AggregationError",(function(e,t){t[PC]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw cy(t,(function(e,t){i+="\n".concat(t," > ").concat(hS(e))})),new EC(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[AC]=a,t[BC]=e,t.add=function(e){if(e&&e.h[PC]>0){l||(l=[]),c||(c=Vy((function(){c=null,u()}),0));for(var t=0;t<e.h[PC];t++){var i=e.h[t];i&&-1===dy(l,i)&&l[FC](i)}}},t[MC]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===dy(i,t)&&i[FC](t)}},i=t}(l),o,"config","Creating"),l}function e_(e,t,i,n){var r=Xb(i,e||{},n);return t&&r[OC](r.cfg,t),r}function t_(e,t,i){var n=e[Ub]||e;return!n.cfg||n.cfg!==e&&n.cfg[Ub]!==n?(function(e,t){e?(e[DC](t),e[kC](2,108,t)):Gb(t)}(i,"Not dynamic - "+hS(e)),e_(e,null,i)[NC](t)):n[NC](t)}function i_(e,t){if(e&&e[tT])return e[tT](t)}function n_(e,t,i){var n;return i||(n=oE((function(e){i=e}))),e&&Dy(e)>0?VT(i_(e[0],t),(function(){n_(uy(e,1),t,i)})):i(),n}var r_="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function s_(e){return{mrg:!0,v:e}}function a_(e){return{isVal:jv,v:uS(e||TE)}}var o_,l_,c_=[ME,DE,kE,OE],d_=null;function u_(e,t){return function(){var i=arguments,n=h_(t);if(n){var r=n.listener;r&&r[e]&&r[e][xC](r,i)}}}function h_(e){var t=d_;return t||!0===e.disableDbgExt||(t=d_||function(){var e=qS("Microsoft");return e&&(d_=e.ApplicationInsights),d_}()),t?t.ChromeDbgExt:null}var g_="warnToConsole",p_={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},m_=((l_={})[0]=null,l_[1]="errorToConsole",l_[2]=g_,l_[3]="debugToConsole",l_);function f_(e){return e?'"'+e[yT](/\"/g,TE)+'"':TE}function v_(e,t){var i=typeof console!==lv?console:qS("console");if(i){var n="log";i[e]&&(n=e),Gv(i[n])&&i[n](t)}}var S_=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[oT]=e,r[lT]=(i?"AI: ":"AI (Internal): ")+e;var s=TE;gb()&&(s=(gb()?JSON||qS(sb):null).stringify(n));var a=(t?" message:"+f_(t):TE)+(n?" props:"+f_(s):TE);r[lT]+=a}return e.dataType="MessageData",e}();function y_(e,t){return(e||{})[LC]||new E_(t)}var C_,T_,E_=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};TC(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[oT];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[FC](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new S_(23,c,!1);e.queue[FC](u),1===t?e.errorToConsole(c):e[DC](c)}}}function d(e,i){var n=h_(t||{});n&&n[dT]&&n[dT](e,i)}a=function(t){return t_(e_(t,p_,e).cfg,(function(e){var t=e.cfg;i=t[rT],n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[kC]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new S_(n,r,o,a);if(s)throw hS(u);var h=m_[t]||g_;if(Bv(u[lT]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[oT];!l[g]&&i>=t&&(e[h](u[lT]),l[g]=!0)}else i>=t&&e[h](u[lT]);c(t,u)}},e.debugToConsole=function(e){v_("debug",e),d("warning",e)},e[DC]=function(e){v_("warn",e),d("warning",e)},e.errorToConsole=function(e){v_("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[tT]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function b_(e){return e||new E_}function __(e,t,i,n,r,s){void 0===s&&(s=!1),b_(e)[kC](t,i,n,r,s)}function I_(e,t){b_(e)[DC](t)}var w_,A_="toGMTString",P_="toUTCString",R_="cookie",M_="expires",D_="isCookieUseDisabled",k_="disableCookiesUsage",O_="_ckMgr",N_=null,L_=null,x_=null,F_={},U_={},B_=((C_={cookieCfg:s_((T_={},T_[UE]={fb:"cookieDomain",dfVal:jE},T_.path={fb:"cookiePath",dfVal:jE},T_.enabled=CE,T_.ignoreCookies=CE,T_.blockedCookies=CE,T_)),cookieDomain:CE,cookiePath:CE})[k_]=CE,C_);function V_(){!w_&&(w_=function(){var e={};return!LS&&BS(),e.b=LS.lzy,sS(e,"v",{configurable:!0,get:function(){var t=YS();return LS.lzy||sS(e,"v",{value:t}),e.b=LS.lzy,t}}),e}())}function H_(e){return!e||e.isEnabled()}function $_(e,t){return!!(t&&e&&zv(e.ignoreCookies))&&-1!==dy(e.ignoreCookies,t)}function j_(e,t){var i=t[XC];if(Vv(i)){var n=void 0;Bv(e[D_])||(n=!e[D_]),Bv(e[k_])||(n=!e[k_]),i=n}return i}function G_(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=t.cookieCfg;i=n&&n[O_]?n[O_]:q_(t)}return i||(i=function(e,t){var i=q_[O_]||U_[O_];return i||(i=q_[O_]=q_(e,t),U_[O_]=i),i}(t,(e||{})[LC])),i}function q_(e,t){var i,n,r,s,a,o,l,c,d;e=e_(e||U_,null,t).cfg,a=t_(e,(function(t){t[OC](t.cfg,B_),n=t.ref(t.cfg,"cookieCfg"),r=n[BE]||"/",s=n[UE],o=!1!==j_(e,n),l=n.getCookie||Y_,c=n.setCookie||Q_,d=n.delCookie||Q_}),t);var u=((i={isEnabled:function(){var i=!1!==j_(e,n)&&o&&z_(t),r=U_[O_];return i&&r&&u!==r&&(i=H_(r)),i},setEnabled:function(e){o=!1!==e,n[XC]=e},set:function(e,t,i,a,o){var l=!1;if(H_(u)&&!function(e,t){return!!(t&&e&&zv(e.blockedCookies)&&-1!==dy(e.blockedCookies,t))||$_(e,t)}(n,e)){var d={},h=by(t||TE),g=Ny(h,";");if(-1!==g&&(h=by(kS(t,g)),d=W_(MS(t,g+1))),KE(d,UE,a||s,Zv,Bv),!Vv(i)){var p=mb();if(Bv(d[M_])){var m=Sy()+1e3*i;if(m>0){var f=new Date;f.setTime(m),KE(d,M_,K_(f,p?A_:P_)||K_(f,p?A_:P_)||TE,Zv)}}p||KE(d,"max-age",TE+i,null,Bv)}var v=hb();v&&"https:"===v[mT]&&(KE(d,"secure",null,null,Bv),null===L_&&(L_=!function(e){return!(!jv(e)||!qE(e,"CPU iPhone OS 12")&&!qE(e,"iPad; CPU OS 12")&&!(qE(e,"Macintosh; Intel Mac OS X 10_14")&&qE(e,"Version/")&&qE(e,"Safari"))&&(!qE(e,"Macintosh; Intel Mac OS X 10_14")||!Oy(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!qE(e,"Chrome/5")&&!qE(e,"Chrome/6")&&(!qE(e,"UnrealEngine")||qE(e,"Chrome"))&&!qE(e,"UCBrowser/12")&&!qE(e,"UCBrowser/11"))}((ZS()||{})[fT])),L_&&KE(d,"SameSite","None",null,Bv)),KE(d,BE,o||r,null,Bv),c(e,J_(h,d)),l=!0}return l},get:function(e){var t=TE;return H_(u)&&!$_(n,e)&&(t=l(e)),t},del:function(e,t){var i=!1;return H_(u)&&(i=u.purge(e,t)),i},purge:function(e,i){var n,r=!1;if(z_(t)){var s=((n={})[BE]=i||"/",n[M_]="Thu, 01 Jan 1970 00:00:01 GMT",n);mb()||(s["max-age"]="0"),d(e,J_(TE,s)),r=!0}return r}})[tT]=function(e){a&&a.rm(),a=null},i);return u[O_]=u,u}function z_(e){if(null===N_){N_=!1,!w_&&V_();try{var t=w_.v||{};N_=void 0!==t[R_]}catch(t){__(e,2,68,"Cannot access document.cookie - "+WE(t),{exception:hS(t)})}}return N_}function W_(e){var t={};return e&&e[PC]&&cy(by(e)[vT](";"),(function(e){if(e=by(e||TE)){var i=Ny(e,"=");-1===i?t[e]=null:t[by(kS(e,i))]=by(MS(e,i+1))}})),t}function K_(e,t){return Gv(e[t])?e[t]():null}function J_(e,t){var i=e||TE;return iS(t,(function(e,t){i+="; "+e+(Vv(t)?TE:"="+t)})),i}function Y_(e){var t=TE;if(!w_&&V_(),w_.v){var i=w_.v[R_]||TE;x_!==i&&(F_=W_(i),x_=i),t=by(F_[e]||TE)}return t}function Q_(e,t){!w_&&V_(),w_.v&&(w_.v[R_]=e+"="+t)}var Z_={perfEvtsSendAll:!1};function X_(e){e.h=null;var t=e.cb;e.cb=[],cy(t,(function(e){xv(e.fn,[e.arg])}))}function eI(e,t,i,n){cy(e,(function(e){e&&e[t]&&(i?(i.cb[FC]({fn:n,arg:e}),i.h=i.h||Vy(X_,0,i)):xv(n,[e]))}))}var tI=function(){function e(t){var i,n;this.listeners=[];var r=[],s={h:null,cb:[]},a=e_(t,Z_);n=a[NC]((function(e){i=!!e.cfg.perfEvtsSendAll})),TC(e,this,(function(e){oS(e,"listeners",{g:function(){return r}}),e[GC]=function(e){r[FC](e)},e[jC]=function(e){for(var t=dy(r,e);t>-1;)r[UC](t,1),t=dy(r,e)},e[ME]=function(e){eI(r,ME,s,(function(t){t[ME](e)}))},e[DE]=function(e,t){eI(r,DE,s,(function(i){i[DE](e,t)}))},e[kE]=function(e,t){eI(r,kE,t?s:null,(function(i){i[kE](e,t)}))},e[OE]=function(e){e&&(!i&&e[IT]()||eI(r,OE,null,(function(t){e[cT]?Vy((function(){return t[OE](e)}),0):t[OE](e)})))},e[NE]=function(e){e&&e[PC]&&eI(r,NE,s,(function(t){t[NE](e)}))},e[LE]=function(e){e&&e[wT]&&eI(r,LE,s,(function(t){t[LE](e)}))},e[xE]=function(e,t){if(e>0){var i=t||0;eI(r,xE,s,(function(t){t[xE](e,i)}))}},e[tT]=function(e){var t,i=function(){n&&n.rm(),n=null,r=[],s.h&&s.h[VC](),s.h=null,s.cb=[]};if(eI(r,"unload",null,(function(i){var n=i[tT](e);n&&(t||(t=[]),t[FC](n))})),t)return oE((function(e){return VT(dE(t),(function(){i(),e()}))}));i()}}))}return e.__ieDyn=1,e}(),iI="ctx",nI="ParentContextKey",rI="ChildrenContextKey",sI=function(){function e(t,i,n){var r,s=this;s.start=Sy(),s[JC]=t,s[cT]=n,s[IT]=function(){return!1},Gv(i)&&oS(s,"payload",{g:function(){return!r&&Gv(i)&&(r=i(),i=null),r}}),s[AT]=function(t){return t?t===e[nI]||t===e[rI]?s[t]:(s[iI]||{})[t]:null},s[PT]=function(t,i){t&&(t===e[nI]?(s[t]||(s[IT]=function(){return!0}),s[t]=i):t===e[rI]?s[t]=i:(s[iI]=s[iI]||{})[t]=i)},s[RT]=function(){var t=0,i=s[AT](e[rI]);if(zv(i))for(var n=0;n<i[PC];n++){var r=i[n];r&&(t+=r[YC])}s[YC]=Sy()-s.start,s.exTime=s[YC]-t,s[RT]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),aI=function(){function e(t){this.ctx={},TC(e,this,(function(e){e.create=function(e,t,i){return new sI(e,t,i)},e.fire=function(e){e&&(e[RT](),t&&Gv(t[OE])&&t[OE](e))},e[PT]=function(t,i){t&&((e[iI]=e[iI]||{})[t]=i)},e[AT]=function(t){return(e[iI]||{})[t]}}))}return e.__ieDyn=1,e}(),oI="CoreUtils.doPerf";function lI(e,t,i,n,r){if(e){var s=e;if(s[FE]&&(s=s[FE]()),s){var a=void 0,o=s[AT](oI);try{if(a=s.create(t(),n,r)){if(o&&a[PT]&&(a[PT](sI[nI],o),o[AT]&&o[PT])){var l=o[AT](sI[rI]);l||(l=[],o[PT](sI[rI],l)),l[FC](a)}return s[PT](oI,a),i(a)}}catch(e){a&&a[PT]&&a[PT]("exception",e)}finally{a&&s.fire(a),s[PT](oI,o)}}}return i()}function cI(){var e=dI();return MS(e,0,8)+"-"+MS(e,8,12)+"-"+MS(e,12,16)+"-"+MS(e,16,20)+"-"+MS(e,20)}function dI(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=TE,n=0;n<4;n++)i+=t[15&(e=wb())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&wb())|0];return DS(i,0,8)+DS(i,9,4)+"4"+DS(i,13,3)+r+DS(i,16,3)+DS(i,19,12)}function uI(e,t,i){return!(!e||e[PC]!==t||e===i||!e.match(/^[\da-f]*$/i))}function hI(e){return uI(e,32,"00000000000000000000000000000000")}function gI(e){return uI(e,16,"0000000000000000")}var pI=Ob("plugin");function mI(e){return pI.get(e,"state",{},!0)}function fI(e,t){for(var i,n=[],r=null,s=e[gT]();s;){var a=s[WC]();if(a){r&&r[pT]&&a[PE]&&r[pT](a);var o=!!(i=mI(a))[qC];a[qC]&&(o=a[qC]()),o||n[FC](a),r=a,s=s[gT]()}}cy(n,(function(n){var r=e[bE]();n[HC](e.getCfg(),r,t,e[gT]()),i=mI(n),n[bE]||i[bE]||(i[bE]=r),i[qC]=!0,delete i[aT]}))}function vI(e){return e.sort((function(e,t){var i=0;if(t){var n=t[PE];e[PE]?i=n?e[RE]-t[RE]:1:n&&(i=-1)}else i=e?1:-1;return i}))}var SI,yI="_hasRun",CI="_getTelCtx",TI=0;function EI(e,t,i,n){var r=null,s=[];t||(t=e_({},null,i[LC])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[WC]()===i)return e;e=e[gT]()}return wI([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[gT]():null,!e){var t=s;t&&t[PC]>0&&(cy(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){__(i[LC],2,73,"Unexpected Exception during onComplete - "+hS(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return y_(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&iS(i,(function(e,i){if(Vv(n[e])){var r=t.cfg[e];!r&&Vv(r)||(n[e]=r)}Fb(t,n,e,i)})),t[OC](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Vv(s[i])?!a[i]&&Vv(a[i])||(r=a[i]):r=s[i],r||!Vv(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[WC]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[FC]({func:e,self:Bv(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[wE];!s&&i&&(s={}),r[wE]=s,(s=t.ref(r,wE))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function bI(e,t,i,n){var r=e_(t),s=EI(e,r,i,n),a=s.ctx;return a[QC]=function(e){var t=s._next();return t&&t[PE](e,a),!t},a[sT]=function(e,t){return void 0===e&&(e=null),zv(e)&&(e=wI(e,r.cfg,i,t)),bI(e||a[gT](),r.cfg,i,t)},a}function _I(e,t,i){var n=e_(t.config),r=EI(e,n,t,i),s=r.ctx;return s[QC]=function(e){var t=r._next();return t&&t[tT](s,e),!t},s[sT]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=wI(e,n.cfg,t,i)),_I(e||s[gT](),t,i)},s}function II(e,t,i){var n=e_(t.config),r=EI(e,n,t,i).ctx;return r[QC]=function(e){return r.iterate((function(t){Gv(t[hT])&&t[hT](r,e)}))},r[sT]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=wI(e,n.cfg,t,i)),II(e||r[gT](),t,i)},r}function wI(e,t,i,n){var r=null,s=!n;if(zv(e)&&e[PC]>0){var a=null;cy(e,(function(e){if(s||n!==e||(s=!0),s&&e&&Gv(e[PE])){var o=function(e,t,i){var n,r=null,s=Gv(e[PE]),a=Gv(e[pT]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=mI(e);return!n[aT]&&!n[IE]&&(a&&e[pT](r),e[PE](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[QC](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=mI(e),s=e[bE]||r[bE];!e||s&&s!==t.core()||r[aT]||(r[bE]=null,r[aT]=!0,r[qC]=!1,e[aT]&&!0===e[aT](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[cT])||t[QC](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=mI(e),s=e[bE]||r[bE];!e||s&&s!==t.core()||r[aT]||e[hT]&&!0===e[hT](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[QC](i)},_id:n=e?e[$C]+"-"+e[RE]+"-"+TI++:"Unknown-0-"+TI++,_setNext:function(e){r=e}};function l(){var n;return e&&Gv(e[CI])&&(n=e[CI]()),n||(n=bI(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[$C]:"TelemetryPluginChain",d=t[yI];return d||(d=t[yI]={}),t.setNext(r),e&&lI(t[bE](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:TE;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||__(t[dT](),1,73,"Plugin ["+c+"] failed during "+s+" - "+hS(e)+", run flags: "+hS(d))}}),a,o),l}return CS(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?wI([n],t,i):r}function AI(){var e=[];return{add:function(t){t&&e[FC](t)},run:function(t,i){cy(e,(function(e){try{e(t,i)}catch(e){__(t[dT](),2,73,"Unexpected error calling unload handler - "+hS(e))}})),e=[]}}}function PI(){var e=[];return{run:function(t){var i=e;e=[],cy(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){__(t,2,73,"Unloading:"+hS(e))}}))},add:function(t){t&&ly(e,t)}}}var RI,MI="getPlugin",DI=((SI={})[wE]={isVal:jE,v:{}},SI),kI=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||bI(null,{},a[bE]);t=n&&n[MI]?r[sT](null,n[MI]):r[sT](null,n)}return t}function l(e,t,r){e_(e,DI,y_(t)),!r&&t&&(r=t[ZC]()[gT]());var s=n;n&&n[MI]&&(s=n[MI]()),a[bE]=t,i=bI(r,e,t,s)}function c(){t=!1,a[bE]=null,i=null,n=null,s=PI(),r=AI()}c(),TC(e,a,(function(e){e[HC]=function(e,i,n,r){l(e,i,r),t=!0},e[aT]=function(t,i){var a,o=e[bE];if(o&&(!t||o===t[bE]())){var l,d=!1,u=t||_I(null,o,n&&n[MI]?n[MI]():n),h=i||((a={reason:0})[cT]=!1,a);return e[uT]&&!0===e[uT](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[dT]()),!0===l&&u[QC](h),c())}},e[hT]=function(t,i){var r=e[bE];if(r&&(!t||r===t[bE]())){var s,a=!1,o=t||II(null,r,n&&n[MI]?n[MI]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[gT]()))}},JE(e,"_addUnloadCb",(function(){return r}),"add"),JE(e,"_addHook",(function(){return s}),"add"),oS(e,"_unloadHooks",{g:function(){return s}})})),a[dT]=function(e){return o(e)[dT]()},a[qC]=function(){return t},a.setInitialized=function(e){t=e},a[pT]=function(e){n=e},a[QC]=function(e,t){t?t[QC](e):n&&Gv(n[PE])&&n[PE](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),OI=function(e){function t(){var i,n,r=e.call(this)||this;function s(){i=0,n=[]}return r.identifier="TelemetryInitializerPlugin",r.priority=199,s(),TC(t,r,(function(e,t){e.addTelemetryInitializer=function(e){return function(e,t,i){var n={id:t,fn:i};return ly(e,n),{remove:function(){cy(e,(function(t,i){if(t.id===n.id)return e[UC](i,1),-1}))}}}(n,i++,e)},e[PE]=function(t,i){(function(e,t,i){for(var n=!1,r=e[PC],s=0;s<r;++s){var a=e[s];if(a)try{if(!1===a.fn[xC](null,[t])){n=!0;break}}catch(e){__(i,2,64,"Telemetry initializer failed: "+WE(e),{exception:hS(e)},!0)}}return!n})(n,t,i?i[dT]():e[dT]())&&e[QC](t,i)},e[uT]=function(){s()}})),r}return jy(t,e),t.__ieDyn=1,t}(kI),NI="Plugins must provide initialize method",LI="SDK is still unloading...",xI=SS(((RI={cookieCfg:{}})[AE]={rdOnly:!0,ref:!0,v:[]},RI[EE]={rdOnly:!0,ref:!0,v:[]},RI[wE]={ref:!0,v:{}},RI[_E]=CE,RI.loggingLevelConsole=0,RI.diagnosticLogInterval=CE,RI));function FI(e,t){return new aI(t)}function UI(e,t){var i=!1;return cy(t,(function(t){if(t===e)return i=!0,-1})),i}function BI(e,t,i,n){i&&iS(i,(function(i,r){n&&_y(r)&&_y(t[i])&&BI(e,t[i],r,n),n&&_y(r)&&_y(t[i])?BI(e,t[i],r,n):e.set(t,i,r)}))}function VI(e,t){var i=null,n=-1;return cy(e,(function(e,r){if(e.w===t)return i=e,n=r,-1})),{i:n,l:i}}var HI=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P;TC(e,this,(function(e){function R(e){return w&&w[XC]||P||(e||n&&n.queue[PC]>0)&&(A||(A=!0,j(t[NC]((function(e){var t=e.cfg.diagnosticLogInterval;t&&t>0||(t=1e4);var i=!1;w&&(i=w[XC],w[VC]()),(w=function(e,t){return By(!1,mv,Lv[wv](arguments))}(F,t)).unref(),w[XC]=i})))),w[XC]=!0),w}function M(){var e={};_=[];var t=function(t){t&&cy(t,(function(t){if(t[$C]&&t[nT]&&!e[t.identifier]){var i=t[$C]+"="+t[nT];_[FC](i),e[t.identifier]=t}}))};t(h),u&&cy(u,(function(e){t(e)})),t(d)}function D(){i=!1,(t=e_({},xI,e[LC])).cfg[rT]=1,oS(e,"config",{g:function(){return t.cfg},s:function(t){e.updateCfg(t,!1)}}),oS(e,"pluginVersionStringArr",{g:function(){return _||M(),_}}),oS(e,"pluginVersionString",{g:function(){return I||(_||M(),I=_.join(";")),I||TE}}),oS(e,"logger",{g:function(){return n||(n=new E_(t.cfg),t[LC]=n),n},s:function(e){t[LC]=e,n!==e&&(i_(n,!1),n=e)}}),e[LC]=new E_(t.cfg),b=[];var y=e.config[AE]||[];y.splice(0,y[PC]),ly(y,b),p=new OI,r=[],i_(s,!1),s=null,a=null,o=null,i_(l,!1),l=null,c=null,d=[],u=null,h=null,g=!1,m=null,f=kb("AIBaseCore",!0),v=AI(),C=null,T=null,S=PI(),E=[],I=null,_=null,P=!1,w=null,A=!1}function k(){var i=bI(L(),t.cfg,e);return i[iT](R),i}function O(t){var i=function(e,t,i){var n,r=[],s=[],a={};return cy(i,(function(t){(Vv(t)||Vv(t[HC]))&&gS(NI);var i=t[RE],n=t[$C];t&&i&&(Vv(a[i])?a[i]=n:I_(e,"Two extensions have same priority #"+i+" - "+a[i]+", "+n)),!i||i<500?r[FC](t):s[FC](t)})),(n={})[bE]=r,n[EE]=s,n}(e[LC],0,d);c=null,I=null,_=null,h=vI(ly(h=(u||[])[0]||[],i[EE]));var n=ly(vI(i[bE]),h);b=CS(n);var r=e.config[AE]||[];r.splice(0,r[PC]),ly(r,b);var s=k();h&&h[PC]>0&&fI(s[sT](h),n),fI(s,n),t&&V(t)}function N(e){var t=null,i=null,n=[];return cy(b,(function(t){if(t[$C]===e&&t!==p)return i=t,-1;t.getChannel&&n[FC](t)})),!i&&n[PC]>0&&cy(n,(function(t){if(!(i=t.getChannel(e)))return-1})),i&&(t={plugin:i,setEnabled:function(e){mI(i)[IE]=!e},isEnabled:function(){var e=mI(i);return!e[aT]&&!e[IE]},remove:function(e,t){var n;void 0===e&&(e=!0);var r=[i],s=((n={reason:1})[cT]=e,n);x(r,s,(function(e){e&&O({reason:32,removed:r}),t&&t(e)}))}}),t}function L(){if(!c){var i=(b||[]).slice();-1===dy(i,p)&&i[FC](p),c=wI(vI(i),t.cfg,e)}return c}function x(i,n,r){if(i&&i[PC]>0){var s=_I(wI(i,t.cfg,e),e);s[iT]((function(){var e=!1,t=[];cy(d,(function(n,r){UI(n,i)?e=!0:t[FC](n)})),d=t,I=null,_=null;var n=[];u&&(cy(u,(function(t,r){var s=[];cy(t,(function(t){UI(t,i)?e=!0:s[FC](t)})),n[FC](s)})),u=n),r&&r(e),R()})),s[QC](n)}else r(!1)}function F(){if(n&&n.queue){var t=n.queue.slice(0);n.queue[PC]=0,cy(t,(function(t){var i,n=((i={})[JC]=m||"InternalMessageId: "+t[oT],i.iKey=T,i[YC]=zE(new Date),i.baseType=S_.dataType,i.baseData={message:t[lT]},i);e.track(n)}))}}function U(e,t,i,n){var r=1,s=!1,a=null;function o(){r--,s&&0===r&&(a&&a[VC](),a=null,t&&t(s),t=null)}return n=n||5e3,h&&h[PC]>0&&k()[sT](h).iterate((function(t){if(t.flush){r++;var s=!1;t.flush(e,(function(){s=!0,o()}),i)||s||(e&&null==a?a=Vy((function(){a=null,o()}),n):o())}})),s=!0,o(),!0}function B(){var i;j(t[NC]((function(t){if(t.cfg.enablePerfMgr){var n=t.cfg[_E];i!==n&&(n||(n=FI),function(e,t,i){var n;e?!(n=e[t])&&Vv(n)&&(n=Bv(i)?{}:i,e[t]=n):n=Bv(i)?{}:i}(t.cfg,_E,n),i=n,o=null),a||o||!Gv(n)||(o=n(e,e[zC]()))}else o=null,i=null})))}function V(t){var i=II(L(),e);i[iT](R),e._updateHook&&!0===e._updateHook(i,t)||i[QC](t)}function H(t){var i=e[LC];i?(__(i,2,73,t),R()):gS(t)}function $(t){var i=e[zC]();i&&i[DE]([t],2)}function j(e){S.add(e)}D(),e._getDbgPlgTargets=function(){return[b]},e[qC]=function(){return i},e[HC]=function(r,a,o,l){g&&gS(LI),e[qC]()&&gS("Core cannot be initialized more than once"),r=(t=e_(r,xI,o||e[LC],!1)).cfg,j(t[NC]((function(e){T=e.cfg.instrumentationKey;var t=e.ref(e.cfg,wE);iS(t,(function(i){e.ref(t,i)})),Vv(T)&&gS("Please provide instrumentation key")}))),y=function(e,t,i,n){return t.add(e[NC]((function(e){var t=e.cfg.disableDbgExt;!0===t&&n&&(i[jC](n),n=null),i&&!n&&!0!==t&&(n=function(e){if(!o_){o_={};for(var t=0;t<c_[PC];t++)o_[c_[t]]=u_(c_[t],e)}return o_}(e.cfg),i[GC](n))}))),n}(t,S,(s=l)&&e[zC](),y),B(),e[LC]=o;var c=r[AE];if((d=[])[FC].apply(d,Gy(Gy([],a),c)),u=r[EE],O(null),h&&0!==h[PC]||gS("No "+EE+" available"),u&&u[PC]>1){var p=e[WC]("TeeChannelController");p&&p.plugin||__(n,1,28,"TeeChannel required")}(function(e,t,i){cy(t,(function(t){var n=t_(e,t.w,i);delete t.w,t.rm=function(){n.rm()}}))})(r,E,n),E=null,i=!0,e.releaseQueue(),e[KC]()},e.getChannels=function(){var e=[];return h&&cy(h,(function(t){e[FC](t)})),CS(e)},e.track=function(t){lI(e[FE](),(function(){return"AppInsightsCore:track"}),(function(){null===t&&($(t),gS("Invalid telemetry item")),!t[JC]&&Vv(t[JC])&&($(t),gS("telemetry name required")),t.iKey=t.iKey||T,t[YC]=t[YC]||zE(new Date),t.ver=t.ver||"4.0",!g&&e[qC]()?k()[QC](t):r[FC](t)}),(function(){return{item:t}}),!t.sync)},e[ZC]=k,e[zC]=function(){return s||(s=new tI(t.cfg),e._notificationManager=s),s},e[GC]=function(t){e.getNotifyMgr()[GC](t)},e[jC]=function(e){s&&s[jC](e)},e.getCookieMgr=function(){return l||(l=q_(t.cfg,e[LC])),l},e.setCookieMgr=function(e){l!==e&&(i_(l,!1),l=e)},e[FE]=function(){return a||o||null},e.setPerfMgr=function(e){a=e},e.eventCnt=function(){return r[PC]},e.releaseQueue=function(){if(i&&r[PC]>0){var e=r;r=[],cy(e,(function(e){k()[QC](e)}))}},e[KC]=function(e){return m=e||null,P=!1,w&&w[VC](),R(!0)},e[eT]=function(){P=!0,w&&w[VC](),F()},YE(e,(function(){return p}),["addTelemetryInitializer"]),e[tT]=function(t,r,a){var o;void 0===t&&(t=!0),i||gS("SDK is not initialized"),g&&gS(LI);var c,d=((o={reason:50})[cT]=t,o.flushComplete=!1,o);t&&!r&&(c=oE((function(e){r=e})));var u=_I(L(),e);return u[iT]((function(){S.run(e[LC]),n_([l,s,n],t,(function(){D(),r&&r(d)}))}),e),F(),U(t,(function(t){d.flushComplete=t,g=!0,v.run(u,d),e[eT](),u[QC](d)}),6,a),c},e[WC]=N,e.addPlugin=function(e,t,i,n){if(!e)return n&&n(!1),void H(NI);var r=N(e[$C]);if(r&&!t)return n&&n(!1),void H("Plugin ["+e[$C]+"] is already loaded!");var s={reason:16};function a(t){d[FC](e),s.added=[e],O(s),n&&n(!0)}if(r){var o=[r.plugin];x(o,{reason:2,isAsync:!!i},(function(e){e?(s.removed=o,s.reason|=32,a()):n&&n(!1)}))}else a()},e.updateCfg=function(i,n){var r;if(void 0===n&&(n=!0),e[qC]()){r={reason:1,cfg:t.cfg,oldCfg:My({},t.cfg),newConfig:My({},i),merge:n},i=r.newConfig;var s=t.cfg;i[AE]=s[AE],i[EE]=s[EE]}t._block((function(e){var t=e.cfg;BI(e,t,i,n),n||iS(t,(function(n){tS(i,n)||e.set(t,n,CE)})),e[OC](t,xI)}),!0),t[MC](),r&&V(r)},e.evtNamespace=function(){return f},e.flush=U,e.getTraceCtx=function(e){return C||(C=function(){var e={};return{getName:function(){return e[JC]},setName:function(t){e[JC]=t},getTraceId:function(){return e[LT]},setTraceId:function(t){hI(t)&&(e[LT]=t)},getSpanId:function(){return e[xT]},setSpanId:function(t){gI(t)&&(e[xT]=t)},getTraceFlags:function(){return e[FT]},setTraceFlags:function(t){e[FT]=t}}}()),C},e.setTraceCtx=function(e){C=e||null},e.addUnloadHook=j,JE(e,"addUnloadCb",(function(){return v}),"add"),e.onCfgChange=function(n){return function(e){return oS({rm:function(){e.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(e)+">"}})}(i?t_(t.cfg,n,e[LC]):function(e,t){var i=VI(e,t).l;return i||(i={w:t,rm:function(){var i=VI(e,t);-1!==i.i&&e[UC](i.i,1)}},e[FC](i)),i}(E,n))},e.getWParam=function(){return zS()||t.cfg.enableWParam?0:-1}}))}return e.__ieDyn=1,e}(),$I="",jI="&NoResponseBody=true",GI="POST",qI=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p=0;TC(e,this,(function(e,m){var f=!0;function v(e,t){__(n,2,26,"Failed to send telemetry.",{message:e}),y(t,400,{})}function S(e){v("No endpoint url is provided for the batch",e)}function y(e,t,i,n){try{e&&e(t,i,n)}catch(e){}}function C(e,t){var i=ZS(),n=e[MT];if(!n)return S(t),!0;n=e[MT]+(h?jI:$I);var s=e[wT],a=r?s:new Blob([s],{type:"text/plain;charset=UTF-8"});return i.sendBeacon(n,a)}function T(e,t,i){var a=e[wT];try{if(a)if(C(e,t))!function(e,t){y(t,200,{},"")}(0,t);else{var l=s&&s.beaconOnRetry;l&&Gv(l)?l(e,t,C):(o&&o[DT](e,t,!0),__(n,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(e){r&&I_(n,"Failed to send telemetry using sendBeacon API. Ex:"+hS(e)),y(t,r?0:400,{},$I)}}function E(e,i,n){var a,o,l,c=e[kT]||{};!n&&t&&(a=oE((function(e,t){o=e,l=t}))),r&&n&&e.disableXhrSync&&(n=!1);var d=e[MT];if(!d)return S(i),void(o&&o(!1));var u=function(e,t,i,n,r,s){function a(e,t,i){try{e[t]=i}catch(e){}}void 0===n&&(n=!1),void 0===r&&(r=!1);var o=new XMLHttpRequest;return n&&a(o,"Microsoft_ApplicationInsights_BypassAjaxInstrumentation",n),i&&a(o,ib,i),o.open(e,t,!r),i&&a(o,ib,i),!r&&s&&a(o,"timeout",s),o}(GI,d,f,!0,n,e[OT]);function h(t){var n=s&&s.xhrOnComplete;if(n&&Gv(n))n(t,i,e);else{var a=XE(t);y(i,t[ET],rb(t,r),a)}}return r||u[NT]("Content-type","application/json"),cy(vS(c),(function(e){u[NT](e,c[e])})),u.onreadystatechange=function(){r||(h(u),4===u.readyState&&o&&o(!0))},u.onload=function(){r&&h(u)},u.onerror=function(e){y(i,r?u[ET]:400,rb(u,r),r?$I:eb(u)),l&&l(e)},u.ontimeout=function(){y(i,r?u[ET]:500,rb(u,r),r?$I:eb(u)),o&&o(!1)},u.send(e[wT]),a}function b(e,i,n){var a,o,l,c,d=e[MT],u=e[wT],m=r?u:new Blob([u],{type:"application/json"}),v=new Headers,C=u[PC],T=!1,E=!1,b=e[kT]||{},_=((a={method:GI,body:m})[r_]=!0,a);e.headers&&vS(e.headers)[PC]>0&&(cy(vS(b),(function(e){v.append(e,b[e])})),_[kT]=v),f&&r&&(_.credentials="include"),n&&(_.keepalive=!0,p+=C,r?2===e._sendReason&&(T=!0,h&&(d+=jI)):T=!0);var I=new Request(d,_);try{I[r_]=!0}catch(e){}if(!n&&t&&(o=oE((function(e,t){l=e,c=t}))),!d)return S(i),void(l&&l(!1));function w(e){y(i,r?0:400,{},r?$I:e)}function A(e,t,n){var r=e[ET],a=s.fetchOnComplete;a&&Gv(a)?a(e,i,n||$I,t):y(i,r,{},n||$I)}try{VT(fetch(r?d:I,r?_:null),(function(t){if(n&&(p-=C,C=0),!E)if(E=!0,t.rejected)w(t.reason&&t.reason[lT]),c&&c(t.reason);else{var i=t.value;try{r||i.ok?r&&!i.body?(A(i,null,$I),l&&l(!0)):VT(i.text(),(function(t){A(i,e,t.value),l&&l(!0)})):(w(i.statusText),l&&l(!1))}catch(t){w(hS(t)),c&&c(t)}}}))}catch(e){E||(w(hS(e)),c&&c(e))}return T&&!E&&(E=!0,y(i,200,{}),l&&l(!0)),r&&!E&&e[OT]>0&&g&&g.set((function(){E||(E=!0,y(i,500,{}),l&&l(!0))}),e[OT]),o}function _(e,t,i){var a=QS(),o=new XDomainRequest,l=e[wT];o.onload=function(){var i=XE(o),n=s&&s.xdrOnComplete;n&&Gv(n)?n(o,t,e):y(t,200,{},i)},o.onerror=function(){y(t,400,{},r?$I:function(e){return e?"XDomainRequest,Response:"+XE(e)||0:void 0}(o))},o.ontimeout=function(){y(t,500,{})},o.onprogress=function(){};var c=a&&a.location&&a.location[mT]||"",d=e[MT];if(d){if(!r&&0!==d.lastIndexOf(c,0)){var u="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return __(n,2,40,". "+u),void v(u,t)}var h=r?d:d[yT](/^(https?:)/,"");o.open(GI,h),e[OT]&&(o[OT]=e[OT]),o.send(l),r&&i?g&&g.set((function(){o.send(l)}),0):o.send(l)}else S(t)}function I(){p=0,i=!1,t=!1,n=null,r=null,s=null,a=null,o=null,l=!1,c=!1,d=!1,u=!1,h=!1,g=null}I(),e[HC]=function(t,r){n=r,i&&__(n,1,28,"Sender is already initialized"),e.SetConfig(t),i=!0},e._getDbgPlgTargets=function(){return[i,r,a,t]},e.SetConfig=function(e){try{if(s=e.senderOnCompleteCallBack||{},a=!!e.disableCredentials,r=!!e.isOneDs,t=!!e.enableSendPromise,l=!!e.disableXhr,c=!!e.disableBeacon,d=!!e.disableBeaconSync,g=e.timeWrapper,h=!!e.addNoResponse,u=!!e.disableFetchKeepAlive,o={sendPOST:E},r||(f=!1),a){var i=hb();i&&i.protocol&&"file:"===i.protocol[wC]()&&(f=!1)}return!0}catch(e){}return!1},e.getSyncFetchPayload=function(){return p},e.getSenderInst=function(e,t){return e&&e[PC]?function(e,t){for(var i,n=0,r=null,s=0;null==r&&s<e[PC];)n=e[s],l||1!==n?2!==n||!vb(t)||t&&u?3!==n||!fb()||(t?d:c)||(r=T):r=b:(null===cb&&(cb=typeof XDomainRequest!==lv)&&Sb()&&(cb=cb&&!ub(qS(ab),"withCredentials")),cb?r=_:Sb()&&(r=E)),s++;return r?((i={_transport:n,_isSync:t})[DT]=r,i):null}(e,t):null},e.getFallbackInst=function(){return o},e[uT]=function(e,t){I()}}))}return e.__ieDyn=1,e}(),zI="attachEvent",WI="addEventListener",KI="detachEvent",JI="removeEventListener",YI="events",QI="visibilitychange",ZI="pagehide",XI="pageshow",ew="unload",tw="beforeunload",iw=kb("aiEvtPageHide"),nw=kb("aiEvtPageShow"),rw=/\.[\.]+/g,sw=/[\.]+$/,aw=1,ow=Ob("events"),lw=/^([^.]*)(?:\.(.+)|)/;function cw(e){return e&&e[yT]?e[yT](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,TE):e}function dw(e,t){var i;if(t){var n=TE;zv(t)?(n=TE,cy(t,(function(e){(e=cw(e))&&("."!==e[0]&&(e="."+e),n+=e)}))):n=cw(t),n&&("."!==n[0]&&(n="."+n),e=(e||TE)+n)}var r=lw.exec(e||TE)||[];return(i={})[CT]=r[1],i.ns=(r[2]||TE).replace(rw,".").replace(sw,TE)[vT](".").sort().join("."),i}function uw(e,t,i){void 0===i&&(i=!0);var n=ow.get(e,YI,{},i),r=n[t];return r||(r=n[t]=[]),r}function hw(e,t,i,n){e&&t&&t[CT]&&(e[JI]?e[JI](t[CT],i,n):e[KI]&&e[KI]("on"+t[CT],i))}function gw(e,t,i,n){for(var r=t[PC];r--;){var s=t[r];s&&(i.ns&&i.ns!==s.evtName.ns||n&&!n(s)||(hw(e,s.evtName,s[TT],s.capture),t[UC](r,1)))}}function pw(e,t){return t?dw("xx",zv(t)?[e].concat(t):[e,t]).ns[vT]("."):e}function mw(e,t,i,n,r){var s;void 0===r&&(r=!1);var a=!1;if(e)try{var o=dw(t,n);if((a=function(e,t,i,n){var r=!1;return e&&t&&t[CT]&&i&&(e[WI]?(e[WI](t[CT],i,n),r=!0):e[zI]&&(e[zI]("on"+t[CT],i),r=!0)),r}(e,o,i,r))&&ow.accept(e)){var l=((s={guid:aw++,evtName:o})[TT]=i,s.capture=r,s);uw(e,o.type)[FC](l)}}catch(e){}return a}function fw(e,t,i,n,r){if(void 0===r&&(r=!1),e)try{var s=dw(t,n),a=!1;(function(e,t,i){if(t[CT])gw(e,uw(e,t[CT]),t,i);else{var n=ow.get(e,YI,{});iS(n,(function(n,r){gw(e,r,t,i)})),0===vS(n)[PC]&&ow.kill(e,YI)}})(e,s,(function(e){return!((!s.ns||i)&&e[TT]!==i||(a=!0,0))})),a||hw(e,s,i,r)}catch(e){}}function vw(e,t,i,n){var r=!1;return t&&e&&e[PC]>0&&cy(e,(function(e){e&&(i&&-1!==dy(i,e)||(r=function(e,t,i){var n=!1,r=QS();r&&(n=mw(r,e,t,i),n=mw(r.body,e,t,i)||n);var s=YS();return s&&(n=mw(s,e,t,i)||n),n}(e,t,n)||r))})),r}function Sw(e,t,i){e&&zv(e)&&cy(e,(function(e){e&&function(e,t,i){var n=QS();n&&(fw(n,e,t,i),fw(n.body,e,t,i));var r=YS();r&&fw(r,e,t,i)}(e,t,i)}))}function yw(e,t,i){var n=pw(iw,i),r=vw([ZI],e,t,n);return t&&-1!==dy(t,QI)||(r=vw([QI],(function(t){var i=YS();e&&i&&"hidden"===i.visibilityState&&e(t)}),t,n)||r),!r&&t&&(r=yw(e,null,i)),r}function Cw(e,t,i){var n=pw(nw,i),r=vw([XI],e,t,n);return!(r=vw([QI],(function(t){var i=YS();e&&i&&"visible"===i.visibilityState&&e(t)}),t,n)||r)&&t&&(r=Cw(e,null,i)),r}var Tw,Ew="",bw="version",_w="properties",Iw="initialize",ww="logger",Aw="timings",Pw="pollInternalLogs",Rw="value",Mw="kind",Dw="length",kw="processTelemetryStart",Ow="1DS-Web-JS-4.2.1",Nw=uv.hasOwnProperty,Lw=((Tw={})[0]=0,Tw[2]=6,Tw[1]=1,Tw[3]=7,Tw[4098]=6,Tw[4097]=1,Tw[4099]=7,Tw);function xw(e){return!(e===Ew||Vv(e))}function Fw(e,t,i){var n=-1;if(!Bv(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=Lw[jw(e)]||-1;-1!==n&&-1!==r?n|=r:6===r&&(n=r)}return n}function Uw(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||Ew}function Bw(e){void 0===e&&(e="D");var t=cI();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,Ew)),t}function Vw(e,t,i,n,r){var s={},a=!1,o=0,l=arguments[Dw],c=arguments;for(Jv(c[0])&&(a=c[0],o++);o<l;o++)iS(c[o],(function(e,t){a&&t&&qv(t)?zv(t)?(s[e]=s[e]||[],cy(t,(function(t,i){s[e][i]=t&&qv(t)?Vw(!0,s[e][i],t):t}))):s[e]=Vw(!0,s[e],t):s[e]=t}));return s}var Hw=ky;function $w(e,t){var i=e;i[Aw]=i[Aw]||{},i[Aw][kw]=i[Aw][kw]||{},i[Aw][kw][t]=Hw()}function jw(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===ov&&(t=4,zv(e)?(t=4096,e[Dw]>0&&(t|=jw(e[0]))):Nw.call(e,"value")&&(t=8192|jw(e[Rw])))}return t}function Gw(e){return e>0}var qw=SS({endpointUrl:"https://browser.events.data.microsoft.com/OneCollector/1.0/",propertyStorageOverride:{isVal:function(e){return!e||e.getProperty&&e.setProperty||gS("Invalid property storage override passed."),!0}}}),zw=function(e){function t(){var i=e.call(this)||this;return TC(t,i,(function(e,t){e[Iw]=function(i,n,r,s){lI(e,(function(){return"AppInsightsCore.initialize"}),(function(){try{t[Iw](e_(i,qw,r||e[ww],!1).cfg,n,r,s)}catch(t){var a=e[ww],o=hS(t);-1!==o.indexOf("channels")&&(o+="\n - Channels must be provided through config.channels only!"),__(a,1,514,"SDK Initialization Failed - no telemetry will be sent: "+o)}}),(function(){return{config:i,extensions:n,logger:r,notificationManager:s}}))},e.track=function(i){lI(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n[Aw]=n[Aw]||{},n[Aw].trackStart=Hw(),function(e){return!!(e&&Kv(e)&&e>=1&&e<=4)}(n.latency)||(n.latency=1);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=Ow;var s=n.baseData=n.baseData||{};s[_w]=s[_w]||{};var a=s[_w];a[bw]=a[bw]||e.pluginVersionString||Ew}t.track(n)}),(function(){return{item:i}}),!i.sync)},e[Pw]=function(e){return t[Pw](e||"InternalLog")}})),i}return jy(t,e),t.__ieDyn=1,t}(HI),Ww=bC({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),Kw=bC({Normal:1,Critical:2}),Jw="REAL_TIME",Yw="",Qw="drop",Zw="requeue",Xw="no-cache, no-store",eA="application/x-json-stream",tA="cache-control",iA="content-type",nA="client-version",rA="client-id",sA="time-delta-to-apply-millis",aA="upload-time",oA="apikey",lA="AuthMsaDeviceTicket",cA="WebAuthToken",dA="AuthXToken",uA="msfpc",hA="trace",gA="user",pA="allowRequestSending",mA="firstRequestSent",fA="shouldAddClockSkewHeaders",vA="getClockSkewHeaderValue",SA="setClockSkew",yA="length",CA="concat",TA="iKey",EA="count",bA="events",_A="push",IA="split",wA="splice",AA="toLowerCase",PA="hdrs",RA="useHdrs",MA="initialize",DA="setTimeoutOverride",kA="clearTimeoutOverride",OA="overrideEndpointUrl",NA="avoidOptions",LA="enableCompoundKey",xA="disableXhrSync",FA="disableFetchKeepAlive",UA="useSendBeacon",BA="alwaysUseXhrOverride",VA="serializeOfflineEvt",HA="getOfflineRequestDetails",$A="createPayload",jA="createOneDSPayload",GA="payloadBlob",qA="headers",zA="_thePayload",WA="urlString",KA="batches",JA="sendType",YA="addHeader",QA="canSendRequest",ZA="sendQueuedRequests",XA="isCompletelyIdle",eP="setUnloading",tP="sendSynchronousBatch",iP="_transport",nP="getWParam",rP="isBeacon",sP="timings",aP="isTeardown",oP="isSync",lP="data",cP="_sendReason",dP="setKillSwitchTenants",uP="_backOffTransmission",hP="identifier",gP="eventsLimitInMem",pP="autoFlushEventsLimit",mP="baseData",fP="sendAttempt",vP="latency",SP="sync";function yP(e){var t=(e.ext||{}).intweb;return t&&xw(t[uA])?t[uA]:null}function CP(e){for(var t=null,i=0;null===t&&i<e[yA];i++)t=yP(e[i]);return t}var TP=function(){function e(t,i){var n=i?[][CA](i):[],r=this,s=CP(n);r[TA]=function(){return t},r.Msfpc=function(){return s||Yw},r[EA]=function(){return n[yA]},r[bA]=function(){return n},r.addEvent=function(e){return!!e&&(n[_A](e),s||(s=yP(e)),!0)},r[IA]=function(i,r){var a;if(i<n[yA]){var o=n[yA]-i;Vv(r)||(o=r<o?r:o),a=n[wA](i,o),s=CP(n)}return new e(t,a)}}return e.create=function(t,i){return new e(t,i)},e}(),EP=function(){function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",s=!1;TC(e,this,(function(e){e[pA]=function(){return t},e[mA]=function(){n&&(n=!1,s||(t=!1))},e[fA]=function(){return i},e[vA]=function(){return r},e[SA]=function(e){s||(e?(r=e,i=!0,s=!0):i=!1,t=!0)}}))}return e.__ieDyn=1,e}(),bP=function(){function e(){var t={};TC(e,this,(function(e){e[dP]=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&cy(e,(function(e){t[_A](by(e))})),t}(e[IA](","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),s=0;s<n[yA];++s)t[n[s]]=Sy()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=by(e);return void 0!==i[n]&&i[n]>Sy()||(delete i[n],!1)}}))}return e.__ieDyn=1,e}();function _P(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)}var IP,wP=2e6,AP=Math.min(wP,65e3),PP="metadata",RP="f",MP=/\./,DP=function(){function e(t,i,n,r,s,a){var o="data",l="baseData",c=!!r,d=!0,u=i,h={},g=!!a,p=s||Fw;TC(e,this,(function(e){function i(e,t){var i=h[e];return void 0===i&&(e.length>=7&&(i=Ly(e,"ext.metadata")||Ly(e,"ext.web")),h[e]=i),i}function r(e,t,s,a,o,l,d){iS(e,(function(e,h){var g=null;if(h||xw(h)){var p=s,m=e,f=o,v=t;if(c&&!a&&MP.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var T=S[C];v=v[T]=v[T]||{},p+="."+T,f&&f.push(T)}m=S[y-1]}}if(g=a&&i(p)||!u||!u.handleField(p,m)?function(e,t,i){if(!t&&!xw(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||zv(t))t={value:t};else if("object"!==n||Nw.call(t,"value")){if(Vv(t[Rw])||t[Rw]===Ew||!jv(t[Rw])&&!Kv(t[Rw])&&!Jv(t[Rw])&&!zv(t[Rw]))return null}else t={value:i?JSON.stringify(t):t};if(zv(t[Rw])&&!function(e){return e[Dw]>0}(t[Rw]))return null;if(!Vv(t[Mw])){if(zv(t[Rw])||!function(e){return 0===e||e>0&&e<=13||32===e}(t[Mw]))return null;t[Rw]=t[Rw].toString()}return t}(m,h,n):u.value(p,m,h,n)){var E=g.value;if(v[m]=E,l&&l(f,m,g),d&&"object"==typeof E&&!zv(E)){var b=f;b&&(b=b.slice()).push(m),r(h,E,p+"."+m,a,b,l,d)}}}}))}e.createPayload=function(e,t,i,n,r,s){return{apiKeys:[],payloadBlob:Yw,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendType:s,sendReason:r}},e.appendPayload=function(i,n,r){var s=i&&n&&!i.overflow;return s&&lI(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),s=i.payloadBlob,a=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?AP:wP,g=0,p=0;g<t.length;){var m=t[g];if(m){if(a>=r){i.overflow=n.split(g);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(s.length+v>u){i.overflow=n.split(g);break}s&&(s+="\n"),s+=f,++p>20&&(DS(s,0,1),p=0),o=!0,a++}else f?l.push(m):c.push(m),t.splice(g,1),g--}g++}if(l.length>0&&i.sizeExceed.push(TP.create(n.iKey(),l)),c.length>0&&i.failedEvts.push(TP.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=s,i.numEvents=a;var S=n.iKey();-1===dy(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),s},e.getEventBlob=function(e){try{return lI(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+function(e){if(e){var t=Ny(e,"-");if(t>-1)return kS(e,t)}return Ew}(e.iKey);var i,n={};g||(i=function(e,t,i){!function(e,t,i,n,r){if(r&&t){var s=e(r.value,r.kind,r.propertyType);if(s>-1){var a=t[PP];a||(a=t[PP]={f:{}});var o=a[RP];if(o||(o=a[RP]={}),i)for(var l=0;l<i.length;l++){var c=i[l];o[c]||(o[c]={f:{}});var d=o[c][RP];d||(d=o[c][RP]={}),o=d}o=o[n]={},zv(r.value)?o.a={t:s}:o.t=s}}}(p,n,e,t,i)});var s=e.ext;s&&(t.ext=n,iS(s,(function(e,t){r(t,n[e]={},"ext."+e,!0,null,null,!0)})));var a=t[o]={};a.baseType=e.baseType;var c=a[l]={};return r(e.baseData,c,l,!1,[l],i,d),r(e.data,a,o,!1,[],i,d),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))}return e.__ieDyn=1,e}();function kP(e,t){return{set:function(i,n){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return function(e,t,i){return By(!0,e,Lv[wv](arguments,1))}([e,t],i,n,r)}}}var OP="sendAttempt",NP="?cors=true&"+iA[AA]()+"="+eA,LP=((IP={})[1]=Zw,IP[100]=Zw,IP[200]="sent",IP[8004]=Qw,IP[8003]=Qw,IP),xP={},FP={};function UP(e,t,i){xP[e]=t,!1!==i&&(FP[t]=e)}function BP(e,t){var i=!1;if(e&&t){var n=vS(e);if(n&&n[yA]>0)for(var r=t[AA](),s=0;s<n[yA];s++){var a=n[s];if(a&&eS(t,a)&&a[AA]()===r){i=!0;break}}}return i}function VP(e,t,i,n){t&&i&&i[yA]>0&&(n&&xP[t]?(e[PA][xP[t]]=i,e[RA]=!0):e.url+="&"+t+"="+i)}UP(lA,lA,!1),UP(nA,nA),UP(rA,"Client-Id"),UP(oA,oA),UP(sA,sA),UP(aA,aA),UP(dA,dA);var HP,$P=function(){function e(t,i,n,r){var s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x=!1;TC(e,this,(function(e){function F(e,t){try{return L&&L.getSenderInst(e,t)}catch(e){}return null}function U(e,t,i){var n=XE(e);H(t,200,{},n),ie(n)}function B(e,t,i,n){var r={},s=e[qA];s&&s.forEach((function(e,t){r[t]=e})),function(e,i,n){H(t,e,i,n),ie(n)}(e.status,r,i||Yw)}function V(e,t,i){var n=XE(e);H(t,e.status,rb(e,!0),n),ie(n)}function H(e,t,i,n){try{e(t,i,n)}catch(e){__(u,2,518,hS(e))}}function $(e,t,i){var n=200,r=e[zA],s=e[WA]+(A?"&NoResponseBody=true":Yw);try{var a=ZS();if(r){var o=!!g.getPlugin("LocalStorage"),l=[],c=[];cy(r[KA],(function(e){if(l&&e&&e[EA]()>0)for(var t=e[bA](),i=0;i<t[yA];i++){if(!a.sendBeacon(s,S.getEventBlob(t[i]))){l[_A](e[IA](i));break}c[_A](e[i])}else l[_A](e[IA](0))})),c[yA]>0&&(r.sentEvts=c),o||ne(l,8003,r[JA],!0)}else n=0}catch(e){I_(u,"Failed to send telemetry using sendBeacon API. Ex:"+hS(e)),n=0}finally{H(t,n,{},Yw)}}function j(e){return 2===e||3===e}function G(e){return T&&j(e)&&(e=2),e}function q(){return!o&&c<i}function z(){var e=v;return v=[],e}function W(e,t,i){var n=!1;return e&&e[yA]>0&&!o&&h[t]&&S&&(n=0!==t||q()&&(i>0||l[pA]())),n}function K(e){var t={};return e&&cy(e,(function(e,i){t[i]={iKey:e[TA](),evts:e[bA]()}})),t}function J(e,i,n,r,s){if(e&&0!==e[yA])if(o)ne(e,1,r);else{r=G(r);try{var l=e,c=0!==r;lI(g,(function(){return"HttpManager:_sendBatches"}),(function(o){o&&(e=e.slice(0));for(var l=[],d=null,u=Hw(),g=h[r]||(c?h[1]:h[0]),p=g&&g[iP],m=w&&(T||j(r)||3===p||g._isSync&&2===p);W(e,r,i);){var f=e.shift();f&&f[EA]()>0&&(a.isTenantKilled(f[TA]())?l[_A](f):(d=d||S[$A](i,n,c,m,s,r),S.appendPayload(d,f,t)?null!==d.overflow&&(e=[d.overflow][CA](e),d.overflow=null,Z(d,u,Hw(),s),u=Hw(),d=null):(Z(d,u,Hw(),s),u=Hw(),e=[f][CA](e),d=null)))}d&&Z(d,u,Hw(),s),e[yA]>0&&(v=e[CA](v)),ne(l,8004,r)}),(function(){return{batches:K(l),retryCount:i,isTeardown:n,isSynchronous:c,sendReason:s,useSendBeacon:j(r),sendType:r}}),!c)}catch(e){__(u,2,48,"Unexpected Exception sending batch: "+hS(e))}}}function Y(e,t){var i={url:s,hdrs:{},useHdrs:!1};t?(i[PA]=Vw(i[PA],f),i.useHdrs=vS(i.hdrs)[yA]>0):iS(f,(function(e,t){FP[e]?VP(i,FP[e],t,!1):(i[PA][e]=t,i[RA]=!0)})),VP(i,rA,"NO_AUTH",t),VP(i,nA,Ow,t);var n=Yw;cy(e.apiKeys,(function(e){n[yA]>0&&(n+=","),n+=e})),VP(i,oA,n,t),VP(i,aA,Sy().toString(),t);var r=function(e){for(var t=0;t<e.batches[yA];t++){var i=e[KA][t].Msfpc();if(i)return encodeURIComponent(i)}return Yw}(e);if(xw(r)&&(i.url+="&ext.intweb.msfpc="+r),l[fA]()&&VP(i,sA,l[vA](),t),g[nP]){var a=g[nP]();a>=0&&(i.url+="&w="+a)}for(var o=0;o<m[yA];o++)i.url+="&"+m[o].name+"="+m[o].value;return i}function Q(e,t,i){e[t]=e[t]||{},e[t][d.identifier]=i}function Z(e,t,i,n){if(e&&e.payloadBlob&&e.payloadBlob[yA]>0){var r=!!R,s=h[e.sendType];!j(e[JA])&&e[rP]&&2===e.sendReason&&(s=h[2]||h[3]||s);var a=E;(e.isBeacon||3===s[iP])&&(a=!1);var o=Y(e,a);a=a||o[RA];var d=Hw();lI(g,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var h=0;h<e.batches[yA];h++)for(var m=e[KA][h][bA](),f=0;f<m[yA];f++){var v=m[f];if(y){var S=v[sP]=v[sP]||{};Q(S,"sendEventStart",d),Q(S,"serializationStart",t),Q(S,"serializationCompleted",i)}v[OP]>0?v[OP]++:v[OP]=1}ne(e[KA],1e3+(n||0),e[JA],!0);var C={data:e[GA],urlString:o.url,headers:o[PA],_thePayload:e,_sendReason:n,timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};a&&(BP(C[qA],tA)||(C[qA][tA]=Xw),BP(C[qA],iA)||(C[qA][iA]=eA));var T=null;s&&(T=function(t){l[mA]();var i=function(t,i){X(t,i,e,n)},r=e[aP]||e[oP];try{s.sendPOST(t,i,r),M&&M(C,t,r,e[rP])}catch(e){I_(u,"Unexpected exception sending payload. Ex:"+hS(e)),H(i,0,{})}}),lI(g,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(T)if(0===e[JA]&&c++,r&&!e.isBeacon&&3!==s[iP]){var t={data:C[lP],urlString:C[WA],headers:Vw({},C[qA]),timeout:C.timeout,disableXhrSync:C[xA],disableFetchKeepAlive:C[FA]},i=!1;lI(g,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{R(t,(function(e){i=!0,p||e[zA]||(e[zA]=e[zA]||C[zA],e[cP]=e[cP]||C[cP]),T(e)}),e.isSync||e[aP])}catch(e){i||T(C)}}))}else T(C)}))}),(function(){return{thePayload:e,serializationStart:t,serializationCompleted:i,sendReason:n}}),e[oP])}e.sizeExceed&&e.sizeExceed[yA]>0&&ne(e.sizeExceed,8003,e[JA]),e.failedEvts&&e.failedEvts[yA]>0&&ne(e.failedEvts,8002,e[JA])}function X(e,t,i,r){var s=9e3,o=null,d=!1,u=!1;try{var h=!0;if(typeof e!==lv){if(t){l[SA](t["time-delta-millis"]);var g=t["kill-duration"]||t["kill-duration-seconds"];cy(a[dP](t["kill-tokens"],g),(function(e){cy(i[KA],(function(t){if(t[TA]()===e){o=o||[];var n=t[IA](0);i.numEvents-=n[EA](),o[_A](n)}}))}))}if(200==e||204==e)return void(s=200);(!function(e){return!(e>=300&&e<500&&429!=e||501==e||505==e)}(e)||i.numEvents<=0)&&(h=!1),s=9e3+e%1e3}if(h){s=100;var p=i.retryCnt;0===i[JA]&&(p<n?(d=!0,te((function(){0===i[JA]&&c--,J(i[KA],p+1,i[aP],T?2:i[JA],5)}),T,_P(p))):(u=!0,T&&(s=8001)))}}finally{d||(l[SA](),ee(i,s,r,u)),ne(o,8004,i[JA])}}function ee(t,i,n,r){try{r&&d[uP]();var s=t[KA];200===i&&(s=t.sentEvts||t[KA],r||t[oP]||d._clearBackOff(),function(e){if(y){var t=Hw();cy(e,(function(e){e&&e[EA]()>0&&function(e,t){y&&cy(e,(function(e){Q(e[sP]=e[sP]||{},"sendEventCompleted",t)}))}(e[bA](),t)}))}}(s)),ne(s,i,t[JA],!0)}finally{0===t[JA]&&(c--,5!==n&&e.sendQueuedRequests(t[JA],n))}}function te(e,t,i){t?e():O.set(e,i)}function ie(e){var t=D;try{for(var i=0;i<t[yA];i++)try{t[i](e)}catch(e){__(u,1,519,"Response handler failed: "+e)}if(e){var n=JSON.parse(e);xw(n.webResult)&&xw(n.webResult[uA])&&C.set("MSFPC",n.webResult[uA],31536e3)}}catch(e){}}function ne(e,t,i,n){if(e&&e[yA]>0&&r){var s=r[function(e){var t=LP[e];return xw(t)||(t="oth",e>=9e3&&e<=9999?t="rspFail":e>=8e3&&e<=8999?t=Qw:e>=1e3&&e<=1999&&(t="send")),t}(t)];if(s){var a=0!==i;lI(g,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){te((function(){try{s.call(r,e,t,a,i)}catch(e){__(u,1,74,"send request notification failed: "+e)}}),n||a,0)}),(function(){return{batches:K(e),reason:t,isSync:a,sendSync:n,sendType:i}}),!a)}}}!function(){var e;s=null,a=new bP,o=!1,l=new EP,x=!1,c=0,d=null,u=null,h=null,g=null,p=!0,m=[],f={},v=[],S=null,y=!1,C=null,T=!1,E=!1,b=e,_=e,I=e,w=e,A=e,P=[],R=e,M=e,D=[],k=!1,O=kP(),N=!1,L=null}(),e[MA]=function(e,t,i){k||(g=t,C=t.getCookieMgr(),u=(d=i).diagLog(),ly(P,t_(e,(function(e){var n,r=e.cfg,a=e.cfg.extensionConfig[i.identifier];O=kP(a[DA],a[kA]),xw(r.anonCookieName)?function(e,t,i){for(var n=0;n<e[yA];n++)if(e[n].name===t)return void(e[n].value=i);e[_A]({name:t,value:i})}(m,"anoncknm",r.anonCookieName):function(e){for(var t=0;t<e[yA];t++)if("anoncknm"===e[t].name)return void e[wA](t,1)}(m),R=a.payloadPreprocessor,M=a.payloadListener;var o=a.httpXHROverride,l=a[OA]?a[OA]:r.endpointUrl;s=l+NP,E=!!Bv(a[NA])||!a[NA],y=!a.disableEventTimings;var c=a.valueSanitizer,d=a.stringifyObjects,f=!!r[LA];Bv(a[LA])||(f=!!a[LA]),b=a.xhrTimeout,_=!!a[xA],I=!!a[FA],A=!1!==a.addNoResponse,N=!!a.excludeCsMetaData,t.getPlugin("LocalStorage")&&(I=!0),x=!pb(),S=new DP(g,c,d,f,Fw,N),Vv(a[UA])||(x=!!a[UA]);var v=function(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!1,disableXhr:!1,disableBeacon:!x,disableBeaconSync:!x,disableFetchKeepAlive:I,timeWrapper:O,addNoResponse:A,senderOnCompleteCallBack:{xdrOnComplete:U,fetchOnComplete:B,xhrOnComplete:V,beaconOnRetry:$}}}catch(e){}return null}();L?L.SetConfig(v):(L=new qI)[MA](v,u);var C=o,T=a[BA]?o:null,P=a[BA]?o:null,D=[3,2];if(!o){p=!1;var k=[];pb()?(k=[2,1],D=[2,1,3]):k=[1,2,3],(o=F(k=tb(k,a.transports),!1))||I_(u,"No available transport to send events"),C=F(k,!0)}T||(T=F(D=tb(D,a.unloadTransports),!0)),w=!p&&(x&&fb()||!I&&vb(!0)),(n={})[0]=o,n[1]=C||F([1,2,3],!0),n[2]=T||C||F([1],!0),n[3]=P||F([2,3],!0)||C||F([1],!0),h=n}))),k=!0)},e.addResponseHandler=function(e){return D[_A](e),{rm:function(){var t=D.indexOf(e);t>=0&&D[wA](t,1)}}},e[VA]=function(e){try{if(S)return S.getEventBlob(e)}catch(e){}return Yw},e[HA]=function(){try{return Y(S&&S[$A](0,!1,!1,!1,1,0),E)}catch(e){}return null},e[jA]=function(e,i){try{var n=[];cy(e,(function(e){i&&(e=QE(e));var t=TP.create(e[TA],[e]);n[_A](t)}));for(var r=null;n[yA]>0&&S;){var s=n.shift();s&&s[EA]()>0&&(r=r||S[$A](0,!1,!1,!1,1,0),S.appendPayload(r,s,t))}var a=Y(r,E),o={data:r[GA],urlString:a.url,headers:a[PA],timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};return E&&(BP(o[qA],tA)||(o[qA][tA]=Xw),BP(o[qA],iA)||(o[qA][iA]=eA)),o}catch(e){}return null},e._getDbgPlgTargets=function(){return[h[0],a,S,h]},e[YA]=function(e,t){f[e]=t},e.removeHeader=function(e){delete f[e]},e[QA]=function(){return q()&&l[pA]()},e[ZA]=function(e,t){Bv(e)&&(e=0),T&&(e=G(e),t=2),W(v,e,0)&&J(z(),0,!1,e,t||0)},e[XA]=function(){return!o&&0===c&&0===v[yA]},e[eP]=function(e){T=e},e.addBatch=function(e){if(e&&e[EA]()>0){if(a.isTenantKilled(e[TA]()))return!1;v[_A](e)}return!0},e.teardown=function(){v[yA]>0&&J(z(),0,!0,2,2),cy(P,(function(e){e&&e.rm&&e.rm()})),P=[]},e.pause=function(){o=!0},e.resume=function(){o=!1,e[ZA](0,4)},e[tP]=function(e,t,i){e&&e[EA]()>0&&(Vv(t)&&(t=1),T&&(t=G(t),i=2),J([e],0,!1,t,i||0))}}))}return e.__ieDyn=1,e}(),jP=1e4,GP="eventsDiscarded",qP=void 0,zP=SS({eventsLimitInMem:{isVal:Gw,v:jP},immediateEventLimit:{isVal:Gw,v:500},autoFlushEventsLimit:{isVal:Gw,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:function(e){return e&&e.sendPOST},v:qP},overrideInstrumentationKey:qP,overrideEndpointUrl:qP,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:qP,clearTimeoutOverride:qP,payloadPreprocessor:qP,payloadListener:qP,disableEventTimings:qP,valueSanitizer:qP,stringifyObjects:qP,enableCompoundKey:qP,disableOptimizeObj:!1,transports:qP,unloadTransports:qP,useSendBeacon:qP,disableFetchKeepAlive:qP,avoidOptions:!1,xhrTimeout:qP,disableXhrSync:qP,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:Kv,v:6},maxUnloadEventRetryAttempts:{isVal:Kv,v:2},addNoResponse:qP,excludeCsMetaData:qP}),WP=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="4.2.1";var r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R=!1,M=[],D=!1,k=0,O=0,N={},L=Jw;return TC(t,n,(function(e,t){function n(){(function(e,t){Sw([tw,ew,ZI],null,t)})(0,T),function(e,t){var i=pw(iw,t);Sw([ZI],null,i),Sw([QI],null,i)}(0,T),function(e,t){var i=pw(nw,t);Sw([XI],null,i),Sw([QI],null,i)}(0,T)}function x(e){var t="";return e&&e[yA]&&cy(e,(function(e){t&&(t+="\n"),t+=e})),t}function F(e){var t="";try{V(e),t=u[VA](e)}catch(e){}return t}function U(e){"beforeunload"!==(e||QS().event).type&&(S=!0,u[eP](S)),K(2,2)}function B(e){S=!1,u[eP](S)}function V(e){e.ext&&e.ext[hA]&&delete e.ext[hA],e.ext&&e.ext[gA]&&e.ext[gA].id&&delete e.ext[gA].id,v&&(e.ext=QE(e.ext),e[mP]&&(e[mP]=QE(e[mP])),e[lP]&&(e[lP]=QE(e[lP])))}function H(e,t){if(e[fP]||(e[fP]=0),e[vP]||(e[vP]=1),V(e),e[SP])if(c||D)e[vP]=3,e[SP]=!1;else if(u)return v&&(e=QE(e)),void u[tP](TP.create(e[TA],[e]),!0===e[SP]?1:e[SP],3);var i=e[vP],n=O,r=a;4===i&&(n=k,r=s);var o=!1;if(n<r)o=!Q(e,t);else{var l=1,d=20;4===i&&(l=4,d=1),o=!0,function(e,t,i,n){for(;i<=t;){var r=J(e,t,!0);if(r&&r[EA]()>0){var s=r[IA](0,n),a=s[EA]();if(a>0)return 4===i?k-=a:O-=a,ae(GP,[s],IC.QueueFull),!0}i++}return Z(),!1}(e[TA],e[vP],l,d)&&(o=!Q(e,t))}o&&se(GP,[e],IC.QueueFull)}function $(e,t,i){var n=X(e,t,i);return u[ZA](t,i),n}function j(){return O>0}function G(){if(m>=0&&X(m,0,f)&&u[ZA](0,f),k>0&&!l&&!D){var e=N[L][2];e>=0&&(l=z((function(){l=null,$(4,0,1),G()}),e))}var t=N[L][1];!o&&!r&&t>=0&&!D&&(j()?o=z((function(){o=null,$(0===d?3:1,0,1),d++,d%=2,G()}),t):d=0)}function q(){i=null,R=!1,M=[],r=null,D=!1,k=0,s=500,O=0,a=jP,N={},L=Jw,o=null,l=null,c=0,d=0,h={},g=0,w=!1,p=0,m=-1,f=null,v=!0,S=!1,y=6,C=2,T=null,A=null,P=!1,E=kP(),u=new $P(500,2,1,{requeue:ne,send:oe,sent:le,drop:ce,rspFail:de,oth:ue}),ie(),h[4]={batches:[],iKeyMap:{}},h[3]={batches:[],iKeyMap:{}},h[2]={batches:[],iKeyMap:{}},h[1]={batches:[],iKeyMap:{}},he()}function z(e,t){0===t&&c&&(t=1);var i=1e3;return c&&(i=_P(c-1)),E.set(e,t*i)}function W(){return null!==o&&(o.cancel(),o=null,d=0,!0)}function K(e,t){W(),r&&(r.cancel(),r=null),D||$(1,e,t)}function J(e,t,i){var n=h[t];n||(n=h[t=1]);var r=n.iKeyMap[e];return!r&&i&&(r=TP.create(e),n.batches[_A](r),n.iKeyMap[e]=r),r}function Y(t,i){u[QA]()&&!c&&(g>0&&O>g&&(i=!0),i&&null==r&&e.flush(t,(function(){}),20))}function Q(e,t){v&&(e=QE(e));var i=e[vP],n=J(e[TA],i,!0);return!!n.addEvent(e)&&(4!==i?(O++,t&&0===e[fP]&&Y(!e.sync,p>0&&n[EA]()>=p)):k++,!0)}function Z(){for(var e=0,t=0,i=function(i){var n=h[i];n&&n[KA]&&cy(n[KA],(function(n){4===i?e+=n[EA]():t+=n[EA]()}))},n=1;n<=4;n++)i(n);O=t,k=e}function X(t,i,n){var r=!1,s=0===i;return!s||u[QA]()?lI(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=4;i>=t;){var n=h[i];n&&n.batches&&n.batches[yA]>0&&(cy(n[KA],(function(t){u.addBatch(t)?r=r||t&&t[EA]()>0:e=e[CA](t[bA]()),4===i?k-=t[EA]():O-=t[EA]()})),n[KA]=[],n.iKeyMap={}),i--}e[yA]>0&&se(GP,e,IC.KillSwitch),r&&m>=t&&(m=-1,f=0)}),(function(){return{latency:t,sendType:i,sendReason:n}}),!s):(m=m>=0?Math.min(m,t):t,f=Math.max(f,n)),r}function ee(e,t){$(1,0,t),Z(),te((function(){e&&e(),M[yA]>0?r=z((function(){r=null,ee(M.shift(),t)}),0):(r=null,G())}))}function te(e){u[XA]()?e():r=z((function(){r=null,te(e)}),.25)}function ie(){(N={})[Jw]=[2,1,0],N.NEAR_REAL_TIME=[6,3,0],N.BEST_EFFORT=[18,9,0]}function ne(t,i){var n=[],r=y;S&&(r=C),cy(t,(function(t){t&&t[EA]()>0&&cy(t[bA](),(function(t){t&&(t[SP]&&(t[vP]=4,t[SP]=!1),t[fP]<r?($w(t,e[hP]),H(t,!1)):n[_A](t))}))})),n[yA]>0&&se(GP,n,IC.NonRetryableStatus),S&&K(2,2)}function re(t,i){var n=I||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){__(e.diagLog(),1,74,t+" notification failed: "+i)}}function se(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[yA]>0&&re(e,[t][CA](i))}function ae(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[yA]>0&&cy(t,(function(t){t&&t[EA]()>0&&re(e,[t.events()][CA](i))}))}function oe(e,t,i){e&&e[yA]>0&&re("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])}function le(e,t){ae("eventsSent",e,t),G()}function ce(e,t){ae(GP,e,t>=8e3&&t<=8999?t-8e3:IC.Unknown)}function de(e){ae(GP,e,IC.NonRetryableStatus),G()}function ue(e,t){ae(GP,e,IC.Unknown),G()}function he(){p=_?0:Math.max(1500,a/6)}q(),e._getDbgPlgTargets=function(){return[u,i]},e[MA]=function(r,o,l){lI(o,(function(){return"PostChannel:initialize"}),(function(){t[MA](r,o,l),I=o.getNotifyMgr();try{T=pw(kb(e[hP]),o.evtNamespace&&o.evtNamespace()),e._addHook(t_(r,(function(t){var r=t.cfg,l=bI(null,r,o);i=l.getExtCfg(e[hP],zP),E=kP(i[DA],i[kA]),v=!i.disableOptimizeObj&&!!qS("chrome"),b=i.ignoreMc1Ms0CookieProcessing,function(e){var t=e[nP];e[nP]=function(){var i=0;return b&&(i|=2),i|t.call(e)}}(o),a=i[gP],s=i.immediateEventLimit,g=i[pP],y=i.maxEventRetryAttempts,C=i.maxUnloadEventRetryAttempts,_=i.disableAutoBatchFlushLimit,he(),A=i.overrideInstrumentationKey,P=!!i.disableTelemetry,w&&n();var c=r.disablePageUnloadEvents||[];w=function(e,t,i){return function(e,t,i,n){var r=!1;return t&&e&&zv(e)&&!(r=vw(e,t,i,n))&&i&&i[PC]>0&&(r=vw(e,t,null,n)),r}([tw,ew,ZI],e,t,i)}(U,c,T),w=yw(U,c,T)||w,w=Cw(B,r.disablePageShowEvents,T)||w}))),u[MA](r,e.core,e)}catch(t){throw e.setInitialized(!1),t}}),(function(){return{theConfig:r,core:o,extensions:l}}))},e.processTelemetry=function(t,i){$w(t,e[hP]),i=i||e._getTelCtx(i);var n=t;P||R||(A&&(n[TA]=A),H(n,!0),S?K(2,2):G()),e.processNext(n,i)},e.getOfflineSupport=function(){try{var e=u&&u[HA]();if(u)return{getUrl:function(){return e?e.url:null},serialize:F,batch:x,shouldProcess:function(e){return!P},createPayload:function(e){return null},createOneDSPayload:function(e){if(u[jA])return u[jA](e,v)}}}catch(e){}return null},e._doTeardown=function(e,t){K(2,2),R=!0,u.teardown(),n(),q()},e.setEventQueueLimits=function(e,t){i[gP]=a=Gw(e)?e:jP,i[pP]=g=Gw(t)?t:0,he();var n=O>e;if(!n&&p>0)for(var r=1;!n&&r<=3;r++){var s=h[r];s&&s[KA]&&cy(s[KA],(function(e){e&&e[EA]()>=p&&(n=!0)}))}Y(!0,n)},e.pause=function(){W(),D=!0,u.pause()},e.resume=function(){D=!1,u.resume(),G()},e._loadTransmitProfiles=function(e){W(),ie(),L=Jw,G(),iS(e,(function(e,t){var i=t[yA];if(i>=2){var n=i>2?t[2]:0;if(t[wA](0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t[_A](n),N[e]=t}}))},e.flush=function(e,t,i){var n;if(void 0===e&&(e=!0),!D)if(i=i||1,e)t||(n=oE((function(e){t=e}))),null==r?(W(),X(1,0,i),r=z((function(){r=null,ee(t,i)}),0)):M[_A](t);else{var s=W();$(1,1,i),t&&t(),s&&G()}return n},e.setMsaAuthTicket=function(e){u[YA](lA,e)},e.setAuthPluginHeader=function(e){u[YA](cA,e)},e.removeAuthPluginHeader=function(){u.removeHeader(cA)},e.hasEvents=j,e._setTransmitProfile=function(e){L!==e&&void 0!==N[e]&&(W(),L=e,G())},YE(e,(function(){return u}),["addResponseHandler"]),e[uP]=function(){c<4&&(c++,W(),G())},e._clearBackOff=function(){c&&(c=0,W(),G())}})),n}return jy(t,e),t.__ieDyn=1,t}(kI),KP="locale",JP="ver",YP="name",QP=_C({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"]}),ZP=_C({id:[0,"id"],ver:[1,JP],appName:[2,YP],locale:[3,KP],expId:[4,"expId"],env:[5,"env"]}),XP=_C({domain:[0,"domain"],browser:[1,"browser"],browserVer:[2,"browserVer"],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),eR=_C({locale:[0,KP],localId:[1,"localId"],id:[2,"id"]}),tR=_C({osName:[0,YP],ver:[1,JP]}),iR=_C({ver:[0,JP],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),nR=_C({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,"serviceName"]}),rR=_C({popSample:[0,"popSample"],eventFlags:[1,"eventFlags"]}),sR=_C({tz:[0,"tz"]}),aR=_C({sessionId:[0,"sesId"]}),oR=_C({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),lR=_C({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),cR=_C({traceId:[0,"traceID"],traceName:[1,YP],parentId:[2,"parentID"]}),dR=_C({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function uR(){return void 0===HP&&(HP=!!gR(0)),HP}function hR(){return uR()?gR(0):null}function gR(e){var t,i,n=null;try{var r=GS();if(!r)return null;i=new Date,(n=0===e?r.localStorage:r.sessionStorage)&&Gv(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}function pR(){return this.getId()}function mR(e){this.setId(e)}var fR=function(){function e(){TC(e,this,(function(e){e.setId=function(t){e.customId=t},e.getId=function(){return jv(e.customId)?e.customId:e.automaticId}}))}return e._staticInit=void oS(e.prototype,"id",{g:pR,s:mR}),e}(),vR="ai_session",SR=function(){function e(t,i,n){var r,s,a,o=y_(t),l=G_(t);TC(e,this,(function(t){var c=t_(i,(function(){a=i,t.config=a}));function d(){var e=l.get(s());if(e&&Gv(e.split))u(e);else{var i=function(e,t){var i=hR();if(null!==i)try{return i.getItem(t)}catch(t){HP=!1,__(e,1,503,"Browser failed read of local storage. "+t)}return null}(o,s());i&&u(i)}t.automaticSession.getId()||h()}function u(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){__(o,1,510,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&__(o,2,517,"AI session renewal date is 0, session will be reset.")}function h(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid;!Bv(n)&&n?Jv(n)?e.setId(Bw()):e.setId(Bw(n)):e.setId(Ab(a.idLength||22)),e.acquisitionDate=i,e.renewalDate=i,g(e.getId(),e.acquisitionDate,e.renewalDate),uR()||__(o,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function g(e,i,n){var a=i+t.config.sessionExpirationMs,o=n+t.config.sessionRenewalMs,c=new Date,d=[e,i,n];a<o?c.setTime(a):c.setTime(o);var u=t.config.cookieDomain||null;l.set(s(),d.join("|")+";expires="+c.toUTCString(),null,u),r=(new Date).getTime()}n&&n.add(c),s=function(){return t.config.namePrefix?vR+t.config.namePrefix:vR},t.automaticSession=new fR,t.update=function(){t.automaticSession.getId()||d();var i=t.automaticSession,n=t.config,s=(new Date).getTime(),a=s-i.acquisitionDate>n.sessionExpirationMs,o=s-i.renewalDate>n.sessionRenewalMs;a||o?h():(!r||s-r>e.cookieUpdateInterval)&&(i.renewalDate=s,g(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;!function(e,t,i){!function(e,t,i){var n=hR();if(null!==n)try{return n.setItem(t,i),!0}catch(t){HP=!1,__(e,1,504,"Browser failed write to local storage. "+t)}}(o,s(),[e,t,i].join("|"))}(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.cookieUpdateInterval=6e4,e}(),yR=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function CR(e,t){void 0===t&&(t=yR);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)TR(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function TR(e,t){if(void 0===t&&(t=yR),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}function ER(){return this.getExpId()}var bR=function(){function e(t,i,n){var r,s=null,a=yR.slice(0),o=null;TC(e,this,(function(e){if(function(t){var s=t_(t,(function(){r=i&&i.getCookieMgr(),o=t||{},e.env=o.env||function(e){var t,i={},n=YS();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var s=t[r];s.name&&0===s.name.toLowerCase().indexOf(e)&&(i[s.name.replace(e,"")]=s.content)}}return i}("awa-").env}));n&&n.add(s)}(t),zS()){var l=YS().documentElement;l&&(e.locale=l.lang)}function c(e){e!==s&&(s=CR(e,a))}e.getExpId=function(){return o.expId?function(e){return c(e),s}(o.expId):(c(Uw(r,"Treatments")),s)}}))}return e.validateAppExpId=CR,e._staticInit=void oS(e.prototype,"expId",{g:ER}),e}(),_R=function(){},IR=function(){};function wR(){return this.getMsfpc()}function AR(){return this.getAnid()}var PR=function(){function e(t,i,n){var r;TC(e,this,(function(e){(function(t){var s=t_(t,(function(){r=i&&i.getCookieMgr();var n=t||{};n.serviceName&&(e.serviceName=n.serviceName)}));n&&n.add(s)})(t),e.getMsfpc=function(){return Uw(r,"MSFPC")},e.getAnid=function(){return Uw(r,"ANON").slice(0,34)}}))}var t;return e._staticInit=(oS(t=e.prototype,"msfpc",{g:wR}),void oS(t,"anid",{g:AR})),e}(),RR=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},MR={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},DR={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},kR="([\\d,_,.]+)",OR="Unknown",NR=[{r:MR.WINPHONE,os:"Windows Phone"},{r:MR.WINRT,os:"Windows RT"},{r:MR.WIN,os:"Windows"},{r:MR.IOS,os:"iOS"},{r:MR.ANDROID,os:"Android"},{r:MR.LINUX,os:"Linux"},{r:MR.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:MR.OSX,os:"Mac OS X"}];function LR(e,t){var i=e.match(new RegExp(t+" ([\\d,.]+)"));return i?DR[i[1]]?DR[i[1]]:i[1]:OR}function xR(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null}var FR=function(e,t){var i=null,n=null,r=null,s=null,a=t_(e,(function(){if((e||{}).populateOperatingSystemInfo){var t=ZS()||{},r=e.userAgent||t.userAgent||"",s=(e.userAgentData||{}).platform||(t.userAgentData||{}).platform;if(r){var a=function(e){for(var t=0;t<NR.length;t++){var i=NR[t];if(i.r&&e.match(i.r))return i.os;if(i.s&&-1!==e.indexOf(i.s))return i.os}return OR}(r.toLowerCase());i=a,n=function(e,t){return"Windows"===t?LR(e,"Windows NT"):"Android"===t?LR(e,t):"Mac OS X"===t?function(e){var t=e.match(new RegExp("Mac OS X "+kR));if(t){var i=t[1].replace(/_/g,".");if(i){var n=xR(i);return n?i.split(n)[0]:i}}return OR}(e):"iOS"===t?function(e){var t=e.match(new RegExp("OS "+kR));if(t){var i=t[1].replace(/_/g,".");if(i){var n=xR(i);return n?i.split(n)[0]:i}}return OR}(e):OR}(r,a)}i&&i!==OR||!jv(s)||(i=s)}}));t&&t.add(a),oS(this,"name",{s:function(e){r=e},g:function(){return r||i}}),oS(this,"ver",{s:function(e){s=e},g:function(){return s||n}})},UR="MicrosoftApplicationsTelemetryDeviceId",BR=function(){function e(t,i,n){var r,s=0;TC(e,this,(function(e){e.seq=s,e.epoch=wb(!1).toString(),e.getSequenceId=function(){return++s};var a=t_(t,(function(t){r=i&&i.getCookieMgr();var n=t.cfg.propertyStorageOverride;if(r.isEnabled()||n){var s=function(e,t,i){return t?t.getProperty(i)||"":Uw(e,i)}(r,n,UR);s||(s=cI()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(r,n,UR,s),e.installId=s}else r.purge(UR)}));n&&n.add(a)}))}return e.__ieDyn=1,e}(),VR=function(e,t,i,n,r){var s=this;s.traceId=t||dI();var a=t_(e,(function(){var t=e;if(t.enableDistributedTracing&&!i&&(i=dI().substring(0,16)),s.parentId=s.parentId||i,t.enableApplicationInsightsTrace&&!n){var r=hb();r&&r.pathname&&(n=r.pathname)}s.name=s.name||n}));r&&r.add(a)},HR="setLocalId";function $R(){return this.getLocalId()}function jR(e){this[HR](e)}var GR=function(){function e(t,i,n,r){var s,a,o;TC(e,this,(function(l){if(function(i){var c=t_(i,(function(){if(o=n&&n.getCookieMgr(),s=i,a=null,o&&o.isEnabled()&&(d(),s.enableApplicationInsightsUser)){var r=Uw(o,e.userCookieName);if(r){var c=r.split(e.cookieSeparator);c.length>0&&(l.id=c[0])}if(!l.id){l.id=Ab(t&&!Bv(t.idLength)?t.idLength:22);var u=zE(new Date);l.accountAcquisitionDate=u;var h=[l.id,u],g=s.cookieDomain?s.cookieDomain:void 0;o.set(e.userCookieName,h.join(e.cookieSeparator),31536e3,g)}}}));r&&r.add(c)}(i),"undefined"!=typeof navigator){var c=navigator;l.locale=c.userLanguage||c.language}function d(){if(!s.hashIdentifiers&&!s.dropIdentifiers){var e=Uw(o,"MUID");e&&(a="t:"+e)}return a}l.getLocalId=function(){return a||d()},l[HR]=function(e){a=e}}))}return e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void oS(e.prototype,"localId",{g:$R,s:jR}),e}(),qR=function(e,t){var i=this;i.popSample=100;var n=t_(e,(function(){i.eventFlags=0,e.hashIdentifiers&&(i.eventFlags=1048576|i.eventFlags),e.dropIdentifiers&&(i.eventFlags=2097152|i.eventFlags),e.scrubIpOnly&&(i.eventFlags=4194304|i.eventFlags)}));t&&t.add(n)},zR=["Required","Analytics","SocialMedia","Advertising"],WR="([\\d,.]+)",KR="Unknown",JR="Edg/",YR=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:JR,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"}],QR=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function ZR(e,t){return t.indexOf(e)>-1}function XR(e,t){for(var i=0;i<t.length;i++)if(e==t[i].brand)return t[i].version;return null}function eM(){return this.getUserConsent()}var tM=function(){function e(t,i,n){var r=G_(i),s=t||{},a=null,o=null,l=null,c=null,d=null,u=null,h=null;TC(e,this,(function(e){!function(e){var t=t_(e,(function(){if((s=e).populateBrowserInfo){var t=s.userAgent,i=(s.userAgentData||{}).brands;if(t!==a||i!==o){if(!t||!i||0===i.length){var n=ZS();n&&(t=t||n.userAgent||"",i=i||(n.userAgentData||{}).brands)}(function(e,t){if(zv(t))try{for(var i=0;i<QR.length;i++){var n=XR(QR[i].br,t);if(n)return d=QR[i].b,void(u=n)}}catch(e){}if(e){var r=function(e){if(e)for(var t=0;t<YR.length;t++)if(ZR(YR[t].ua,e))return YR[t].b;return KR}(e);d=r,u=function(e,t){return"MSIE"===t?function(e){var t=e.match(new RegExp("MSIE "+WR));if(t)return t[1];var i=e.match(new RegExp("rv:"+WR));return i?i[1]:void 0}(e):function(e,t){"Safari"===e?e="Version":"Edge"===e&&ZR(JR,t)&&(e="Edg");var i=t.match(new RegExp(e+"/"+WR));return i||"Opera"===e&&(i=t.match(new RegExp("OPR/"+WR)))?i[1]:KR}(t,e)}(e,r)}})(t,i),a=t,o=i}}h=Jv(s.gpcDataSharingOptIn)?s.gpcDataSharingOptIn:null}));n&&n.add(t)}(t);var i=hb();if(i){var g=i.hostname;g&&(e.domain="file:"===i.protocol?"local":g)}var p=function(){var e={h:0,w:0},t=QS();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e}();e.screenRes=p.w+"X"+p.h,e.getUserConsent=function(){return s.userConsented||!!Uw(r,s.userConsentCookieName||"MSCC")},e.getUserConsentDetails=function(){var e=null;try{var t=s.callback;if(t&&t.userConsentDetails){var i=t.userConsentDetails();if(i){e=s.disableConsentDetailsSanitize?i:{};for(var n=0;n<zR.length;n++){var r=zR[n];e[r]=i[r]||!1}}}return null!==h&&((e=e||{}).GPC_DataSharingOptIn=!!h),e?JSON.stringify(e):null}catch(e){}},lS(e,{userConsent:{g:e.getUserConsent},browser:{s:function(e){l=e},g:function(){return l||d}},browserVer:{s:function(e){c=e},g:function(){return c||u}},gpcDataSharingOptIn:{g:function(){return h},s:function(e){h=Jv(e)?e:null,s.gpcDataSharingOptIn=h}}})}))}return e._staticInit=void oS(e.prototype,"userConsent",{g:eM}),e}();function iM(e,t,i,n,r){var s=t.ext[QP[e]];if(s)try{iS(n,(function(e,t){if(jv(t)||Kv(t)||Jv(t)){var n=s[i[e]];!r&&(n||jv(n)||Kv(n)||Jv(n))&&(t=n),s[i[e]]=t}}))}catch(e){}return s}var nM,rM=function(){function e(t,i,n,r){TC(e,this,(function(e){e.app=new bR(i,n,r),e.cloud=new _R,e.user=new GR(t,i,n,r),e.os=new FR(i,r),e.web=new tM(i,n,r);var s=new BR(t,n,r),a=new PR(i,n,r),o=new qR(i,r);e.loc=new RR,e.device=new IR;var l=new SR(n,i,r);e.session=new fR;var c=void 0,d=function(e,t){var i=e||{};return{getName:function(){return i.name},setName:function(e){t&&t.setName(e),i.name=e},getTraceId:function(){return i.traceId},setTraceId:function(e){t&&t.setTraceId(e),hI(e)&&(i.traceId=e)},getSpanId:function(){return i.parentId},setSpanId:function(e){t&&t.setSpanId(e),gI(e)&&(i.parentId=e)},getTraceFlags:function(){return i.traceFlags},setTraceFlags:function(e){t&&t.setTraceFlags(e),i.traceFlags=e}}}(new VR(i,c,c,c,r),g()),u=!(i||{}).eventContainExtFields;function h(){var t=e.session;if(t&&jv(t.customId))return t.customId;l.update();var i=l.automaticSession;if(i){var n=i.getId();n&&jv(n)&&(t.automaticId=n)}return t.automaticId}function g(){var e=d;return n&&n.getTraceCtx&&(e=n.getTraceCtx(!1)||d),e}e.getTraceCtx=function(){return d},e.getSessionId=h,e.applyApplicationContext=function(t){var i,n=e.app;iM(4,t,ZP,((i={})[0]=n.id,i[1]=n.ver,i[2]=n.name,i[3]=n.locale,i[4]=n.getExpId(),i[5]=n.env,i),u)},e.applyUserContext=function(t){var i,n=e.user;iM(0,t,eR,((i={})[1]=n.getLocalId(),i[0]=n.locale,i[2]=n.id,i),u)},e.applyWebContext=function(t){var i,n=e.web;iM(3,t,XP,((i={})[0]=n.domain,i[1]=n.browser,i[2]=n.browserVer,i[3]=n.screenRes,i[5]=n.getUserConsentDetails(),i[4]=n.getUserConsent(),i),u)},e.applyOsContext=function(t){var i,n=e.os;iM(5,t,tR,((i={})[0]=n.name,i[1]=n.ver,i),u)},e.applySdkContext=function(e){var t;iM(6,e,iR,((t={})[2]=s.installId,t[1]=s.getSequenceId(),t[3]=s.epoch,t),u)},e.applyIntWebContext=function(e){var t;iM(7,e,nR,((t={})[0]=a.getMsfpc(),t[1]=a.getAnid(),t[2]=a.serviceName,t),u)},e.applyUtcContext=function(e){var t,i=((t={})[0]=o.popSample,t);o.eventFlags>0&&(i[1]=o.eventFlags),iM(8,e,rR,i,u)},e.applyLocContext=function(t){var i;iM(9,t,sR,((i={})[0]=e.loc.tz,i),u)},e.applySessionContext=function(e){var t;iM(4,e,aR,((t={})[0]=h(),t),u)},e.applyDeviceContext=function(t){var i,n=e.device;iM(1,t,oR,((i={})[0]=n.localId,i[2]=n.make,i[3]=n.model,i[1]=n.deviceClass,i),u)},e.applyCloudContext=function(t){var i,n=e.cloud;iM(10,t,lR,((i={})[0]=n.role,i[1]=n.roleInstance,i[2]=n.roleVer,i),u)},e.applyAITraceContext=function(e){var t;if(i.enableApplicationInsightsTrace){var n=g();n&&iM(2,e,cR,((t={})[0]=n.getTraceId(),t[1]=n.getName(),t[2]=n.getSpanId(),t),!1)}},e.applyDistributedTraceContext=function(e){var t,i=g();if(i){var n=((t={})[0]=i.getTraceId(),t[1]=i.getSpanId(),t),r=i.getTraceFlags();Vv(r)||(n[2]=r),iM(11,e,dR,n,!1)}}}))}return e.__ieDyn=1,e}(),sM=[QP[4],QP[0],QP[3],QP[5],QP[6],QP[7],QP[8],QP[9],QP[1],QP[2],QP[11],QP[10]],aM=SS({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:a_(),userAgentData:s_({brands:nM,mobile:nM,platform:nM}),userConsentCookieName:a_(),userConsented:!1,serviceName:a_(),env:a_(),expId:a_(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:a_(),namePrefix:a_(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:s_({userConsentDetails:null}),gpcDataSharingOptIn:nM,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),oM=function(e){function t(){var i,n,r,s=e.call(this)||this;return s.identifier="SystemPropertiesCollector",s.priority=3,s.version="4.2.1",TC(t,s,(function(e,t){function s(){i=null,n={}}function a(t){var n=e.identifier,s=e.core;e._addHook(t_(t,(function(){var e=bI(null,t,s);r=e.getExtCfg(n,aM)}))),i=new rM(t,r,s,e._unloadHooks),s&&s.setTraceCtx&&s.setTraceCtx(i.getTraceCtx())}s(),e.initialize=function(e,i,n){t.initialize(e,i,n),a(e)},e.processTelemetry=function(t,s){$w(t,e.identifier),s=e._getTelCtx(s);var a=t.ext=t.ext?t.ext:{};t.data=t.data?t.data:{},cy(sM,(function(e){a[e]=a[e]||{}})),i&&(i.applyUtcContext(t),i.applyApplicationContext(t),i.applyUserContext(t),i.applyWebContext(t),i.applyOsContext(t),i.applySdkContext(t),i.applyIntWebContext(t),i.applyLocContext(t),i.applySessionContext(t),i.applyDeviceContext(t),r.enableApplicationInsightsTrace&&i.applyAITraceContext(t),r.enableDistributedTracing&&i.applyDistributedTraceContext(t),i.applyCloudContext(t)),cy(vS(a),(function(e){0===vS(a[e]).length&&delete a[e]})),function(e,t){e&&iS(e,(function(e,i){t[e]||(t[e]=i)}))}(n,t.data),e.processNext(t,s)},e.getPropertiesContext=function(){return i},e.setProperty=function(e,t){n[e]=t},e._doTeardown=function(e,t){var n=(e||{}).core();if(n&&n.getTraceCtx&&i){var r=n.getTraceCtx(!1);r&&r===i.getTraceCtx()&&n.setTraceCtx(null)}s()},e._getDbgPlgTargets=function(){return[r]}})),s}return jy(t,e),t.__ieDyn=1,t}(kI),lM=function(e){this._setOverride=function(t,i){e.setOverride(t,i)},this._getOverride=function(t){return e.getOverride(t)}},cM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setId=function(e){s._setOverride(ZP.id,e)},s.getId=function(){return s._getOverride(ZP.id)},s.setVer=function(e){s._setOverride(ZP.ver,e)},s.getVer=function(){return s._getOverride(ZP.ver)},s.setName=function(e){s._setOverride(ZP.appName,e)},s.getName=function(){return s._getOverride(ZP.appName)},s.setLocale=function(e){s._setOverride(ZP.locale,e)},s.getLocale=function(){return s._getOverride(ZP.locale)},s.setEnv=function(e){s._setOverride(ZP.env,e)},s.getEnv=function(){return s._getOverride(ZP.env)},s.setExpId=function(e){s._setOverride(ZP.expId,bR.validateAppExpId(e))},s.getExpId=function(){return s._getOverride(ZP.expId)};var a=t_(i,(function(){i&&(Bv(i.env)||s.setEnv(i.env),Vv(i.expId)||s.setExpId(i.expId))}));return n&&n.add(a),r}return jy(t,e),t}(lM),dM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setRole=function(e){n._setOverride(lR.role,e)},n.getRole=function(){return n._getOverride(lR.role)},n.setRoleInstance=function(e){n._setOverride(lR.roleInstance,e)},n.getRoleInstance=function(){return n._getOverride(lR.roleInstance)},n.setRoleVer=function(e){n._setOverride(lR.roleVer,e)},n.getRoleVer=function(){return n._getOverride(lR.roleVer)},i}return jy(t,e),t}(lM),uM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setProperty=function(e,t){n._setOverride(e,t)},n.getProperty=function(e){return n._getOverride(e)},i}return jy(t,e),t}(lM),hM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(oR.localId,e)},n.getLocalId=function(){return n._getOverride(oR.localId)},n.setDeviceClass=function(e){n._setOverride(oR.deviceClass,e)},n.getDeviceClass=function(){return n._getOverride(oR.deviceClass)},n.setMake=function(e){n._setOverride(oR.make,e)},n.getMake=function(){return n._getOverride(oR.make)},n.setModel=function(e){n._setOverride(oR.model,e)},n.getModel=function(){return n._getOverride(oR.model)},i}return jy(t,e),t}(lM),gM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setTz=function(e){n._setOverride(sR.tz,e)},n.getTz=function(){return n._getOverride(sR.tz)},i}return jy(t,e),t}(lM),pM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r,a=null;s.setOsName=function(e){s._setOverride(tR.osName,e)},s.getOsName=function(){return s._getOverride(tR.osName)},s.setVer=function(e){s._setOverride(tR.ver,e)},s.getVer=function(){return s._getOverride(tR.ver)};var o=t_(i,(function(){!a&&i.userAgent&&i.populateOperatingSystemInfo&&(a=new FR(i,n)),a&&(s.setOsName(a.name),s.setVer(a.ver))}));return n&&n.add(o),r}return jy(t,e),t}(lM);function mM(e,t){if(e)for(var i=0;i<t.length;i++){var n=t[i];Vv(e[n])&&(e[n]={}),e=e[n]}return e}var fM,vM,SM=function(e){var t=this,i=[];t.setOverride=function(e,t){e&&i.push({key:e,value:t})},t.hasOverride=function(e){var t=!1;return cy(i,(function(i){i.key===e&&(t=!0)})),t},t.getOverride=function(e){var t;return cy(i,(function(i){i.key===e&&(t=i.value)})),t},t.applyOverrides=function(t,n){if(i.length>0)try{var r=mM(t,e);cy(i,(function(e){!function(e,t,i){if(e&&t){var n=t.split("."),r=n[n.length-1];n.length>1&&(e=mM(e,n.slice(0,-1))),Vv(i)?Bv(e[r])||delete e[r]:e[r]=i}}(r,e.key,e.value)}))}catch(e){}}},yM=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(eR.localId,e)},n.getLocalId=function(){return n._getOverride(eR.localId)},n.setLocale=function(e){n._setOverride(eR.locale,e)},n.getLocale=function(){return n._getOverride(eR.locale)},n.setId=function(e){n._setOverride(eR.id,e)},n.getId=function(){return n._getOverride(eR.id)},i}return jy(t,e),t}(lM),CM=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setDomain=function(e){s._setOverride(XP.domain,e)},s.getDomain=function(){return s._getOverride(XP.domain)},s.setBrowser=function(e){s._setOverride(XP.browser,e)},s.getBrowser=function(){return s._getOverride(XP.browser)},s.setBrowserVer=function(e){s._setOverride(XP.browserVer,e)},s.getBrowserVer=function(){return s._getOverride(XP.browserVer)},s.setScreenRes=function(e){s._setOverride(XP.screenRes,e)},s.getScreenRes=function(){return s._getOverride(XP.screenRes)},s.setUserConsent=function(e){s._setOverride(XP.userConsent,e)},s.getUserContext=function(){return s._getOverride(XP.userConsent)};var a=t_(i,(function(){i&&(Bv(i.userConsented)||s.setUserConsent(i.userConsented))}));return n&&n.add(a),r}return jy(t,e),t}(lM),TM="ext",EM=function(e,t,i,n){var r=this,s={};function a(e){for(var t="",i=0;i<e.length;i++)t&&(t+="_"),t+=e[i];return Bv(s[t])&&(s[t]=new SM(e)),t?s[t]:null}r.data=new uM(a(["data"])),r.app=new cM(a([TM,QP.AppExt]),t,n),r.user=new yM(a([TM,QP.UserExt])),r.os=new pM(a([TM,QP.OSExt]),t,n),r.web=new CM(a([TM,QP.WebExt]),t,n),r.device=new hM(a([TM,QP.DeviceExt])),r.loc=new gM(a([TM,QP.LocExt])),r.cloud=new dM(a([TM,QP.CloudExt])),r.applyOverrides=function(e,t){var i=vS(s);i&&i.length>0&&cy(i,(function(i){s[i].applyOverrides(e,t)}))}},bM=void 0,_M=SS({env:bM,expId:bM,populateOperatingSystemInfo:!1,userAgent:bM,userAgentData:s_({brands:bM,mobile:bM,platform:bM}),userConsented:bM}),IM="OverridePropertiesPlugin",wM=function(e){function t(){var i=e.call(this)||this;i.identifier=IM,i.priority=4,i.version="4.2.1";var n=null;return TC(t,i,(function(e,t){e.initialize=function(i,n,r){t.initialize(i,n,r),e._baseInit(i,n,r)},e.processTelemetry=function(t,n){$w(t,i.identifier),n=e._getTelCtx(n);var r=e.getOverrideContext();r&&r.applyOverrides(t,n),e.processNext(t,n)},e._baseInit=function(t,r,s){n=new EM(t,i._getTelCtx().getExtCfg(i.identifier,_M),r,e._unloadHooks)},e.setProperty=function(e,t){n&&n.data.setProperty(e,t)},e.getOverrideContext=function(){return n}})),i}return jy(t,e),t.__ieDyn=1,t}(kI),AM="_dropInst",PM=["channelConfiguration","propertyStorageOverride"];function RM(e,t){if(t)for(var i=vS(t),n=0;n<i.length;n++){var r=i[n];tS(e,r)||Ly(r,"Symbol(")||(e[r]=t[r])}}function MM(e,t,i){var n;return oS(e,t,{g:function(){return function(e){return e===fv||$v(typeof e)}(i)?i:(zv(i)?(zv(n)||(n=[]),n.length=i.length):qv(n)||(n={}),iS(i,(function(e,t){Ly(e,"Symbol(")||MM(n,e,t)})),n)}})}function DM(e,t){var i=null;if(t){t.endpointUrl&&(i=t.endpointUrl);var n=(t.extensionConfig||{})[e]||{};n.overrideEndpointUrl&&(i=n.overrideEndpointUrl)}return i}var kM=SS({cookieCfg:{},channelConfiguration:s_({}),propertyConfiguration:s_({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:s_({}),createPerfMgr:vM,loggingLevelConsole:0}),OM=SS({propertyConfiguration:s_({}),cookieCfg:s_({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:s_((fM={},fM[IM]=s_({}),fM)),createPerfMgr:vM,loggingLevelConsole:0}),NM=function(e){function t(i,n){var r=e.call(this)||this;return TC(t,r,(function(e,t){function r(e){var t=[];return e&&cy(e,(function(e){e.iKey===i&&t.push(e)})),t}function s(t){if(e[t]&&e.listeners)for(var i=0;i<e.listeners.length;i++){var n=e.listeners[i];if(n&&n[t])return!0}return!1}var a={eventsSent:function(t){if(s("eventsSent")){var i=r(t);i.length>0&&e.eventsSent(i)}},eventsDiscarded:function(t,i){if(s("eventsDiscarded")){var n=r(t);n.length>0&&e.eventsDiscarded(n,i)}},eventsSendRequest:function(t,i){s("eventsSendRequest")&&e.eventsSendRequest(t,i)},perfEvent:function(t){s("perfEvent")&&e.perfEvent(t)}};n.addNotificationListener(a)})),r}return jy(t,e),t.__ieDyn=1,t}(tI),LM=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m=null,f=null;TC(e,this,(function(e){function v(){t=e_({},kM,null),i=[],n=null,r=null,s=[],a=[],o={},l=null,c=null,d=null,h=null,g=null,p=!1,t.cfg.loggingLevelConsole=1,u=new E_(t.cfg),oS(e,"sharedConfig",{g:function(){return p&&C(),t.cfg}})}function S(e,i){var n;if(void 0===i&&(i=null),e){(!function(e){return e.pause&&e.teardown&&e.flush}(e)?s:a).push(e);var r=e.identifier,o=t.cfg.extensionConfig;t.setDf(o,((n={})[r]={ref:!0,v:i||{}},n))}return e}function y(e){var n=t.cfg;i=[],l=S(new oM,n.propertyConfiguration),i.push(l),n.extensions&&cy(n.extensions,(function(e){Gv(e)||S(e)})),e&&cy(e,(function(e){e&&!Gv(e)&&i.push(S(e))}))}function C(){n||(p||__(e.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),t.cfg.instrumentationKey=t.cfg.instrumentationKey||"_not_defined_",r=new tI,(n=new xM(e,e.diagLog(),r)).initialize(t.cfg,i),n.isInitialized()&&(lS((t=$b(n.config)).cfg,{channelConfiguration:{g:function(){return t.cfg.extensionConfig[c.identifier]}},propertyConfiguration:{g:function(){return t.cfg.extensionConfig[l.identifier]}}}),c&&(d=DM(c.identifier,t.cfg))),m&&n.setCookieMgr(m))}function T(i,n){var r=[],s=t.cfg,a={};if(iS(s.extensionConfig,(function(e,t){e===c.identifier||e===l.identifier||Ly(e,"Symbol(")||(e!==IM?MM(a,e,t):(a[e]={},RM(a[e],t)))})),n){n.extensions&&n.extensions.length>0&&(r=ly(r,n.extensions));var o=n.extensionConfig;o&&(tS(o,c.identifier)&&vS(o).length>0&&__(e.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),RM(a,o))}var d={instrumentationKey:i,channels:E(n),extensions:r,extensionConfig:a};return RM(d,n),d}function E(e){var i=t.cfg,n=[[]];return i.channels&&cy(i.channels,(function(e,t){Gv(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),e&&e.channels&&cy(e.channels,(function(e,t){Gv(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),n}function b(e){var t=[];return i&&i.length>0&&(t=t.concat(i)),e&&e.length>0&&(t=t.concat(e)),t}v(),e.diagLog=function(){return u||(u=new E_(t.cfg)),u},e.getCookieMgr=function(){return C(),m||n.getCookieMgr()},e.setCookieMgr=function(e){m=e,n&&n.setCookieMgr(e)},e.getPerfMgr=function(){return g||t&&t.cfg.enablePerfMgr&&(g=f||new aI(e.getNotifyMgr())),g},e.setPerfMgr=function(e){f=e,g=e},e.create=function(i,r){p?__(e.diagLog(),2,514,"Shared Manager has already been initialized."):(t=e_(function(e){if(e&&zv(e.extensionConfig)){var t=e.extensionConfig,i={};iS(t,(function(e,t){Gv(t)||Ly(e,"Symbol(")||(i[e]=t)})),e.extensionConfig=i}return e}(i?ZE({},i):{}),kM,null),n=null,function(){var e=t.cfg,i=e.channels,n=new WP,r=n.identifier,s=!1;c=null,d=null,cy(i,(function(e){s||cy(e,(function(e){if(!Gv(e)&&(S(e),e.identifier===r))return c=e,s=!0,-1}))})),s||(c=S(n,e.channelConfiguration),i.length>0?ly(i[0],c):e.channels.push([c]))}(),y(r),p=!0)},e.getInst=function(e){return(o[e]||{}).inst},e.newInst=function(i,s,a){var l=e.getInst(i);if(l)return __(e.diagLog(),2,514,"Instance already exists for ["+i+"]"),l;if(C(),n.isInitialized()){var u=T(i,s);if(c){var h=DM(c.identifier,u);d&&h&&d!==h&&__(e.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+d+"] is different from configured ["+h+"] shared will be used!")}var g=new NM(i,r);if(l=new xM(e,e.diagLog(),g),o[i]={iKey:i,inst:l,notifyMgr:g},l.setPerfMgr(e.getPerfMgr()),l.initialize(u,b(a)),l.isInitialized()){var p=l.config;lS(p,{propertyConfiguration:{g:function(){return p.extensionConfig[IM]}}});try{delete p.endpointUrl,delete p.channelConfiguration,delete p.propertyStorageOverride}catch(t){__(e.diagLog(),2,108,"Failed to remove unused defaults!")}iS(t.cfg,(function(e,t){tS(p,e)||Ly(e,"Symbol(")||gy(PM,e)||MM(p,e,t)}))}else __(e.diagLog(),2,520,"Failed to initialize new instance!"),l=null,delete o[i]}return l},e.getSharedPlugin=function(e){C();var t=null,i=n.getPlugin(e);return i&&(t=i.plugin),t},e.getPropertyManager=function(){return C(),l},e.getPostChannel=function(){return C(),c},e.getNotifyMgr=function(){return h||(h=new tI),h},e.unload=function(e,t,i){var r,s=vS(o),a=s.length+1,l={reason:50,isAsync:e,flushComplete:!1};function c(e,i){0==--a&&(v(),t&&t(i))}return e&&!t&&(r=oE((function(e){t=e}))),n&&(cy(s,(function(t){!function(e,t,i,n){var r=o[e];r&&(r.inst&&r.inst.isInitialized()?r.inst.unload(t,(function(e){i&&i(0,e)}),n):i&&i(0,{reason:50,isAsync:t,flushComplete:!1}))}(t,e,(function(e,t){c(0,t)}),i)})),n.isInitialized()&&(n.unload(e,(function(e){c(0,l=e)}),i),n=null)),c(0,l),r},e.addUnloadHook=function(e){C(),n.addUnloadHook(e)},e.addSharedPlugin=function(e,t,i,r){return C(),n.addPlugin(e,t,i,r)},e.updateCfg=function(e,t){return C(),n.updateCfg(e,t)},e.evtNamespace=function(){return C(),n.evtNamespace()},e.addUnloadCb=function(e){C(),n.addUnloadCb(e)},e.onCfgChange=function(e){return C(),n.onCfgChange(e)},e[AM]=function(e){e&&o.iKey&&delete o[e]}}))}return e.__ieDyn=1,e}(),xM=function(e){function t(i,n,r){var s,a=e.call(this)||this,o=i;return TC(t,a,(function(e,t){e.getSharedPropertyManager=function(){return o.getPropertyManager()},e.getSharedPostChannel=function(){return o.getPostChannel()},e.getOverridePropertyManager=function(){return s},e.initialize=function(i,a){lI(e,(function(){return"ApplicationInsights:initialize"}),(function(){var o=[s=new wM];a&&(o=o.concat(a));var l=i.propertyConfiguration||{};if(i.propertyConfiguration)try{delete i.propertyConfiguration}catch(e){i.propertyConfiguration={}}i.extensionConfig=i.extensionConfig||{},i.extensionConfig[s.identifier]=l,i=e_(i,OM,n||e.logger,!1).cfg;try{t.initialize(i,o,n,r)}catch(t){__(e.logger,1,514,"Failed to initialize SDK."+hS(t))}}),(function(){return{config:i,extensions:a}}))},e.unload=function(i,n,r){return o[AM]&&o[AM]((e.config||{}).instrumentationKey),t.unload(i,n,r)}})),a}return jy(t,e),t.__ieDyn=1,t}(zw),FM=class{constructor(e){this.key=e.config.bwSeedOptions.localStorageKey||"bwSeed";const t=localStorage.getItem(this.key);parseInt(t)||localStorage.setItem(this.key,e.config.bwSeedOptions.constValue.toString())}getSeed(){const e=localStorage.getItem(this.key),t=parseInt(e);return isNaN(t)?void 0:t}saveSeed(e){localStorage.setItem(this.key,e.toString())}static localStorageAvailable(){try{const e=window.localStorage,t="someKey",i="someValue";return e.setItem(t,i),e.removeItem(t),!0}catch(e){return!1}}},UM=class e{constructor(t){e.value??(e.value=t.config.bwSeedOptions.constValue)}getSeed(){return e.value}saveSeed(t){e.value=t}},BM=class{constructor(e){this.value=e}addValue(e){}getAggregated(){return this.value}},VM=class{addValue(e){this.value=e}getAggregated(){return this.value}},HM=class{constructor(e){this.size=e,this.items=[]}clear(){this.items=[]}},$M=class extends HM{get isFull(){return this.items.length>=this.size}add(e){return this.isFull&&this.items.shift(),this.items.push(e),!0}},jM=class extends HM{add(e){return!(this.items.length>=this.size||(this.items.push(e),0))}},GM=class{constructor(e){this.values=new $M(e)}addValue(e){this.values.add(e)}getAggregated(){return Math.floor(Yi(this.values.items))}},qM=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(e){(e||0===e)&&(this.total+=e,this.duration++,this.max=Math.max(e,this.max),0!==e&&(this.minNonZero=Math.min(e,this.minNonZero)))}},zM=class{constructor(){this.sampleCounts={}}get min(){const e=Object.keys(this.sampleCounts).map(Number).filter((e=>e>0));return e.length>0?Math.min(...e):0}get max(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?Math.max(...e):0}get mode(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?e.reduce(((e,t)=>this.sampleCounts[t]>this.sampleCounts[e]?t:e),e[0]):0}captureSample(e){var t;if(void 0!==e){const i=`${e}`;(t=this.sampleCounts)[i]??(t[i]=0),this.sampleCounts[i]++}}},WM=class{get delta(){if(void 0!==this.cur&&void 0!==this.last)return this.cur-this.last}captureSample(e,t){void 0!==e&&(void 0!==this.cur&&(this.last=this.cur),this.cur=e)}},KM=class{constructor(e=0){this.precision=e}get delta(){if(void 0!==this.currentSample&&void 0!==this.prevSample){let e=1;return void 0!==this.currentTimestamp&&void 0!==this.prevTimestamp&&(e=(this.currentTimestamp-this.prevTimestamp)/1e3),e&&mn((this.currentSample-this.prevSample)/e,this.precision)}}captureSample(e,t){if(this.currentTimestamp!==t){if(void 0===e)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=t,this.currentSample=e}}},JM=class{constructor(){this.startTime=Date.now()}get elapsed(){return mn((Date.now()-this.startTime)/1e3,0)}},YM=class{constructor(e){this.numOfHistogramSamples=e,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 qM}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 nn(this.timestampBuckets)}get counts(){return nn(this.countBuckets)}set active(e){if(!this.current&&e)this.current=new JM;else if(this.current&&!e){const e=this.current.elapsed;this.averager.captureSample(e),this.totalActiveDuration+=e;for(const t of Object.keys(Gi.HISTOGRAM_BATCH))if(e<=Gi.HISTOGRAM_BATCH[t]){this.countBuckets[t]++,Sn(this.timestampBuckets[t],this.current.startTime,this.numOfHistogramSamples);break}this.eventCount++,this.current=void 0}}},QM=class{constructor(){this.sampleChangeCount=0,this.sampleDurations={}}get durations(){return nn(this.sampleDurations)}get sortedDurations(){return Object.keys(this.sampleDurations).sort(((e,t)=>this.sampleDurations[t]-this.sampleDurations[e]))}get durationRatios(){const e={};let t=0;for(const e in this.sampleDurations)t+=this.sampleDurations[e];for(const i in this.sampleDurations)e[i]=mn(this.sampleDurations[i]/t*100);return e}get changeCount(){return this.sampleChangeCount}captureSample(e){this.sampleDurations[e]||(this.sampleDurations[e]=0),this.sampleDurations[e]++,e!==this.lastSample&&(this.sampleChangeCount++,this.lastSample=e)}},ZM=class{constructor(e,t){this.validTimeBetweenFramesArrival=e,this.invalidFPSAboveMax=t,this.lastSampleTimestamp=-1,this.fpsHarmonicSumWeigtsTs=0,this.fpsHarmonicWeigtedSumsFramePerDelayTs=0}captureSample(e){const t=Date.now();if(e>0&&this.lastSampleTimestamp>0){const i=t-this.lastSampleTimestamp;if(this.lastSampleTimestamp=t,i<0||i>this.validTimeBetweenFramesArrival||e>this.invalidFPSAboveMax)return;const n=i/e;this.fpsHarmonicSumWeigtsTs+=i,this.fpsHarmonicWeigtedSumsFramePerDelayTs+=i*n}(this.lastSampleTimestamp<0||0===e)&&(this.lastSampleTimestamp=t)}get harmonicMean(){return this.fpsHarmonicWeigtedSumsFramePerDelayTs>0?1e3*this.fpsHarmonicSumWeigtsTs/this.fpsHarmonicWeigtedSumsFramePerDelayTs:0}},XM=class{constructor(e){this.samplesNum=e,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(e){void 0===e||e<0||(Sn(this.samples,e,this.samplesNum),this.sortedSamples=nn(this.samples).sort(((e,t)=>e-t)),this.lastReport={avg:this.getAvg(),median:this.calculatePercentile(50),p90:this.calculatePercentile(90),max:this.calculatePercentile(100),volatilityPercent:this.getVolatility()})}getAvg(){return Yi(this.samples)}getVolatility(){const e=this.getAvg();if(0===e)return 0;let t=0;return this.samples.forEach((i=>{t+=Math.abs(i-e)})),mn(t/this.samples.length*100/e,2)}calculatePercentile(e){if(e<0||e>100)throw new Error("Percentile must be between 0 and 100");const t=e/100*(this.sortedSamples.length-1),i=Math.floor(t),n=Math.ceil(t),r=t-i;return n>=this.sortedSamples.length?this.sortedSamples[i]:this.sortedSamples[i]*(1-r)+this.sortedSamples[n]*r}},eD=class{constructor(){this.duration=0,this.reportAggr={avg:0,max:0,median:0,p90:0,volatilityPercent:0}}captureSample(e){!e||e.avg<0||(this.reportAggr={avg:this.reportAggr.avg+e.avg,max:Math.max(this.reportAggr.max,e.max),median:this.reportAggr.median+e.median,p90:this.reportAggr.p90+e.p90,volatilityPercent:this.reportAggr.volatilityPercent+e.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}}},tD=class{constructor(e,t=0){this.overshootType=e,this.allowedOvershoot=t,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(e,t){const i=mn(e-t);i>this.allowedOvershoot&&(0===this.lastAllowed||t===this.lastAllowed||!this.current&&t>this.lastAllowed)?(this.totalOvershootDuration++,this.current?(this.current.min=Math.min(this.current.min,i),this.current.max=Math.max(this.current.max,i)):this.current={timestamp:Date.now(),min:i,max:i,type:this.overshootType}):this.current&&(this.current.duration=Date.now()-this.current.timestamp,this.past.push(this.current),this.current=void 0),this.lastAllowed=t}},iD=class{constructor(e=!1){this.disableNormalization=e,this.prevLost=0,this.prevReceived=0,this.minPackets=100}calculate(e,t){if(void 0===e||void 0===t)return;const i=e-this.prevReceived,n=t-this.prevLost;if(i+n<this.minPackets)return;this.prevReceived=e,this.prevLost=t;const r=n*(this.disableNormalization?1:this.minPackets)/(n+i);return r>(this.disableNormalization?1:this.minPackets)?0:r}},nD=class{constructor(){this.capturedSamples=[]}captureSample(e){e&&this.capturedSamples.push(e)}calculateStd(){if(!this.capturedSamples.length)return;const e=this.capturedSamples.reduce(((e,t)=>e+t),0)/this.capturedSamples.length,t=this.capturedSamples.map((t=>(t-e)**2)),i=t.reduce(((e,t)=>e+t),0)/t.length;return mn(Math.sqrt(i),2)}getFirst(){return this.capturedSamples[0]}getLast(){if(this.capturedSamples.length)return this.capturedSamples[this.capturedSamples.length-1]}calculatePercentile(e){if(!this.capturedSamples.length)return;const t=this.capturedSamples.sort(((e,t)=>e-t)),i=(t.length-1)*e,n=Math.floor(i),r=i-n;return void 0!==t[n+1]?t[n]+r*(t[n+1]-t[n]):t[n]}};function rD(e){if(!e)return;const t=["libvpx","ffmpeg"];let i=!0;for(const n of t)if(e.toLowerCase().includes(n)){i=!1;break}return i}var sD=class{constructor(e){this.samplesCount=e,this.capturedSamples=[]}captureSample(e){void 0!==e&&Sn(this.capturedSamples,e,this.samplesCount)}getRate(){if(!this.capturedSamples.length)return;const e=this.samplesCount/this.capturedSamples.length;return this.capturedSamples.reduce(((e,t)=>e+t))*e/this.samplesCount}},aD=class{constructor(e=5){this.limit=e,this.curWidth=0,this.curHeight=0,this.resolutionSwitches=[]}captureSample(e,t){e===this.curWidth&&t===this.curHeight||(Sn(this.resolutionSwitches,`${e}x${t}`,this.limit),this.curWidth=e,this.curHeight=t)}get switches(){if(this.resolutionSwitches.length)return this.resolutionSwitches}};function oD(e,t,i){return e&&t?Math.ceil(e/Gi.MACROBLOCK_SIZE)*Math.ceil(t/Gi.MACROBLOCK_SIZE)*i:0}var lD=class{constructor(){this.macroblockRateAveragerReceived=new qM,this.macroblockRateAveragerDecoded=new qM,this.maxDecoderLoss=0,this.decoderLoss=0}captureSample(e,t){this.macroblockRateAveragerReceived.captureSample(e),this.macroblockRateAveragerDecoded.captureSample(t);let i=this.maxDecoderLoss;e&&(i=(e-t)/e*100),this.decoderLoss=i,this.maxDecoderLoss=Math.max(i,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)}}},cD=class{constructor(){this.codecReport={}}captureSample(e,t){var i,n;const r=e.split("/").pop();return void 0===this.activeMsi||this.activeMsi!==t?(this.activeMsi=t,this.previousCodec=r,void((i=this.codecReport)[t]??(i[t]={[r]:1,codecSwitchCounter:0}))):this.previousCodec!==r?((n=this.codecReport[t])[r]??(n[r]=0),this.codecReport[t][r]++,this.codecReport[t].codecSwitchCounter++,void(this.previousCodec=r)):void this.codecReport[t][r]++}get report(){return this.codecReport}},dD=class{constructor(e=5){this.limit=e,this.curPowerEfficientCodecState=!1,this.powerEfficientCodecEvents=[],this.powerEfficientCodecEventOnCount=0,this.powerEfficientCodecEventOffCount=0}captureSample(e,t){if(e!==this.curPowerEfficientCodecState){const i={timestamp:Date.now(),powerEfficient:e,frameHeight:t};Sn(this.powerEfficientCodecEvents,i,this.limit),this.curPowerEfficientCodecState=e,e?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}},uD=class{constructor(){this.bandwidthAverager=new qM}addValue(e){this.bandwidthAverager.captureSample(e)}getAggregated(){return Math.floor(this.bandwidthAverager.avg)}},hD=class{constructor(e){this.configProvider=e,this.aggregator=this.getAggregator(),this.storage=this.getStorage(),this.cappingValue=this.configProvider.config.bwSeedOptions.cappingValue,this.minValue=this.configProvider.config.bwSeedOptions.minValue??-1}getSeed(){const e=this.storage.getSeed()??-1;return this.cappingValue>0?Math.min(Math.max(e,this.minValue),this.cappingValue):Math.max(e,this.minValue)}saveSeed(e){this.aggregator.addValue(e);const t=this.aggregator.getAggregated();this.storage.saveSeed(t)}getAggregator(){switch(this.configProvider.config.bwSeedOptions.aggregation){case"avg":return this.configProvider.config.bwSeedOptions.aggregateLastN>0?new GM(this.configProvider.config.bwSeedOptions.aggregateLastN):new uD;case"last":return new VM;default:return new BM(this.configProvider.config.bwSeedOptions.constValue)}}getStorage(){return this.configProvider.config.bwSeedOptions.useLocalStorage&&FM.localStorageAvailable()?new FM(this.configProvider):new UM(this.configProvider)}},gD=Z;function pD(e,t){const i=e.width/e.height,n=(0,gD.clone)(e);return i>t?n.width=Math.floor(e.height*t):i<t&&(n.height=Math.floor(e.width/t)),n}var mD=class e{constructor(e,t,i=!0,n=!1,r){this.audio=e,this.video=t,this.withTimeout=i,this.withEffect=n,this.withOverridenStream=r}clone(){const t=nn(this.video),i=nn(this.audio);return new e(i,t,this.withTimeout,this.withEffect,this.withOverridenStream)}},fD=class{constructor(e){this.logger=e}dispose(){}updateVideoConstraints(e,t,i){const n=this.calculateConstraints(t,i);this.logger.safe.info(`Calculated constraints: ${JSON.stringify(n)} from capabilities: ${JSON.stringify(t)}`);const r=n.resolution,s=n.fps,a=r&&(!dn(r.width,e.video.minWidth,e.video.maxWidth)||!dn(r.height,e.video.minHeight,e.video.maxHeight)),o=e.video.fps!==s;if(!a&&!o)return e;const l=e.clone();return a&&this.setResolution(l,r),o&&(l.video.fps=s),l}updateResolution(e,t){const i=e.clone();return this.setResolution(i,t),i}setResolution(e,t){e.video.maxWidth=t.width,e.video.minWidth=t.width,e.video.maxHeight=t.height,e.video.minHeight=t.height}getKey(e){return e.video?Xi(e.video)?"video":e.video.deviceId&&e.video.minWidth&&e.video.minHeight?`${e.video.deviceId}x${e.video.minWidth}x${e.video.minHeight}`:e.video.minWidth&&e.video.minHeight?`${e.video.minWidth}x${e.video.minHeight}`:e.video.deviceId?`${e.video.deviceId}`:(this.logger.safe.error(`Cannot create key for constraints: ${hm(e)}`),""):"audio"}convertConstraints(e,t={}){if(!e)return null;const i=nn(t);return e?.deviceId&&(i.deviceId=e.deviceId),i}},vD=class{constructor(){this.MAX_SHARING_WIDTH=1920,this.MAX_SHARING_HEIGHT=1080}getResolutionTable(e,t){const i=this.constraintToMaxResolution(e,t);return this.generateResolutionTable(i)}constraintToMaxResolution(e,t){const i=this.getPortraitOrLandscapeMaxResolution(e),n=pD({width:e.width,height:e.height},t),r=i.width/n.width,s=i.height/n.height,a=Math.min(r,s);return this.resizeResolution(n,a)}resizeResolution(e,t){return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}getPortraitOrLandscapeMaxResolution(e){return e.width>e.height?{width:this.MAX_SHARING_WIDTH,height:this.MAX_SHARING_HEIGHT}:{width:this.MAX_SHARING_HEIGHT,height:this.MAX_SHARING_WIDTH}}ceilToMackroblockSize(e){const t=e.width,i=e.height;return{width:Math.ceil(t/Gi.MACROBLOCK_SIZE)*Gi.MACROBLOCK_SIZE,height:Math.ceil(i/Gi.MACROBLOCK_SIZE)*Gi.MACROBLOCK_SIZE}}generateResolutionTable(e){return[1,2/3,1/3,1/6].map((t=>this.resizeResolution(e,t))).map((e=>this.ceilToMackroblockSize(e)))}},SD=class{constructor(e){this.logger=e,this.FPS_TABLE=[15,7.5,3.75,1.875],this.resolutionTableCalculator=new vD,this.initialAspectRatio=null}calculateConstraints(e,t){this.initialAspectRatio||(this.initialAspectRatio=t.width/t.height);const i=this.resolutionTableCalculator.getResolutionTable(t,this.initialAspectRatio);let n={resolution:i[i.length-1],fps:this.FPS_TABLE[this.FPS_TABLE.length-1]};return i.some((t=>{const i=this.getFs(t);return this.FPS_TABLE.some((r=>{const s=this.getMbps(i,r);return i<=e.maxFs&&r<=e.maxFps&&s<=e.maxMbps&&(n={resolution:t,fps:r},!0)}))}))?this.logger.safe.info(`Calculated resolution: ${JSON.stringify(n)}`):this.logger.safe.error(`None of available resolutions are suitable: ${JSON.stringify(i)}. Fallback to: ${JSON.stringify(n)}`),n}getMbps(e,t){return e*t}getFs(e){return Math.ceil(e.width/Gi.MACROBLOCK_SIZE)*Math.ceil(e.height/Gi.MACROBLOCK_SIZE)}},yD=class{constructor(e,t){this.logger=e,this.maxCapabilities=t}ensureValidity(e){this.throwIfMissing(e);const t=this.calculateMissing(e);return this.maxCapabilities&&this.applyMaxCapabilities(t),this.logger.safe.info(`Validating capabilities ${JSON.stringify(t)}`),t}throwIfMissing(e){if(!e.maxFs&&!e.maxMbps&&!e.maxFps||e.maxFs&&!e.maxMbps&&!e.maxFps||!e.maxFs&&e.maxMbps&&!e.maxFps||!e.maxFs&&!e.maxMbps&&e.maxFps)throw new Error(`Missing video capabilities ${JSON.stringify(e)}`)}calculateMissing(e){const t=tn(e);return!e.maxFs&&e.maxMbps&&e.maxFps&&(t.maxFs=e.maxMbps/e.maxFps),e.maxFs&&!e.maxMbps&&e.maxFps&&(t.maxMbps=e.maxFs*e.maxFps),e.maxFs&&e.maxMbps&&!e.maxFps&&(t.maxFps=e.maxMbps/e.maxFs),t}applyMaxCapabilities(e){this.maxCapabilities.maxFs&&(e.maxFs=Math.min(e.maxFs,this.maxCapabilities.maxFs)),this.maxCapabilities.maxMbps&&(e.maxMbps=Math.min(e.maxMbps,this.maxCapabilities.maxMbps)),this.maxCapabilities.maxFps&&(e.maxFps=Math.min(e.maxFps,this.maxCapabilities.maxFps))}},CD=class extends fD{constructor(e,t){super(e),this.initialConstraints={maxWidth:1920,minWidth:1920,maxHeight:1080,minHeight:1080,fps:15},this.maxCapabilities={maxFs:8160,maxFps:15},this.validator=new yD(this.logger.createChild("CV"),this.maxCapabilities),this.constraintsCalculator=new SD(this.logger.createChild("CC")),t.config.resizeModeForSharing&&(this.initialConstraints.resizeMode=t.config.resizeModeForSharing)}createConstraintsObject(e){if(!e.sharing)throw new Error(`Sharing constraints are not presented: ${JSON.stringify(e)}`);const t=this.convertConstraints(e.sharing,this.initialConstraints),i=e.audio?e.audio:null;return i?.deviceId===Gi.SYSTEM_AUDIO_SOURCE_ID&&delete i.deviceId,new mD(i,t,!1,!1,e.withOverridenStream)}generatePolicies(e){return[e]}calculateConstraints(e,t){this.logger.safe.info(`Stream resolution is ${JSON.stringify(t)}`);const i=this.validator.ensureValidity(e);return this.constraintsCalculator.calculateConstraints(i,t)}},TD=class extends CD{constructor(e,t,i){super(e,i);const n=t.screen.width/t.screen.height;n<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 r=pD({width:this.initialConstraints.maxWidth,height:this.initialConstraints.maxHeight},n);[this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[r.width,r.height],r=pD({width:this.initialConstraints.minWidth,height:this.initialConstraints.minHeight},n),[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[r.width,r.height]}},ED=class extends fD{constructor(e,t){super(t),this.configProvider=e}get currentMaxFS(){return this.streamConstraintsMaxFS??this.configProvider.config.webrtcCameraOpenFs}createConstraintsObject(e){const t={};void 0!==e.audioProcessingFlags&&(Ot.isEngine("Chromium","ChromiumAVD")?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags),this.configProvider.config.useGoogPrefixAudioConstraints&&(t.googAutoGainControl=!!(1&e.audioProcessingFlags),t.googAutoGainControl2=!!(1&e.audioProcessingFlags),t.googEchoCancellation=!!(2&e.audioProcessingFlags),t.googHighpassFilter=!!(4&e.audioProcessingFlags),t.googNoiseSuppression=!!(4&e.audioProcessingFlags),t.googTypingNoiseDetection=!!(4&e.audioProcessingFlags))):Ot.isEngine("Safari","Firefox")?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags)):this.logger.warn(`Unsupported browser engine for audio processing flags ${Ot.getBrowserInfo().engine}`));const i=this.convertConstraints(e.audio,t);this.streamConstraintsMaxFS=e.videoMaxFS;const n=this.convertConstraints(e.video,this.initialVideoConstraints(this.currentMaxFS));return new mD(i,n,e.withTimeout,e.withEffect,e.withOverridenStream)}calculateConstraints(e){const t=Math.min(e.maxFs,this.currentMaxFS);return{resolution:Hn.Send.getResolutionByFs(t),fps:e.maxFps}}initialVideoConstraints(e){const t=Hn.Send.getResolutionByFs(e);return{maxWidth:t.width,minWidth:t.width,maxHeight:t.height,minHeight:t.height,fps:this.configProvider.config.maxCameraOpenFps}}},bD=class{static getProvider(e,t,i){if("ScreenShare"===e){const e=i.createChild("SharingCP");return Ot.isBrowser("Safari")?new TD(e,Mp.window,t):new CD(e,t)}return new ED(t,i.createChild("VideoCP"))}},_D=class{constructor(e,t,i){this.error=e,this.constraints=t,this.configProvider=i,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 e;switch(this.error.name){case"SourceUnavailableError":case"TrackStartError":case"NotReadableError":case"AbortError":e={type:Gi.MEDIA_ERROR.sourceUnavailableError,detail:`media device is already used by another process: ${tt(this.error)}`};break;case"ConstraintNotSatisfiedError":case"OverconstrainedError":e={type:Gi.MEDIA_ERROR.constraintNotSatisfiedError,detail:`could not obtain constrained media stream: ${tt(this.error)}`};break;case"DevicesNotFoundError":case"NotFoundError":e=this.configProvider.config.permissionDeniedUFDWorkaround?{type:Gi.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${tt(this.error)}`}:{type:Gi.MEDIA_ERROR.devicesNotFoundError,detail:`specified device not found: ${tt(this.error)}`};break;case"NotAllowedError":e=this.permissionDeniedBySystemErrorMsg.some((e=>e===this.error.message))?{type:Gi.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${tt(this.error)}`}:{type:Gi.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${tt(this.error)}`};break;case"PermissionDeniedError":case"PermissionDismissedError":e={type:Gi.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.extensionNotFoundError:e={type:Gi.MEDIA_ERROR.extensionNotFoundError,detail:`extension is not found: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.chromeRuntimeNotDefinedError:e={type:Gi.MEDIA_ERROR.chromeRuntimeNotDefinedError,detail:`chrome runtime is not defined: ${tt(this.error)}`};break;case Gi.MEDIA_ERROR.sharingCancelledError:e=this.getSharingCancelledError(this.error);break;case Gi.MEDIA_ERROR.mediaStreamRequestTimedOut:e={type:Gi.MEDIA_ERROR.mediaStreamRequestTimedOut,detail:"Media Stream request timed out."};break;default:e=this.error.message===Gi.MEDIA_ERROR.sharingCancelledError?this.getSharingCancelledError(this.error):{type:Gi.MEDIA_ERROR.mediaStreamRequestError,detail:`media stream request error: ${tt(this.error)}`}}return e.isAudio=!!this.constraints.audio,e.detail+=` constraints: ${tt(hm(this.constraints))}`,e.message=e.detail,e}getSharingCancelledError(e){return{type:Gi.MEDIA_ERROR.sharingCancelledError,detail:`screen sharing cancelled: ${tt(e)}`}}},ID=class{constructor(e,t){this.logger=e,this.configProvider=t}static isSupported(){return!0}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be applied: ${JSON.stringify(hm(t))}`),new Promise(((e,i)=>{Mp.window.navigator.getUserMedia(t,e,i)})).catch((t=>{throw new _D(t,e,this.configProvider).getMediaError()}))}applyConstraints(e,t){if(!e?.getVideoTracks()?.[0])return Promise.reject("No video tracks found");const i=e.getVideoTracks()[0];return this.applyConstraintsForTrack(i,t)}applyConstraintsForTrack(e,t){const i=this.constraintsAdapter.toTrackConstraints(t);return e.applyConstraints?(this.logger.safe.info(`Apply constraints: ${JSON.stringify(i)} on ${JSON.stringify(e.id)}`),e.applyConstraints(i).catch((e=>{throw new _D(e,t,this.configProvider).getMediaError()}))):Promise.reject("track.applyConstraints() is not supported")}},wD=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};return e.audio&&(t.audio=nn(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Gi.MEDIA_DEVICE.defaultId&&(t.audio.deviceId=e.audio.deviceId)),e.video&&(t.video={mandatory:{}},e.video.deviceId&&(t.video.mandatory.sourceId=e.video.deviceId),e.video.minWidth&&(t.video.mandatory.minWidth=e.video.minWidth),e.video.maxWidth&&(t.video.mandatory.maxWidth=e.video.maxWidth),e.video.minHeight&&(t.video.mandatory.minHeight=e.video.minHeight),e.video.maxHeight&&(t.video.mandatory.maxHeight=e.video.maxHeight),e.video.fps&&(t.video.mandatory.maxFrameRate=e.video.fps,this.configProvider.config.setMinFpsForWebkit&&(t.video.mandatory.minFrameRate=this.configProvider.config.minCameraOpenFps,t.video.mandatory.idealFrameRate=e.video.fps)),Xi(t.video.mandatory)&&delete t.video.mandatory),t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},AD=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};if(e.audio&&(t.audio=nn(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Gi.MEDIA_DEVICE.defaultId&&(t.audio.deviceId={exact:e.audio.deviceId})),e.video){t.video={width:{},height:{},frameRate:{}},e.video.deviceId&&(t.video.deviceId={exact:e.video.deviceId}),e.video.minWidth&&(t.video.width.min=e.video.minWidth),e.video.maxWidth&&(t.video.width.max=e.video.maxWidth),e.video.minHeight&&(t.video.height.min=e.video.minHeight),e.video.maxHeight&&(t.video.height.max=e.video.maxHeight),e.video.fps&&(t.video.frameRate.max=e.video.fps,t.video.frameRate.min=this.configProvider.config.minCameraOpenFps,t.video.frameRate.ideal=e.video.fps);for(const e in t.video)Xi(t.video[e])&&delete t.video[e]}return t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},PD=class{toGumConstraints(e){if(!e?.video)throw new Error(`constraints cannot be applied: ${e}`);const t={video:{}},i=e.video.deviceId&&e.video.deviceId!==Gi.DISPLAY_SOURCE_ID;return e.video.resizeMode&&(t.video.resizeMode=e.video.resizeMode),i&&(t.video.deviceId={exact:e.video.deviceId}),e.video.maxWidth&&(t.video.width={max:e.video.maxWidth},i&&(t.video.width.ideal=e.video.maxWidth)),e.video.maxHeight&&(t.video.height={max:e.video.maxHeight},i&&(t.video.height.ideal=e.video.maxHeight)),e.video.fps&&(t.video.frameRate=e.video.fps),e.audio&&(t.audio=!e.audio.deviceId||{deviceId:{exact:e.audio.deviceId}}),t}toTrackConstraints(e){const t=navigator.mediaDevices.getSupportedConstraints();if(!t)throw new Error("Constraints are not supported by browser");const i={};return t.width&&e.video.minWidth&&(i.width=e.video.minWidth),t.height&&e.video.minHeight&&(i.height=e.video.minHeight),t.frameRate&&e.video.fps&&(i.frameRate=e.video.fps),i.resizeMode=e.video.resizeMode,i}},RD=class extends ID{constructor(e,t){if(super(t.createChild("WebRTCProvider"),e),this.timeoutId=null,void 0!==navigator.webkitGetUserMedia&&void 0!==webkitRTCPeerConnection&&Ap()){if(!this.configProvider.config.overrideGumFromWebkit||!Ip)return void(this.constraintsAdapter=new wD(e));this.logger.safe.info("Overriding getUserMedia from webkit"),Rp()}this.constraintsAdapter=new AD(e)}getStream(e){if(!e.withTimeout||!this.configProvider.config.gumRequestTimeout)return super.getStream(e);const t=this.startGumRequestTimer(e),i=super.getStream(e).then((t=>{if(!this.timeoutId)throw this.stopStreamAfterTimeout(t,e),this.getMediaStreamTimeoutError(e);return this.stopGumRequestTimer(),t}));return Promise.race([t,i]).catch((e=>{throw this.stopGumRequestTimer(),e}))}getMediaStreamTimeoutError(e){const t={name:Gi.MEDIA_ERROR.mediaStreamRequestTimedOut,message:`Media stream request timed out. Constraints: ${tt(hm(e))}`};return new _D(t,e,this.configProvider).getMediaError()}startGumRequestTimer(e){return new Promise(((t,i)=>{this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,i(this.getMediaStreamTimeoutError(e))}),this.configProvider.config.gumRequestTimeout)}))}stopGumRequestTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}stopStreamAfterTimeout(e,t){this.logger.safe.info(`Stopping media stream acquired after timeout: ${JSON.stringify(e.id)} with constraints: ${JSON.stringify(t)}`);try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${tt(e)}`)}}},MD=class extends ID{constructor(e,t){super(e.createChild("WebRTCDispProvider"),t),this.constraintsAdapter=new PD}static isSupported(){return!!window.navigator.mediaDevices.getDisplayMedia}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be used: ${JSON.stringify(t)}`),Promise.resolve().then((()=>e.video?.deviceId&&e.video?.deviceId!==Gi.DISPLAY_SOURCE_ID?Mp.window.navigator.mediaDevices.getUserMedia(t):Mp.window.navigator.mediaDevices.getDisplayMedia(t))).catch((t=>{throw new _D(t,e,this.configProvider).getMediaError()}))}},DD=class{constructor(e){this.detail=e}getStream(e){throw this.getError(e)}applyConstraints(e,t){throw this.getError(t)}applyConstraintsForTrack(e,t){throw this.getError(t)}getError(e){return{type:Gi.MEDIA_ERROR.unsupportedStream,detail:this.detail,message:this.detail,isAudio:!!e.audio}}},kD=class{static getStreamProvider(e,t,i){return"ScreenShare"===e?MD.isSupported()?new MD(i,t):(i.error("GUM stream provider cannot be created for display stream"),new DD("Sharing not supported")):new RD(t,i)}},OD=[30,15,7.5,3.75,1.875];function ND(e){return e?.getVideoTracks?.()[0]?LD(e.getVideoTracks()[0]):null}function LD(e){const t=e?.getSettings?.();return t?{width:t.width,height:t.height}:null}function xD(e){return e?.getVideoTracks?.()[0]?FD(e.getVideoTracks()[0]):0}function FD(e){const t=e?.getSettings?.();return t?cn(OD,t.frameRate,!0):0}var UD=class extends Vi{constructor(e,t,i,n,r,s,a){super(a),this.id=e,this.masterStream=t,this.currentConstraints=i,this.constraintsProvider=n,this.streamProvider=r,this.configProvider=s,this._isDisposed=!1,this.masterStreamSubscriptions=[],this.mixerSubscriptions=[],this.parentId=t.id,this.logger=a.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}getMasterStream(){return this.masterStream}dispose(e){this._isDisposed||(this._isDisposed=!0,this.logger.safe.info(`dispose: ${e}`),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(e){if(!this.mediaTrack)return!1;const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t||!this.configProvider.config.recoverOnStreamUnmute&&this.currentConstraints===t)return!1;const i=async e=>{try{return await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t,!0}catch(t){if(e)throw this.logger.safe.error(`Apply constraints error: ${JSON.stringify(t)}`),t;return this.logger.safe.warn(`Apply constraints failed and will be re-tried, error ${JSON.stringify(t)}`),!1}},n=this.currentConstraints.withEffect&&this.configProvider.config.effectsApplyConstraintsRetryMs;return!await i(!n)&&n&&(await Yt(this.configProvider.config.effectsApplyConstraintsRetryMs),await i(!0)),!0}start(){return this.masterStream.start()}clone(e){return this.masterStream||this.logger.safe.error(`clone: master stream is null, reason: ${e}`),this.masterStream.getClient(`streamclient: ${e}`)}setMuted(e,t){this.isMuted=e,this.applyState(t)}setHold(e,t){this.isHold=e,this.applyState(t)}isSameStream(e){return this.parentId===e.parentId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=LD(this.mediaTrack),i=t?.width?t:e,n=`Track resolution is ${i.width}x${i.height}.`;return t?.width?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=FD(this.mediaTrack);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}update(e){e?this.mediaTrack?this.logger.safe.error(`Media track is already created: ${this.mediaTrack.id}`):(this.mediaTrack=this.getTrackByMediaType(e,this.mediaType),this.updateTrackConstraints(),this.subscribeOnMediaTrackEvents(this.mediaTrack),this.hasMasterAudio=e&&e.getAudioTracks().length>0,this.hasMasterVideo=e&&e.getVideoTracks().length>0,this.hasMasterAudio&&this.hasMasterVideo&&(this.rawMediaStream=e),this.logger.safe.info(`Updated: ${Sm(e)}`)):this.logger.safe.error("No master media stream, skipping update")}resetEffectsOutputConstraints(e){this.masterStream.resetEffectsOutputConstraints(e)}async updateTrackConstraints(){if("ScreenShare"!==this.mediaType)return;const e=this.masterStream.getResolution();if(e){const t=this.currentConstraints.clone();t.video.maxWidth=e.width,t.video.minWidth=e.width,t.video.maxHeight=e.height,t.video.minHeight=e.height;try{await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t}catch(e){this.logger.safe.error(`Apply constraints error: ${JSON.stringify(e)}`)}}}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}applyState(e){void 0!==this.mediaTrack?.enabled&&(this.mediaTrack.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`[${e}] Track ${JSON.stringify(this.mediaTrack.id)} enabled state set to => ${this.mediaTrack.enabled}`))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`),this.event("onStreamClientEnded").raise(this,t)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`),this.event("onStreamClientMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.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((e=>e.dispose())),this.mixerSubscriptions=[]}subscribeOnMasterStreamEvents(){this.masterStreamSubscriptions.push(this.masterStream.on("onStreamStarted",((e,t)=>this.event("onStreamClientStarted").raise(this,t))),this.masterStream.on("onStreamError",((e,t)=>this.event("onStreamClientError").raise(this,t))),this.masterStream.on("onStreamTrackMuted",((e,t)=>this.event("onStreamClientMuted").raise(this,t))),this.masterStream.on("onStreamDisposing",(e=>this.dispose())),this.masterStream.on("onStreamQualityChanged",((e,t,i,n)=>this.event("onStreamQualityChanged").raise(this,t,i,n))),this.masterStream.on("onStreamTrackEnded",((e,t)=>this.event("onStreamClientEnded").raise(this,t))))}unsubscribeFromMasterStreamEvents(){this.masterStreamSubscriptions.forEach((e=>e.dispose())),this.masterStreamSubscriptions=[]}hasAudio(){return this.hasMasterAudio}hasVideo(){return this.hasMasterVideo}isActive(){return this.mediaTrack?.enabled&&!this.mediaTrack?.muted&&"live"===this.mediaTrack?.readyState}onVideoStreamQualityChanged(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.masterStream.onVideoStreamQualityChanged(e,t,i)}isDisposed(){return this._isDisposed}},BD=class extends Vi{constructor(e,t,i,n,r,s){super(s),this.stream=e,this.constraints=t,this.constraintsProvider=i,this.gumStreamProvider=n,this.configProvider=r,this.logger=s,this.clients=[],this.streams=[],this.clientId=0,this.mediaStreamSubscription=this.stream.on("onStreamAcquired",(()=>this.onStreamAcquired()))}getClient(){const e=new UD(this.clientId++,this.stream,this.constraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger);return this.addClient(e),e}disposeClient(e){this.removeClient(e),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((e=>e.id)))}`),this.streams.forEach((e=>this.disposeStream(e))),super.dispose()}getOrCreateStream(){const e=this.streams.length?this.streams[this.streams.length-1]:this.stream.rawStream;if(!e)return null;const t=e.clone();return this.logger.safe.info(`Cloned: ${Sm(e)} -> ${Sm(t)}`),this.resetStream(t),this.streams.push(t),t}addClient(e){this.updateClient(e),this.clients.push(e)}updateClient(e){const t=this.getOrCreateStream();t&&e.update(t)}removeClient(e){const t=this.clients.indexOf(e);this.clients.splice(t,1)}addStream(){this.clients.forEach((e=>this.updateClient(e)))}disposeStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Stopping track: ${JSON.stringify(e.id)}`),e.stop()}))}onStreamAcquired(){this.addStream()}resetStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Resetting state for track: ${e.id}`),e.enabled=!0}))}},VD=class{constructor(){}getPolicies(e){if(e.audio&&!e.video&&this.hasAudioProcessingConstraints(e))return[e,new mD({deviceId:e.audio.deviceId},null)];if(!e.video)return[e];const t=this.getSuitableResolutions(e).map((t=>this.getConstraintsForResolution(e,t))),i=e.audio,n={deviceId:e.video.deviceId},r=new mD(i,n,e.withTimeout);return t.push(r),t}getSuitableResolutions(e){return Hn.Send.getResolutions().filter((t=>t.width<=e.video.maxWidth&&t.height<=e.video.maxHeight)).reverse()}getConstraintsForResolution(e,t){const i=e.clone();return i.video.minWidth=t.width,i.video.minHeight=t.height,i}hasAudioProcessingConstraints(e){const t=e&&e.audio;return t&&(void 0!==t.echoCancellation||void 0!==t.autoGainControl||void 0!==t.noiseSuppression)}},HD=class{static getStrategy(e,t,i,n,r,s){return s?new qD(i,n):"Video"===e?new GD(t,i,n,r):new jD(t,i,n)}},$D=class{constructor(e,t,i){this.gumStreamProvider=e,this.serialQueue=t,this.logger=i}getStream(e){return this.logger.safe.info(`Requesting stream with constraints: ${JSON.stringify(hm(e))}`),this.serialQueue.add((()=>this.request(e)))}},jD=class extends $D{constructor(e,t,i){super(e,t,i.createChild("SimpleStrat"))}request(e){return this.gumStreamProvider.getStream(e)}},GD=class extends $D{constructor(e,t,i,n){super(e,t,i.createChild("MultStrat")),this.policyGenerator=new VD}request(e){const t=this.policyGenerator.getPolicies(e);return this.makeRequests(t)}makeRequests(e){const t=e[0];return this.logger.safe.info(`Requesting media stream with policy: ${JSON.stringify(t)}`),this.makeRequestWithPolicy(t).catch((t=>{const i=e.slice(1);if(i.length&&Gi.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("Could not obtain constrained media stream, will attempt weaker policy"),this.makeRequests(i);throw t}))}makeRequestWithPolicy(e){return this.gumStreamProvider.getStream(e)}},qD=class extends $D{constructor(e,t){super(null,e,t.createChild("WithOveriddenStreamStart"))}request(e){return new Promise(((t,i)=>t(e.withOverridenStream)))}},zD=class e extends Vi{constructor(t,i,n,r,s){super(r),this.serialQueue=i,this.configProvider=n,this.effectManager=s,this.gumRequestTime=0,this.id=e.streamId++,this.logger=r.createChild(`MediaStream:${this.id}`),this.mediaType=this.getMediaType(t),this.initialize(t)}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(e){this.event("onStreamDisposing").raise(this),this.stopMediaStream(e).catch((e=>{this.event("onStreamError").raise(this,e)})).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(e){this.clientGenerationStrategy.disposeClient(e)}getClient(e){return this.logger.safe.debug(`getClient: ${e}`),this.clientGenerationStrategy.getClient()}getOriginalMediaStream(){return this.originalMediaStream}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=ND(this.mediaStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=xD(this.mediaStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}resetEffectsOutputConstraints(e){const t=ND(this.originalMediaStream);this.effectManager.resetOutputConstraints("Video",{width:Math.min(e.width,t.width||Number.MAX_SAFE_INTEGER),height:Math.min(e.height,t.height||Number.MAX_SAFE_INTEGER)})}initialize(e){this.constraintsProvider=bD.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(e),this.gumStreamProvider=kD.getStreamProvider(this.mediaType,this.configProvider,this.logger),this.mediaStreamRequestStrategy=HD.getStrategy(this.mediaType,this.gumStreamProvider,this.serialQueue,this.logger,this.configProvider,!!this.currentConstraints.withOverridenStream),this.clientGenerationStrategy=new BD(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(e){try{await this.getOrCreateMediaStream(e),this.event("onStreamStarted").raise(this,this.currentConstraints)}catch(e){throw this.event("onStreamError").raise(this,e),e}}async getOrCreateMediaStream(e){if(this.mediaStream)return Promise.resolve();const t=this.getRequestStartTimestamp(),i=await this.mediaStreamRequestStrategy.getStream(e);return this.gumRequestTime=this.getRequestDuration(t),this.handleMediaStreamRequestSuccess(i,e)}async handleMediaStreamRequestSuccess(e,t){this.logger.safe.info(`Media stream acquired: ${Sm(e)} with constraints: ${JSON.stringify(hm(t))}`),this.originalMediaStream=e,this.subscribeToTrackEvents(this.originalMediaStream),this.currentConstraints=t,this.mediaStream=await this.applyEffects(e),this.applyState(this.mediaStream),this.event("onStreamAcquired").raise(this,this.gumRequestTime,"Audio"!==this.mediaType&&this.getResolution()||void 0)}async applyEffects(e){switch(this.mediaType){case"Video":return this.getVideoEffectStream(e);case"Audio":return this.startNoiseSuppression(e);case"ScreenShare":return this.delayScreenShare(e)}return e}async delayScreenShare(e){return this.configProvider.config.useDelayedScreenShareStream?this.effectManager.startEffect("ScreenShare",e):e}async startNoiseSuppression(e){return this.configProvider.config.applyAudioEffectOnDemand&&!this.currentConstraints.withEffect?e:(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",e))}async getVideoEffectStream(e){if(!this.currentConstraints.withEffect||this.currentConstraints.withOverridenStream&&this.configProvider.config.useRawMediaApiForVideoEffects)return e;this.sub=this.effectManager.on("onVideoStreamQualityChanged",((e,t,i)=>this.onVideoStreamQualityChanged(e,t,i)));const t=await this.effectManager.startEffect("Video",e);return this.logger.safe.info(`Media stream switched: ${Sm(e)} -> ${Sm(t)}`),t}subscribeToTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=e=>{this.logger.safe.info(`Track ${t.id} ended: ${JSON.stringify(e)}`),this.event("onStreamTrackEnded").raise(this,e)},t.onmute=()=>{this.logger.safe.info(`Track ${t.id} muted`),this.event("onStreamTrackMuted").raise(this,!0)},t.onunmute=()=>{this.logger.safe.info(`Track ${t.id} unmute`),this.event("onStreamTrackMuted").raise(this,!1)})}unsubscribeFromTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=null,t.onmute=null,t.onunmute=null)}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}removeVideoEffectStream(){this.sub?.dispose(),this.effectManager.stopEffect("Video",this.mediaStream)}applyState(e){e.getAudioTracks()?.forEach((e=>this.applyAudioState(e)));const t=e.getVideoTracks()[0];this.applyVideoState(t)}applyAudioState(e){e&&(this.hasNonDefaultAudioProcessingConstraints()||"ScreenShare"===this.mediaType?this.applyContentHint(e,"music"):this.configProvider.config.defaultAudioContentHint&&this.applyContentHint(e,this.configProvider.config.defaultAudioContentHint),e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`))}applyVideoState(e){e&&("ScreenShare"===this.mediaType&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(e,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(e.id)}`))}applyContentHint(e,t){this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t}hasNonDefaultAudioProcessingConstraints(){const e=this.currentConstraints.audio;if(e){const t=this.configProvider.config.defaultAudioProcessingFlags;let i;return void 0===e.echoCancellation&&void 0===e.autoGainControl&&void 0===e.noiseSuppression||(i=0,void 0!==e.echoCancellation&&(i+=e.echoCancellation?2:0),void 0!==e.autoGainControl&&(i+=e.autoGainControl?1:0),void 0!==e.noiseSuppression&&(i+=e.noiseSuppression?4:0)),i!==t}return!1}getRequestStartTimestamp(){return Date.now()}getRequestDuration(e){return 0===e?0:Date.now()-e}stopMediaStream(e){return this.mediaStreamStartPromise?(this.logger.safe.info(`Queueing media stream stop: ${e}`),this.serialQueue.add((()=>this.stopMediaStreamInternal()))):Promise.resolve()}stopOneMediaStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${tt(e)}`)}}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(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.event("onStreamQualityChanged").raise(this,e,t,i)}};zD.streamId=0;var WD=zD,KD=class{static getStrategy(e){switch(e.config.diagnostics.performanceMonitoring.monitoringStrategy){case"decodeTime":default:return new JD(e);case"renderedFps":return new YD(e);case"rendererVolatility":return new QD(e)}}},JD=class{constructor(e){this.configProvider=e,this.decodeThresholds=this.configProvider.config.diagnostics.performanceMonitoring.decodeThresholds,this.defaultThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultThrehold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.decodeThresholds[n]||this.defaultThreshold,s=e.decodeTimeTracker.getReport();return s.median>r.maxDecodeTime&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),s.median<r.maxDecodeTime&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},YD=class{constructor(e){this.configProvider=e,this.fpsDiffThresholds=this.configProvider.config.diagnostics.performanceMonitoring.fpsDiffThresholds,this.defaultFpsDiffThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultFpsDiffThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.fpsDiffThresholds[n]||this.defaultFpsDiffThreshold,s=e.incomingFps.getReport(),a=e.rendererFps.getReport(),o=s.median-a.median;return o>=r.fpsDiff&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),o<r.fpsDiff&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},QD=class{constructor(e){this.configProvider=e,this.volatilityThresholds=this.configProvider.config.diagnostics.performanceMonitoring.volatilityThresholds,this.defaultVolatilityThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultVolatilityThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=Hn.Recv.getResolutionRecord(Math.min(e.frameHeight,e.frameWidth)).height,r=this.volatilityThresholds[n]||this.defaultVolatilityThreshold,s=e.rendererFps.getReport(),a=e.incomingFps.getReport(),o=Math.abs(s.volatilityPercent-a.volatilityPercent);return r&&o>=r&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),o<r&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},ZD=class{constructor(e,t){this.streamClient=e,this.logger=t,this.rawBaseClient=new wg((()=>this.getStream()),(()=>this.activeRawInputMediaStreamClient?.dispose()),t)}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)}},XD=class{constructor(e,t){this.logger=e,this.raiseTelemetryEvent=t,this.handlerMap=new Map([["Audio",new Map],["Video",new Map],["ScreenShare",new Map]])}dispose(e){this.logger.info(`disposing IRawStream ${e}`),this.handlerMap.get(e).forEach((e=>e.client().dispose()))}disposeAll(){this.logger.info("Dispose All clients"),this.handlerMap.forEach((e=>e.forEach((e=>e.client().dispose()))))}notifyChange(e){this.handlerMap.get(e).forEach((e=>{e.disposeActiveMediaStreamClient(),e.client().notifyStreamChange()}))}createIRawStreamClient(e,t){this.logger.info(`Create new IRawStream client for ${t}`);const i=new ZD(e,this.logger);return this.handlerAdded(i,t),i.client()}handlerAdded(e,t){const i=e.client();this.setClientSubscription(i,t),this.handlerMap.get(t).set(i.clientId,e)}deleteRawStreamManagerById(e,t){this.logger.info(`Deleting from map: ${t}`),this.handlerMap.get(t).delete(e)}setClientSubscription(e,t){this.logger.info(`Setting subscription on IRawStream client for ${t}`),e.on("clientDisposed",(i=>{this.deleteRawStreamManagerById(e.clientId,t),this.raiseTelemetryEvent("IRawStream_client_disposed",{mediaType:t,clientId:i})})),e.on("rawStreamRequested",(e=>{this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})})),e.on("notifiedOnStreamChanged",(e=>this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})))}},ek=class extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.audioRendererDiagnostics=i,this.window=Mp.window,this.isMuted=!1,this.isPlayingAllowed=!1,this.hadPlaybackError=!1,this.id=sn(),this.onAudioError=e=>{const t=e&&e.target||this.audio;if(this.hadPlaybackError=!0,t?.error){const e=t.error.code,i=`error with rendering audio code: ${e}, message: ${t.error.message}`;this.event("onAudioPlaybackError").raise(e,Gi.MEDIA_ERROR.audioPlaybackError,i),this.logger.safe.error(i)}else this.logger.safe.error("error with audio rendering")},this.onAudioPaused=async()=>{if(this.configProvider.config.audioRendererRestartOnPause&&this.canPlay&&!this.isMuted){const e=be();this.logger.safe.info(`[${e}] audio playback is paused by OS, resuming it`),await this.startStream(e)}},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(e,t){return this.isMuted=e,e?this.stopStream(t):this.startStream(t)}async getSpeakerVolume(e){const t=this.audio?.volume??0;return this.logger.safe.info(`[${e}] get speaker volume: ${t}`),t}async setSpeakerVolume(e,t){this.assureAudioElement(t),this.audio.volume=e,this.logger.safe.info(`[${t}] set speaker volume: ${e}`)}getStream(){return this.stream}getDeviceId(){return this.deviceId}async play(e){if(this.stream=e,this.isPlayingAllowed=!0,!this.isMuted)return this.startStream()}stop(){this.stopStream(),this.isPlayingAllowed=!1}async setOutputDevice(e,t=be()){if(this.audio)if(this.configProvider.config.disableAudioOutputSelection)this.logger.safe.warn(`[${t}] audio-output selection is disabled, disableAudioOutputSelection: true`);else if(this.audio.setSinkId){if(e&&e!==this.currentSinkId){this.logger.safe.info(`[${t}] setting audio output device ID to ${De(e)}`),this.deviceId=e;try{this.configProvider.config.audioSetSinkIdWorkaround&&this.stream&&!this.stream.active?(this.audio.srcObject=null,await this.audio.setSinkId(e),this.audio.srcObject=this.stream):await this.audio.setSinkId(e),this.currentSinkId=e}catch(e){this.logger.safe.warn(`[${t}] setSinkId operation was aborted with error ${tt(e)}`)}this.configProvider.config.audioRendererRestartOnDeviceError&&this.hadPlaybackError&&!this.isMuted&&(this.audioRendererDiagnostics?.registerReopenRequest(e),this.logger.safe.info(`[${t}] audio playback error happened, restarting audio stream on new device`),await this.startStream(t),this.hadPlaybackError=!1)}}else this.logger.safe.warn(`[${t}] setting output device is not supported`);else this.deviceId=e}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(e=be()){if(this.canPlay)try{await this.assureAudioElement(e),this.logger.safe.info(`[${e}] 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(t){this.logger.safe.warn(`[${e}] play operation was aborted with error ${tt(t)}`)}}async assureAudioElement(e=be()){if(!this.audio)return this.logger.safe.info(`[${e}] 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,e)}stopStream(e=be()){this.audio&&this.canPlay&&(this.detachGainNode(),this.configProvider.config.audioRendererUsePauseOnDetach?(this.logger.safe.info(`[${e}] Pausing with stream: ${this.stream?.id}`),this.audio.pause()):(this.logger.safe.info(`[${e}] Detaching from stream: ${this.stream?.id}`),this.audio.srcObject=null),this.event("onAudioStateChanged").raise(null,this.id))}attachToGainNode(e,t){this.audioContext=new Mp.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(e),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t,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(e,t){this.detachGainNode(),this.attachToGainNode(e,t)}},tk=class{constructor(e){this.logger=e,this.queue=Promise.resolve()}add(e,t=be()){let i;i=e instanceof Kt?()=>e.promise:e;const n=this.queue.then(i);return this.queue=n.catch((e=>{if(this.queue){let i="";e instanceof TypeError&&(i=e.stack),this.logger.safe.error(`[${t}] Error from promiseQueue! ${tt(e)} ${i}`)}})),n}dispose(){this.queue=null}},ik=Z,nk=(e=>(e[e.NONE=0]="NONE",e[e.VIDEO=1]="VIDEO",e[e.AUDIO=2]="AUDIO",e))(nk||{});function rk(e,t){const{rid:i,ssrc:n,frameWidth:r,frameHeight:s,framesPerSecond:a,keyFramesEncoded:o,nackCount:l,firCount:c,pliCount:d,encoderImplementation:u,qualityLimitationReason:h}=e.outboundRTP,{cameraOpenResolution:g,bitrate:p,encodeTime:m,frameRateEncoded:f,frameRateSent:v,qp:S}=e.extensions??{},{mimeType:y}=t.codec??{},{lossRate:C}=t.extensions??{},{audioLevel:T}=t.mediaSource??{};return{rid:{overlayTab:1,values:[i],hideUndefined:!0},cameraSize:{overlayTab:1,format:"{0}x{1}",values:[g?.width,g?.height]},inputSize:{overlayTab:1,format:"{0}x{1}",values:[e.mediaSource?.width,e.mediaSource?.height]},sentSize:{overlayTab:1,format:"{0}x{1}",values:[r,s]},ssrc:{overlayTab:1,values:[n]},fps:{overlayTab:1,text:"FPS(i/e/s)",format:"{0}/{1}/{2}",values:[a,f,v],lowerThreshold:7,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{overlayTab:1,format:"{0} kbps",values:[sk(p)],lowerThreshold:24},encodeTime:{overlayTab:1,format:"{0} ms",values:[m],upperThreshold:15},keyFramesEncoded:{overlayTab:1,text:"KFs",values:[o]},qp:{overlayTab:1,values:[S]},nacksFirsPlisRecv:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[l,c,d],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"encoder",values:[u],highlightUndefined:!0},qualityLimitationReason:{overlayTab:1,text:"limited",values:[h],fixedValueThreshold:"none"},bwe:{overlayTab:1,format:"{0} kbps",values:[sk(e.transport?.selectedCandidatePair?.availableOutgoingBitrate)],lowerThreshold:100},audioCodec:{overlayTab:2,values:[y?.split("/").pop()]},audioLevel:{overlayTab:2,values:[mn(T,4)]},lossRate:{overlayTab:2,values:[mn(C,4)]}}}function sk(e){return e&&Math.floor((e||0)/1e3)}var ak=class{constructor(e){this.container=e,this.formatRegexPattern=new RegExp(/{(\d+)}/g),this.elements={},this.previousSamples={},this.overlayTab=1,this.createTableCell=(e,t,i)=>{this.elements[e]=document.createElement("td"),this.elements[e].title=e,this.addElementStyle(e,i),this.elements[t].appendChild(this.elements[e])},this.topElement=e.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=function(e){const t=Object.keys(nk).filter((e=>isNaN(Number(e)))),i=(e+1)%t.length;return nk[t[i]]}(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(e,t){for(const i of Object.keys(e)){const n=e[i];n.overlayTab===this.overlayTab&&(n.hideUndefined&&n.values.every((e=>!e))||this.createTableRow(i,n,t))}}createTableRow(e,t,i){this.elements[e]||(this.elements[e]=document.createElement("tr"),this.table.appendChild(this.elements[e]));const n=`${e}-title`,r=`${e}-${i}`,s=this.formatValue(t),a=this.previousSamples[r]!==s;this.previousSamples[r]=s;const o=function(e){const{values:t,lowerThreshold:i,upperThreshold:n,highlightUndefined:r,fixedValueThreshold:s,allowedDeviationThreshold:a}=e;for(const e of t){if(void 0===e&&null===e&&r)return!0;if(s&&s!==e)return!0;if(null==e||!(0,ik.isNumber)(e))return!1;if(i&&Number(e)<=i)return!0;if(n&&Number(e)>=n)return!0;if(a){const i=(0,ik.mean)(t),n=i*a;if(Math.abs(Number(e)-i)>n)return!0}}return!1}(t)||!(!t.highlightChange||!a);this.elements[n]||(this.createTableCell(n,e,!1),this.elements[n].innerText=t.text?t.text:e),this.createTableCell(r,e,!t.suppressHighlighting&&o),this.elements[r].innerText=s}clearTable(){for(;this.table.hasChildNodes();)this.table.removeChild(this.table.lastChild);this.elements={}}getOverlayTab(){return this.overlayTab}addElementStyle(e,t){this.elements[e].style.color=t?"#F72F35":"#FBF719",this.elements[e].style.fontSize="smaller",this.elements[e].style.lineHeight="1",this.elements[e].style.padding="0px 1px 0px 1px",this.elements[e].style.maxWidth="60px",this.elements[e].style.overflow="hidden",this.elements[e].style.whiteSpace="nowrap",this.elements[e].style.textOverflow="ellipsis"}formatValue(e){const{values:t,format:i,undefinedFallback:n="N/A"}=e;return i?i.replace(this.formatRegexPattern,((e,i)=>t?.[i]?.toString()??n.toString())):t?.[0]?.toString()??n.toString()}},ok=class{constructor(e,t,i){this.container=t,this.renderer=i,this.subs=[],e&&!this.overlay&&(this.overlay=new ak(this.container),this.rendererStats={msid:()=>this.renderer.getLocalMsi(),sourceId:()=>this.renderer.getMsi()},this.subs.push(this.renderer.on("onVideoSizeChanged",((e,t)=>this.rendererStats.streamSize={width:e,height:t}))),this.subs.push(this.renderer.on("onRendererSizeChanged",((e,t)=>this.rendererStats.rendererSize={width:Math.ceil(t.width),height:Math.ceil(t.height)}))))}setStats(e,t){this.overlay&&(this.overlay.clearTable(),this.overlay.createTableColumn(function(e,t,i){const{ssrc:n,keyFramesDecoded:r,nackCount:s,firCount:a,pliCount:o,decoderImplementation:l,packetsLost:c}=e.inboundRTP,{frameRateReceived:d,frameRateDecoded:u,bitrate:h,decodeTime:g,isFrozen:p}=e.extensions??{},{sourceId:m,msid:f,streamSize:v,rendererSize:S}=i,y=e.renderer?.modality===Gi.MODALITY.sharing,{audioLevel:C}=t.inboundRTP,{mimeType:T}=t.codec??{},{healedRatio:E,lossRate:b}=t.extensions??{};return{streamSize:{overlayTab:1,format:"{0}x{1}",values:[v?.width,v?.height],undefinedFallback:0},rendererSize:{overlayTab:1,format:"{0}x{1}",values:[S?.width,S?.height],undefinedFallback:0},ssrc:{overlayTab:1,values:[n]},msid:{overlayTab:1,text:"sourceId/msid",format:"{0}/{1}",values:[m(),f()]},fps:{overlayTab:1,text:"FPS(r/d)",format:"{0}/{1}",values:[d,u],highlightUndefined:!0,lowerThreshold:1,upperThreshold:45,allowedDeviationThreshold:.2,suppressHighlighting:y},bitrate:{overlayTab:1,format:"{0} kbps",values:[sk(h)],lowerThreshold:24,suppressHighlighting:y},decodeTime:{overlayTab:1,format:"{0} ms",values:[g],upperThreshold:15,highlightUndefined:!0,suppressHighlighting:y},keyFramesDecoded:{overlayTab:1,text:"KFs",values:[r]},nacksFirsPlisSent:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[s,a,o],undefinedFallback:0,highlightChange:!0},packetsLost:{overlayTab:1,text:"lost",values:[c],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"decoder",values:[l],highlightUndefined:!0},isFrozen:{overlayTab:1,values:[p?"YES":"NO"],fixedValueThreshold:"NO"},audioCodec:{overlayTab:2,values:[T?.split("/").pop()]},audioLevel:{overlayTab:2,values:[mn(C,4)]},healedRatio:{overlayTab:2,values:[mn(E,4)],upperThreshold:.2},lossRate:{overlayTab:2,values:[mn(b,4)],upperThreshold:.1}}}(e,t,this.rendererStats),e.inboundRTP.id))}dispose(){this.subs.forEach((e=>e.dispose())),this.subs=[],this.overlay?.dispose(),this.overlay=null,this.container=null,this.renderer=null}},lk=class{constructor(e,t){this.container=t,e&&!this.overlay&&(this.overlay=new ak(this.container))}setStats(e,t){if(!this.overlay)return;if(this.overlay.clearTable(),2===this.overlay.getOverlayTab())return void this.overlay.createTableColumn(rk(e,t),e.outboundRTP.id);const i=[e,...e.altLayouts??[]];for(const e of i)this.overlay.createTableColumn(rk(e,t),e.outboundRTP.id)}dispose(){this.overlay?.dispose(),this.overlay=null,this.container=null}},ck=class e extends Vi{constructor(t,i,n){const r=i.createChild(""+e.rendererId++);super(r),this.container=t,this.configProvider=n,this.video=this.container.ownerDocument.createElement("video"),this.lastNotifiedVideoWidth=0,this.lastNotifiedVideoHeight=0,this.isVideoAttached=!1,this.onVideoDataUpdated=()=>{let e=this.video.videoWidth,t=this.video.videoHeight;(e<32||t<32)&&(e=t=0),this.lastNotifiedVideoWidth===e&&this.lastNotifiedVideoHeight===t||(this.lastNotifiedVideoWidth=e,this.lastNotifiedVideoHeight=t,this.event("onVideoSizeChanged").raise(e,t)),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=e=>{e.preventDefault()},this.logger=r,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(e){this.stream!==e&&(this.stream&&(this.video.srcObject=null),e&&(this.video.hidden=0===e.getVideoTracks().length,this.video.srcObject=e,this.isVideoAttached||(this.container.appendChild(this.video),this.isVideoAttached=!0)),this.stream=e)}setScalingMode(e){this.video.style.objectFit=function(e){switch(e){case"crop":return"cover";case"stretch":return"fill";default:return"contain"}}(e)}getMediaStream(){return this.stream}getTrackId(){return this.stream?.getTracks()[0]?.id??void 0}async captureFrame(){const e=this.stream;if(!e)throw this.logger.safe.error("Mediastream not found"),new Error("Mediastream not found");const t=e.getVideoTracks?.()?.[0]?.getSettings(),i=t?.width,n=t?.height;if(!i||!n)throw this.logger.safe.error("Failed to get video track width/height"),new Error("Failed to get video track width/height");const r=this.getImageData(i,n);return{getSize:()=>({width:i,height:n}),isMirrored:()=>!1,getImageData:()=>r}}playVideo(){this.video?.paused&&this.video.play().catch((e=>{this.logger.safe.error(`Play video error: ${e}`)}))}getImageData(e,t){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=e,this.canvas.height=t,this.context.drawImage(this.video,0,0,e,t),this.context.getImageData(0,0,e,t)}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)}};ck.rendererId=0;var dk=ck,uk=class extends dk{constructor(e,t,i,n,r){super(e,i.createChild("local"),n),this.mediaStreamProvider=t,this.mediaType=r,this.isDisposed=!1,this.serialQueue=new tk(this.logger.createChild("rendererQueue")),this.logger.safe.info("ctor"),this.overlayStats=new lk(this.configProvider.config.showStatsInCall,e)}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(e){this.configProvider.config.localPreviewMirroringSupported&&(this.getVideoElement().style.transform=e?"scaleX(-1)":void 0)}startVideoAsync(e=be()){return this.logger.safe.info(`[${e}] starting local video`),this.event("onRendererStarted").raise(this),this.serialQueue.add((()=>this.restartVideo()),e)}updateStreamAsync(e=be()){return this.logger.safe.info(`[${e}] updating local video`),this.serialQueue.add((()=>this.restartVideo()),e)}onDiagnosticUpdated(e){e.video?.send?.length&&e.audio?.send?.length&&this.overlayStats.setStats(e.video.send[0],e.audio.send[0])}async restartVideo(){try{let e;if("Video"===this.mediaType)e=await this.mediaStreamProvider.getVideoStream(!1,"localVideoRenderer");else{if("ScreenShare"!==this.mediaType)throw new Error("Not yet supported");e=await this.mediaStreamProvider.getDisplayStream("localSSRenderer")}if(await e.start(),this.isDisposed)throw e.dispose(),new Error("local video renderer is disposed");this.attachStream(e)}catch(e){throw this.mediaStreamProvider.raiseTelemetryEvent("video_preview_error",{mediaType:this.mediaType,error:tt(e)}),e}}attachStream(e){if(this.mediaStream!==e)if(this.mediaStream?.parentId!==e?.parentId){this.logger.safe.info(`attach media stream ${e?.id}`);try{this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),e&&super.attachMediaStream(e.rawStream),this.mediaStream=e}catch(t){throw e&&e.dispose(),t}}else e.dispose()}},hk=class extends Vi{constructor(e,t,i){super(i),this.mediaStream=e,this.logger=i,this.mediaStreamSubscriptions=[],this.isHold=!1,this.isMuted=this.mediaStream.getMuted(),this._isDisposed=!1,this.originalId=e.id,this.subscribeOnMediaStreamEvents(),this.update(t),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(e){e&&(this.gumStream=e,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 e=this.mediaStream.getClient();return this.isMuted&&e.setMuted(!0),this.isHold&&e.setHold(!0),e}applyCapabilities(e){return this.mediaStream.applyCapabilities(e)}setMuted(e,t=be()){this.isMuted=e||this.mediaStream.getMuted(),this.logger.safe.info(`[${t}] setMuted => ${this.isMuted}`),this.enableDisableTracks()}setHold(e){this.isHold=e,this.enableDisableTracks()}start(){return this.mediaStream.start()}hasAudio(){return this.mediaStream.hasAudio()}hasVideo(){return this.mediaStream.hasVideo()}hasDisplay(){return this.mediaStream.hasDisplay()}isSameStream(e){return this.parentId===e.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",((e,t)=>{this.event("onStreamClientStarted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamError",((e,t)=>{this.event("onStreamClientError").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackMuted",((e,t)=>{this.event("onStreamClientMuted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackEnded",((e,t)=>{this.event("onStreamClientEnded").raise(this,t)})))}unsubscribeFromMediaStreamEvents(){this.mediaStreamSubscriptions.forEach((e=>e.dispose())),this.mediaStreamSubscriptions=[]}enableDisableTracks(){this.gumStream?this.gumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`Track ${JSON.stringify(e.id)} enabled state set to => ${e.enabled}`))})):this.logger.safe.warn("gumStream stream doesn't exist")}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}},gk=class e extends Vi{constructor(t,i,n,r){super(n),this.streamConstraints=t,this.serialQueue=i,this.configProvider=r,this.clientId=0,this.clients=[],this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.isMuted=!1,this.isHold=!1,this.gumStartTime=0,this.streamId=e.streamGeneration++,this.logger=n.createChild(`MediaStream:${this.streamId}`),this.mediaType=this.getMediaType(this.streamConstraints),this.constraintsProvider=bD.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(t)}get id(){return this.streamId}get rawStream(){return this.currentGumStream}get deviceId(){return this.rawStream?.getTracks()?.[0]?.getSettings?.()?.deviceId??null}applyCapabilities(e){if(this.currentGumStream){const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t)return Promise.resolve(!1);if(this.currentConstraints!==t){this.currentConstraints=t;const e=this.currentConstraints;return this.hasDisplay()?this.applyConstraints(this.currentConstraints).then((()=>an(this.currentConstraints,e))).catch((e=>(this.logger.safe.error(`Apply constraints error: ${tt(e)}`),!1))):this.applyConstraintsInternal().then((()=>an(this.currentConstraints,e)))}}return Promise.resolve(!1)}getClient(){let e;this.currentGumStream?(e=this.getClone(),this.clientGumStreams.push({[this.constraintsProvider.getKey(this.currentConstraints)]:e})):this.clientGumStreams.push({});const t=new hk(this,e,this.logger.createChild("Client:"+this.clientId++));return this.clients.push(t),t}getClone(){return this.hasDisplay()?this.currentGumStream:this.currentGumStream.clone()}setMuted(e){this.isMuted=e,this.clients.forEach((t=>{t.setMuted(e)})),this.enableDisableTracks()}getMuted(){return this.isMuted}setHold(e){this.isHold=e,this.clients.forEach((t=>{t.setHold(e)})),this.enableDisableTracks()}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(){for(let e=this.clients.length-1;e>=0;e--)this.clients[e].dispose()}disposeClient(e){const t=this.clients.indexOf(e);t>=0&&(this.clients.splice(t,1),this.streamsDump.push(this.clientGumStreams[t]),this.clientGumStreams.splice(t,1),0===this.clients.length)&&this.disposeStream()}async disposeStream(){this.event("onStreamDisposing").raise(this);try{await this.stopGumStream(),this.event("onStreamDisposed").raise(this)}catch(e){this.event("onStreamError").raise(this,e)}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!==Gi.DISPLAY_SOURCE_ID}hasDisplay(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId===Gi.DISPLAY_SOURCE_ID}getVideoDeviceId(){return this.currentConstraints.video.deviceId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=ND(this.currentGumStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=xD(this.currentGumStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}async startStream(e){let t;t=e.video?this.applyConstraintsInternal():this.updateGumStreamInternal(e);try{await t,this.event("onStreamStarted").raise(this,e)}catch(e){throw this.event("onStreamError").raise(this,e),e}}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}updateClients(e){const t=this.constraintsProvider.getKey(e);this.clients.forEach(((e,i)=>{this.clientGumStreams[i][t]||(this.clientGumStreams[i][t]=this.getClone()),e.update(this.clientGumStreams[i][t])}))}applyConstraints(e){const t=this.getGumStreamProvider();return Promise.all(this.clients.map((i=>t.applyConstraints(i.rawStream,e)))).then((()=>{}))}applyConstraintsInternal(){return new Promise(((e,t)=>{this.logger.safe.info(`applying stream constraints: ${JSON.stringify(hm(this.currentConstraints))}`);const i=new Kt;this.clients.forEach((e=>{e.onApplyConstraints&&e.onApplyConstraints(i.promise)}));const n=this.serialQueue.add((()=>{const e=(new VD).getPolicies(this.currentConstraints);return this.mediaStreamStartPromise=this.updateGumStreamInternal(e[0]),e.slice(1).forEach((e=>{this.mediaStreamStartPromise=this.mediaStreamStartPromise.catch((t=>{if(Gi.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("could not obtain constrained media stream, will attempt weaker policy"),this.updateGumStreamInternal(e);throw t.constraints=e,t}))})),this.mediaStreamStartPromise})).then((()=>{i.resolve()})).catch((e=>{throw this.logger.safe.error(`failed to apply constraints: ${JSON.stringify(hm(e.constraints))} error: ${tt(e)}`),i.reject(e),e}));e(n)}))}enableDisableTracks(){this.currentGumStream&&this.currentGumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!("audio"===e.kind&&this.isMuted||this.isHold),this.logger.safe.info(`control media stream track kind: ${e.kind} enabled: ${e.enabled} muted: ${e.muted}`))}))}getGumStreamProvider(){return kD.getStreamProvider(this.mediaType,this.configProvider,this.logger.createChild("MSProvider"))}async updateGumStreamInternal(e){this.logger.safe.info(`querying user media for stream: ${JSON.stringify(e)}`),this.logger.safe.info("Getting GUM stream");const t=await this.getGumStream(e);this.logger.safe.info("Updating gum stream audio tracks"),this.updateGumStreamAudioTracks(t),this.currentGumStream=t,this.logger.safe.info("Updating stream constraints"),this.updateConstraints(e,t),this.logger.safe.info("Caching GUM stream"),this.cacheGumStream(this.currentConstraints,t),this.updateClients(this.currentConstraints),this.updateGumStreamVideoTracks(t),this.enableDisableTracks(),this.logger.safe.info("media stream updated");const i=this.stopRequestCalculation();this.event("onStreamAcquired").raise(this,i,(this.hasVideo()||this.hasDisplay())&&this.getResolution()||void 0)}async getGumStream(e){const t=this.gumStreams[this.constraintsProvider.getKey(e)];if(t)return t;const i=this.getGumStreamProvider();return this.startRequestCalculation(),i.getStream(e)}updateGumStreamAudioTracks(e){e.getAudioTracks().forEach((e=>{e.onended=e=>{this.logger.safe.info(`Audio stream track ended: ${JSON.stringify(e.error?.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},e.onmute=()=>{this.logger.safe.info("Audio stream track muted"),this.event("onStreamTrackMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info("Audio stream track unmuted"),this.event("onStreamTrackMuted").raise(this,!1)},e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`)}))}updateGumStreamVideoTracks(e){const[t]=e.getVideoTracks();t&&(t.onmute=e=>{this.logger.safe.error(`Video stream track muted: ${JSON.stringify(hm(this.currentConstraints))}; ${JSON.stringify(e)}`)},t.onended=e=>{this.logger.safe.info(`Video stream track ended: ${JSON.stringify(hm(this.currentConstraints))}; ${JSON.stringify(e?.error.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},this.hasDisplay()&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(t,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(t.id)}`))}cacheGumStream(e,t){const i=this.constraintsProvider.getKey(e);this.gumStreams[i]!==t&&(this.gumStreams[i]&&(this.logger.safe.info(`Stream cache hit for ${i}, stopping old stream`),this.stopOneGumStream(this.gumStreams[i])),this.gumStreams[i]=t)}updateConstraints(e,t){this.currentConstraints=e.video?this.constraintsProvider.updateResolution(e,this.getResolution()):e,this.logger.safe.info(`Stream constraints updated: ${JSON.stringify(this.currentConstraints)}`)}applyContentHint(e,t){["","text","detail","motion"].indexOf(t)<0?this.logger.safe.error(`Cannot apply content hint: ${t}`):(this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t)}startRequestCalculation(){this.gumStartTime=Date.now()}stopRequestCalculation(){if(0===this.gumStartTime)return 0;const e=Date.now()-this.gumStartTime;return this.gumStartTime=0,e}stopGumStream(){return this.mediaStreamStartPromise?(this.logger.safe.info("queueing media stream stop"),this.serialQueue.add((()=>{this.stopGumStreamInternal()}))):Promise.resolve()}stopOneGumStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.onended=null,e.onmute=null,e.stop()})),this.logger.safe.info("media stream stopped")}catch(e){this.logger.safe.warn(`failed to stop media stream: ${tt(e)}`)}}stopGumStreamInternal(){this.currentGumStream&&([...this.clientGumStreams,...this.streamsDump,this.gumStreams].forEach((e=>{qi(e,(e=>{this.stopOneGumStream(e)}))})),this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.currentGumStream=null)}};gk.streamGeneration=0;var pk=gk,mk=class e extends Vi{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.effectsManager=i,this.cachedStreamsSubs=new Map,this.cachedStreamsMap=new Map,this.mediaStreamSerialQueue=new tk(this.logger),this.couldUseWebrtc_1_0=!1}getMediaStream(e,t){this.logger.safe.info(`retrieving media stream: ${JSON.stringify(hm(e))}`),this.cachedStreamsMap.size||(this.couldUseWebrtc_1_0=pm(this.configProvider.config.checkSupportForWebrtc_1_0));let i=this.getSuitableStream(e);i||(this.logger.safe.info(`cached stream is not found. Creating a new one with constraints: ${tt(hm(e))}`),i=this.createCachedStream(e)),this.logger.safe.info(`starting cached stream id=${i.id}`,t);const n=i.getClient(t);return n.start().catch((e=>{this.logger.safe.error(`could not start media stream: ${i.id}, total streams: ${this.cachedStreamsMap.size}, error: ${tt(e)}`),this.removeStream(i)})),n}dispose(){this.cachedStreamsSubs&&(this.cachedStreamsSubs.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.cachedStreamsSubs=null),this.cachedStreamsMap&&(this.cachedStreamsMap.forEach((e=>e.dispose("MSM dispose"))),this.cachedStreamsMap=null),this.mediaStreamSerialQueue&&(this.mediaStreamSerialQueue.dispose(),this.mediaStreamSerialQueue=null),super.dispose()}getCachedStreams(){return this.cachedStreamsMap}getActiveConstraints(){const e={audio:!1,video:!1,sharing:!1};return this.cachedStreamsMap.forEach(((t,i)=>{i.audio&&(e.audio=!0),i.video&&(e.video=!0),i.sharing&&(e.sharing=!0)})),e}onDevicesChanged(t){this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t)?this.logger.safe.info("Device list is empty, permission workaround enabled"):this.cachedStreamsMap.forEach(((e,i)=>{if(!i.sharing){const e=this.isDeviceOutdated(i.audio,t),n=this.isDeviceOutdated(i.video,t);(e||n)&&this.cachedStreamsMap.delete(i)}}))}getSuitableStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{this.isSuitable(this.addDeviceIdIfNecessary(i,n),e)&&(t=n)})),t&&this.cachedStreamsMap.get(t)}addDeviceIdIfNecessary(e,t){if(!e.deviceId)return t;const i=this.cloneStreamConstraints(t);return t.audio&&void 0===t.audio.deviceId&&(i.audio.deviceId=e.deviceId),t.video&&void 0===t.video.deviceId&&(i.video.deviceId=e.deviceId),t.sharing&&(i.sharing.deviceId=Gi.DISPLAY_SOURCE_ID),i}cloneStreamConstraints(e){return{...nn(e),withOverridenStream:e.withOverridenStream}}createCachedStream(e){const t=this.createStream(e);return this.event("onStreamCreated").raise(t.id,t.mediaType),this.subscribeOnStreamEvents(t),this.logger.safe.info(`created media stream, id: ${t.id} total: ${this.cachedStreamsMap.size}`),this.cachedStreamsMap.set(e,t),t}disposeCurrentDeviceStream(t){for(const[i,n]of this.cachedStreamsMap.entries())t.sharing||i.sharing||(e.deviceChanged(t.audio,i.audio)||e.deviceChanged(t.video,i.video))&&n.dispose("MSM dispose oneStreamPerDeviceType")}createStream(e){return this.configProvider.config.oneStreamPerDeviceType&&this.couldUseWebrtc_1_0&&this.disposeCurrentDeviceStream(e),this.configProvider.config.webrtcSimulcastSessionEnabled&&Vp.hasApplyConstraints()&&this.couldUseWebrtc_1_0?new WD(e,this.mediaStreamSerialQueue,this.configProvider,this.logger,this.effectsManager):new pk(e,this.mediaStreamSerialQueue,this.logger,this.configProvider)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamAcquired",((e,t,i)=>this.onStreamAcquired(e,t,i)))),t.push(e.on("onStreamDisposing",(e=>this.onStreamDisposing(e)))),this.cachedStreamsSubs.set(e,t)}unsubscribeFromStreamEvents(e){this.cachedStreamsSubs.get(e).forEach((e=>e.dispose())),this.cachedStreamsSubs.delete(e)}removeStream(e){this.logger.safe.info(`release media stream generation: ${e.id} cached: ${this.cachedStreamsMap.size}`),this.cachedStreamsSubs.has(e)?(this.unsubscribeFromStreamEvents(e),this.cachedStreamsMap.delete(this.getConstraintsForStream(e)),this.getStreamsCountByType("Audio")||this.effectsManager.stopEffect("Audio"),this.cachedStreamsMap.size||this.event("onAllStreamsRemoved").raise()):this.logger.safe.warn(`skipping unknown stream ${e.id}`)}getConstraintsForStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{e===i&&(t=n)})),t}isSuitable(e,t){const i=!(!e.withOverridenStream||!t.withOverridenStream),n=i||t.sharing||this.isAcceptable(e.audio,t.audio)&&e.audioProcessingFlags===t.audioProcessingFlags,r=i||this.isAcceptable(e.video,t.video),s=this.configProvider.config.requireUserActionForAudioSharing&&t.sharing&&!!e.audio!=!!t.audio,a=this.isAcceptable(e.sharing,t.sharing),o=a&&this.isAcceptable(e.audio,t.audio),l=s?o:a,c=e.withEffect===t.withEffect,d=e.withOverridenStream?.id===t.withOverridenStream?.id;return!t.force&&n&&r&&l&&c&&d}isAcceptable(e,t){return!e&&!t||e&&t&&e.deviceId===t.deviceId}isDeviceOutdated(e,t){return e?.deviceId&&!t.some((t=>t.deviceId===e.deviceId))}onStreamDisposing(e){this.logger.safe.info(`onStreamDisposing event ${e.id}`),this.event("onStreamDisposing").raise(e.id,e.mediaType),this.removeStream(e)}onStreamAcquired(e,t,i){const n="Audio"===e.mediaType?void 0:!!e.rawStream.getAudioTracks()[0],r="ScreenShare"===e.mediaType?this.getSharingSource(e):void 0,s="Audio"===e.mediaType||n?e.rawStream?.getAudioTracks?.()[0]?.getSettings?.()?.sampleRate:void 0;this.event("onStreamAcquired").raise({id:e.id,mediaType:e.mediaType,timestamp:t,resolution:i,withAudio:n,source:r,sampleRate:s})}getSharingSource(e){const t=e.rawStream.getVideoTracks()[0],i=t.getConstraints();if(i?.deviceId)return"camera";const n=t.getSettings();return n?.displaySurface??"unknown"}static deviceChanged(e,t){return!(!e||!t)&&e.deviceId!==t.deviceId}static isDeviceListEmpty(e){return e.every((e=>""===e.label))}getStreamsCountByType(e){let t=0;return this.cachedStreamsMap.forEach((i=>{t+=i.mediaType===e?1:0})),t}},fk=class{constructor(e){this.configProvider=e,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(e){this.data.permissionStates=e}setSelectedDevices(e,t){const i={microphone:fn(e.microphone?.label,this.configProvider.config.devices.piiSafeWords),camera:fn(e.camera?.label,this.configProvider.config.devices.piiSafeWords),speaker:fn(e.speaker?.label,this.configProvider.config.devices.piiSafeWords)};this.rawUsedDevices={microphone:e.microphone?.label,camera:e.camera?.label,speaker:e.speaker?.label},this.data.usedDevices&&(this.data.deviceSelectionChangeCount++,t&&this.data.deviceSelectionChangeCountFromInterface++),this.data.usedDevices=i}setDeviceList(e,t,i){this.data.deviceList=e.map((e=>({label:fn(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.type}))),i&&(this.data.deviceDebugStrings=nn(i)),this.data.devicesCount.microphone=e.filter((e=>"microphone"===e.type)).length,this.data.devicesCount.camera=e.filter((e=>"camera"===e.type)).length,this.data.devicesCount.speaker=e.filter((e=>"speaker"===e.type)).length,this.data.devicesCount.compositeAudio=e.filter((e=>"compositeAudio"===e.type)).length,this.data.devicesChangeCount++,t&&this.data.devicesPollChangeCount++}registerDeviceTelemetryEvent(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.data.latestCameraOpenResolution=t.resolution)}"Audio"===e.payload.mediaType&&("stream_acquired"===e.eventType&&(this.data.audioSourceNumOfReopenRequests++,this.data.audioSourceNumOfSuccessfulReopens++),"stream_error"===e.eventType&&this.data.audioSourceNumOfReopenRequests++),rt(this.data.deviceTelemetryEvents,e,this.configProvider.config.diagnostics.collectionLimits.numDeviceEvents)}logAudioDeviceError(e,t){switch(e){case"reconnect_on_audio_playback_error":{const e=this.getAudioPlaybackErrorCode(t.error);this.registerAudioRenderError(e);break}case"enumeration_failed":this.registerAudioRenderError(1),this.registerAudioCaptureError(1);break;case"permissions_state_changed":"denied"===t.microphone&&this.registerAudioCaptureError(0x800000000000);break;case"stream_ended_error":this.registerAudioCaptureError(4194304)}}getAudioPlaybackErrorCode(e){switch(e){case 3:return 4194304;case 4:return 128;default:return 0x8000000000000000}}registerVideoEffectsEvent(e){rt(this.data.videoEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numVideoEffectsEvents)}registerAudioEffectsEvent(e){rt(this.data.audioEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numAudioEffectsEvents)}registerWorkerEvent(e){rt(this.data.workerEvents,e,this.configProvider.config.diagnostics.collectionLimits.numWorkerEvents)}registerAudioCaptureError(e){const t={timestamp:Date.now(),audioDeviceErrorFlag:e};rt(this.data.audioCaptureDeviceErrorFlags,t,this.configProvider.config.diagnostics.collectionLimits.numAudioCaptureErrors)}registerAudioRenderError(e){const t={timestamp:Date.now(),audioDeviceErrorFlag:e};rt(this.data.audioRenderDeviceErrorFlags,t,this.configProvider.config.diagnostics.collectionLimits.numAudioRenderErrors)}getObjectRef(){return this.data}},vk=class{constructor(e,t,i,n,r){this.deviceId=e,this.label=t,this.kind=i,this.groupId=n,this.capabilities=r,this.type=this.getType(this.kind),this.guid=`${this.type}:${this.deviceId}`,this.isSystemDefault=this.deviceId===Gi.MEDIA_DEVICE.defaultId}toDeviceDesc(){return{id:this.guid,browserId:this.deviceId,label:this.label,kind:this.type}}getType(e){switch(e){case Gi.MEDIA_DEVICE_KIND.audioInput:return Gi.MEDIA_DEVICE.microphone;case Gi.MEDIA_DEVICE_KIND.audioOutput:return Gi.MEDIA_DEVICE.speaker;case Gi.MEDIA_DEVICE_KIND.videoInput:return Gi.MEDIA_DEVICE.camera;case Gi.MEDIA_DEVICE_KIND.compositeAudio:return Gi.MEDIA_DEVICE.compositeAudio;case Gi.MEDIA_DEVICE_KIND.virtualDevice:return Gi.MEDIA_DEVICE.virtualDevice;default:throw new Error(`Device kind to recognized: ${e}`)}}},Sk=class extends vk{constructor(e,t,i,n){super(e,t,i,n)}},yk=class extends vk{constructor(e,t,i,n,r){super(e,t,i,n,r)}toDeviceDesc(){const e=super.toDeviceDesc();return e.isSystemDefault=this.isSystemDefault,e}},Ck=class extends vk{constructor(e,t,i,n,r){if(super(e,t,i,n,r),this.position="unknown",r&&r.facingMode&&1===r.facingMode.length)switch(r.facingMode[0]){case"user":this.position="front";break;case"environment":this.position="back"}}toDeviceDesc(){const e=super.toDeviceDesc();return e.position=this.position,e}},Tk=class extends vk{constructor(e,t,i,n,r,s){super(null,i,n,""),this.micDevice=e,this.speakerDevice=t,this.formFactor=r,this.isPcInternalDevice=s,this.guid=null,this.isSystemDefault=!1}get micDeviceId(){return this.micDevice.guid}get speakerDeviceId(){return this.speakerDevice.guid}toDeviceDesc(){const e=super.toDeviceDesc();return e.microphoneId=this.micDeviceId,e.speakerId=this.speakerDeviceId,e.formFactor=this.formFactor,e.isPcInternalDevice=this.isPcInternalDevice,e}};function Ek(e){const t=e.getCapabilities&&e.getCapabilities();switch(t&&(delete t.groupId,delete t.deviceId),e.kind){case Gi.MEDIA_DEVICE_KIND.audioInput:case Gi.MEDIA_DEVICE_KIND.audioOutput:return new yk(e.deviceId,e.label,e.kind,e.groupId,t);case Gi.MEDIA_DEVICE_KIND.videoInput:return new Ck(e.deviceId,e.label,e.kind,e.groupId,t);default:throw new Error(`Device kind is not recognized: ${e.kind}`)}}function bk(e,t,i){return new Tk(e,t,i,"compositeAudio",0,!1)}function _k(e){switch(e){case Gi.MEDIA_DEVICE.microphone:return Gi.MEDIA_DEVICE_KIND.audioInput;case Gi.MEDIA_DEVICE.speaker:return Gi.MEDIA_DEVICE_KIND.audioOutput;case Gi.MEDIA_DEVICE.camera:return Gi.MEDIA_DEVICE_KIND.videoInput;default:throw new Error(`Device type to recognized: ${e}`)}}function Ik(e,t){let i=999,n=null;if(e.length>0&&t.length>0)for(const r of e)for(const e of t){const t=pn(r.label,e.label);t<i&&(i=t,n={microphone:r,speaker:e})}return n}function wk(e,t){if(e===t)return e;let i=gn(e,t);i=i.trim().replace(/^\((.+)\)$/,"$1");let n="",r="",s=0;const a=[Ak(e),Ak(t)];if(0===a[0]||0===a[1])return i;for(let e=0;e<i.length;e++)if("("===i[e])s++,r+=i[e];else if(")"===i[e]){if(!(s>0))break;s--,r+=i[e],n+=r,r=""}else s>0?r+=i[e]:n+=i[e];const o=Ak(n);return o!==a[0]&&o!==a[1]||(n=n.replace(/\w+\s?\((.+)\)/,"$1"),n=wk(i,n)),n.trim()}function Ak(e){const t=["(",")"];let i=0;for(let n=0;n<e.length;n++)t.some((t=>e[n]===t))&&i++;return i}var Pk={microphone:"",camera:"",speaker:"",compositeAudio:"",audioIngestDevice:"",virtualDevice:""},Rk=class extends Vi{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.debugInfo=Pk,this.lists=new Map,this.lists.set(Gi.MEDIA_DEVICE.microphone,[]),this.lists.set(Gi.MEDIA_DEVICE.camera,[]),this.configProvider.userAgentConfig.isAudioOutputSelectionSupported&&(this.lists.set(Gi.MEDIA_DEVICE.speaker,[]),this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,[])),e.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>this.onConfigUpdated())),this.logger.safe.info("Initialized")}get devices(){const e=[];return this.lists.forEach((t=>e.push(...t))),e}getDevicesByType(e){return this.lists.get(e)??[]}updateDevices(e,t=!1){if(an(this.latestRawList,e))return;this.latestRawList=e;const i=this.devices;this.debugInfo.microphone="microphone",this.debugInfo.camera="camera",this.debugInfo.speaker="speaker",this.debugInfo.compositeAudio="compositeAudio",this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.microphone,e.filter((e=>e.type===Gi.MEDIA_DEVICE.microphone))),this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.camera,e.filter((e=>e.type===Gi.MEDIA_DEVICE.camera))),this.lists.get(Gi.MEDIA_DEVICE.speaker)&&(this.updatePrimitiveDeviceList(Gi.MEDIA_DEVICE.speaker,e.filter((e=>e.type===Gi.MEDIA_DEVICE.speaker))),this.lists.get(Gi.MEDIA_DEVICE.compositeAudio)&&this.updateCompositeAudioDeviceList(this.lists.get(Gi.MEDIA_DEVICE.microphone),this.lists.get(Gi.MEDIA_DEVICE.speaker)));const n=this.lists.get(Gi.MEDIA_DEVICE.compositeAudio)||[];this.lists.set(Gi.MEDIA_DEVICE.microphone,this.orderDeviceList(this.lists.get(Gi.MEDIA_DEVICE.microphone),n)),this.lists.get(Gi.MEDIA_DEVICE.speaker)&&this.lists.set(Gi.MEDIA_DEVICE.speaker,this.orderDeviceList(this.lists.get(Gi.MEDIA_DEVICE.speaker),n));const r=this.lists.get(Gi.MEDIA_DEVICE.microphone);this.setTopItemToDefault(r);const s=this.lists.get(Gi.MEDIA_DEVICE.speaker);this.setTopItemToDefault(s),an(i,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,t))}updateVirtualDeviceList(e){const t=this.lists.get(Gi.MEDIA_DEVICE.virtualDevice),i=e.map((e=>new Sk(e.id,e.label,"virtualDevice","")));an(t,i)?this.logger.safe.info("Device lists did not change."):(this.lists.set(Gi.MEDIA_DEVICE.virtualDevice,i),this.event("onDevicesChanged").raise(this.devices,!1))}updateActiveMicrophone(e){if(!e||e.deviceId===Gi.MEDIA_DEVICE.defaultId)return;const t=this.lists.get(Gi.MEDIA_DEVICE.microphone),i=t.findIndex((e=>e.isSystemDefault));-1!==i&&t[i]!==e?(this.logger.safe.info("Removing synthetic default microphone"),e.isSystemDefault=!0,t.splice(i,1),this.lists.set(Gi.MEDIA_DEVICE.microphone,t),this.event("onDevicesChanged").raise(this.devices,!1)):e.isSystemDefault=!0}updatePrimitiveDeviceList(e,t){const i={str:this.debugInfo[e]};this.lists.set(e,function(e,t,i,n,r={str:""}){r.str+=`|input(${t.length})`;let s=[];const a=[n.config.devices.blacklist[e],n.defaultConfig.devices.blacklist[e]];for(const e of a)try{const i=new RegExp(e,"i");s=t.filter((t=>e&&t.label.match(i)?(r.str+=`|-blacklisted(${t.label})`,!1):t.deviceId!==Gi.MEDIA_DEVICE.communicationsId||(r.str+="|-communications",!1)));break}catch(i){r.str+=`|filterError('${e}', ${tt(i)})`,s=t}if(s.length){const t=function(e,t,i){if(1===t.length)return i.str+="|default:only",t[0];const n=t.find((e=>e.isSystemDefault&&e.deviceId===Gi.MEDIA_DEVICE.defaultId));if(!n)return i.str+="|default:noSynthetic",t.find((e=>e.isSystemDefault))||t[0];{const r=t.filter((e=>e!==n));if(1===r.length)return i.str+="|default:firstNonDefault",r[0];if(""!==n.groupId){const e=r.filter((e=>e.groupId===n.groupId));if(1===e.length)return i.str+=`|default:groupId(${De(e[0].guid)})`,e[0]}const s=r.map((e=>e.label)),a=function(e,t){return t.reduce(((t,i)=>{const n=e.includes(i)?i.length:0;return t.length<n?i:t}),"")}(n.label,s),o=r.find((e=>e.label===a));if(o)return i.str+=`|default:label(${De(o.guid)})`,o;const l=e.find((e=>e.isSystemDefault));if(l){const e=r.find((e=>e.deviceId===l.deviceId));if(e)return i.str+=`|default:previousList(${De(e.guid)})`,e}}return i.str+="|default:anyOrNull",t.find((e=>e.isSystemDefault))||null}(i,s,r);if(t&&(t.isSystemDefault=!0,r.str+=`|default(${De(t.guid)})`),t&&t.deviceId!==Gi.MEDIA_DEVICE.defaultId&&s.length>1&&(s=s.filter((e=>e.deviceId!==Gi.MEDIA_DEVICE.defaultId||(r.str+="|-defaultId",!1)))),e===Gi.MEDIA_DEVICE.camera||t||(r.str+="|+syntheticDefault",s.unshift(function(e){const t={deviceId:Gi.MEDIA_DEVICE.defaultId,label:Gi.MEDIA_DEVICE.defaultDeviceLabel,kind:_k(e),groupId:"",toJSON:()=>JSON.stringify(t)};return Ek(t)}(e))),i.forEach((e=>{const t=s.find((t=>t.guid===e.guid));t&&!t.label&&e.label&&(r.str+=`|migrateLabel(${De(t.guid)})`,t.label=e.label)})),e===Gi.MEDIA_DEVICE.speaker){const e=s.filter((e=>""===e.label));e.length>1&&e.length===s.length&&(s=t?[t]:[s[0]],r.str+=`|-filteredEmptyLabels(${e.length})`)}}return s}(e,t,this.lists.get(e)||[],this.configProvider,i)),this.debugInfo[e]=i.str}updateCompositeAudioDeviceList(e,t){const i={str:this.debugInfo.compositeAudio};this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,function(e,t,i=.5,n={str:""}){const r=[];if(e.length&&t.length){const s=function(e,t,i={str:""}){const n=new Set;for(const i of[...e,...t])n.add(i.groupId);const r=[];for(const s of n.values()){let n=e.filter((e=>e.groupId===s)),a=t.filter((e=>e.groupId===s));if(n&&a)if(1===n.length&&1===a.length)r.push({microphone:n[0],speaker:a[0]}),i.str+=`|pairSimple(${De(n[0].guid)}, ${De(a[0].guid)})`;else if(n.length>1||a.length>1){let e=Ik(n,a);for(;e;)i.str+=`|pairComplex(${De(e.microphone.guid)}, ${De(e.speaker.guid)})`,r.push(e),n=n.filter((t=>t!==e.microphone)),a=a.filter((t=>t!==e.speaker)),e=Ik(n,a)}}return r}(e.filter((e=>""!==e.groupId)),t.filter((e=>""!==e.groupId)),n);s.length&&(r.push(...s.map((e=>bk(e.microphone,e.speaker,wk(e.microphone.label,e.speaker.label))))),n.str+=`|directMatched(${r.length})`);const a=r.length;r.push(...function(e,t,i,n){const r=[];return e.length&&t.length?(e.forEach((e=>{const s=t.filter((t=>t.groupId===e.groupId));if(!s.length)return void(n.str+=`|lbl_nocand(${De(e.guid)})`);let a=gn(e.label,s[0].label).length;const o=s.sort(((t,i)=>{const n=gn(e.label,t.label),r=gn(e.label,i.label);return n.length>a&&(a=n.length),r.length>a&&(a=r.length),r.length-n.length}));if(o.length){const t=a/e.label.length;t>i&&(r.push(bk(e,o[0],wk(e.label,o[0].label))),n.str+=`|lbl_matched(${De(e.guid)} & ${De(o[0].guid)}, ${Math.round(1e4*t)/100}%)`)}})),r):r}(e.filter((e=>!r.some((t=>t.micDeviceId===e.guid)))),t.filter((e=>!r.some((t=>t.speakerDeviceId===e.guid)))),i,n)),n.str+=`|otherMatched(${r.length-a})`}return r}(e,t,this.configProvider.config.devices.compositeLabelMatchingThreshold,i)),this.debugInfo.compositeAudio=i.str}orderDeviceList(e,t){return e.sort(((e,i)=>this.getDevicePriority(i,this.getCompositeAudioDeviceCounterpart(i,t))-this.getDevicePriority(e,this.getCompositeAudioDeviceCounterpart(e,t))))}getCompositeAudioDeviceCounterpart(e,t){const i=t.find((t=>t.micDeviceId===e.guid||t.speakerDeviceId===e.guid));return i?i[e.type===Gi.MEDIA_DEVICE.speaker?"micDevice":"speakerDevice"]:null}getDevicePriority(e,t){let i=0;return this.configProvider.config.devices.overrideDefault&&t&&(!e.isSystemDefault&&t.isSystemDefault?(this.debugInfo[e.type]+=`|overrideDefault(${De(e.guid)})`,i+=10):e.isSystemDefault&&!t.isSystemDefault&&"microphone"===e.type&&(i+=15)),e.isSystemDefault&&(i+=5),t&&(i+=1,t.isSystemDefault&&(i+=2)),i}setTopItemToDefault(e){e?.length&&(e.forEach((e=>e.isSystemDefault=!1)),e[0].isSystemDefault=!0)}onConfigUpdated(){let e=!1;this.configProvider.userAgentConfig.isAudioOutputSelectionSupported?this.lists.has(Gi.MEDIA_DEVICE.speaker)||(this.lists.set(Gi.MEDIA_DEVICE.speaker,[]),this.lists.set(Gi.MEDIA_DEVICE.compositeAudio,[]),e=!0):(this.lists.has(Gi.MEDIA_DEVICE.speaker)&&(this.lists.delete(Gi.MEDIA_DEVICE.speaker),e=!0),this.lists.has(Gi.MEDIA_DEVICE.compositeAudio)&&(this.lists.delete(Gi.MEDIA_DEVICE.compositeAudio),e=!0)),e&&(this.logger.safe.info("Updating device list due to config update"),this.updateDevices(this.latestRawList||[]))}},Mk=class e extends Vi{constructor(t,i){super(i),this.pollingInterval=0,e.enumeratorUsers.add(this),e.initialize(this,t,i)}startDevicePolling(t){this.pollingInterval=t?e.configProvider.config.devices.pollingIntervalIdle:e.configProvider.config.devices.pollingIntervalActive,e.updatePollingTask()}stopDevicePolling(t){this.pollingInterval=t?0:e.configProvider.config.devices.pollingIntervalIdle,e.updatePollingTask()}dispose(){super.dispose(),this.stopDevicePolling(!0),e.enumeratorUsers.delete(this),0===e.enumeratorUsers.size&&(e.logger.safe.info("disposing"),e.initializeCalled=!1,e.isDeviceListAvailable=new Kt,e.list=void 0,e.window.navigator.mediaDevices.ondevicechange=void 0)}static get isPolling(){return 0!==e.currentPollingInterval}static initialize(t,i,n){e.initializeCalled||(e.initializeCalled=!0,e.window=Mp.window,e.configProvider=i,e.logger=n,e.list=new Rk(i,n.createChild("DeviceList")),i.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>e.enumerateDevices())),i.on("configUpdated",(()=>{void 0!==i.config.devices.pollingIntervalIdle&&null!==e.pollingTimer&&t.startDevicePolling(!0)})),i.config.devices.pollingIntervalIdle&&i.config.devices.idlePollingOnStart&&t.startDevicePolling(!0),e.window.navigator.mediaDevices&&(e.window.navigator.mediaDevices.ondevicechange=()=>{n.safe.info("enumerating due to ondevicechange callback"),e.enumerateDevices().catch((e=>{n.safe.error(`unable to enumerate ondevicechange: ${tt(e)}`)}))}),e.enumerateDevices())}static async enumerateDevices(t=!1){if(!e.window.navigator?.mediaDevices?.enumerateDevices){const t=new Error("device enumeration unsupported");throw e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.reject(t),t}if(e.enumerateDevicesPromise&&!t)return e.logger.safe.info("enumeration request postponed"),e.hasPendingUpdate=!0,void(e.isDeviceListAvailable.isPending&&Ot.isEngine("Firefox")&&e.isDeviceListAvailable.resolve());try{if(!e.enumerateDevicesPromise)if(e.configProvider.config.devices.enumerateDevicesTimeout){const t=Jt(e.configProvider.config.devices.enumerateDevicesTimeout);e.enumerateDevicesPromise=t.promise,e.window.navigator.mediaDevices.enumerateDevices().then(t.resolve,t.reject)}else e.enumerateDevicesPromise=e.window.navigator.mediaDevices.enumerateDevices();const i=await e.enumerateDevicesPromise;e.list.updateDevices(i.map((e=>Ek(e))),t),e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.resolve()}catch(t){const i=tt(t);throw e.logger.safe.warn(`error with enumerating devices: ${i}`),e.raiseFailedEnumeration(i),e.isDeviceListAvailable.isPending&&e.isDeviceListAvailable.reject(t),t}finally{e.enumerateDevicesPromise=void 0,e.hasPendingUpdate&&(e.hasPendingUpdate=!1,e.logger.safe.info("running postponed enumeration"),e.enumerateDevices())}}static updatePollingTask(){let t=Number.MAX_SAFE_INTEGER;for(const i of e.enumeratorUsers.values())i.pollingInterval<t&&(t=i.pollingInterval);if(t===Number.MAX_SAFE_INTEGER&&(t=0),(e.pollingTimer||e.currentPollingInterval!==t)&&e.pollingTimer&&(e.window.clearTimeout(e.pollingTimer),e.pollingTimer=void 0),e.currentPollingInterval=t,0===t)return;const i=async()=>{if(e.currentPollingInterval)try{await e.enumerateDevices(!0),e.pollingTimer=e.window.setTimeout(i,e.currentPollingInterval)}catch(t){throw e.pollingTimer=null,t}};e.logger.safe.info(`starting device polling with interval ${t}ms`),e.pollingTimer=1,i()}static raiseFailedEnumeration(t){for(const i of e.enumeratorUsers.values())i.event("onDeviceEnumerationfailed").raise(t)}};Mk.isDeviceListAvailable=new Kt,Mk.initializeCalled=!1,Mk.currentPollingInterval=0,Mk.hasPendingUpdate=!1,Mk.enumeratorUsers=new Set;var Dk=Mk,kk=class extends Vi{constructor(e,t,i){super(i),this.deviceList=e,this.configProvider=t,this.logger=i,this.userSelectedDevices={microphone:null,camera:null,speaker:null},this.currentlySelectedDevices={microphone:null,camera:null,speaker:null,audioIngestDevice:null},this.deviceList.on("onDevicesChanged",(e=>this.onDevicesChanged(e))),e.devices.length>0&&this.onDevicesChanged(e.devices),this.logger.safe.info("Initialized")}get selectedDevices(){return nn(this.currentlySelectedDevices)}selectDevices(e){let t=!1;if(qi(e,((e,i)=>{const n=this.getDeviceToSelect(i,this.deviceList.getDevicesByType("audioIngestDevice"===i?"microphone":i),e);"camera"===i&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i]),n?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i],t=!0),this.currentlySelectedDevices[i]=n})),t){const e=Zi(this.currentlySelectedDevices).map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed from public interface: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!0)}}getDeviceToSelect(e,t,i){let n;const r=this.userSelectedDevices[e];return i?n=t.find((e=>e.guid===i)):r&&(n=t.find((e=>e.guid===r))),"audioIngestDevice"===e?n:n||t[0]}onDevicesChanged(e){let t=!1;if(Object.keys(this.currentlySelectedDevices).forEach((i=>{const n="audioIngestDevice"===i?"microphone":i,r=e.filter((e=>e.type===n));if(r.length>0){const e=this.getDeviceToSelect(i,r);e?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.currentlySelectedDevices[i]=e,t=!0)}else this.currentlySelectedDevices[i]&&(this.currentlySelectedDevices[i]=null,t=!0)})),t){const e=Zi(this.currentlySelectedDevices).map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed due to device list change: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!1)}}},Ok=class extends Vi{constructor(e,t){super(e),this.logger=e,this.mediaStream=t,this.subs=[],this.subscribeOnMediaStreamEvents(t)}acquire(){return this.mediaStream?this.mediaStream.start().then((()=>this.logger.safe.info("Stream acquired"))).catch((e=>{throw this.logger.safe.warn(`Failed to acquire the stream: ${tt(e)}`),e})):Promise.reject("Disposed")}dispose(){this.logger.safe.info("Disposing stream"),this.unsubscribeFromMediaStreamEvents(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),super.dispose()}subscribeOnMediaStreamEvents(e){this.subs=[e.on("onStreamClientStarted",(()=>this.event("onStreamStateChanged").raise("active"))),e.on("onStreamClientMuted",((e,t)=>this.event("onStreamStateChanged").raise(t?"inactive":"active"))),e.on("onStreamClientEnded",(()=>this.event("onStreamStateChanged").raise("stopped"))),e.on("onStreamClientError",((e,t)=>{const i=t.type===Gi.MEDIA_ERROR.permissionDeniedError||t.type===Gi.MEDIA_ERROR.sharingCancelledError;this.event("onStreamStateChanged").raise(i?"cancelled":"failed")}))]}unsubscribeFromMediaStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},Nk=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive,Gi.MEDIA_STATE.send,Gi.MEDIA_STATE.sendReceive],Lk=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive],xk=class extends Vi{constructor(e,t,i){super(i),this.configProvider=e,this.deviceManager=t,this.logger=i,this.currentState={microphone:"unknown",camera:"unknown"},this.lastGum={audio:!1,video:!1},this.registeredTrackers=new Set,this.accessIssuePermissionOther={audio:!1,video:!1},this.window=Mp.window,this.permittedModalities={audio:Nk,video:Nk,sharing:Nk},this.initialize()}async initialize(){!Vp.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(e){return this.currentState[e]||"unknown"}isPermissionKnown(e){const t=this.getPermissionState(e);return"unknown"!==t&&"prompt"!==t}get browserPermittedModalities(){return this.permittedModalities}get knownPermissionStates(){return nn(this.currentState)}update(e,t){const i=nn(t);e.audio||delete i.audio,e.video||delete i.video;const n=nn(this.permittedModalities);qi(i,((e,t)=>{this.permittedModalities[t]=e?Nk:Lk})),an(n,this.permittedModalities)||this.event("onDevicesPermissionChanged").raise()}async askDevicePermission(e){const t=e?nn(e):{audio:!0,video:this.deviceManager.hasCamera()};if(this.accessIssuePermissionOther={audio:!1,video:!1},this.configProvider.config.permissions.rememberNegative&&(t.audio=t.audio&&this.permittedModalities.audio===Nk,t.video=t.video&&this.permittedModalities.video===Nk),t.sharing)throw new Error("askDevicePermission does not support sharing constraints.");const i={audio:!1,video:!1};this.lastGum={audio:!1,video:!1};const n=async(i,n,r)=>{const s={audio:!!i.audio,video:!!i.video,sharing:!0};return!(this.configProvider.config.permissions.adpRequestAVLast&&t.audio&&t.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(t,s),this.deviceManager.raiseTelemetryEvent("ask_device_permission",{constraints:e,resultConstraints:i,error:r,reason:n}),s};await this.initialize();const r=this.getPermissionState("microphone"),s=this.getPermissionState("camera");if(this.logger.safe.info(`Permission state { audio: ${r}, video: ${s} }`),this.configProvider.config.permissions.useNegativeInAdp&&(!t.audio||"denied"===r)&&(!t.video||"denied"===s))return n(i,"navigator_permissions_denied");if(this.configProvider.config.permissions.usePositiveInAdp&&(!t.audio||t.audio&&"granted"===r)&&(!t.video||t.video&&"granted"===s))return n(t,"navigator_permissions_granted");try{return n(this.getConstrainsWithPermissionError(await this.askDevicePermissionPrompt(t,this.configProvider.config.permissions.adpFallback)),"stream_acquisition")}catch(e){return n(i,"stream_acquisition",e)}}async askDevicePermissionPrompt(e,t=!0){const i={audio:!1,video:!1};try{const t=this.deviceManager.getMediaStream(e);return t&&(this.lastGum=nn(e),await t.start(),i.audio=t.hasAudio(),i.video=t.hasVideo(),this.disposeLater(t)),i}catch(n){if(e.audio&&e.video&&t){try{i.video=this.configProvider.config.permissions.adpFallbackVideo&&(await this.askDevicePermissionPrompt({video:!0})).video}catch(e){e.type!==Gi.MEDIA_ERROR.permissionDeniedError&&e.type!==Gi.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.video=!0)}try{i.audio=this.configProvider.config.permissions.adpFallbackAudio&&(await this.askDevicePermissionPrompt({audio:!0})).audio}catch(e){e.type!==Gi.MEDIA_ERROR.permissionDeniedError&&e.type!==Gi.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.audio=!0)}}else if(t)throw n;return i}}getConstrainsWithPermissionError(e){return this.configProvider.config.permissions.disableOnPermissionDeniedOnly?{audio:this.accessIssuePermissionOther.audio||e.audio,video:this.accessIssuePermissionOther.video||e.video}:e}disposeLater(e){setTimeout((()=>{e.dispose()}),this.configProvider.config.mediaStreamHoldInterval)}async registerPermissionTracker(e){if(!this.registeredTrackers.has(e))try{const t=await this.window.navigator.permissions.query({name:e});this.handlePermissionStateChanged(e,t.state),t.onchange=()=>this.handlePermissionStateChanged(e,t.state),this.registeredTrackers.add(e)}catch(t){this.logger.safe.error(`Error querying permissions for ${e}: ${tt(t)}`)}}handlePermissionStateChanged(e,t){if(this.logger.safe.info(`Permission state for ${e} changed ${this.currentState[e]} -> ${t}`),this.configProvider.config.permissions.enumerateDevicesAfterChange){this.logger.safe.info(`enumerateDevicesAfterChange: ${JSON.stringify(this.configProvider.config.permissions)}`),Dk.logger.safe.info("enumerating due to permission change");try{Dk.enumerateDevices()}catch(e){Dk.logger.safe.error(`unable to enumerate on permission change: ${tt(e)}`)}}this.currentState[e]=t,this.deviceManager.raiseTelemetryEvent("permissions_state_changed",this.knownPermissionStates),this.deviceManager.handlePermissionStateChange()}},Fk=class extends gt{constructor(e,t=sn()){super(),this.dms=e,this.label=t,this.id=sn(),this.receivedEvents=new Map,this.subscribeToDeviceManagers(e)}getDeviceManagers(){return this.dms}dispose(){super.dispose(),this.dms?.forEach((e=>e.dispose())),this.dms=null}subscribeToDeviceManagers(e){e.forEach(((e,t)=>{e.on("onVideoEffectsEvent",((...t)=>this.eventHandler("onVideoEffectsEvent",e,(()=>this.event("onVideoEffectsEvent").raise(...t))))),e.on("onVideoEffectApplied",((...t)=>this.eventHandler("onVideoEffectApplied",e,(()=>this.event("onVideoEffectApplied").raise(...t))))),e.on("onDeviceTelemetryEvent",(e=>this.event("onDeviceTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onVideoEffectsTelemetryEvent",(e=>this.event("onVideoEffectsTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise(`${this.id}/${t}`))),e.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))}))}eventHandler(e,t,i){let n=this.receivedEvents.get(e);if(n??(n=new Set),n.add(t),this.dms.every((e=>n.has(e))))return i(),void n.clear();this.receivedEvents.set(e,n)}},Uk=()=>(e,t,i)=>{const n=i.value;return i.value=function(...e){return this.serialQueue.add(n.bind(this,...e))},i},Bk=class{constructor(e,t,i){this.configProvider=e,this.statistics=t,this.logger=i}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 e=this.configProvider.config.webcv.webGLUnsupportedRenderers;let t=!1;const i=Vp.unmaskedGlRenderer;return i&&!e.some((e=>e===i))?t=!0:(this.statistics.setError("RendererIsNotSupported",`Blacklisted from ${JSON.stringify(e)}`),this.logger.info(`Unsupported renderer: ${tt(i)}`)),t}isWebGL2Supported(){try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return this.statistics.setError("WebGL2IsNotSupported"),this.logger.info("WebGL2 context is not supported"),!1;const t=e.getSupportedExtensions(),i=this.configProvider.config.webcv.webGLRequiredExtensions.filter((e=>!t.includes(e)));if(i.length>0)return this.statistics.setError("WebGL2RequiredExtensionsNotSupported","Required WebGL2 extensions not supported."),this.logger.info(`Unsupported WebGL2 extensions: ${tt(i)}`),!1}catch(e){return this.statistics.setError("WebGL2IsNotSupported",`Error: ${tt(e)}`),this.logger.error(`isWebGL2Supported: ${tt(e)}`),!1}return!0}},Vk=class{constructor(e){this.loadDuration=-1,this.error=new jM(e)}hasData(){return this.error.items.length>0||this.loadDuration>0}startLoadTimer(){this.loadStartTimestamp=Date.now()}stopLoadTimer(){this.loadDuration=Date.now()-this.loadStartTimestamp}clearErrors(){this.error.clear()}setError(e,t){this.error.add({type:e,message:t})}getReport(){return{loadDuration:this.loadDuration,error:this.error.items}}},Hk=class extends Vi{constructor(e,t,i,n){super(i),this.webcvProvider=e,this.configProvider=t,this.logger=i,this.wasmLoader=n,this.serialQueue=new tk(this.logger),this.videoEffectToWebCVEffectMapping={0:vh.VideoEffectType.Off,1:vh.VideoEffectType.BackgroundBlur,16:vh.VideoEffectType.BackgroundReplacement,512:vh.VideoEffectType.PresenterMode,256:vh.VideoEffectType.None,2048:vh.VideoEffectType.None,262144:vh.VideoEffectType.None},this.currentEffect=0,this.effectProviderSubs=[],this.statistics=new Vk(this.configProvider.config.effectsTelemetryBufferSize),this.processorType=vh.ProcessorType.Webgl2,this.queryMessageProcessor=new $k(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(e){throw Error(e)}}async dispose(){this.logger.safe.debug("Dispose"),this.effectProvider&&(this.effectProviderSubs.forEach((e=>e.dispose())),this.effectProviderSubs=null,await this.effectProvider.disposeAsync()),super.dispose()}async configure(e){if(this.logger.safe.debug(`Set config: ${JSON.stringify(e)}`),this.effectConfig={backgroundImageUrl:e.imagePath,headers:e.headers},this.effectProvider)return this.effectProvider.configureEffect(this.effectConfig);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setEffectAsync(e){if(this.currentEffect===e)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: ${e}`);const t=this.getWebCVEffect(e);if(!t)throw new Error(`Effect with type ${e} is not supported`);if(this.shouldCollectStats(e)&&this.notifyAboutLastSessionStats("EffectChanged"),this.currentEffect=e,this.effectProvider)try{await this.effectProvider.setEffectAsync(t)}catch(e){throw await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to apply ${t}, error:${tt(e)}`),e}else this.logger.safe.debug("WebCV is not initialized. Do nothing")}async processingVideoEffectMessage(e){let t={code:0,response:{effects:[]},type:"EnableEffects"};try{await this.init()}catch(e){return this.logger.error(`Failed to initialize WebCV, error:${tt(e)}`),this.notifyError("FailedToInitialize",`Initialization failed, error:${tt(e)}`),t}const i=this.currentEffect;this.logger.info(`Processing video effect request type: ${JSON.stringify(e.type)}`),t=await this.queryMessageProcessor.processVideoEffectMessage(e),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(i)&&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 t}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}`),!this.effectProvider)return this.logger.safe.debug("WebCV is not initialized. Do nothing"),e;let t=e;try{t=await this.effectProvider.setSourceAsync(e)}catch(e){await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to set source, error:${tt(e)}`)}return t}async removeSourceAsync(e){if(this.logger.safe.debug(`Remove source: ${e?e.id:"no stream"}`),this.effectProvider)return this.effectProvider.removeSourceAsync(e);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async getEffectsCapability(){let e=0;const t=await this.getCapability();this.logger.safe.debug(`Get capabilty with return: ${JSON.stringify(t)}`);for(const i of t)e|=i;return e}getStats(e){if(!this.effectProvider)return;const t=this.effectProvider.getStats(),i=this.statistics.getReport();return t||i.error.length?{timestamp:Date.now(),statsReason:e,...this.createTelemetryEvent(t,i)}:void 0}getVersion(){return this.effectProvider?.getVersion?.()??"Unknown"}async resetOutputConstraints(e,t=vh.EffectQualityChangeReason.ExternalParam){const i={...this.configProvider.config.webcv.qualityConfig};return i.outputResolution=e.height,this.effectProvider?.configureStreamProcessor(i,vh.EffectQualityChangeReason.ExternalParam)}createTelemetryEvent(e,t){return{payload:{version:this.getVersion(),...t,...e,isWasmEnabled:this.processorType===vh.ProcessorType.Wasm}}}notifyError(e,t){this.statistics.setError(e,t),this.notifyAboutLastSessionStats("EffectError")}notifyAboutLastSessionStats(e){const t=this.getStats(e);t&&this.event("onVideoEffectTelemetryEvent").raise(t)}async initializeVideoEffectProvider(){if(!this.webcvProvider)return this.logger.safe.debug("WebCV provider is not set"),null;this.statistics.startLoadTimer();const e=await this.webcvProvider.getVideoEffectProvider();if(this.statistics.stopLoadTimer(),!e)return this.statistics.setError("FailedToInitialize"),this.logger.safe.warn("WebCV is not initialized"),null;this.logger.safe.debug(`WebCV v${e.getVersion?.()} is initialized`);const t=await this.webcvProvider.getModelConfig();return await e.configureModel(t),this.configProvider.config.webcv.loadWorkerCallback=this.wasmLoader.getWorkerFunction("wasmcv"),this.configProvider.config.webcv.loadTimerWorkerCallback=this.wasmLoader.getWorkerFunction("timer"),await e.configure({...this.configProvider.config.webcv,processorType:this.processorType}),this.effectConfig&&await e.configureEffect(this.effectConfig),this.effectProviderSubs=[e.on("onEffectApplied",(()=>this.event("onMediaStreamUpdateRequested").raise("Video"))),e.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats("EffectStopped"))),e.on("onVideoEffectQualityChanged",(e=>this.event("onVideoEffectQualityChanged").raise(e))),e.on("onVideoStreamQualityChanged",(e=>this.event("onVideoStreamQualityChanged").raise(e.resolution,e.fps,e.reason))),e.on("onCapabilitiesChanged",(()=>this.event("onVideoEffectCapabilitiesChanged").raise())),e.on("onFirstFrameProcessed",(()=>this.onFirstFrameProcessed())),e.on("onErrorNotified",(e=>this.notifyError("WebcvProcessorError",e))),e.on("videoFreezeDetected",(e=>this.event("videoFreezeDetected").raise(e)))],e}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 e=new Bk(this.configProvider,this.statistics,this.logger.createChild("CapabilityChecker"));let t=[0];return e.isWasmEffectSupported()?(t=[0,1,16,262144,512,2048],this.processorType=vh.ProcessorType.Wasm):e.isWebgl2EffectSupported()&&(t=[0,1,16],this.processorType=vh.ProcessorType.Webgl2),t}getWebCVEffect(e){return this.videoEffectToWebCVEffectMapping[e]||vh.VideoEffectType.None}onFirstFrameProcessed(){this.event("onVideoEffectApplied").raise(),this.logger.safe.debug("onVideoEffectApplied event raised")}async handleFailedProcessing(){this.currentEffect=0;try{await this.effectProvider.setEffectAsync(vh.VideoEffectType.Off)}catch(e){this.notifyError("WebcvProcessorError",`Failed to handle error state, error:${tt(e)}`)}}shouldCollectStats(e){return 0!==this.currentEffect&&0!==e&&this.currentEffect!==e}};m([Uk()],Hk.prototype,"init",1),m([Uk()],Hk.prototype,"dispose",1),m([Uk()],Hk.prototype,"configure",1),m([Uk()],Hk.prototype,"setSourceAsync",1),m([Uk()],Hk.prototype,"removeSourceAsync",1),m([Uk()],Hk.prototype,"getEffectsCapability",1);var $k=class{constructor(e,t){this.configProvider=e,this.logger=t,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(e){this.shouldReconfigure=e}async processVideoEffectMessage(e){switch(e.type){case"EnableEffects":return await this.processEnableEffectsMessage(e);case"DisableEffects":return await this.processDisableEffectsMessage(e);case"QueryEffects":return await this.processQueryEffectsMessage(e);default:return this.logger.error(`Unsupported video effect message type: ${e.type}`),null}}async processEnableEffectsMessage(e){const t={code:0,response:{effects:[]},type:"EnableEffects"};for(let i=0;i<e.request.effects.length;i++){const n=e.request.effects[i];switch(n.type){case"BackgroundModification":if("Blur"===n.options.variant){this.currentEffects|=1;const e={type:"BackgroundModification",options:{variant:"Blur"}};t.response.effects.push(e),this.currentEffects&=-262673}else if("Replacement"===n.options.variant){this.currentEffects|=16;const e={type:"BackgroundModification",options:{variant:"Replacement",location:n.options.location}};this.shouldReconfigure=!0,this.currentEffectPayload.imageConfig={backgroundImageUrl:n.options.location,headers:n.options?.headers},t.response.effects.push(e),this.currentEffects&=-262658}else if("WeatherPerson"===n.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 e={type:"BackgroundModification",options:{variant:"WeatherPerson"}};t.response.effects.push(e),this.currentEffects&=-262162}else if("Bokeh"===n.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 e={type:"BackgroundModification",options:{variant:"Bokeh"}};t.response.effects.push(e),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,t.response.effects.push({type:"AutoAdjust"})}}return t}async processQueryEffectsMessage(e){const t={code:0,response:{effects:[]},type:"QueryEffects"};if(1&this.currentEffects){const e={type:"BackgroundModification",options:{variant:"Blur"},state:"On"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"Blur"},state:"Off"};t.response.effects.push(e)}if(262144&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Off"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Unavailable"};t.response.effects.push(e)}if(16&this.currentEffects){const e={variant:"Replacement",location:""};this.currentEffectPayload?.imageConfig&&(e.location=this.currentEffectPayload?.imageConfig.backgroundImageUrl);const i={type:"BackgroundModification",options:e,state:"On"};t.response.effects.push(i)}else{const e={type:"BackgroundModification",options:{variant:"Replacement",location:""},state:"Off"};t.response.effects.push(e)}if(512&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Off"};t.response.effects.push(e)}else{const e={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Unavailable"};t.response.effects.push(e)}if(256&this.currentEffects){const e={type:"TouchUp",state:"Unavailable",options:{strength:0}};t.response.effects.push(e)}if(2048&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const e={type:"AutoAdjust",state:"On"};t.response.effects.push(e)}else if(this.configProvider.config.webcv.useWasmEffects){const e={type:"AutoAdjust",state:"Off"};t.response.effects.push(e)}else{const e={type:"AutoAdjust",state:"Unavailable"};t.response.effects.push(e)}return t}async processDisableEffectsMessage(e){const t={code:0,response:{effects:[]},type:"DisableEffects"},i=e,n={effects:[]};for(let e=0;e<i.request.effects.length;e++){const t=i.request.effects[e];switch(t.type){case"BackgroundModification":if("Blur"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"Blur"}};n.effects.push(e),this.currentEffects&=-2}if("Bokeh"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"Bokeh"}};n.effects.push(e),this.currentEffects&=-262145}if("Replacement"===t.options.variant){const e={variant:"Replacement",location:""};void 0!==this.payload?.imageConfig&&(e.location=this.payload?.imageConfig.backgroundImageUrl);const t={type:"BackgroundModification",options:e};n.effects.push(t),this.currentEffects&=-17}if("WeatherPerson"===t.options.variant){const e={type:"BackgroundModification",options:{variant:"WeatherPerson"}};n.effects.push(e),this.currentEffects&=-513}break;case"TouchUp":this.logger.error("TouchUp effect is not supported now"),n.effects.push({type:"TouchUp",options:{strength:0}}),this.currentEffects&=-257,this.currentEffectPayload.softfocusStrength=0;break;case"AutoAdjust":n.effects.push({type:"AutoAdjust"}),this.currentEffects&=-2049}}return t.response=n,t}},jk=class extends Vi{constructor(e,t,i,n,r,s){super(r),this.wasmdnsProvider=e,this.wasmaecProvider=t,this.wasmVqeProvider=i,this.configProvider=n,this.logger=r,this.wasmLoader=s,this.serialQueue=new tk(this.logger),this.stopped=!0,this.hasError=!1,this.isProviderReady=!1,this.statistics=new Vk(this.configProvider.config.effectsTelemetryBufferSize),this.currentEffect=Sh.AudioEffectType.Off,this.currentEffectCapability=0,this.audioEffectToWasmAudioEffectType={0:Sh.AudioEffectType.Off,1:Sh.AudioEffectType.NoiseSuppressionClassic,2:Sh.AudioEffectType.NoiseSuppressionDeep,4:Sh.AudioEffectType.EchoCancellationClassic,8:Sh.AudioEffectType.VoiceQualityEnhancementClassic,16:Sh.AudioEffectType.VoiceQualityEnhancementDeep},this.noiseSuppressionModeToWasmDnsEffectMapping={Off:Sh.AudioEffectType.Off,High:Sh.AudioEffectType.NoiseSuppressionDeep,Low:Sh.AudioEffectType.NoiseSuppressionClassic},this.wasmLoaderSub=this.wasmLoader?.on("onLoadError",(e=>{this.handleWasmLoaderError(e)}))}get isEffectEnabled(){return this.currentEffect!==Sh.AudioEffectType.Off}shouldFallbackToNativeProcessing(){return this.configProvider.config.wasmvqe.enableVqe||this.configProvider.config.wasmdns.enableNoiseSuppression?this.configProvider.config.wasmvqe.asyncInitialization&&!this.isProviderReady?(this.logger.safe.info("shouldFallbackToNativeProcessing: provider is not yet initialized"),!0):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(e,t){switch(e){case"High":return t?Sh.VqeMode.DeepVQE:Sh.VqeMode.DeepNS;case"Low":return t?Sh.VqeMode.SkypeVQE:Sh.VqeMode.SkypeNS;default:return t?Sh.VqeMode.SkypeAEC:Sh.VqeMode.Off}}vqeModeToNsMode(e){switch(e){case Sh.VqeMode.DeepVQE:case Sh.VqeMode.DeepNS:return"High";case Sh.VqeMode.SkypeVQE:case Sh.VqeMode.SkypeNS:return"Low";case Sh.VqeMode.SkypeAEC:case Sh.VqeMode.Off:default:return"Off"}}vqeModeToAudioEffectType(e){switch(e){case Sh.VqeMode.DeepVQE:return 16;case Sh.VqeMode.DeepNS:return 2;case Sh.VqeMode.SkypeVQE:return 8;case Sh.VqeMode.SkypeNS:return 1;case Sh.VqeMode.SkypeAEC:return 4;case Sh.VqeMode.Off:default:return 0}}audioEffectTypeToVqeMode(e){switch(e){case 16:return Sh.VqeMode.DeepVQE;case 2:return Sh.VqeMode.DeepNS;case 8:return Sh.VqeMode.SkypeVQE;case 1:return Sh.VqeMode.SkypeNS;case 4:return Sh.VqeMode.SkypeAEC;default:return Sh.VqeMode.Off}}async setSourceWithAsyncInitialization(e){if(this.hasError)return e;if(!this.isProviderReady)return this.logger.safe.info("Provider is not ready. Initializing provider async"),this.initialize(),e;if(this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),e;try{const t=await this.vqeProvider.setSourceAsync(e);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),t}catch(t){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${t})`),e}}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}, currentEffect = ${this.currentEffect}`),this.stopped||this.stop(),this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),e;if(await this.initializeProvider(),await this.configureEffect(),this.isProviderReady=!0,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const t=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${t}).`),this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${t}).`),e}if(!this.configProvider.config.wasmvqe.enableVqe&&!this.configProvider.config.wasmdns.enableNoiseSuppression)return e;if(this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((e,t)=>this.notifyError("WasmVqeProcessorError",e,t))),this.dnsProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onErrorNotified",(e=>this.notifyError("WasmDnsProcessorError",e))),this.aecProvider?.on("onErrorNotified",(e=>this.notifyError("WasmAecProcessorError",e)))],this.configProvider.config.wasmvqe.enableVqe)try{const t=await this.vqeProvider.setSourceAsync(e);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),t}catch(t){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${t})`),e}let t=e;try{t=await this.aecProvider.setSourceAsync(e),this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId))}catch(e){this.notifyError("WasmAecProcessorError",`setSourceAsync: Failed to asynchronously set source for AEC (${e})`)}try{return await this.dnsProvider.setSourceAsync(t)}catch(e){this.notifyError("WasmDnsProcessorError",`setSourceAsync: Failed to asynchronously set source for DNS (${e})`)}return t}setAecRefStream(e,t){try{if(!e&&this.rendererId!==t)return void this.logger.safe.debug(`Ref stream can't be set to null by renderer ${t}`);if(this.logger.safe.debug(`Setting the reference stream to: ${e?e.id:"Null"} requested by renderer ${t}`),this.aecRefStream=e,this.rendererId=t,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setAecRefStream: audio effect provider not initialized (${e}).`),void this.logger.safe.warn(`Unable to setAecRefStream for audio effects: audio effect provider not initialized (${e}).`)}this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider.setRefStream(e):this.configProvider.config.wasmdns.enableNoiseSuppression&&this.aecProvider.setRefStream(e)}catch(e){this.notifyError("WasmVqeProcessorError",`setRefStream: Failed to set reference stream for echo cancellation (${e})`)}}async setEffectAsync(e){const t=this.audioEffectToWasmAudioEffectType[e];if(this.currentEffect===t)return;const i=this.currentEffect===Sh.AudioEffectType.Off||t===Sh.AudioEffectType.Off;if(this.currentEffect=t,this.userNoiseSuppressionMode=this.audioEffectTypeToVqeMode(e),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";throw this.notifyError("FailedToInitialize",`setEffectAsync: audio effect provider not initialized (${e}).`),Error("FailedToInitialize")}try{this.configProvider.config.wasmvqe.enableVqe?await this.vqeProvider.setEffectAsync(t):this.configProvider.config.wasmdns.enableNoiseSuppression&&(await this.dnsProvider.setEffectAsync(t),await this.aecProvider.setEffectAsync(t)),this.configProvider.config.applyAudioEffectOnDemand&&this.configProvider.config.wasmvqe.enableVqe&&i&&this.requestStreamUpdate(),this.logger.safe.debug(`The audio effect was set to '${t}'`)}catch(e){throw this.notifyError("WasmVqeProcessorError",`setEffectAsync: Failed to apply '${t}' audio effect, error: ${tt(e)}`),e}}stop(){try{this.dnsProvider?.dispose(),this.dnsProvider=null,this.aecProvider?.dispose(),this.aecProvider=null,this.vqeProvider?.dispose(),this.vqeProvider=null,this.effectProviderSubs?.forEach((e=>e?.dispose())),this.effectProviderSubs=null,this.wasmLoaderSub?.dispose(),this.wasmLoaderSub=null,this.stopped=!0,this.isProviderReady=!1,this.logger.safe.debug("The audio effects provider was stopped.")}catch(e){this.logger.safe.error(`Failed to stop the audio effects provider (${e})`)}}dispose(){try{this.hasError=!1,this.stop(),super.dispose(),this.logger.safe.debug("The audio effects provider was disposed.")}catch(e){this.logger.safe.error(`dispose: Failed to dispose the audio effects provider (${e})`)}}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(){let e=this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider?.getStats():this.dnsProvider?.getStats();if(!e){if(!this.statistics.hasData())return null;e={}}return e.userNoiseSuppressionMethod=this.userNoiseSuppressionMode,{timestamp:Date.now(),...this.createTelemetryEvent(e)}}notifyError(e,t,i=!1){this.logger.error(`Audio effect error: ${e}, message: ${t}`),this.statistics.setError(e,t),this.notifyAboutLastSessionStats(),i&&(this.stop(),this.requestStreamUpdate(),this.hasError=!0),this.event("onEffectsError").raise("Audio",e,t)}async initialize(){this.stopped||this.stop(),this.statistics.startLoadTimer(),await this.initializeProvider(),this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((e,t)=>this.notifyError("WasmVqeProcessorError",e,t)))],await this.configureEffect(),this.isProviderReady=!0,this.statistics.stopLoadTimer(),this.requestStreamUpdate()}async initializeProvider(){if(this.configProvider.config.wasmvqe.enableVqe&&!this.vqeProvider)return this.logger.safe.debug("Initializing VQE provider ..."),void(this.vqeProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.VoiceQualityEnhancementDeep));this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.dnsProvider&&(this.logger.safe.debug("Initializing DNS provider ..."),this.dnsProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.NoiseSuppressionDeep)),this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.aecProvider&&(this.logger.safe.debug("Initializing AEC provider ..."),this.aecProvider=await this.initializeAudioEffectProvider(Sh.AudioEffectType.EchoCancellationClassic))}async configureEffect(e){this.statistics.clearErrors();let t=e;if(!t){let e=this.configProvider.mediaConfig.noiseSuppressionMode;this.logger.safe.info(`Configuring the audio effect manager for Noise Suppression mode: ${e}`),"Auto"===e&&(e=this.configProvider.config.wasmvqe.enableVqe?this.vqeModeToNsMode(this.configProvider.config.wasmvqe.defaultVqeMode):this.configProvider.config.wasmdns.noiseSuppressionMode,this.logger.safe.info(`Overriding 'Auto' with ${e}`)),t={...this.configProvider.config.wasmdns,...this.configProvider.config.wasmvqe},t.noiseSuppressionMode=e}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&&(t.defaultVqeMode=this.userNoiseSuppressionMode),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorklet,t.loadWasmWorkerCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorker,this.logger.safe.debug("Configuring VQE audio effects ..."),await this.vqeProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${tt(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${tt(t)},\n under the following capability: ${this.currentEffectCapability}.`,!0)}else if(this.configProvider.config.wasmdns.enableNoiseSuppression){t.noiseSuppressionMode||(this.logger.safe.debug("configureEffect was called without a noiseSuppressionMode. Using noiseSuppressionMode from config provider ..."),t.noiseSuppressionMode=this.configProvider.mediaConfig.noiseSuppressionMode),this.currentEffect=this.noiseSuppressionModeToWasmDnsEffectMapping[t.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 ..."),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmDnsWorklet,await this.dnsProvider.configureEffect(t),t.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmAecWorklet,await this.aecProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${tt(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${tt(t)},\n under the following capability: ${this.currentEffectCapability}.`,!0)}}}async initializeAudioEffectProvider(e){if(!this.wasmVqeProvider&&e===Sh.AudioEffectType.VoiceQualityEnhancementDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmVqe package not available."),this.logger.safe.warn("WasmVqe package not available."),null;if(!this.wasmdnsProvider&&e===Sh.AudioEffectType.NoiseSuppressionDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmDns package not available."),this.logger.safe.warn("WasmDns package not available."),null;if(!this.wasmaecProvider&&e===Sh.AudioEffectType.EchoCancellationClassic)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmAec package not available."),this.logger.safe.warn("WasmAec package not available."),null;let t;try{this.configProvider.config.wasmvqe.enableVqe&&e===Sh.AudioEffectType.VoiceQualityEnhancementDeep&&(t=await this.wasmVqeProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===Sh.AudioEffectType.NoiseSuppressionDeep&&(t=await this.wasmdnsProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===Sh.AudioEffectType.EchoCancellationClassic&&(t=await this.wasmaecProvider.getAudioEffectProvider())}catch(e){this.logger.safe.warn(`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`),this.statistics.setError("FailedToInitialize",`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`)}return this.statistics.stopLoadTimer(),t?(e===Sh.AudioEffectType.VoiceQualityEnhancementDeep&&this.logger.safe.debug(`WasmVqe v${t.getVersion?.()} initialized!`),e===Sh.AudioEffectType.NoiseSuppressionDeep&&this.logger.safe.debug(`WasmDns v${t.getVersion?.()} initialized!`),e===Sh.AudioEffectType.EchoCancellationClassic&&this.logger.safe.debug(`WasmAec v${t.getVersion?.()} initialized!`),t):(this.logger.safe.warn("Unitialized Wasm audio effect provider."),null)}createTelemetryEvent(e){return{payload:{audioEffectsCapability:this.currentEffectCapability,version:this.getVersion(),isProviderReady:this.isProviderReady,...this.statistics.getReport(),...e}}}notifyAboutLastSessionStats(){const e=this.getStats();e&&this.event("onAudioEffectTelemetryEvent").raise(e)}handleWasmLoaderError(e){"wasmvqe"===e&&this.notifyError("FailedToInitialize","Error loading additional scripts",!0)}requestStreamUpdate(){this.hasError||(this.logger.warn("Requesting stream update"),this.event("onMediaStreamUpdateRequested").raise("Audio"))}};m([Uk()],jk.prototype,"setSourceWithAsyncInitialization",1),m([Uk()],jk.prototype,"setSourceAsync",1),m([Uk()],jk.prototype,"setAecRefStream",1),m([Uk()],jk.prototype,"setEffectAsync",1),m([Uk()],jk.prototype,"stop",1),m([Uk()],jk.prototype,"dispose",1);var Gk=class{constructor(e){this.logger=e}async setSourceAsync(e){let t=document.createElement("video");return t.srcObject=e,this.logger.info(`Stream settings before play: ${JSON.stringify(this.getSettings(e))}`),await t.play(),this.logger.info(`Stream settings after play: ${JSON.stringify(this.getSettings(e))}`),t.pause(),t.srcObject=null,t.remove(),t=null,e}getSettings(e){return e.getVideoTracks()?.[0]?.getSettings()}},qk=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.logger=t}isEffectEnabled(e){switch(e){case"Video":return this.videoEffectManager?.isEffectEnabled;case"Audio":return this.audioEffectManager?.isEffectEnabled;default:return!1}}shouldFallbackToNativeProcessing(e){return"Audio"===e&&this.audioEffectManager?.shouldFallbackToNativeProcessing()}addEffectManager(e,t){switch(e){case"Audio":this.addAudioEffectManagerAndSubscribe(t);break;case"Video":this.configProvider.config.waitForVideoEffectStreamStart&&(this.delayedVideoEffectManager=new Gk(this.logger.createChild("DelayedVideoEffectManager"))),this.addVideoEffectManagerAndSubscribe(t);break;case"ScreenShare":this.delayedScreenShareEffectManager=new Gk(this.logger.createChild("DelayedScreenShareEffectManager"))}}async startEffect(e,t){switch(e){case"Audio":return this.initAudioEffectsWithTimeout(t);case"Video":if(this.configProvider.config.waitForVideoEffectStreamStart){const e=await this.videoEffectManager.setSourceAsync(t);return this.delayedVideoEffectManager.setSourceAsync(e)}return this.videoEffectManager.setSourceAsync(t);case"ScreenShare":return this.delayedScreenShareEffectManager.setSourceAsync(t);default:return t}}async setEffectType(e,t){switch(e){case"Audio":return this.audioEffectManager?.setEffectAsync(t);case"Video":return this.videoEffectManager?.setEffectAsync(t)}}async processingVideoEffectMessage(e){return this.videoEffectManager.processingVideoEffectMessage(e)}stopEffect(e,t){switch(e){case"Audio":this.logger.safe.info("stopping audio effect"),this.audioEffectManager?.dispose();break;case"Video":this.logger.safe.info("stopping video effect"),this.videoEffectManager?.removeSourceAsync(t)}}resetOutputConstraints(e,t,i){"Video"===e&&this.videoEffectManager?.resetOutputConstraints(t,i)}getStats(e,t){switch(e){case"Audio":return this.audioEffectManager?.getStats();case"Video":return this.videoEffectManager?.getStats(t);default:return}}async configure(e,t){if("Video"===e)return this.videoEffectManager?.configure(t)}async getEffectsCapability(e){switch(e){case"Audio":return this.audioEffectManager?.getEffectsCapability();case"Video":return this.videoEffectManager?.getEffectsCapability();default:return 0}}setAecRefStream(e,t){return this.audioEffectManager.setAecRefStream(e,t)}vqeModeToAudioEffectType(e){return this.audioEffectManager.vqeModeToAudioEffectType(e)}nsModeToVqeMode(e,t){return this.audioEffectManager.nsModeToVqeMode(e,t)}getAudioEffectsProviderName(){let e="None";return this.configProvider.config.wasmvqe.enableVqe?e="DeepVqe":this.configProvider.config.wasmdns.enableNoiseSuppression&&(e="DNS"),e}dispose(){super.dispose(),this.audioEffectManager?.dispose(),this.audioEffectManager=null,this.videoEffectManager?.dispose(),this.videoEffectManager=null}async initAudioEffectsWithTimeout(e){return new Promise(((t,i)=>{const n=window.setTimeout((()=>{const i=`AudioEffects init timeout. Init took more then ${this.configProvider.config.wasmvqe.initializationTimeoutMs} ms`;this.logger.warn(i),this.audioEffectManager.notifyError("InitializationTimeout",i),t(e)}),this.configProvider.config.wasmvqe.initializationTimeoutMs);this.configProvider.config.wasmvqe.asyncInitialization?this.audioEffectManager.setSourceWithAsyncInitialization(e).then((e=>{clearTimeout(n),t(e)})):this.audioEffectManager.setSourceAsync(e).then((e=>{clearTimeout(n),t(e)}))}))}addAudioEffectManagerAndSubscribe(e){this.audioEffectManager||(this.audioEffectManager=new jk(e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.configProvider,this.logger.createChild("AudioEffectManager"),e.wasmLoader),this.audioEffectManager.on("onAudioEffectTelemetryEvent",(e=>{this.event("onAudioEffectTelemetryEvent").raise(e)})),this.audioEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})),this.audioEffectManager.on("onEffectsError",((e,t,i)=>{this.event("onEffectsError").raise(e,t,i)})))}addVideoEffectManagerAndSubscribe(e){this.videoEffectManager||(this.videoEffectManager=new Hk(e.webcvProvider,this.configProvider,this.logger.createChild("VideoEffectManager"),e.wasmLoader),this.videoEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})),this.videoEffectManager.on("onVideoEffectQualityChanged",(e=>{this.event("onVideoEffectQualityChanged").raise(e)})),this.videoEffectManager.on("onVideoStreamQualityChanged",((e,t,i)=>{this.event("onVideoStreamQualityChanged").raise(e,t,i)})),this.videoEffectManager.on("onVideoEffectCapabilitiesChanged",(()=>{this.event("onVideoEffectCapabilitiesChanged").raise()})),this.videoEffectManager.on("onVideoEffectTelemetryEvent",(e=>{this.event("onVideoEffectTelemetryEvent").raise(e)})),this.videoEffectManager.on("onVideoEffectApplied",(()=>{this.event("onVideoEffectApplied").raise()})),this.videoEffectManager.on("videoFreezeDetected",(e=>{this.event("videoFreezeDetected").raise(e)})))}},zk=class{constructor(e){this.audioContext=new Mp.window.AudioContext,e?(this.sourceNode=this.audioContext.createMediaStreamSource(e),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(e){return 1===e?this.analyzerNode?.getByteFrequencyData(this.freqs):0===e&&this.analyzerNode?.getByteTimeDomainData(this.freqs),this.freqs}getDataFloat(e){return 1===e?this.analyzerNode?.getFloatFrequencyData(this.ffreqs):0===e&&this.analyzerNode?.getFloatTimeDomainData(this.ffreqs),this.ffreqs}getInputLevel(){return this.analyzerNode?.getByteFrequencyData(this.freqs),function(e){return e.reduce(((e,t)=>e+t),0)/(e.length?e.length:1)}(this.freqs)}getInputLevelNormalized(e=65535,t=255){return Math.floor(this.getInputLevel()*e/t)}createAnalyserNode(e){const t=this.audioContext.createAnalyser();return t.fftSize=1024,t.smoothingTimeConstant=.1,e.connect(t),t}},Wk=class{constructor(e,t){this.getAudioStream=e,this.logger=t,this.initialized=!1,this.disposeCachedStream=!1}async init(){if(this.initialized=!0,!this.cachedStream)return this.createStream();this.createAnalyzer()}getInputLevel(){if(!this.initialized||!this.audioStreamAnalyzer)return 0;try{return this.audioStreamAnalyzer.getDataFloat(0).reduce(((e,t)=>Math.max(Math.abs(t),e)),0)}catch(e){return this.logger.error(JSON.stringify(e)),0}}getInputLevelNormalized(e,t){throw new Error("Method not implemented.")}dispose(e){this.logger.safe.info(`[${e}] AudioStreamAnalyzerWrapper disposed`),this.disposeStreamAnalyzer(),this.disposeStream(),this.initialized=!1}async updateStreamAfterDeviceChange(){this.initialized&&this.disposeCachedStream&&(this.disposeStream(),await this.createStream())}setStream(e,t){this.initialized?("AudioStreamAnalyzerWrapper"!==t&&this.disposeStream(),this.cachedStream=e,this.createAnalyzer()):this.cachedStream=e}createAnalyzer(){this.disposeStreamAnalyzer(),this.audioStreamAnalyzer=new zk(this.cachedStream.getMasterStream().rawStream),this.logger.safe.info("AudioStreamAnalyzerWrapper created")}async createStream(){await this.getAudioStream(!1,"AudioStreamAnalyzerWrapper"),this.disposeCachedStream=!0}disposeStreamAnalyzer(){this.audioStreamAnalyzer?.dispose(),this.audioStreamAnalyzer=null}disposeStream(){this.disposeCachedStream&&(this.cachedStream?.getMasterStream()?.dispose(),this.cachedStream?.dispose(),this.cachedStream=null,this.disposeCachedStream=!1)}},Kk=class e extends Vi{constructor(t,i,n,r,s,a,o,l,c,d){super(t),this.logger=t,this.configProvider=i,this.diagnostics=n,this.domOverrides=r,this.ufdManager=s,this.id=sn(),this.virtualDeviceRecord=new Map,this.deviceEnumerator=new Dk(this.configProvider,this.logger.createChild("DeviceEnumerator")),this.deviceSelection=new kk(Dk.list,this.configProvider,this.logger.createChild("DeviceSelection")),this.permissionManager=new xk(this.configProvider,{getMediaStream:e=>this.getMediaStream({...e,withEffect:!1,withTimeout:!0,force:!1,audioProcessingFlags:e.audio&&!e.video?this.getAudioProcessingFlags():void 0},"permissionManager"),hasCamera:()=>this.hasDeviceType("camera"),raiseTelemetryEvent:(e,t)=>this.raiseTelemetryEvent(e,t),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 XD(this.logger.createChild("RawDeviceStream"),this.raiseTelemetryEvent.bind(this)),this.customDeviceMediaStreamMap=new Map,this.clientAudioRenderers=new Map,this.audioStreamAnalyzerWrapper=new Wk(((e,t)=>this.getAudioStream(e,t)),this.logger.createChild("AudioStreamAnalyzerWrapper")),this.audioSharingRequested=!1,this.virtualDeviceSubs=new Map,this.effectsManagerInternal=new qk(this.configProvider,this.logger.createChild("EffectsManager")),this.effectsManagerInternal.addEffectManager("Audio",{wasmdnsProvider:o,wasmaecProvider:l,wasmVqeProvider:c,wasmLoader:d}),this.effectsManagerInternal.addEffectManager("Video",{webcvProvider:a,wasmLoader:d}),this.effectsManagerInternal.addEffectManager("ScreenShare",null),this.mediaStreamManager=new mk(this.logger.createChild("MediaStreamManager"),this.configProvider,this.effectsManager),this.deviceManagerSubscriptions=[this.permissionManager.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise())),Dk.list.on("onDevicesChanged",((e,t)=>this.onDevicesChanged(e,t))),this.deviceSelection.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),this.effectsManager.on("onAudioEffectTelemetryEvent",(e=>{this.diagnostics.registerAudioEffectsEvent(nn(e)),this.event("onAudioEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onMediaStreamUpdateRequested",(e=>this.onMediaStreamUpdateRequested(e,!0))),this.effectsManager.on("onVideoEffectQualityChanged",(e=>this.onVideoEffectsQualityEventHandler(e))),this.effectsManager.on("onVideoEffectTelemetryEvent",(e=>{this.diagnostics.registerVideoEffectsEvent(nn(e)),this.event("onVideoEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onVideoEffectApplied",(()=>{this.raiseTelemetryEvent("video_effect_applied",{}),this.event("onVideoEffectApplied").raise()})),this.effectsManager.on("onEffectsError",((e,t,i)=>this.event("onEffectsError").raise(e,t,i)))],this.subscribeOnStreamManagerEvents(),this.subscribeOnDeviceEnumeratorEvents(),this.deviceList.length&&this.onSelectedDevicesChanged(this.deviceSelection.selectedDevices,!1),this.createChildDeviceManager=t=>new e(t,i,new fk(i),r,s,a,o,l,c,d)}get deviceList(){return Dk.list.devices}get isDeviceListAvailable(){return Dk.isDeviceListAvailable}get isAudioOutputSelectionSupported(){return this.configProvider.userAgentConfig.isAudioOutputSelectionSupported}get effectsManager(){return this.effectsManagerInternal}createPreviewRenderer(e,t){const i=new uk(e,this,this.logger.createChild("videorenderer"),this.configProvider,t);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(i.getVideoElement()),this.subscribeOnRendererEvents(i),i}async askDevicePermission(e){await this.isDeviceListAvailable.promise;const t=await this.permissionManager.askDevicePermission(e);if(this.configProvider.config.devices.enumerateDevicesAfterADP)try{await Dk.enumerateDevices()}catch(e){this.logger.safe.warn(`Post-ADP device enumeration failed: ${tt(e)}`)}return t}getPermissionState(e){return this.permissionManager.getPermissionState(e)}handlePermissionStateChange(){this.diagnostics&&(this.diagnostics.permissionStates=this.permissionManager.knownPermissionStates),this.event("onPermissionStateChanged").raise()}onMediaStreamUpdateRequested(e,t=!1){if("Video"===e&&(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(e)));this.event("onStreamUpdateRequested").raise(e,t)}createAudioRenderer(){const e=new ek(this.logger.createChild("CustomAudioRenderer"),this.configProvider),t=e.id;this.clientAudioRenderers.set(t,e);const i=e.play.bind(e),n=e.stop.bind(e);return this.raiseTelemetryEvent("custom_audio_renderer_created",this.getSelectedDevices()),{play:i,stop:n,dispose:()=>{this.clientAudioRenderers.get(t)?.dispose(),this.clientAudioRenderers.delete(t)},setMuted:(t,i=be())=>e.setMuted(t,i),isMuted:()=>e.muted}}setAudioSharingRequested(e){this.audioSharingRequested=e}createDevicesHandle(e,t,i){const n=e.sharing?"ScreenShare":e.video?"Video":"Audio";return new Ok(this.logger.createChild("DevicesHandle"),this.getMediaStream({...e,...i&&{deviceId:i},withTimeout:!1,withEffect:!1,audioProcessingFlags:this.audioProcessingFlags,force:!1,withOverridenStream:this.customDeviceMediaStreamMap.get(n)?.active&&this.customDeviceMediaStreamMap.get(n)},t))}shareSystemSound(e){this.configProvider.config.postponeAudioMixerForAudioSharing&&(this.audioSharingRequested=e,this.event("onAudioSharingToggled").raise(e))}getAllowedModalities(){const e=tn(this.permissionManager.browserPermittedModalities);return this.hasDeviceType("microphone")||(e.audio=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive]),this.hasDeviceType("camera")||(e.video=[Gi.MEDIA_STATE.inactive,Gi.MEDIA_STATE.receive]),e}getRawDeviceMediaStream(e,t){if("ScreenShare"!==e&&!this.hasDeviceType(this.getDeviceType(e)))throw new Error("NoInputDevice");this.audioSharingRequested=t;const i=this.getStreamHandlerByType(e);if(!i)return this.logger.safe.debug(`method not found for ${e}`),null;const n=this.rawDeviceStreamManager.createIRawStreamClient(i,e);return this.raiseTelemetryEvent("IRawStream_client_created",e),n}setRawMediaStream(e,t){if(!e)throw this.logger.error(`Could not set ${e} as to ${t}`),new Error("InvalidStream");this.customDeviceMediaStreamMap.set(t,e),this.onMediaStreamUpdateRequested(t),this.raiseTelemetryEvent("set_raw_outgoing_media_stream",t)}unsetRawMediaStream(e){this.customDeviceMediaStreamMap.get(e)?(this.customDeviceMediaStreamMap.delete(e),this.onMediaStreamUpdateRequested(e),this.raiseTelemetryEvent("unset_raw_outgoing_media_stream",e)):this.logger.safe.debug("no custom stream")}async setVideoEffects(e){return this.effectsManager.setEffectType("Video",e)}async sendMessageDeviceVideoEffectsAsync(e,t){return this.effectsManager.processingVideoEffectMessage(t)}async setAudioEffects(e){return this.effectsManager.setEffectType("Audio",e)}async getAudioStream(e,t,i=!1){const n=this.configProvider.config.devices.enumerateBeforeGettingStream;return n&&("always"!==n&&Dk.isPolling||await Dk.enumerateDevices()),this.getMediaStream({audio:!0,withTimeout:this.permissionManager.isPermissionKnown("microphone"),withEffect:!i&&this.effectsManager.isEffectEnabled("Audio"),audioProcessingFlags:this.getAudioProcessingFlags(),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Audio")?.active&&this.customDeviceMediaStreamMap.get("Audio")},t)}async getVideoStream(e,t,i=!1,n){const r=this.configProvider.config.devices.enumerateBeforeGettingStream;return r&&("always"!==r&&Dk.isPolling||await Dk.enumerateDevices()),this.getMediaStream({video:!0,withTimeout:this.permissionManager.isPermissionKnown("camera"),withEffect:!i&&this.configProvider.config.enableVideoEffects&&this.effectsManager.isEffectEnabled("Video"),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Video")?.active&&this.customDeviceMediaStreamMap.get("Video"),videoMaxFS:n},t)}getDisplayStream(e,t=!1){const i=!(!this.configProvider.config.enableAudioSharing||!this.audioSharingRequested);return this.getMediaStream({audio:i,sharing:!0,withTimeout:!1,withEffect:!1,audioProcessingFlags:i?0:void 0,force:!1,withOverridenStream:!t&&this.customDeviceMediaStreamMap.get("ScreenShare")?.active&&this.customDeviceMediaStreamMap.get("ScreenShare")},e)}async enumerateDevicesAsync(){return await this.isDeviceListAvailable.promise,this.getDeviceDescriptions(this.deviceList)}async getDeviceNameAsync(e){await this.isDeviceListAvailable.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.label??""}async getSpeakerDeviceDomIdAsync(e){await this.isDeviceListAvailable.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.deviceId??""}selectDevices(e){return this.pendingDevices?(this.logger.safe.info(`Overriding device selection until enumeration is complete with ${JSON.stringify(dm(this.pendingDevices))}`),void(this.pendingDevices=e)):this.isDeviceListAvailable.isPending?(this.logger.safe.info("Postponing device selection until enumeration is complete"),this.pendingDevices=e,void this.isDeviceListAvailable.promise.then((()=>{this.logger.safe.info("Performing postponed device selection");const e=this.pendingDevices;this.pendingDevices=null,this.selectDevices(e)}))):void this.deviceSelection.selectDevices(e)}getSelectedDevices(){return this.toSelectedDevices(this.deviceSelection.selectedDevices)}setAudioProcessingFlags(e){e!==this.audioProcessingFlags&&(this.logger.debug(`Setting audio processing flags: ${this.audioProcessingFlags} -> ${e}`),this.audioProcessingFlags=e,this.event("onStreamUpdateRequested").raise("Audio"))}getOutputDeviceId(){return this.selectedDevices.speaker?.deviceId}getDeviceDescriptions(e){return(e||this.deviceList).map((e=>e.toDeviceDesc()))}getDevicesCount(){return this.deviceList.reduce(((e,t)=>(e[t.type]++,e)),{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((e=>e.dispose())),this.deviceManagerSubscriptions=null,this.virtualDeviceSubs?.forEach((e=>e.forEach((e=>e.dispose())))),this.virtualDeviceSubs?.clear(),this.virtualDeviceSubs=null,this.virtualDeviceRecord?.forEach((e=>e.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(e,t){const i=e.length?e.map((({id:e},t)=>{const i=this.createChildDeviceManager(this.logger.createChild(`VirtualDevice-${t}`));return i.selectDevices({camera:e}),i})):[this.createChildDeviceManager(this.logger.createChild("VirtualDevice"))],n=new Fk(i,t),r=n.id,s=[n.on("onVideoEffectApplied",((...e)=>this.event("onVideoEffectApplied").raise(...e))),n.on("onVideoEffectsEvent",((...e)=>this.event("onVideoEffectsEvent").raise(...e))),n.on("onDeviceTelemetryEvent",((...e)=>this.event("onDeviceTelemetryEvent").raise(...e))),n.on("onVideoEffectsTelemetryEvent",((...e)=>this.event("onVideoEffectsTelemetryEvent").raise(...e))),n.on("onDevicesPermissionChanged",((...e)=>this.event("onDevicesPermissionChanged").raise(...e))),n.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))];return this.virtualDeviceSubs.set(r,s),this.virtualDeviceRecord.set(r,n),Dk.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.raiseTelemetryEvent("register_virtual_device",{deviceCount:i.length,id:r}),this.event("onVirtualDevicesChanged").raise(),r}async unregisterVirtualDevice(e){this.virtualDeviceRecord.has(e)?(this.virtualDeviceSubs.get(e).forEach((e=>e.dispose())),this.virtualDeviceSubs.delete(e),this.virtualDeviceRecord.get(e).dispose(),this.virtualDeviceRecord.delete(e),Dk.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.event("onVirtualDevicesChanged").raise(),this.raiseTelemetryEvent("unregister_virtual_device",{id:e})):this.logger.error(`No virtual device found with id ${e}`)}getRegisteredDevices(){return Array.from(this.virtualDeviceRecord.values())}async getNrgLevelPollerForDeviceTuner(){return await this.audioStreamAnalyzerWrapper.init(),this.audioStreamAnalyzerWrapper}getAudioProcessingFlags(){if(!this.effectsManager.shouldFallbackToNativeProcessing("Audio"))return this.audioProcessingFlags??this.configProvider.config.defaultAudioProcessingFlags;this.logger.safe.info("Applying netive audio processing flags")}disposeClientAudioRenderer(){this.clientAudioRenderers.size&&(this.clientAudioRenderers.forEach((e=>{e.dispose()})),this.clientAudioRenderers.clear(),this.raiseTelemetryEvent("custom_audio_renderer_disposed",this.getSelectedDevices()))}disposeRawStreamAccess(){this.rawDeviceStreamManager.disposeAll(),this.rawDeviceStreamManager=null}toSelectedDevices(e){return Object.entries(e).reduce(((e,[t,i])=>(i&&(e[t]=i.guid),e)),{})}getStreamConstraints(e){const t={deviceId:e?.deviceId||void 0};return this.configProvider.config.audioSampleRate&&(t.sampleRate=this.configProvider.config.audioSampleRate),t}hasDeviceType(e){return Zi(this.deviceList).some((t=>t.type===e))}getConstraints(e){if(!e.audio&&!e.video&&!e.sharing)throw new Error("requesting nothing");if(this.logger.safe.info(`retrieving media stream: ${JSON.stringify(e)}`),e.sharing){let t;const i=this.selectedDevices.audioIngestDevice;return t=i&&e.deviceId?{deviceId:i.deviceId}:e.audio&&!e.deviceId?{deviceId:Gi.SYSTEM_AUDIO_SOURCE_ID}:void 0,{audio:t,sharing:{deviceId:e.deviceId||Gi.DISPLAY_SOURCE_ID},withTimeout:e.withTimeout,withEffect:!1,audioProcessingFlags:e.audioProcessingFlags,force:!1,withOverridenStream:e.withOverridenStream}}const t=this.selectedDevices.microphone,i=this.selectedDevices.camera,n=e.audio&&t,r=e.video&&i;if(!n&&!r)throw{type:Gi.MEDIA_ERROR.noDeviceSelected,detail:`audio requested ${e.audio}, video requested: ${e.video} Devices: ${JSON.stringify(this.deviceList.map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords)))))}`};const s=this.getStreamConstraints(t),a=this.getStreamConstraints(i);let o=e.audioProcessingFlags;return void 0!==o&&e.audio&&!e.video&&t?.capabilities&&(t.capabilities.echoCancellation&&!t.capabilities.echoCancellation.includes(!!(2&o))&&(o^=2),t.capabilities.autoGainControl&&!t.capabilities.autoGainControl.includes(!!(1&o))&&(o^=1),t.capabilities.noiseSuppression&&!t.capabilities.noiseSuppression.includes(!!(4&o))&&(o^=4)),o!==e.audioProcessingFlags&&this.logger.safe.warn(`Unable to fulfill processing flags ${e.audioProcessingFlags}, using ${o} instead`),{audio:e.audio?s:void 0,video:e.video?a:void 0,withTimeout:e.withTimeout,withEffect:e.withEffect,audioProcessingFlags:o,force:e.force,withOverridenStream:e.withOverridenStream,videoMaxFS:e.videoMaxFS}}getMediaStream(e,t){const i=this.getConstraints(e),n=this.mediaStreamManager.getMediaStream(i,t);return this.subscribeOnStreamEvents(n),n.start().then((()=>{const i=n.hasAudio(),r=n.hasVideo();i&&(this.signalDeviceGood("Audio",n.rawTrack.muted),this.audioStreamAnalyzerWrapper.setStream(n,t)),r&&this.signalDeviceGood(n.mediaType,n.rawTrack.muted),this.permissionManager.update(e,e)})).catch((t=>this.handleUserMediaError(e,t))),n}signalDeviceGood(e,t){this.ufdManager.signalDeviceEvent(0,"Good",e,this.id),this.ufdManager.signalDeviceEvent(2,"Good",e,this.id),this.ufdManager.signalDeviceEvent(4,"Good",e,this.id),t||"Audio"!==e&&!this.configProvider.config.raiseVideoMuteUfd||this.ufdManager.signalDeviceEvent(3,"Good",e,this.id)}handleUserMediaError(e,t){const i=this.getMediaType(e),n=e.audio&&e.video,r=(e,t)=>{!n&&this.ufdManager.signalDeviceEvent(e,t,i,this.id)},s=e=>{!n&&"Audio"===i&&this.diagnostics.registerAudioRenderError(e)};switch(t.type){case Gi.MEDIA_ERROR.permissionDeniedError:"ScreenShare"!==i&&(r(4,"Bad"),s(0x800000000000),this.configProvider.config.permissions.persistOnDeniedError&&this.refreshPermissions(e));break;case Gi.MEDIA_ERROR.permissionDeniedBySystemError:r(4,"Bad"),s(0x800000000000);break;case Gi.MEDIA_ERROR.sourceUnavailableError:r(0,"Bad"),s(512);break;case Gi.MEDIA_ERROR.mediaStreamRequestTimedOut:r(2,"Bad"),s(35184372088832);break;default:this.logger.safe.error(`getMediaStream() error: ${tt(t)}`),r(0,"Bad"),s(4194304)}}refreshPermissions(e){const t=e.audio&&!e.video,i=!e.audio&&e.video;t?this.permissionManager.update({audio:!0},{audio:!1}):i&&this.permissionManager.update({video:!0},{video:!1})}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`mediaType is not defined for this constraint ${JSON.stringify(e)}`)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamClientStarted",((e,t)=>this.onStreamStarted(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),t.push(e.on("onStreamClientEnded",((e,t)=>this.onStreamEnded(e,t)))),t.push(e.on("onStreamClientMuted",((e,t)=>this.onStreamMuted(e,t)))),t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),this.configProvider.config.useRawMediaApiForVideoEffects&&t.push(e.on("onStreamClientDisposed",(e=>this.removeVideoEffectStream(e)))),this.streamSubscriptions.set(e,t)}async removeVideoEffectStream(e){if(e.getCurrentConstraints().withEffect){this.logger.safe.info(`this.activeVideoEffectSub: ${this.activeVideoEffectSub} to be disposed`),this.activeVideoEffectSub?.dispose();const e=await(this.activeVideoStreamForEffect?.getMediaStream());this.effectsManager.stopEffect("Video",e)}}unsubscribeFromStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}subscribeOnRendererEvents(e){const t=[];t.push(e.on("onRendererDisposed",(e=>this.onRendererDisposed(e)))),t.push(e.on("onRendererStarted",(e=>this.onRendererStarted(e)))),this.rendererSubscriptions.set(e,t)}unsubscribeFromRendererEvents(e){this.rendererSubscriptions.has(e)&&(this.rendererSubscriptions.get(e).forEach((e=>e.dispose())),this.rendererSubscriptions.delete(e))}subscribeOnStreamManagerEvents(){this.streamManagerSubscriptions=[],this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onAllStreamsRemoved",(()=>this.onAllStreamsRemoved()))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamAcquired",(e=>this.onStreamAcquired(e)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamCreated",((e,t)=>this.onStreamCreated(e,t)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamDisposing",((e,t)=>this.onMasterStreamDisposing(e,t))))}subscribeOnDeviceEnumeratorEvents(){this.deviceEnumerator.on("onDeviceEnumerationfailed",(e=>this.raiseTelemetryEvent("enumeration_failed",{error:e})))}unsubscribeFromStreamManagerEvents(){this.streamManagerSubscriptions.forEach((e=>e.dispose()))}async updateRenderersAsync(){try{await Promise.all(this.activeRenderers.map((e=>e.updateStreamAsync()))),this.logger.safe.info("Renderers updates finished")}catch(e){this.logger.safe.error(`Error updating renderers: ${tt(e)}`)}}onSelectedDevicesChanged(e,t){const i=this.selectedDevices;if(this.selectedDevices=e,this.diagnostics.setSelectedDevices(e,t),!("camera"in i^"camera"in this.selectedDevices||"microphone"in i^"microphone"in this.selectedDevices)){const e=this.toSelectedDevices(this.selectedDevices),t=this.toSelectedDevices(i);this.event("onSelectedDevicesChanged").raise(e,t),e.microphone!==t.microphone&&(this.rawDeviceStreamManager.notifyChange("Audio"),this.audioStreamAnalyzerWrapper.updateStreamAfterDeviceChange()),e.camera!==t.camera&&this.rawDeviceStreamManager.notifyChange("Video"),this.clientAudioRenderers.forEach((e=>{e.setOutputDevice(this.getOutputDeviceId())}))}const n=this.configProvider.config.devices.piiSafeWords;this.raiseTelemetryEvent("selected_devices_changed",{microphone:this.selectedDevices.microphone&&fn(this.selectedDevices.microphone.label,n),camera:this.selectedDevices.camera&&fn(this.selectedDevices.camera.label,n),speaker:this.selectedDevices.speaker&&fn(this.selectedDevices.speaker.label,n),fromInterface:t}),this.updateRenderersAsync()}onDevicesChanged(e,t){this.event("onDevicesChanged").raise(e,t),this.mediaStreamManager.onDevicesChanged(e),this.diagnostics.setDeviceList(e,t,this.getDeviceListDebugInfo());const i=this.getDevicesCount(),n=i.microphone>0,r=i.speaker>0;this.ufdManager.signalEvent("ZeroCaptureDevicesEnumerated",n?"Good":"Bad"),n||this.diagnostics.registerAudioCaptureError(1),this.isAudioOutputSelectionSupported&&(this.ufdManager.signalEvent("ZeroRenderDevicesEnumerated",r?"Good":"Bad"),r||this.diagnostics.registerAudioRenderError(1));const s=new Map;let a=1;this.raiseTelemetryEvent("devices_changed",{devices:e.map((e=>{const t=s.get(e.groupId)||a++;return s.set(e.groupId,t),{label:fn(e.label,this.configProvider.config.devices.piiSafeWords),isSystemDefault:e.isSystemDefault,kind:e.kind,type:e.type,capabilities:e.capabilities,groupId:`${t}`}})),debug:this.getDeviceListDebugInfo()})}getDeviceListDebugInfo(){return Dk.list.debugInfo}raiseTelemetryEvent(e,t){this.logger.safe.info(`Device event: ${e}: ${JSON.stringify(this.scrubPayload(e,t))}`);const i={eventType:e,timestamp:Date.now(),payload:t};this.diagnostics.registerDeviceTelemetryEvent(nn(i)),this.diagnostics.logAudioDeviceError(e,t),this.event("onDeviceTelemetryEvent").raise(i)}scrubPayload(e,t){return"devices_changed"===e?{devices:Zi(t.devices).map((e=>um(e,this.configProvider.config.devices.piiSafeWords))),debug:t.debug}:t}async onStreamStarted(e,t){if(this.permissionManager.browserPermittedModalities.audio.some((e=>e===Gi.MEDIA_STATE.send))||this.permissionManager.browserPermittedModalities.video.some((e=>e===Gi.MEDIA_STATE.send)))try{await Dk.enumerateDevices()}catch(e){this.logger.safe.warn(`onStreamStarted device enumeration failed: ${tt(e)}`)}if(e.rawTrack){switch(e.mediaType){case"Audio":this.deviceEnumerator.startDevicePolling(),this.updateActiveMicrophone(e,t);break;case"Video":this.deviceEnumerator.startDevicePolling()}this.configProvider.config.useRawMediaApiForVideoEffects&&e.getCurrentConstraints().withEffect&&(this.activeVideoEffectSub=this.effectsManager.on("onVideoStreamQualityChanged",((t,i,n)=>e.onVideoStreamQualityChanged(t,i,n))))}else this.logger.safe.warn(`stream:${e.id} is already disposed`)}updateActiveMicrophone(e,t){if(e.deviceId){const i=this.deviceList.find((t=>t.deviceId===e.deviceId));if(!i&&"default"!==e.deviceId)return void this.logger.safe.error("Active device not found",`Device id from track: '${De(e.deviceId)}', known devices: [${this.deviceList.map((e=>JSON.stringify(um(e,this.configProvider.config.devices.piiSafeWords))))}]}`,JSON.stringify(hm(t)));i&&"default"!==e.deviceId&&t.audio&&t.audio.deviceId===Gi.MEDIA_DEVICE.defaultId&&Dk.list.updateActiveMicrophone(i)}}onStreamDisposing(e){this.unsubscribeFromStreamEvents(e)}onStreamMuted(e,t){("Audio"===e.mediaType||this.configProvider.config.raiseVideoMuteUfd)&&this.ufdManager.signalDeviceEvent(3,t?"Bad":"Good",e.mediaType,this.id),"Audio"===e.mediaType&&this.event("onAudioStreamMuted").raise(t),this.raiseTelemetryEvent(t?"stream_muted":"stream_unmuted",e.mediaType)}onStreamEnded(e,t){t.error?(this.raiseTelemetryEvent("stream_ended_error",{mediaType:e.mediaType,error:{type:t.error.name,detail:t.error.message}}),"SourceUnavailableError"===t.error.name&&this.ufdManager.signalDeviceEvent(0,"Bad","Audio",this.id)):("Audio"!==e.mediaType&&"Video"!==e.mediaType||this.ufdManager.signalDeviceEvent(0,"Bad",e.mediaType,this.id),this.raiseTelemetryEvent("stream_ended",e.mediaType))}onStreamError(e,t){this.raiseTelemetryEvent("stream_error",{mediaType:e.mediaType,error:t})}onAllStreamsRemoved(){this.deviceEnumerator.stopDevicePolling(),this.audioSharingRequested=!1}onStreamAcquired({id:e,mediaType:t,timestamp:i,resolution:n,withAudio:r,source:s,sampleRate:a}){0!==i&&this.raiseTelemetryEvent("stream_acquired",{id:e,mediaType:t,timestamp:i,resolution:n,withAudio:r,source:s,sampleRate:a})}onStreamCreated(e,t){this.raiseTelemetryEvent("stream_created",{id:e,mediaType:t})}onMasterStreamDisposing(e,t){this.raiseTelemetryEvent("stream_disposed",{id:e,mediaType:t})}onRendererDisposed(e){Qi(this.activeRenderers,(t=>t===e)),this.domOverrides.onMediaElementRemoved?.(e.getVideoElement()),this.unsubscribeFromRendererEvents(e)}onRendererStarted(e){this.activeRenderers.push(e),this.event("onLocalRendererStarted").raise(e)}onVideoEffectsQualityEventHandler(e){const t=this.deviceSelection.selectedDevices.camera;if(t?.deviceId){const i={type:"onVideoEffectQualityChanged",payload:{message:e.message,effectType:e.effectType}};this.event("onVideoEffectsEvent").raise(t.deviceId,i)}}getDeviceType(e){if("Video"===e)return"camera";if("Audio"===e)return"microphone";throw new Error(`DeviceType for mediaType: ${e} doesn't exist`)}getStreamHandlerByType(e){return"Video"===e?()=>this.getVideoStream(!1,"rawStream",!0):"Audio"===e?()=>this.getAudioStream(!1,"rawStream",!0):"ScreenShare"===e?()=>Promise.resolve(this.getDisplayStream("rawStream",!0)):null}},Jk=Z,Yk=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:Gi.ALLOWED_CONTENT_TYPES.SDP_NGC,webrtcMediaContentType:Gi.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:[Gi.MEDIA_ERROR.iceConnectionError,Gi.MEDIA_ERROR.noNetworkError,Gi.MEDIA_ERROR.srtpError,Gi.MEDIA_ERROR.incompatibleOffer,Gi.MEDIA_ERROR.internalError].join(","),forceReconnectErrors:[Gi.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,webrtcSendBandwidthAlwaysReportAfterDrop:!1,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:Ww.Normal,eventLatencyRealTime:Ww.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,useRawMediaApiForVideoEffects:!1,waitForVideoEffectStreamStart:!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,asyncInitialization:!1,initializationTimeoutMs:1e4,backgroundMode:!1,performanceThresholdMs:8,performanceWindowDurationSecs:10,defaultVqeMode:Sh.VqeMode.Off,callType:Sh.CallType.Conference,audioUsageMode:Sh.AudioUsageMode.Default,performanceProfile:Sh.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:vh.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:vh.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,enabledStatsProcessors:{dataChannel:!0,transport:!0,audio:!0,video:!0,sharing:!0,bandwidth:!0,recvVideoStreamsCounter:!0,aggregated:!0,multiview:!0,simulcast:!0,networkInfo:!0,macroblockRate:!0},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:!0,useNewSendBandwidthCalculation:!0,useNewStatsForLocalVideoStreamWatcher:!0,useFallbackToNewExtensions:!0,logContributingSourcesError:!0,useTwoSampleVBSSFreezeDetection:!0,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:Gi.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:Gi.RES_TABLE.SEND,recvResolutionTableOverride:Gi.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,enabledViaApi:!1,maxParticipantNumber:20,debounceTime:1e3,list:{},remoteUFDHandlerV2:!0,maxNumberOfBadUFDsForThrottling:3,throttlingTimeInterval:6e4,disableInterval:6e4,bundlingInterval:6e3,maxNumberOfBundles:4,bundlingWindowInterval:6e4},fixOpusComfortNoise:!0,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,fixExtraNegotiation:!1}}getEnforcedSettings(){return{}}},Qk=class extends Yk{getInitialSettings(){const e=super.getInitialSettings();return e.oneStreamPerDeviceType=!0,e.removeUnsupportedVideoModality=!0,e.webrtcPranswerWaitForMediaPollingInterval=100,e.diagnostics.features.useLastSampleDeltaPerSecondConverter=!0,Ot.isFormFactor("Mobile")&&(e.webrtcCameraOpenFs=920,e.webrtcVideoCapabilityMaxFS=920),e}},Zk=class extends Yk{getEnforcedSettings(){return{useAudioAnalyzer:!1,enableAudioSharing:!1}}},Xk=class extends Qk{getEnforcedSettings(){const e={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 Ot.isVersionGreaterOrEqual("15.0")||(e.statsAllowAnyVideoSendTrack=!0),Ot.isVersionGreaterOrEqual("16.0")&&Ot.isFormFactor("Mobile")&&(e.enablePermissionsWorkaround=!0),Ot.isVersionGreaterOrEqual("17.0")&&Ot.isFormFactor("Mobile")&&(e.recoverOnStreamUnmute=!0,e.enablePlayVideoOnStreamUnmuteWorkaround=!0),e}},eO=class extends Qk{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}}},tO=class extends Yk{getEnforcedSettings(){const e={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"}],setMinFpsForWebkit:!0};return"43"===Pp()?(0,Jk.mergeWith)(e,{postponeAudioMixerForAudioSharing:!0,enableAudioSharing:!0,filterCodecsInSdp:!0,webrtcPranswerWaitForMediaPollingInterval:250,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!1}},localPreviewMirroringSupported:!0,webrtcContributingSourcesPollingStartDelay:3e3,devices:{setSinkImmediately:!1}}):"44"===Pp()?(0,Jk.mergeWith)(e,{postponeAudioMixerForAudioSharing:!0,enableAudioSharing:!0,disposeSendersSync:!0,disposeStreamsSync:!0,filterCodecsInSdp:!0,useInactiveAudioTrack:!0,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!0,minFsForSimulcast:[920]}},webrtcPranswerWaitForMediaPollingInterval:250,webrtcContributingSourcesPollingStartDelay:5e3}):"45"===Pp()?(0,Jk.mergeWith)(e,{setParametersMaxBitrateUndefined:!0,specCompliantSimulcastMultiparty:{video:{useApplyConstraints:!0,minFsForSimulcast:[920]}}}):e}},iO=class extends Qk{getEnforcedSettings(){const e={};return Ot.isVersionGreaterOrEqual("74.0")&&(e.webrtcSimulcastSessionEnabled=!0,e.webrtcAllowRestoreKeyframe=!0,e.enableAudioSharing=!0),Ot.isVersionGreaterOrEqual("122.0")&&(e.useKeyFrameApi=!0),Ot.isFormFactor("RoomAudioProcessing")&&(e.defaultAudioProcessingFlags=0,e.wasmvqe={enableAec:!1,enableVqe:!1,backgroundMode:!1},e.wasmdns={enableNoiseSuppression:!1,backgroundMode:!1}),(Ot.isBrowser("CiscoOS")||Ot.isBrowser("ZoomRoom"))&&(e.waitReportStatsAtCallStop=!0,e.setDisconnectAfterCleanUp=!0),Ot.isFormFactor("Mobile")&&(e.enableAudioSharing=!1,e.audioRendererFailedReconnectTimes=3,e.devices={pollingIntervalIdle:1e4}),Ot.isBrowser("SamsungTV")&&(e.useSetParametersToApplyCapabilities=!0),Ot.isVersionGreaterOrEqual("98.0")&&Ot.isFormFactor("Desktop")&&(e.specCompliantSimulcastMultiparty={video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!0,minFsForSimulcast:[920]},maxBrControlEnabled:!0,allowResLimit:!0,disableTilde:!1},e.extmapAllowMixedMultiparty=!0,e.enableVlaMultiparty=!0,e.allowRemoteVlaMultiparty=!0,e.enableNonAdvVlaMultiparty=!0,e.useMediaQualityControllerMultiparty=!0),Ot.isVersionGreaterOrEqual("100.0")&&(e.redReceiveEnabledMultiparty=!0),e.webcv={useWasmEffects:!0,processorType:vh.ProcessorType.Wasm},e}},nO=class{constructor(e){this.settings=e,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(e,t){this.maxBandwidthInKbps=Math.floor((e.maxBandwidthInBps||0)/1e3),this.isTransportUnbundled=this.settings.forceUnbundledTransport||this.settings.enableQosSupport&&(e.enableMediaQoS||!!e.mediaPortRanges),this._mediaPortRanges=e.mediaPortRanges,this.simulcastSessionEnabled=this.settings.webrtcSimulcastSessionEnabled&&pm(this.settings.checkSupportForWebrtc_1_0),this._noiseSuppressionMode=e.noiseSuppressionMode||"Auto",this._enableMediaBypass=this.settings.allowMediaBypass&&e.enableMediaBypass,this.webrtcRejectedFeatures=this._enableMediaBypass?"":this.settings.webrtcRejectedFeatures,this.webrtcRequiredFeatures=this._enableMediaBypass?"":this.settings.webrtcRequiredFeatures,this.spatialAudioEnabled=t?t.spatialAudioEnabled:e.enableSpatialAudio}get mediaBypassEnabled(){return this._enableMediaBypass}get noiseSuppressionMode(){return this._noiseSuppressionMode}get maxBandwidthInKbps(){return this._maxBandwidthInKbps}set maxBandwidthInKbps(e){this._maxBandwidthInKbps=e,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}},rO=class extends Vi{constructor(e,t,i={}){super(e),this.logger=e,this.platformCallConstraintsProvider=t,this.platformConfig=Ot.isEngine("ChromiumAVD")?new Zk:Ot.isEngine("Safari")?new Xk:Ot.isEngine("Firefox")?new eO:Ap()?new tO:Ot.isEngine("Chromium")?new iO:new Yk,this.sessionCount=0,this._consoleOverrides={},this.uaConfig=new Vp(this),this.mediaConfiguration={},this.configReceivedDefer=new Kt,this.logger.info(`initializing configProvider ${this.constructor.name} from BrowserInfo: ${Ot.toString()}`),this.initialSettings=(0,av.mergeWith)({},(0,av.cloneDeep)(this.platformConfig.getInitialSettings()),(0,av.cloneDeep)(i),this.platformConfig.getEnforcedSettings(),xm),this.settings=this.initialSettings,this.settingsWithoutOverrides=this.initialSettings,this.stackSettings=(0,av.cloneDeep)(i),this.mediaSettings=new nO(this.settings),this.platformCallConstraintsProvider.changed((()=>{this.updateSettings();const e=this.platformCallConstraintsProvider.constraints,t=this.logger.createChild("SettingsToCallConstraintsConverter"),i=Am(t,this.settings,e);this.platformCallConstraintsProvider.addCallConstraintsTelemetryEvent(i,"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(e){return this.platformCallConstraintsProvider.setConstraints(e),e}getCallConstraintsTelemetry(){return this.logger.error("Not supported globally, returning empty array"),[]}addCallConstraintsTelemetryEvent(e,t){this.logger.error("Not supported globally")}overrideMaxSessionBandwidth(e){return this.logger.error("Not supported globally"),!1}getIceTransportPolicy(){return this.logger.warn(`Not supported globally, returning default ${Gi.ICE_TRANSPORT_POLICY.all}`),Gi.ICE_TRANSPORT_POLICY.all}setIceTransportPolicy(e){this.logger.error("Not supported globally")}getConfigReceivedOrTimeout(){return this.configReceivedDefer.promise}getConfigView(e,t){const i=e?"Multiparty":"1on1",n=Object.entries((0,av.cloneDeep)(this.settings)).reduce(((e,[t,n])=>(e[t]=n,t.endsWith(i)&&(e[t.replace(i,"")]=n),e)),{}),r=new nO(n);return r.setMediaConfiguration(this.mediaConfiguration,t?.mediaConfig),new Um(this.logger.createChild("ConfigProviderView"),n,r,this.userAgentConfig,this.countryCode,this.platformCallConstraintsProvider,t?.getCallConstraints())}updateConfig(e,t,i,n){this.etag=t||this.etag,this.configIds=i||this.configIds,this.country=n||this.country,this.event("newConfigReceived").raise(e,t,i),this.settingsWithoutOverrides=(0,av.mergeWith)({},this.settingsWithoutOverrides,e,xm),this.updateSettings(),this.configReceivedTimeout&&(window.clearTimeout(this.configReceivedTimeout),this.configReceivedTimeout=void 0),this.configReceivedDefer.resolve()}updateSessionCount(e){this.sessionCount=e,0===e&&this.pendingSettings&&(this.logSettings("Applying pending configuration",this.pendingSettings),this.updateSettings(this.pendingSettings),this.pendingSettings=null),e>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(e){this.mediaConfiguration=e,this.mediaSettings.setMediaConfiguration(e)}get mediaConfig(){return this.mediaSettings}get ETag(){return this.etag}get ecsConfigIds(){return this.configIds}setConsoleOverrides(e){this._consoleOverrides=(0,av.mergeWith)({},this._consoleOverrides,e,xm),this.updateSettings()}setConsoleOverride(e,t){this._consoleOverrides[e]=t,this.updateSettings()}clearConsoleOverride(e){delete this._consoleOverrides[e],this.updateSettings()}clearAllConsoleOverrides(){this._consoleOverrides={},this.updateSettings()}updateSettings(e=this.settingsWithoutOverrides){if(this.sessionCount>0)return this.pendingSettings=e,void this.logSettings("pendingSettings updated",e);this.settings=this.mergeSettings(e),this.event("configUpdated").raise(),this.logSettings("Settings updated",this.settings)}logSettings(e,t){const i=Object.entries(t).reduce(((e,[t,i])=>(i!==this.initialSettings[t]&&(e[t]=i),e)),{});this.logger.safe.info(`${e}: ${JSON.stringify(i)}`)}mergeSettings(e){if(!e.enablePlatformCallConstraints&&!this._consoleOverrides.enablePlatformCallConstraints)return this.mergeSettingsWithConsoleOverrides(e);let t=e;const{setConsoleOverridesBeforeCallConstraints:i}=this._consoleOverrides;return i&&(t=this.mergeSettingsWithConsoleOverrides(t)),t=this.mergeSettingsWithPlatformConstraints(t),i||(t=this.mergeSettingsWithConsoleOverrides(t)),t}mergeSettingsWithConsoleOverrides(e){return this.logger.safe.info(`Merging settings with console overrides: ${tt(this._consoleOverrides)}`),(0,av.mergeWith)({},e,this._consoleOverrides,xm)}mergeSettingsWithPlatformConstraints(e){const t=this.platformCallConstraintsProvider.getSettings(e);return this.logger.safe.info(`Merging settings with platform call constraints: ${tt(t)}`),(0,av.assign)({},e,t,xm)}},sO=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(e){this.data.activeStrategy=e}resetState(){return this.data.lastMsgOrigin=void 0,this}recordHistoryEvent(e,t){var i,n;this.data.changedCountDSH++,(i=this.data)[n=t+"DSH"]??(i[n]={count:0,duplicateCount:0}),this.data.lastMsgOrigin=t;const r=this.data[t+"DSH"];r.count++,r.firstMsgTime??(r.firstMsgTime=Date.now()),an(this.data.lastHistory,e)&&r.duplicateCount++,this.data.lastHistory=e,this.data.lastMsgDate=Date.now()}getObjectRef(){return this.data}},aO=class{constructor(e,t,i,n,r,s,a,o){this.mediaStream=e,this.receiver=t,this.modality=i,this.sourceStreamId=n,this.controller=r,this.videoCapabilities=s,this.getMaxAllowedVideoFS=a,this.substreamIndex=o,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(e){this.msi=e;const t=this.operations.then((()=>{let t;return this.videoCapabilities&&(this.videoCapabilities.resetToInitial(),this.getMaxAllowedVideoFS&&this.videoCapabilities.setMaxFS(Math.min(this.getMaxAllowedVideoFS(),this.videoCapabilities.getMaxFS())),t=this.videoCapabilities.buildFmtp(),this.videoCapabilities.resetToInitial()),this.controller.requestSource(this.mediaStream.id,e,t)}));return this.operations=t.catch((()=>{})),t}},oO=class{constructor(e){this.subscription=e}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(e){this.checkDisposed(),this.mediaStreamChanged=e,this.subscription.isStreamReady&&this.notifyMediaStreamChanged()}setOnErrorHandler(e){this.checkDisposed(),this.error=e}dispose(){this.subscription&&(this.subscription.dispose(be(),this),this.subscription=null)}unsubscribe(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null)}notifyMediaStreamChanged(){if(this.mediaStreamChanged){const e=this.subscription.stream,t=this.subscription.isStreamReady;this.mediaStreamChanged(e&&t?e.getMediaStream():null)}}notifyError(e){this.error&&this.error(e)}checkDisposed(){if(!this.subscription)throw new Error("subscription disposed")}},lO=class extends Vi{constructor(e,t,i){super(),this.modality=e,this.msi=t,this.disposeDelay=i,this.clients=[],this.streamReady=!1}createClient(){const e=new oO(this);return this.clients.push(e),e}get isStreamReady(){return this.streamReady}get localMsi(){return this.subStream?.getSourceStreamId()}get isInactive(){return!this.clients.length}get stream(){return this.subStream}set stream(e){try{if(e===this.subStream)return;this.subStream&&(this.unsubscribe(!1),this.notifyStreamChanged()),this.subStream=e,e&&(this.streamReady=!1,e.requestSource(this.msi).then((()=>{this.streamReady=!0,this.notifyStreamChanged()})).catch((e=>{this.notifyError(e)})))}catch(e){this.event("onFailed").raise(this,e)}}notifyError(e){this.clients.forEach((t=>{t.notifyError(e)})),this.event("onFailed").raise(this,e)}dispose(e,t){t?(Qi(this.clients,(e=>e===t)),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(e=!0){this.subStream&&(this.subStream.requestSource(-1).catch((()=>{})),this.streamReady=!1,this.subStream=null),e&&this.event("onDisposed").raise(this)}notifyStreamChanged(){this.clients.forEach((e=>e.notifyMediaStreamChanged())),this.event("onStreamChanged").raise()}},cO=class extends Vi{constructor(e,t,i,n){super(e),this.configProvider=t,this.diagnostics=n,this.videoSubscriptions=[],this.isMcpSrAvailable=!1,this.subscriptionEvents=new Map,this.setLogger(e),this.diagnostics??(this.diagnostics=new dO(this.configProvider,(()=>{}))),this.setStreamProvider(i),this.logger.safe.info("created")}getSubscriptionsCount(){return this.videoSubscriptions.filter((e=>e.isStreamReady)).length}setStreamProvider(e){this.streamProvider=e,this.streamProvider.setOnStreamsChangedHandler((()=>this.streamsChanged()))}setLogger(e){this.logger=e}subscribeVideo(e,t=-2){let i=this.videoSubscriptions.find((i=>i.msi===t&&i.modality===e)),n=this.getAvailableStream(e);if(i)!i.stream&&n?this.assignStream(i,n):this.logger.safe.info(`subscription #${t} for modality ${e} already exists, stream assigned: ${!!i.stream}`);else{const r=Date.now();this.disposeInactiveSubscriptionIfNeeded(e),n=this.getAvailableStream(e);const s=n?.getSourceStreamId();this.logger.safe.info(`creating new subscription #${t} for modality ${e}`),this.event("onSubscriptionChanged").raise(1,e,t,s,null),this.diagnostics.addSubscribe(e,t,s),i=new lO(e,t,this.configProvider.config.webrtcVideoSubscriptionDisposeTimeout);const a=[];a.push(i.on("onDisposed",(e=>this.onSubscriptionDisposed(e)))),a.push(i.on("onStreamChanged",(()=>{const n=i.stream?.getId(),s=i.localMsi;if(this.updateTrackIds(),i.isStreamReady){const i=Date.now();this.event("onSubscriptionChanged").raise(2,e,t,s,i-r,n),this.diagnostics.addSubscribed(e,t,s,i-r)}}))),a.push(i.on("onFailed",((e,t)=>this.onSubscriptionFailed(e,t)))),this.subscriptionEvents.set(i,a),this.videoSubscriptions.push(i),n?this.assignStream(i,n):this.logger.safe.info(`waiting for available stream for subscription #${t}`)}return i.createClient()}dispose(){const e=be();this.videoSubscriptions.concat().forEach((t=>t.dispose(e))),this.streamProvider.setOnStreamsChangedHandler(null),super.dispose(),this.logger.safe.info("disposed")}reriseSubscribeEvents(){this.logger.safe.info(`rerising subscription events: ${this.videoSubscriptions.length}`);const e=[];this.videoSubscriptions.forEach((t=>{const i=t.modality,n=t.msi,r=t.localMsi;this.event("onSubscriptionChanged").raise(1,i,n,r),this.diagnostics.addSubscribe(i,n,r),e.push(...this.getSubscriptionVideoTrackIds(t))})),this.diagnostics.subscribedTrackIds=e}setDiagnostics(e){this.diagnostics=e??new dO(this.configProvider,(e=>{this.logger.safe.warn(`Unhandled stats error from inactive subscription manager: ${e}`)}))}streamChangedByMsi(e){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`);const t=this.videoSubscriptions.find((t=>t.msi===e));t?this.assignSubscriptionToStream(t):this.logger.safe.error(`Subscription for msi ${e} not found`)}mcpSourceRequestsAvailable(){this.isMcpSrAvailable=!0}streamsChanged(){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`),this.videoSubscriptions.forEach((e=>{this.assignSubscriptionToStream(e)}))}assignSubscriptionToStream(e){const t=!e.stream||this.isStreamRemoved(e.stream);if(this.logger.safe.info(`Subscription for ${e.modality} #${e.msi} needs new stream: ${t}`),!t)return;const i=this.getAvailableStream(e.modality);i?this.assignStream(e,i):this.resignStream(e)}getAvailableStream(e){let t=this.streamProvider.getStreams();return"video"===e&&!this.isMcpSrAvailable&&this.configProvider.config.multiStreamSupported&&(t=t.filter((e=>void 0===e.getSubstreamIndex()))),t.find((t=>e===t.getModality()&&-1===t.getMsi()))}isStreamRemoved(e){return!this.streamProvider.getStreams().some((t=>t===e))}assignStream(e,t){this.logger.safe.info(`assigning stream #${t.getId()} to subscription #${e.msi}`),e.stream=t}resignStream(e){if(e.stream)this.logger.safe.info(`removing stream from subscription #${e.msi}`),e.stream=null;else{const t=this.streamProvider.getStreams().filter((t=>e.modality===t.getModality()&&-1!==t.getMsi())).length;this.logger.safe.warn(`no stream available for ${e.modality} #${e.msi}, ${e.modality} used stream count: ${t}`)}}disposeInactiveSubscriptionIfNeeded(e){this.getAvailableStream(e)||this.videoSubscriptions.find((t=>t.modality===e&&t.isInactive))?.unsubscribeIfInactive()}onSubscriptionDisposed(e){const t=be(),i=e.modality,n=e.msi,r=e.localMsi;this.event("onSubscriptionChanged").raise(3,i,n,r),this.diagnostics.addUnsubscribe(i,n,r),this.logger.safe.info(`disposing subscription for ${i} #${n}`),Qi(this.videoSubscriptions,(t=>t===e)),this.streamsChanged(),this.updateTrackIds(),this.subscriptionEvents.has(e)&&(this.subscriptionEvents.get(e).forEach((e=>e.dispose(t))),this.subscriptionEvents.delete(e))}updateTrackIds(){const e=[],t=[];this.videoSubscriptions.forEach((i=>{if(!i.isStreamReady)return;const n=i.stream?.getId().split("-")[1];t.push(n),e.push(...this.getSubscriptionVideoTrackIds(i))})),this.event("onTrackIdsChanged").raise(e),this.diagnostics.subscribedTrackIds=e,this.configProvider.config.subscribeToSsrcForVideo&&this.event("onTrackSsrcChanged").raise(t)}getSubscriptionVideoTrackIds(e){return e?.stream?.getMediaStream()?.getVideoTracks().map((e=>e.id))??[]}onSubscriptionFailed(e,t){this.event("onSubscriptionFailed").raise(-1,e.modality,e.msi,e.localMsi,t),this.diagnostics.addFailed(e.modality,e.msi,e.localMsi,tt(t))}},dO=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,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(e){this.data.subscribedTrackIds=e}addSubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:1,msi:t,localMsi:i,ts:Date.now()};Sn(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.attempted++}}addSubscribed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:2,msi:t,localMsi:i,ts:Date.now(),duration:n};Sn(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.subscribed++}}addUnsubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:3,msi:t,localMsi:i,ts:Date.now()};Sn(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.unsubscribed++}}addFailed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:-1,msi:t,localMsi:i,ts:Date.now(),error:n};Sn(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.failed++}}getObjectRef(){return this.data}getModalityData(e){switch(e){case Gi.MEDIA_TYPE.video:return this.data.video;case Gi.MEDIA_TYPE.sharing:return this.data.sharing;default:return void this.addStatsError(`Unsupported modality ${e}`)}}},uO=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,this.data={videoMaxCapabilitiesEvents:[],videoMaxCapabilitiesErrors:[],sharingMaxCapabilitiesEvents:[],sharingMaxCapabilitiesErrors:[],currentVideoSsrcRequestedCapabilities:{},currentVideoSsrcAppliedCapabilities:{},currentSharingSsrcRequestedCapabilities:{},currentSharingSsrcAppliedCapabilities:{},numVideoControlMessages:0,numOutOfOrderVideoControlMessages:0,numWebcamFreezeIntervals:0,numProcessedStreamFreezeIntervals:0}}onMaxCapabilitiesRequested(e){const t={causeId:e.causeId,events:[{eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled}]};try{if(e.modality===Gi.MODALITY.video){Sn(this.data.videoMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentVideoSsrcRequestedCapabilities={};for(const t of e.capabilities)this.data.currentVideoSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}else if(e.modality===Gi.MODALITY.sharing){Sn(this.data.sharingMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentSharingSsrcRequestedCapabilities={};for(const t of e.capabilities)this.data.currentSharingSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}}catch(e){this.addStatsError?.("onMaxCapabilitiesRequested",tt(e))}}onMaxCapabilitiesApplied(e){try{const t=this.getEventForCause(e.modality,e.causeId),i={eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:`${e.error}`||"none"};if(t&&(Sn(t.events,i,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1),e.error&&(e.modality===Gi.MODALITY.video?Sn(this.data.videoMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1):e.modality===Gi.MODALITY.sharing&&Sn(this.data.sharingMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1))),e.modality===Gi.MODALITY.video){this.data.currentVideoSsrcAppliedCapabilities={};for(const t of e.capabilities)this.data.currentVideoSsrcAppliedCapabilities[`${t.ssrc??0}`]=t}else if(e.modality===Gi.MODALITY.sharing){this.data.currentSharingSsrcAppliedCapabilities={};for(const t of e.capabilities)this.data.currentSharingSsrcAppliedCapabilities[`${t.ssrc??0}`]=t}}catch(e){this.addStatsError?.("onMaxCapabilitiesApplied",tt(e))}}addVideoControlMessage(e=!1){this.data.numVideoControlMessages++,e&&this.data.numOutOfOrderVideoControlMessages++}getObjectRef(){return this.data}registerWebcamFreeze(){this.data.numWebcamFreezeIntervals++}registerProcessedStreamFreeze(){this.data.numProcessedStreamFreezeIntervals++}getEventForCause(e,t){return(e===Gi.MODALITY.video?this.data.videoMaxCapabilitiesEvents:this.data.sharingMaxCapabilitiesEvents).find((e=>e.causeId===t))}},hO=class{constructor(e){this.configProvider=e,this.data={renderers:[],firstTimeToFirstFrameVideo:-1,firstTimeToFirstFrameSharing:-1,timeToFirstFrameSinceSubscriptionStartVideo:-1,timeToFirstFrameSinceSubscriptionStartSharing:-1,isRenderingEvents:{video:[],sharing:[]},preferredResolution:{video:void 0,sharing:void 0}}}setTimeToFirstFrame(e,t){-1!==e&&(t===Gi.MODALITY.video&&-1===this.data.firstTimeToFirstFrameVideo?this.data.firstTimeToFirstFrameVideo=e:t===Gi.MODALITY.sharing&&-1===this.data.firstTimeToFirstFrameSharing&&(this.data.firstTimeToFirstFrameSharing=e))}setTimeToFirstFrameSinceSubscriptionStart(e,t){-1!==e&&(t===Gi.MODALITY.video&&-1===this.data.timeToFirstFrameSinceSubscriptionStartVideo?this.data.timeToFirstFrameSinceSubscriptionStartVideo=e:t===Gi.MODALITY.sharing&&-1===this.data.timeToFirstFrameSinceSubscriptionStartSharing&&(this.data.timeToFirstFrameSinceSubscriptionStartSharing=e))}setIsRendering(e,t){this.data.isRenderingEvents[t]&&Sn(this.data.isRenderingEvents[t],{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents)}setPreferredResolution(e,t){(e.width||e.height)&&(this.data.preferredResolution[t]=e)}newRendererDiagnostics(){const e=new gO(this,this.configProvider),t=e.on("onDisposed",(()=>{this.removeDeadRenderers(),t.dispose()}));return this.data.renderers.push(e.getObjectRef()),e}getObjectRef(){return this.data}removeDeadRenderers(){this.data.renderers=this.data.renderers.filter((e=>e.alive))}},gO=class extends Vi{constructor(e,t){super(),this.managerDiagnostics=e,this.configProvider=t,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(e){this.data.trackId=e}set rendererSize(e){this.data.rendererSize=e,e.toString=()=>`${e.width}x${e.height}`,this.managerDiagnostics.setPreferredResolution(e,this.data.modality)}set msi(e){this.data.msi=e}set modality(e){this.data.modality=e}set isRendering(e){this.data.isRendering=e,this.managerDiagnostics.setIsRendering(e,this.data.modality)}set timeToFirstFrame(e){this.data.timeToFirstFrame=e,this.managerDiagnostics.setTimeToFirstFrame(e,this.data.modality)}set timeToFirstFrameSinceSubscriptionStart(e){this.data.timeToFirstFrameSinceSubscriptionStart=e,this.managerDiagnostics.setTimeToFirstFrameSinceSubscriptionStart(e,this.data.modality)}addFreezeDuration(e){this.data.totalFreezeDuration+=e}addStateChange(e){Sn(this.data.rendererStates,e,this.configProvider.config.diagnostics.telemetryLimits.numRendererStateChangedEvents)}dispose(){this.isAlive=!1,this.event("onDisposed").raise()}getObjectRef(){return this.data}},pO=Z,mO=p(ye()),fO=Z;function vO(e){let t="";return qi(e,((e,i)=>{t+=(t?";":"")+i,void 0!==e&&(t+=`=${e}`)})),t}var SO=class{constructor(e){this.parameters={},e&&e.split(";").forEach((e=>{const t=e.split("=");this.parameters[t[0]]=t[1]}))}setIfMissing(e,t){this.contains(e)||(this.parameters[e]=t)}removeIfPresent(e){this.contains(e)&&delete this.parameters[e]}get(e){return this.parameters[e]}names(){return Object.keys(this.parameters)}contains(e){return this.parameters.hasOwnProperty(e)}toString(){return vO(this.parameters)}};function yO(e,t,i){if(!e.rtp)return;const n=e.rtp.filter((e=>e.payload===t))[0];n&&TO(e,{codec:n.codec,rate:n.rate,payload:n.payload,encoding:n.encoding},(e=>(e.rtp.payload=i,e)))}function CO(e){const t=new Set;for(const i of e.media)for(const e of i.rtp??[])t.add(e.payload);const i=[96,127];for(let e=i[0];e<=i[1];e++)if(!t.has(e))return e;const n=[35,64];for(let e=n[0];e<=n[1];e++)if(!t.has(e))return e;return-1}function TO(e,t,i,n){bO(e,t,!0,n,i)}function EO(e,t,i,n){bO(e,t,!1,n,i)}function bO(e,t,i,n=!0,r){if(e.rtp){for(let s=0;s<e.rtp.length;s++){const a=e.rtp[s],o=a.payload;if(t.codec.toLowerCase()!==a.codec.toLowerCase()||t.rate!==a.rate||t.encoding!==a.encoding||t.payload&&t.payload!==a.payload)continue;const l={rtp:a};e.fmtp||(e.fmtp=[]);const c=e.fmtp.find((e=>a.payload===e.payload));l.fmtp=c,e.rtcpFb||(e.rtcpFb=[]),l.rtcpFb=e.rtcpFb.filter((e=>e.payload===a.payload));const d=l.rtcpFb.length>0;if(null===r(l))e.payloads=e.payloads.toString().split(" ").filter((e=>a.payload!==+e)).join(" "),e.fmtp=e.fmtp.filter((e=>a.payload!==e.payload)),e.rtcpFb=e.rtcpFb.filter((e=>a.payload!==e.payload)),e.rtp[s]=null;else{if(l.rtp.payload!==o){const t=l.rtp.payload;e.payloads=e.payloads.toString().split(" ").map((e=>+e===o?t:+e)).join(" "),l.fmtp&&(l.fmtp.payload=t),l.rtcpFb&&l.rtcpFb.forEach((e=>e.payload=t)),n&&e.fmtp.filter((e=>e.config&&e.config.indexOf(`apt=${o}`)>-1)).forEach((e=>e.config=e.config.replace(`apt=${o}`,`apt=${t}`)))}!c&&l.fmtp&&e.fmtp.push(l.fmtp),!d&&l.rtcpFb&&l.rtcpFb.forEach((t=>e.rtcpFb.push(t)))}if(i)break}e.rtp=e.rtp.filter((e=>!!e))}}function _O(e,t){if(!e.rtp)return;let i=-1;if(e.rtp.forEach((function(e,n){t.codec.toLowerCase()!==e.codec.toLowerCase()||t.rate!==e.rate||t.encoding!==e.encoding||t.payload&&t.payload!==e.payload||(i=n)})),i>=0&&e.rtp.length>1){const t=e.rtp[i].payload;e.rtp.splice(i,1),e.payloads=e.payloads.split(" ").filter((e=>t!==+e)).join(" "),e.fmtp=e.fmtp?.filter((e=>t!==e.payload))}}function IO(e,t){e.rtp.unshift({payload:t.payload,codec:t.codec,rate:t.rate,encoding:t.encoding}),e.payloads=`${t.payload} ${e.payloads}`}function wO(e,t,i){if(!(0,fO.isUndefined)(e.rate)&&e.rate!==t.rate)return!1;if(!(0,fO.isUndefined)(e.codec)&&e.codec.toLowerCase()!==t.codec.toLowerCase())return!1;if(!(0,fO.isUndefined)(e.encoding)){if(!(0,fO.isUndefined)(t.encoding)&&e.encoding!==t.encoding)return!1;if((0,fO.isUndefined)(t.encoding)&&1!==e.encoding)return!1}if(!(0,fO.isUndefined)(e.fmtpLine)){const n=i?.find((i=>i.payload===t.payload&&-1!==i.config.toLowerCase().indexOf(e.fmtpLine.toLowerCase())));return!!n}return!0}function AO(e,t){return t===e||"*"===t}function PO(e,t,i,n){if(!e.rtp?.length)return;let r=e.rtp.filter((i=>t.some((t=>wO(t,i,e.fmtp)))));e.type===Gi.MEDIA_TYPE.video&&(r=r.filter((t=>{const i=e.fmtp?.find((e=>e.payload===t.payload&&e.config.startsWith("apt=")));if(i){const e=+i.config.split(";")[0].split("=")[1];return r.some((t=>t.payload===e))}return!0}))),r.length?(e.rtp=r,i&&(e.rtp=(0,fO.flatten)(t.map((t=>e.rtp.filter((i=>wO(t,i,e.fmtp))))))),e.payloads=e.rtp.map((e=>e.payload)).join(" "),e.fmtp=e.fmtp?.filter((t=>e.rtp.some((e=>AO(e.payload,t.payload))))),e.rtcpFb=e.rtcpFb?.filter((t=>e.rtp.some((e=>AO(e.payload,t.payload)))))):n&&n.warn("Empty rtp list after filtering")}function RO(e){if(e.label)switch(e.label){case Gi.MEDIA_LABEL.audio:return"Audio";case Gi.MEDIA_LABEL.video:return"Video";case Gi.MEDIA_LABEL.sharing:return"ScreenShare";case Gi.MEDIA_LABEL.data:return"Data"}else switch(e.type){case Gi.MEDIA_TYPE.audio:return"Audio";case Gi.MEDIA_TYPE.video:return"Video";case Gi.MEDIA_TYPE.data:case Gi.MEDIA_TYPE.dataChannel:return"Data"}return null}function MO(e){if(e.label)switch(e.label){case Gi.MEDIA_LABEL.audio:return Gi.MODALITY.audio;case Gi.MEDIA_LABEL.video:return Gi.MODALITY.video;case Gi.MEDIA_LABEL.sharing:return Gi.MODALITY.sharing;case Gi.MEDIA_LABEL.data:return Gi.MODALITY.data}else switch(e.type){case Gi.MEDIA_TYPE.audio:return Gi.MODALITY.audio;case Gi.MEDIA_TYPE.video:return Gi.MODALITY.video;case Gi.MEDIA_TYPE.data:case Gi.MEDIA_TYPE.dataChannel:return Gi.MODALITY.data}return null}function DO(e){switch(e){case Gi.MODALITY.audio:return Gi.MEDIA_LABEL.audio;case Gi.MODALITY.video:return Gi.MEDIA_LABEL.video;case Gi.MODALITY.sharing:return Gi.MEDIA_LABEL.sharing;case Gi.MODALITY.data:return Gi.MEDIA_LABEL.data;default:return null}}function kO(e){return e.media.reduce(((e,t)=>{if(0!==t.port){const i=MO(t);if(!(i in e)){const n=t.direction?t.direction.toLowerCase():Gi.MEDIA_STATE.sendReceive;e[i]=n}}return e}),{})}function OO(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));if(t){const i=t.mids?.toString().split(" ")[0];return e.media.find((e=>{const t="number"==typeof e.mid?e.mid.toString():e.mid;return i===t}))||null}return null}function NO(e){return 0===e.port}function LO(e){let t;return e&&TO(e,{codec:"h264",rate:9e4},(e=>{e.fmtp?.config&&(t=function(e){const t=new SO(e);return{maxFs:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Gi.VIDEO_CAPABILITIES.MAX_BR_PATH)}}(e.fmtp.config))})),t}function xO(e){const t=e.media.map((e=>parseFloat(e.mid||"0")));for(let e=1;e<=Math.max(...t)+1;e++)if(!t.includes(e))return e.toString();return"-1"}var FO=Z;function UO(){const e=[{jsep:"active",msSdp:"tcp-act"},{jsep:"passive",msSdp:"tcp-pass"},{jsep:"so",msSdp:"tcp-so"}];function t(e,t){delete e.generation,delete e["network-id"],delete e["network-cost"],e.transport.match(/tcp/i)&&i(e,t)}function i(t,i){e.some((function(e){if(i){if(e.msSdp===t.transport.toLowerCase())return t.transport="tcp",t.tcptype=e.jsep,!0}else if(t.tcptype&&e.jsep===t.tcptype.toLowerCase())return t.transport=e.msSdp,delete t.tcptype,!0;return!1}))}function n(e,t,i){const n=t.connection||i.connection,r=function(e,t,i){return e.port===i&&e.ip===t};return!!n&&(1===e.component?r(e,n.ip,t.port):!!t.rtcp&&r(e,t.rtcp.ip||n.ip,t.rtcp.port))}this.fromMsSdp=function(e){e.candidates=e.candidates||[],e.xCandidatesIpv6&&(e.xCandidatesIpv6.forEach((function(t){e.candidates.push(t)})),delete e.xCandidatesIpv6),e.candidates.forEach((function(e){t(e,!0)}))},this.toMsSdp=function(e,i){e.candidates=e.candidates||[],e.candidates.sort((function(t,r){return t.foundation!==r.foundation?t.foundation-r.foundation:t.component!==r.component?t.component-r.component:+n(r,e,i)-+n(t,e,i)})),e.candidates=e.candidates.filter((function(i,n){t(i,!1);const r=e.candidates[n-1];return!r||r.component!==i.component||r.foundation!==i.foundation})),function(e,t){if(e.port&&!e.candidates.length){const i=OO(t);i&&(e.port=i.port,e.connection=i.connection)}}(e,i)}}var BO=class{toMsSdp(e,t){"offer"===t?e.rtcp&&(e.rtcp={port:e.port}):delete e.rtcp}},VO={STREAM_ID:{audio:"mainAudio",video:"mainVideo",sharing:"applicationsharingVideo"},STREAM_ID_DELIMITER:"-"},HO=[{label:Gi.MEDIA_LABEL.audio,id:VO.STREAM_ID.audio},{label:Gi.MEDIA_LABEL.video,id:VO.STREAM_ID.video},{label:Gi.MEDIA_LABEL.sharing,id:VO.STREAM_ID.sharing}].reduce(((e,t)=>(e[t.label]=t.id,e)),{}),$O=sn(),jO=class{constructor(e){this.configuration=e}fromMsSdp(e){if(0!==e.port){if(!this.isRecvOnly(e)||this.configuration.unifiedPlanEnabled){if(e.msid){e.ssrcs&&1===e.ssrcs.length&&(this.addStream(e,e.ssrcs[0].id,e.ssrcs[0].value,e.msid),e.ssrcs.shift());const t=e.msid.split(" ");(this.configuration.addPrefixForMsid||"-"===t[0])&&(e.msid=this.getMsidValue(t[0],t[1]||t[0],e.label))}if(e.ssrcs)this.updateMsids(e.ssrcs,((t,i)=>this.configuration.addPrefixForMsid||"-"===t?this.getMsidValue(t,i,e.label):`${t} ${i}`));else{const t=this.getFlowSsrcs(e);t.length>0?t.forEach((i=>{this.addStream(e,i,$O,this.getMsidValue(t[0],t[0],e.label))})):e.xSsrcRange&&this.addStream(e,e.xSsrcRange.ssrcMin,$O,this.getMsidValue(e.xSsrcRange.ssrcMin,e.xSsrcRange.ssrcMin,e.label))}}delete e.xSsrcRange}}toMsSdp(e,t){if(0===e.port)return;let i;e.ssrcs?.[0]&&(i=e.ssrcs[0].id),void 0!==i&&(e.xMultiStream||(e.xSsrcRange={ssrcMin:i,ssrcMax:i+t}))}getFlowSsrcs(e){if(e.ssrcGroups&&e.type===Gi.MEDIA_TYPE.video){let t;if(e.ssrcGroups.some((e=>"FID"===e.semantics&&(t=e,!0))),t)return t.ssrcs.split(" ").map((e=>+e))}return[]}addStream(e,t,i,n){e.ssrcs=e.ssrcs||[],e.ssrcs.push({attribute:"cname",id:t,value:i}),e.ssrcs.push({attribute:"msid",id:t,value:n})}updateMsids(e,t){e.filter((e=>"msid"===e.attribute)).forEach((e=>{const i=e.value.split(" ");e.value=t(i[0],i[1]||i[0])}))}getMsidValue(e,t,i){const n=this.getMsidPrefix(i);return n+e+" "+n+t}getMsidPrefix(e){return HO[e]?HO[e]+VO.STREAM_ID_DELIMITER:""}isRecvOnly(e){return"recvonly"===e.direction}},GO={audio:"main-audio",video:"main-video"},qO=class{constructor(e,t){this.context=e,this.mediaManager=t,this.logger=this.context.logger,this.candidateTransform=new UO,this.streamTransform=new jO(this.context.configuration),this.rtcpTransform=new BO}toMsSdp(e,t){return e.msidSemantic={semantic:"WMS",token:"*"},e.media.forEach(((i,n)=>{if(i.protocol=Gi.PROFILES.rtpSavp,i.label=i.label||this.getLabel(i.type),NO(i)){for(const e in i)i.hasOwnProperty(e)&&["type","port","protocol","payloads"].indexOf(e)<0&&delete i[e];i.payloads="34"}const r=this.getSsrcRangeForIndex(i.direction,n);this.streamTransform.toMsSdp(i,r),i.crypto&&i.crypto.forEach((function(e){e.config+="|2^31"})),0!==i.port&&e.fingerprint&&(i.fingerprint=e.fingerprint),this.candidateTransform.toMsSdp(i,e),this.rtcpTransform.toMsSdp(i,t),i.invalid&&(this.logger.unsafe.error(`Unknown SDP attributes! ${JSON.stringify(i.invalid)}`),delete i.invalid),this.transformExtensions(i,!1),0!==i.port&&(i.type===Gi.MEDIA_TYPE.audio&&this.context.configProvider.config.webrtcAudioChannelSignalingFeedback?i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcAudioChannelSignalingFeedback}:i.type===Gi.MEDIA_TYPE.video&&this.context.configProvider.config.webrtcVideoChannelSignalingFeedback&&(i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcVideoChannelSignalingFeedback}))})),delete e.fingerprint,e}fromMsSdp(e,t){for(let i=e.media.length-1;i>=0;--i){const n=e.media[i];if((n.ssrcs?.[0]||n.xSsrcRange)&&(e.msidSemantic={semantic:"WMS",token:"*"}),NO(n))n.direction||(n.direction="inactive");else{if(this.streamTransform.fromMsSdp(n),delete n.cryptoscale,n.fingerprint&&(!this.isOffer(t)||this.context.configProvider.config.disableIncomingDtlsRoleOverride&&n.setup||(n.setup="actpass")),n.crypto)for(let e=n.crypto.length-1;e>=0;--e){const t=n.crypto[e];t.config.match(/.*\|\d+:\d+/)?n.crypto.splice(e,1):t.config=t.config.replace(/(.*)\|2\^\d+/,"$1")}n.remoteCandidates&&(delete n.candidates,delete n.xCandidatesIpv6,delete n.remoteCandidates),this.candidateTransform.fromMsSdp(n),n.rtcpFbXMessage&&delete n.rtcpFbXMessage,n.invalid&&this.logger.unsafe.info(`Unknown SDP attributes! ${JSON.stringify(n.invalid)}`),this.transformExtensions(n,!0)}}return e}transformExtensions(e,t){const i=[{name:Gi.ABS_SEND_TIME.EXT_URI,encoded:Gi.ABS_SEND_TIME.MSSDP_ENCODED_URI},{name:Gi.TRANSPORT_CC.EXT_URI,encoded:Gi.TRANSPORT_CC.MSSDP_ENCODED_URI}];e.ext&&e.ext.forEach((function(e){i.some((function(i){const n=t?i.encoded:i.name,r=t?i.name:i.encoded;return n===e.uri&&(e.uri=r,!0)}))}))}isOffer(e){return"offer"===e}getLabel(e){return GO.hasOwnProperty(e)&&GO[e]||"undefined"}getSsrcRangeForIndex(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();return Wp(e)&&n?n.getSsrcRange():0}},zO=4294967040,WO=class{constructor(){this.ssrc=Math.floor(Math.random()*(zO-1))+1}nextAudioStreamSsrc(){return this.nextSsrc(0)}nextVideoStreamSsrc(){return this.nextSsrc(99)}nextSsrc(e){let t=this.ssrc;do{t=this.ssrc,this.ssrc=(this.ssrc+e+1)%zO,0===this.ssrc&&(this.ssrc=1)}while(t+e>zO);return{min:t,max:t+e}}},KO=Z,JO=class{constructor(e,t,i){this.mediaEntity=e,this.logger=t,this.configProvider=i,this.activeRids=[],this.isLocalDescSet=!1,this.enabledLocally=!1,this.enabledRemotely=!1;const n=sm(this.mediaEntity.getModality());this.config=function(e,t){return"Video"===e?t.config.specCompliantSimulcast?.video:"ScreenShare"===e?t.config.specCompliantSimulcast?.sharing:null}(n,this.configProvider),this.config?this.logger.safe.debug(`Adding simulcast info to ${e.getModality()} with mid: ${e.getMid()}, config: ${JSON.stringify(this.config)}`):this.logger.safe.debug(`Simulcast is disabled for ${e.getModality()}`)}get ridList(){return this.config?(0,KO.times)(this.config.layerScaleFactors.length,(e=>e+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 e=this.mediaEntity.getRtpHeaderExtensions();return e?.some((e=>"mid"===e.headerType||"rid"===e.headerType||"rrid"===e.headerType))}},YO=Z,QO=[2812,4218,8437,16875,33750,67500,108e3,135e3,198e3,244800,27e4,352500,52e4],ZO=class{constructor(e,t,i,n){this.initialMaxFS=e,this.initialMaxFPS=t,this.isAv1Allowed=i,this.h264SubscribeProfile=n,this.maxFS=e,this.maxFPS=t}setMaxFS(e,t){return!(this.maxFS===e||(this.maxFS=e,!t)||(t(this),0))}getMaxFS(){return this.maxFS}getMaxFPS(){return this.maxFPS}getMaxMBPS(){return this.calculateMbps(this.maxFS,this.maxFPS)}calculateMbps(e,t){return cn(QO,e*t/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 e=[];let t=this.fmtpParams();return this.h264SubscribeProfile&&(t["profile-level-id"]=this.h264SubscribeProfile),e.push(t),this.isAv1Allowed&&(t=this.fmtpParams(),t.codec="AV1",e.push(t)),e}},XO=class e{constructor(e,t){this.entity=e,this.configProvider=t,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(e,t,i){if(e!==Gi.MEDIA_TYPE.video)return null;let n,r;t===Gi.MODALITY.sharing?(n=i.config.webrtcScreensharingCapabilityMaxFS,r=i.config.webrtcScreensharingCapabilityMaxFPS):(n=i.config.webrtcVideoCapabilityMaxFS,r=i.config.webrtcVideoCapabilityMaxFPS,i.config.useMultiviewLimitsOnInitialRequest&&i.config.multiviewResolutionLimits[1]&&(n=Hn.Send.getMaxFsForHeight(i.config.multiviewResolutionLimits[1])));const s=i.config.isAv1Allowed&&t===Gi.MODALITY.sharing;return new ZO(n,r,s,i.config.h264SubscribeProfile)}static create(t,i,n){const r=function(e){switch(e){case Gi.MODALITY.audio:return Gi.MEDIA_TYPE.audio;case Gi.MODALITY.video:case Gi.MODALITY.sharing:return Gi.MEDIA_TYPE.video;case Gi.MODALITY.data:return Gi.MEDIA_TYPE.data;default:return null}}(i),s=new e({modality:i,mid:n,mtype:r,extensions:{}},t);return s.localRecvCapabilities=e.getVideoCababilities(r,i,t),s}clone(){const t=new e((0,YO.cloneDeep)(this.entity),this.configProvider);return t.setSimulcastContext(this.simulcastContext),t.localRecvCapabilities=this.localRecvCapabilities,t.remoteRecvCapabilities=this.remoteRecvCapabilities,t.supportedSendProfiles=this.supportedSendProfiles,t}getModality(){return this.entity.modality}getType(){return this.entity.mtype}getMid(){return this.entity.mid}disable(){this.entity.mid=null}update(t,i){this.entity.modality!==t&&(this.localRecvCapabilities=e.getVideoCababilities(this.entity.mtype,t,this.configProvider)),this.entity.modality=t,this.entity.mid=i,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(e){this.remoteRecvCapabilities=e}getRemoteStreamId(){return this.entity.remoteStreamId}setRemoteStreamId(e){this.entity.remoteStreamId=e}setRemoteSsrc(e){this.entity.remoteSsrc=e}getRemoteSsrc(){return this.entity.remoteSsrc}setLocalSsrc(e){this.entity.localSsrc=e}getLocalSsrc(){return this.entity.localSsrc}getRemoteTrackId(){return this.entity.remoteTrackId}setRemoteTrackId(e){this.entity.remoteTrackId=e}getXSourceStreamId(){return this.entity.xSourceStreamId}setXSourceStreamId(e){this.entity.xSourceStreamId=e}setLocalTrackId(e){this.entity.localTrackId=e}getLocalTrackId(){return this.entity.localTrackId}setSubStreamIndex(e){this.entity.subStreamIndex=e}getSubstreamIndex(){return this.entity.subStreamIndex}getExtension(e){return this.entity.extensions[e]}setExtension(e,t){this.entity.extensions[e]=t}getRtpHeaderExtensions(){return this.entity.rtpExt}setRtpHeaderExtensions(e){this.entity.rtpExt=e}setSimulcastContext(e){this.simulcastContext=e}getSimulcastContext(){return this.simulcastContext}addSupportedSendProfile(e,t){void 0===this.supportedSendProfiles[e]&&(this.supportedSendProfiles[e]=new Set),this.supportedSendProfiles[e].add(t)}isSendProfileSupported(e,t){const i=this.supportedSendProfiles[e];if(void 0!==i){const e=t.slice(0,2);for(const t of i)if(t.startsWith(e))return!0}return!1}serialize(){return nn(this.entity)}},eN={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"},tN=class{constructor(e){this.context=e,this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.ssrcGenerator=new WO,this.rollbackHandlers=[],this.logger=e.logger.createChild("MM2"),this.configProvider=e.configProvider}fromOffer(e,t,i=!1){this.logger.safe.debug(`fromOffer, modalities: ${JSON.stringify(t)} disableOnly: ${i}`),this.updateMediaEntitiesFromModel(e,i),this.updateSharingEntity(!!t.sharing),e.media.forEach((e=>{this.logger.safe.debug(`Media entity for mid: ${e.mid}, ${this.getMediaEntityByMid(e.mid)}`);const t=this.getMediaEntityByMid(e.mid);t&&this.saveLocalSsrc(t,e)}))}fromRemote(e,t){const i=0===this.mediaEntities.length;this.updateMediaEntitiesFromModel(e,!1,t),e.media.forEach(((e,t)=>{const i=this.getMediaEntityByMid(e.mid);i&&(this.saveRemoteMsid(i,e),this.saveRemoteSsrc(i,e),this.saveRtpHeaderExtensions(i,e),i.setXSourceStreamId(e.xSourceStreamId||this.generateSourceStreamId(t)),i.setRemoteRecvCapabilities(LO(e)),i.setSubStreamIndex(e.subStreamIndex)),this.logger.safe.debug(`Media entity for mid: ${e.mid}, ${i}`)})),i&&this.updateReinvitelessState(e)}isEmpty(){return 0===this.mediaEntities.length}createMediaEntity(e,t){const i=XO.create(this.configProvider,e,t);return this.logger.safe.debug(`Creating media entity for modality: ${e}, mid: ${t}`),this.context.useSimulcast&&!this.mediaEntities.find((t=>t.getModality()===e))&&this.setSimulcastContext(i),i.setExtension("reinviteless",!1),this.mediaEntities.push(i),i}getMediaEntities(){return this.mediaEntities}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntitiesByMediaType(e){const t=sm(e);return this.getMediaEntitiesByModality(t)}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[],this.rollbackHandlers=[]}syncModalities(e,t,i=!1){this.logger.safe.debug(`syncModalities, modalities: ${JSON.stringify(t)}, disableOnly: ${i},`),this.fromOffer(e,t,i)}setLocalTracksInfo(e){this.mediaTracks=e}getLocalTracksInfo(){return this.mediaTracks}backup(){this.logger.safe.debug("backup"),this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{e.setExtension("unnegotiatedModality",!1)}))}rollback(){this.logger.safe.debug(`rollback, if backup exists: ${!!this.mediaEntitiesBackup.length}`),this.mediaEntitiesBackup.length&&(this.rollbackHandlers.forEach((e=>e(this.mediaEntities,this.mediaEntitiesBackup))),this.mediaEntities.forEach(((e,t)=>{this.mediaEntitiesBackup[t]?this.mediaEntities[t]=this.mediaEntitiesBackup[t]:(e.disable(),e.setExtension("rollback",!0))})))}updateMediaEntitiesWithLocalTracks(){this.mediaTracks?(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?(this.logger.safe.debug(`Setting local track id ${e.trackId} for modality ${e.modality}`),t.setLocalTrackId(e.trackId)):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)}))):this.logger.safe.debug("No mediaTracks, not updating local tracks for media entities")}updateMediaEntitiesWithActivityState(e,t){this.logger.safe.debug(`Updating activity indexes for ${e} to ${JSON.stringify(t)}`);const i=am(e),n=this.getMediaEntitiesByModality(i)[0];if(!n)return void this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(i)}`);const r=n.getSimulcastContext();r&&(r.activeRids=t)}setRollbackUpdateHandler(e){this.rollbackHandlers.push(e)}saveRtpHeaderExtensions(e,t){if(e.isDisabled())return void e.setRtpHeaderExtensions(void 0);const i=t.ext?.map((e=>this.getHeaderExtension(e)));this.logger.safe.debug(`RTP header ext for mid=${t.mid}, modality=${e.getModality()}: ${JSON.stringify(i)}`),e.setRtpHeaderExtensions(i)}getHeaderExtension(e){let t="unknown";for(const[i,n]of Object.entries(eN))if(e.uri.endsWith(i)){t=n;break}return{headerType:t,value:e.value}}saveRemoteMsid(e,t){if(NO(t))e.setRemoteStreamId(null);else if(t.msid)e.setRemoteStreamId(t.msid.split(" ")[0]);else if(t.ssrcs){const i=t.ssrcs.find((e=>"msid"===e.attribute));i?e.setRemoteStreamId(i.value.split(" ")[0]):this.logger.safe.warn(`No ssrc msid for media of type ${t.type} with mid ${t.mid}`)}}saveRemoteSsrc(e,t){if(t.ssrcs?.length){const i=t.ssrcs[0];e.setRemoteSsrc(+i.id)}}saveLocalSsrc(e,t){const i=t.ssrcs?.[0]?.id;if(!Wp(t.direction))return this.logger.safe.debug(`set local SSRC to ${i}`),void e.setLocalSsrc(+i);this.logger.safe.debug("has no send direction");const n=i||e.getLocalSsrc()||this.ssrcGenerator.nextVideoStreamSsrc().min;e.setLocalSsrc(+n)}updateMediaEntitiesFromModel(e,t,i){e.media.forEach(((e,n)=>{if(this.mediaEntities[n])if(NO(e))this.logger.safe.debug(`Disabling media entity for mid: ${e.mid}`),this.mediaEntities[n].disable();else{const t=e.mid||this.mediaEntities[n].getMid(),i=this.mediaEntities[n].getModality();this.logger.safe.debug(`Updating media entity for mid: ${t}, modality: ${i}`),this.mediaEntities[n].update(i,t),this.logger.safe.debug(`updated entity: ${this.mediaEntities[n]}`)}else t||this.createMediaEntity(MO(e),e.mid||n.toString());this.mediaEntities[n]&&i&&!(this.mediaEntities[n].getModality()in i)&&(this.logger.safe.debug(`Disabling media entity for mid: ${e.mid} as it is not found in modalities ${JSON.stringify(i)}`),this.mediaEntities[n].disable())}))}updateSharingEntity(e){if(e&&!this.getMediaEntitiesByModality(Gi.MODALITY.sharing).length){const e=this.getMediaEntitiesByModality(Gi.MODALITY.video).pop();e.update(Gi.MODALITY.sharing,e.getMid())}}setSimulcastContext(e){if(!e||e.getSimulcastContext())return;const t=new JO(e,this.logger.createChild(`SimContext:${e.getModality()}`),this.configProvider);e.setSimulcastContext(t)}generateSourceStreamId(e){return e+10}updateReinvitelessState(e){const t={[Gi.MODALITY.audio]:0,[Gi.MODALITY.video]:0,[Gi.MODALITY.sharing]:0};for(const i of e.media){const e=MO(i);void 0!==t[e]&&t[e]++;const n=this.getMediaEntityByMid(i.mid);if(n){const r=this.context.reinviteltessContext?.maxStreamsForModality[e]>=t?.[e]&&(!i.direction||"sendrecv"===i.direction);n.setExtension("reinviteless",r)}}}},iN=class{constructor(e){this.modifierList=e}modify(e){for(const t of this.modifierList)t.modify(e)}},nN=class{constructor(e,t,i,n){this.context=e,this.mediaManager=t,this.modalities=i,this.cname=n}build(e){switch(e.sdpSource){case 0:return new iN([new JN(this.context.configProvider),new AN(this.context.configProvider),new aL(this.mediaManager,this.context.configProvider),new sL(this.mediaManager),new FN(this.context.configProvider),new ON(this.context.configProvider),new KN(this.context.configProvider,this.mediaManager,e.sdpType,!1,this.context.getLogger().createChild("OverrideH264SendProfile")),new MN(this.mediaManager,this.context.configProvider,e.sdpType),new RN(this.mediaManager,this.context.configProvider,this.context.config.isConference,!1),new fL(this.context.configProvider,e.sdpType),new GN(this.context.configProvider)]);case 2:return new iN([new cN(this.mediaManager,this.modalities),new PN,new dN(this.mediaManager,!0),new XN(this.context.configProvider,this.mediaManager),new vN(this.modalities,this.mediaManager),new VN,new xN,new UN,new BN(this.context.configProvider),new LN(this.context.configProvider),new WN(this.context.configProvider),new KN(this.context.configProvider,this.mediaManager,e.sdpType,!0,this.context.getLogger().createChild("OverrideH264SendProfile")),new yN,new aN(this.context),new nL(this.mediaManager,this.context.configProvider),new wN(this.context.configProvider),new uL,new dL(this.context.configProvider),new oL(this.context.configProvider),new EN(this.mediaManager,this.modalities,this.context.configProvider),new fN(this.context),new hL(this.context.configProvider),new pN(this.context.configProvider),new MN(this.mediaManager,this.context.configProvider,e.sdpType),new DN(this.mediaManager,this.context.configProvider,e.sdpType),new RN(this.mediaManager,this.context.configProvider,this.context.config.isConference,!0),new $N(this.context.configProvider,this.context.getLogger()),new TN,new pL(this.context.configProvider),new GN(this.context.configProvider),new vL(e,this.context),new tL(this.context.configProvider),new QN(this.context.configProvider)]);case 1:return new iN([new hN(this.context,this.modalities.data),new dN(this.mediaManager,!1),new bN(this.context.configProvider),new cN(this.mediaManager,this.modalities),new CN(this.mediaManager),new xN,new NN(this.context.configProvider),new oN(this.mediaManager,"offer"===e.sdpType,this.context.configProvider),new rL(this.mediaManager,this.context.getLogger()),new cL(this.context.configProvider,this.mediaManager),new SN(this.context.config.isConference,this.cname),new _N(this.mediaManager),new IN,new YN(this.context.configProvider),new mN(this.context.configProvider),new gL(this.context.configProvider),new mL(this.context.configProvider),new DN(this.mediaManager,this.context.configProvider,e.sdpType),new zN(this.mediaManager,this.context.configProvider,e.sdpType),new QN(this.context.configProvider)])}}},rN=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new qO(this.context,this.mediaManager)}modify(e){this.msSdpT.toMsSdp(e,this.sessionType)}},sN=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new qO(this.context,this.mediaManager)}modify(e){this.msSdpT.fromMsSdp(e,this.sessionType)}},aN=class{constructor(e){this.context=e}modify(e){const t=gm(this.context.configProvider,this.context.config.isPstnCall),i=im(e),n=e.media.find((e=>!!e.crypto));e.media.forEach((e=>{e.type!==Gi.MEDIA_TYPE.dataChannel&&(!t&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!i.dtls||i.sdes&&t?Gi.PROFILES.rtpSavpf:Gi.PROFILES.udpTlsRtpSavpf,NO(e)&&e.protocol===Gi.PROFILES.rtpSavpf&&n&&(e.crypto=n.crypto))}))}},oN=class{constructor(e,t,i){this.mediaManager=e,this.isOffer=t,this.configProvider=i}modify(e){e.media.forEach(((e,t)=>{const i=e.setup,n=this.mediaManager.getMediaEntities()[t],r=n.getExtension("setup");i&&n.isEnabled()&&("actpass"!==i?n.setExtension("setup",i):this.isOffer&&void 0!==r&&"actpass"!==r&&!this.configProvider.config.disableOutgoingDtlsRoleOverride&&(e.setup=r))}))}},lN=class{modify(e){e.media.forEach((e=>{e.direction===Gi.MEDIA_STATE.sendReceive&&(e.direction=Gi.MEDIA_STATE.receive),e.direction===Gi.MEDIA_STATE.send&&(e.direction=Gi.MEDIA_STATE.inactive)}))}},cN=class{constructor(e,t){this.mediaManager=e,this.modalities=t}modify(e){let t=0;e.media.forEach(((e,i)=>{const n=parseInt(e.mid,10);!isNaN(n)&&n>=t&&(t=n+1)})),e.media.forEach(((i,n)=>{const r=this.mediaManager.getMediaEntities()[n];if(NO(i)||r.isDisabled()||!(r.getModality()in this.modalities)){const s=r.getExtension("midApplied")?void 0:i.mid||""+t++;0===n?i.direction=Gi.MEDIA_STATE.inactive:e.media[n]=SL(i.type,void 0,i.protocol,s)}}))}},dN=class{constructor(e,t){this.mediaManager=e,this.remote=t}modify(e){const t=this.mediaManager.getMediaEntities();for(let i=0;i<t.length;i++){const n=t[i],r=e.media[i];if(n.getExtension("rollback"))if(r&&!this.remote)e.media[i]=null;else if(!r&&this.remote){const t=n.getType()===Gi.MEDIA_TYPE.data?Gi.MEDIA_TYPE.dataChannel:n.getType(),i=t===Gi.MEDIA_TYPE.dataChannel?Gi.PROFILES.udpDtlsSctp:Gi.PROFILES.udpTlsRtpSavpf;e.media.push(SL(t,void 0,i,void 0))}}e.media=e.media.filter((e=>e))}},uN=class{constructor(e){this.mediaManager=e}modify(e){this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];t.getModality()!==Gi.MODALITY.data||n&&n.type===Gi.MEDIA_TYPE.dataChannel||e.media.splice(i,0,SL(Gi.MEDIA_TYPE.data,Gi.MEDIA_LABEL.data,Gi.PROFILES.rtpSavp,void 0))}))}},hN=class{constructor(e,t){this.context=e,this.direction=t}modify(e){e.media.forEach((e=>{e.type===Gi.MEDIA_TYPE.dataChannel&&(e.type=Gi.MEDIA_TYPE.data,e.payloads=Gi.PAYLOAD_TYPE.X_DATA)})),mm(this.context)&&yL(e,Gi.MEDIA_TYPE.data).forEach((t=>{t.rtp=t.rtp||[],t.fmtp=t.fmtp||[],t.rtp.push({codec:"x-data",payload:127,rate:9e4}),t.rtp.push({codec:"rtx",payload:126,rate:9e4}),t.fmtp.push({payload:126,config:"apt=127"});const i=this.getNonOverlappingSsrc(e);t.xSsrcRange={ssrcMin:i,ssrcMax:i},t.rtcpMux="rtcp-mux",t.xDataProtocol="sctp",t.direction=this.direction}))}getNonOverlappingSsrc(e){let t,i=!0;do{t=Math.floor(4294967293*Math.random())+2,yL(e).forEach((e=>{e?.ssrcs?.[0]?.id===t&&(i=!1)}))}while(!i);return t}},gN=class{constructor(e){this.configProvider=e,this.uri="urn:3gpp:video-orientation",this.value=13}modify(e){if(this.configProvider.config.enableVideoOrientationExtension)for(const t of yL(e,Gi.MEDIA_TYPE.video))this.modifyMedia(t)}},pN=class extends gN{modifyMedia(e){e.ext??(e.ext=[]),e.ext.some((e=>e.uri===this.uri))||e.ext.push({value:this.getAvailableValue(e.ext),uri:this.uri})}getAvailableValue(e){const t=e.map((e=>e.value));return t.includes(this.value)?Math.max(...t)+1:this.value}},mN=class extends gN{modifyMedia(e){e.ext=e.ext?.filter((e=>e.uri!==this.uri))}},fN=class{constructor(e){this.context=e}modify(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));for(let i=e.media.length-1;i>=0;i--){const n=e.media[i];if(n.type===Gi.MEDIA_TYPE.data){const r=this.context.configProvider.config.rejectUnbundledDataModality&&!this.context.configProvider.mediaConfig.isTransportUnbundled&&!t?.mids?.toString().includes(n.mid),s=mm(this.context);s||this.context.configProvider.config.acceptDisabledDataModality?(n.port=s&&!r?n.port:0,n.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL,n.type=Gi.MEDIA_TYPE.dataChannel,n.protocol=Gi.PROFILES.udpDtlsSctp,n.sctpPort??(n.sctpPort=this.context.configProvider.config.sctpPort),delete n.xDataProtocol,delete n.rtp,delete n.fmtp,delete n.rtcp,delete n.rtcpMux,delete n.ext,delete n.ssrcs,delete n.ssrcGroups,delete n.xSsrcRange):e.media.splice(i,1)}}}},vN=class{constructor(e,t){this.modalities=e,this.mediaManager=t}modify(e){yL(e).forEach((e=>{const t=MO(e),i=this.mediaManager.getMediaEntityByMid(e.mid);!(this.modalities[t]!==Gi.MEDIA_STATE.send||i.getExtension("reinviteless")||e.direction&&e.direction.toLowerCase()===Gi.MEDIA_STATE.receive)&&(e.direction=Gi.MEDIA_STATE.receive)}))}},SN=class{constructor(e,t){this.isMultiparty=e,this.cname=t}modify(e){this.isMultiparty&&yL(e).forEach((e=>{const t=e.direction;t!==Gi.MEDIA_STATE.receive&&t!==Gi.MEDIA_STATE.inactive||(e.ssrcs?.[0]?e.ssrcs=[{id:e.ssrcs[0].id,attribute:"cname",value:this.cname}]:e.type===Gi.MEDIA_TYPE.audio?e.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:e.type===Gi.MEDIA_TYPE.video&&(e.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}))}},yN=class{modify(e){const t=new Set;yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{e.ssrcs&&e.ssrcs.length>1&&t.add(+e.ssrcs[0].id)}));const i=yL(e,Gi.MEDIA_TYPE.video).find((e=>e.direction===Gi.MEDIA_STATE.sendReceive||e.direction===Gi.MEDIA_STATE.send));yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{const n=e.direction;if((n===Gi.MEDIA_STATE.receive||n===Gi.MEDIA_STATE.inactive)&&e.ssrcs&&1===e.ssrcs.length){const n=e.ssrcs[0].id;(1===n||i&&i.ssrcs[0].id===n||!i&&t.has(n))&&(delete e.ssrcs,delete e.ssrcGroups)}}))}},CN=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t];e.label=DO(i.getModality())}))}},TN=class{modify(e){e.media.forEach((e=>{delete e.label}))}},EN=class{constructor(e,t,i){this.mediaManager=e,this.modalities=t,this.configProvider=i}modify(e){let t=this.configProvider.mediaConfig.maxBandwidthInKbps;const i=e.bandwidth?.find((e=>"CT"===e.type));i&&(!t||t>+i.limit)&&(t=+i.limit);const n=this.configProvider.config.audioBandwidthInKbps||0,r=Math.max(t-n,0),s=this.configProvider.config.videoBandwidthAllocation&&Wp(this.modalities.video)&&Wp(this.modalities.sharing);yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{if(delete e.bandwidth,r){let t=r;if(s){const i=this.mediaManager.getMediaEntityByMid(e.mid).getModality()===Gi.MODALITY.video?this.configProvider.config.videoBandwidthAllocation:1-this.configProvider.config.videoBandwidthAllocation;t=Math.round(r*i)}e.bandwidth=[{limit:t,type:"AS"}]}}))}},bN=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.mediaConfig.maxBandwidthInKbps;t&&(e.bandwidth=[{limit:t,type:"CT"}])}},_N=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i.getExtension("iceUfrag");i.setExtension("iceRestart",!!e.iceUfrag&&!!n&&n!==e.iceUfrag),i.setExtension("iceUfrag",e.iceUfrag)}))}},IN=class{modify(e){const t=new Set(["urn:ietf:params:rtp-hdrext:csrc-audio-level","http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]);yL(e).forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}))}},wN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed&&(e.extmapAllowMixed="extmap-allow-mixed")}},AN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed||delete e.extmapAllowMixed}},PN=class{modify(e){yL(e).forEach((e=>{delete e.signalingFbXMessage}))}},RN=class{constructor(e,t,i,n){this.mediaManager=e,this.configProvider=t,this.isConference=i,this.remote=n}modify(e){if(this.configProvider.config.isAv1Allowed&&this.isConference){const t=function(e,t){const i=new Set,n=[];for(const t of e.media)for(const e of t.rtp??[])i.add(e.payload);for(let e=t[0];e<=t[1];e++)i.has(e)||n.push(e);return n}(e,[96,127]);this.mediaManager.getMediaEntities().forEach(((i,n)=>{let r=0;const s=e.media[n];if(i.getModality()!==Gi.MODALITY.audio){if(!this.remote){const e=bL(s,{codec:"AV1",rate:9e4},t,!0,r);r=t.length-1,e.forEach((e=>{bL(s,{codec:"rtx",rate:9e4,payload:e+1},t,!1,r),r--}))}this.remote&&this.configProvider.config.av1LevelIndex&&EO(s,{codec:"AV1",rate:9e4},(e=>{e.fmtp.config=((e,t)=>e.replace(/level-idx=\d+((\.\d+)+)?/g,`level-idx=${t}`))(e.fmtp.config,this.configProvider.config.av1LevelIndex)}))}}))}}},MN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new kN(this.mediaManager,this.configProvider,this.sdpType,!1)}modify(e){this.configProvider.config.filterCodecsInSdpV2||this.baseModifier.modify(e)}},DN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new kN(this.mediaManager,this.configProvider,this.sdpType,!0)}modify(e){this.configProvider.config.filterCodecsInSdpV2&&this.baseModifier.modify(e)}},kN=class{constructor(e,t,i,n=!1){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.alwaysReorder=n}modify(e){this.configProvider.config.filterCodecsInSdp&&"offer"===this.sdpType&&this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];if(!n)return;const r=fm(this.configProvider,n.type);r.length&&PO(n,vm(r),!!t.getExtension("unnegotiatedModality")||this.alwaysReorder,null)}))}},ON=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally)return this.removeSubstitutionCodec(t,"SatinFB"),void this.removeSubstitutionCodec(t,"MUCHv2");i.codec!==i.lastUsedCodec&&"None"!==i.lastUsedCodec&&this.removeSubstitutionCodec(t,i.lastUsedCodec),i.enabledLocally&&!i.disabledRemotely&&this.addSubstitutionCodecIfNeeded(t,i.codec,e)}addSubstitutionCodecIfNeeded(e,t,i){if(this.isSubstitutionCodecAdded(e,t))return;const n=CO(i);if(-1===n)return;const r=TL(t,"SUBSTITUTION");EL(i,r.payload,n),IO(e,r)}removeSubstitutionCodec(e,t){_O(e,TL(t,"SUBSTITUTION"))}isSubstitutionCodecAdded(e,t){let i=!1;return TO(e,TL(t,"SUBSTITUTION"),(()=>{i=!0})),i}},NN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally||i.disabledRemotely)return this.removeSubstitutionCodec(t,"SatinFB"),void this.removeSubstitutionCodec(t,"MUCHv2");const n=TL(i.codec,"SUBSTITUTION"),r=TL(i.codec,"CODEC");TO(t,n,(e=>{e.rtp.codec=r.codec,e.rtp.rate=r.rate,e.rtp.encoding=r.encoding,"SatinFB"===i.codec&&(e.fmtp={payload:r.payload,config:"decoderversion=1"})}))}removeSubstitutionCodec(e,t){_O(e,TL(t,"SUBSTITUTION"))}},LN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(!t)return;const i=this.configProvider.mediaConfig.audioCodecContext;if(!i?.enabledLocally)return this.removeCodec(t,"SatinFB"),void this.removeCodec(t,"MUCHv2");const n=TL(i.codec,"CODEC"),r=TL(i.codec,"SUBSTITUTION");let s=!1;TO(t,n,(e=>{i.enabledForSend&&(e.rtp.codec=r.codec,e.rtp.rate=r.rate,e.rtp.encoding=r.encoding,e.fmtp={payload:n.payload,config:"ptime=20"}),s=!0})),i.disabledRemotely=!s}removeCodec(e,t){_O(e,TL(t,"CODEC")),_O(e,TL(t,"SUBSTITUTION"))}},xN=class{modify(e){_O(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"CN",rate:16e3})}},FN=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;if(this.configProvider.config.fixOpusComfortNoise){if(!t||i&&(!i.enabledLocally||i.disabledRemotely))return}else if(!t||!i?.enabledLocally||i.disabledRemotely)return;let n=!1;const r={codec:"CN",rate:48e3};if(TO(t,r,(()=>{n=!0})),n)return;const s=CO(e);-1!==s&&(this.configProvider.config.fixOpusComfortNoise?r.payload=s:(EL(e,Gi.PAYLOAD_TYPE.MSRTC_CNFB,s),r.payload=Gi.PAYLOAD_TYPE.MSRTC_CNFB),IO(t,r))}},UN=class{modify(e){_O(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"g722",rate:8e3,encoding:2})}},BN=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.config.enforceOpusFmtp;t&&TO(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"opus",rate:48e3,encoding:2},(e=>{e.fmtp||(e.fmtp={payload:e.rtp.payload});const i=new SO(e.fmtp.config);Object.keys(t).forEach((e=>{i.removeIfPresent(e),i.setIfMissing(e,`${t[e]}`)})),e.fmtp.config=i.toString()}))}},VN=class{modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(t&&NO(t)){const i=e.media.find((e=>!!e.iceUfrag));i&&(t.port=9,t.direction="inactive",t.iceUfrag=i.iceUfrag,t.icePwd=i.icePwd,t.rtcpMux="rtcp-mux",i.crypto&&(t.crypto=i.crypto),i.fingerprint&&(t.fingerprint=i.fingerprint,t.setup=i.setup),t.rtp=[{payload:0,codec:"PCMU",rate:8e3}],t.payloads="0")}}},HN=class{constructor(e){this.otherPartyCodecs=e}modify(e){const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=["cn","telephone-event"],n=t.rtp.filter((e=>-1!==this.otherPartyCodecs.indexOf(e.codec.toLowerCase())&&-1===i.indexOf(e.codec.toLowerCase())));if(0===n.length)throw new Error("there is no matching primary audio codec");t.rtp.filter((e=>e!==n[0]&&-1===i.indexOf(e.codec.toLowerCase()))).forEach((e=>{_O(t,e)}))}},$N=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){this.configProvider.config.webrtcInjectTransportCCAudio&&yL(e,Gi.MEDIA_TYPE.audio).forEach((e=>{const t=e.ext?.find((e=>e.uri===Gi.TRANSPORT_CC.EXT_URI));if(!t)return void this.logger.safe.info("transport-cc ext not present in sdp, skipping injecting transport-cc attribute for audio");const i=e.rtp?.find((e=>"opus"===e.codec.toLowerCase()));if(!i)return void this.logger.safe.info("opus codec not found, skipping injecting transport-cc attribute for audio");const n=i.payload,r=e.rtcpFb?.find((e=>e.type===Gi.TRANSPORT_CC.ATTRIBUTE&&e.payload===n));r?this.logger.safe.info("opus codec already has transport-cc attribute"):(e.rtcpFb=e.rtcpFb||[],e.rtcpFb.push({payload:n,type:Gi.TRANSPORT_CC.ATTRIBUTE}),this.logger.safe.info("injected transport-cc attribute"))}))}},jN=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){e.media.forEach(((e,t)=>{if(NO(e)||e.type!==Gi.MEDIA_TYPE.video)return;const i=this.mediaManager.getMediaEntities()[t];TO(e,{codec:"h264",rate:9e4},(e=>{const t=i.getLocalRecvCapabilities();if(!t)return;e.fmtp||(e.fmtp={payload:e.rtp.payload});const n=new SO(e.fmtp.config);this.configProvider.config.h264SdpProfile?(n.removeIfPresent("profile-level-id"),n.setIfMissing("profile-level-id",this.configProvider.config.h264SdpProfile)):n.setIfMissing("profile-level-id","42C02A"),n.setIfMissing("max-fs",t.getMaxFS().toString()),n.setIfMissing("max-mbps",t.getMaxMBPS().toString()),n.setIfMissing("max-fps",t.getMaxFPS().toString()),e.fmtp.config=n.toString()}))}))}},GN=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.removeRtcpRsizeFromLocalSdp)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));t?.rtcpRsize&&delete t.rtcpRsize}},qN=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<this.configProvider.config.nonMultiStreamChannels)return;let t=0;for(let i=0;i<e.media.length;i++)if("Video"===RO(e.media[i])){if(e.media[i].xMultiStream)break;t++}const i=e.media.findIndex((e=>e.xMultiStream)),n=e.media[i];if(!n)return;const r=n.xMultiStream.startSsrc,s=n.xMultiStream.ssrcGroupRange,a=n.xMultiStream.ssrcRange;delete n.xMultiStream;const o=this.configProvider.config.numVideoChannelsGvc-t-1;n.subStreamIndex=o;const l=[];for(let t=0;t<o;t++){const o=(0,FO.cloneDeep)(n);o.mid=xO(e),o.xSourceStreamId=n.xSourceStreamId,o.subStreamIndex=t,l.push(o.mid);const c=r+t*a;o.ssrcGroups=[{ssrcs:`${c} ${c+s}`,semantics:"FID"}],o.xSsrcRange={ssrcMin:c,ssrcMax:c+a-1},e.media.splice(i+t,0,o)}const c=r+o*a;n.ssrcGroups=[{ssrcs:`${c} ${c+s}`,semantics:"FID"}],n.xSsrcRange={ssrcMin:c,ssrcMax:c+a-1};const d=e.groups.find((e=>e.mids.includes(n.mid)));d.mids=`${d.mids} ${l.join(" ")}`}},zN=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.type=i}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<=this.configProvider.config.nonMultiStreamChannels+1)return;const t=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.video);let i=-1,n=-1;if(t.forEach(((t,r)=>{const s=e.media.findIndex((e=>e.mid===t.getMid()));r===this.configProvider.config.nonMultiStreamChannels-1&&(n=s),i=s})),-1===i||-1===n)return;const r=e.media[i];e.media.splice(n+1,i-n-1);const s=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;r.xMultiStream={numberOfStreams:s,startSsrc:1,ssrcRange:1,ssrcGroupRange:1},"answer"===this.type&&(r.xMultiStream.numberOfStreams=Math.min(s,this.configProvider.mediaConfig.multiStreamChannelsOffered),r.ssrcGroups&&delete r.ssrcGroups,r.xSsrcRange&&delete r.xSsrcRange)}},WN=class{constructor(e){this.configProvider=e}modify(e){yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{TO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO,i=new SO(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((e=>{if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n=this.configProvider.config.h264SendProfileOverride||n),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}))}},KN=class{constructor(e,t,i,n,r){this.configProvider=e,this.mediaManager=t,this.sdpType=i,this.remote=n,this.log=r}process(e,t,i){yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{RO(e)===t&&TO(e,{codec:"h264",rate:9e4},(t=>{if(t.fmtp){const n=new SO(t.fmtp.config),r=new SO;let s=!1;for(const t of n.names()){let a=n.get(t);if("profile-level-id"===t){const t=this.mediaManager.getMediaEntities().filter((t=>t.getModality()===MO(e))).filter((e=>e.isEnabled())),n=i(t,a);typeof n==typeof a&&n!==a&&(a=n,s=!0)}r.setIfMissing(t,a)}s&&(t.fmtp.config=r.toString())}}))}))}modify(e){const t=this.configProvider.config.preferredH264SendProfileFallback,i=this.configProvider.config.preferredH264SharingSendProfile,n=this.configProvider.config.preferredH264VideoSendProfile;if(this.remote){const r=e=>(i,n)=>i.some((t=>t.isSendProfileSupported("H264",e)))?(this.log.safe.info(`Overriding H264 send profile: ${n} => ${e}`),e):(this.log.safe.info(`Applying fallback H264 profile: ${n} => ${t}`),t);n&&this.process(e,"Video",r(n)),i&&this.process(e,"ScreenShare",r(i))}else"answer"===this.sdpType&&(n||i)&&this.configProvider.config.enableFallbackH264SendProfileForLocalAnswer&&this.process(e,"Video",((e,r)=>r===n||r===i?(this.log.safe.info(`Restoring fallback profile in local answer: ${r} => ${t}`),t):r))}},JN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{EO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO(e.fmtp.config);t.setIfMissing("sps-pps-idr-in-keyframe","1"),e.fmtp.config=t.toString()}}))}))}},YN=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&yL(e,Gi.MEDIA_TYPE.video).forEach((e=>{EO(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new SO(e.fmtp.config);t.removeIfPresent("sps-pps-idr-in-keyframe"),e.fmtp.config=t.toString()}}))}))}},QN=class{constructor(e){this.configProvider=e}modify(e){const t=(e.groups||[]).findIndex((e=>"BUNDLE"===e.type)),i=e.groups?e.groups[t]:void 0;i&&(this.configProvider.mediaConfig.isTransportUnbundled?(i.mids=this.createBundleFromMedia(yL(e,Gi.MEDIA_TYPE.video)),i.mids||e.groups.splice(t,1)):i.mids=this.createBundleFromMedia(yL(e)))}createBundleFromMedia(e){return e.map((e=>e.mid?.toString())).filter((e=>e)).join(" ")}},ZN=class{modify(e){e.media.forEach((e=>{NO(e)&&e.bundleOnly&&(e.port=9,delete e.invalid)}))}},XN=class{constructor(e,t){this.configProvider=e,this.mediaManager=t}modify(e){if(!this.configProvider.mediaConfig.isTransportUnbundled&&!e.groups?.find((e=>"BUNDLE"===e.type))){let t=!1;if(e.media.forEach(((e,i)=>{const n=this.mediaManager.getMediaEntities()[i];!t&&n.isEnabled()?(e.mid=n.getMid(),t=!0):(n.disable(),e.port=0)})),t){e.groups||(e.groups=[]);const t={type:"BUNDLE"};e.groups.push(t)}}}},eL=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){e.media.forEach((e=>{const t=!!e.candidates;if(e.candidates&&(e.candidates=e.candidates.filter((e=>{let t=!0,i=!0,n=!0;return this.configProvider.config.iceCandidateType&&(t=!!e.type.match(new RegExp(this.configProvider.config.iceCandidateType,"i"))),this.configProvider.config.iceCandidateTransport&&(i=!!e.transport.match(new RegExp(this.configProvider.config.iceCandidateTransport,"i"))),this.configProvider.config.iceCandidateFilterMDns&&(n=!this.isMdns(e.ip),n||this.logger.safe.info(`Filtering out mDNS candidate ${De(e.ip)}:${De(e.port)}`)),t&&i&&n}))),t&&e.connection&&this.configProvider.config.iceCandidateFilterMDns&&(e.candidates&&0!==e.candidates.length||(e.candidates=[CL(e.port)]),this.isMdns(e.connection.ip)||!this.hasMatchingCandidate(e))){const t=this.getDefaultCandidate(e);e.connection.ip=t.ip,e.port=t.port}}))}hasMatchingCandidate(e){const t=e.connection;return t&&!!e.candidates.find(this.createIpAndPortMatcher(t.ip,e.port))}getDefaultCandidate(e){return e.candidates.slice().sort(((e,t)=>e.type===t.type?0:"host"===e.type||"relay"===t.type?1:"relay"===e.type||"host"===t.type?-1:0))[0]}isMdns(e){return e.indexOf(".local")>-1||e.indexOf(".encrypted")>-1}createIpAndPortMatcher(e,t){return i=>i.ip===e&&i.port===t}},tL=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.useOneRelayCandidateForRemoteSDP&&e.media.forEach((e=>{if(e.candidates){const t=e.candidates.filter((e=>!!e.type.match(new RegExp("relay","i"))));t.length>0&&(e.candidates=t.slice(0,1))}}))}},iL=class{modify(e){const t=yL(e)[0];t&&(t.candidates=[CL()])}},nL=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){e.media.forEach(((e,t)=>{this.fromMsSdp(e,t)}))}fromMsSdp(e,t){if(NO(e)||e.rids&&e.simulcast)return;const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n?.shouldBeEnabledInRemoteDesc()&&(n.enableInRemoteDesc(),e.simulcast={dir1:"recv",list1:this.configProvider.config.specCompliantSimulcast?.disableTilde?n.ridList.map((e=>`${e}`)).join(";"):n.ridList.map((e=>`${n.activeRids.includes(e)?"":"~"}${e}`)).join(";")},e.rids=n.ridList.map((e=>({id:e,direction:"recv"}))))}},rL=class{constructor(e,t){this.mediaManager=e,this.logger=t}modify(e){e.media.forEach(((e,t)=>{this.toMsSdp(e,t)}))}toMsSdp(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n&&(n.localDescriptionIsApplied(),n.shouldBeEnabledInLocalDesc()&&(n.enableInLocalDesc(),this.removeSimulcastEnvelope(e),this.addStreamSsrc(e,i.getLocalSsrc())))}removeSimulcastEnvelope(e){e.rids&&delete e.rids,e.simulcast&&delete e.simulcast}addStreamSsrc(e,t){if(!t)return;if(e.ssrcs)return void this.logger.safe.debug(`Media mid: ${e.mid} already contains ssrc: ${JSON.stringify(e.ssrcs)}`);const i=t;this.setSsrc(e,i)}setSsrc(e,t){e.ssrcs=[{id:t,attribute:"fake_attribute",value:"fake_value"}]}},sL=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i?.getLocalTrackId();(!e.msid&&i?.getSimulcastContext()?.shouldUseSimulcast()&&n||i?.getExtension("reinviteless"))&&(e.msid=`- ${n??t}`)}))}},aL=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){const t=this.mediaManager.getMediaEntities(),i=(0,FO.flatMap)(t,(e=>e.getRtpHeaderExtensions())),n=i.find((e=>"vla"===e?.headerType))?.value,r=i.find((e=>"non-adv-vla"===e?.headerType))?.value,s=n??r??(0,FO.flatMap)(e.media,(e=>e.ext||[])).find((e=>e.uri===Gi.VLA.EXT_URI))?.value,a=function(e,t,i,n=!1){const r=(0,FO.flatMap)(e.media,(e=>e.ext||[])).map((e=>e.value));if(0===r.length)return i;if(n&&!r.includes(i))return i;let s;for(let e=2;e<=14;e++)if(!r.includes(e)){s=e;break}return!s&&t&&(s=Math.max(...r)+1),s}(e,this.configProvider.config.extmapAllowMixed,Gi.VLA.DEFAULT_VALUE);e.media.forEach(((e,i)=>{const n=RO(e);if(!this.configProvider.config.enableVla||"Video"!==n&&"ScreenShare"!==n)return;if(e.ext?.find((e=>e.uri===Gi.VLA.EXT_URI)))return;const r=t[i]?.getRtpHeaderExtensions(),o=r?r.find((e=>"vla"===e.headerType))?.value??r.find((e=>"non-adv-vla"===e.headerType))?.value:s??a;o&&(e.ext=e.ext||[],e.ext.push({value:o,uri:Gi.VLA.EXT_URI}))}))}},oL=class{constructor(e){this.configProvider=e}modify(e){e.media.forEach((e=>{const t=RO(e);if(this.configProvider.config.allowRemoteVla&&("Video"===t||"ScreenShare"===t))return;const i=e.ext?.findIndex((e=>e.uri===Gi.VLA.EXT_URI));i>-1&&e.ext.splice(i,1)}))}},lL=class{constructor(e){this.configProvider=e}modify(e,t,i){e.media.forEach((e=>{const n=RO(e);if(!this.configProvider.config.enableNonAdvVla||"Video"!==n&&"ScreenShare"!==n||e.ext?.find((e=>e.uri===i)))return;const r=e.ext?.find((e=>e.uri===t));r&&(r.uri=i)}))}},cL=class extends lL{constructor(e,t){super(e),this.mediaManager=t}modify(e){const t=this.mediaManager.getMediaEntities();(0,FO.flatMap)(t,(e=>e.getRtpHeaderExtensions())).some((e=>"vla"===e?.headerType))||super.modify(e,Gi.VLA.EXT_URI,Gi.VLA.EXT_URI_NON_ADV)}},dL=class extends lL{constructor(e){super(e)}modify(e){super.modify(e,Gi.VLA.EXT_URI_NON_ADV,Gi.VLA.EXT_URI)}},uL=class{modify(e){e.media.forEach((e=>{e.ext?.forEach((e=>e.uri=this.normalizeSlashesInUri(e.uri)))}))}normalizeSlashesInUri(e){return e.replace(/\\/g,"/")}},hL=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.fixSdpForPartialIceRestart){const[{iceUfrag:t,icePwd:i}={}]=e.media;void 0!==t&&void 0!==i&&e.media.forEach((e=>{e.iceUfrag=t,e.icePwd=i}))}}},gL=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.reduceRtcpFbInSdp?.length)for(const t of yL(e,Gi.MEDIA_TYPE.video))t.rtcpFb=t.rtcpFb&&this.getFbList(t.rtcpFb)}getFbList(e){const t=[],i=[];for(const n of e){const e=n.subtype?`${n.type}/${n.subtype}`:`${n.type}`;t.includes(e)||(this.configProvider.config.reduceRtcpFbInSdp.includes(e)?(t.push(e),i.push({...n,payload:"*"})):i.push(n))}return i}},pL=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.redReceiveEnabled)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));let i=0;TO(t,{codec:"opus",rate:48e3,encoding:2},(e=>{i=e.rtp.payload}));const n={codec:"RED",rate:8e3};TO(t,n,(e=>{e.rtp.rate=48e3,e.rtp.encoding=2,i&&(e.fmtp={payload:e.rtp.payload,config:`${i}/${i}`})})),_O(t,n)}},mL=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.redReceiveEnabled&&TO(e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),{codec:"red",rate:48e3,encoding:2},(e=>{e.rtp.codec="RED",e.rtp.rate=8e3,delete e.rtp.encoding}))}},fL=class{constructor(e,t){this.configProvider=e,this.sdpType=t}modify(e){if(!this.configProvider.config.redReceiveEnabled||"offer"!==this.sdpType)return;const t=e.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i={codec:"red",rate:48e3,encoding:2};let n=0;if(TO(t,i,(e=>{n=e.rtp.payload})),n===Gi.PAYLOAD_TYPE.MSRTC_RED)return;const r=CO(e);-1!==r&&(EL(e,Gi.PAYLOAD_TYPE.MSRTC_RED,r),TO(t,i,(e=>{e.rtp.payload=Gi.PAYLOAD_TYPE.MSRTC_RED})))}},vL=class{constructor(e,t){this.modification=e,this.context=t,this.logger=t.getLogger().createChild("IncomingDtlsRoleModifier")}modify(e){if("answer"!==this.modification.sdpType)if("offer"===this.modification.sdpType&&2===this.modification.sdpSource){if(this.modification.isOrWasProvisional){const t=this.context.config.isPstnCall?this.context.configProvider.config.createProvisionalAnswer.dtlsRolePstn:this.context.configProvider.config.createProvisionalAnswer.dtlsRole;if(!t)return;this.logger.debug(`Configured DTLS role override: ${t}`),e.media.forEach(((e,i)=>{const n=e.setup;"inactive"!==e.direction&&(n&&"actpass"!==n?this.logger.warn(`Remote DTLS role is ${n}, cannot change`):(e.setup=t,this.logger.debug(`Remote DTLS role changed from ${n} to ${e.setup} for mid=${e.mid}`)))}))}}else this.logger.error(`Tried to apply invalid change to DTLS role: ${this.modification.sdpType} ${this.modification.sdpSource}`)}};function SL(e,t,i,n){const r={type:e,port:0,label:t,payloads:e===Gi.MEDIA_TYPE.dataChannel||e===Gi.MEDIA_TYPE.data?Gi.PAYLOAD_TYPE.DATA_CHANNEL:"36",protocol:i,connection:{ip:"10.10.10.10",version:4}};return n&&(r.mid=n),r}function yL(e,t=null){return e.media.filter((e=>!(NO(e)||t&&e.type!==t)))}function CL(e=1234){return{component:1,ip:"10.10.10.10",foundation:"1755259772",priority:2122197247,port:9!==e?e:1234,transport:"UDP",type:"host"}}function TL(e,t){if(!tf[e]?.[t])throw`unsupported codec ${e} or type ${t}`;const i=tf[e][t];return{codec:i.NAME,rate:i.RATE,encoding:i.ENCODING,payload:tf[e].PT}}function EL(e,t,i){for(const n of e.media)yO(n,t,i)}function bL(e,t,i,n,r){const s=new Set;return EO(e,t,(e=>{e.rtp.payload<96&&(s.add(e.rtp.payload),e.rtp.payload=i[r]??e.rtp.payload,r++)}),n),s}var _L=class e{constructor(e,t,i,n){this.context=e,this.sessionType=t,this.sdp=i,this.remote=n,this.mediaManager=this.context.mediaManager,this.sdpTransform=this.context.sdpTransform,this.logger=this.context.logger.createChild("SessionDescr"),this.sdpModel=mO.parse(this.sdp),n&&new qN(this.context.configProvider).modify(this.sdpModel),this.sdpModel.media.forEach((e=>{(0,pO.isUndefined)(e.mid)||(e.mid=e.mid.toString())})),this.remote&&!this.context.configProvider.config.disableMsSdp&&new sN(e,this.mediaManager,t).modify(this.sdpModel)}getSdp(){return mO.write(this.sdpModel)}clone(){return new e(this.context,this.sessionType,this.sdp,this.remote)}getModalities(){return this.modalities||kO(this.sdpModel)}updateModalities(e){this.logger.debug("updateModalities",e),this.modalities=e}getSrtpInfo(){return im(this.sdpModel)}getVideoCodecs(){const e={};return this.sdpModel.media.forEach((t=>{"video"===t.type&&t.rtp.map((e=>e.codec.toLowerCase())).forEach((t=>e[t]=!0))})),Object.keys(e)}usePrimaryAudioCodecOnly(e){new HN(e).modify(this.sdpModel)}isCodecSwitchSupported(){return!this.sdpModel.media.some((e=>e.type===Gi.MEDIA_TYPE.audio&&e.xMediaSettings&&this.containsMediaSetting(e.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 e="offer"===this.sessionType;return new eL(this.context.configProvider,this.logger).modify(this.sdpModel),(new ZN).modify(this.sdpModel),e&&this.mediaManager.isEmpty()&&this.mediaManager.fromOffer(this.sdpModel,this.modalities),this.mediaManager.syncModalities(this.sdpModel,this.modalities,!e),this.sdpModel=e?this.sdpTransform.toOffer(this.sdpModel,this.mediaManager,this.modalities):this.sdpTransform.toAnswer(this.sdpModel,this.mediaManager,this.modalities),this.context.configProvider.config.disableMsSdp||new rN(this.context,this.mediaManager,this.sessionType).modify(this.sdpModel),new jN(this.mediaManager,this.context.configProvider).modify(this.sdpModel),this.modalities=kO(this.sdpModel),this.getSdp()}setModalities(e){this.modalities=e,this.mediaManager.fromRemote(this.sdpModel,this.modalities)}toRemote(e=!1){return this.sdpModel=this.sdpTransform.toRemote(this.sdpModel,this.mediaManager,this.modalities,this.sessionType,e),this.getSdp()}getVideoRecvCapabilities(){return LO(this.getMediaByLabel(Gi.MEDIA_LABEL.video))}getSharingRecvCapabilities(){return LO(this.getMediaByLabel(Gi.MEDIA_LABEL.sharing))}getMediaByType(e){return this.sdpModel.media.find((t=>t.type===e))}isUnbundled(){const e=this.sdpModel.groups?.find((e=>"BUNDLE"===e.type)),t=this.sdpModel.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),i=this.sdpModel.media.find((e=>e.type===Gi.MEDIA_TYPE.video));return e?!e.mids.toString().split(" ").find((e=>e===t.mid)):!!i}couldBeUnbundled(){return!this.sdpModel.groups?.find((e=>"BUNDLE"===e.type))||this.hasUnbundledIceCandidates()}containsMediaSetting(e,t){return e.some((e=>-1!==e.settings.indexOf(t)))}getMediaByLabel(e){return this.sdpModel.media.find((t=>t.label===e))}hasIceCandidatesForMediaType(e,t=""){const i=this.sdpModel.media?this.sdpModel.media.filter((t=>t.type===e&&!!t.candidates&&0!==t.candidates.length)):[];return t?i.some((e=>!!e.candidates&&e.candidates.some((e=>e.type===t)))):!!i.length}hasIceCandidates(){return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio)||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video)}hasRelayIceCandidates(){return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio,"relay")||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video,"relay")}hasUnbundledIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Gi.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio)&&(!e.length||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video))}hasUnbundledRelayIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Gi.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.audio,"relay")&&(!e.length||this.hasIceCandidatesForMediaType(Gi.MEDIA_TYPE.video,"relay"))}isIceRestart(){return this.mediaManager.getMediaEntities().some((e=>e.getExtension("iceRestart")))}isMSRTC(){return!!this.sdpModel.xMediaBw}insertFakeCandidateIfNeeded(){return!this.hasIceCandidates()&&((new iL).modify(this.sdpModel),!0)}forceRecvonly(){(new lN).modify(this.sdpModel)}getBweType(){const e=this.sdpModel.media.find((e=>0!==e.port&&e.type===Gi.MEDIA_TYPE.video));if(!e)return"Unknown";const t=e.ext?.find((e=>e.uri===Gi.TRANSPORT_CC.EXT_URI||e.uri===Gi.TRANSPORT_CC.MSSDP_ENCODED_URI));return t?"SSBWE":"REMB"}fixDataModality(){new uN(this.mediaManager).modify(this.sdpModel)}getPayloadsForMedia(e){const t=this.sdpModel.media.find((t=>t.type===e&&0!==t.port));return t?.rtp??[]}},IL=class{constructor(e){this.context=e}createLocalOffer(e){return new _L(this.context,"offer",e)}createRemoteOffer(e){return new _L(this.context,"offer",e,!0)}createLocalAnswer(e){return new _L(this.context,"answer",e)}createRemoteAnswer(e){return new _L(this.context,"answer",e,!0)}},wL=class{static build(e){return new IL(e=e||{})}};function AL(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var PL=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(e){"host"===e.type&&"udp"===e.protocol?this.setIPAddressInfo(e.ip):"srflx"===e.type&&this.setReflexiveLocalIP(e.ip)}setOfferedModalities(e){this.offeredModalities=e,this.activeModalities=e}setNegotiatedModalities(e){this.negotiatedModalities=e,this.activeModalities=e}setNegotiatedSrtpInfo(e){this.info.NegotiatedSrtp=AL(e)}setOfferedSrtpInfo(e){this.info.OfferedSrtp=AL(e)}setIceConnectionState(e){this.info.IceConnectionStatePrevious=this.info.IceConnectionState,this.info.IceConnectionState=e}setSignalingConnectionState(e){this.info.SignalingStatePrevious=this.info.SignalingState,this.info.SignalingState=e}setRelayCandidateInfo(e){this.info.RelayCandidate=JSON.stringify(e)}fillExtensionInfo(e){!function(e,t){for(const i in t)t.hasOwnProperty(i)&&(e[i]=t[i])}(e,this.info)}setIceTransportPolicy(e){this.info.IceTransportPolicy=e}setIceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.info.IceServers=JSON.stringify(t)}setFakeIceCandidate(e){this.info.FakeIceCandidate=e}setBweType(e){"Unknown"!==e&&(this.info.BweType=e)}setSdpSemantics(e){this.info.SdpSemantics=e}setBundlePolicy(e){this.info.BundlePolicy=e}setEncodedStreamWorkerLoaded(e){this.info.EncodedStreamWorker=e}setAudioCodecEvents(e){this.info.AudioCodecEvents=JSON.stringify(e)}setIPAddressInfo(e){this.info.NumberOfInterfaces+=1,"none"===this.info.IPAddress&&(this.info.IPAddress=e)}setReflexiveLocalIP(e){"none"===this.info.ReflexiveLocalIP&&(this.info.ReflexiveLocalIP=e)}},RL=class{constructor(){this.presentationAPIUserDuration=0,this.presentationAudioDuration=0,this.isActiveScreenSharing=!1}handleInputLevel(e,t){this.isActiveScreenSharing&&("ScreenShare"===e&&t>0&&(this.presentationAPIUserDuration+=Gi.TIME_INTERVAL.SEC_1),"Audio"===e&&t>0&&(this.presentationAudioDuration+=Gi.TIME_INTERVAL.SEC_1))}updateScreenSharingStream(e,t){"ScreenShare"===t&&(this.isActiveScreenSharing=!!e)}getPresentationAudioDuration(){return this.presentationAudioDuration}getPresentationAudioAPIUserDuration(){return this.presentationAPIUserDuration}},ML=class e{constructor(e){this.name=e,this.sharedState={mark:new Map,measure:[]}}mark(e,t){const i=_n();this.sharedState.mark.set(e,{name:e,ts:i,startTime:mn(In+i),details:t})}measure(e,t){const i=this.sharedState.mark.get(t.start),n=this.sharedState.mark.get(t.end);if(i&&n){const r={...t,parentName:this.name===e?"":this.name};this.sharedState.measure.push({name:e,details:r,duration:mn(n.ts-i.ts),startTime:i.startTime})}}markAndMeasure(e,t,i,n){!1===this.sharedState.mark.has(t)&&this.mark(t,i);const r=this.sharedState.mark.get(e),s=this.sharedState.mark.get(t);if(r&&s){const e={...n,parentName:this.name===t?"":this.name};this.sharedState.measure.push({name:t,details:e,duration:mn(s.ts-r.ts),startTime:r.startTime})}}clone(t){const i=new e(`${this.name}|${t}`);return i.setSharedState(this.sharedState),i}setSharedState(e){this.sharedState=e}getReport(){return this.sharedState.measure.map((e=>({name:e.name,duration:e.duration,ts:e.startTime,parentName:e.details.parentName})))}},DL=class e{mark(){}measure(){}markAndMeasure(){}clone(){return new e}getReport(){return[]}},kL=class{constructor(e){this.enableTimerTracker=e,this.timerTrackers={},this.timerTrackerOptions={}}getTimerTracker(e,t){if(!this.enableTimerTracker)return new DL;const i=new ML(e);if(this.timerTrackers[e]){const t=this.timerTrackerOptions[e];if(t?.first)return new DL;t?.last&&(this.timerTrackers[e]=[i]),t?.all&&this.timerTrackers[e].push(i)}else this.timerTrackers[e]=[i],this.timerTrackerOptions[e]=t;return i}getReport(){if(this.enableTimerTracker)return Object.keys(this.timerTrackers).reduce(((e,t)=>{const i=this.timerTrackerOptions[t];return(i.first||i.last)&&(e[t]=[this.timerTrackers[t][0]?.getReport()]),i.all&&(e[t]=Object.values(this.timerTrackers[t]).map((e=>e?.getReport()))),e}),{})}},OL=class{constructor(e,t){this.configProvider=e,this.sessionInfo=t,this.data={fakeCandidate:!1,bweType:"Unknown",offeredSrtp:"unknown",negotiatedSrtp:"unknown",callSetupTimeReport:{}},this.timerTrackerManager=new kL(this.configProvider.config.enableTimerTracker),yn(this.data,{callSetupTimeReport:()=>this.timerTrackerManager.getReport()})}getTimerTracker(e,t){return this.timerTrackerManager.getTimerTracker(e,t)}set offeredModalities(e){this.data.offeredModalities=e,this.data.activeModalities=e,this.sessionInfo.setOfferedModalities(e)}set negotiatedModalities(e){this.data.negotiatedModalities=e,this.data.activeModalities=e,this.sessionInfo.setNegotiatedModalities(e)}set fakeCandidate(e){var t;(t=this.data).fakeCandidate||(t.fakeCandidate=e),this.sessionInfo.setFakeIceCandidate(e)}set bweType(e){this.data.bweType=e,this.sessionInfo.setBweType(e)}set negotiatedSrtp(e){this.data.negotiatedSrtp=NL(e),this.sessionInfo.setNegotiatedSrtpInfo(e)}set offeredSrtp(e){this.data.offeredSrtp=NL(e),this.sessionInfo.setOfferedSrtpInfo(e)}set meetingScenario(e){this.data.meetingScenario=e}set isTownHall(e){this.data.isTownHall=e}getObjectRef(){return this.data}};function NL(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var LL=class{constructor(e){this.data=e,this.reopenRequestDeviceIds=new Set}registerReopenRequest(e){this.reopenRequestDeviceIds.has(e)||(this.data.sinkNumOfReopenRequests++,this.reopenRequestDeviceIds.add(e))}registerSuccessfullReopen(e){this.reopenRequestDeviceIds.has(e)&&(this.data.sinkNumOfSuccessfulReopens++,this.reopenRequestDeviceIds.delete(e))}getObjectRef(){return this.data}},xL=class{constructor(e){this.configProvider=e,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={},yn(this.data,{scheduledCallbacks:()=>this.scheduledCallbacks.values(),timers:()=>{const e={};for(const t of Object.keys(this.stateTrackers))e[t]=this.stateTrackers[t].durations;return e}})}dispose(){for(const e of Object.values(this.stateTrackers))e.dispose()}set hasConnectionState(e){this.data.hasConnectionState=e}set transportState(e){this.data.transportStatePrevious=this.data.transportState,this.data.transportState=e,this.addStateEvent("transport",this.data.transportStatePrevious,this.data.transportState)}set signalingState(e){this.data.signalingStatePrevious=this.data.signalingState,this.data.signalingState=e,this.addStateEvent("signaling",this.data.signalingStatePrevious,this.data.signalingState)}set iceConnectionState(e){this.data.iceConnectionStatePrevious=this.data.iceConnectionState,this.data.iceConnectionState=e,this.addStateEvent("ice",this.data.iceConnectionStatePrevious,this.data.iceConnectionState)}set connectionState(e){this.data.connectionStatePrevious=this.data.connectionState,this.data.connectionState=e,this.addStateEvent("connection",this.data.connectionStatePrevious,this.data.connectionState)}set dtlsTransportState(e){this.data.dtlsTtransportStatePrevious=this.data.dtlsTransportState,this.data.dtlsTransportState=e,this.addStateEvent("dtlsTransport",this.data.dtlsTtransportStatePrevious,this.data.dtlsTransportState)}set provisional(e){this.addStateEvent("provisional",`${this.data.isProvisional}`,`${e}`),this.data.isProvisional=e}scheduleDoOnConnected(e,t,i,n){this.scheduledCallbacks.set(e,`${t}: ${i?"p":""}${n?"n":""}`),this.addCallbackEvent(t,i,n),this.data.numCallbacksScheduled++}runDoOnConnected(e,t=!1){this.scheduledCallbacks.get(e)&&this.scheduledCallbacks.delete(e),this.data.numCallbacksExecuted++,t&&this.data.numCallbacksExecutedImmediately++}getObjectRef(){return this.data}addCallbackEvent(e,t,i){rt(this.data.events,{evType:"callback",timestamp:Date.now(),logName:e,allowProvisional:t,mayRunImmediately:i},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents)}addStateEvent(e,t,i){rt(this.data.events,{evType:"stateChanged",timestamp:Date.now(),changedState:e,previous:t,current:i},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents);const n=this.stateTrackers[e]??new FL;n.state=i,this.stateTrackers[e]=n}},FL=class{constructor(){this.stopwatches={}}set state(e){if(this.stateInternal===e)return;this.running?.stop();const t=this.stopwatches[e]??new GL;this.stopwatches[e]=t,t.start(),this.running=t,this.stateInternal=e}get durations(){const e={};for(const t in this.stopwatches){const i=this.stopwatches[t];e[t]=i.elapsed}return e}dispose(){this.running?.stop(),this.running=void 0}},UL=/profile-level-id=(.{6})/,BL=class{constructor(e,t,i=()=>{},n=()=>this,r=()=>{},s=new sO,a){this.configProvider=e,this.dmDiagnostics=t,this.addSessionStatsError=i,this.newNativeSession=n,this.commitNativeSession=r,this.dshDiagnostics=s,this.getSessionRef=a,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 RL,yn(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(e){this.bandwidthStatsRef=e}get callIsMuted(){return this.getSessionRef?.().callIsMuted}get sharingAudioLevel(){return this.analyzerSharing?.getInputLevelNormalized()}set relayCandidateInfo(e){this.data.relayCandidate=JSON.stringify(e)}set iceTransportPolicy(e){this.data.iceTransportPolicy=e}set reinvitelessContext(e){this.data.reinvitelessContext=e}set iceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.data.iceServers=JSON.stringify(t)}set sdpSemantics(e){this.data.sdpSemantics=e}set isCodecsSupported(e){this.data.codecSupport=e}set bundlePolicy(e){this.data.bundlePolicy=e}set latestRawReport(e){this.data.latestRawReport=e}set recvVideoStreamsCount(e){this.data.recvVideoStreamCount=e}set aggregatedStatsRef(e){this.data.aggregatedModalityStats=e}set multiViewStats(e){this.data.multiViewStats=e}set videoCapabilities(e){if(!e?.codecs)return;const t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=UL.exec(e.sdpFmtpLine)?.[1];i&&t.push(i)}})),this.data.H264Profiles=[...new Set(this.data.H264Profiles.concat(t))]}setSupportedH264Profiles(e,t){if(!e?.codecs&&!t?.codecs)return;const i=e=>{const t=[];return e.codecs?.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=UL.exec(e.sdpFmtpLine)?.[1];i&&!t.includes(i)&&t.push(i)}})),t};this.data.h264CodecCapabilities.sendProfiles=i(e),this.data.h264CodecCapabilities.receiveProfiles=i(t)}set sentBWSeed(e){var t;(t=this.data).initialBWSeed??(t.initialBWSeed=e),this.data.sentBWSeed=e}reportedSendBandwidthLayouts(e){rt(this.data.reportedSendBandwidthLayouts,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}set maxSessionBandwidth(e){this.data.maxSessionBandwidth=e}set bwStabilizationTime(e){this.data.bwStabilizationTime=e}set bwDownlinkStabilizationTime(e){this.data.bwDownlinkStabilizationTime=e}set statsOnSubscribed(e){this.data.statsOnSubscribed=e}set loopIntervalMax(e){this.data.loopIntervalMax=e}set loopIntervalMedian(e){this.data.loopIntervalMedian=e}set fetchTimeMax(e){this.data.fetchTimeMax=e}set fetchTimeMedian(e){this.data.fetchTimeMedian=e}set simulcastReport(e){this.data.simulcast=e}setTotalVideoRecvMblocksRates(e){this.data.totalVideoRecvMblocksRates=e}set dataChannelSessionState(e){this.data.dataChannelSessionState=e}set createChannelFailReason(e){this.data.dataChannelCreationError=e}setCandidateDetails(e){"host"===e.type&&"udp"===e.protocol?(this.data.numInterfaces++,this.data.IPAddress||(this.data.IPAddress=e.ip)):"srflx"!==e.type||this.data.reflexiveLocalIP||(this.data.reflexiveLocalIP=e.ip)}setAudioSendStream(e,t){if(this.configProvider.config.useAudioAnalyzer){const i=new zk(e.rawStream);"ScreenShare"===t&&e.hasAudio()?(this.analyzerSharing?.dispose(),this.analyzerSharing=i):"Audio"===t&&(this.analyzer?.dispose(),this.analyzer=i)}}addNetworkInfo(e){rt(this.data.networkInfo,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addIceCandidateError(e){this.data.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.data.iceCandidateErrors=[]}registerEarlyMediaPoll(){this.data.earlyMediaNumStatsPolls++}addReportedReceiveBandwidth(e){rt(this.data.reportedReceiveBandwidth,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addOvcSubscriptionReport(e,t,i){const n=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];n?.ovc.count!==e&&rt(this.data.ovcToSubscriptionEvents,{ovc:{ts:Date.now(),count:e,subsCount:t,...i},subs:[]},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addSubscriptionToOvcEvent(e){const t=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];t&&rt(t.subs,{ts:Date.now(),count:e},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addStatsReport(e){rt(this.data.statsReports,e,this.configProvider.config.diagnostics.collectionLimits.numStatsReports)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));i?i.count++:rt(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors),this.addSessionStatsError(`nativeSession:${e}`,t)}setPresentationAudioOnScreenSharing(e,t){this.presentationAudioTelemetry.updateScreenSharingStream(e,t)}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 e=new uO(this.configProvider,((e,t)=>this.addStatsError(`qualityManagerDiagnostics:${e}`,t)));return this.data.qualityManager=e.getObjectRef(),e}newRemoteVideoManagerDiagnostics(){const e=new hO(this.configProvider);return this.data.remoteVideoManager=e.getObjectRef(),e}newNegotiationDiagnostics(e){const t=new OL(this.configProvider,e);return this.data.negotiation=t.getObjectRef(),t}newSubscriptionManagerDiagnostics(){const e=new dO(this.configProvider,(e=>this.addStatsError("subscriptionManagerDiagnostics",e)));return this.data.subscriptionManager=e.getObjectRef(),e}newDataChannelDiagnostics(e){const t=new Jg(e);return this.data.dataChannel=t.getObjectRef(),t}newTransportStateDiagnostics(){const e=new xL(this.configProvider);return this.data.transportState=e.getObjectRef(),e}set encodedStreamWorker(e){this.data.encodedStreamWorker=e}set audioCodecEvents(e){this.data.audioCodecEvents=e}getObjectRef(){return this.data}registerVideoPerformanceEvent(e,t,i){const n={type:t,perfEvent:e,resRequestEvent:null,resChangedEvent:[],perfConstrainedOvc:i};rt(this.data.videoPerformanceEvent,n,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}registerLocalVideoPerformanceEvent(e){rt(this.data.localVideoPerformanceEvents,{timestamp:Date.now(),description:e.description,activeModalities:e.activeModalities,isTransient:e.isTransient},this.configProvider.config.diagnostics.collectionLimits.numPerformanceEvents)}registerResolutionChangeRequest(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];t&&(t.resRequestEvent=e)}registerResolutionChangeEvent(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];e.ts-t?.resRequestEvent?.ts<this.configProvider.config.diagnostics.performanceMonitoring.telemetryResolutionRequestSpanMs&&t.resChangedEvent.push(e)}set contributingSourcesError(e){this.data.contributingSourcesError=e}newAudioRendererDiagnostics(){return this.data.audioRenderer=this.getSessionRef?.().audioRenderer,this.data.audioRenderer?new LL(this.data.audioRenderer):null}},VL=Symbol("sessionDiagnosticsRef"),HL=class{constructor(e,t,i,n,r,s,a){this.logger=e,this.configProvider=t,this.diagnosticsReport=i,this.dmDiagnostics=n,this.ufdDiagnostics=r,this.dshDiagnostics=new sO,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:[],remoteUfdsCount:{},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,ufdManager:void 0,relayTimers:void 0,authTokenFetcherStats:void 0,dominantSpeaker:this.dshDiagnostics.getObjectRef(),[VL]:this,callConstraints:[],audioRenderer:{sinkNumOfReopenRequests:0,sinkNumOfSuccessfulReopens:0},elevation:[],batteryLevel:void 0},this.transportDisconnected=!1,this.commonMuteTracker=new GL,this.swMuteTracker=new GL,this.osMuteTracker=new GL,this.speakerMuteTracker=new GL,this.hwSilentTracker=new GL,this.isSpeakingTracker=new GL,this.networkRecvTracker=new qL,this.networkSendTracker=new qL,this.zeroCaptureTracker=new qL,this.zeroRenderTracker=new qL,this.deviceRenderTracker=new qL,this.deviceCaptureTracker=new qL,this.rawMediaTimers={audio:{send:new GL,recv:new GL}},this.dmFragmenter=new jL(this.dmDiagnostics),this.ufdFragmenter=new $L(this.ufdDiagnostics),this.durationTimer=new GL,this.data.callNumber=s,this.data.sessionId=a,this.durationTimer.start(),yn(this.data,{isOngoing:()=>void 0===this.data.terminationTime,duration:()=>this.durationTimer.elapsed,callMutedRatio:()=>zL(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(),ufdManager:()=>this.ufdFragmenter.getFragment(this.ufdDiagnostics)}),yn(this.data.rawMedia.audio.recv,{durationRatio:()=>zL(this.rawMediaTimers.audio.recv.elapsed,this.data.duration)}),yn(this.data.rawMedia.audio.send,{durationRatio:()=>zL(this.rawMediaTimers.audio.send.elapsed,this.data.duration)})}get telemetryReport(){const e={type:"WebRtcMediaStats",data:this.diagnosticsReport.getSessionTelemetry(this.data.sessionId)},t={};return zi(e.data,((e,i,n)=>{let r=0;Hp.test(e)?(r=13,t[i]="IPv4"):$p.test(e)&&(r=4,t[i]="IPv6"),n[i]={type:r,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(t),__VALUE__:!0},e}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(e){this._relayManager=e}set isMultiParty(e){this.data.isMultiParty=e}set mediaLegId(e){this.data.mediaLegId=e.process()}set ETag(e){this.data.ETag=e}set configIds(e){this.data.configIds=e}set reconnect(e){this.data.reconnect=e}set relay(e){this.data.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}set sessionError(e){this.data.error=e}set dtmfResult(e){e?this.data.dtmfSuccessCount++:this.data.dtmfFailureCount++}set swMute(e){e?this.swMuteTracker.start():this.swMuteTracker.stop(),this.updateCommonMute()}set speakerMute(e){e?this.speakerMuteTracker.start():this.speakerMuteTracker.stop()}set hwSilent(e){e?this.hwSilentTracker.start():this.hwSilentTracker.stop()}set isSpeaking(e){e?this.isSpeakingTracker.start():this.isSpeakingTracker.stop()}set iceInitTime(e){this.data.iceInitTime||(this.data.iceInitTime=e)}set finalAnswerTime(e){this.data.finalAnswerTime||(this.data.finalAnswerTime=e)}set iceConnectedStateTimestamp(e){this.data.iceConnectedStateTime||(this.data.iceConnectedStateTime=e)}set allowedModalities(e){this.data.allowedAudioSend=e.audio.some((e=>Wp(e))),this.data.allowedVideoSend=e.video.some((e=>Wp(e))),this.data.allowedScreensharingSend=e.sharing.some((e=>Wp(e)))}negotiationStart(e){var t;(t=this.data).initialNegotiationType??(t.initialNegotiationType=e),this.data.negotiationCount++}negotiationCompleted(e){this.data.initialNegotiationCompleted=!0,this.data.activeModalities=e,this.data.error=void 0}negotiationRejected(){this.data.rejectedNegotiationCount++}registerRollbackEvent(e){this.data.rollbackNegotiation.push({type:e.type,attempt:this.data.rollbackNegotiation.length+1,error:e.error})}registerRawMediaAccess(e,t,i){const n=this.data.rawMedia[e]?.[t];if(n){n.numAttempts++;const r=this.rawMediaTimers[e]?.[t];i?r?.start():r?.stop()}}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.data.noIceCandidatesEventCount.good++:this.data.noIceCandidatesEventCount.bad++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.data.noRelayIceCandidatesEventCount.good++:this.data.noRelayIceCandidatesEventCount.bad++;break;case"DeviceCaptureNotFunctioning":this.deviceCaptureTracker.updateLevel(e.value),"Good"===e.value?this.data.microphoneInUseEventCount.good++:this.data.microphoneInUseEventCount.bad++;break;case"DeviceRenderNotFunctioning":this.deviceRenderTracker.updateLevel(e.value);break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.data.cameraInUseEventCount.good++:this.data.cameraInUseEventCount.bad++;break;case"DeviceCaptureMute":"Bad"===e.value?this.osMuteTracker.start():this.osMuteTracker.stop(),this.updateCommonMute();break;case"NetworkRecvQuality":this.networkRecvTracker.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSendTracker.updateLevel(e.value);break;case"ZeroCaptureDevicesEnumerated":this.zeroCaptureTracker.updateLevel(e.value);break;case"ZeroRenderDevicesEnumerated":this.zeroRenderTracker.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.data.cameraFreezeEventCount.end++:this.data.cameraFreezeEventCount.start++}"DeviceSpeakWhileMuted"!==e.type&&Sn(this.data.ufds,{...e,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRemoteQualityStateChangedEvent(e,t){e.forEach((e=>{var i,n,r;(i=this.data.remoteUfdsCount)[n=Rf(e)]??(i[n]={});const s=this.data.remoteUfdsCount[Rf(e)];s[r=e.value.toLowerCase()]??(s[r]=0),s[e.value.toLowerCase()]++,rt(this.data.remoteUfds,{...e,participantId:t,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(e){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=nn(e),this.data.terminationTime=Date.now(),this.durationTimer.stop(),this.dmFragmenter.terminated(this.dmDiagnostics),this.ufdFragmenter.terminated(this.ufdDiagnostics)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));this.logger.safe.error(`Stats error from '${e}': ${t} (${i?.count??1})`),i?i.count++:Sn(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}newNativeSessionDiag(e=!0){let t;return t=new BL(this.configProvider,this.dmDiagnostics,((e,t)=>this.addStatsError(e,t)),(e=>this.newNativeSessionDiag(e)),(()=>this.pushNativeSessionDiag(t.getObjectRef())),this.dshDiagnostics.resetState(),(()=>this.getObjectRef())),e&&Sn(this.data.webrtcSessions,t.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numNativeSessions),t}pushNativeSessionDiag(e){Sn(this.data.webrtcSessions,e,this.configProvider.config.diagnostics.collectionLimits.numNativeSessions)}getObjectRef(){return this.data}setBatteryLevel(e){this.data.batteryLevel=e}updateCommonMute(){this.swMuteTracker.isRunning||this.osMuteTracker.isRunning?this.commonMuteTracker.start():this.swMuteTracker.isRunning||this.osMuteTracker.isRunning||this.commonMuteTracker.stop()}registerElevation(e){rt(this.data.elevation,{event:e,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numElevation)}},$L=class{constructor(e){this.fragmentBase=nn(e)}getFragment(e){const t=this.fragmentTerminated??e,i={};for(const[e,n]of Object.entries(t.count))for(const[t,r]of Object.entries(n)){const n=this.fragmentBase.count[e]?this.fragmentBase.count[e][t]:void 0,s=n?r-n:r;s&&(i[e]??(i[e]={}),i[e][t]=s)}return{count:i}}terminated(e){this.fragmentTerminated=nn(e)}},jL=class{constructor(e){this.initTimestamp=Number.MIN_SAFE_INTEGER,this.terminatedTimestamp=Number.MAX_SAFE_INTEGER,this.fragmentBase=this.sanitizeDiagnostics(e),this.initTimestamp=Date.now()}getFragment(e){const t=this.fragmentTerminated??e;return{devicesChangeCount:t.devicesChangeCount-this.fragmentBase.devicesChangeCount,deviceSelectionChangeCount:t.deviceSelectionChangeCount-this.fragmentBase.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:t.deviceSelectionChangeCountFromInterface-this.fragmentBase.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:t.devicesPollChangeCount-this.fragmentBase.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:t.audioSourceNumOfSuccessfulReopens-this.fragmentBase.audioSourceNumOfSuccessfulReopens||void 0,audioSourceNumOfReopenRequests:t.audioSourceNumOfReopenRequests-this.fragmentBase.audioSourceNumOfReopenRequests||void 0,audioCaptureDeviceErrorFlag:e.audioCaptureDeviceErrorFlags.filter((e=>e.timestamp>this.initTimestamp&&e.timestamp<this.terminatedTimestamp)).reduce(((e,t)=>Number(BigInt(e)|BigInt(t.audioDeviceErrorFlag))),0),audioRenderDeviceErrorFlag:e.audioRenderDeviceErrorFlags.filter((e=>e.timestamp>this.initTimestamp&&e.timestamp<this.terminatedTimestamp)).reduce(((e,t)=>Number(BigInt(e)|BigInt(t.audioDeviceErrorFlag))),0)}}terminated(e){this.fragmentTerminated=this.sanitizeDiagnostics(e),this.terminatedTimestamp=Date.now()}sanitizeDiagnostics(e){return{devicesChangeCount:e.devicesChangeCount,deviceSelectionChangeCount:e.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:e.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:e.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:e.audioSourceNumOfSuccessfulReopens,audioSourceNumOfReopenRequests:e.audioSourceNumOfReopenRequests,audioCaptureDeviceErrorFlag:0,audioRenderDeviceErrorFlag:0}}},GL=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+_n()-this.startTime:this.elapsedInternal)}get count(){return this.countInternal}start(){this.startTime||(this.startTime=_n(),this.countInternal++)}stop(){this.startTime&&(this.elapsedInternal+=_n()-this.startTime,this.startTime=0)}},qL=class{constructor(){this.currentLevel="Good",this.stopWatches={},this.startTime=_n(),this.getStopWatch(this.currentLevel).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getRatio(e){return zL(this.getStopWatch(e).elapsed,Math.round((this.endTime||_n())-this.startTime))}dispose(e){this.getStopWatch(this.currentLevel).stop(),this.endTime=_n()}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new GL,this.stopWatches[e]=t),t}};function zL(e,t){return e/(t||1)}function WL(e,t,i){return rn({recv:rn({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytesReceived:Pn(e.audio?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Pn(e.audio?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Pn(e.audio?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:t?.codec?.mimeType.split("/").pop(),googTrackId:t?.track?.trackIdentifier,transport_id:t?.transport?.id,transportId:t?.inboundRTP.transportId,transport_selectedCandidatePairId:t?.transport?.selectedCandidatePairId,transport_dtlsCipher:t?.transport?.dtlsCipher,transport_srtpCipher:t?.transport?.srtpCipher,pair_id:t?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:t?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:t?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:t?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:t?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(e.audio?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:t?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:t?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:t?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:t?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:t?.transport?.selectedCandidatePair?.localCandidate?.ip??t?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:t?.transport?.selectedCandidatePair?.remoteCandidate?.ip??t?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:t?.transport?.selectedCandidatePair?.nominated}),send:rn({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytesSent:Pn(e.audio?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Pn(e.audio?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Pn(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:i?.codec?.mimeType.split("/").pop(),googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.outboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(e.audio?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated})})}function KL(e,t,i,n){return rn({recv:rn({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytesReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Pn(t[e]?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:i?.codec?.mimeType.split("/").pop(),codecImplementationName:i?.inboundRTP.decoderImplementation,googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.inboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(t[e]?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated,framesDecoded:Pn(t[e]?.recv,(e=>e.inboundRTP.framesDecoded)),googFrameHeightReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.frameHeight)),googFrameWidthReceived:Pn(t[e]?.recv,(e=>e.inboundRTP.frameWidth)),googFrameRateReceived:Pn(t[e]?.recv,(e=>e.extensions?.frameRateReceived||0)),googNacksSent:Pn(t[e]?.recv,(e=>e.inboundRTP.nackCount)),googPlisSent:Pn(t[e]?.recv,(e=>e.inboundRTP.pliCount)),keyFramesDecoded:Pn(t[e]?.recv,(e=>e.inboundRTP.keyFramesDecoded)),googFirsSent:Pn(t[e]?.recv,(e=>e.inboundRTP.firCount)),googJitterBufferMs:Pn(t[e]?.recv,(e=>e.extensions?.jitterBufferMs)),googFrameRateDecoded:Pn(t[e]?.recv,(e=>e.extensions?.frameRateDecoded||0)),googFrameRateOutput:i?.extensions?.trackRecvFps,jitter:i?.inboundRTP.jitter}),send:rn({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytesSent:Pn(t[e]?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Pn(t[e]?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Pn(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:n?.codec?.mimeType.split("/").pop(),codecImplementationName:n?.outboundRTP.encoderImplementation,googTrackId:n?.track?.trackIdentifier,transport_id:n?.transport?.id,transportId:n?.outboundRTP.transportId,transport_selectedCandidatePairId:n?.transport?.selectedCandidatePairId,transport_dtlsCipher:n?.transport?.dtlsCipher,transport_srtpCipher:n?.transport?.srtpCipher,pair_id:n?.transport?.selectedCandidatePair?.id,pair_responsesSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:n?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:n?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:n?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:n?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Pn(t[e]?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:n?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:n?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:n?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:n?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:n?.transport?.selectedCandidatePair?.localCandidate?.ip??n?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:n?.transport?.selectedCandidatePair?.remoteCandidate?.ip??n?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Pn(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:n?.transport?.selectedCandidatePair?.nominated,framesEncoded:Pn(t[e]?.send,(e=>e.outboundRTP.framesEncoded)),googNacksReceived:Pn(t[e]?.send,(e=>e.outboundRTP.nackCount)),googPlisReceived:Pn(t[e]?.send,(e=>e.outboundRTP.pliCount)),googFirsReceived:Pn(t[e]?.send,(e=>e.outboundRTP.firCount)),keyFramesEncoded:Pn(t[e]?.send,(e=>e.outboundRTP.keyFramesEncoded)),googFrameHeightInput:n?.mediaSource?.height,googFrameWidthInput:n?.mediaSource?.width,googFrameRateInput:Pn(t[e]?.send,(e=>e.mediaSource?.framesPerSecond)),googFrameHeightSent:Pn(t[e]?.send,(e=>e.outboundRTP.frameHeight)),googFrameWidthSent:Pn(t[e]?.send,(e=>e.outboundRTP.frameWidth)),googFrameRateSent:Pn(t[e]?.send,(e=>e.extensions?.frameRateSent)),googRtt:Pn(t[e]?.send,(e=>1e3*(e.remoteInboundRTP?.roundTripTime??0)),!0),hugeFramesSent:n?.outboundRTP.hugeFramesSent,qpSum:Pn(t[e]?.send,(e=>e.outboundRTP.qpSum)),qualityLimitationDurations:n?JSON.stringify(n?.outboundRTP.qualityLimitationDurations):void 0,qualityLimitationReason:n?.outboundRTP.qualityLimitationReason,qualityLimitationResolutionChanges:n?.outboundRTP.qualityLimitationResolutionChanges,jitter:n?.remoteInboundRTP?.jitter,retransmittedPacketsSent:Pn(t[e]?.send,(e=>e.outboundRTP.retransmittedPacketsSent))})})}var JL=e=>rn({id:e.outboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,rtt:e.remoteInboundRTP?.roundTripTime,frameRateInput:e.mediaSource?.framesPerSecond,frameWidthInput:e.mediaSource?.width,frameHeightInput:e.mediaSource?.height,framesEncoded:e.outboundRTP.framesEncoded,frameRateEncoded:e.extensions?.frameRateEncoded,framesSent:e.outboundRTP.framesSent,frameRateSent:e.extensions?.frameRateSent,frameWidthSent:e.outboundRTP.frameWidth,frameHeightSent:e.outboundRTP.frameHeight,keyFramesEncoded:e.outboundRTP.keyFramesEncoded,nackCount:e.outboundRTP.nackCount,firCount:e.outboundRTP.firCount,pliCount:e.outboundRTP.pliCount,transportId:e.outboundRTP.transportId,isFsOvershooting:e.extensions?.isFsOvershooting,isFpsOvershooting:e.extensions?.isFpsOvershooting,isBrOvershooting:e.extensions?.isBrOvershooting,totalFsOvershootDuration:e.extensions?.totalFsOvershootDuration,totalFpsOvershootDuration:e.extensions?.totalFpsOvershootDuration,totalBrOvershootDuration:e.extensions?.totalBrOvershootDuration,altLayouts:e.altLayouts?.map(JL)}),YL=e=>rn({id:e.inboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,msi:e.renderer?.msi,jitterBufferMs:e.extensions?.jitterBufferMs,frameRateOutput:e.extensions?.frameRateDecoded,frameRateDecoded:e.extensions?.frameRateDecoded,frameRateReceived:e.extensions?.frameRateReceived,frameWidthReceived:e.inboundRTP.frameWidth,frameHeightReceived:e.inboundRTP.frameHeight,longestFreezeDuration:e.extensions?.longestFreeze,totalFreezeDuration:e.extensions?.totalFreezeDuration,framesReceived:e.inboundRTP.framesReceived,framesDropped:e.inboundRTP.framesDropped,framesDecoded:e.inboundRTP.framesDecoded,keyFramesDecoded:e.inboundRTP.keyFramesDecoded,nackCount:e.inboundRTP.nackCount,firCount:e.inboundRTP.firCount,pliCount:e.inboundRTP.pliCount,transportId:e.inboundRTP.transportId}),QL=e=>rn({id:e.outboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.remoteInboundRTP?.packetsDiscarded,rtt:e.remoteInboundRTP?.roundTripTime,audioLevel:e.mediaSource?.audioLevel,transportId:e.outboundRTP.transportId}),ZL=e=>rn({id:e.inboundRTP.ssrc.toString(),codecName:e.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,jitterBufferMs:e.extensions?.jitterBufferMs,audioLevel:e.inboundRTP.audioLevel,healedRatio:e.extensions?.healedRatio,transportId:e.inboundRTP.transportId}),XL=e=>rn({id:e.id,state:e.state,dataChannelIdentifier:e.dataChannelIdentifier,messagesSent:e.messagesSent,bytesSent:e.bytesSent,messagesReceived:e.messagesReceived,bytesReceived:e.bytesReceived,sendBitrate:e.extensions?.sendBitrate,recvBitrate:e.extensions?.recvBitrate,messagesSentPerSecond:e.extensions?.sendMessageRate,messagesReceivedPerSecond:e.extensions?.recvMessageRate}),ex=e=>rn({id:e.id,rtt:e.selectedCandidatePair?.currentRoundTripTime,availableIncomingBitrate:e.selectedCandidatePair?.availableIncomingBitrate,availableOutgoingBitrate:e.selectedCandidatePair?.availableOutgoingBitrate,relayProtocol:e.selectedCandidatePair?.localCandidate?.relayProtocol,candidateType:`${e.selectedCandidatePair?.localCandidate?.candidateType??""}:${e.selectedCandidatePair?.remoteCandidate?.candidateType??""}`});function tx(e){return(e.audio?.send??[]).map(QL)}function ix(e){return(e.audio?.recv??[]).map(ZL)}function nx(e){return e.video?.send?.length?e.video.send.map(JL):[]}function rx(e){return(e.video?.recv??[]).map(YL)}function sx(e){return e.sharing?.send?.length?e.sharing.send.map(JL):[]}function ax(e){return(e.sharing?.recv??[]).map(YL)}function ox(e){return(e.data??[]).map(XL)}function lx(e){return Object.values(e.transports??{}).map(ex)}function cx(e){return 1e4*e}function dx(e,t=Number(new Date)){if(!e)return;const i=nn(e);return e.lastMsgDate&&(e.timeSinceLastMsg=e.lastMsgDate-t),delete i.lastMsgDate,delete i.lastHistory,rn(i)}function ux(e,t,i=0){const n=t.filter((e=>void 0!==e));let r;switch(e){case"Difference":r=n[n.length-1]-n[0];break;case"Average":r=n.reduce(((e,t)=>e+t),0)/n.length;break;case"LastValue":r=n[n.length-1]}return r||0===r?`${"number"==typeof r?+r.toFixed(i):r}`:void 0}function hx(e,t,i){return(i?e.map((e=>e?.[t]?.[i])):e.map((e=>e?.[t]))).filter((e=>void 0!==e)).reduce(((e,t)=>e.concat(t)),[])}function gx(e){const t=e[e.length-1]?.extensions?.powerEfficient;return void 0===t?"":t?"hw":"sw"}function px(e,t){return e&t?"Bidirectional":e?"ReceiveFromPeer":t?"SendToPeer":"Inactive"}function mx(e){const t=e[e.length-1]?.extensions?.callIsMuted,i=e[e.length-1]?.extensions?.rawInputVolume;return t?"0":!t&&i>0?"2":t||0!==i?void 0:"1"}function fx(e,t){const i=ux("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/").pop(),n=i?i+` ${gx(e)}`:void 0;return{"Rtp Packet Sent":ux("Difference",e.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":ux("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Current Bitrate":ux("Average",e.map((e=>e?.extensions?.bitrate))),"Allocated Send Bandwidth Average":ux("LastValue",e.map((e=>e?.extensions?.bitrateAvg))),"Send Actual Height":ux("LastValue",e.map((e=>e?.outboundRTP.frameHeight))),"Send Actual Width":ux("LastValue",e.map((e=>e?.outboundRTP.frameWidth))),"Send Current Frame Rate":ux("Average",e.map((e=>e?.extensions?.frameRateSent))),"Send RTT (Avg)":ux("LastValue",e.map((e=>e?.extensions?.rttAvg))),"Sent Codec Name":n,"Webcam Freeze Intervals":ux("LastValue",e.map((e=>e?.extensions?.captureFreezeIntervalsCount))),"Current Capture Device Name":t?.camera,"Number of Sync Frame Request per Minute":ux("LastValue",e.map((e=>e?.extensions?.pliRate)))}}function vx(e){const t=ux("LastValue",e.map((e=>e?.mediaEntity?.xSourceStreamId))),i=ux("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/").pop(),n=i?i+` ${gx(e)}`:void 0;return{"Recv Loss Rate (Avg)":ux("LastValue",e.map((e=>e?.extensions?.lossRate)),3),"Received BW estimate":ux("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Receive Current Bitrate":ux("Average",e.map((e=>e?.extensions?.bitrate))),"Rtp Packets Received":ux("Difference",e.map((e=>e?.inboundRTP.packetsReceived))),"Receive Actual Height":ux("LastValue",e.map((e=>e?.inboundRTP.frameHeight))),"Receive Actual Width":ux("LastValue",e.map((e=>e?.inboundRTP.frameWidth))),"Receive Current Frame Rate":ux("Average",e.map((e=>e?.extensions?.frameRateReceived))),"Received Codec Name":n,"Received Total Freeze Fraction (ms per min)":ux("LastValue",e.map((e=>e?.extensions?.totalFreezeFraction))),videoSourceId:t?parseInt(t):void 0,"Received Fps Time Weighted Harmonic Average":ux("LastValue",e.map((e=>e?.extensions?.fpsHarmonicAverage)))}}function Sx(e,t,i){const n=function(e,t){const i=hx(e,"audio","send"),n=hx(e,"audio","recv"),r=function(e){const t=e.find((e=>e?.transports));return t?t.transports[Object.keys(t.transports)[0]]:void 0}(e);if(i.length||n.length)return rn({mediaType:"Audio",mediaDirection:px(n.length,i.length),"Received BW estimate":ux("Average",n.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Recv Loss Rate (Avg)":ux("LastValue",n.map((e=>e?.extensions?.lossRate/100)),3),"Rtp Packets Received":ux("Difference",n.map((e=>e?.inboundRTP.packetsReceived))),"Rtp Packet Sent":ux("Difference",i.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":ux("Average",i.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Audio Codec":ux("LastValue",i.map((e=>e?.codec?.mimeType)))?.split("/").pop(),"Send RTT (Avg)":ux("LastValue",i.map((e=>e?.extensions?.rttAvg))),"Audio NW jitter avg":ux("LastValue",n.map((e=>e?.extensions?.jitterAvg)),3),"Audio send bps":ux("Average",i.map((e=>e?.extensions?.bitrate))),"JB delay (ms)":ux("LastValue",n.map((e=>e?.extensions?.jitterBufferDelayMs))),"Recv Audio Codec":ux("LastValue",n.map((e=>e?.codec?.mimeType)))?.split("/").pop(),"Current Render Device Name":t?.speaker,"Current Capture Device Name":t?.microphone,"Latest Network Type":r?.selectedCandidatePair?.localCandidate?.networkType,"Latest Transport Protocol":r?.selectedCandidatePair?.localCandidate?.protocol,"Latest Reflexive Address":ym(r?.extensions?.reflexiveLocalIP),"Local Address":ym(r?.selectedCandidatePair?.localCandidate?.ip),"Local short-term Healed Data Ratio":ux("LastValue",n.map((e=>e?.extensions?.healedRatio))),"Send activity (0=muted; 1=inactive; 2=active)":mx(i)})}(e,t);n&&i.channels.push(n);const r=function(e,t){const i=[],n=function(e){const t={},i=i=>{e.map((e=>e?.video?.[i])).forEach((e=>{e?.forEach((e=>{var n;const r=e?.mediaEntity?.remoteSsrc;t[r]??(t[r]={}),(n=t[r])[i]??(n[i]=[]),t[r][i].push(e)}))}))};return i("recv"),i("send"),t}(e);for(const{send:e,recv:r}of Object.values(n)){let n={mediaType:"Camera",mediaDirection:px(r?.length,e?.length)};r&&(n={...n,...vx(r)}),e&&(n={...n,...fx(e,t)}),i.push(rn(n))}return i}(e,t);r.length&&i.channels.push(...r);const s=function(e){const t=hx(e,"sharing","send"),i=hx(e,"sharing","recv");if(!i.length&&!t.length)return;let n={mediaType:"AppSharing",mediaDirection:"Bidirectional","Render Device Name":""};return i.length&&(n={...n,...vx(i)}),t.length&&(n={...n,...fx(t,{microphone:void 0,camera:"Screen sharing",speaker:void 0})}),rn(n)}(e);s&&i.channels.push(s)}function yx(e,t,i,n,r){return rn({recv:rn({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytes:Rn(t[e]?.recv,(e=>e.inboundRTP.bytesReceived),r),packets:Rn(t[e]?.recv,(e=>e.inboundRTP.packetsReceived),r),packetsLost:Rn(t[e]?.recv,(e=>e.inboundRTP.packetsLost),r),codec:i?.codec?.mimeType.split("/").pop(),codecReport:i?.aggregated?.codecReport,framesDecoded:Rn(t[e]?.recv,(e=>e.inboundRTP.framesDecoded),r),height:Rn(t[e]?.recv,(e=>e.inboundRTP.frameHeight),r),width:Rn(t[e]?.recv,(e=>e.inboundRTP.frameWidth),r),frameRate:Rn(t[e]?.recv,(e=>e.extensions?.frameRateReceived),r)}),send:rn({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytes:Rn(t[e]?.send,(e=>e.outboundRTP.bytesSent),r),packets:Rn(t[e]?.send,(e=>e.outboundRTP.packetsSent),r),packetsLost:Rn(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost),r),codec:n?.codec?.mimeType.split("/").pop(),framesEncoded:Rn(t[e]?.send,(e=>e.outboundRTP.framesEncoded),r),heightInput:n?.mediaSource?.height,widthInput:n?.mediaSource?.width,height:Rn(t[e]?.send,(e=>e.outboundRTP.frameHeight),r),width:Rn(t[e]?.send,(e=>e.outboundRTP.frameWidth),r),frameRate:Rn(t[e]?.send,(e=>e.extensions?.frameRateSent),r)})})}function Cx(e,t,i,n){return rn({recv:rn({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytes:Rn(e.audio?.recv,(e=>e.inboundRTP.bytesReceived),n),packets:Rn(e.audio?.recv,(e=>e.inboundRTP.packetsReceived),n),packetsLost:Rn(e.audio?.recv,(e=>e.inboundRTP.packetsLost),n),codec:t?.codec?.mimeType.split("/").pop(),audioLevel:Rn(e.audio?.recv,(e=>Math.floor(65535*e.inboundRTP.audioLevel)),n)}),send:rn({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytes:Rn(e.audio?.send,(e=>e.outboundRTP.bytesSent),n),packets:Rn(e.audio?.send,(e=>e.outboundRTP.packetsSent),n),packetsLost:Rn(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost),n),codec:i?.codec?.mimeType.split("/").pop(),audioLevel:Rn(e.audio?.send,(e=>Math.floor(65535*e.aggregated.audioLevel)),n)})})}function Tx(e){return rn({negotiationCount:e.negotiationCount,rejectedNegotiationCount:e.rejectedNegotiationCount})}var Ex=class{constructor(e,t){this.rootRef=e,this.configProvider=t}get rawRootRef(){return this.rootRef}getSessionTelemetry(e){const t=this.getLatestSession(e);if(!t)return;const i={metrics:{},Extensions:{}},n=_n();try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,n=e?.terminationTime??0,r=t.webrtcSessions[t.webrtcSessions.length-1];i.metrics=function(e,t,i,n){const r=n.config.diagnostics.telemetryLimits,s=e.webrtcSessions[e.webrtcSessions.length-1];return rn({MediaLegId:e.mediaLegId,CreationTime:cx(e.creationTime),CallNumber:e.callNumber,SessionId:e.sessionId,MultiParty:e.isMultiParty,ErrorType:e.error?.type??"none",ErrorDetail:e.error?.detail??"none",IncompatibleOffer:e.error?.type===Gi.MEDIA_ERROR.incompatibleOffer,TerminationTime:cx(e.terminationTime),TerminationReason_code:e.terminationReason?.code,TerminationReason_subCode:e.terminationReason?.subCode,TerminationReason_phrase:e.terminationReason?.phrase,TerminationReason_remoteTerminated:e.terminationReason?.remoteTerminated,TerminationReason_clientReasonPhrase:e.terminationReason?.clientReasonPhrase,TerminationReason_clientReasonSubCode:e.terminationReason?.clientReasonSubCode,TerminationReason_resultCategories:e.terminationReason?.resultCategories,CallDuration:cx(e.duration),IceInitTime:cx(e.iceInitTime),IceConnectedStateTime:cx(e.iceConnectedStateTime),NegotiationCount:e.negotiationCount,RejectedNegotiationCount:e.rejectedNegotiationCount,InitialNegotiationCompleted:e.initialNegotiationCompleted,InitialNegotiationType:e.initialNegotiationType,FinalAnswerTime:cx(e.finalAnswerTime),TransportReconnectedCount:e.transportReconnectedCount,RollbackNegotiation:JSON.stringify(e.rollbackNegotiation),Relay:e.relay?JSON.stringify(e.relay):void 0,ActiveModalities:JSON.stringify(e.activeModalities),AllowedAudioSend:e.allowedAudioSend,AllowedVideoSend:e.allowedVideoSend,AllowedScreensharingSend:e.allowedScreensharingSend,RelayManager:JSON.stringify(e.relayTimers),AuthTokenStats:JSON.stringify(e.authTokenFetcherStats),CallMutedRatio:e.callMutedRatio,CallOsMuted:cx(e.callOsMuted),CallHwSilent:cx(e.callHwSilent),CallSwMuted:cx(e.callSwMuted),CallSpeakerMuted:cx(e.callSpeakerMuted),CallIsSpeaking:cx(e.callIsSpeaking),DtmfSuccess:e.dtmfSuccessCount,DtmfFailure:e.dtmfFailureCount,ContributingSourcesError:s.contributingSourcesError,ReconnectInProgress:e.reconnect?.isReconnecting,RetargetIncomingCount:e.reconnect?.retargetCount.incoming,RetargetOutgoingCount:e.reconnect?.retargetCount.outgoing,RetargetCompletedCount:e.reconnect?.retargetCount.completed,RetargetRejectedCount:e.reconnect?.retargetCount.rejected,EscalationAttemptedCount:e.reconnect?.escalationCount.attempted,EscalationCompletedCount:e.reconnect?.escalationCount.completed,EscalationRejectedCount:e.reconnect?.escalationCount.rejected,Elevation:JSON.stringify(e.elevation),ReconnectAttemptedCount:e.reconnect?.reconnectCount.attempted,ReconnectConnectedCount:e.reconnect?.reconnectCount.connected,ReconnectAttempts:xn(e.reconnect?.records,r.numReconnects,"startTime",e.creationTime),NetworkEvents:xn(e.reconnect?.tmpRecords,r.numNetworkEvents,"startTime",e.creationTime),NoIceCandidatesGoodEventCount:e.noIceCandidatesEventCount.good,NoIceCandidatesBadEventCount:e.noIceCandidatesEventCount.bad,NoRelayIceCandidatesGoodEventCount:e.noRelayIceCandidatesEventCount.good,NoRelayIceCandidatesBadEventCount:e.noRelayIceCandidatesEventCount.bad,MicrophoneInUseGoodEventCount:e.microphoneInUseEventCount.good,MicrophoneInUseBadEventCount:e.microphoneInUseEventCount.bad,CameraInUseGoodEventCount:e.cameraInUseEventCount.good,CameraInUseBadEventCount:e.cameraInUseEventCount.bad,CameraFreezeStartEventCount:e.cameraFreezeEventCount.start,CameraFreezeEndEventCount:e.cameraFreezeEventCount.end,NetworkRecvGood:e.networkRecvUFD.good,NetworkRecvGoodRatio:e.networkRecvUFD.goodRatio,NetworkRecvPoor:e.networkRecvUFD.poor,NetworkRecvPoorRatio:e.networkRecvUFD.poorRatio,NetworkRecvBad:e.networkRecvUFD.bad,NetworkRecvBadRatio:e.networkRecvUFD.badRatio,NetworkSendGood:e.networkSendUFD.good,NetworkSendGoodRatio:e.networkSendUFD.goodRatio,NetworkSendPoor:e.networkSendUFD.poor,NetworkSendPoorRatio:e.networkSendUFD.poorRatio,NetworkSendBad:e.networkSendUFD.bad,NetworkSendBadRatio:e.networkSendUFD.badRatio,Connection_Downlink:Pn(s.networkInfo,(e=>e.downlink)),Connection_EffectiveType:s.networkInfo.map((e=>e.effectiveType)).filter((e=>e)).join(","),Connection_Rtt:Pn(s.networkInfo,(e=>e.rtt)),Connection_SaveData:Cn(s.networkInfo)?.saveData,RawOutputAudioAccessAttempted:e.rawMedia.audio.recv.numAttempts,RawOutputAudioAccessDurationRatio:e.rawMedia.audio.recv.durationRatio,RawInputAudioOverrideAttempted:e.rawMedia.audio.send.numAttempts,RawInputAudioOverrideDurationRatio:e.rawMedia.audio.send.durationRatio,ZeroCaptureDevicesEnumeratedEventRatio:mn(e.zeroCaptureDevicesRatio,Gi.NATIVE_RATIO_PRECISION),ZeroRenderDevicesEnumeratedEventRatio:mn(e.zeroRenderDevicesRatio,Gi.NATIVE_RATIO_PRECISION),DeviceCaptureNotFunctioningEventRatio:mn(e.deviceCaptureFailuresRatio,Gi.NATIVE_RATIO_PRECISION),DeviceRenderNotFunctioningEventRatio:mn(e.deviceRenderFailuresRatio,Gi.NATIVE_RATIO_PRECISION),UFDs:xn(e.ufds,r.numUFDs,"timestamp",e.creationTime),remoteUFDs:xn(e.remoteUfds,r.numUFDs,"timestamp",e.creationTime),UFDs_count:JSON.stringify(e.ufdManager.count),remoteUFDs_count:JSON.stringify(e.remoteUfdsCount),MediaQosEnabled:i.configuration.mediaConfig?.enableMediaQoS??!1,PortRangeConfigured:!!i.configuration.mediaConfig?.mediaPortRanges,hardwareConcurrency:i.configuration.userAgentConfig.hardwareConcurrency,ETag:e.ETag,ConfigIds:e.configIds,GPUName:i.configuration.userAgentConfig.unmaskedGlRenderer,PermissionStates:JSON.stringify(i.deviceManager.permissionStates),DeviceList:JSON.stringify(i.deviceManager.deviceList),DeviceListDebug:JSON.stringify(i.deviceManager.deviceDebugStrings),DevicesChangeCount:e.deviceManager.devicesChangeCount,DevicesPollChangeCount:e.deviceManager.devicesPollChangeCount,DeviceSelectionChangeCount:e.deviceManager.deviceSelectionChangeCount,DeviceSelectionChangeFromInterfaceCount:e.deviceManager.deviceSelectionChangeCountFromInterface,DevicesCount:JSON.stringify(i.deviceManager.devicesCount),UsedMicrophone:i.deviceManager.usedDevices?.microphone,UsedSpeaker:i.deviceManager.usedDevices?.speaker,UsedCamera:i.deviceManager.usedDevices?.camera,DeviceEvents:xn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),r.numDeviceEvents,"timestamp",e.creationTime),VideoEffects:xn(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>t)),r.numVideoEffectsEvents,"timestamp",e.creationTime),AudioEffects:xn(i.deviceManager.audioEffectsEvents.filter((e=>e.timestamp>t)),r.numAudioEffectsEvents,"timestamp",e.creationTime),WorkerEvents:xn(i.deviceManager.workerEvents.filter((e=>e.timestamp>t)),r.numWorkerEvents,"timestamp",e.creationTime),MediaByPassEnabled:!!i.configuration.mediaConfig.enableMediaBypass,CallConstraints:JSON.stringify(e.callConstraints),DominantSpeaker:JSON.stringify(dx(e.dominantSpeaker,e.terminationTime)),AudioSourceNumOfReopenRequests:e.deviceManager.audioSourceNumOfReopenRequests||void 0,AudioSourceNumOfSuccessfulReopens:e.deviceManager.audioSourceNumOfSuccessfulReopens||void 0,AudioCaptureErrorCodeFlagsInit:e.deviceManager.audioCaptureDeviceErrorFlag,AudioRenderErrorCodeFlagsInit:e.deviceManager.audioRenderDeviceErrorFlag,AudioSinkNumOfReopenRequests:e.audioRenderer.sinkNumOfReopenRequests,AudioSinkNumOfSuccessfulReopens:e.audioRenderer.sinkNumOfSuccessfulReopens,CallSetupTimeTracker:JSON.stringify(e.webrtcSessions[0].negotiation.callSetupTimeReport),LastSessionSetupTimeTracker:e.webrtcSessions.length>1?JSON.stringify(s.negotiation.callSetupTimeReport):void 0,BatteryLevel:e.batteryLevel})}(t,n,this.rootRef,this.configProvider),i.Extensions=function(e,t,i){const n=t.config.diagnostics.telemetryLimits,r=e.aggregatedModalityStats,s=Cn(r.audio?.recv),a=Cn(r.audio?.send),o=Cn(r.video?.recv),l=Cn(r.video?.send),c=Cn(r.sharing?.recv),d=Cn(r.sharing?.send),u=i=>i&&vn(nn(i).map((t=>wn(vn(t.events,n.numCapabilitiesApplied,1),"timestamp",e.startTime))),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),h=u(e.qualityManager?.videoMaxCapabilitiesEvents),g=u(e.qualityManager?.videoMaxCapabilitiesErrors),p=u(e.qualityManager?.sharingMaxCapabilitiesEvents),m=u(e.qualityManager?.sharingMaxCapabilitiesErrors),f="REMB"!==e.negotiation.bweType?e.bandwidthReport:void 0,v="REMB"===e.negotiation.bweType?e.bandwidthReport:void 0;return rn({BundlePolicy:e.bundlePolicy,FakeIceCandidate:e.negotiation.fakeCandidate,h264AvailableProfiles:JSON.stringify(e.H264Profiles),h264CodecCapabilities:JSON.stringify(e.h264CodecCapabilities),IceConnectionState:e.transportState?.iceConnectionState,IceConnectionStatePrevious:e.transportState?.iceConnectionStatePrevious,IceServers:e.iceServers,IceTransportPolicy:e.iceTransportPolicy,NegotiatedSrtp:JSON.stringify(e.negotiation.negotiatedSrtp),OfferedSrtp:JSON.stringify(e.negotiation.offeredSrtp),RelayCandidate:e.relayCandidate,SdpSemantics:e.sdpSemantics,iceCandidateErrors:JSON.stringify(e.iceCandidateErrors),SignalingState:e.transportState?.signalingState,SignalingStatePrevious:e.transportState?.signalingStatePrevious,WebRTCStats_statsErrors:JSON.stringify(i),MaxSessionBandwidth:e.maxSessionBandwidth,Bandwidth_uplinkStabilizationTime:JSON.stringify(e.bwStabilizationTime),Bandwidth_downlinkStabilizationTime:JSON.stringify(e.bwDownlinkStabilizationTime),totalVideoControlMessages:e.qualityManager?.numVideoControlMessages,outOfOrderVideoControlMessages:e.qualityManager?.numOutOfOrderVideoControlMessages,webcamFreezeIntervals:e.qualityManager?.numWebcamFreezeIntervals,processedStreamFreezeIntervals:e.qualityManager?.numProcessedStreamFreezeIntervals,IPAddress:e.IPAddress??"none",ReflexiveLocalIP:e.reflexiveLocalIP??"none",NumberOfInterfaces:e.numInterfaces,StartTime:e.startTime,EndTime:e.endTime,AudioTransportRecvBitrate:s?.transport?.extensions?.recvBWAvg,AudioTransportSendBitrate:s?.transport?.extensions?.sendBWAvg,AudioPayloadRecvBitrate:s?.aggregated?.bitrateAvg,AudioPayloadSendBitrate:a?.aggregated?.bitrateAvg,VideoPayloadRecvBitrate:o?.aggregated?.bitrateAvg,VideoPayloadSendBitrate:l?.aggregated?.bitrateAvg,WebRTCStats_bweStat_googAvailableReceiveBandwidth:Pn(r.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate))??Pn(r.video?.send,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate)),WebRTCStats_bweStat_googAvailableSendBandwidth:Pn(r.video?.send,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate))??Pn(r.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate)),Bandwidth_jumpsHistogram:JSON.stringify(l?.transport?.extensions?.bwJumpsHistogram),StartCallBWESendSide:JSON.stringify(f?.startOfTheCall),EndCallBWESendSide:JSON.stringify(f?.endOfTheCall),BWEStdSendSide:JSON.stringify(f?.std),BwPercentilesSendSide:JSON.stringify(f?.bwPercentiles),AvgBwSendSide:JSON.stringify(f?.avgBwe),StartCallBWE:JSON.stringify(v?.startOfTheCall),EndCallBWE:JSON.stringify(v?.endOfTheCall),BWEStd:JSON.stringify(v?.std),BwPercentiles:JSON.stringify(v?.bwPercentiles),AvgBw:JSON.stringify(v?.avgBwe),WebRTCStats_ssrc:rn({audio:WL(r,s,a),video:KL("video",r,o,l),sharing:KL("sharing",r,c,d)}),Audio_recv_jitterBufferAvgSize:s?.aggregated?.avgJitterBufferSize,Audio_recv_packetsLostRateMax:mn(s?.aggregated?.lossRateMax,6),Audio_recv_jitterAvg:s?.aggregated?.jitterAvg,Audio_recv_jitterMax:s?.aggregated?.jitterMax,Audio_recv_networkAvgLossRate:mn(s?.aggregated?.networkAvgLossRate,6),Audio_recv_packetsLostAvg:s?.aggregated?.packetsLostAvg,Audio_recv_healedRatioAvg:s?.aggregated?.healedRatioAvg,Audio_recv_healedRatioMax:s?.aggregated?.healedRatioMax,Audio_send_rttAvg:a?.aggregated?.rttAvg&&mn(1e3*a.aggregated.rttAvg),Audio_send_rttMax:a?.aggregated?.rttMax&&mn(1e3*a.aggregated.rttMax),Audio_send_RawInputVolume:Pn(r.audio?.send,(e=>e.aggregated?.rawInputVolume)),Audio_send_packetsLostRateMax:mn(a?.aggregated?.lossRateMax,6),Audio_send_presentationAPIUserDuration:e.presentationAPIUserDuration,Audio_send_presentationDuration:e.presentationAudioDuration,Video_recv_DurationSeconds:o?.aggregated?.duration,Video_recv_FreezeHistogram:JSON.stringify(o?.aggregated?.freezeCountHistogram),Video_recv_FreezeTimestamps:JSON.stringify(An(o?.aggregated?.freezeTimestampsHistogram,e.startTime,n.numOfHistogramSamples)),Video_recv_LongestFreezeDuration:o?.aggregated?.longestFreeze,Video_recv_OngoingFreeze:o?.extensions?.isFrozen,Video_recv_OngoingFreezeDuration:o?.aggregated?.ongoingFreezeDuration,Video_recv_TotalFreezeDuration:o?.aggregated?.totalFreezeDuration,Video_recv_RecvAvgFreezeDuration:o?.aggregated?.avgFreezeDuration,Video_recv_NumResolutionSwitches:o?.aggregated?.numResolutionSwitches,Video_recv_ResolutionDurations:JSON.stringify(o?.aggregated?.resolutionDurations),Video_recv_StreamsMax:e.recvVideoStreamCount.max,Video_recv_StreamsMin:e.recvVideoStreamCount.min,Video_recv_StreamsMode:e.recvVideoStreamCount.mode,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_bitrateAvg:o?.aggregated?.bitrateAvg,Video_recv_bitrateMax:o?.aggregated?.bitrateMax,Video_recv_frameRateAvg:o?.aggregated?.avgFrameRate,Video_recv_jitterBufferAvgSize:o?.aggregated?.avgJitterBufferSize,Video_recv_packetsLostRateMax:mn(o?.aggregated?.lossRateMax,6),Video_recv_isRenderingEvents:JSON.stringify(vn(e.remoteVideoManager?.isRenderingEvents.video,n.numIsRenderingEvents)),Video_recv_FpsHarmonicAverage:o?.aggregated?.fpsHarmonicAverage,Video_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.video?.toString(),Video_recv_statsOnSubscribed:JSON.stringify(e.statsOnSubscribed.video),Video_SubscriptionEvents:JSON.stringify(wn(e.subscriptionManager?.video.events,"ts",e.startTime)),Video_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.video.counters),Video_send_CaptureFramerateAvg:l?.aggregated?.captureFramerateAvg,Video_send_DurationSeconds:l?.aggregated?.duration,Video_send_FreezeIntervals:l?.extensions?.captureFreezeIntervalsCount,Video_send_MaxCapabilities:JSON.stringify(h),Video_send_MaxCapabilitiesErrors:JSON.stringify(g),Video_send_OvershootDurations:JSON.stringify({fs:l?.aggregated?.totalFsOvershootDuration,fps:l?.aggregated?.totalFpsOvershootDuration,br:l?.aggregated?.totalBrOvershootDuration}),Video_send_OvershootEvents:xn(l?.aggregated?.overshootEvents,n.numOvershootEvents,"timestamp",e.startTime),Video_send_QpAvg:l?.aggregated?.qpAvg,Video_send_bitrateAvg:l?.aggregated?.bitrateAvg,Video_send_bitrateMax:l?.aggregated?.bitrateMax,Video_send_frameRateAvg:l?.aggregated?.frameRateAvg,Video_send_AllocateBWAvg:l?.aggregated?.bweAvg,Video_send_CameraOpenWidth:l?.extensions?.cameraOpenResolution?.width,Video_send_CameraOpenHeight:l?.extensions?.cameraOpenResolution?.height,Video_send_packetsLostRateMax:mn(l?.aggregated?.lossRateMax,6),Video_send_resolutionSwitches:JSON.stringify(l?.aggregated?.resolutionSwitches),Video_send_performanceEvents:xn(e.localVideoPerformanceEvents,n.numPerformanceEvents,"timestamp",e.startTime),Video_send_Simulcast:JSON.stringify(e.simulcast?.video),Video_send_powerEfficientEncoderEvents:xn(l?.extensions?.powerEfficientEncoderEvents,n.numPowerEfficientEncoderEvents,"timestamp",e.startTime),Video_send_powerEfficientEncoderEventOnCount:l?.extensions?.powerEfficientEncoderEventOnCount,Video_send_powerEfficientEncoderEventOffCount:l?.extensions?.powerEfficientEncoderEventOffCount,Sharing_recv_DurationSeconds:c?.aggregated?.duration,Sharing_recv_FreezeHistogram:JSON.stringify(c?.aggregated?.freezeCountHistogram),Sharing_recv_FreezeTimestamps:JSON.stringify(An(c?.aggregated?.freezeTimestampsHistogram,e.startTime,n.numOfHistogramSamples)),Sharing_recv_LongestFreezeDuration:c?.aggregated?.longestFreeze,Sharing_recv_OngoingFreeze:c?.extensions?.isFrozen,Sharing_recv_TotalFreezeDuration:c?.aggregated?.totalFreezeDuration,Sharing_recv_RecvAvgFreezeDuration:c?.aggregated?.avgFreezeDuration,Sharing_recv_NumResolutionSwitches:c?.aggregated?.numResolutionSwitches,Sharing_recv_ResolutionDurations:JSON.stringify(c?.aggregated?.resolutionDurations),Sharing_recv_StreamsMax:e.recvVideoStreamCount.max,Sharing_recv_StreamsMin:e.recvVideoStreamCount.min,Sharing_recv_StreamsMode:e.recvVideoStreamCount.mode,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_bitrateAvg:c?.aggregated?.bitrateAvg,Sharing_recv_bitrateMax:c?.aggregated?.bitrateMax,Sharing_recv_frameRateAvg:c?.aggregated?.avgFrameRate,Sharing_recv_jitterBufferAvgSize:c?.aggregated?.avgJitterBufferSize,Sharing_recv_packetsLostRateMax:mn(c?.aggregated?.lossRateMax,6),Sharing_recv_FpsHarmonicAverage:c?.aggregated?.fpsHarmonicAverage,Sharing_recv_isRenderingEvents:JSON.stringify(vn(e.remoteVideoManager?.isRenderingEvents.sharing,n.numIsRenderingEvents)),Sharing_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.sharing?.toString(),Sharing_recv_statsOnSubscribed:JSON.stringify(e.statsOnSubscribed.sharing),Sharing_SubscriptionEvents:JSON.stringify(wn(e.subscriptionManager?.sharing.events,"ts",e.startTime)),Sharing_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.sharing.counters),Sharing_send_CaptureFramerateAvg:d?.aggregated?.captureFramerateAvg,Sharing_send_DurationSeconds:d?.aggregated?.duration,Sharing_send_MaxCapabilities:JSON.stringify(p),Sharing_send_MaxCapabilitiesErrors:JSON.stringify(m),Sharing_send_OvershootDurations:JSON.stringify({fs:d?.aggregated?.totalFsOvershootDuration,fps:d?.aggregated?.totalFpsOvershootDuration,br:d?.aggregated?.totalBrOvershootDuration}),Sharing_send_resolutionSwitches:d?.aggregated?.resolutionSwitches,Sharing_send_OvershootEvents:xn(d?.aggregated?.overshootEvents,n.numOvershootEvents,"timestamp",e.startTime),Sharing_send_QpAvg:d?.aggregated?.qpAvg,Sharing_send_bitrateAvg:d?.aggregated?.bitrateAvg,Sharing_send_bitrateMax:d?.aggregated?.bitrateMax,Sharing_send_frameRateAvg:d?.aggregated?.frameRateAvg,Sharing_send_AllocateBWAvg:d?.aggregated?.bweAvg,Sharing_send_packetsLostRateMax:mn(d?.aggregated?.lossRateMax,6),Sharing_send_Simulcast:JSON.stringify(e.simulcast?.sharing),Data_ProtocolCounters:JSON.stringify(e.dataChannel?.protocolCounters),Data_Error:e.dataChannel?.error,Data_SessionState:e.dataChannelSessionState?.toString(),Data_CreateChannelError:e.dataChannelCreationError,multipleVideoStreams:JSON.stringify(wn(e.multiViewStats,"startTime",e.startTime)),ReportedReceiveBandwidth:JSON.stringify(e.reportedReceiveBandwidth),ReportedSendBandwidth:JSON.stringify(e.reportedSendBandwidthLayouts),OvcToSubscriptions:JSON.stringify(e.ovcToSubscriptionEvents),EncodedStreamWorker:e.encodedStreamWorker,AudioCodecEvents:JSON.stringify(e.audioCodecEvents),HevcCodecSupport:JSON.stringify(e.codecSupport),MeetingScenario:JSON.stringify(e.negotiation.meetingScenario),IsTownHall:e.negotiation.isTownHall,InitialBWSeed:e.initialBWSeed,SentBWSeed:e.sentBWSeed,videoPerformanceEvent:JSON.stringify(e.videoPerformanceEvent),EarlyMedia_NumStatsPolls:e.earlyMediaNumStatsPolls})}(r,this.configProvider,t.statsErrors)}catch(e){t[VL].addStatsError("DiagnosticsReport:getSessionTelemetry",tt(e)),i.Extensions.WebRTCStats_statsErrors=JSON.stringify(t.statsErrors)}return i.metrics.ReportGenerationTimeMs=mn(_n()-n),i}getTeamsRealtimeTelemetry(e){const t=this.getLatestSession(e);if(t)try{const e=t.webrtcSessions[t.webrtcSessions.length-1],i=this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval;return function(e,t){const i=hx(e,"inactiveTracks"),n={channels:[]};return Sx(e,t,n),i.length&&Sx(i,void 0,n),n}(e.statsReports.slice(e.statsReports.length-i),this.rootRef.deviceManager.rawUsedDevices)}catch(e){throw t[VL].addStatsError("DiagnosticsReport:getRealTimeTelemetry",tt(e)),e}}getMediaSessionStats(e){const t=this.getLatestSession(e);if(t)try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,i=e?.terminationTime??0,n=t.webrtcSessions[t.webrtcSessions.length-1],r=n?.statsReports.length?n.statsReports[n.statsReports.length-1]:void 0,s=r?function(e){return{audio:{send:tx(e),recv:ix(e)},video:{send:nx(e),recv:rx(e)},screenShare:{send:sx(e),recv:ax(e)},data:ox(e),transports:lx(e)}}(r):void 0;return s&&(s.extensions=function(e,t){const i=e.qualityManager&&vn(nn(e.qualityManager.videoMaxCapabilitiesEvents),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),n=e.qualityManager&&vn(nn(e.qualityManager.sharingMaxCapabilitiesEvents),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested);return rn({Video_SubscriptionEvents:JSON.stringify(e.subscriptionManager?.video.events),Sharing_SubscriptionEvents:JSON.stringify(e.subscriptionManager?.sharing.events),Video_send_MaxCapabilities:JSON.stringify(i),Sharing_send_MaxCapabilities:JSON.stringify(n),RelayCandidate:e.relayCandidate,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartVideo,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartSharing,IceServers:e.iceServers})}(n,this.configProvider),s.metrics=function(e,t,i){return rn({DeviceEvents:JSON.stringify(wn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),IceConnectedStateTime:1e4*e.iceConnectedStateTime})}(t,i,this.rootRef)),s}catch(e){throw t[VL].addStatsError("DiagnosticsReport:getMediaSessionStats",tt(e)),e}}getDiagnosticsForE2eTests(e){const t=this.getLatestSession(e);let i={statsErrors:[]};if(t){try{const e=t.webrtcSessions[t.webrtcSessions.length-1],n=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,r=n?.terminationTime??0;i=function(e,t,i,n,r){const s=e.aggregatedModalityStats,a=Cn(s.audio?.recv),o=Cn(s.audio?.send),l=Cn(s.video?.recv),c=Cn(s.video?.send),d=Cn(s.sharing?.recv),u=Cn(s.sharing?.send),h=[],g=[];return e.statsOnSubscribed.video?.forEach((e=>h.push(e))),e.statsOnSubscribed.sharing?.forEach((e=>g.push(e))),rn({multipleVideoStreams:e.multiViewStats,WebRTCStats_ssrc:rn({audio:Cx(s,a,o,r),video:yx("video",s,l,c,r),sharing:yx("sharing",s,d,u,r),negotiationStats:Tx(t)}),CallSwMuted:1e3*t.callSwMuted,DeviceEvents:wn(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),VideoEffects:wn(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),AudioEffects:wn(i.deviceManager.audioEffectsEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),statsErrors:t.statsErrors,WorkerEvents:wn(i.deviceManager.workerEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),transportState:e.transportState})}(e,t,this.rootRef,r,this.configProvider.config.diagnostics.collectionLimits.numSamplesForE2E)}catch(e){const n="DiagnosticsReport:getDiagnosticsForE2eTests",r=tt(e);t[VL].addStatsError(n,r),Sn(i.statsErrors,{origin:n,error:r,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}return i}}getLatestSession(e){return this.rootRef.sessions.filter((t=>t.sessionId===e)).sort(((e,t)=>e.callNumber-t.callNumber)).pop()}},bx=class{constructor(e,t,i){this.configProvider=e,this.deviceManagerDiagnostics=t,this.ufdManagerDiagnostics=i,this.root={creationTime:Date.now(),numTotalSessions:0,deviceManager:this.deviceManagerDiagnostics.getObjectRef(),ufdManager:this.ufdManagerDiagnostics.getObjectRef(),configuration:{stackConfig:this.configProvider.stackConfig,defaultConfig:this.configProvider.defaultConfig,mediaConfig:{},userAgentConfig:{isAudioOutputSelectionSupported:this.configProvider.userAgentConfig.isAudioOutputSelectionSupported,isBrowserRollbackSupported:this.configProvider.userAgentConfig.isBrowserRollbackSupported,hardwareConcurrency:Vp.hardwareConcurrency,unmaskedGlRenderer:Vp.unmaskedGlRenderer,hasMediaApi:Vp.hasMediaApi(),hasCapabilitiesApi:Vp.hasCapabilitiesApi(),hasUnifiedPlanSupport:void 0},consoleOverrides:this.configProvider.consoleOverrides,fullConfig:nn(this.configProvider.config),ecsConfigUpdates:[]},browserInfo:Ot.getBrowserInfo(),sessions:[]},this.diagnosticsReport=new Ex(this.root,this.configProvider),this.configProvider.on("newConfigReceived",((e,t,i)=>{this.root.configuration.ecsConfigUpdates.push({timestamp:Date.now(),etag:t,configIds:i,config:e})})),this.configProvider.on("configUpdated",(()=>{this.root.configuration.consoleOverrides=this.configProvider.consoleOverrides,this.root.configuration.fullConfig=nn(this.configProvider.config)}))}get reportGenerator(){return this.diagnosticsReport}get rootRef(){return this.root}set mediaConfig(e){this.root.configuration.mediaConfig=e}newSession(e,t,i){this.root.configuration.userAgentConfig.hasUnifiedPlanSupport=this.configProvider.mediaConfig.simulcastSessionEnabled;const n=new HL(i,e,this.diagnosticsReport,this.root.deviceManager,this.root.ufdManager,++this.root.numTotalSessions,t);return Sn(this.root.sessions,n.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numSessions),n}},_x=class e{constructor(e,t){this.safe=e,this.unsafe=t,this.safe||(this.safe=this.unsafe)}warn(...e){this.unsafe.warn(...e)}error(...e){this.unsafe.error(...e)}debug(...e){this.unsafe.debug(...e)}info(...e){this.unsafe.info(...e)}createChild(t){return new e(this.safe.createChild(t),this.unsafe.createChild(t))}},Ix=Z,wx=class{constructor(e){this.logger=e,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(e){this.isExtensionAvailable&&(0===this.connectionCount&&1===e?("stopped"===this.loggingState&&await this.discardLogs(),await this.initialStartLogging()):0===e&&await this.stopLogging(),this.connectionCount=e)}async collect(){return this.isExtensionAvailable?this.collectPromise?this.collectPromise:this.collectPromise=new Promise((async e=>{try{this.connectionCount>0&&(this.logger.safe.info(`Stopping logger for gathering, open connections: ${this.connectionCount}`),await this.stopLogging()),await this.storeLogs();const t=await this.gatherFromStorage();this.connectionCount>0&&await this.continueLogging(),e(t.length>0?t.join("\r\n"):"")}catch(t){this.logger.safe.error("Error while collecting logs",t),e(JSON.stringify(t))}this.collectPromise=void 0})):""}async initialStartLogging(){try{await this.startLogging()}catch(e){if(e?.includes("A log is already open"))try{const t=e.match(/State=(\w+)/);await this.cleanState(t?.[1]),await this.startLogging()}catch(e){this.logger.safe.error("Error while starting logging at cleanup phase",e),this.loggingState="unknown"}else this.logger.safe.error("Error while starting logging",e),this.loggingState="unavailable"}}async continueLogging(){try{await this.startLogging()}catch(e){this.logger.safe.error("Error while continuing logging",e),this.loggingState="stopped"}}async startLogging(){await this.sendMessage(this.extensionId,{method:"logging.start"}),this.logger.safe.info("Logging started"),this.loggingState="started"}async cleanState(e){try{if("started"===e)await this.stopLogging(),await this.discardLogs();else{if("stopped"!==e)throw new Error(`Unexpected logging state: ${e}`);await this.discardLogs()}}catch(e){this.logger.safe.error("Error while cleaning state",e)}}async stopLogging(){try{await this.sendMessage(this.extensionId,{method:"logging.stop"}),this.logger.safe.info("Logging stopped"),this.loggingState="stopped"}catch(e){this.logger.safe.error("Error while stopping logging",e)}}async discardLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.discard"}),this.logger.safe.info("Logs discarded"),this.loggingState="closed"}catch(e){this.logger.safe.error("Error while discarding logs",e)}}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(e){this.logger.safe.error("Error while storing logs",e)}}async gatherFromStorage(){const e=[];let t={offset:0};do{t=await this.sendMessage(this.editorExtensionId,{api:"getWebRtcLog",logId:this.logId,offset:t.offset}),e.push(t.data),this.logger.safe.info(`Batch gathered with offset: ${t.offset}, moreData: ${t.moreData}`)}while(t.moreData);return this.logger.safe.info("Finished gathering"),e}sendMessage(e,t){return new Promise(((i,n)=>{const r=chrome.runtime;r.sendMessage(e,t,(e=>{if(!e||e?.error){const i=e?JSON.stringify(e.error):r.lastError;n(`sendMessage ${JSON.stringify(t)} failed with error: ${i}`)}i(e)}))}))}},Ax=(()=>{let e;return{getInstance:function(t,i){return i.config.enableWebRtcInternalsLogs&&Ot.isBrowser("EdgeAnaheim")&&chrome?.runtime?(e||(e=new wx(t)),e):(t.safe.info("WebRTC internal logging is disabled"),{collect:()=>Promise.resolve(""),updateSessionCount:()=>Promise.resolve()})}}})(),Px=class{getId(){return 0}getDeviceId(){return Gi.EMPTY_DEVICE_ID}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return"display"}getType(){return 1}getIcon(e,t){return Promise.resolve(null)}},Rx=class{constructor(e){this.descr=e}getId(){return 0}getDeviceId(){return this.descr.browserId}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return this.descr.label}getType(){return 3}getIcon(e,t){return Promise.resolve(null)}},Mx=class{constructor(e){this.deviceManager=e,this.sharingSource=new Px}onScreensChanged(e){return{dispose:()=>{}}}enumerateScreensAsync(){return Promise.resolve([this.sharingSource])}enumerateWindowsAsync(){return Promise.resolve([])}async enumerateCamerasAsync(){return(await this.deviceManager.enumerateDevicesAsync()).filter((e=>"camera"===e.kind)).map((e=>new Rx(e)))}},Dx=class{constructor(e){this.configProvider=e,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(e){const t="connected"===e?this.activeTmpRecord:this.getTmpRecord();t&&t.events[t.events.length-1]?.type!==e&&(t.events.push({type:e,time:Date.now()-t.startTime}),"networkOnline"===e?this.data.networkRecoveredCount++:"connected"===e&&this.data.disconnectedRecoveredCount++,"reconnect"!==e&&"connected"!==e||(t.endTime=Date.now()-t.startTime,this.activeTmpRecord=null))}registerReconnectAttempt(e){this.activeRecord&&(this.activeAttempt={direction:e,startTime:Date.now()-this.activeRecord.startTime,status:!1},this.data.isReconnecting=!0,rt(this.activeRecord.attempts,this.activeAttempt,this.configProvider.config.diagnostics.collectionLimits.numReconnectRecords))}registerReconnectAttemptStatus(e){"completed"===e&&(this.data.isReconnecting=!1),this.activeAttempt&&this.activeRecord&&(this.activeAttempt.endTime=Date.now()-this.activeRecord.startTime,this.activeAttempt.status="completed"===e)}registerReconnect(e){if(this.data.reconnectCount[e]++,this.data.isReconnecting="attempted"===e,"attempted"===e){if(this.activeRecord)return;this.activeRecord={startTime:Date.now(),attempts:[]},rt(this.data.records,this.activeRecord,this.configProvider.config.diagnostics.collectionLimits.numReconnects)}else if("connected"===e){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(e){this.data.retargetCount[e]++}registerEscalation(e){this.data.escalationCount[e]++}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}},kx=class{constructor(){}process(e){return this.mediaLegId=e||this.mediaLegId||sn().toUpperCase(),this.mediaLegId}},Ox=class{constructor(e,t){this.relayManager=e,this.diagnostics=t}initialize(){}setRelayOverride(){}async queryRelaysAsync(e){const t=await this.relayManager.queryRelaysAsync(e);return t.length>0&&(this.diagnostics.relay=t[0]),t}getStats(){return this.relayManager.getStats?.()??{stats:{unavailable:"1"}}}getAuthTokenStats(){return this.relayManager.getAuthTokenStats()}},Nx=class{constructor(e,t,i){this.stats=e,this.diag=t,i&&t&&(i.reconnect=t.getObject())}registerState(e){this.diag?.registerState(e)}registerReconnectAttempt(e){this.stats.registerReconnectAttempt(e),this.diag?.registerReconnectAttempt(e)}registerReconnectAttemptStatus(e){switch(e){case"completed":this.stats.registerReconnectAttemptCompleted();break;case"rejected":this.stats.registerReconnectAttemptRejected()}this.diag?.registerReconnectAttemptStatus(e)}registerReconnect(e){switch(e){case"attempted":this.stats.registerReconnectAttempted();break;case"connected":this.stats.registerReconnectConnected()}this.diag?.registerReconnect(e)}registerRetarget(e){switch(e){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(e)}registerEscalation(e){switch(e){case"attempted":this.stats.registerEscalationStart();break;case"completed":this.stats.registerEscalationCompleted();break;case"rejected":this.stats.registerEscalationRejected()}this.diag?.registerEscalation(e)}},Lx=class{constructor(e){this.initialCallbacks=e,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((e=>{e.method.apply(null,e.args)})),this.clear()}clear(){this.queue=[]}genCallback(e){return(...t)=>this.queue.push({method:e,args:t})}},xx=class{constructor(e,t){this.relayConfig=e,this.logger=t}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 e=0;this.probeDeferred=new Kt;const t=async()=>{await this.performCheck()&&this.finalize()},i=()=>{t(),e<3e3&&(e+=1e3),this.probeTimer=setTimeout(i,e)};return i(),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 e=this.tryCreatePc();if(!e)return!1;e.createDataChannel("probe");const t=new Kt;function i(i){e.onicecandidate=void 0,e.close(),t.resolve(i)}let n=!1;return e.onicecandidate=e=>{const t=e.candidate;if(!t)return n||this.logger.safe.info("still offline"),void i(n);const r=t.type??rm(t.candidate).type;"srflx"!==r&&"relay"!==r||(this.logger.safe.info(`Back online through ${r} candidate`),n=!0,"srflx"===r&&(this.ipFromRelay=t.address,i(!0)))},await e.setLocalDescription(await e.createOffer()),t.promise}tryCreatePc(){try{return new Mp.window.RTCPeerConnection({iceServers:this.relayConfig})}catch(e){return this.logger.safe.info(`Failed to create PC, errCode=${e.code}`),null}}},Fx=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],s=i.fqdns&&i.fqdns.length>0,a=t.iceUdpAddressType,o=t.iceTcpAddressType,l=t.iceServerTransport;if(!r&&!s)return e;if(l.includes("udp")&&i.udpPort){const e=!s||"fqdn"!==a&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.udpPort}?transport=udp`)}if(l.includes("tcp")&&i.tcpPort){const e=!s||"fqdn"!==o&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.tcpPort}?transport=tcp`)}return l.includes("tls")&&i.tlsPort&&s&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),Ux=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],s=i.fqdns&&i.fqdns.length>0,a=t.iceUdpAddressType,o=t.iceServerTransport;if(!r&&!s)return e;if(o.includes("udp")&&i.udpPort){const e=!s||"fqdn"!==a&&r?r:i.fqdns[0];n.push(`stun:${e}:${i.udpPort}`)}return o.includes("tls")&&i.tlsPort&&s&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),Bx=class{constructor(e,t,i,n,r,s,a,o){this.session=e,this.context=t,this.diagnostics=i,this.sessionOperationQueue=n,this.callback=r,this.sessionCallbacks=s,this.configProvider=a,this.relayManager=o,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 Kt},this.logger=t.getLogger().createChild("ReconnectManagerV2"),this.ufdManager=t.getUfdManager(),this.session.callbacks=s,this.reconnectManagerMessageQueue=new Lx(s),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)}get isOnline(){return!this.isOnlineDeferred}async createRelayProber(){if(!this._relayProber){const e=Date.now(),t=Ux(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config),i=Date.now()-e;this.logger.safe.info(`RelayProber configuration fetched in ${i} ms`),i>5e3&&this.diagnostics.registerState("relayConfigFetched"),this._relayProber=new xx(t,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(e){if(this.wasConnected)this.raiseReconnectEvent("Bad",e);else if(!this.settings.reconnectWithNoRelays&&!this.session.hasRelayCandidates())return void this.onReconnectFailed("no relays",e);if(this.isDisconnected=!0,!this.isReconnecting()&&!this.isWaitingForNetwork)return this.logger.safe.info(`[${e}] reconnect attempt after iceDisconnect error`),this.session.transportStateProvider?.isFailed&&this.diagnostics.registerState("failed"),this.diagnostics.registerReconnect("attempted"),this.reconnectAsync(e)}onTransportDisconnect(e){this.isDisconnected=!0,this.wasConnected&&(this.diagnostics.registerState("disconnected"),this.handleTmpConnectivityLoss(e))}onConnected(e){this.isDisconnected=!1,this.logger.safe.info(`[${e}] set allow UFD`),this.diagnostics.registerState("connected"),this.raiseReconnectEvent("Good",e),this.wasConnected=!0,this._relayProber?.finalize()}onNegotiationCompletedAsync(e){return this.logger.safe.info(`[${e}] handle negotiation completed`),this.setSignalingState(!0),this.isReconnecting()&&(this.diagnostics.registerRetarget("completed"),2===this.escalationType&&this.blockCurrentSession(e)),Promise.resolve()}async onSessionErrorOccurred(e,t){this.logger.safe.info(`[${t}] handle session error`,tt(e)),await this.rejectReconnect(t),this.isReconnectAllowed()?await this.scheduleReconnectRetry(t,!1,!1):this.callback.onSessionErrorOccurred(e,t,this.wasConnected)}onNegotiationRejection(e,t){this.logger.safe.info(`[${t}] handle negotiation rejection`),this.diagnostics.registerRetarget("rejected");const i=1===this.escalationType;return this.rejectReconnect(t).then((()=>{const n=e.type===Gi.RENEGOTIATION_ERROR.glare&&i;(e.type!==Gi.RENEGOTIATION_ERROR.glare||i)&&(this.isRecoverableError(e.type)||n?this.scheduleReconnectRetry(t,n,i):this.onReconnectFailed(tt(e),t))}))}async ensureNetwork(e){const t=this.isOnline;if(!this.isOnline){this.logger.safe.info(`[${e}] waiting for network...`);try{await this.isOnlineDeferred.promise}catch(t){return void this.logger.safe.info(`${e} call disposed while waiting for network`)}this.logger.safe.info(`[${e}] network seems up`)}if(this.isDisconnected){const i=await this.createRelayProber(),n=await i.ensureOnline();this.logger.safe.info(`[${e}] probing complete in ${n} ms`),this.diagnostics.registerState("relaysUp"),t&&n<1e3&&this.logger.safe.info(`[${e}] looks like network failed on remote side, recovery was quick`)}}oldSessionIsOnline(e){return!!this.session?.transportStateProvider?.isConnected&&(this.logger.safe.info(`[${e}] old session recovered`),this.isReconnecting()||this.diagnostics.registerReconnect("connected"),!0)}async waitForNetworkAndTryLightweightRecovery(e){const t=this.oldSessionIsOnline(e);if(t||!this.settings.reconnectWithProbes)return t;this.setReconnectTimer(),this.isWaitingForNetwork=!0;const i=this.getMaxNetworkWaitTime();return this.logger.safe.info(`[${e}] can wait up to ${i} ms`),await Promise.race([this.ensureNetwork(e),Yt(i)]),this.isWaitingForNetwork=!1,this.session&&(this.session.transportStateProvider?.isConnected||this.session.transportStateProvider?.isFailed||(this.logger.safe.info(`[${e}] giving session a moment to recover`),await Yt(this.settings.reconnectWaitTimeAfterProbe)),this.oldSessionIsOnline(e))?(this.resetReconnectTimer(),!0):this.checkIfTimerFailed(e)?(this.logger.safe.info(`[${e}] session reconnect timer reached during network checks`),!0):!!this.isDisposing&&(this.logger.safe.info(`[${e}] session is disposed`),!0)}reconnectAsync(e,t=!1,i=!1,n){return this.logger.safe.info(`[${e}] queueing reconnect, force=${t}, escalation=${i}`),this.diagnostics.registerReconnectAttempt(i?"local escalation":"out"),this.context.getSmallCallTelemetry()?.setEventType("reconnect"),this._isReconnectScheduled=!0,i&&(this.escalationType=1,this.onReconnectCompleted=n),this.sessionOperationQueue.queueOperation((async()=>{if(this._isReconnectScheduled=!1,t||!await this.waitForNetworkAndTryLightweightRecovery(e))return this.isReconnecting()?(this.logger.safe.info(`[${e}] ongoing reconnect is in progress`),void this.sessionOperationQueue.completeCurrentOperation()):(this.diagnostics.registerState("reconnect"),await this.initReconnect(e),await this.reconnectSession.configureModalitiesAsync(this.getConfiguredModalities(),e),void this.sessionOperationQueue.completeCurrentOperation());this.sessionOperationQueue.completeCurrentOperation()}),e)}async acceptReconnectStartAsync(e,t){return this.logger.safe.info(`[${t}] accepting reconnect`),this.diagnostics.registerRetarget("incoming"),e?(this.escalationType=2,this.diagnostics.registerEscalation("attempted")):(!this.isReconnecting()&&this.isDisconnected?this.diagnostics.registerReconnect("attempted"):this.isReconnecting()&&await this.rejectReconnect(t),this.diagnostics.registerState("reconnect"),this.diagnostics.registerReconnectAttempt("in")),this.initReconnect(t)}acceptReconnectFinish(e){const t=this.getConfiguredModalities();return this.reconnectSession.configureModalitiesAsync(t,e).then((()=>t))}isReconnecting(){return!!this.reconnectSession}isReconnectScheduled(){return this._isReconnectScheduled}cleanUp(){this.sessionCallbacks=null,this.reconnectSession=null}async terminateAsync(e){try{await(this.session?.terminate(e,{}))}catch{}try{await this.terminateReconnectSessionAsync(e,!0)}catch{}this.cleanUp()}completeReconnect(e){return this.logger.safe.info(`[${e}] completing reconnect`),2===this.escalationType&&(this.unblockCurrentSession(e),this.diagnostics.registerEscalation("completed")),this.escalationType=0,this.reconnectSession&&(this.context.config.isConference=this.isReconnectConference,this.disposeActiveSession(e),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(e){this.logger.safe.info(`[${e}] rejecting reconnect`),this.setSignalingState(!1),2===this.escalationType&&this.diagnostics.registerEscalation("rejected"),this.escalationType=0,this.reconnectSession&&(await this.terminateReconnectSessionAsync(e,!1),this.diagnostics.registerReconnectAttemptStatus("rejected")),this.session&&(this.reconnectManagerMessageQueue.flush(),this.session.callbacks=this.sessionCallbacks,this.unblockCurrentSession(e))}configureModalitiesAsync(e,t,i){this.lastKnownConfiguredModalities=e;const n=[];return this.session&&n.push(this.session.configureModalitiesAsync(e,t,i)),this.reconnectSession&&n.push(this.reconnectSession.configureModalitiesAsync(e,t,i)),Promise.all(n).then((()=>Promise.resolve()))}canSendDtmf(){return this.getMainSession().canSendDtmf()}muteHold(e,t){this.getMainSession().muteHold(e,t)}muteInputAsync(e){return this.getMainSession().muteInputAsync(e)}unmuteInputAsync(e){return this.getMainSession().unmuteInputAsync(e)}muteOutputAsync(e){return this.getMainSession().muteOutputAsync(e)}unmuteOutputAsync(e){return this.getMainSession().unmuteOutputAsync(e)}async getSpeakerVolume(e){return this.getMainSession().getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.getMainSession().setSpeakerVolume(e,t)}_deviceSelectionChanged(){this.session&&this.session.deviceSelectionChanged(),this.reconnectSession&&this.reconnectSession.deviceSelectionChanged()}disposeActiveSession(e){if(this.session&&this.isReconnecting()){this.logger.safe.info(`[${e}] About to dispose current session...`);const t=this.session;return this.lastKnownConfiguredModalities=this.session.getConfiguredModalities(),t.callbacks=this.reconnectManagerMessageQueue.queueCallbacks,t.move(this.reconnectSession,e),this.session=null,t.terminate(e,{},!1)}return Promise.resolve()}registerRetargetOutgoing(){this.diagnostics.registerRetarget("outgoing")}isSignalingStable(){return this._isSignalingStable}getConfiguredModalities(){return this.getMainSession().getConfiguredModalities()||this.lastKnownConfiguredModalities}checkIfTimerFailed(e){return!(this.isReconnectAllowed()||this.session&&!this.session.transportStateProvider?.isFailed||(this.onReconnectFailed("the time limit was reached",e),0))}async scheduleReconnectRetry(e,t,i){const n=this.getReconnectDelayTime();if(this.logger.safe.info(`[${e}] scheduling reconnect retry attempt in ${n}`),await Yt(n),t||!this.checkIfTimerFailed(e))return this.reconnectAsync(e,i,i,this.onReconnectCompleted)}isRecoverableError(e){return Gi.RENEGOTIATION_ERROR.media===e||Gi.RENEGOTIATION_ERROR.signaling===e}async resetReconnectSession(e){this.logger.safe.info(`[${e}] Resetting reconnect session. Session exists: old: ${!!this.session}, new: ${!!this.reconnectSession}`),this.isReconnectConference=0!==this.escalationType||this.context.config.isConference;const t=0!==this.escalationType||this.context.config.isConference&&this.wasConnected&&!this.isDisconnected,i=this.getMainSession(),n=this.configProvider.getConfigView(this.isReconnectConference,i.getSessionConfig()),r=i.clone(t,n);r.callbacks={...this.sessionCallbacks,onTransportConnected:e=>{2!==this.escalationType&&this.completeReconnect(e),this.onReconnectCompleted?.(),this.raiseReconnectEvent("Good",e),this.sessionCallbacks.onTransportConnected(e)}},this.session&&(this.session.callbacks={...this.reconnectManagerMessageQueue.queueCallbacks,onSessionErrorOccurred:(e,t)=>(e.type!==Gi.MEDIA_ERROR.iceConnectionError&&this.reconnectManagerMessageQueue.queueCallbacks.onSessionErrorOccurred(e,t),Promise.resolve())}),this.reconnectSession&&(this.reconnectSession.move(r,e),this.logger.safe.info(`[${e}] reconnect session still exists during reconnect clone operation`),await this.terminateReconnectSessionAsync(e,!1)),this.logger.safe.info(`[${e}] New session reset.`),this.reconnectSession=r}async initReconnect(e){this.logger.safe.info(`[${e}] initiate reconnect`),this.setReconnectTimer(),await this.resetReconnectSession(e),this.setSignalingState(!1),this.session&&(this.blockCurrentSession(e),await Promise.all([this.reconnectSession.muteInputAsync(e),this.reconnectSession.muteOutputAsync(e)]))}blockCurrentSession(e){this.logger.safe.debug(`[${e}] blocking current session negotiations`),this.negotiationPausePromise=this.session.pauseNegotiations(e)}unblockCurrentSession(e){this.negotiationPausePromise&&(this.logger.safe.debug(`[${e}] unblocking current session negotiations`),this.negotiationPausePromise.resolve(),this.negotiationPausePromise=null)}raiseReconnectEvent(e,t){this.ufdManager.signalEvent("NetworkReconnect",e,"Audio",!0,t)}async terminateReconnectSessionAsync(e,t){if(this.reconnectSession){const i=new Lx(this.sessionCallbacks);this.reconnectSession.callbacks={...i.queueCallbacks,onTerminated:t?this.sessionCallbacks.onTerminated:i.queueCallbacks.onTerminated},await this.reconnectSession.terminate(e,{},!1),i.clear(),this.reconnectSession=null}}setReconnectTimer(){const e=this.wasConnected?this.settings.reconnectTimeLimit:this.settings.initialReconnectTimeLimit;e>0&&!this.reconnectTimer&&(this.reconnectTimerStart=Date.now(),this.reconnectTimer=window.setTimeout((()=>this.resetReconnectTimer()),e))}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 e=this.reconnectTimerStart>0?Date.now()-this.reconnectTimerStart:0;return Math.max(this.settings.reconnectTimeLimit-e,0)}onReconnectFailed(e,t){this.callback.onSessionErrorOccurred({type:Gi.MEDIA_ERROR.iceConnectionError,detail:`Reconnect failed, error - ${tt(e)}`},t,this.wasConnected)}setSignalingState(e){this._isSignalingStable=e}async handleTmpConnectivityLoss(e){this.logger.safe.info(`[${e}] Session went into disconnected state, giving it ${this.settings.losingConnectivityTimeoutMs}ms to recover`),-1!==this.settings.losingConnectivityTimeoutMs&&(await Yt(this.settings.losingConnectivityTimeoutMs),this.isDisconnected&&this.raiseReconnectEvent("Poor",e)),this.isDisconnected&&this.settings.reconnectOnDisconnect&&(this.logger.safe.info(`[${e}] Session is still down, triggering reconnect`),this.onIceDisconnect(e))}},Vx=class{constructor(e,t){this.stats=e,this.diagnostics=t}set mediaLegId(e){this.stats.setMediaLegId(e.process()),this.diagnostics&&(this.diagnostics.mediaLegId=e)}set isMultiParty(e){e&&this.stats.setMultiParty(),this.diagnostics&&(this.diagnostics.isMultiParty=e)}set allowedModalities(e){this.stats.setSendModalities(e),this.diagnostics&&(this.diagnostics.allowedModalities=e)}set sessionError(e){this.stats.setError(e),this.diagnostics&&(this.diagnostics.sessionError=e)}set finalAnswerTime(e){this.stats.setFinalAnswerTimestamp(e),this.diagnostics&&(this.diagnostics.finalAnswerTime=e)}set dtmfResult(e){this.stats.dtmfResult(e),this.diagnostics&&(this.diagnostics.dtmfResult=e)}set swMute(e){this.stats.setSwMute(e),this.diagnostics&&(this.diagnostics.swMute=e)}set speakerMute(e){this.stats.setSpeakerMute(e),this.diagnostics&&(this.diagnostics.speakerMute=e)}set hwSilent(e){this.stats.setHwSilent(e),this.diagnostics&&(this.diagnostics.hwSilent=e)}set isSpeaking(e){this.stats.setSpeakingState(e),this.diagnostics&&(this.diagnostics.isSpeaking=e)}set iceConnectedStateTimestamp(e){this.stats.setIceConnectedStateTimestamp(e),this.diagnostics&&(this.diagnostics.iceConnectedStateTimestamp=e)}set iceInitTime(e){this.stats.setIceInitTimestamp(e),this.diagnostics&&(this.diagnostics.iceInitTime=e)}set ETag(e){this.stats.setETag(e),this.diagnostics&&(this.diagnostics.ETag=e)}set configIds(e){this.stats.setConfigIds(e),this.diagnostics&&(this.diagnostics.configIds=e)}set relay(e){this.stats.setRelay(e),this.diagnostics&&(this.diagnostics.relay=e)}negotiationStart(e){switch(this.diagnostics?.negotiationStart(e),e){case"Offering":this.stats.negotiation.offering.started();break;case"Answering":this.stats.negotiation.answering.started()}}negotiationCompleted(e){this.stats.negotiation.current.completed(e),this.diagnostics?.negotiationCompleted(e)}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(e){this.stats.registerRollbackEvent(e),this.diagnostics?.registerRollbackEvent(e)}registerRawMediaAccess(e,t,i){"send"===t?this.stats.registerSetInputRawMedia(i):this.stats.registerOutputRawMediaAccess(),this.diagnostics?.registerRawMediaAccess(e,t,i)}registerQualityStateChangedEvent(e){this.stats.registerQualityStateChangedEvent(e),this.diagnostics?.registerQualityStateChangedEvent(e)}terminated(e){this.stats.terminated(e),this.diagnostics?.terminated(e)}registerRemoteQualityStateChangedEvent(e,t){this.stats.registerRemoteQualityStateChangedEvent(e,t),this.diagnostics?.registerRemoteQualityStateChangedEvent(e,t)}},Hx=class{constructor(e){this.logger=e,this.operationQueue=null,this.currentOperationDeferred=null,this.operationQueue=new tk(this.logger)}queueOperation(e,t=be()){this.logger.safe.info(`[${t}] queueing operation`);const i=new Kt,n=this.operationQueue.add((()=>(this.currentOperationDeferred=i,e())),t);return this.operationQueue.add(i,t),n}completeCurrentOperation(){this.currentOperationDeferred&&(this.logger.safe.info("completing operation"),this.currentOperationDeferred.resolve())}},$x=class extends Vi{constructor(e,t,i,n,r,s,a,o=i.getLogger().createChild("SessionV2",t)){super(o),this.context=i,this.callback=n,this.statistics=r,this.configProvider=s,this.diagnostics=a,this.logger=o,this.audioStreamStates={[Gi.STREAMING_STATE.inactive]:[Gi.STREAMING_STATE.started,Gi.STREAMING_STATE.active,Gi.STREAMING_STATE.failed],[Gi.STREAMING_STATE.started]:[Gi.STREAMING_STATE.active,Gi.STREAMING_STATE.removed,Gi.STREAMING_STATE.stopped,Gi.STREAMING_STATE.failed],[Gi.STREAMING_STATE.active]:[Gi.STREAMING_STATE.removed,Gi.STREAMING_STATE.stopped,Gi.STREAMING_STATE.failed]},this.mediaLegId=new kx,this.rejectedNegotiations=0,this.negotiationState=null,this.audioStreamState=Gi.STREAMING_STATE.inactive,this.deviceManagerDisposables=[],this.visibilityChangedHandler=()=>{if(this.logger.safe.debug(`document.visibilityState changed: ${document.visibilityState}`),"visible"===document.visibilityState&&this.pcClosedInfo){const e=this.pcClosedInfo;this.pcClosedInfo=null,Date.now()<e.timestamp+this.configProvider.config.reconnectWakeupTimeLimit?(this.logger.safe.info(`[${e.causeId}] start reconnect after wakeup`),this.startReconnect(e.causeId)):(this.logger.safe.info(`[${e.causeId}] terminate a call after wakeup because allowed time limit for reconnect exceeded`),this.endCallOnFailure(e.mediaError,e.causeId))}"hidden"===document.visibilityState&&this.context.getSmallCallTelemetry()?.setEventType("visibilityHidden")},this.ufdManager=i.getUfdManager(),this.ufdManagerDisposable=this.ufdManager.on("onQualityChanged",(e=>this.qualityChanged(e))),this.sessionOperationQueue=new Hx(this.logger),this.mediaLegId=new kx,this.diagnosticsWrapper=new Vx(this.statistics,this.diagnostics),this.statistics.setId(t),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.diagnosticsWrapper.ETag=this.configProvider.ETag,this.diagnosticsWrapper.configIds=this.configProvider.ecsConfigIds,this.diagnosticsWrapper.isMultiParty=!!i.config.isConference,this.recoverableErrors=this.configProvider.config.recoverableMediaErrors.split(","),this.forceReconnectErrors=this.configProvider.config.forceReconnectErrors.split(",");const l=this.getSessionCallbacks();e.callbacks=l,e.relayManagerProvider=this,this.reconnectManager=new Bx(e,i,new Nx(this.statistics,this.diagnostics?new Dx(this.configProvider):void 0,this.diagnostics),this.sessionOperationQueue,this.getReconnectManagerCallbacks(),l,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",((e,t)=>this.deviceListChanged(t)))),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount()),this.diagnostics&&(this.diagnostics.relayManager=this.getRelayManager()),this.ufdManager.applyCurrentState((e=>this.qualityChanged(e))),document.addEventListener("visibilitychange",this.visibilityChangedHandler),this.requestWakeLock()}async requestWakeLock(){if(Vp.isWakeLockSupported()&&this.configProvider.config.useWakeLockApi)try{this.wakeLock=await window.navigator.wakeLock.request("screen")}catch(e){this.logger.safe.info(`Wakelock request failed - ${e.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(e,t){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Offering");try{const i=await this.getCurrentSession().createOfferAsync(e,t);return this.updateSelectedDevices(),i.mediaLegId=this.mediaLegId.process(i.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.reconnectManager.isReconnecting()&&!this.reconnectManager.isSignalingStable()&&(this.reconnectManager.registerRetargetOutgoing(),i.newOffer=!0),i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),e)}registerRemoteQualityStateChangedEvent(e,t){this.diagnosticsWrapper.registerRemoteQualityStateChangedEvent(e,t)}setCallConstraints(e,t){return this.getCurrentSession().setCallConstraints(e,t)}processOfferAsync(e,t){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Answering"),e.mediaLegId=this.mediaLegId.process(e.mediaLegId);try{e.newOffer&&await this.reconnectManager.acceptReconnectStartAsync(e.escalationOccurring,t);const i=await this.getCurrentSession().processOfferAsync(e,t);if(e.newOffer){const e=await this.reconnectManager.acceptReconnectFinish(t);return i.sharing===Gi.MEDIA_STATE.sendReceive&&(i.sharing=e.sharing===Gi.MEDIA_STATE.send?Gi.MEDIA_STATE.send:Gi.MEDIA_STATE.receive),i}return i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),t)}async processAnswerAsync(e,t,i,n){try{return this.configProvider.config.muteDuringRemotePranswer&&(i&&!this.callMuteState&&(this.logger.safe.info(`[${t}] Muting input before processing full answer`),await this.muteInputAsync(t),this.lastMuteFromPranswer=!0),!i&&this.lastMuteFromPranswer&&(this.logger.safe.info(`[${t}] Unmuting input before processing full answer`),await this.unmuteInputAsync(t),this.lastMuteFromPranswer=!1)),await this.getCurrentSession().processAnswerAsync(e,t,i,n)}catch(e){throw this.lastMuteFromPranswer=!1,this.diagnosticsWrapper.sessionError=e,e}}async completeNegotiationAsync(e){this.rejectedNegotiations=0;try{const t=await this.getCurrentSession().completeNegotiationAsync(e);return this.negotiationState=t,this.diagnosticsWrapper.finalAnswerTime=Date.now(),this.diagnosticsWrapper.negotiationCompleted?.(t.activeModalities),await this.reconnectManager.onNegotiationCompletedAsync(e),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}ignoreNotReconnectError(e){return e.detail?.type!==Gi.MEDIA_ERROR.incompatibleOriginator}async rejectNegotiationAsync(e,t){this.logger.safe.info(`[${t}] rejectNegotiationAsync`,e);try{if(this.reconnectManager.isReconnecting()&&this.ignoreNotReconnectError(e))return await this.reconnectManager.onNegotiationRejection(e,t),this.registerNegotiationRejection(this.negotiationState),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState;{const i=await this.getCurrentSession().rejectNegotiationAsync(e,t,this.isRenegotiationAllowed(e.type));return this.sessionOperationQueue.completeCurrentOperation(),this.registerNegotiationRejection(i),i}}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}completeEscalationAsync(e){return this.reconnectManager.completeReconnect(e)}rejectEscalationAsync(e){return this.reconnectManager.rejectReconnect(e)}async terminate(e,t){this.logger.safe.info(`terminate reject reason: ${JSON.stringify(t||"")}`),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(t);const i=()=>this.cleanUp();return this.reconnectManager.terminateAsync(e).then(i,i)}async getStatsAsync(e){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.getMainSession().getStatsAsync(e).then((e=>this.prepareStats(e)))}getLastKnownStats(e=!1){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.prepareStats(this.getMainSession().getLastKnownStats(e),e)}getCallTechnicalInfo(){return this.diagnostics?.realtimeTelemetryReport}async createAnswerAsync(e,t){try{const i=await this.getCurrentSession().createAnswerAsync(e,t);return this.updateSelectedDevices(),i.mediaLegId=this.mediaLegId.process(i.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}configureModalitiesAsync(e,t,i){return qi(e,((t,i)=>{t||delete e[i]})),this.reconnectManager.configureModalitiesAsync(e,t,i)}getAllowedModalities(){return this.deviceManager.getAllowedModalities()}createRemoteRenderer(e){return this.getMainSession().createRemoteRenderer(e)}async sendDtmf(e){try{const t=await this.getMainSession().sendDtmf(e);return this.diagnosticsWrapper.dtmfResult=!0,t}catch(e){throw this.diagnosticsWrapper.dtmfResult=!1,e}}canSendDtmf(){return this.reconnectManager.canSendDtmf()}muteHold(e,t){this.reconnectManager.muteHold(e,t)}muteInputAsync(e){return this.callMuteState=!0,this.diagnosticsWrapper.swMute=!0,this.lastMuteFromPranswer=!1,this.reconnectManager.muteInputAsync(e)}unmuteInputAsync(e){return this.callMuteState=!1,this.diagnosticsWrapper.swMute=!1,this.lastMuteFromPranswer=!1,this.reconnectManager.unmuteInputAsync(e)}muteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!0,this.reconnectManager.muteOutputAsync(e)}unmuteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!1,this.reconnectManager.unmuteOutputAsync(e)}async getSpeakerVolume(e){return this.reconnectManager.getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.reconnectManager.setSpeakerVolume(e,t)}getAcceptedTypes(){return this.reconnectManager.getCurrentSession().getAcceptedTypes()}useNullAudioStreamClient(){this.getCurrentSession().useNullAudioStreamClient()}createAudioElement(e){this.getCurrentSession().createAudioElement(e)}getIncomingRawAudioStream(e){return this.diagnosticsWrapper.registerRawMediaAccess("audio","recv",!0),this.getCurrentSession().getIncomingRawAudioStream(e)}getUnmixedAudioProvider(){return this.getCurrentSession().getUnmixedAudioProvider()}deviceSelectionChanged(){this.updateSelectedDevices(),this.reconnectManager._deviceSelectionChanged()}registerDeviceTelemetryEvent(e){this.getCurrentSession().onDeviceEvent(e),this.statistics.registerDeviceTelemetryEvent(e)}registerVideoEffectsTelemetryEvent(e){this.statistics.registerVideoEffectsTelemetryEvent(e)}registerAudioEffectsTelemetryEvent(e){this.statistics.registerAudioEffectsTelemetryEvent(e)}reconnectAsync(e,t=!1,i){return this.reconnectManager.reconnectAsync(e,!0,t,i)}isReconnecting(){return this.reconnectManager.isReconnecting()}getRelayManager(){return this.relayManager??(this.relayManager=new Ox(this.context.maContext.getRelayManager(),this.diagnosticsWrapper))}getSessionConfig(){return this.reconnectManager.getCurrentSession().getSessionConfig()}getDiagnostics(){return this.diagnostics}async getAudioSenderStats(){return this.getCurrentSession().getAudioSenderStats()}getLocalMediaTrackId(e){return this.reconnectManager.getMainSession().getLocalMediaTrackId(e)}getSubscriptionManager(){return this.getCurrentSession().getSubscriptionManager()}getDisabledModalities(){return this.getCurrentSession().getDisabledModalities()}configureSpatialAudio(e,t){this.getCurrentSession().configureSpatialAudio(e,t)}setParticipantSpatialAudioPositions(e,t){this.getCurrentSession().setParticipantSpatialAudioPositions(e,t)}startMediaDescriptionsUpdateAsync(e,t){return this.getCurrentSession().startMediaDescriptionsUpdateAsync(e,t)}completeMediaDescriptionsUpdateAsync(e){return this.getCurrentSession().completeMediaDescriptionsUpdateAsync(e)}rejectMediaDescriptionsUpdateAsync(e,t){return this.getCurrentSession().rejectMediaDescriptionsUpdateAsync(e,t)}processNotification(e,t){this.getCurrentSession().processNotification(e,t)}getMediaControlPlaneInstance(){return this.getCurrentSession().getMediaControlPlaneInstance()}async cleanUp(){this.callback=null,this.deviceManagerDisposables.forEach((e=>e.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 e=this.deviceManager.getSelectedDevices(),t=e=>e?this.deviceManager.getDeviceNameAsync(e).then((e=>fn(e,this.configProvider.config.devices.piiSafeWords))):Promise.resolve("none");Promise.all([t(e.microphone),t(e.speaker),t(e.camera)]).then((([e,t,i])=>{this.statistics.setUsedDevices({microphone:e,speaker:t,camera:i})}))}getCurrentSession(){return this.reconnectManager.getCurrentSession()}getMainSession(){return this.reconnectManager.getMainSession()}setAudioStreamState(e,t,i){this.isAudioStateValid(e)?this.raiseAudioStateChanged(e,t,i):this.logger.safe.error(`[${t}] audio state transition is invalid: ${this.audioStreamState} -> ${e}`)}isAudioStateValid(e){return this.audioStreamStates[this.audioStreamState].indexOf(e)>=-1}raiseAudioStateChanged(e,t,i){if(this.logger.safe.info(`[${t}] audio state changed to ${e}`),this.callback.onAudioStateChanged){const t={content:"audio",direction:"receive",stream:e};this.callback.onAudioStateChanged(t,i)}}getReconnectManagerCallbacks(){return{onSessionErrorOccurred:(e,t,i)=>{this.isNetworkMediaError(e)&&!i&&this.ufdManager.raisePendingWhitelistingUFD(),this.endCallOnFailure(e,t)}}}isNetworkMediaError(e){return e.type===Gi.MEDIA_ERROR.iceConnectionError||e.type===Gi.MEDIA_ERROR.noNetworkError}isRecoverableMediaError(e){return this.recoverableErrors.includes(e.type)}startReconnect(e=be()){return this.reconnectManager.onIceDisconnect(e)}shouldForceReconnect(e){return this.forceReconnectErrors.includes(e.type)}isUnexpectedPcClose(e){return e.type===Gi.MEDIA_ERROR.unexpectedClose}getSessionCallbacks(){return this.sessionCallbacks||(this.sessionCallbacks={onTerminated:()=>{this.logger.safe.warn("call onTerminated"),this.event("onTerminated").raise(this)},onSessionErrorOccurred:(e,t=be())=>this.isUnexpectedPcClose(e)?this.handlePcClosed(e,t):this.shouldForceReconnect(e)?this.reconnectManager.reconnectAsync(t,!0):this.isRecoverableMediaError(e)?this.reconnectManager.isReconnecting()?this.reconnectManager.onSessionErrorOccurred(e,t):this.startReconnect(t):(this.endCallOnFailure(e,t),Promise.resolve()),onNegotiationRequired:(e,t)=>this.callback.onNegotiationRequired(e,t),onAudioHwSilentChanged:e=>{this.diagnosticsWrapper.hwSilent=e},onAudioStateChanged:(e,t)=>{this.setAudioStreamState(e,t)},onTransportConnected:(e=be())=>{this.logger.safe.info(`[${e}] Transport connectivity established`),this.ufdManager.cancelPendingWhitelistingUFD(),this.reconnectManager.onConnected(e),this.diagnosticsWrapper.registerTransportConnected(),this.diagnosticsWrapper.iceConnectedStateTimestamp=Date.now(),this.callback?.onTransportConnected(e)},onTransportDisconnected:(e=be())=>{this.logger.safe.warn(`[${e}] Transport connectivity lost`),this.reconnectManager.onTransportDisconnect(e),this.diagnosticsWrapper.registerTransportDisconnected(),this.callback?.onTransportDisconnected?.(e)},onTransportFailed:()=>{this.diagnosticsWrapper.registerTransportFailed(),this.callback?.onTransportFailed?.()},onTransportInitialized:()=>{this.diagnosticsWrapper.iceInitTime=Date.now()},onUpdateMediaDescriptionsRequired:(e,t)=>this.callback.onUpdateMediaDescriptionsRequired(e,t),onTeamsRealtimeTelemetryReport:()=>this.callback.onRealtimeTelemetryReport()}),this.sessionCallbacks}registerNegotiationRejection(e){this.rejectedNegotiations++,this.diagnosticsWrapper.negotiationRejected?.(),e.rollback&&this.diagnosticsWrapper.registerRollbackEvent(e.rollback)}isRenegotiationAllowed(e){return this.rejectedNegotiations<this.context.configProvider.config.renegotiationAttempts&&!this.reconnectManager.isReconnectScheduled&&(Gi.RENEGOTIATION_ERROR.signaling===e||Gi.RENEGOTIATION_ERROR.media===e)}prepareStats(e,t=!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 i=this.statistics.generateStatistics(e,this.mediaLegId,t);return this.configProvider.config.diagnostics.features.useNewerStatisticsMetrics&&(i.data.metrics=this.diagnostics?.telemetryReport?.data.metrics),!e.data.Extensions?.StartTime&&this.configProvider.config.diagnostics.features.useFallbackToNewExtensions&&(i.data.Extensions=this.diagnostics?.telemetryReport?.data.Extensions),i}deviceListChanged(e){e&&this.statistics.deviceChangedByPoll(),this.statistics.devicesChanged(),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount())}qualityChanged(e){const t=e.deviceManagerId;!t||this.context.callDeviceManager.hasDevice(t)?(this.context.getSmallCallTelemetry()?.setEventType(e.type),this.callback?.onQualityChanged&&(this.diagnosticsWrapper.registerQualityStateChangedEvent(e),"DeviceSpeakWhileMuted"===e.type&&(this.diagnosticsWrapper.isSpeaking="Good"!==e.value),this.callback.onQualityChanged(e))):this.logger.info(`${t} - is not added to Call, skipping UFD.`)}endCallOnFailure(e,t,i){this.callback&&(this.callback.onSessionErrorOccurred&&this.callback.onSessionErrorOccurred(e,t),this.diagnosticsWrapper.sessionError=e,this.setAudioStreamState(Gi.STREAMING_STATE.failed,t,i))}async handlePcClosed(e,t){const i=this.configProvider.config.reconnectWakeupTimeLimit;return this.logger.safe.info(`[${t}] handle unexpected PC closed event`,`visibilityState=${document.visibilityState}, wakeupLimit=${this.configProvider.config.reconnectWakeupTimeLimit}`),"visible"===document.visibilityState?this.startReconnect(t):i?void(this.pcClosedInfo={timestamp:Date.now(),causeId:t,mediaError:e}):this.endCallOnFailure(e,t,"suspended")}},jx=class{constructor(e){this.creationTime=e,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(e){if(!this.activeRecord)return null;this.activeAttempt={direction:e,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(e){this.activeAttempt&&this.activeRecord&&(this.activeAttempt.status=e,this.activeAttempt.endTime=this.getTimestamp())}getTimestamp(){return Date.now()-this.creationTime-this.activeRecord.startTime}},Gx=window.navigator,qx=class{constructor(e="Good"){this.stopWatches=[],this.currentLevel=e,this.getStopWatch(e).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getElapsed(e){const t=this.stopWatches[e];return t?t.elapsed:0}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new GL,this.stopWatches[e]=t),t}},zx=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})?$/),Wx=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})?$/),Kx=class{constructor(e,t,i){this.configProvider=e,this.callNumber=t,this.sessionDiagnostics=i,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 qx,this.networkSend=new qx,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 GL,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 GL,this.osMute=new GL,this.hwSilent=new GL,this.isSpeaking=new GL,this.swMute=new GL,this.speakerMute=new GL,this.deviceTelemetryEvents=[],this.videoEffectsTelemetryEvents=new $M(this.configProvider.config.effectsTelemetryBufferSize),this.audioEffectsTelemetryEvents=new $M(this.configProvider.config.effectsTelemetryBufferSize),this.devicesCount=null,this.reconnectStats=new jx(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 GL},this.rawInputAudioOverride={attempt:0,timer:new GL},this.connectionEffectiveTypeSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionRttSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionDownlinkSeries=new $M(this.configProvider.config.navConnectionNumSamplesToCollect),this.navigatorConnectionInterval=setInterval((()=>{const e=Gx?.connection;e&&("number"==typeof e.downlink&&this.connectionDownlinkSeries.add(e.downlink),"number"==typeof e.rtt&&this.connectionRttSeries.add(e.rtt),"number"==typeof e.effectiveType&&this.connectionEffectiveTypeSeries.add(e.effectiveType))}),this.configProvider.config.navConnectionPollingInterval),this.durationTimer.start()}terminated(e){this.terminationReason=nn(e),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(e,t){this.deviceList=e.map((e=>({label:fn(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.kind}))),t&&(this.deviceDebugStrings=nn(t))}setPermissionStates(e){this.permissionStates=e}setSwMute(e){e?this.swMute.start():this.swMute.stop(),this.updateCommonMute()}setSpeakerMute(e){e?this.speakerMute.start():this.speakerMute.stop()}setHwSilent(e){e?this.hwSilent.start():this.hwSilent.stop()}setSpeakingState(e){e?this.isSpeaking.start():this.isSpeaking.stop()}setETag(e){this.ETag=e}setConfigIds(e){this.configIds=e}setVideoEffectStats(e){e&&this.videoEffectsTelemetryEvents.add(e)}setAudioEffectStats(e){e&&this.audioEffectsTelemetryEvents.add(e)}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.noIceCandidatesGoodEventCount++:this.noIceCandidatesBadEventCount++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.noRelayIceCandidatesGoodEventCount++:this.noRelayIceCandidatesBadEventCount++;break;case"DeviceCaptureNotFunctioning":"Good"===e.value?this.microphoneInUseGoodEventCount++:this.microphoneInUseBadEventCount++;break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.cameraInUseGoodEventCount++:this.cameraInUseBadEventCount++;break;case"DeviceCaptureMute":"Audio"===e.mediaType&&("Bad"===e.value?this.osMute.start():this.osMute.stop(),this.updateCommonMute());break;case"NetworkRecvQuality":this.networkRecv.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.cameraFreezeEndEventCount++:this.cameraFreezeStartEventCount++}"DeviceSpeakWhileMuted"!==e.type&&this.ufds.push({...e,timestamp:Date.now()-this.creationTime}),this.ufds.length>this.configProvider.config.maxStoredUFDCount&&this.ufds.shift()}registerRemoteQualityStateChangedEvent(e,t){e.forEach((e=>{rt(this.remoteUfds,{...e,participantId:t,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(e){e&&this.rollbackNegotiation.push({type:e.type,attempt:this.rollbackNegotiation.length+1,error:e.error?e.error:""})}registerReconnectAttempted(){this.reconnectAttemptedCount++,this.reconnectStats.onReconnectStart()}registerReconnectConnected(){this.reconnectConnectedCount++,this.reconnectStats.onReconnectConnected()}registerDeviceTelemetryEvent(e){e.timestamp=e.timestamp-this.creationTime,this.deviceTelemetryEvents.push(e)}registerVideoEffectsTelemetryEvent(e){e&&(e.timestamp=e.timestamp-this.creationTime,this.videoEffectsTelemetryEvents.add(e))}registerAudioEffectsTelemetryEvent(e){if(e){e.timestamp=e.timestamp-this.creationTime;const t=this.audioEffectsTelemetryEvents.items.pop();t&&this.audioEffectsChanged(t,e)&&this.audioEffectsTelemetryEvents.add(t),this.audioEffectsTelemetryEvents.add(e)}}audioEffectsChanged(e,t){return e.payload.fallback!==t.payload.fallback||void 0!==t.payload.userNoiseSuppressionMethod&&e.payload.userNoiseSuppressionMethod!==t.payload.userNoiseSuppressionMethod||void 0!==t.payload.userAudioEffect&&e.payload.userAudioEffect!==t.payload.userAudioEffect}registerReconnectAttempt(e){this.reconnectStats.onReconnectAttempt(e)}registerReconnectAttemptCompleted(){this.reconnectStats.onReconnectCompleted()}registerReconnectAttemptRejected(){this.reconnectStats.onReconnectRejected()}setMediaLegId(e){this.mediaLegId=e}setId(e){this.sessionId=e}setError(e){e.type===Gi.MEDIA_ERROR.incompatibleOffer&&(this.incompatibleOffer=!0),this.mediaError.type=e.type||Gi.MEDIA_ERROR.internalError,this.mediaError.detail=e.detail||e.toString()}setRelay(e){this.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}setRelayManagerTimers(e){this.relayManagerTimers=e}setSendModalities(e){this.allowedAudioSend=e.audio.some((e=>Wp(e))),this.allowedVideoSend=e.video.some((e=>Wp(e))),this.allowedScreensharingSend=e.sharing.some((e=>Wp(e)))}setIceInitTimestamp(e){this.iceInitTime||(this.iceInitTime=e)}setFinalAnswerTimestamp(e){this.finalAnswerTime||(this.finalAnswerTime=e)}setIceConnectedStateTimestamp(e){this.iceConnectedStateTime||(this.iceConnectedStateTime=e)}dtmfResult(e){e?++this.dtmfSuccess:++this.dtmfFailure}setUsedDevices(e){this.usedDevices&&JSON.stringify(e)!==JSON.stringify(this.usedDevices)&&this.deviceSelectionChangeCount++,this.usedDevices=e}setDevicesCount(e){this.devicesCount=e}setMediaQosEnabled(e){this.mediaQosEnabled=e}setPortRangeConfigured(e){this.portRangeConfigured=e}devicesChanged(){this.devicesChangeCount++}deviceChangedByPoll(){this.devicesPollChangeCount++}registerOutputRawMediaAccess(){this.rawOutputAudioAccess.attempt++,this.rawOutputAudioAccess.timer.start()}registerSetInputRawMedia(e){this.rawInputAudioOverride.attempt++,e?this.rawInputAudioOverride.timer.start():this.rawInputAudioOverride.timer.stop()}getReport(){const e=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:e.microphone,UsedSpeaker:e.speaker,UsedCamera:e.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(wn(vn(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),remoteUfdsCount:this.sessionDiagnostics?.getObjectRef().remoteUfdsCount,MediaQosEnabled:this.mediaQosEnabled,PortRangeConfigured:this.portRangeConfigured,RollbackNegotiation:JSON.stringify(this.rollbackNegotiation),hardwareConcurrency:Vp.hardwareConcurrency,GPUName:Vp.unmaskedGlRenderer,Connection_Downlink:Pn(this.connectionDownlinkSeries.items,(e=>e)),Connection_EffectiveType:this.connectionEffectiveTypeSeries.items.filter((e=>e)).join(","),Connection_Rtt:Pn(this.connectionRttSeries.items,(e=>e)),Connection_SaveData:Gx?.connection?.saveData,MediaByPassEnabled:!!this.configProvider.mediaConfig.mediaBypassEnabled,CallConstraints:JSON.stringify(this.configProvider.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(dx(this.sessionDiagnostics?.getObjectRef().dominantSpeaker,this.terminationTime))}}generateStatistics(e,t,i=!1){if(this.setMediaLegId(t.process()),"WebRtcMediaStats"!==e.type)throw new Error(`Unknown stats type - ${e.type}`);if(i){const e=this.deviceTelemetryEvents.length;this.deviceTelemetryEvents.splice(0,e-1),this.deviceDebugStrings=Pk,this.audioEffectsTelemetryEvents.clear()}e.data.metrics=this.getReport();const n=this.sessionDiagnostics?.getObjectRef().statsErrors;if(n?.length)if(e.data.Extensions?.WebRTCStats?.statsErrors){const t=JSON.parse(e.data.Extensions.WebRTCStats.statsErrors);t.push(...n),e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(t)}else e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(n);const r={};return zi(e.data,((e,t,i)=>{let n=0;zx.test(e)?(n=13,r[t]="IPv4"):Wx.test(e)&&(n=4,r[t]="IPv6"),i[t]={type:n,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(r),__VALUE__:!0},e}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:e=>{this.initialNegotiationCompleted=!0,this.activeModalities=e,this.resetError()},rejected:()=>{++this.rejectedNegotiationCount}}}getDurationRatio(e){const t=this.getCurrentDuration();return e/(0!==t?t:1)}getCurrentDuration(){return this.durationTimer.elapsed}getHpTimeFromMillis(e){return 1e4*e}},Jx=class{constructor(e,t,i,n){this.onActiveSpeakersChanged=e,this.onDominantSpeakersChanged=t,this.logger=i,this.diagnostics=n}setStrategy(e){this.disposeStrategy(),this.dshStrategy=e,this.dshStrategy?.setOnDominantSpeakerChanged(this.onDominantSpeakerHistoryChanged.bind(this)),this.diagnostics?.setCurrentActiveStrategy("client")}onContributingSourcesChanged(e){this.onActiveSpeakersChanged(e),this.diagnostics?.contributingSourcesChanged(),this.dshStrategy?.setSources(e)}onDominantSpeakerHistoryChanged(e,t){this.onDominantSpeakersChanged(e),this.diagnostics?.recordHistoryEvent(e,t),"client"!==t&&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}},Yx=class{constructor(e){this.listener=e,this.streams=[]}add(e){this.streams.some((t=>t.getId()===e.getId()))||(this.streams.push(e),this.listener.streamAdded(e))}remove(e){let t;Qi(this.streams,(i=>i.getId()===e&&(t=i,!0)))&&this.listener.streamRemoved(t)}getStreams(){return this.streams}clear(){this.streams.forEach((e=>e.dispose())),this.streams=[]}},Qx=p(ye()),Zx=class{constructor(e,t,i){this.logger=e,this.qualityManager=t,this.configProvider=i}getControlItem(){return this.controlItem}setControlItem(e){this.controlItem=e}dispose(){this.controlItem=null}setVideoControlMessage(e){this.controlItem=this.messageToControlItem(e),this.logger.safe.info(`BW limit requested to ${this.controlItem.bandwidth}`)}modifyDescriptor(e){if(!this.controlItem)return e;const t=Qx.parse(e.sdp);if(!t.media[1])return this.logger.unsafe.warn("video modality is disabled, skipping sdp modification, ",e),e;const i=this.getCurrentResolutionBitrate();this.logger.safe.info(`Select the BW limit as min of requested ${this.controlItem.bandwidth} and Current Resolution Max BR ${i}`);const n=this.getSessionBitrate(t),r=Math.min(i,this.controlItem.bandwidth,n);if(t.media[1].bandwidth)t.media[1].bandwidth[0].limit=r;else{const e={limit:r,type:"AS"};t.media[1].bandwidth=[e]}return e.sdp=Qx.write(t),e}messageToControlItem(e){const t=new SO(e.controlVideoStreaming.controlInfo[0].fmtParams),i="max-br";if(!t.contains(i))return null;const n=Math.round(1.2*+t.get(i));return{sourceId:e.controlVideoStreaming.controlInfo[0].sourceId,streamMsid:e.controlVideoStreaming.controlInfo[0].streamMsid,bandwidth:n}}getCurrentResolutionBitrate(){const e=this.qualityManager.getCurrentResolution(),t=Hn.Send.getResolutionByFs(e);return e&&t?Math.floor(Hn.Send.getBitrateForResolution(t.width,t.height).maxBitrate/1e3):Number.MAX_VALUE}getSessionBitrate(e){let t=Number.MAX_SAFE_INTEGER;return this.configProvider.mediaConfig.maxBandwidthInKbps&&(t=this.configProvider.mediaConfig.maxBandwidthInKbps),e.bandwidth&&(t=Math.min(+e.bandwidth[0].limit,t)),t-(this.configProvider.config.audioBandwidthInKbps||0)}},Xx=class{constructor(e,t,i){this.pc=e,this.configProvider=t,this.logger=i.createChild("MediaRollbackModifier")}modifyDescriptor(e){const t=Qx.parse(e.sdp);return Qx.parse(this.pc.localDescription.sdp).media.forEach(((e,i)=>{const n=t.media[i];(NO(e)&&!e.bundleOnly||!n||NO(n))&&(this.logger.safe.info(`Adding disabled media ${e.type}, position ${i}`),t.media[i]=SL(e.type,void 0,e.protocol,void 0))})),new QN(this.configProvider).modify(t),e.sdp=Qx.write(t),e}},eF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send){this.diagnostics.handlePresentationAudioInputLevel();for(const i of e.send)try{t.add(i.outboundRTP.id);let e=this.sendExtenders.get(i.outboundRTP.id)??new nF(this.diagnostics,this.configProvider);i.outboundRTP.bytesSent<e.lastBytes&&(e=new nF(this.diagnostics,this.configProvider)),this.sendExtenders.set(i.outboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:send",tt(e))}}if(Mn(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new tF(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new tF(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:recv",tt(e))}Mn(this.recvExtenders,t)}},tF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.totalSamplesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.concealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.silentConcealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.concealedRatioAverager=new qM,this.stretchedRatioAverager=new qM,this.codecSwitchesTracker=new QM,this.packetDurationTracker=new QM,this.jitterAverager=new qM,this.jitterBufferDelayAverager=new qM,this.lastBytes=0}processSample(e){let t,i,n,r,s;const a=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDiff.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp),this.totalSamplesReceivedDiff.captureSample(e.inboundRTP.totalSamplesReceived,e.inboundRTP.timestamp),this.concealedSamplesDiff.captureSample(e.inboundRTP.concealedSamples,e.inboundRTP.timestamp),this.silentConcealedSamplesDiff.captureSample(e.inboundRTP.silentConcealedSamples,e.inboundRTP.timestamp);const o=this.bytesReceivedDiff.delta&&8*this.bytesReceivedDiff.delta;this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const l=e.inboundRTP.jitterBufferDelay&&e.inboundRTP.jitterBufferEmittedCount&&mn(e.inboundRTP.jitterBufferDelay/e.inboundRTP.jitterBufferEmittedCount*1e3,0);if(this.jitterAverager.captureSample(1e3*e.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(e.inboundRTP.jitterBufferDelay),t=this.totalSamplesReceivedDiff.delta&&this.concealedSamplesDiff.delta&&this.silentConcealedSamplesDiff.delta&&mn((this.concealedSamplesDiff.delta-this.silentConcealedSamplesDiff.delta)/this.totalSamplesReceivedDiff.delta),e.customHealerStats){e.customHealerStats.numSamplesPerFrame&&(r=e.customHealerStats.decodedSamples/e.customHealerStats.numSamplesPerFrame,s=e.customHealerStats.cngSamples/e.customHealerStats.numSamplesPerFrame),t=e.customHealerStats.healedSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),n=e.customHealerStats.concealSamples&&e.customHealerStats.concealSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),i=e.customHealerStats.stretchSamples&&e.customHealerStats.stretchSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples);const a=e.customHealerStats.packetDurationInMs&&e.customHealerStats.packetDurationInMs>100?100:e.customHealerStats.packetDurationInMs;this.concealedRatioAverager.captureSample(n),this.stretchedRatioAverager.captureSample(i),this.codecSwitchesTracker.captureSample(`${e.customHealerStats.pullAdspPayloadType}`),this.packetDurationTracker.captureSample(`${a}`)}e.extensions={lossRate:a,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,healedRatio:t,jitterBufferMs:l,bitrate:o||0,customHealerStats:e.customHealerStats&&{concealedDataRatio:n,concealedDataRatioMax:this.concealedRatioAverager.maxSample,stretchedDataRatio:i,stretchedDataRatioMax:this.stretchedRatioAverager.maxSample,numberOfDecodedFrames:r,usageMetricsCodecId:this.codecSwitchesTracker.sortedDurations,percentageOfPtime:this.packetDurationTracker.durationRatios,pushPacketProcessingTimes:e.customHealerStats.pushProcessingTimes,pullPacketProcessingTimes:e.customHealerStats.pullProcessingTimes,pullProcessingTimePerStreamNumber:e.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:e.customHealerStats.pullTimings,cnpPushCount:e.customHealerStats.cnpPushCount,cnpPullCount:e.customHealerStats.cnpPullCount,numberOfCNFrames:s,redPacketsCount:e.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:e.customHealerStats.pullNumOfStreamsCounter},jitterAvg:mn(this.jitterAverager.avg),jitterBufferDelayMs:mn(this.jitterBufferDelayAverager.avg)},this.duration++}},iF=class{constructor(){this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.jitterBufferAverager=new qM,this.jitterAverager=new qM,this.jitterBufferDelayAverager=new qM,this.healedRatioAverager=new qM}processSample(e,t,i){const n=e[0],r={inboundRTP:n.inboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.healedRatioAverager.captureSample(n.extensions.healedRatio),this.jitterBufferAverager.captureSample(n.extensions.jitterBufferMs),this.jitterAverager.captureSample(1e3*n.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(n.inboundRTP.jitterBufferDelay);const e=n.inboundRTP.packetsReceived+n.inboundRTP.packetsLost;r.aggregated={lossRateMax:this.lossRateAverager.maxSample,lossRateAvg:this.lossRateAverager.avg,networkAvgLossRate:e>0?n.inboundRTP.packetsLost/e:0,packetsLostAvg:this.duration>0?n.inboundRTP.packetsLost/this.duration:0,duration:this.duration,bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(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:n.extensions.customHealerStats&&{concealedDataRatio:n.extensions.customHealerStats.concealedDataRatio,concealedDataRatioMax:n.extensions.customHealerStats.concealedDataRatioMax,stretchedDataRatio:n.extensions.customHealerStats.stretchedDataRatio,stretchedDataRatioMax:n.extensions.customHealerStats.stretchedDataRatioMax,numberOfDecodedFrames:n.extensions.customHealerStats.numberOfDecodedFrames,usageMetricsCodecId:n.extensions.customHealerStats.usageMetricsCodecId,percentageOfPtime:n.extensions.customHealerStats.percentageOfPtime,pushPacketProcessingTimes:n.extensions.customHealerStats.pushPacketProcessingTimes,pullPacketProcessingTimes:n.extensions.customHealerStats.pullPacketProcessingTimes,pullProcessingTimePerStreamNumber:n.extensions.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:n.extensions.customHealerStats.pullTimings,cnpPushCount:n.extensions.customHealerStats.cnpPushCount,cnpPullCount:n.extensions.customHealerStats.cnpPullCount,numberOfCNFrames:n.extensions.customHealerStats.numberOfCNFrames,redPacketsCount:n.extensions.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:n.extensions.customHealerStats.pullNumOfStreamsCounter}},this.duration++}Sn(t,r,i)}},nF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.bytesSendDiff=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.rttAverager=new qM,this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost)??0;this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDiff.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDiff.delta;this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,bitrate:i?8*i:0,rttAvg:mn(this.rttAverager.avg),callIsMuted:this.diagnostics.callIsMuted,rawInputVolume:this.diagnostics.audioLevel},this.duration++}},rF=class{constructor(e){this.diagnostics=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.rttAverager=new qM}processSample(e,t,i){const n=e[0],r={outboundRTP:n.outboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),r.aggregated={duration:this.duration,lossRateMax:this.lossRateAverager.maxSample,bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),rttAvg:mn(this.rttAverager.avg),rttMax:mn(this.rttAverager.maxSample),rawInputVolume:this.diagnostics.audioLevel,audioLevel:n.track?.audioLevel??n.mediaSource?.audioLevel},this.duration++),Sn(t,r,i)}},sF=Z,aF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send&&(0,sF.flatMap)(e.send,(e=>[e,...e.altLayouts??[]])).forEach((e=>{try{t.add(e.outboundRTP.id);let i=this.sendExtenders.get(e.outboundRTP.id)??new cF(this.diagnostics,this.configProvider);e.outboundRTP.bytesSent<i.lastBytes&&(i=new cF(this.diagnostics,this.configProvider)),this.sendExtenders.set(e.outboundRTP.id,i),i.processSample(e)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:send",tt(e))}})),Mn(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new oF(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new oF(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:recv",tt(e))}Mn(this.recvExtenders,t)}},oF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.framesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.framesDecodedDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.trackFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.decodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new KM(2):new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.prevTimeToFirstFrame=-1,this.hasPrevFramerate=!1,this.lastBytes=0,this.macroblockStatsTracker=new lD}processSample(e){const t=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.framesReceivedDelta.captureSample(e.inboundRTP.framesReceived,e.inboundRTP.timestamp),this.framesDecodedDelta.captureSample(e.inboundRTP.framesDecoded,e.inboundRTP.timestamp),this.trackFramesDelta.captureSample(e.inboundRTP.framesReceived??e.track?.framesReceived,e.inboundRTP.timestamp),this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const i=this.framesReceivedDelta.delta,n=this.framesDecodedDelta.delta;this.harmonicDecodedFps.captureSample(n),this.decodeTimeDelta.captureSample(e.inboundRTP.totalDecodeTime,e.inboundRTP.timestamp);const r=this.decodeTimeDelta.delta&&n&&mn(this.decodeTimeDelta.delta/n*1e3,2),s=n>0&&i>0,a=e.renderer?.timeToFirstFrame??(s?0:-1);this.freezeHistogram.active=-1!==a&&-1!==this.prevTimeToFirstFrame&&!s,"sharing"===e.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.prevTimeToFirstFrame=a,this.hasPrevFramerate=s,this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDelta.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp);const o=this.bytesReceivedDelta.delta,l=e.inboundRTP.jitterBufferEmittedCount&&mn((e.inboundRTP.jitterBufferDelay??0)/e.inboundRTP.jitterBufferEmittedCount*1e3),c=oD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,i||0),d=oD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,n||0);this.macroblockStatsTracker.captureSample(c,d),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,frameRateReceived:i,frameRateDecoded:n,trackRecvFps:this.trackFramesDelta.delta,decodeTime:r||0,jitterBufferMs:l,bitrate:o?8*o:0,isFrozen:this.freezeHistogram.active,macroblockRateReceived:c,macroblockRateDecoded:d,macroblockRateStats:this.macroblockStatsTracker.getReport(),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,powerEfficient:void 0!==e.inboundRTP.powerEfficientDecoder?e.inboundRTP.powerEfficientDecoder:rD(e.inboundRTP.decoderImplementation),totalFreezeFraction:this.duration?this.freezeHistogram.totalDuration/this.duration:0,fpsHarmonicAverage:mn(this.harmonicDecodedFps.harmonicMean)},this.duration++}},lF=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.jitterAverager=new qM,this.frameRateAverager=new qM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.resolutionDurations=new QM,this.codecCalculator=new cD}processSample(e,t,i){const n=e.sort(((e,t)=>t.inboundRTP.frameHeight*t.inboundRTP.frameWidth-e.inboundRTP.frameHeight*e.inboundRTP.frameWidth))[0],r={inboundRTP:n.inboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec,this.configProvider.config.isAv1Allowed&&"sharing"===n.mediaEntity?.modality&&this.codecCalculator.captureSample(n.codec.mimeType,n.renderer?.msi)),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions&&(this.harmonicDecodedFps.captureSample(n.extensions.frameRateDecoded),this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.jitterAverager.captureSample(1e3*(n.inboundRTP.jitter??0)),this.frameRateAverager.captureSample(n.extensions.frameRateReceived??n.extensions.frameRateDecoded),this.freezeHistogram.active=n.extensions.isFrozen,n.inboundRTP.frameWidth&&n.inboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.inboundRTP.frameWidth}x${n.inboundRTP.frameHeight}`),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,avgFrameRate:mn(this.frameRateAverager.avg),fpsHarmonicAverage:mn(this.harmonicDecodedFps.harmonicMean),avgJitterBufferSize:mn(this.jitterAverager.avg),bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),bitrateMinNonZero:mn(this.bitrateAverager.minNonZeroSample,0),ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,numFreezes:this.freezeHistogram.numEvents,avgFreezeDuration:mn(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:n.extensions.macroblockRateStats,codecReport:this.codecCalculator?.report},this.duration++),rt(t,r,i)}},cF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new iD(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.lossRateAverager=new qM,this.freezeHistogram=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.hasPrevFramerate=!1,this.captureFreezeIntervalsCount=0,this.bytesSendDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.encodedFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sentFramesDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.harmonicEncodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.encodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new KM(2):new WM,this.qpDelta=this.useLastSampleDeltaPerSecondConverter?new KM(3):new WM,this.fsOvershoot=new tD("fs"),this.fpsOvershoot=new tD("fps",1),this.brOvershoot=new tD("br"),this.plisDelta=new WM,this.pliRate=new sD(60),this.resolutionSwitcherTracker=new aD(this.configProvider.config.diagnostics.collectionLimits.numResolutionSwitches),this.bitrateAverager=new qM,this.rttAverager=new qM,this.powerEfficientEncoderChangeTracker=new dD(this.configProvider.config.diagnostics.collectionLimits.numPowerEfficientEncoderEvents),this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost);this.lossRateAverager.captureSample(t),this.plisDelta.captureSample(e.outboundRTP.pliCount),this.pliRate.captureSample(this.plisDelta.delta),this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDelta.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDelta.delta,n=i?8*i:void 0;this.bitrateAverager.captureSample(n),this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),this.encodedFramesDelta.captureSample(e.outboundRTP.framesEncoded,e.outboundRTP.timestamp);const r=this.encodedFramesDelta.delta;this.sentFramesDelta.captureSample(e.outboundRTP.framesSent,e.outboundRTP.timestamp);const s=this.sentFramesDelta.delta||0;this.harmonicEncodedFps.captureSample(r);const a=e.mediaSource?.framesPerSecond;0===a&&void 0!==this.lastCaptureFramerate&&this.lastCaptureFramerate>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFramerate=a;const o=r>0&&s>0;this.freezeHistogram.active=!o,"sharing"===e.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.hasPrevFramerate=o,this.encodeTimeDelta.captureSample(e.outboundRTP.totalEncodeTime,e.outboundRTP.timestamp);const l=this.encodeTimeDelta.delta&&r&&mn(this.encodeTimeDelta.delta/r*1e3,2);this.qpDelta.captureSample(e.outboundRTP.qpSum,e.outboundRTP.timestamp);const c=this.qpDelta.delta&&r&&mn(this.qpDelta.delta/r,2);e.outboundRTP.frameWidth&&e.outboundRTP.frameHeight&&this.resolutionSwitcherTracker.captureSample(e.outboundRTP.frameWidth,e.outboundRTP.frameHeight);const d=this.diagnostics.deviceManager?.latestCameraOpenResolution,u=e.appliedCapabilities??e.requestedCapabilities;u&&(void 0!==e.outboundRTP.frameHeight&&void 0!==e.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(e.outboundRTP.frameHeight/16*(e.outboundRTP.frameWidth/16),u.maxFs),this.fpsOvershoot.captureSample(s,u.maxFps),u.maxBr&&this.brOvershoot.captureSample(n,u.maxBr));const h=[...this.fsOvershoot.events,...this.brOvershoot.events,...this.fpsOvershoot.events];if(h.sort(((e,t)=>e.timestamp-t.timestamp)),e.outboundRTP.frameHeight&&(e.outboundRTP.powerEfficientEncoder||e.outboundRTP.encoderImplementation)){const t=void 0!==e.outboundRTP.powerEfficientEncoder?e.outboundRTP.powerEfficientEncoder:rD(e.outboundRTP.encoderImplementation);this.powerEfficientEncoderChangeTracker.captureSample(t,e.outboundRTP.frameHeight)}e.extensions={cameraOpenResolution:d,lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,pliRate:this.pliRate.getRate(),frameRateEncoded:this.encodedFramesDelta.delta,frameRateSent:s,bitrate:n||0,encodeTime:l||0,qp:c||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:h,powerEfficient:this.powerEfficientEncoderChangeTracker.curPowerEfficientEncoderState,powerEfficientEncoderEvents:this.powerEfficientEncoderChangeTracker.events,powerEfficientEncoderEventOnCount:this.powerEfficientEncoderChangeTracker.eventOnCount,powerEfficientEncoderEventOffCount:this.powerEfficientEncoderChangeTracker.eventOffCount,bitrateAvg:mn(this.bitrateAverager.avg,0),rttAvg:mn(this.rttAverager.avg)},this.duration++}},dF=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new qM,this.bitrateAverager=new qM,this.sendBWEAverager=new qM,this.rttAverager=new qM,this.framerateAverager=new qM,this.captureFpsAverager=new qM,this.captureFreezeIntervalsCount=0,this.lastCaptureFps=void 0,this.resolutionDurations=new QM,this.fsOvershoot=new tD("fs"),this.fpsOvershoot=new tD("fps",1),this.brOvershoot=new tD("br"),this.harmonicEncodedFps=new ZM(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax)}processSample(e,t,i){e.length>1&&e.sort(((e,t)=>{const i=e.appliedCapabilities??e.requestedCapabilities,n=t.appliedCapabilities??t.requestedCapabilities;return i?.maxMbps&&n?.maxMbps?n.maxMbps-i.maxMbps:0}));const n=e[0],r={outboundRTP:n.outboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.sendBWEAverager.captureSample(n.transport?.selectedCandidatePair?.availableOutgoingBitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),this.framerateAverager.captureSample(n.extensions.frameRateSent);const e=n.mediaSource?.framesPerSecond;this.captureFpsAverager.captureSample(e),0===e&&void 0!==this.lastCaptureFps&&this.lastCaptureFps>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFps=e,n.outboundRTP.frameWidth&&n.outboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.outboundRTP.frameWidth}x${n.outboundRTP.frameHeight}`);const t=n.appliedCapabilities??n.requestedCapabilities;t&&(void 0!==n.outboundRTP.frameHeight&&void 0!==n.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(n.outboundRTP.frameHeight/16*(n.outboundRTP.frameWidth/16),t.maxFs),this.fpsOvershoot.captureSample(n.extensions.frameRateSent,t.maxFps),t.maxBr&&this.brOvershoot.captureSample(n.extensions?.bitrate,t.maxBr)),this.harmonicEncodedFps.captureSample(n.extensions.frameRateEncoded);const i=[...this.fsOvershoot.events,...this.fpsOvershoot.events,...this.brOvershoot.events];i.sort(((e,t)=>e.timestamp-t.timestamp)),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,frameRateAvg:mn(this.framerateAverager.avg),captureFramerateAvg:mn(this.captureFpsAverager.avg),fpsHarmonicAverage:mn(this.harmonicEncodedFps.harmonicMean),qpAvg:mn(n.outboundRTP.qpSum/n.outboundRTP.framesSent),rttAvg:mn(this.rttAverager.avg),bitrateAvg:mn(this.bitrateAverager.avg,0),bitrateMax:mn(this.bitrateAverager.maxSample,0),bitrateMinNonZero:mn(this.bitrateAverager.minNonZeroSample,0),bweAvg:mn(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:i},this.duration++}rt(t,r,i)}},uF=class{constructor(e){this.configProvider=e,this.samplesCountPerSubscription=0,this.data=new $M(this.configProvider.config.diagnostics.collectionLimits.numVideoSubscriptionStats)}prepareCollectingStatsOnSubscribed(e){this.samplesCountPerSubscription=0,this.data.add({timestamp:Date.now(),framesDecoded:[],bytesReceived:[],height:[],msi:e})}captureStatsOnSubscribed(e,t,i){if(this.samplesCountPerSubscription>=this.configProvider.config.diagnostics.collectionLimits.numVideoStatsAfterSubscription)return;const n=Cn(this.data.items);n&&(e&&n.framesDecoded.push(e),t&&n.bytesReceived.push(t),i&&n.height.push(i)),this.samplesCountPerSubscription++}get videoStatsOnSubscribed(){return this.data.items}},hF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){const t=new Set;for(const i in e)try{t.add(i);const n=e[i],r=this.extenders.get(n.id)??new gF(this.configProvider,this.diagnostics);this.extenders.set(n.id,r),r.processSample(n)}catch(e){this.diagnostics.addStatsError("TransportStatsProcessor",tt(e))}Mn(this.extenders,t)}},gF=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.bwJumpsHistogramCollector=new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.sendBWEAverager=new qM,this.recvBWEAverager=new qM,this.sendBW=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvBW=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sendBWAverager=new qM,this.recvBWAverager=new qM}processSample(e){this.sendBWEAverager.captureSample(e.selectedCandidatePair?.availableOutgoingBitrate),this.recvBWEAverager.captureSample(e.selectedCandidatePair?.availableIncomingBitrate),this.sendBW.captureSample(e.selectedCandidatePair?.bytesSent,e.selectedCandidatePair?.timestamp),this.recvBW.captureSample(e.selectedCandidatePair?.bytesReceived,e.selectedCandidatePair?.timestamp);const t=this.sendBW.delta,i=this.recvBW.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendBWAverager.captureSample(n),this.recvBWAverager.captureSample(r);const s=e.selectedCandidatePair?.availableOutgoingBitrate;s&&(this.bwJumpsHistogramCollector.active=this.bwJumpsHistogramCollector.active&&s<this.configProvider.config.webrtcBWJumpUpperLimit||s<this.configProvider.config.webrtcBWJumpLowerLimit),e.extensions={sendBWEAvg:mn(this.sendBWEAverager.avg,0),sendBWEMax:mn(this.sendBWEAverager.maxSample,0),recvBWEAvg:mn(this.recvBWEAverager.avg,0),recvBWEMax:mn(this.recvBWEAverager.maxSample,0),sendBitrate:n,recvBitrate:r,sendBWAvg:mn(this.sendBWAverager.avg,0),sendBWMax:mn(this.sendBWAverager.maxSample,0),recvBWAvg:mn(this.recvBWAverager.avg,0),recvBWMax:mn(this.recvBWAverager.maxSample,0),bwJumpsHistogram:this.bwJumpsHistogramCollector.counts,reflexiveLocalIP:this.diagnostics.reflexiveLocalIP}}},pF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){if(!e)return;const t=new Set;for(const i of e)try{t.add(i.id);const e=this.extenders.get(i.id)??new mF(this.configProvider);this.extenders.set(i.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("DataChannelStatsProcessor",tt(e))}Mn(this.extenders,t)}},mF=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.sendBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.sendMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM,this.recvMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new KM:new WM}processSample(e){this.sendBytesDeltaCalculator.captureSample(e.bytesSent,e.timestamp),this.recvBytesDeltaCalculator.captureSample(e.bytesReceived,e.timestamp);const t=this.sendBytesDeltaCalculator.delta,i=this.recvBytesDeltaCalculator.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendMessagesDeltaCalculator.captureSample(e.messagesSent,e.timestamp),this.recvMessagesDeltaCalculator.captureSample(e.messagesReceived,e.timestamp);const s=this.sendMessagesDeltaCalculator.delta,a=this.recvMessagesDeltaCalculator.delta;e.extensions={sendBitrate:n,recvBitrate:r,sendMessageRate:s,recvMessageRate:a}}},fF=class{constructor(e,t,i,n){this.slidingWindowSize=e,this.maxDeviation=t,this.minBandwidth=i,this.directionalityCheck=n,this.slidingWindow=new $M(this.slidingWindowSize),this.currentModality=null,this.previousModality=null,this.inProcess=!1}processBandwidth(e,t,i){this.currentModality?this.handleStopEvent(t,i):this.handleStartEvent(t,i),this.inProcess&&(this.stabilizationTime++,this.slidingWindow.add(e),this.inProcess=!this.slidingWindow.isFull||!this.isBandwidthStable())}getReport(e=!1){if(void 0!==this.stabilizationTime)return{time:this.inProcess?this.stabilizationTime:Math.max(this.stabilizationTime-this.slidingWindowSize,0),bandwidth:e?mn(this.averageBandwidth,2):this.averageBandwidth,finished:!this.inProcess,modality:this.previousModality}}handleStartEvent(e,t){this.currentModality=this.GetModalityString(e),t&&this.currentModality&&!this.previousModality&&(this.previousModality=this.currentModality,this.stabilizationTime=0,this.slidingWindow.clear(),this.inProcess=!0)}handleStopEvent(e,t){t&&(this.directionalityCheck(e.audio)||this.directionalityCheck(e.video)||this.directionalityCheck(e.sharing))||(this.currentModality=null,this.inProcess=!1)}GetModalityString(e){return[this.directionalityCheck(e.audio)?Gi.MODALITY.audio:null,this.directionalityCheck(e.video)?Gi.MODALITY.video:null,this.directionalityCheck(e.sharing)?Gi.MODALITY.sharing:null].filter(Boolean).join(", ")}isBandwidthStable(){if(this.averageBandwidth=Yi(this.slidingWindow.items),this.averageBandwidth<this.minBandwidth)return!1;{const e=this.averageBandwidth*this.maxDeviation,t=this.averageBandwidth-e,i=this.averageBandwidth+e;return this.slidingWindow.items.every((e=>dn(e,t,i)))}}},vF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.uplinkStabilizationTelemetry=new fF(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wp),this.downlinkStabilizationTelemetry=new fF(this.configProvider.config.downlinkBWStabilizationSlidingWindowSize,this.configProvider.config.downlinkBWStabilizationMaxDeviation,this.configProvider.config.downlinkBWStabilizationMinBandwidth,Kp),this.bandwidthCalculator=new nD,this.bandwidthAvg=new qM}processStats(e){const t=this.diagnostics.getObjectRef(),i=t?.negotiation.activeModalities;if(!i||!e.transports)return;const n=e.transports[Object.keys(e.transports)[0]],r=t?.reportedReceiveBandwidth?.[t.reportedReceiveBandwidth.length-1],s=n?.selectedCandidatePair?.availableOutgoingBitrate,a=e.audio?.send?.length>0||e.video?.send?.length>0||e.sharing?.send?.length>0,o=e.audio?.recv?.length>0||e.video?.recv?.length>0||e.sharing?.recv?.length>0;this.bweType!==t?.negotiation.bweType&&(this.bandwidthCalculator=new nD,this.bandwidthAvg=new qM,this.bweType=t?.negotiation.bweType);const l="REMB"===t?.negotiation.bweType?"availableIncomingBitrate":"availableOutgoingBitrate",c=n?.selectedCandidatePair?.[l];this.bandwidthCalculator.captureSample(c),this.bandwidthAvg.captureSample(c);try{this.uplinkStabilizationTelemetry.processBandwidth(s,i,a),this.downlinkStabilizationTelemetry.processBandwidth(r,i,o)}catch(e){this.diagnostics.addStatsError("BandwidthStatsProcessor",tt(e))}}getStabilizedReport(e=!1){return this.uplinkStabilizationTelemetry.getReport(e)}getDownlinkStabilizedReport(e=!1){return this.downlinkStabilizationTelemetry.getReport(e)}calculateBwPercentiles(){if(!this.bandwidthCalculator.getFirst())return;const e=this.configProvider.config.bwPercentiles,t={};return e.forEach((e=>{Object.defineProperty(t,e,{value:this.bandwidthCalculator.calculatePercentile(e/100),enumerable:!0})})),t}getBandwidthReport(){return{startOfTheCall:this.bandwidthCalculator.getFirst(),endOfTheCall:this.bandwidthCalculator.getLast(),std:this.bandwidthCalculator.calculateStd(),bwPercentiles:this.calculateBwPercentiles(),avgBwe:mn(this.bandwidthAvg.avg,2)}}},SF=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.videoSimulcastStreamsData={},this.videoLayoutProcessor=new yF(this.diagnostics,Gi.MODALITY.video),this.sharingSimulcastStreamsData={},this.sharingLayoutProcessor=new yF(this.diagnostics,Gi.MODALITY.sharing)}processStats(e){if(e.video?.send?.length){const t=e.video.send[0],i=[t,...t.altLayouts??[]];this.processSimulcastStream(i,this.videoSimulcastStreamsData),this.videoLayoutProcessor.processLayout(i)}if(e.sharing?.send?.length){const t=e.sharing.send[0],i=[t,...t.altLayouts??[]];this.processSimulcastStream(i,this.sharingSimulcastStreamsData),this.sharingLayoutProcessor.processLayout(i)}this.diagnostics.simulcastReport=this.getSimulcastDiagnostics()}processSimulcastStream(e,t){const{numAggregatedSamples:i}=this.configProvider.config.diagnostics.telemetryLimits;for(const n of e){const e=n.outboundRTP.rid;if(!e)continue;t[e]??(t[e]={sentLayerProcessor:new TF,appliedLayerProcessor:new TF,requestedLayerProcessor:new TF,encoderProcessor:new CF,debugResolutionTracker:new QM,outboundStats:[],report:{ssrc:n.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 r=t[e],{sentLayer:s,requestedLayer:a,appliedLayer:o}=this.getLayers(n);r.sentLayerProcessor.processLayer(s),r.appliedLayerProcessor.processLayer(o),r.requestedLayerProcessor.processLayer(a),r.encoderProcessor.processVideo(n),o&&s&&r.debugResolutionTracker.captureSample(`${o.width}x${o.height}:${s.width}x${s.height}`),rt(r.outboundStats,n.outboundRTP,i),r.report.time.sent=r.sentLayerProcessor.getTime(),r.report.time.applied=r.appliedLayerProcessor.getTime(),r.report.time.requested=r.requestedLayerProcessor.getTime(),r.report.duration.sent=r.sentLayerProcessor.getDuration(),r.report.duration.applied=r.appliedLayerProcessor.getDuration(),r.report.duration.requested=r.requestedLayerProcessor.getDuration(),r.report.restarts.sent=r.sentLayerProcessor.getRestarts(),r.report.restarts.applied=r.appliedLayerProcessor.getRestarts(),r.report.restarts.requested=r.requestedLayerProcessor.getRestarts(),r.report.resolution.sent=r.sentLayerProcessor.getResolutionDurations(),r.report.resolution.applied=r.appliedLayerProcessor.getResolutionDurations(),r.report.resolution.requested=r.requestedLayerProcessor.getResolutionDurations(),r.report.resolution.debug=r.debugResolutionTracker.durations,r.report.framerate.sent=r.sentLayerProcessor.getFpsDurations(),r.report.framerate.applied=r.appliedLayerProcessor.getFpsDurations(),r.report.framerate.requested=r.requestedLayerProcessor.getFpsDurations(),r.report.bitrate.sent=r.sentLayerProcessor.getBitrateDurations(),r.report.bitrate.applied=r.appliedLayerProcessor.getBitrateDurations(),r.report.bitrate.requested=r.requestedLayerProcessor.getBitrateDurations(),r.report.encoder=r.encoderProcessor.getEncoderReport(),r.report.stats.fir=Pn(r.outboundStats,(e=>e.firCount)),r.report.stats.nack=Pn(r.outboundStats,(e=>e.nackCount)),r.report.stats.pli=Pn(r.outboundStats,(e=>e.pliCount)),r.report.stats.packetsSent=Pn(r.outboundStats,(e=>e.packetsSent)),r.report.overshootEvents=n.extensions?.overshootEvents,r.report.totalBrOvershootDuration=n.extensions?.totalBrOvershootDuration,r.report.totalFpsOvershootDuration=n.extensions?.totalFpsOvershootDuration,r.report.totalFsOvershootDuration=n.extensions?.totalFsOvershootDuration,r.report.totalFreezeDuration=n.extensions?.totalFreezeDuration,r.report.ongoingFreezeDuration=n.extensions?.ongoingFreezeDuration,r.report.freezeHistogram=n.extensions?.freezeCountHistogram}}getSimulcastDiagnostics(){if(!Xi(this.videoSimulcastStreamsData)||!Xi(this.sharingSimulcastStreamsData))return{video:{streams:Object.fromEntries(Object.entries(this.videoSimulcastStreamsData).map((([e,{report:t}])=>[e,t]))),layouts:this.videoLayoutProcessor.getLayoutReport()},sharing:{streams:Object.fromEntries(Object.entries(this.sharingSimulcastStreamsData).map((([e,{report:t}])=>[e,t]))),layouts:this.sharingLayoutProcessor.getLayoutReport()}}}getLayers(e){const t=e.outboundRTP.rid,i=this.diagnostics.getObjectRef().qualityManager,n=e=>Object.values(e).find((e=>e.rid===t)),r="sharing"===e.mediaEntity?.modality?n(i.currentSharingSsrcAppliedCapabilities):n(i.currentVideoSsrcAppliedCapabilities),s="sharing"===e.mediaEntity?.modality?n(i.currentSharingSsrcRequestedCapabilities):n(i.currentVideoSsrcRequestedCapabilities);return{sentLayer:e.outboundRTP.frameHeight&&{height:e.outboundRTP.frameHeight,width:e.outboundRTP.frameWidth,framerate:e.extensions?.frameRateSent,bitrate:e.extensions?.bitrate},appliedLayer:r&&EF(r),requestedLayer:s&&EF(s)}}},yF=class{constructor(e,t){this.diagnostics=e,this.modality=t,this.sentResolutionTracker=new QM,this.requestedResolutionTracker=new QM,this.appliedResolutionTracker=new QM,this.debugResolutionTracker=new QM}processLayout(e){const t=e=>e.filter((e=>e.width&&e.height)).sort(((e,t)=>e.height-t.height)).map((e=>`${e.width}x${e.height}`)).join(":"),i=e=>Object.values(e).map(EF),n=t(e.map((e=>({height:e.outboundRTP.frameHeight,width:e.outboundRTP.frameWidth,framerate:e.extensions?.frameRateSent,bitrate:e.extensions?.bitrate})))),r=this.diagnostics.getObjectRef().qualityManager,s="sharing"===this.modality?r.currentSharingSsrcAppliedCapabilities:r.currentVideoSsrcAppliedCapabilities,a="sharing"===this.modality?r.currentSharingSsrcRequestedCapabilities:r.currentVideoSsrcRequestedCapabilities,o=t(i(s)),l=t(i(a));n&&this.sentResolutionTracker.captureSample(n),l&&this.requestedResolutionTracker.captureSample(l),o&&this.appliedResolutionTracker.captureSample(o),o&&n&&this.debugResolutionTracker.captureSample(`${o}->${n}`)}getLayoutReport(){return{requested:this.requestedResolutionTracker.durations,sent:this.sentResolutionTracker.durations,applied:this.appliedResolutionTracker.durations,debug:this.debugResolutionTracker.durations}}},CF=class{constructor(){this.report={}}processVideo(e){var t,i;const{encoderImplementation:n,frameWidth:r,frameHeight:s,rid:a}=e.outboundRTP,{encodeTime:o}=e.extensions;if(!n||!s)return;const l=function(e,t){if(e.startsWith("SimulcastEncoderAdapter")){const i=e.indexOf("(")+1,n={},r=e.indexOf(")");e.substring(i,r).split(",").forEach(((e,t)=>{n[`${t+1}`]=e.trim()})),e=n[t]??"Unknown"}switch(e){case"OpenH264":return"H264:SW";case"ExternalEncoder":case"MediaFoundationVideoEncodeAccelerator":case"VideoToolbox":case"WMFVideoEncoder":case"VTVideoEncoder":case"VaapiVideoEncodeAccelerator":return"H264:HW";default:return"H264:Other"}}(n,a),c=`${r}x${s}`;(t=this.report)[l]??(t[l]={resolutionTracker:new QM,encodingHistograms:{},report:{resolution:{},encodeTime:{},restarts:0}});const d=this.report[l];d.resolutionTracker.captureSample(c),(i=d.encodingHistograms)[c]??(i[c]=new QM),d.encodingHistograms[c].captureSample(function(e){return bF(e,[{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"}])}(o)),d.report.resolution=d.resolutionTracker.durations,d.report.encodeTime[c]=d.encodingHistograms[c].durations,this.prevEncoder&&this.prevEncoder!==l&&d.report.restarts++,this.prevEncoder=l}getEncoderReport(){return Object.fromEntries(Object.entries(this.report).map((([e,{report:t}])=>[e,t])))}},TF=class{constructor(){this.resolutionTracker=new QM,this.fpsTracker=new QM,this.bitrateTracker=new QM,this.durationTracker=new GL,this.startedAt=0}processLayer(e){e?(this.startedAt||(this.startedAt=_n()),this.durationTracker.start(),this.resolutionTracker.captureSample(`${e.width}x${e.height}`),this.fpsTracker.captureSample(function(e){return bF(e,[{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"}])}(e.framerate)),this.bitrateTracker.captureSample(function(e){return bF(e,[{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"}])}(e.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 EF(e){const t={...Hn.Send.getResolutionByFs(e.maxFs)};return 405===e.maxFs&&(t.width=426,t.height=240),{width:t.width,height:t.height,framerate:e.maxFps,bitrate:e.maxBr}}function bF(e,t){for(const{limit:i,label:n}of t)if(e>i)return n;return`${e}`}var _F=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.dataChannelStatsProcessor=new pF(this.diagnostics,this.configProvider),this.transportStatsProcessor=new hF(this.diagnostics,this.configProvider),this.audioStatsProcessor=new eF(this.diagnostics,this.configProvider),this.videoStatsProcessor=new aF(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new aF(this.diagnostics,this.configProvider),this.bandwidthStatsProcessor=new vF(this.diagnostics,this.configProvider),this.simulcastStatsProcessor=new SF(this.diagnostics,this.configProvider),this.macroblockStatsTracker=new lD,this.statsAggregators={audio:{recv:new iF,send:new rF(this.diagnostics)},video:{recv:new lF(this.configProvider),send:new dF(this.configProvider)},sharing:{recv:new lF(this.configProvider),send:new dF(this.configProvider)}},this.aggregatedModalityStats={},this.recvVideoStreamsCounter=new zM,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(e){const t=this.configProvider.config.diagnostics.enabledStatsProcessors;this.execute((()=>this.dataChannelStatsProcessor.processStats(e.data)),"dataChannelStatsProcessor",t.dataChannel),this.execute((()=>this.transportStatsProcessor.processStats(e.transports)),"transportStatsProcessor",t.transport),this.execute((()=>this.audioStatsProcessor.processStats(e.audio)),"audioStatsProcessor",t.audio),this.execute((()=>this.videoStatsProcessor.processStats(e.video)),"videoStatsProcessor",t.video),this.execute((()=>this.sharingStatsProcessor.processStats(e.sharing)),"sharingStatsProcessor",t.sharing),this.execute((()=>{this.bandwidthStatsProcessor.processStats(e),this.diagnostics.bwStabilizationTime=this.bandwidthStatsProcessor.getStabilizedReport(!0),this.diagnostics.bwDownlinkStabilizationTime=this.bandwidthStatsProcessor.getDownlinkStabilizedReport(!0)}),"bandwidthStatsProcessor",t.bandwidth),this.execute((()=>{this.recvVideoStreamsCounter.captureSample(e.video?.recv?.length),this.diagnostics.recvVideoStreamsCount={min:this.recvVideoStreamsCounter.min,max:this.recvVideoStreamsCounter.max,mode:this.recvVideoStreamsCounter.mode}}),"recvVideoStreamsCounter",t.recvVideoStreamsCounter),this.execute((()=>this.processAggregated(e)),"processAggregated",t.aggregated),this.execute((()=>this.processMultiview(e.video?.recv??[])),"processMultiview",t.multiview),this.execute((()=>this.simulcastStatsProcessor.processStats(e)),"processSimulcastStats",t.simulcast),this.execute((()=>this.processNetworkInfoStats()),"processNetworkInfoStats",t.networkInfo),this.execute((()=>this.processMacroblockRateStats(e.video?.recv)),"processMacroblockRateStats",t.macroblockRate)}signalNoConnection(){this.transportStatsProcessor=new hF(this.diagnostics,this.configProvider),this.audioStatsProcessor=new eF(this.diagnostics,this.configProvider),this.videoStatsProcessor=new aF(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new aF(this.diagnostics,this.configProvider)}processNetworkInfoStats(){const e=navigator?.connection;e&&this.diagnostics.addNetworkInfo({downlink:e.downlink,rtt:e.rtt,effectiveType:e.effectiveType,saveData:e.saveData})}processMultiview(e){const t=new Set;for(const i of e){const e=i.inboundRTP.id;t.add(e);let n=this.multiviewData[e];n&&this.multiviewKeySet.has(e)?n.stats.duration++:(n={bitrateAverager:new qM,jitterAverager:new qM,frameRateAverager:new qM,freezeHistogram:new YM(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),resolutionDurations:new QM,isRenderingEvents:[],statsOnSubscribed:new uF(this.configProvider),stats:{ssrc:i.inboundRTP.ssrc,startTime:Date.now(),duration:0,framesDecoded:[],bytesReceived:[],height:[],width:[]}},n.statsOnSubscribed.prepareCollectingStatsOnSubscribed(i.renderer?.msi),this.multiviewData[e]=n),n.statsOnSubscribed.captureStatsOnSubscribed(i.inboundRTP.framesDecoded,i.inboundRTP.bytesReceived,i.inboundRTP.frameHeight),n.bitrateAverager.captureSample(i.extensions?.bitrate),n.jitterAverager.captureSample(1e3*(i.inboundRTP.jitter??0)),n.frameRateAverager.captureSample(i.extensions.frameRateReceived),n.freezeHistogram.active=i.extensions?.isFrozen,i.inboundRTP.frameWidth&&i.inboundRTP.frameHeight&&n.resolutionDurations.captureSample(`${i.inboundRTP.frameWidth}x${i.inboundRTP.frameHeight}`);const r=i.renderer?.isRendering??!1;(!n.isRenderingEvents.length&&r||n.isRenderingEvents.length&&Cn(n.isRenderingEvents).isRendering!==r)&&Sn(n.isRenderingEvents,{isRendering:r,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents),n.stats.frameRateAvg=mn(n.frameRateAverager.avg),n.stats.bitrateAvg=mn(n.bitrateAverager.avg,0),n.stats.bitrateMax=mn(n.bitrateAverager.maxSample,0),n.stats.bitrateMinNonZero=mn(n.bitrateAverager.minNonZeroSample),n.stats.freezeHistogram=n.freezeHistogram.counts,n.stats.freezeTimestamps=n.freezeHistogram.timestamps,n.stats.avgFreezeDuration=mn(n.freezeHistogram.avgDuration),n.stats.totalFreezeDuration=n.freezeHistogram.totalDuration,n.stats.ongoingFreeze=n.freezeHistogram.active,n.stats.ongoingFreezeDuration=n.freezeHistogram.ongoingDuration,n.stats.numResolutionSwitches=n.resolutionDurations.changeCount,n.stats.rendererSize=`${i.renderer?.rendererSize?.width}x${i.renderer?.rendererSize?.height}`,n.stats.resolutionDurations=n.resolutionDurations.durations,n.stats.timeToFirstFrame=i.renderer?.timeToFirstFrame,n.stats.timeToFirstFrameSinceSubscriptionStart=i.renderer?.timeToFirstFrameSinceSubscriptionStart,n.stats.isRenderingEvents=n.isRenderingEvents,n.stats.statsOnSubscribed=n.statsOnSubscribed.videoStatsOnSubscribed,n.stats.msi=i.renderer?.msi,n.stats.rendererStates=i.renderer?.rendererStates,Sn(n.stats.framesDecoded,i.inboundRTP.framesDecoded,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.bytesReceived,i.inboundRTP.bytesReceived,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.height,i.inboundRTP.frameHeight,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Sn(n.stats.width,i.inboundRTP.frameWidth,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples);const s=i.extensions?.macroblockRateStats??{};for(const e in s)n.stats[e]=mn(s[e],0)}this.diagnostics.multiViewStats=Object.values(this.multiviewData).map((e=>e.stats)),this.multiviewKeySet=t}processAggregated(e){for(const t of["audio","video","sharing"])if(e[t])for(const i in e[t])this.processAggregatedModality(e,t,i)}processAggregatedModality(e,t,i){var n,r;const s=e[t]?.[i]?.length??0;s>0&&((n=this.aggregatedModalityStats)[t]??(n[t]={}),(r=this.aggregatedModalityStats[t])[i]??(r[i]=[]),s>1&&("audio"===t||"sharing"===t)&&this.diagnostics.addStatsError("webrtcStatistics:processAggregatedModality",`Multiple ${t} ${i} streams: ${s}`),this.statsAggregators[t][i].processSample(e[t][i],this.aggregatedModalityStats[t][i],this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),"sharing"!==t&&"video"!==t||"recv"!==i||this.processStatsOnSubscribed(e[t][i],t))}processStatsOnSubscribed(e,t){const i=new Set;for(const n of e)if(n.inboundRTP){const e=`${n.inboundRTP.id}x${n.renderer?.msi}`;let r=this.statsOnSubscribedData[t]?.[e];i.add(e),r||(r=new uF(this.configProvider),r.prepareCollectingStatsOnSubscribed(n.renderer?.msi),this.statsOnSubscribedData[t][e]=r,this.statsOnSubscribed[t].push(...r.videoStatsOnSubscribed)),r.captureStatsOnSubscribed(n.inboundRTP.framesDecoded,n.inboundRTP.bytesReceived)}!function(e,t){const i=[];for(const n of Object.keys(e))t.has(n)||i.push(n);for(const t of i)delete e[t]}(this.statsOnSubscribedData[t],i)}processMacroblockRateStats(e){if(!e?.length)return;let t=0,i=0;for(const n of e)t+=n.extensions?.macroblockRateReceived,i+=n.extensions?.macroblockRateDecoded;this.macroblockStatsTracker.captureSample(t,i),this.diagnostics.setTotalVideoRecvMblocksRates(this.macroblockStatsTracker.getReport())}execute(e,t,i){try{i&&e()}catch(e){this.diagnostics.addStatsError(`webrtcStatistics:${t}`,tt(e))}}},IF=Z,wF=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.webrtcStats=new _F(this.configProvider,this.diagnostics),this.ssrcToRecvTrackMap=new Map,this.activeChannels={}}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}setAudioEncoderCodecName(e){this.audioEncoderCodecName=e}signalNoConnection(){this.webrtcStats.signalNoConnection()}processRawReport(e){this.diagnostics.latestRawReport=e;const t={loopTime:-1,fetchTime:-1,convertTime:-1,processingTime:-1,legacyProcessingTime:-1};try{let i=_n(),n=i;const r=this.convertStatsReport(e);return r.perfCounters=t,i=_n(),t.convertTime=i-n,n=i,this.webrtcStats.processStats(r),this.diagnostics.addStatsReport(r),i=_n(),t.processingTime=i-n,r}catch(e){const t=tt(e);return this.logger.safe.error(`Error processing raw stats: ${t}`),void this.diagnostics.addStatsError("StatisticsGatherer:processRawReport",t)}}setSsrcTrackPair(e,t){null===t?this.ssrcToRecvTrackMap.delete(e):this.ssrcToRecvTrackMap.set(e,t)}convertStatsReport(e){const t={transports:this.processTransportStats(e)};return this.appendPcStats(e,t),this.appendSendMediaStats(e,t),this.appendRecvMediaStats(e,t),e["data-channel"]&&(t.data=Object.values(e["data-channel"])),t}processTransportStats(e){if(e.transport){const t={};for(const i in e.transport){const n=e.transport[i];if(t[i]=tn(n),n.selectedCandidatePairId){const r=tn(e["candidate-pair"][n.selectedCandidatePairId]);r.localCandidate=e["local-candidate"][r.localCandidateId],r.remoteCandidate=e["remote-candidate"][r.remoteCandidateId],t[i].selectedCandidatePair=r}n.localCertificateId&&e.certificate&&(t[i].localCertificate=e.certificate[n.localCertificateId]),n.remoteCertificateId&&e.certificate&&(t[i].remoteCertificate=e.certificate[n.remoteCertificateId])}return t}if(e["candidate-pair"]){const t={};for(const i in e["candidate-pair"]){const n=tn(e["candidate-pair"][i]);n.selected&&(n.localCandidate=e["local-candidate"][n.localCandidateId],n.remoteCandidate=e["remote-candidate"][n.remoteCandidateId],t.faketransport={id:"faketransport",timestamp:n.timestamp,type:"transport",selectedCandidatePair:n,selectedCandidatePairId:n.id})}return t}}appendPcStats(e,t){let i="";e["peer-connection"]&&(Object.keys(e["peer-connection"]).forEach((e=>{""===i?i=e:(this.logger.safe.error(`Unexpected second peer connection stats id ${e}, also found ${i}`),this.diagnostics.addStatsError("StatisticsGatherer","Unexpected second peer connection stats"))})),t.peerConnection=e["peer-connection"][i])}appendSendMediaStats(e,t){var i,n,r,s;for(const a in e["outbound-rtp"]){const o=e["outbound-rtp"][a],l={outboundRTP:o};o.codecId&&e.codec&&(l.codec=e.codec[o.codecId]),Object.defineProperty(l,"transport",{value:t.transports[o.transportId??"faketransport"],configurable:!1,enumerable:!1}),o.remoteId&&e["remote-inbound-rtp"]&&(l.remoteInboundRTP=e["remote-inbound-rtp"][o.remoteId]),o.mediaSourceId&&e["media-source"]&&(l.mediaSource=e["media-source"][o.mediaSourceId]),o.trackId&&e.track&&(l.track=e.track[o.trackId]);const c=DF(this.mediaManager,l.track?.trackIdentifier??l.mediaSource?.trackIdentifier,o.rid)??MF(this.mediaManager,o.ssrc,o.rid)??LF(this.mediaManager,l.outboundRTP.mid,o.rid);if(!c?.getLocalTrackId())continue;l.mediaEntity=c.serialize(),!l.mediaSource&&l.mediaEntity&&e["media-source"]&&(l.mediaSource=Object.values(e["media-source"]).find((e=>e.trackIdentifier===l.mediaEntity.localTrackId)));const d="video"===o.kind?"sharing"===c?.getModality()?"sharing":"video":o.kind;if((i=this.activeChannels)[d]??(i[d]={}),(n=this.activeChannels[d]).send??(n.send={}),Wp(this.diagnostics.getObjectRef().negotiation.activeModalities?.[d])){if(t[d]||(t[d]={}),t[d].send||(t[d].send=[]),"video"===o.kind){const e=kF(this.diagnostics,d,o.ssrc)??kF(this.diagnostics,d,0);e&&(l.requestedCapabilities=e);const i=OF(this.diagnostics,d,o.ssrc)??OF(this.diagnostics,d,0);i&&(l.appliedCapabilities=i);const n=t[d].send.find((e=>e.outboundRTP.trackId===l.outboundRTP.trackId));if(n){const e=parseInt(n.outboundRTP.rid,10)>parseInt(l.outboundRTP.rid,10);if(!n.altLayouts&&e&&(n.altLayouts=[]),e)n.altLayouts.push(l);else{l.altLayouts=[],l.altLayouts.push(n);const e=t[d].send.indexOf(n);t[d].send[e]=l}continue}}"audio"===o.kind&&l.codec&&this.audioEncoderCodecName&&"None"!==this.audioEncoderCodecName&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing send audio codec with custom audio encoder codec"),l.codec.mimeType=this.audioEncoderCodecName),this.activeChannels[d].send[o.id]=l,t[d].send.push(l)}else this.activeChannels[d].send[o.id]&&"sharing"!==d&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[d]??(r[d]={}),(s=t.inactiveTracks[d]).send??(s.send=[]),t.inactiveTracks[d].send.push(this.activeChannels[d].send[o.id]))}}appendRecvMediaStats(e,t){var i,n,r,s;const a=this.diagnostics.getObjectRef().subscriptionManager?.subscribedTrackIds;for(const o in e["inbound-rtp"]){const l=e["inbound-rtp"][o],c={inboundRTP:l};l.codecId&&e.codec&&(c.codec=e.codec[l.codecId]),"audio"===l.kind&&c.inboundRTP.ssrc===this.audioDecoderStatsProvider?.ssrc&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing recv audio stats with custom audio decoder stats"),c.codec||(c.codec={transportId:l.transportId??"faketransport",id:"fakeCodec",payloadType:999,timestamp:l.timestamp,type:"codec",mimeType:"unk"}),c.codec.mimeType=this.audioDecoderStatsProvider.codecName,c.inboundRTP=(0,IF.merge)(c.inboundRTP,this.audioDecoderStatsProvider.getWebRtcCompatibleStats()),c.customHealerStats=this.audioDecoderStatsProvider.getWasmStats()),t.transports[l.transportId??"faketransport"]&&Object.defineProperty(c,"transport",{value:t.transports[l.transportId??"faketransport"],configurable:!1,enumerable:!1}),l.remoteId&&e["remote-outbound-rtp"]&&(c.remoteOutboundRTP=e["remote-outbound-rtp"][l.remoteId]);const d=c.inboundRTP.trackIdentifier??this.ssrcToRecvTrackMap.get(l.ssrc);if(l.trackId||d){l.trackId&&e.track?c.track=e.track[l.trackId]:d&&(c.track={id:"ssrcToTrackId",kind:l.kind,timestamp:l.timestamp,type:"track",trackIdentifier:d});const t=NF(this.diagnostics,c.track?.trackIdentifier);t&&(c.renderer=t)}const u=RF(this.mediaManager,c.track?.trackIdentifier)??PF(this.mediaManager,l.ssrc);if(!u)continue;c.mediaEntity=u.serialize();const h="video"===l.kind&&c.track?"sharing"===u?.getModality()?"sharing":"video":l.kind;(i=this.activeChannels)[h]??(i[h]={}),(n=this.activeChannels[h]).recv??(n.recv={}),"video"!==l.kind||a.some((e=>e&&e===c.track?.trackIdentifier))?Kp(this.diagnostics.getObjectRef().negotiation.activeModalities?.[h])&&(t[h]||(t[h]={}),t[h].recv||(t[h].recv=[]),this.activeChannels[h].recv[l.id]=c,t[h].recv.push(c)):this.activeChannels[h].recv[l.id]&&"sharing"!==h&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[h]??(r[h]={}),(s=t.inactiveTracks[h]).recv??(s.recv=[]),t.inactiveTracks[h].recv.push(this.activeChannels[h].recv[l.id]))}}};function AF(e,t){return!t||e.getSimulcastContext()?.activeRids.map(String).some((e=>e===t))}function PF(e,t){return e.getMediaEntities().find((e=>e.getRemoteSsrc()===t))}function RF(e,t){const i=e.getMediaEntities();return void 0!==t?i.find((e=>e.getRemoteTrackId()===t)):void 0}function MF(e,t,i){return e.getMediaEntities().find((e=>e.getLocalSsrc()===t&&AF(e,i)))}function DF(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getLocalTrackId()===t&&AF(e,i))):void 0}function kF(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcRequestedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcRequestedCapabilities[`${i}`]:void 0}function OF(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcAppliedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcAppliedCapabilities[`${i}`]:void 0}function NF(e,t){return e.getObjectRef().remoteVideoManager?.renderers.find((e=>e.trackId===t))}function LF(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getMid()===t&&AF(e,i))):void 0}var xF=class{constructor(){this.googCandidatePair={},this.ssrc={},this.googComponent={},this.VideoBwe={bweforvideo:{}}}},FF=class{constructor(){this.statistics=new xF,this.statsDiffMap=new Map,this.ssrcTrackMap=new Map}build(e){return this.statistics=new xF,this.constructGoogCandidatePair(e),this.constructGoogSsrc(e),this.constructGoogComponent(e),this.constructDataChannel(e),this.constructBwe(e),this.statistics}setSsrcTrackPair(e,t){null===t?this.ssrcTrackMap.delete(e):this.ssrcTrackMap.set(e,t)}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}setAudioEncoderCodecName(e){this.audioEncoderCodecName=e}constructGoogSsrc(e){const t={};if(e.hasOwnProperty("outbound-rtp")){const i=e["outbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_send`,s=this.constructSendSsrc(e,i[n]);t[r]=s}))}if(e.hasOwnProperty("inbound-rtp")){const i=e["inbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_recv`,s=this.constructRecvSsrc(e,i[n]);t[r]=s}))}this.statistics.ssrc=t}constructSendSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=t.mediaSourceId?e["media-source"][t.mediaSourceId]:null,r=e["remote-inbound-rtp"]?.[t.remoteId],s=`ssrc_${t.ssrc}_send`,a=n?.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let o={id:s,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesSent:t.bytesSent,bytesSentDiff:this.calculateDiff(s,t.bytesSent,4),packetsSent:t.packetsSent,packetsLost:r?.packetsLost,jitter:r?.jitter,googRtt:this.getRtt(r),googCodecName:this.getCodec(e,t.codecId),transportId:t.transportId,googTrackId:a};return"audio"===o.mediaType&&(o={...o,...this.constructAudioSendSsrc(t,n)}),"video"===o.mediaType&&(o={...o,...this.constructVideoSendSsrc(t,n,s,i)}),rn(o)}constructAudioSendSsrc(e,t){const i={audioInputLevel:t?.audioLevel,totalAudioEnergy:t?.totalAudioEnergy,fecPacketsSent:e.fecPacketsSent};return this.audioEncoderCodecName&&"None"!==this.audioEncoderCodecName&&(i.googCodecName=this.audioEncoderCodecName),i}constructVideoSendSsrc(e,t,i,n){return{framesEncoded:e.framesEncoded,googFrameRateEncoded:this.calculateDiff(i,e.framesEncoded,2),googFrameRateSent:this.calculateDiff(i,e.framesSent??n?.framesSent,1),googFrameRateInput:t?.framesPerSecond,googFrameHeightSent:e.frameHeight??n?.frameHeight,googFrameWidthSent:e.frameWidth??n?.frameWidth,googFrameHeightInput:t?.height,googFrameWidthInput:t?.width,hugeFramesSent:e.hugeFramesSent??n?.hugeFramesSent,keyFramesEncoded:e.keyFramesEncoded,qpSum:e.qpSum,qp:this.calculateDiff(i,e.qpSum,8),googPlisReceived:e.pliCount,googFirsReceived:e.firCount,googNacksReceived:e.nackCount,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,codecImplementationName:e.encoderImplementation,rid:e.rid,encodeTime:e.totalEncodeTime&&Math.round(1e3*this.calculateDiff(i,e.totalEncodeTime,6))}}constructRecvSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=`ssrc_${t.ssrc}_recv`,r=t.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let s={id:n,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesReceived:t.bytesReceived,bytesReceivedDiff:this.calculateDiff(n,t.bytesReceived,5),packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,jitter:t.jitter,googJitterBufferMs:t.jitterBufferEmittedCount&&Math.round(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3),googCodecName:this.getCodec(e,t.codecId),googTrackId:r,transportId:t.transportId};return"audio"===s.mediaType&&(s={...s,...this.constructAudioRecvSsrc(t,i)}),"video"===s.mediaType&&(s={...s,...this.constructVideoRecvSsrc(t,n,i)}),rn(s)}constructAudioRecvSsrc(e,t){const i=this.audioDecoderStatsProvider?.ssrc===e.ssrc?this.audioDecoderStatsProvider?.getWebRtcCompatibleStats():e,n={audioOutputLevel:i.audioLevel??t?.audioLevel,totalAudioEnergy:i.totalAudioEnergy??t?.totalAudioEnergy,concealedSamples:i.concealedSamples,silentConcealedSamples:i.silentConcealedSamples,totalSamplesReceived:i.totalSamplesReceived,healedRatio:i.totalSamplesReceived&&(i.concealedSamples-i.silentConcealedSamples)/i.totalSamplesReceived,fecPacketsReceived:i.fecPacketsReceived,fecPacketsDiscarded:i.fecPacketsDiscarded,packetsDiscarded:i.packetsDiscarded};if(this.audioDecoderStatsProvider?.ssrc===e.ssrc){n.googJitterBufferMs=i.jitterBufferEmittedCount&&Math.round(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3),n.googCodecName=this.audioDecoderStatsProvider.codecName;const e=this.audioDecoderStatsProvider.getDecoderStats();n.pushCount=e.pushCount,n.pushErrCount=e.pushErrCount,n.pullCount=e.pullCount,n.pullErrCount=e.pullErrCount}return n}constructVideoRecvSsrc(e,t,i){return{framesDecoded:e.framesDecoded,googFrameRateDecoded:this.calculateDiff(t,e.framesDecoded,3),googFrameRateReceived:this.calculateDiff(t,e.framesReceived??i?.framesReceived,0),googFrameHeightReceived:e.frameHeight??i?.frameHeight,googFrameWidthReceived:e.frameWidth??i?.frameWidth,keyFramesDecoded:e.keyFramesDecoded,googPlisSent:e.pliCount,googFirsSent:e.firCount,googNacksSent:e.nackCount,codecImplementationName:e.decoderImplementation,decodeTime:e.totalDecodeTime&&Math.round(1e3*this.calculateDiff(t,e.totalDecodeTime,7))}}constructGoogCandidatePair(e){const t=e["candidate-pair"];t&&Object.keys(t).forEach((i=>{const n=this.constructPair(e,t[i]);this.statistics.googCandidatePair[n.id]=n}))}constructPair(e,t){const i=e["local-candidate"][t.localCandidateId],n=e["remote-candidate"][t.remoteCandidateId];return rn({bytesReceived:t.bytesReceived,bytesSent:t.bytesSent,googTransportType:i.protocol,googRtt:t.currentRoundTripTime?Math.round(1e3*t.currentRoundTripTime):void 0,googLocalAddress:`${i.ip?i.ip:i.address}:${i.port}`,googLocalCandidateType:i.candidateType,localRelayProtocol:i.relayProtocol,localNetworkType:i.networkType,googRemoteAddress:`${n.ip?n.ip:n.address}:${n.port}`,googRemoteCandidateType:n.candidateType,googActiveConnection:t.nominated,requestsReceived:t.requestsReceived,requestsSent:t.requestsSent,responsesReceived:t.responsesReceived,responsesSent:t.responsesSent,consentRequestsSent:t.consentRequestsSent,id:t.id,remoteCandidateId:t.remoteCandidateId,localCandidateId:t.localCandidateId,googWritable:t.writable,selected:t.selected,packetsDiscardedOnSend:t.packetsDiscardedOnSend})}constructGoogComponent(e){e.transport&&Object.keys(e.transport).forEach((t=>{this.statistics.googComponent[t]={id:t,selectedCandidatePairId:e.transport[t].selectedCandidatePairId}}))}constructDataChannel(e){if(!e.hasOwnProperty("data-channel"))return;const t=e["data-channel"];this.statistics.data=Object.keys(t).map((e=>{const i=t[e];return{bytesReceived:i.bytesReceived,bytesSent:i.bytesSent,dataChannelIdentifier:i.dataChannelIdentifier,label:i.label,messagesReceived:i.messagesReceived,messagesSent:i.messagesSent,protocol:i.protocol,state:i.state,timestamp:i.timestamp,type:i.type}}))}constructBwe(e){const t=Object.values(e["outbound-rtp"]??{})?.find((e=>{const t=e.mediaType??e.kind;return"audio"===t||"video"===t}));if(!t)return;const i=e.transport?.[t.transportId];if(!i)return;const n=e["candidate-pair"]?.[i.selectedCandidatePairId];if(!n)return;const r={googAvailableSendBandwidth:n.availableOutgoingBitrate,googAvailableReceiveBandwidth:n.availableIncomingBitrate};this.statistics.VideoBwe.bweforvideo=rn(r)}getRtt(e){const t=e?.roundTripTime;return t?Math.round(1e3*t):void 0}getCodec(e,t){if(t&&e.codec&&e.codec[t])return e.codec[t].mimeType.split("/").pop()}calculateDiff(e,t,i){if(void 0===t)return;let n=t;const r=this.statsDiffMap.has(e)?this.statsDiffMap.get(e):new Map;if(r.has(i)){const e=r.get(i);e<=t&&(n=t-e)}return r.set(i,t),this.statsDiffMap.set(e,r),isNaN(n)?void 0:n}},UF=Z,BF=Z,VF=class{constructor(e){this.healedRatio=0,this.healedRatioMax=0,this.healedRatioDuration=0,this.healedRatioTotal=0,this.totalSamplesReceivedDiff=0;const t=e.config;this.networkDetectionDuration=t.webrtcStatNetworkDetectionDuration,this.networkRecvQualityDiagnostics=t.networkRecvQualityDiagnostics,this.networkRecvQualityDiagnostics&&(this.healedRatioAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedDiffAccumulator=new $M(t.webrtcHealedRatioExtendedWindowSize))}captureHealedRatioSamples(e,t,i){!e||!t||!i||e.length<=this.networkDetectionDuration||t.length<=this.networkDetectionDuration||i.length<=this.networkDetectionDuration||this.setHealedRatioPerDuration(e,t,i)}getHealedRatioMax(){return this.healedRatioMax}getHealedRatioAvg(){return this.healedRatioDuration?this.healedRatioTotal/this.healedRatioDuration:0}getHealedRatio(){return this.healedRatio}getTotalSamplesReceivedDiff(){return this.totalSamplesReceivedDiff}setHealedRatioPerDuration(e,t,i){const n=-1-this.networkDetectionDuration,r=Math.max((0,BF.last)(e)-(0,BF.nth)(e,n),0),s=Math.max((0,BF.last)(t)-(0,BF.nth)(t,n),0);this.totalSamplesReceivedDiff=Math.max((0,BF.last)(i)-(0,BF.nth)(i,n),0),0!==this.totalSamplesReceivedDiff&&(this.healedRatio=(r-s)/this.totalSamplesReceivedDiff,this.healedRatioDuration++,this.healedRatioTotal+=this.healedRatio,this.healedRatioMax=Math.max(this.healedRatioMax,this.healedRatio),this.networkRecvQualityDiagnostics&&(this.concealedSamplesAccumulator.add((0,BF.last)(e)),this.silentConcealedSamplesAccumulator.add((0,BF.last)(t)),this.totalSamplesReceivedAccumulator.add((0,BF.last)(i)),this.concealedSamplesDiffAccumulator.add(r),this.silentConcealedSamplesDiffAccumulator.add(s),this.totalSamplesReceivedDiffAccumulator.add(this.totalSamplesReceivedDiff),this.healedRatioAccumulator.add(this.healedRatio)))}getDiagnostics(e){return{quality:(0,BF.last)(e),qualityLevels:e,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((e=>mn(e)))}}},HF=class{constructor(e){this.configProvider=e,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(e){this.jitterBufferDuration+=Gi.TIME_INTERVAL.SEC_1,this.jitterBufferTotal+=e}captureJitter(e){const t=1e3*e;this.jitterTotal+=t,this.jitterMax=Math.max(t,this.jitterMax),this.jitterDuration+=Gi.TIME_INTERVAL.SEC_1}getJitterAvg(){return this.jitterDuration?mn(this.jitterTotal/this.jitterDuration):0}getAvgJitterBuffer(){return this.jitterBufferDuration?Math.round(this.jitterBufferTotal/this.jitterBufferDuration):0}captureRtt(e){if(null!==e){const t=parseInt(e);this.rttDuration+=Gi.TIME_INTERVAL.SEC_1,this.rttTotal+=t,this.rttMax=Math.max(this.rttMax,t)}}getAvgRtt(){return this.rttDuration?mn(this.rttTotal/this.rttDuration):0}getMaxRtt(){return this.rttMax}getJitterMax(){return this.jitterMax}updateSendStream(e,t){if(!this.configProvider.config.useAudioAnalyzer)return;const i=this.audioAnalyzers.get(t);i&&(i.dispose(),this.audioAnalyzers.delete(t)),e?.rawStream?.getAudioTracks().length&&this.audioAnalyzers.set(t,new zk(e.rawStream))}getInputLevel(e){const t=this.audioAnalyzers.get(e);return t?.getInputLevelNormalized()}},$F=class{constructor(e,t){this.dropBadBandwidth=e,this.dropGoodBandwidth=t,this.dropDurationCounts={},Object.keys(Gi.HISTOGRAM_BATCH).forEach((e=>{this.dropDurationCounts[e]=0}))}recordSendBandwidth(e){this.currentDropDuration&&e<this.dropGoodBandwidth||e<this.dropBadBandwidth?this.initiateDrop():this.currentDropDuration&&e>this.dropGoodBandwidth&&this.recoverDrop()}getReport(){const e=tn(this.dropDurationCounts);return this.currentDropDuration&&(e.ongoingDuration=this.currentDropDuration),e}initiateDrop(){this.currentDropDuration?this.currentDropDuration++:this.currentDropDuration=1}recoverDrop(){for(const e of Object.keys(Gi.HISTOGRAM_BATCH))if(this.currentDropDuration<=Gi.HISTOGRAM_BATCH[e]){this.dropDurationCounts[e]+=1,this.currentDropDuration=0;break}}},jF=Z,GF=class{constructor(e,t,i,n){this.lowThreshold=e,this.highThreshold=t,this.isLowerBetter=i,this.curInLowerRange=i,this.stateTracker=new qF(n)}onSample(e,t){let i=this.curInLowerRange;this.curInLowerRange?e>this.highThreshold&&(i=!1):e<this.lowThreshold&&(i=!0);const n=this.stateTracker.onNewState(this.getQuality(i),t);return n!==this.getQuality(this.curInLowerRange)&&(this.curInLowerRange=i),n}getQuality(e){return e===this.isLowerBetter?"Good":"Bad"}},qF=class{constructor(e){this.stickinessTime=e}onNewState(e,t){return"Good"!==e&&"Bad"!==e?this.curState:0===this.stickinessTime?e:e===this.curState?(this.stickTimerStarted=0,this.curState):("Bad"===this.curState?0===this.stickTimerStarted?this.stickTimerStarted=t:t-this.stickTimerStarted>this.stickinessTime&&(this.curState=e,this.stickTimerStarted=0):(this.curState=e,this.stickTimerStarted=0),this.curState)}},zF=class{constructor(e,t,i,n){this.stateProcessor=e,this.windowSize=t,this.extendedWindowSize=i,this.addDiagnosticData=n,this.dataAccumulator=new $M(i),this.avgAccumulator=new $M(i)}getLatestSendQuality(e,t,i){if(this.dataAccumulator.add(e),this.dataAccumulator.items.length>=this.windowSize){const e=this.dataAccumulator.items.slice(-this.windowSize),i=(0,jF.mean)(e);return this.addDiagnosticData&&this.avgAccumulator.add(i),this.stateProcessor.onSample(i,t)}return i}getData(){return this.dataAccumulator.items.map((e=>mn(e)))}getAggregatedData(){return this.avgAccumulator.items.map((e=>mn(e)))}},WF=class{constructor(e,t,i){this.configProvider=e,this.newStatsApi=t,this.webrtcHealedRatio=i,this.sendAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiffAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostDiffAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.totalAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendQualityAccumulator=new $M(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiagnosticsEnabled=this.configProvider.config.networkSendQualityDiagnostics,this.recvDiagnosticsEnabled=this.configProvider.config.networkRecvQualityDiagnostics,this.recvQualityAccumulator=new $M(this.configProvider.config.webrtcHealedRatioExtendedWindowSize);const n=Number(this.configProvider.config.webrtcStatNetworkDetectionHysteresis);this.networkDetectionBadLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionBadLevel)+n/2,this.networkDetectionBadLevelLow=this.networkDetectionBadLevelHigh-n,this.networkDetectionGoodLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionGoodLevel)+n/2,this.networkDetectionGoodLevelLow=this.networkDetectionGoodLevelHigh-n;const r=new GF(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),s=new GF(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime);this.jitterCalculator=new zF(r,e.config.webrtcJitterWindowSize,e.config.webrtcJitterExtendedWindowSize,this.sendDiagnosticsEnabled),this.lossRateCalculator=new zF(s,e.config.webrtcLossRateWindowSize,e.config.webrtcLossRateExtendedWindowSize,this.sendDiagnosticsEnabled)}calculateNetworkSendQualityLevel(e,t,i,n){if(!e||!t)return{quality:n};if(e.length<2||t.length<2||(0,jF.last)(e)<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return{quality:n};const r=Date.now(),s=(0,jF.last)(i),a=this.jitterCalculator.getLatestSendQuality(s,r,n),[o,l]=e.slice(-2),[c,d]=t.slice(-2),u=this.getLossRate(l,o,d,c),h=this.lossRateCalculator.getLatestSendQuality(u,r,n),g="Good"===a&&"Good"===h?"Good":"Bad";return this.sendDiagnosticsEnabled&&(this.sendAccumulator.add(l),this.lostAccumulator.add(d),this.sendQualityAccumulator.add(g)),this.sendDiagnosticsEnabled?{quality:g,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:g}}calculateNetworkRecvQualityLevel(e){if(this.newStatsApi){const t=e;return this.calculateNetworkRecvQualityLevelNewStatsApi(t.concealedSamples,t.silentConcealedSamples,t.totalSamplesReceived,t.oldNetworkLevel)}{const t=e;return this.calculateNetworkRecvQualityLevelLegacyStatsApi(t.googDecodingCTN,t.googDecodingPLC,t.oldNetworkLevel)}}calculateNetworkRecvQualityLevelLegacyStatsApi(e,t,i){const n=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||!t||e.length<2*n)return{quality:i};let r=e.length-1-n;const s=e[e.length-1];for(;r>=0&&s-e[r]<100*n;)r--;if(r<0)return{quality:i};const a=s-e[r],o=t[t.length-1]-t[r];if(a<=0)return{quality:i};const l=o/a;return{quality:this.getRecvQuality(l,i)}}calculateNetworkRecvQualityLevelNewStatsApi(e,t,i,n){const r=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||e.length<=r||!t||t.length<=r||!i||i.length<=r)return{quality:n};if((0,jF.last)(i)<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality)return{quality:n};if(0===this.webrtcHealedRatio.getTotalSamplesReceivedDiff())return{quality:n};const s=this.webrtcHealedRatio.getHealedRatio(),a=this.getRecvQuality(s,n);return this.recvDiagnosticsEnabled?(this.recvQualityAccumulator.add(a),this.webrtcHealedRatio.getDiagnostics(this.recvQualityAccumulator.items)):{quality:a}}getRecvQuality(e,t){return e<this.networkDetectionGoodLevelLow?"Good":e<this.networkDetectionGoodLevelHigh?"Good"===t?"Good":"Poor":e<this.networkDetectionBadLevelLow?"Poor":e<this.networkDetectionBadLevelHigh?"Bad"===t?"Bad":"Poor":"Bad"}getLossRate(e,t,i,n){const r=e-t,s=i-n,a=r+s;return this.sendDiagnosticsEnabled&&(this.sendDiffAccumulator.add(r),this.lostDiffAccumulator.add(s),this.totalAccumulator.add(a)),a>0?s/a:0}},KF=class{constructor(e){this.configProvider=e,this.qualityLimitationReasonEvents=[]}setQualityLimitationReason(e){this.lastQualityLimitationReason!==e&&this.qualityLimitationReasonEvents.push({event:e,startTime:Date.now(),endTime:Date.now()}),this.qualityLimitationReasonEvents.length>this.configProvider.config.maxStoredQualityLimitationReasonEvents&&this.qualityLimitationReasonEvents.shift(),this.lastQualityLimitationReason=e}getQualityLimitationReasonEvents(){return this.qualityLimitationReasonEvents.reduce(((e,t,i)=>"none"===t.event?e:[...e,{...t,endTime:this.qualityLimitationReasonEvents[i+1]?.startTime??Date.now()}]),[])}},JF=class{constructor(){this.bitrateData={[Gi.MEDIA_DIRECTION.SEND]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0,allocateBW:0,allocateBWSamples:0},[Gi.MEDIA_DIRECTION.RECV]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0}}}captureSample(e,t){const i=Date.now()/1e3;if(0!==this.bitrateData[e].lastTimestamp&&t>this.bitrateData[e].lastBytes){const n=i-this.bitrateData[e].lastTimestamp,r=8*(t-this.bitrateData[e].lastBytes)/n;this.onBitrateSample(e,r)}this.bitrateData[e].lastTimestamp=i,this.bitrateData[e].lastBytes=t}getMax(e){return Math.round(this.bitrateData[e].maxSample)}getAvg(e){return 0===this.bitrateData[e].nSamples?0:Math.round(this.bitrateData[e].bitrateTotal/this.bitrateData[e].nSamples)}stopCapture(e){this.bitrateData[e].lastBytes=0,this.bitrateData[e].lastTimestamp=0}onBitrateSample(e,t){t>this.bitrateData[e].maxSample&&(this.bitrateData[e].maxSample=t),this.bitrateData[e].bitrateTotal+=t,this.bitrateData[e].nSamples++}captureAllocateBandwidth(e){if(e){const t=parseInt(e[e.length-1]);this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBW+=t,this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBWSamples+=1}}getAllocateBandwidthAvg(){const e=this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBW,t=this.bitrateData[Gi.MEDIA_DIRECTION.SEND].allocateBWSamples;if(e>0&&t>0)return Math.floor(e/t)}},YF=class{constructor(e,t){this.maxAppliedCapabilitiesCount=t,this.events=[],this.events.push({eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled})}setMaxCapabilitiesApplied(e){this.events.push({eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:e.error?`${e.error}`:"none"}),this.maxAppliedCapabilitiesCount&&this.events.length>this.maxAppliedCapabilitiesCount+1&&this.events.splice(1,1)}getEvents(){return this.events}},QF=class{constructor(e,t){this.configProvider=e,this.logger=t,this.resolutionChangeRequestRecords={},this.currentResolutionsByRid={},this.resolutionChangeCounterByRid={},this.events=[],this.errors=[]}setMaxCapabilitesRequested(e){const t=new YF(e,this.configProvider.config.webrtcLastAppliedVideoCapabilitiesCount);this.events.push({causeId:e.causeId,seq:t}),this.recordResolutionChange(e),this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.length>this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.shift()}setMaxCapabilitesApplied(e){const t=this.events.find((t=>t.causeId===e.causeId));t?(t.seq.setMaxCapabilitiesApplied(e),e.error&&this.errors.push(t)):this.logger.safe.warn(`Requested capabilities with id ${e.causeId} not found`)}getEvents(){return this.events.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getErrors(){return this.errors.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getResolutionRecords(){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo)return{req:this.resolutionChangeRequestRecords,count:this.resolutionChangeCounterByRid}}recordResolutionChange(e){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo){const t=Object.keys(this.currentResolutionsByRid),i=e=>e.rid||"default";[...t,...e.capabilities.map((e=>i(e)))].forEach((t=>{const n=e.capabilities.find((e=>i(e)===t)),r=this.currentResolutionsByRid[t]||0,s=n?.maxFs||0;if(r===s)return;this.resolutionChangeRequestRecords[t]||(this.resolutionChangeRequestRecords[t]=[],this.resolutionChangeCounterByRid[t]=0);const a=this.resolutionChangeRequestRecords[t].find((e=>e.from===r&&e.to===s));a?a.counter++:this.resolutionChangeRequestRecords[t].push({from:r,to:s,counter:1}),this.currentResolutionsByRid[t]=s,this.resolutionChangeCounterByRid[t]++}))}}},ZF=class{constructor(){this.delayCur=[],this.delayTotal=0,this.delayEventCount=0}analyzeDelay(e,t){if(t&&""!==t){this.delayCur.length===e&&this.delayCur.shift();const i=parseInt(t);this.delayCur.push(i),this.delayTotal+=i,this.delayEventCount+=Gi.TIME_INTERVAL.SEC_1}}getDelayCur(){if(this.delayCur.length>0){const e=this.delayCur.reduce(((e,t)=>e+t))/this.delayCur.length;return e<0?0:e}}getDelayAvg(){if(this.delayEventCount>0&&this.delayTotal>0){const e=this.delayTotal/this.delayEventCount;return e<0?0:e}}},XF=class{constructor(e,t){this.configProvider=e,this.startTime=t,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(Gi.HISTOGRAM_BATCH).forEach((e=>{this.receiveFreezeDurationCounts[e]=0,this.receiveFreezeDurationTimestamps[e]=[]}))}gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:n}){if(e){const r=parseInt(e[e.length-1],10),s=t?.length>0?parseInt(t[t.length-1],10):void 0;void 0!==i&&"ScreenShare"!==n&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&!this.configProvider.config.isRenderingBasedOnRawStatistics&&this.calculateBitrate(i,r),-1===this.recvTotalFreezeDuration&&(this.recvTotalFreezeDuration=0),r>0&&(this.mediaStarted=!0),0!==r&&0!==s||!this.mediaStarted?r>0&&(void 0===s||s>0)&&this.recvFreezeIsOngoing&&this.stopRecvDataGathering(!1):(this.recvFreezeIsOngoing||(this.recvCurrentFreezeStartTimestamp=Date.now()-this.startTime),this.recvFreezeIsOngoing=!0,this.recvCurrentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1,this.recvTotalFreezeDuration+=Gi.TIME_INTERVAL.SEC_1)}}getIsRendering(e){return this.recvCurrentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted}detectCaptureFreeze(e){if(e){const t=parseInt(e[e.length-1],10);this.previousInputFrame>0&&0===t&&(this.sendCameraFreezeIntervalsCount+=1),this.previousInputFrame=t}}getSendCameraFreezeIntervals(){return this.sendCameraFreezeIntervalsCount>0?this.sendCameraFreezeIntervalsCount:void 0}stopRecvDataGathering(e=!0){this.finalFreezeIsOngoing=this.recvFreezeIsOngoing,this.recvFreezeIsOngoing=!1,e&&(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(e){if(0===this.recvFreezeCount)return;const t={};return Object.keys(this.receiveFreezeDurationTimestamps).forEach((i=>{const n=this.receiveFreezeDurationTimestamps[i].length;t[i]=n>e?this.receiveFreezeDurationTimestamps[i].slice(n-e):this.receiveFreezeDurationTimestamps[i]})),JSON.stringify(t)}getRecvFreezeIsOngoing(e){return this.finalRecvCurrentFreezeDuration>=e&&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 e of Object.keys(Gi.HISTOGRAM_BATCH))if(this.recvCurrentFreezeDuration<=Gi.HISTOGRAM_BATCH[e]){this.receiveFreezeDurationCounts[e]+=1,this.receiveFreezeDurationTimestamps[e].push(this.recvCurrentFreezeStartTimestamp);break}this.recvCurrentFreezeStartTimestamp=0}populateLongestRecvFreezeDuration(){this.recvCurrentFreezeDuration>this.longestRecvFreezeDuration&&(this.longestRecvFreezeDuration=this.recvCurrentFreezeDuration)}calculateBitrate(e,t){const i=(e-this.lastBytesRecv)/125;this.lastBytesRecv=e,i<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}},eU=class{constructor(){this.mediaData={[Gi.MEDIA_DIRECTION.SEND]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0},[Gi.MEDIA_DIRECTION.RECV]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0}},this.gatheringSendData=!1}captureMediaData(e,t,i){const n=this.mediaData[e];if(e===Gi.MEDIA_DIRECTION.SEND&&(this.gatheringSendData=!0),t){const e=parseInt(t[t.length-1],10);n.totalFrameCount+=e}if(i){-1===n.totalMediaDuration&&(n.totalMediaDuration=0);const e=parseInt(i[i.length-1],10);n.mediaStarted||e>0&&(n.mediaStarted=!0,n.mediaStartTimestamp=new Date)}n.mediaStarted&&(n.totalMediaDuration+=Gi.TIME_INTERVAL.SEC_1)}captureFrameRate(e){const t=this.mediaData[Gi.MEDIA_DIRECTION.SEND];if(e){const i=parseInt(e[e.length-1],10);t.cameraFrameRate+=i}}stopRecvDataGathering(){const e=this.mediaData[Gi.MEDIA_DIRECTION.RECV],t=(new Date).getTime();e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t-e.mediaStartTimestamp.getTime())/1e3):0,e.mediaStarted=!1}isGatheringSendData(){return this.gatheringSendData}stopSendDataGathering(){const e=this.mediaData[Gi.MEDIA_DIRECTION.SEND],t=new Date;e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t.getTime()-e.mediaStartTimestamp.getTime())/1e3):0,this.gatheringSendData=!1,e.mediaStarted=!1}getAvgFrameRate(e){const t=this.mediaData[e];if(t.totalMediaDuration>0&&t.totalFrameCount>0)return t.totalFrameCount/t.totalMediaDuration}getTotalDuration(e){const t=this.mediaData[e];return t.totalMediaDuration>=0?t.totalMediaDuration:void 0}getTimeSinceLastDecode(e){const t=this.mediaData[e];return t.timeSinceLastDecode>0?t.timeSinceLastDecode:void 0}getSendCameraFramerate(){const e=this.mediaData[Gi.MEDIA_DIRECTION.SEND];if(e.totalMediaDuration>0)return e.cameraFrameRate/e.totalMediaDuration}},tU={fs:0,fps:1},iU=class{constructor(e){this.logger=e,this.allowed=new Map,this.lastParams=new Map,this.currentEvents=new Map,this.finishedEvents=[]}setMaxCapabilities(e){e.forEach((e=>{if(e.ssrc||0===e.ssrc){this.finishIfActive(e.ssrc),this.allowed.set(e.ssrc,{fs:e.maxFs+tU.fs,fps:e.maxFps+tU.fps});const t=this.lastParams.get(e.ssrc);t&&this.setCurrentParams(e.ssrc,t.fs,t.fps)}}))}setCurrentParams(e,t,i){this.lastParams.set(e,{fs:t,fps:i});const n=this.getAllowedParams(e);n&&(t>n.fs||i>n.fps)?(this.captureOvershoot(e,i,n.fps,"fps"),this.captureOvershoot(e,t,n.fs,"fs")):n&&this.finishIfActive(e)}flush(){this.currentEvents.forEach(((e,t)=>this.finishIfActive(t)))}getEvents(){const e=[...nn(this.finishedEvents)],t=Date.now();return this.currentEvents.forEach((i=>i.forEach((i=>e.push({ssrc:i.ssrc,timestamp:i.timestamp,duration:t-i.timestamp,overshootType:i.overshootType,amount:i.amount}))))),e}captureOvershoot(e,t,i,n){const r=this.currentEvents.get(e)||[],s=r.findIndex((e=>e.overshootType===n)),a=r[s],o=t-i,l=tU[n];o<=l&&a?(a.duration=Date.now()-a.timestamp,this.finishedEvents.push(a),this.logger.debug(`stopped overshooting ${n} by ${a.amount}`),r.splice(s,1)):o>l&&!a?(this.logger.safe.info(`overshooting ${n} by ${t-i}`),r.push({ssrc:e,timestamp:Date.now(),duration:-1,overshootType:n,amount:{min:o,max:o}})):o>l&&a&&(a.amount={min:Math.min(a.amount.min,o),max:Math.max(a.amount.max,o)}),r.length?this.currentEvents.set(e,r):this.currentEvents.has(e)&&this.currentEvents.delete(e)}getAllowedParams(e){return this.allowed.get(e)||this.allowed.get(0)}finishIfActive(e){const t=this.currentEvents.get(e);if(t){const i=Date.now();t.forEach((t=>{t.duration=i-t.timestamp,this.finishedEvents.push(t),this.logger.debug(`finished overshooting ${t.overshootType} by min:${t.amount.min} max:${t.amount.max} for ${t.duration}ms for ssrc ${e}`)})),this.currentEvents.delete(e)}}},nU=class{constructor(){this.qpData={[Gi.MEDIA_DIRECTION.SEND]:{frames:0,qpSum:0},[Gi.MEDIA_DIRECTION.RECV]:{frames:0,qpSum:0}}}captureQpData(e,t,i){const n=this.qpData[e];if(i&&i.length>0){const e=parseInt(i[i.length-1],10);e>0&&(n.frames=e)}if(t){const e=parseInt(t,10);e>0&&(n.qpSum=e)}}getQpAverage(e){const t=this.qpData[e];if(t.qpSum>0&&t.frames>0)return t.qpSum/t.frames}},rU=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(e){e&&e.width&&e.height&&(this.isResolutionChanged(this.lastResolution,e)&&this.resolutionChanged(e),this.updateResolutionDuration(this.getResolutionKey(e),this.resDurations)),this.lastPreferredResolution&&this.updatePreferredResolutionDurations()}capturePreferredResolution(e,t){const i=this.getResolutionKey(e);this.preferredResolution.includes(i)||(this.preferredResolutions.length>=t&&this.preferredResolutions.shift(),this.preferredResolutions.push(i)),this.isResolutionChanged(this.lastPreferredResolution,e)&&(this.preferredResolutionChanged(e),this.updatePreferredResolutionDurations())}getResolutionKey(e){return`${e.width}x${e.height}`}isResolutionChanged(e,t){return!e||e.width!==t.width||e.height!==t.height}countResolutionDurationRatio(e){const t={};let i=0;for(const t in e)i+=e[t];for(const n in e)t[n]=mn(e[n]/i*100,2);return t}updatePreferredResolutionDurations(){this.updateResolutionDuration(this.getResolutionKey(this.lastPreferredResolution),this.preferredResolutionDurations)}updateResolutionDuration(e,t){t[e]||(t[e]=0),t[e]++}preferredResolutionChanged(e){this.lastPreferredResolution=e}resolutionChanged(e){this.lastResolution=e,this.resolutionChangedCount++}},sU=class{constructor(){this.streamsTimers={}}countRecvStreams(e){const t=`${e}`;this.streamsTimers.hasOwnProperty(t)||(this.streamsTimers[t]=0),this.streamsTimers[t]++}getStreamCounts(){const e={min:void 0,max:void 0,mode:void 0},t=Object.keys(this.streamsTimers).map(Number);return 0===t.length||1===t.length&&0===t[0]||(e.min=Math.min(...t.filter((e=>e>0))),e.max=Math.max(...t),e.mode=t.reduce(((e,t)=>this.streamsTimers[t]>this.streamsTimers[e]?t:e),t[0])),e}},aU=class{constructor(e){this.configProvider=e,this.subscriptionEvents=[],this.subscriptionCounters={attempted:0,subscribed:0,unsubscribed:0,failed:0}}addSubscriptionEvent(e){switch(this.subscriptionEvents.length>this.configProvider.config.webrtcSubscriptionEventLimit&&this.subscriptionEvents.shift(),this.subscriptionEvents.push(e),e.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}},oU=class{constructor(e,t,i,n="Video"){this.startTime=e,this.configProvider=t,this.logger=i,this.mediaType=n,this.subscriptionCounter=0,this.videoFreezeTelemetry=new XF(this.configProvider,this.startTime),this.videoDelayTelemetry=new ZF,this.videoSubscriptionEvents=new aU(this.configProvider),this.videoQPEvents=new nU,this.videoResolutionTelemetry=new rU,this.videoGeneralTelemetry=new eU,this.videoStreamsCounters=new sU,this.videoBitrate=new JF,this.videoMaxCapabilities=new QF(this.configProvider,this.logger),this.videoOvershoot=new iU(this.logger),this.videoQualityLimitations=new KF(this.configProvider),this.videoStatsOnSubscribed=new uF(this.configProvider),this.videoResolutionSwitchTracker=new aD(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(e){this.currentTrackId=e}get isRecvDataGatheringEnabled(){return this.subscriptionCounter>0}startStopRecvDataGathering(e){this.logger.safe.info("Receive data gathering is "+(e?"enabled":"disabled")),e?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(Gi.MEDIA_DIRECTION.RECV)}isSendGathering(){return this.videoGeneralTelemetry.isGatheringSendData()}stopSendGathering(){this.videoGeneralTelemetry.stopSendDataGathering(),this.videoBitrate.stopCapture(Gi.MEDIA_DIRECTION.SEND),this.videoOvershoot.flush()}gatherRecvFreezeData(e,t,i){this.videoFreezeTelemetry.gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:this.mediaType})}detectCaptureFreeze(e){this.videoFreezeTelemetry.detectCaptureFreeze(e)}getRecvFreezeDurationCounts(){return this.videoFreezeTelemetry.getRecvFreezeDurationCounts()}getRecvFreezeDurationTimestamps(){return this.videoFreezeTelemetry.getRecvFreezeDurationTimestamps(this.configProvider.config.maxVideoFreezeTimestampsInBucket)}getRecvTotalFreezeDuration(){return this.videoFreezeTelemetry.getRecvTotalFreezeDuration()}setRecvTotalFreezeDurationMs(e){this.recvTotalFreezeDurationMs=void 0!==e?this.recvTotalFreezeDurationMs+=e:void 0}analyzeDelay(e,t){this.videoDelayTelemetry.analyzeDelay(e,t)}getDelayCur(){return this.videoDelayTelemetry.getDelayCur()}getDelayAvg(){return this.videoDelayTelemetry.getDelayAvg()}addSubscriptionEvent(e){this.videoSubscriptionEvents.addSubscriptionEvent(e)}getSubscriptionEvents(){return this.videoSubscriptionEvents.getSubscriptionEvents()}getSubscriptionCounters(){return this.videoSubscriptionEvents.getSubscriptionCounters()}captureQpData(e,t,i){this.videoQPEvents.captureQpData(e,t,i)}getQpAverage(e){return this.videoQPEvents.getQpAverage(e)}captureMediaData(e,t,i){this.videoGeneralTelemetry.captureMediaData(e,t,i)}getIsRendering(){const e=this.configProvider.config.notRenderingTimeInterval["Video"===this.mediaType?"video":"sharing"];return this.videoFreezeTelemetry.getIsRendering(e)}captureFrameRate(e){this.videoGeneralTelemetry.captureFrameRate(e)}getTotalDuration(e){return this.videoGeneralTelemetry.getTotalDuration(e)}captureResolutionSample(e){this.videoResolutionTelemetry.captureSample(e)}countRecvStreams(e){this.videoStreamsCounters.countRecvStreams(e)}captureBitrateSample(e,t){this.videoBitrate.captureSample(e,t)}captureAllocateBandwidth(e){this.videoBitrate.captureAllocateBandwidth(e)}capturePreferredResolution(e,t){this.videoResolutionTelemetry.capturePreferredResolution(e,t)}setMaxCapabilitesRequested(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesRequested(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}setMaxCapabilitesApplied(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesApplied(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}getMaxCapabilitiesEvents(){const e=this.videoMaxCapabilities.getEvents();return JSON.stringify(e)}getMaxCapabilitiesResolutionChanges(){const e=this.videoMaxCapabilities.getResolutionRecords();return e?JSON.stringify(e):""}getMaxCapabilitiesErrors(){const e=this.videoMaxCapabilities.getErrors();return e?JSON.stringify(e):""}setCurrentParameters(e,t,i){this.videoOvershoot.setCurrentParams(e,t.height/16*(t.width/16),i)}setMaxCapabilitiesOvershoot(e){this.videoOvershoot.setMaxCapabilities(e)}getOvershootEvents(){let e=this.videoOvershoot.getEvents();return e=e.slice(Math.max(0,e.length-(this.configProvider.config.maxReportedOvershootingEvents+1)),e.length),e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify(e)}getOvershootTotalDurations(){const e=this.videoOvershoot.getEvents();return e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify({fs:e.reduce(((e,t)=>"fs"===t.overshootType?e+t.duration:e),0),fps:e.reduce(((e,t)=>"fps"===t.overshootType?e+t.duration:e),0)})}setQualityLimitationReason(e){this.videoQualityLimitations.setQualityLimitationReason(e)}getQualityLimitationReasonEvents(){return this.videoQualityLimitations.getQualityLimitationReasonEvents()}captureTimeToFirstFrame(e,t){-1!==e&&(this.timeToFirstFrame=e,this.timeToFirstFrameSinceSubscriptionStart=t)}getTimeToFirstFrame(){return this.timeToFirstFrame}setIsRendering(e){Sn(this.isRenderingEvents,{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.telemetryLimits.numIsRenderingEvents)}setMsi(e){this.msi=e}setLocalMsi(e){this.localMsi=e}prepareCollectingStatsOnSubscribed(e){this.videoStatsOnSubscribed.prepareCollectingStatsOnSubscribed(e)}captureStatsOnSubscribed(e,t){this.videoStatsOnSubscribed.captureStatsOnSubscribed(e,t)}calculateResolutinSwitches(e,t){this.videoResolutionSwitchTracker.captureSample(e,t)}getReport(e,t,i=!1){const n={};if(n[t+"DurationSeconds"]=this.getTotalDuration(e),n[t+"QpAvg"]=this.getQpAverage(e),n[t+"frameRateAvg"]=this.videoGeneralTelemetry.getAvgFrameRate(e),n[t+"bitrateAvg"]=this.videoBitrate.getAvg(e),n[t+"bitrateMax"]=this.videoBitrate.getMax(e),e===Gi.MEDIA_DIRECTION.SEND)n[t+"DelayCur"]=this.getDelayCur(),n[t+"DelayAvg"]=this.getDelayAvg(),n[t+"TimeSinceLastEncodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"AllocateBWAvg"]=this.videoBitrate.getAllocateBandwidthAvg(),n[t+"CaptureFramerateAvg"]=this.videoGeneralTelemetry.getSendCameraFramerate(),n[t+"FreezeIntervals"]=this.videoFreezeTelemetry.getSendCameraFreezeIntervals(),n[t+"MaxCapabilities"]=i?"":this.getMaxCapabilitiesEvents(),n[t+"MaxCapabilitiesErrors"]=i?"":this.getMaxCapabilitiesErrors(),n[t+"OvershootEvents"]=this.getOvershootEvents(),n[t+"OvershootDurations"]=this.getOvershootTotalDurations(),n[t+"qualityLimitationReasonEvents"]=JSON.stringify(this.getQualityLimitationReasonEvents()),n[t+"MaxCapabilitiesResolutions"]=this.getMaxCapabilitiesResolutionChanges(),n[t+"ResolutionsSwitches"]=this.videoResolutionSwitchTracker.switches?JSON.stringify(this.videoResolutionSwitchTracker.switches):"";else if(e===Gi.MEDIA_DIRECTION.RECV){n[t+"TimeSinceLastDecodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"FreezeHistogram"]=this.getRecvFreezeDurationCounts(),n[t+"FreezeTimestamps"]=this.getRecvFreezeDurationTimestamps(),n[t+"LongestFreezeDuration"]=this.videoFreezeTelemetry.getLongestRecvFreezeDuration(),n[t+"RecvAvgFreezeDuration"]=this.videoFreezeTelemetry.getRecvAvgFreezeDuration(),n[t+"TotalFreezeDuration"]=this.getRecvTotalFreezeDuration(),n[t+"TotalFreezeDurationMs"]=this.recvTotalFreezeDurationMs,n[t+"OngoingFreeze"]=this.videoFreezeTelemetry.getRecvFreezeIsOngoing(this.configProvider.config.webrtcEndOfCallFreezeThreshold),n[t+"NumResolutionSwitches"]=this.videoResolutionTelemetry.resolutionSwitchCount,n[t+"PreferredResolution"]=this.videoResolutionTelemetry.preferredResolution,n[t+"PreferredResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.preferredResolutionDurationRatios),n[t+"ResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.resolutionDurationRatios);const i=this.videoStreamsCounters.getStreamCounts();n[t+"StreamsMin"]=i.min,n[t+"StreamsMax"]=i.max,n[t+"StreamsMode"]=i.mode,n[t+"TimeToFirstFrame"]=this.timeToFirstFrame,n[t+"TimeToFirstFrameSinceSubscriptionStart"]=this.timeToFirstFrameSinceSubscriptionStart,n[t+"LocalMsi"]=this.localMsi,n[t+"Msi"]=this.msi,n[t+"isRenderingEvents"]=JSON.stringify(this.isRenderingEvents),n[t+"statsOnSubscribed"]=JSON.stringify(this.videoStatsOnSubscribed.videoStatsOnSubscribed)}return n}},lU=Symbol("mslbase"),cU=Symbol("mslsamples"),dU=class{constructor(e,t){this.logger=e,this.configProvider=t,this.currentLayouts={},this.collectedModalitySessions=[],this.startTimestamp=Date.now()}get collectedSessions(){return this.collectedModalitySessions}get highestFidelitySSRC(){if(!this.currentModalitySession)return;let e;for(const t in this.currentLayouts)e=this.getHigherFidelitySSRC(t,e);return parseInt(e)}processStats(e){const t=Object.values(e.ssrc??{}).filter((e=>e.rid&&e.ssrc&&e.googFrameHeightInput&&this.lastMaxCapabilitiesEvent?.capabilities.some((t=>t.rid===e.rid)))),i=new Map(t.map((e=>[`${e.ssrc}`,e.rid])));for(const e in this.currentLayouts)i.has(e)||this.collectLayout(e);!this.currentModalitySession&&i.size>0&&(this.currentModalitySession={timestamp:Date.now()-this.startTimestamp,duration:0,numLayouts:0,layouts:[]},this.logger.safe.info("Modality session started")),t.forEach((e=>{this.currentLayouts[`${e.ssrc}`]||this.addLayout(e)})),0===i.size&&this.currentModalitySession&&this.collectSession(),t.forEach((e=>this.processLayoutData(e)))}setMaxCapabilities(e,t){if(this.lastMaxCapabilitiesEvent=e,Object.keys(this.currentLayouts).length)for(const i of e.capabilities){const n=Object.values(this.currentLayouts).find((e=>e.rid===i.rid));n&&(t?(Sn(n.fmtp,{...i,timestamp:Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-n.timestamp,causeId:e.causeId},this.configProvider.config.simulcastTelemetryNumFMTP),n.gatherer.setMaxCapabilitesApplied(e)):n.gatherer.setMaxCapabilitesRequested(e),n.gatherer.setMaxCapabilitiesOvershoot([i]))}}finish(){this.logger.safe.info("Finishing statistics gathering");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession&&this.collectSession()}addLayout(e){const t=`${e.ssrc}`,i=e.rid,n=this.lastMaxCapabilitiesEvent?.capabilities.find((e=>e.rid===i));this.logger.safe.info(`Adding layout for ssrc ${t} rid ${i}`);const r=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,s=new oU(r,this.configProvider,this.logger.createChild(`Telemetry#${t}`));this.currentLayouts[t]={ssrc:e.ssrc,rid:i,fmtp:[{...n,timestamp:r,causeId:this.lastMaxCapabilitiesEvent?.causeId}],timestamp:r,duration:0,gatherer:s,[lU]:{firCount:e.googFirsReceived,nackCount:e.googNacksReceived,pliCount:e.googPlisReceived,framesEncoded:e.framesEncoded,bytesSent:e.bytesSent,packetsSent:e.packetsSent,packetsLost:e.packetsLost,qpSum:e.qpSum},[cU]:{firCount:[],nackCount:[],pliCount:[],framesEncoded:[],bytesSent:[],packetsSent:[],packetsLost:[],qpSum:[],frameHeightInput:[],frameHeightSent:[],frameRateInput:[],frameRateSent:[]}},s.setMaxCapabilitiesOvershoot([n]),this.currentModalitySession.numLayouts++}processLayoutData(e){const t=`${e.ssrc}`,i=this.currentLayouts[t];this.processMediaStats(i,e),i.gatherer.captureMediaData(Gi.MEDIA_DIRECTION.SEND,[String(e.googFrameRateSent)],[String(e.framesEncoded)]),i.gatherer.captureFrameRate([String(e.googFrameRateInput)]),i.gatherer.captureQpData(Gi.MEDIA_DIRECTION.SEND,String(e.qpSum),[String(e.framesEncoded)]),i.gatherer.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,e.bytesSent),i.gatherer.detectCaptureFreeze([String(e.googFrameRateInput)]),i.gatherer.setCurrentParameters(e.ssrc,{width:e.googFrameWidthSent,height:e.googFrameHeightSent},e.googFrameRateSent)}processMediaStats(e,t){const i=e[lU],n=t.googFirsReceived-i.firCount,r=t.googNacksReceived-i.nackCount,s=t.googPlisReceived-i.pliCount,a=t.framesEncoded-i.framesEncoded,o=t.bytesSent-i.bytesSent,l=t.packetsSent-i.packetsSent,c=t.packetsLost-i.packetsLost,d=t.qpSum-i.qpSum,u=e[cU],h=this.configProvider.config.webrtcStatStoredRecordsNumber;Sn(u.firCount,n,h),Sn(u.nackCount,r,h),Sn(u.pliCount,s,h),Sn(u.framesEncoded,a,h),Sn(u.bytesSent,o,h),Sn(u.packetsSent,l,h),Sn(u.packetsLost,c,h),Sn(u.qpSum,d,h),Sn(u.frameHeightInput,t.googFrameHeightInput,h),Sn(u.frameHeightSent,t.googFrameHeightSent,h),Sn(u.frameRateInput,t.googFrameRateInput,h),Sn(u.frameRateSent,t.googFrameRateSent,h)}collectLayout(e){this.logger.safe.info(`Collecting layout for ssrc ${e}`),this.currentLayouts[e].duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-this.currentLayouts[e].timestamp,this.currentLayouts[e].gatherer.isSendGathering()&&this.currentLayouts[e].gatherer.stopSendGathering();const t=this.currentLayouts[e].gatherer.getReport(Gi.MEDIA_DIRECTION.SEND,"",!1);for(const i in t)this.currentLayouts[e][i]=t[i];for(const t in this.currentLayouts[e][cU])this.currentLayouts[e][t]=Pn(this.currentLayouts[e][cU][t],(e=>e));delete this.currentLayouts[e].gatherer,Sn(this.currentModalitySession.layouts,this.currentLayouts[e],this.configProvider.config.simulcastTelemetryLayoutsPerSession),delete this.currentLayouts[e]}collectSession(){this.logger.safe.info("Collecting session");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession.duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,Sn(this.collectedModalitySessions,this.currentModalitySession,this.configProvider.config.simulcastTelemetryNumModalitySessions),this.currentModalitySession=void 0,this.lastMaxCapabilitiesEvent=void 0}getHigherFidelitySSRC(e,t){if(!e||!t)return e||t;const[i]=this.currentLayouts[e].fmtp.slice(-1),[n]=this.currentLayouts[t].fmtp.slice(-1);return(i?.maxMbps??0)>0&&(n?.maxMbps??0)>0?i.maxMbps>n.maxMbps?e:t:e||t}},uU=["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"],hU=["bytesSent","bytesReceived","googRtt","packetsSent","requestsSent","consentRequestsSent","responsesSent","requestsReceived","responsesReceived"],gU=["googAvailableReceiveBandwidth","googAvailableSendBandwidth","googTransmitBitrate"];function pU(e,t,i){const n=i.value;i.value=function(...e){try{return n.apply(this,e)}catch(e){this.processStatsError(t,e)}}}var mU=class{constructor(e,t,i,n,r,s){this.logger=e,this.sessionInfo=t,this.configProvider=i,this.mediaManager=n,this.multiparty=r,this.newStatsApi=s,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 HF(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 kL(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 oU(this.extensions.StartTime,this.configProvider,this.logger.createChild("Video"),"Video"),this.sharingTelemetry=new oU(this.extensions.StartTime,this.configProvider,this.logger.createChild("Sharing"),"ScreenShare"),this.bandwidthTelemetry=new $F(this.configProvider.config.webrtcBWJumpLowerLimit,this.configProvider.config.webrtcBWJumpUpperLimit),this.stabilizationTelemetry=new fF(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wp),this.storedRecordsNumber=Number(this.configProvider.config.webrtcStatStoredRecordsNumber),this.hwSilentDetectionDuration=Number(this.configProvider.config.webrtcStatHwSilentDetectionDuration),this.hwSilentDetectionLevel=Number(this.configProvider.config.webrtcStatHwSilentDetectionLevel),this.audioHealedRatioTelemetry=new VF(this.configProvider),this.networkQualityTelemetry=new WF(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 dU(this.logger.createChild("simulcastVideo"),this.configProvider),this.simulcastSharing=new dU(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(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.cameraOpenResolution=t.resolution)}}onMaxCapabilitiesRequested(e){(e.modality===Gi.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesRequested(e),(e.modality===Gi.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!1)}onMaxCapabilitiesApplied(e){(e.modality===Gi.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesApplied(e),(e.modality===Gi.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!0)}setSubscribedTrackIds(e){this.subscribedTrackIds=e||[]}setSubscribedTrackSsrc(e){this.subscribedTrackSsrc=e||[]}addSubscriptionEvent(e,t,i,n,r,s,a){const o={evt:e,ts:Date.now()-this.extensions.StartTime,msi:i,localMsi:n,duration:s};r&&(o.error=tt(r));const l=this.getHandlerForModality(t);if(l.addSubscriptionEvent(o),a&&this.setMSIDsPair(i,n,a),1===e||3===e){const t=1===e;l.startStopRecvDataGathering(t)}2===e&&l.prepareCollectingStatsOnSubscribed(i)}setMSIDsPair(e,t,i){const n=`ssrc_${i.replace(/\D/g,"")}_recv`;this.MSIDsPairs[n]={msi:e,localMsi:t}}getHandlerForModality(e){switch(e){case Gi.MODALITY.video:return this.videoTelemetry;case Gi.MODALITY.sharing:return this.sharingTelemetry;default:throw new Error(`Handler not found for modality: ${e}`)}}setTerminated(){this.extensions.EndTime=(new Date).getTime(),this.terminated=!0}startWaitingForStreamStart(e){this.streamStartDetection||this.sessionInfo.setOfferedModalities(e),this.streamStartDetection=!0}processStatsDict(e){if(this.processSimulcastStats(e),this.constructWebRtcReportForSingleStream(this.extensions.WebRTCStats,e),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,e),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 t=this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]?this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]:{};this.constructWebRtcReportForMultipleStreams(t,e);for(const e of Object.keys(t)){const i=t[e];this.processVideoStatsRecv(this.multiViewVideoTelemetry[e],i)}this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]=t}this.extensions.WebRTCStats.statsErrors=JSON.stringify(this.statsErrors)}setTimeToFirstFrame(e,t,i){i in this.timeToFirstFrame||(this.timeToFirstFrame[i]=e,this.timeToFirstFrameSinceSubscriptionStart[i]=t)}getCurrentTimeToFirstFrame(e){return this.timeToFirstFrame[e]?this.timeToFirstFrame[e]:-1}getCurrentTimeToFirstFrameSinceSubscriptionStart(e){return this.timeToFirstFrameSinceSubscriptionStart[e]?this.timeToFirstFrameSinceSubscriptionStart[e]:-1}getVideoTelemetryBySsrc(e){let t;return this.extensions.WebRTCStats.ssrc_video_recv&&this.extensions.WebRTCStats.ssrc_video_recv.id===e?t=this.videoTelemetry:this.extensions.WebRTCStats.ssrc_sharing_recv&&this.extensions.WebRTCStats.ssrc_sharing_recv.id===e?t=this.sharingTelemetry:this.isMultiViewVideoTelemetry&&(t=this.multiViewVideoTelemetry[e]),t}getIsRendering(e){const t=this.getVideoTelemetryBySsrc(e);return t?t.getIsRendering():void 0}setFreezeDuration(e,t){for(const i of Object.keys(this.multiViewVideoTelemetry))this.multiViewVideoTelemetry[i].trackId===t&&this.isSubscribed(t)&&this.multiViewVideoTelemetry[i].setRecvTotalFreezeDurationMs(e);this.currentSharingRecvTrackId===t&&this.isSubscribed(t)&&this.sharingTelemetry.setRecvTotalFreezeDurationMs(e),this.currentVideoRecvTrackId===t&&this.isSubscribed(t)&&this.videoTelemetry.setRecvTotalFreezeDurationMs(e)}addVideoControlMessage(e){this.totalVideoControlMessages++,e&&this.outOfOrderVideoControlMessages++}setStreamSenderStarted(e,t){this.streamSenderStarted[e]=t}addReportedReceiveBandwidth(e){this.limitCaptureAmount(this.extensions,"ReportedReceiveBandwidth",e)}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(e){this.simulcastVideo.processStats(e),this.simulcastSharing.processStats(e)}processBandwidthStats(){const e=this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth;if(e){const t=this.streamSenderStarted.Video||this.streamSenderStarted.ScreenShare;this.bandwidthTelemetry.recordSendBandwidth(e[e.length-1]),this.stabilizationTelemetry.processBandwidth(parseInt(e[e.length-1]),this.sessionInfo.activeModalities,t)}}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,UF.last)(this.extensions.WebRTCStats.ssrc_audio_recv.googJitterBufferMs)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.jitter&&this.audioTelemetry.captureJitter((0,UF.last)(this.extensions.WebRTCStats.ssrc_audio_recv.jitter)),this.extensions.WebRTCStats.ssrc_audio_send?.googRtt){const e=this.extensions.WebRTCStats.ssrc_audio_send.googRtt;this.audioTelemetry.captureRtt(e[e.length-1])}}stopGatheringIfNeeded(e,t,i,n){const r=`${t}${i}`;n!==this.lastSSRCs.get(r)&&(this.lastSSRCs.set(r,n),t===Gi.MEDIA_DIRECTION.SEND?e.stopSendGathering():e.stopRecvGathering())}processVideoStatsSend(e,t){t&&Wp(this.sessionInfo.activeModalities.video)?(this.stopGatheringIfNeeded(e,Gi.MEDIA_DIRECTION.SEND,"Video",t.ssrc),e.captureMediaData(Gi.MEDIA_DIRECTION.SEND,t.googFrameRateSent,t.framesEncoded),e.captureFrameRate(t.googFrameRateInput),e.analyzeDelay(this.videoDelayTimePeriod,t.googAvgEncodeMs),e.captureQpData(Gi.MEDIA_DIRECTION.SEND,t.qpSum,t.framesEncoded),e.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,this.getLastSampleInt(t.bytesSent)),e.detectCaptureFreeze(t.googFrameRateInput),e.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),e.setCurrentParameters(parseInt(t.ssrc),{width:this.getLastSampleInt(t.googFrameWidthSent),height:this.getLastSampleInt(t.googFrameHeightSent)},this.getLastSampleInt(t.googFrameRateSent)),e.setQualityLimitationReason(t.qualityLimitationReason),this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo&&e.calculateResolutinSwitches(this.getLastSampleInt(t.googFrameWidthSent),this.getLastSampleInt(t.googFrameHeightSent))):e.isSendGathering()&&(e.stopSendGathering(),this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.SEND}Video`))}processVideoStatsRecv(e,t,i=!1){t&&Kp(this.sessionInfo.activeModalities.video)&&this.videoTelemetry.isRecvDataGatheringEnabled?(i&&this.stopGatheringIfNeeded(e,Gi.MEDIA_DIRECTION.RECV,"Video",t.ssrc),e.trackId=t.googTrackId,e.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived,this.getLastSampleInt(t.bytesReceived)),e.captureMediaData(Gi.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),e.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),e.captureQpData(Gi.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),e.captureBitrateSample(Gi.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),e.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),e.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):i&&this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.RECV}Video`)}processSharingStats(){const e=this.extensions.WebRTCStats.ssrc_sharing_send,t=this.extensions.WebRTCStats.ssrc_sharing_recv;e&&Wp(this.sessionInfo.activeModalities.sharing)?(this.stopGatheringIfNeeded(this.sharingTelemetry,Gi.MEDIA_DIRECTION.SEND,"Sharing",e.ssrc),this.sharingTelemetry.captureMediaData(Gi.MEDIA_DIRECTION.SEND,e.googFrameRateSent,e.framesEncoded),this.sharingTelemetry.captureFrameRate(e.googFrameRateInput),this.sharingTelemetry.analyzeDelay(this.videoDelayTimePeriod,e.googAvgEncodeMs),this.sharingTelemetry.captureQpData(Gi.MEDIA_DIRECTION.SEND,e.qpSum,e.framesEncoded),this.sharingTelemetry.captureBitrateSample(Gi.MEDIA_DIRECTION.SEND,this.getLastSampleInt(e.bytesSent)),this.sharingTelemetry.detectCaptureFreeze(e.googFrameRateInput),this.sharingTelemetry.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),this.sharingTelemetry.setCurrentParameters(parseInt(e.ssrc),{width:this.getLastSampleInt(e.googFrameWidthSent),height:this.getLastSampleInt(e.googFrameHeightSent)},this.getLastSampleInt(e.googFrameRateSent)),this.limitCaptureAmount(this.extensions,"Sharing_send_RawInputVolume",this.audioTelemetry.getInputLevel("ScreenShare"))):this.sharingTelemetry.isSendGathering()&&(this.sharingTelemetry.stopSendGathering(),this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.SEND}Sharing`)),t&&Kp(this.sessionInfo.activeModalities.sharing)&&this.sharingTelemetry.isRecvDataGatheringEnabled?(this.stopGatheringIfNeeded(this.sharingTelemetry,Gi.MEDIA_DIRECTION.RECV,"Sharing",t.ssrc),this.sharingTelemetry.trackId=t.googTrackId,this.sharingTelemetry.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived),this.sharingTelemetry.captureMediaData(Gi.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),this.sharingTelemetry.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),this.sharingTelemetry.captureQpData(Gi.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),this.sharingTelemetry.captureBitrateSample(Gi.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),this.sharingTelemetry.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),this.sharingTelemetry.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):this.lastSSRCs.delete(`${Gi.MEDIA_DIRECTION.RECV}Sharing`)}processStreamsCounters(){const e=this.extensions.WebRTCStats.recvCounters;e&&(this.videoTelemetry.countRecvStreams(e[Gi.MODALITY.video]),this.sharingTelemetry.countRecvStreams(e[Gi.MODALITY.sharing]))}setMissedInitialPreferredResolution(){qi(this.missedInitialPreferredResolution,((e,t)=>{this.setPreferredResolution(t,e)})),this.missedInitialPreferredResolution={}}setPreferredResolution(e,t,i){if((i===Gi.MEDIA_TYPE.video&&!this.currentVideoRecvTrackId||i===Gi.MEDIA_TYPE.sharing&&!this.currentSharingRecvTrackId)&&(this.missedInitialPreferredResolution[e]=t),this.currentVideoRecvTrackId===e&&this.videoTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.currentSharingRecvTrackId===e&&this.sharingTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.isMultiViewVideoTelemetry){const i=this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(e)];i&&i.capturePreferredResolution(t,this.maxStoredPreferredResolutions)}}setIsRendering(e,t,i){t===Gi.MEDIA_TYPE.video&&this.videoTelemetry.setIsRendering(e),t===Gi.MEDIA_TYPE.sharing&&this.sharingTelemetry.setIsRendering(e),this.isMultiViewVideoTelemetry&&this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(i)]?.setIsRendering(e)}setMaxSessionBandwidth(e){this.extensions.MaxSessionBandwidth=e}isSubscribed(e,t){let i=this.subscribedTrackIds.some((t=>t===e));return!i&&this.configProvider.config.subscribeToSsrcForVideo&&(i=this.subscribedTrackSsrc.some((e=>e===`${t}`))),i||!this.multiparty&&this.configProvider.config.subscribeToSsrcForVideo}getReport(e=!1,t=!1){try{t&&this.resetPairValues(),e||(this.videoTelemetry.stopDataGathering(),this.sharingTelemetry.stopDataGathering());const i=this.videoTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.RECV),n=this.videoTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.SEND),r=this.sharingTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.RECV),s=this.sharingTelemetry.getTotalDuration(Gi.MEDIA_DIRECTION.SEND);if(i>=0&&(qi(this.videoTelemetry.getReport(Gi.MEDIA_DIRECTION.RECV,"Video_recv_",t),((e,t)=>this.extensions[t]=e)),!Xi(this.multiViewVideoTelemetry))){const e=[];for(const i of Object.keys(this.multiViewVideoTelemetry)){const n={id:i};qi(this.multiViewVideoTelemetry[i].getReport(Gi.MEDIA_DIRECTION.RECV,"Video",t),((e,t)=>{void 0!==e&&(n[t]=e)})),e.push(n)}this.extensions[Gi.MULTIPLE_RECV_STREAMS]=JSON.stringify(e)}r>=0&&qi(this.sharingTelemetry.getReport(Gi.MEDIA_DIRECTION.RECV,"Sharing_recv_",t),((e,t)=>this.extensions[t]=e)),n>=0&&(qi(this.videoTelemetry.getReport(Gi.MEDIA_DIRECTION.SEND,"Video_send_",t),((e,t)=>this.extensions[t]=e)),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),s>=0&&qi(this.sharingTelemetry.getReport(Gi.MEDIA_DIRECTION.SEND,"Sharing_send_",t),((e,t)=>this.extensions[t]=e)),e||t||(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=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionEvents()),this.extensions.Video_SubscriptionCounters=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionCounters()),this.extensions.Sharing_SubscriptionEvents=t?"":JSON.stringify(this.sharingTelemetry.getSubscriptionEvents()),this.extensions.Sharing_SubscriptionCounters=t?"":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 e of Object.keys(this.extensions))void 0===this.extensions[e]&&delete this.extensions[e];return delete this.extensions.WebRTCStats[Gi.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),nn(this.report)}catch(e){throw this.processStatsError("Report",e),{error:e,partialReport:nn(this.report)}}}getAudioHwSilent(){return this.hwSilent}getSpeakingState(){return this.isSpeaking}getNetworkSendLevel(){return this.networkSendLevel}getNetworkRecvLevel(){return this.networkRecvLevel}addIceCandidateError(e){this.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.iceCandidateErrors=[]}addH264AvailableProfiles(e){this.h264AvailableProfiles=[...new Set(this.h264AvailableProfiles.concat(e))]}setSupportedH264Profiles(e,t){this.h264CodecCapabilities.sendProfiles=e,this.h264CodecCapabilities.receiveProfiles=t}updateSendStream(e,t){this.audioTelemetry.updateSendStream(e,t)}getTimerTracker(e,t){return this.timerTrackerManager.getTimerTracker(e,t)}resetPairValues(){Object.keys(this.extensions.WebRTCStats).forEach((e=>{delete this.extensions.WebRTCStats[e].pair}))}limitCaptureAmount(e,t,i){void 0!==i&&(e[t]=Array.isArray(e[t])?e[t]:[],e[t].push(i),e[t].length>this.storedRecordsNumber&&e[t].shift())}setStartTime(e){const t=this.extensions.WebRTCStats;if(!t.ssrc_audio_send||!t.ssrc_audio_recv)return!1;const i=(e,t)=>!e||t&&-1===t?t:(new Date).getTime();return this.extensions.TimerAudioPayloadRecvBitrate=Kp(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioPayloadRecvBitrate):-1,this.extensions.TimerAudioPayloadSendBitrate=Wp(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioPayloadSendBitrate):-1,this.extensions.TimerAudioTransportRecvBitrate=Kp(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioTransportRecvBitrate):-1,this.extensions.TimerAudioTransportSendBitrate=Wp(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioTransportSendBitrate):-1,!!(t.ssrc_video_send&&t.ssrc_video_recv&&(this.extensions.TimerVideoPayloadRecvBitrate=Kp(e.video)?i(t.ssrc_video_recv.bytesReceived,this.extensions.TimerVideoPayloadRecvBitrate):-1,this.extensions.TimerVideoPayloadSendBitrate=Wp(e.video)?i(t.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 e=this.extensions.EndTime,t=(t,i)=>t&&e-i>0&&0!==i&&-1!==i?Math.round(8*t/(e-i)):0,i=e=>{const t=e.split(".").reduce(((e,t)=>null==e?e:e[t]),this.extensions.WebRTCStats);return Array.isArray(t)?t[t.length-1]:t};this.extensions.AudioPayloadRecvBitrate=t(i("ssrc_audio_recv.bytesReceived"),this.extensions.TimerAudioPayloadRecvBitrate),this.extensions.AudioPayloadSendBitrate=t(i("ssrc_audio_send.bytesSent"),this.extensions.TimerAudioPayloadSendBitrate),this.extensions.VideoPayloadRecvBitrate=t(i("ssrc_video_recv.bytesReceived"),this.extensions.TimerVideoPayloadRecvBitrate),this.extensions.VideoPayloadSendBitrate=t(i("ssrc_video_send.bytesSent"),this.extensions.TimerVideoPayloadSendBitrate),this.extensions.AudioTransportRecvBitrate=t(i("ssrc_audio_send.pair.bytesReceived"),this.extensions.TimerAudioTransportRecvBitrate),this.extensions.AudioTransportSendBitrate=t(i("ssrc_audio_send.pair.bytesSent"),this.extensions.TimerAudioTransportSendBitrate)}addFilteredFields(e,t,i=[]){for(const n in t)if(t.hasOwnProperty(n)&&"type"!==n)if(-1!==i.indexOf(n)){const i=e[n]||[];i.push(this.formatFields(t,n)),i.length>this.storedRecordsNumber&&i.shift(),e[n]||(e[n]=i)}else e[n]=t[n]}formatFields(e,t){const i=e[t];switch(t){case"audioInputLevel":case"audioOutputLevel":return this.newStatsApi?Math.floor(65535*i):2*i;case"googJitterBufferMs":return parseInt(i);case"healedRatio":return mn(parseFloat(i),this.configProvider.config.healedRatioPrecision);case"jitter":return mn(parseFloat(i),this.configProvider.config.jitterPrecision);default:return i}}processSource(e,t,i){let n;if(this.addFilteredFields(e,t,uU),t.transportId){const r=i.googComponent?.[t.transportId];e.transport||(e.transport={}),r&&(this.addFilteredFields(e.transport,r),r.selectedCandidatePairId&&(n=i.googCandidatePair?.[r.selectedCandidatePairId]))}else n=Object.values(i.googCandidatePair).find((e=>e.selected));n&&(e.pair||(e.pair={}),this.addFilteredFields(e.pair,n,hU))}getWebrtcReport(e,t,i,n){const r=e.ssrc[i],s=n?r.id.replace(/[0-9]+/,n):r.id;t[s]?r.ssrc!==t[s].ssrc&&(s.endsWith("video_send")?this.videoTelemetry.stopSendGathering():s.endsWith("video_recv")?this.videoTelemetry.stopRecvGathering():s.endsWith("sharing_send")?this.sharingTelemetry.stopSendGathering():s.endsWith("sharing_recv")&&this.sharingTelemetry.stopRecvGathering()):t[s]={},this.processSource(t[s],r,e)}constructWebRTCDataReport(e,t){if(!t.data?.length)return;const i=t.data.sort(((e,t)=>t.timestamp-e.timestamp)),n=i.find((e=>"open"===e.state));e.data=n||i[0]}constructWebRtcReportForSingleStream(e,t){if(!t.ssrc)return;const i=this.selectSsrcsToCollect(t.ssrc);e.recvCounters=i.recvCounters,delete i.recvCounters,delete i.multiRecv,qi(i,(i=>{qi(i,((i,n)=>{this.getWebrtcReport(t,e,i,n)}))})),t.VideoBwe?.bweforvideo&&(e.bweStat||(e.bweStat={}),this.addFilteredFields(e.bweStat,t.VideoBwe.bweforvideo,gU))}constructWebRtcReportForMultipleStreams(e,t){t.ssrc&&this.selectSsrcsToCollect(t.ssrc).multiRecv.forEach((i=>this.getWebrtcReport(t,e,i)))}getMediaType(e,t){let i=t?t.getModality():e.mediaType;return e.googTrackId?.match("applicationsharing")&&i!==Gi.MEDIA_TYPE.sharing&&(i=Gi.MEDIA_TYPE.sharing),i}selectSsrcsToCollect(e){const t={send:{},recv:{},recvCounters:{video:0,sharing:0},multiRecv:[]};if(!this.sessionInfo.activeModalities)return t;let i=[];for(const n of Object.keys(e)){const r=e[n],s=r.googTrackId;if(!s&&r.mediaType!==Gi.MEDIA_TYPE.audio)continue;const a=this.getMediaEntity(s,r),o=this.getMediaType(r,a),l=a?.getXSourceStreamId();if(n.endsWith("send"))switch(o){case Gi.MEDIA_TYPE.audio:Wp(this.sessionInfo.activeModalities.audio)&&(t.send.audio=n);break;case Gi.MEDIA_TYPE.video:if(this.extensions.Video_send_SourceId=l,this.simulcastVideo.highestFidelitySSRC){this.simulcastVideo.highestFidelitySSRC===r.ssrc&&(t.send.video=n);break}this.streamSenderStarted.Video&&Wp(this.sessionInfo.activeModalities.video)&&a?.getLocalTrackId()&&(a?.getLocalTrackId()===r.googTrackId||this.configProvider.config.statsAllowAnyVideoSendTrack&&!t.send.video)&&(!r.rid||"1"===r.rid)&&(t.send.video=n);break;case Gi.MEDIA_TYPE.sharing:if(this.simulcastSharing.highestFidelitySSRC){this.simulcastSharing.highestFidelitySSRC===r.ssrc&&(t.send.sharing=n);break}this.streamSenderStarted.ScreenShare&&Wp(this.sessionInfo.activeModalities.sharing)&&a?.getLocalTrackId()===r.googTrackId&&(t.send.sharing=n);break;default:this.logger.warn(`Unknown media type '${o}'`)}else if(n.endsWith("recv"))switch(o){case Gi.MEDIA_TYPE.audio:Kp(this.sessionInfo.activeModalities.audio)&&(t.recv.audio=n);break;case Gi.MEDIA_TYPE.video:void 0!==l&&this.MSIDs.add(l),this.isSubscribed(r.googTrackId,r.ssrc)&&Kp(this.sessionInfo.activeModalities.video)&&(i.push(r),+r.googFrameRateReceived>0&&t.recvCounters[Gi.MODALITY.video]++);break;case Gi.MEDIA_TYPE.sharing:this.isSubscribed(r.googTrackId,r.ssrc)&&Kp(this.sessionInfo.activeModalities.sharing)&&(t.recv.sharing=n,+r.googFrameRateReceived>0&&t.recvCounters[Gi.MODALITY.sharing]++);break;default:this.logger.warn(`Unknown media type '${o}'`)}}if(i.length>0){i=i.sort(((e,t)=>+t.googFrameHeightReceived-+e.googFrameHeightReceived));const e=i.find((e=>e.mediaType===Gi.MEDIA_TYPE.video));e&&(t.recv.video=e.id),this.multiparty&&this.configProvider.config.enableMultiViewStats&&(t.multiRecv=i.map((e=>e.id)),t.multiRecv.forEach((e=>{this.multiViewVideoTelemetry[e]||(this.multiViewVideoTelemetry[e]=new oU(this.extensions.StartTime,this.configProvider,this.logger.createChild(`Video[${e}]`,"Video")),this.multiViewVideoTelemetry[e].setMsi(this.MSIDsPairs[e]?.msi),this.multiViewVideoTelemetry[e].setLocalMsi(this.MSIDsPairs[e]?.localMsi),this.multiViewVideoTelemetry[e].prepareCollectingStatsOnSubscribed(this.MSIDsPairs[e]?.msi))})))}return t}getMediaEntityForTrack(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getLocalTrackId()===e||t.getRemoteTrackId()===e))}getMediaEntityByRemoteSsrc(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getRemoteSsrc()===+e))}getMediaEntity(e,t){const i=`${t.ssrc}`,n=t.id;let r=this.getMediaEntityForTrack(e);return!r&&this.configProvider.config.subscribeToSsrcForVideo&&n.endsWith("recv")&&(r=this.getMediaEntityByRemoteSsrc(i)),r}calculateHwSilentState(){const e=this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<2*this.hwSilentDetectionDuration)return;let t=!0;for(let i=e.length-this.hwSilentDetectionDuration-1;i<e.length;i++)if(e[i]>this.hwSilentDetectionLevel){t=!1;break}this.hwSilent!==t&&(this.hwSilent=t,this.logger.safe.info(`HW silent changed to ${this.hwSilent}`))}calculateSpeakingState(){const e=this.newStatsApi&&this.configProvider.config.useAudioAnalyzer?this.extensions.Audio_send_RawInputVolume:this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<=this.speakingWhileMutedBadDuration)return;let t=!1;for(let i=e.length-this.speakingWhileMutedBadDuration;i<e.length;i++)if(e[i]>this.speakingWhileMutedDetectionLevel){t=!0;break}this.isSpeaking=t}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(e,t){const i=tt(t);this.logger.safe.error(`webrtcStatistics error [${e}]: ${i}`);const n=this.statsErrors.find((t=>t.error===i&&t.origin===e));n?n.count++:this.statsErrors.push({origin:e,error:i,count:1}),this.statsErrors.length>10&&this.statsErrors.splice(1)}getLastSampleInt(e){return"number"==typeof e?e:e&&parseInt(e[e.length-1])||0}getSsrcIdFromMultipleVideoStream(e){let t;const i=this.extensions.WebRTCStats[Gi.MULTIPLE_RECV_STREAMS]||{};for(const n in i){const r=i[n];if(r&&r.googTrackId===e){t=n;break}}return t}};m([pU],mU.prototype,"onDeviceEvent",1),m([pU],mU.prototype,"onMaxCapabilitiesRequested",1),m([pU],mU.prototype,"onMaxCapabilitiesApplied",1),m([pU],mU.prototype,"addSubscriptionEvent",1),m([pU],mU.prototype,"processSimulcastStats",1),m([pU],mU.prototype,"processBandwidthStats",1),m([pU],mU.prototype,"processAudioStats",1),m([pU],mU.prototype,"processVideoStatsSend",1),m([pU],mU.prototype,"processVideoStatsRecv",1),m([pU],mU.prototype,"processSharingStats",1),m([pU],mU.prototype,"processStreamsCounters",1),m([pU],mU.prototype,"setMissedInitialPreferredResolution",1),m([pU],mU.prototype,"setPreferredResolution",1),m([pU],mU.prototype,"setIsRendering",1),m([pU],mU.prototype,"setMaxSessionBandwidth",1),m([pU],mU.prototype,"setStartTime",1),m([pU],mU.prototype,"calculateAverages",1),m([pU],mU.prototype,"addFilteredFields",1),m([pU],mU.prototype,"formatFields",1),m([pU],mU.prototype,"processSource",1),m([pU],mU.prototype,"getWebrtcReport",1),m([pU],mU.prototype,"constructWebRTCDataReport",1),m([pU],mU.prototype,"constructWebRtcReportForSingleStream",1),m([pU],mU.prototype,"constructWebRtcReportForMultipleStreams",1),m([pU],mU.prototype,"selectSsrcsToCollect",1),m([pU],mU.prototype,"calculateHwSilentState",1),m([pU],mU.prototype,"calculateSpeakingState",1),m([pU],mU.prototype,"calculateNetworkRecvQualityLevel",1),m([pU],mU.prototype,"calculateNetworkSendQualityLevel",1);var fU=class extends Vi{constructor(e,t,i,n){super(),this.logger=e,this.configProvider=t,this.mediaManager=i,this.window=Mp.window,this._sessionInfo=new PL,this.statisticsMapper=new FF,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.webRtcStatistics=new mU(this.logger.createChild("WebrtcStatistics"),this._sessionInfo,this.configProvider,i,n,this.useNewStatsApi)}setAudioDecoderStatsProvider(e){this.statisticsMapper?.setAudioDecoderStatsProvider(e)}setAudioEncoderCodecName(e){this.statisticsMapper?.setAudioEncoderCodecName(e)}get sessionInfo(){return this._sessionInfo}get isDisposed(){return null===this.pc&&0===this.interval}initialize(e){this.pc=e}startWaitingForStreamStart(e){this.webRtcStatistics.startWaitingForStreamStart(e)}onDeviceEvent(e){this.webRtcStatistics.onDeviceEvent(e)}onMaxCapabilitiesRequested(e){this.webRtcStatistics.onMaxCapabilitiesRequested(e)}onMaxCapabilitiesApplied(e){this.webRtcStatistics.onMaxCapabilitiesApplied(e)}onSendersChanged(e,t){this.webRtcStatistics.setStreamSenderStarted(e,t)}addSubscriptionEvent(e,t,i,n,r,s,a){this.webRtcStatistics.addSubscriptionEvent(e,t,i,n,r,s,a)}setSubscribedTrackIds(e){this.webRtcStatistics.setSubscribedTrackIds(e)}setSubscribedTrackSsrc(e){this.webRtcStatistics.setSubscribedTrackSsrc(e)}setPreferredResolution(e,t,i){this.webRtcStatistics.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.webRtcStatistics.setIsRendering(e,t,i)}setMaxSessionBandwidth(e){this.webRtcStatistics.setMaxSessionBandwidth(e)}setTerminated(){this.webRtcStatistics.setTerminated()}addIceCandidateError(e){this.webRtcStatistics.addIceCandidateError(e)}clearIceCandidateErrors(){this.webRtcStatistics.clearIceCandidateErrors()}updateSendStream(e,t){this.webRtcStatistics.updateSendStream(e,t)}getTimerTracker(e,t){return this.webRtcStatistics.getTimerTracker(e,t)}setH264AvailableProfiles(e){if(!e?.codecs)return;let t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=/profile-level-id=(.{6})/.exec(e.sdpFmtpLine);i?.[1]&&(t=t.concat(i[1]))}})),this.webRtcStatistics.addH264AvailableProfiles(t)}setSupportedH264Profiles(e,t){if(!e?.codecs&&!t?.codecs)return;const i=e=>{const t=[];return e.codecs?.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=/profile-level-id=(.{6})/.exec(e.sdpFmtpLine)?.[1];i&&!t.includes(i)&&t.push(i)}})),t},n=i(e),r=i(t);this.webRtcStatistics.setSupportedH264Profiles(n,r)}processRawReport(e){this.processStatsDict(this.statisticsMapper.build(e))}processLegacyReport(e){this.processStatsDict(function(e){const t={};return e.result().forEach((e=>{e.names().forEach((i=>{t[e.type]=t[e.type]||{},t[e.type][e.id]=t[e.type][e.id]||{},t[e.type][e.id][i]=e.stat(i)})),t[e.type][e.id].id=e.id})),t}(e))}getReport(e,t=!1){const i=this.webRtcStatistics.getReport(e,t);return this.addStreamInfoForE2ETests(i),i}dispose(){this.interval&&(this.window.clearInterval(this.interval),this.interval=0),this.pc=null}getLastStatistics(){return this.statistics}setTimeToFirstFrame(e,t,i){this.webRtcStatistics.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.webRtcStatistics.setFreezeDuration(e,t)}addVideoControlMessage(e=!1){this.webRtcStatistics.addVideoControlMessage(e)}setSsrcTrackPair(e,t){this.statisticsMapper.setSsrcTrackPair(e,t)}updateStatsWithLocalSsrcTrackInfo(){for(const e of this.mediaManager.getMediaEntities()){const t=e.getLocalSsrc();t&&this.statisticsMapper.setSsrcTrackPair(t,e.getLocalTrackId())}}addReportedReceiveBandwidth(e){this.webRtcStatistics.addReportedReceiveBandwidth(e)}addStreamInfoForE2ETests(e){const t=this._sessionInfo.negotiatedModalities;if(t&&!this.isDisposed)try{e.localStreams=this.getSendersReport(this.pc.getSenders(),{audio:Wp(t.audio),video:Wp(t.video)}),e.remoteStreams=this.getReceiversReport(this.pc.getReceivers(),{audio:Kp(t.audio),video:Kp(t.video)})}catch(e){this.logger.safe.warn(`addStreamInfoForE2ETests failed: ${tt(e)}`)}}getReceiversReport(e,t){const i=[];return e.forEach((e=>{const n={tracks:[]};i.push(n),e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}getSendersReport(e,t){const i=[],n={tracks:[]};return i.push(n),e.forEach((e=>{e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}processStatsDict(e){this.webRtcStatistics.processStatsDict(e);let t=0,i=0;const n=e.VideoBwe?.bweforvideo;n&&(t=Number(n.googAvailableReceiveBandwidth),i=Number(n.googAvailableSendBandwidth));const r=1e3*((this.configProvider.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(this.configProvider.config.audioBandwidthInKbps||0)),s=isNaN(t)?0:t,a=isNaN(i)?0:i,o={estimatedReceiveBandwidth:Math.min(s,r),estimatedSendBandwidth:Math.min(a,r),remoteVideoStreams:{},localVideoStreams:{},isSpeaking:this.webRtcStatistics.getSpeakingState(),audioHwSilent:this.webRtcStatistics.getAudioHwSilent(),networkSendLevel:this.webRtcStatistics.getNetworkSendLevel(),networkRecvLevel:this.webRtcStatistics.getNetworkRecvLevel()};qi(e.ssrc,(e=>{if("video"!==e.mediaType)return;const t=e.googTrackId,i=e.id;-1!==i.indexOf("_recv")?(o.remoteVideoStreams[t]={trackId:t,frameRateReceived:Number(e.googFrameRateReceived),frameRateDecoded:Number(e.googFrameRateDecoded),framesDecoded:Number(e.framesDecoded)},this.configProvider.config.isRenderingBasedOnRawStatistics||(o.remoteVideoStreams[t].isRendering=this.webRtcStatistics.getIsRendering(i))):t&&-1!==i.indexOf("_send")&&(o.localVideoStreams[t]={trackId:t,ssrc:Number(e.ssrc),frameRateInput:Number(e.googFrameRateInput)})})),an(this.statistics,o)||(this.statistics=o,this.notifyStatisticsChanged())}notifyStatisticsChanged(){this.event("onStatisticsChanged").raise(this.statistics)}},vU=class extends Vi{constructor(e,t,i,n,r){super(),this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.window=Mp.window,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.loopIntervalTracker=new XM(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.loopIntervalAggregator=new eD,this.fetchTimeTracker=new XM(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.fetchTimeAggregator=new eD,this.gathererV1=new fU(this.logger.createChild("V1"),this.configProvider,this.mediaManager,r),this.gathererV1.on("onStatisticsChanged",(e=>this.event("onStatisticsChanged").raise(e))),this.useNewStatsApi&&t.config.diagnostics.sideBySide&&(this.gathererV2=new wF(this.logger.createChild("V2"),this.configProvider,this.diagnostics,this.mediaManager))}initialize(e){this.pc=e,this.gathererV1.initialize(e),this.interval??(this.interval=this.window.setInterval((()=>this.processStats()),this.configProvider.config.webrtcStatPollInterval))}setAudioDecoderStatsProvider(e){this.gathererV1.setAudioDecoderStatsProvider(e),this.gathererV2?.setAudioDecoderStatsProvider(e)}setAudioEncoderCodecName(e){this.gathererV1.setAudioEncoderCodecName(e),this.gathererV2?.setAudioEncoderCodecName(e)}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 e=_n(),t=void 0===this.loopTimer?-1:e-this.loopTimer;this.loopTimer=e,this.loopIntervalTracker.captureSample(t),this.loopIntervalAggregator.captureSample(this.loopIntervalTracker.getReport());const i=this.loopIntervalAggregator.getReport();i&&(this.diagnostics.loopIntervalMax=i.max,this.diagnostics.loopIntervalMedian=i.median);const n={};(await this.pc.getStats()).forEach((e=>{this.cleanupPii(e);const t=e.type;delete e.type,n[t]??(n[t]={}),n[t][e.id]=e}));const r=_n()-e;this.fetchTimeTracker.captureSample(r),this.fetchTimeAggregator.captureSample(this.fetchTimeTracker.getReport());const s=this.fetchTimeAggregator.getReport();s&&(this.diagnostics.fetchTimeMax=s.max,this.diagnostics.fetchTimeMedian=s.median);const a=this.gathererV2?.processRawReport(n);let o=_n();this.gathererV1.processRawReport(n),o=_n()-o,a&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Raising onDiagnosticUpdated event"),this.event("onDiagnosticUpdated").raise(a)),a?.perfCounters&&(a.perfCounters.loopTime=t,a.perfCounters.fetchTime=r,a.perfCounters.legacyProcessingTime=o)}else this.pc.getStats((e=>{e.result&&this.gathererV1.processLegacyReport(e)}))}cleanupPii(e){switch(e.type){case"local-candidate":case"remote-candidate":{const t=e;Object.defineProperty(t,"address",{enumerable:!1}),Object.defineProperty(t,"url",{enumerable:!1}),Object.defineProperty(t,"relatedAddress",{enumerable:!1}),Object.defineProperty(t,"ip",{enumerable:!1}),Object.defineProperty(t,"usernameFragment",{enumerable:!1});break}case"certificate":{const t=e;Object.defineProperty(t,"fingerprint",{enumerable:!1}),Object.defineProperty(t,"base64Certificate",{enumerable:!1});break}}}get sessionInfo(){return this.gathererV1.sessionInfo}onMaxCapabilitiesApplied(e){this.gathererV1.onMaxCapabilitiesApplied(e)}clearIceCandidateErrors(){this.gathererV1.clearIceCandidateErrors()}setSsrcTrackPair(e,t){this.gathererV1.setSsrcTrackPair(e,t),this.gathererV2?.setSsrcTrackPair(e,t)}addSubscriptionEvent(e,t,i,n,r,s,a){this.gathererV1.addSubscriptionEvent(e,t,i,n,r,s,a)}setSubscribedTrackSsrc(e){this.gathererV1.setSubscribedTrackSsrc(e)}addIceCandidateError(e){this.gathererV1.addIceCandidateError(e)}setH264AvailableProfiles(e){this.gathererV1.setH264AvailableProfiles(e)}setSupportedH264Profiles(e,t){this.gathererV1.setSupportedH264Profiles(e,t)}setTerminated(){this.gathererV1.setTerminated()}onDeviceEvent(e){this.gathererV1.onDeviceEvent(e)}getReport(e,t=!1){const i=this.gathererV1.getReport(e,t);if(this.gathererV2&&this.configProvider.config.diagnostics.sideBySide){const e=this.loopIntervalAggregator.getReport();e&&(i.data.Extensions.LoopIntervalMax=`${mn(e.max,1)}`,i.data.Extensions.LoopIntervalMedian=`${mn(e.median,1)}`);const t=this.fetchTimeAggregator.getReport();t&&(i.data.Extensions.FetchTimeMax=`${mn(t.max,1)}`,i.data.Extensions.FetchTimeMedian=`${mn(t.median,1)}`);const n=this.diagnostics.getObjectRef();i.data.Extensions.multipleVideoStreams=JSON.stringify(wn(n.multiViewStats,"startTime",n.startTime)),i.data.Extensions.OvcToSubscriptions=JSON.stringify(n.ovcToSubscriptionEvents),i.data.Extensions.videoPerformanceEvent=JSON.stringify(n.videoPerformanceEvent);const r=n.bandwidthReport;"REMB"===n.negotiation.bweType?(i.data.Extensions.StartCallBWE=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWE=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStd=JSON.stringify(r?.std),i.data.Extensions.BwPercentiles=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwe=JSON.stringify(r?.avgBwe)):(i.data.Extensions.StartCallBWESendSide=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWESendSide=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStdSendSide=JSON.stringify(r?.std),i.data.Extensions.BwPercentilesSendSide=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwSendSide=JSON.stringify(r?.avgBwe)),i.data.Extensions.InitialBWSeed=JSON.stringify(n.initialBWSeed),i.data.Extensions.SentBWSeed=JSON.stringify(n.sentBWSeed),i.data.Extensions.Bandwidth_downlinkStabilizationTime=JSON.stringify(n.bwDownlinkStabilizationTime),i.data.Extensions.ReinvitelessContext=JSON.stringify(n.reinvitelessContext),i.data.Extensions.ReportedSendBandwidth=JSON.stringify(n.reportedSendBandwidthLayouts),i.data.Extensions.Data_ProtocolCounters=JSON.stringify(n.dataChannel?.protocolCounters),i.data.Extensions.Data_Error=n.dataChannel?.error,i.data.Extensions.Data_SessionState=n.dataChannelSessionState?.toString(),i.data.Extensions.Data_CreateChannelError=n.dataChannelCreationError;const s=n.aggregatedModalityStats?.video?.recv||[],a=n.aggregatedModalityStats?.audio?.recv||[],o=n.aggregatedModalityStats?.sharing?.recv||[],l=n.aggregatedModalityStats?.video?.send||[],c=n.aggregatedModalityStats?.sharing?.send||[],d=i.data.Extensions.WebRTCStats,u=s[s.length-1],h=o[o.length-1],g=a[a.length-1],p=l[l.length-1],m=c[c.length-1],f=u?.aggregated?.macroblockRateStats??{},v=g?.aggregated?.customHealerStats??{};if(v?.pullPacketProcessingTimes){const e=kn(v.pullPacketProcessingTimes);v.pullPacketProcessingTimeP50=e.getPercentile(.5),v.pullPacketProcessingTimeP95=e.getPercentile(.95)}if(v?.pushPacketProcessingTimes){const e=kn(v.pushPacketProcessingTimes);v.pushPacketProcessingTimeP50=e.getPercentile(.5),v.pushPacketProcessingTimeP95=e.getPercentile(.95)}for(const e in f)i.data.Extensions[`Video_recv_${e}`]=`${mn(f[e],0)}`;for(const e in n.totalVideoRecvMblocksRates)i.data.Extensions[`totalVideoRecv_${e}`]=`${mn(n.totalVideoRecvMblocksRates[e],0)}`;for(const e in v)if(void 0!==v[e]){const t="number"!=typeof v[e]?JSON.stringify(v[e]):v[e];i.data.Extensions[`Audio_recv_customHealer_${e}`]=t}i.data.Extensions.MeetingScenario=JSON.stringify(n.negotiation.meetingScenario),i.data.Extensions.IsTownHall=JSON.stringify(n.negotiation.isTownHall),i.data.Extensions.Audio_send_presentationAPIUserDuration=JSON.stringify(n.presentationAPIUserDuration),i.data.Extensions.Audio_send_presentationDuration=JSON.stringify(n.presentationAudioDuration),i.data.Extensions.CodecSupport=JSON.stringify(n.codecSupport),i.data.Extensions.Video_recv_FpsHarmonicAverage=u?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_FpsHarmonicAverage=h?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_CodecReport=JSON.stringify(h?.aggregated?.codecReport),i.data.Extensions.Video_send_performanceEvents=JSON.stringify(vn(wn(n.localVideoPerformanceEvents,"timestamp",n.startTime),this.configProvider.config.diagnostics.telemetryLimits.numPerformanceEvents)),d?.ssrc_sharing_send&&((d?.ssrc_sharing_send).retransmittedPacketsSent=Pn(n.aggregatedModalityStats?.sharing?.send,(e=>e.outboundRTP.retransmittedPacketsSent))),this.configProvider.config.diagnostics.features.takeFreezeTelemetryFromGathererV2&&(s.length&&(i.data.Extensions.Video_recv_FreezeHistogram=JSON.stringify(u.aggregated?.freezeCountHistogram),i.data.Extensions.Video_recv_LongestFreezeDuration=JSON.stringify(u?.aggregated?.longestFreeze),i.data.Extensions.Video_recv_OngoingFreeze=JSON.stringify(u?.extensions?.isFrozen),i.data.Extensions.Video_recv_OngoingFreezeDuration=JSON.stringify(u?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Video_recv_TotalFreezeDuration=JSON.stringify(u?.aggregated?.totalFreezeDuration),i.data.Extensions.Video_recv_RecvAvgFreezeDuration=JSON.stringify(u?.aggregated?.avgFreezeDuration),i.data.Extensions.Video_recv_FreezeTimestamps=JSON.stringify(An(u?.aggregated?.freezeTimestampsHistogram,n.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples))),o.length&&(i.data.Extensions.Sharing_recv_FreezeHistogram=JSON.stringify(h.aggregated?.freezeCountHistogram),i.data.Extensions.Sharing_recv_LongestFreezeDuration=JSON.stringify(h?.aggregated?.longestFreeze),i.data.Extensions.Sharing_recv_OngoingFreeze=JSON.stringify(h?.extensions?.isFrozen),i.data.Extensions.Sharing_recv_OngoingFreezeDuration=JSON.stringify(h?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Sharing_recv_TotalFreezeDuration=JSON.stringify(h?.aggregated?.totalFreezeDuration),i.data.Extensions.Sharing_recv_RecvAvgFreezeDuration=JSON.stringify(h?.aggregated?.avgFreezeDuration),i.data.Extensions.Sharing_recv_FreezeTimestamps=JSON.stringify(An(h?.aggregated?.freezeTimestampsHistogram,n.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples)))),i.data.Extensions.EarlyMedia={NumStatsPolls:`${n.earlyMediaNumStatsPolls}`},i.data.Extensions.Audio_recv_packetsLostRateMax=`${mn(g?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Audio_recv_networkAvgLossRate=`${mn(g?.aggregated?.networkAvgLossRate,6)||0}`,i.data.Extensions.Video_recv_packetsLostRateMax=`${mn(u?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Sharing_recv_packetsLostRateMax=`${mn(h?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Video_send_packetsLostRateMax=`${mn(p?.aggregated?.lossRateMax,6)||0}`,i.data.Extensions.Sharing_send_packetsLostRateMax=`${mn(m?.aggregated?.lossRateMax,6)||0}`,this.configProvider.config.diagnostics.features.useNewSimulcastTelemetryExtension&&(i.data.Extensions.Video_send_Simulcast=JSON.stringify(n.simulcast?.video),i.data.Extensions.Sharing_send_Simulcast=JSON.stringify(n.simulcast?.sharing)),i.data.Extensions.Video_send_powerEfficientEncoderEvents=xn(p?.extensions?.powerEfficientEncoderEvents,this.configProvider.config.diagnostics.telemetryLimits.numPowerEfficientEncoderEvents,"timestamp",n.startTime),i.data.Extensions.Video_send_powerEfficientEncoderEventOnCount=JSON.stringify(p?.extensions?.powerEfficientEncoderEventOnCount),i.data.Extensions.Video_send_powerEfficientEncoderEventOffCount=JSON.stringify(p?.extensions?.powerEfficientEncoderEventOffCount)}return rn(i)}startWaitingForStreamStart(e){this.gathererV1.startWaitingForStreamStart(e)}getTimerTracker(e,t){return this.gathererV1.getTimerTracker(e,t)}getLastStatistics(){return this.gathererV1.getLastStatistics()}updateSendStream(e,t){this.gathererV1.updateSendStream(e,t)}setSubscribedTrackIds(e){this.gathererV1.setSubscribedTrackIds(e)}setMaxSessionBandwidth(e){this.gathererV1.setMaxSessionBandwidth(e)}updateStatsWithLocalSsrcTrackInfo(){this.gathererV1.updateStatsWithLocalSsrcTrackInfo()}onSendersChanged(e,t){this.gathererV1.onSendersChanged(e,t)}setPreferredResolution(e,t,i){this.gathererV1.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.gathererV1.setIsRendering(e,t,i)}setTimeToFirstFrame(e,t,i){this.gathererV1.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.gathererV1.setFreezeDuration(e,t)}addVideoControlMessage(e){this.gathererV1.addVideoControlMessage(e)}onMaxCapabilitiesRequested(e){this.gathererV1.onMaxCapabilitiesRequested(e)}addReportedReceiveBandwidth(e){this.gathererV1.addReportedReceiveBandwidth(e)}},SU=101,yU=[48e3,32e3,24e3,16e3,12e3],CU=class{constructor(e){this.context=e,this.cname=sn(),this.dataMedia={type:Gi.MEDIA_TYPE.data,protocol:Gi.PROFILES.rtpSavp,port:0},this.configProvider=e.configProvider,this.logger=e.getLogger().createChild("WebkitSdpTrans")}fixTelephoneEvent(e){let t;return yU.forEach((t=>{_O(e,{codec:"telephone-event",rate:t})})),yO(e,SU,999),TO(e,{codec:"telephone-event",rate:8e3},(e=>(t=e.rtp.payload,e.rtp.payload=SU,e))),yO(e,999,t||SU),t}toLocal(e,t,i){const n=t.isEmpty(),r=nn(e);let s;return r.media.forEach((e=>{if("audio"===e.type)n&&(s=this.fixTelephoneEvent(e)),EU(e);else{s&&yO(e,SU,s);const i=t.getLocalSsrcs().get(MO(e));this.enforceFixedSsrc(e,i)}const r=fm(this.configProvider,e.type);"offer"===i&&wU(e,r,n,this.logger)})),new JN(this.configProvider).modify(r),delete r.extmapAllowMixed,r}toOffer(e,t,i){return this.fromNative(e,t,i,!0)}toAnswer(e,t,i){return this.fromNative(e,t,i,!1)}toRemote(e,t,i,n){const r=nn(e);let s,a,o=this.configProvider.mediaConfig.maxBandwidthInKbps;r.bandwidth&&(!o||o>+e.bandwidth[0].limit)&&(o=+e.bandwidth[0].limit),r.media.forEach(((e,i)=>{t.getMediaEntity(i).isDisabled()&&e.type!==Gi.MEDIA_TYPE.audio&&(e.port=0)}));let l=function(e){return e.groups?e.groups.find((e=>"BUNDLE"===e.type)):null}(r);if(!l){let e=!1;r.media.forEach(((i,n)=>{const r=t.getMediaEntity(n);!e&&r.isEnabled()?(i.mid=r.getMid(),e=!0):(r.disable(),i.port=0)})),e&&(r.groups||(r.groups=[]),l={type:"BUNDLE"},r.groups.push(l))}r.media.forEach((e=>{const t=MO(e);i[t]===Gi.MEDIA_STATE.send&&(e.direction&&e.direction.toLowerCase()===Gi.MEDIA_STATE.receive||(e.direction=Gi.MEDIA_STATE.receive))}));const c=r.media.filter((e=>e.type===Gi.MEDIA_TYPE.video));if(c.length>0){const e=c.filter((e=>0!==e.port));if(e.length>0){a=nn(e[0]),a.bandwidth&&delete a.bandwidth;const t=this.configProvider.config.audioBandwidthInKbps?this.configProvider.config.audioBandwidthInKbps:0;o&&o-t>0&&(a.bandwidth=[{limit:o-t,type:"AS"}]),a.mid="video",a.direction=null,delete a.label,a.ssrcs=[],a.ssrcGroups=[],delete a.msid,e.forEach((e=>{e.ssrcs&&(a.ssrcs=a.ssrcs.concat(e.ssrcs)),e.ssrcGroups&&(a.ssrcGroups=a.ssrcGroups.concat(e.ssrcGroups)),a.direction=function(e,t){return e===Gi.MEDIA_STATE.sendReceive||t===Gi.MEDIA_STATE.sendReceive?Gi.MEDIA_STATE.sendReceive:e===t?e:e&&t&&e!==t?Gi.MEDIA_STATE.sendReceive:e||t}(a.direction,e.direction||Gi.MEDIA_STATE.sendReceive)})),TU(a)}else a=_U(Gi.MEDIA_TYPE.video,void 0,c[0].protocol,c[0].payloads)}const d=r.media.find((e=>e.type===Gi.MEDIA_TYPE.audio));if(d)if(0!==d.port)s=nn(d),s.mid="audio",delete s.label,function(e){_O(e,{codec:"g722",rate:8e3,encoding:2})}(s),EU(s),TU(s);else{s=_U(Gi.MEDIA_TYPE.audio,void 0,d.protocol,d.payloads);const e=r.media.find((e=>!!e.iceUfrag));e&&(s.port=9,s.direction="inactive",s.mid="audio",s.iceUfrag=e.iceUfrag,s.icePwd=e.icePwd,s.rtcpMux="rtcp-mux",e.crypto&&(s.crypto=e.crypto),e.fingerprint&&(s.fingerprint=e.fingerprint,s.setup=e.setup),s.rtp=[{payload:0,codec:"PCMU",rate:8e3}],s.payloads="0")}r.media.forEach(((e,t)=>{e.type===Gi.MEDIA_TYPE.data&&(e.type=Gi.MEDIA_TYPE.dataChannel,e.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL,e.protocol=Gi.PROFILES.udpDtlsSctp,e.mid="data",delete e.xDataProtocol,delete e.direction,NO(e)&&(r.media[t]=_U(e.type,void 0,e.protocol,e.payloads)))}));const u=mm(this.context)?r.media.find((e=>e.type===Gi.MEDIA_TYPE.dataChannel)):null;r.media=[s,a,u].filter((e=>e)),t.getMediaEntities()[0].getModality()!==Gi.MODALITY.audio&&r.media.reverse();const h=gm(this.context.configProvider,this.context.config.isPstnCall),g=im(e);return r.media.forEach((e=>{e.type!==Gi.MEDIA_TYPE.dataChannel&&(!h&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!g.dtls||g.sdes&&h?Gi.PROFILES.rtpSavpf:Gi.PROFILES.udpTlsRtpSavpf)})),"offer"===n&&(wU(s,this.configProvider.config.allowedAudioCodecs,!1,this.logger),wU(a,this.configProvider.config.allowedVideoCodecs,!1,this.logger)),bU(r,this.configProvider.mediaConfig.isTransportUnbundled),r}splitMedia(e,t,i,n,r){const s=e.getMid(),a=e.getModality(),o=nn(t);if(o.label=DO(a),o.direction=n,o.mid=s,o.ssrcs=[],o.ssrcGroups=[],e.getModality()===Gi.MODALITY.data)return o.type=Gi.MEDIA_TYPE.data,o.payloads=Gi.PAYLOAD_TYPE.X_DATA,o;const l=i.filter((e=>e.modality===a));if(l&&l.length){const e=[];t.ssrcs&&(l.forEach((i=>{const n=t.ssrcs.filter((e=>"msid"===e.attribute&&i.trackId===IU(e.value))).map((e=>e.id));e.push(...n)})),o.ssrcs=t.ssrcs.filter((t=>e.indexOf(+t.id)>-1)),o.ssrcs.forEach((e=>{"cname"===e.attribute&&(e.value=this.cname)}))),t.ssrcGroups&&(o.ssrcGroups=t.ssrcGroups.filter((t=>t.ssrcs.split(" ").find((t=>e.indexOf(+t)>-1)))))}else{if(n===Gi.MEDIA_STATE.send||n===Gi.MEDIA_STATE.sendReceive)return _U(t.type,DO(a),t.protocol,t.payloads);n!==Gi.MEDIA_STATE.receive&&n!==Gi.MEDIA_STATE.inactive||(r[t.type].ssrcs?.[0]?o.ssrcs=[{id:r[t.type].ssrcs[0].id,attribute:"cname",value:this.cname}]:t.type===Gi.MEDIA_TYPE.audio?o.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:t.type===Gi.MEDIA_TYPE.video&&(o.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}return o}fromNative(e,t,i,n){const r=nn(e),s=this.configProvider.mediaConfig.maxBandwidthInKbps;s&&(r.bandwidth=[{limit:s,type:"CT"}]),new YN(this.configProvider).modify(r);const a=r.media.find((e=>e.type===Gi.MEDIA_TYPE.audio)),o=r.media.find((e=>e.type===Gi.MEDIA_TYPE.video)),l=r.media.find((e=>e.type===Gi.MEDIA_TYPE.dataChannel)),c={};c[Gi.MODALITY.audio]=a,c[Gi.MODALITY.video]=o,c[Gi.MODALITY.sharing]=o,c[Gi.MODALITY.data]=l||this.dataMedia;const d={};d[Gi.MEDIA_TYPE.audio]=a,d[Gi.MEDIA_TYPE.video]=o,d[Gi.MEDIA_TYPE.data]=l||this.dataMedia;const u={};return u[Gi.MODALITY.audio]=t.getMediaEntitiesByModality(Gi.MODALITY.audio)[0],u[Gi.MODALITY.video]=t.getMediaEntitiesByModality(Gi.MODALITY.video)[0],u[Gi.MODALITY.sharing]=t.getMediaEntitiesByModality(Gi.MODALITY.sharing)[0],u[Gi.MODALITY.data]=t.getMediaEntitiesByModality(Gi.MODALITY.data)[0],r.media=[],t.getMediaEntities().forEach((e=>{let s,a=i[e.getModality()];!e.isEnabled()||0===c[e.getModality()].port||e!==u[e.getModality()]&&a===Gi.MEDIA_STATE.send?(s=_U(e.getType(),DO(e.getModality()),c[e.getModality()].protocol,c[e.getModality()].payloads),c[e.getModality()].payloads===Gi.PAYLOAD_TYPE.DATA_CHANNEL&&(s.payloads=Gi.PAYLOAD_TYPE.DATA_CHANNEL)):(a!==Gi.MEDIA_STATE.inactive&&e!==u[e.getModality()]&&(a=Gi.MEDIA_STATE.receive),s=this.splitMedia(e,c[e.getModality()],t.getLocalTracksInfo(),a,d),e!==u[e.getModality()]&&(s.candidates=[]));const o=c[e.getModality()].setup;o&&("actpass"!==o?e.setExtension("setup",o):n&&void 0!==e.getExtension("setup")&&(s.setup="actpass"!==e.getExtension("setup")?e.getExtension("setup"):o));const l=c[e.getModality()].iceUfrag,h=e.getExtension("iceUfrag");e.setExtension("iceRestart",!!l&&!!h&&h!==l),e.setExtension("iceUfrag",l),NO(s)&&e.disable(),r.media.push(s)})),new hN(this.context,i.data).modify(r),bU(r,this.configProvider.mediaConfig.isTransportUnbundled),r}enforceFixedSsrc(e,t){let i=-1;if(!e.ssrcs)return;const n=[];if(e.ssrcs.forEach((e=>{"msid"===e.attribute&&n.push({ssrc:e.id,trackId:IU(e.value)})})),e.ssrcs.forEach((e=>{"cname"===e.attribute&&i++,t&&(e.id=this.getVideoSSRC(i,t))})),e.ssrcGroups){const t=e.ssrcs.filter((e=>"cname"===e.attribute)).map((e=>e.id));e.ssrcGroups.forEach(((e,i)=>{e.ssrcs=[t[2*i],t[2*i+1]].join(" ")}))}}getVideoSSRC(e,t){return e%2==1?t+50:t}};function TU(e){const t=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"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}function EU(e){_O(e,{codec:"CN",rate:16e3})}function bU(e,t){const i=e.groups?.findIndex((e=>"BUNDLE"===e.type)),n=e.groups?e.groups[i]:void 0;n&&(t?(n.mids=e.media.filter((e=>e.type===Gi.MEDIA_TYPE.video)).map((e=>e.mid)).filter((e=>e)).join(" "),n.mids||delete e.groups[i]):n.mids=e.media.map((e=>e.mid)).filter((e=>e)).join(" "))}function _U(e,t,i,n){return{type:e,port:0,label:t,payloads:n,protocol:i}}function IU(e){return e.split(" ")[1]}function wU(e,t,i,n){t.length&&e?.port&&PO(e,vm(t),i,n)}var AU=p(ye()),PU=class{getCapabilities(e){const t=RTCRtpReceiver.getCapabilities(e);return t.codecs.forEach((e=>{e.mimeType=e.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(t)}},RU=class{getCapabilities(e){const t=RTCRtpSender.getCapabilities(e);return t.codecs.forEach((e=>{e.mimeType=e.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(t)}},MU=class{constructor(e,t){this.noRequiredCodecsWorkaround=t,this.selfGlobal=e.global.capabilityGatherer=e.global.capabilityGatherer||{},this.getCapabilities("video")}async getCapabilities(e){if("video"!==e&&"audio"!==e)return Promise.reject(new Error(`capabilities for ${e} are not supported`));if(!this.selfGlobal.gatherTask){const e=new Kt;this.selfGlobal.gatherTask=e.promise;const t=void 0!==Mp.window.webkitRTCPeerConnection,i=t?new Mp.window.webkitRTCPeerConnection(null):new Mp.window.RTCPeerConnection(null),n=e=>t?new Promise(((t,n)=>{i.createOffer(t,n,e)})):(this.noRequiredCodecsWorkaround&&i.addTrack(i.addTransceiver("video").receiver.track),i.createOffer(e));try{const t=await n({offerToReceiveVideo:1,offerToReceiveAudio:1}),r={};AU.parse(t.sdp).media.forEach((e=>{r[e.type]=e.rtp.map((t=>{const i={mimeType:t.codec.toLowerCase()};if("video"===e.type){const n=e.fmtp?.find((e=>e.payload===t.payload));i.sdpFmtpLine=n?.config}return i}))})),i.close(),e.resolve(r)}catch(t){this.selfGlobal.gatherTask=null,i.close(),e.reject(t)}}return this.selfGlobal.gatherTask.then((t=>({codecs:t[e]})))}},DU=(e,t,i=!1,n=!1)=>n?new RU:!t&&Vp.hasCapabilitiesApi()?new PU:new MU(e,i),kU=p(ye()),OU="rollback";function NU(){const e=[].slice.apply(arguments);let t=e[0]&&LU(e[0].type);e.splice(0,t?1:0,null);const i=new(Function.prototype.bind.apply(Mp.window.RTCSessionDescription,e)),n=Object.getOwnPropertyDescriptor(Mp.window.RTCSessionDescription.prototype,"type");return Object.defineProperty(i,"type",{get:()=>t?OU:n.get.call(i),set(e){t=LU(e),t||n.set.call(i,e)}}),i}function LU(e){return OU===e}var xU=()=>NU,FU=[{codec:"telephone-event",rate:8e3},{codec:"cn",rate:16e3}];function UU(e){const t=[],i=xU(),n=[].slice.apply(arguments);n.splice(0,1,null),function(e){n[1]?.[e]&&(n[1].iceTransports=n[1][e])}("iceTransportPolicy");const r=new(Function.prototype.bind.apply(Mp.window.webkitRTCPeerConnection,n));function s(e,t){let i;Object.defineProperty(this,"dtmf",{get:()=>"audio"===e.kind?(i=i||r.createDTMFSender(e),i):null}),this.track=e,this._stream=t}return[{name:"createOffer",reverseArgs:!0},"createAnswer","setRemoteDescription","setLocalDescription"].forEach((function(e){const t=e.name||e,i=r[t];r[t]=function(){const t=arguments;return new Promise((function(n,s){const a=[n,s];t.length>0&&a.splice(e.reverseArgs?a.length:0,0,t[0]),i.apply(r,a)}))}})),function(){["createOffer","createAnswer","setLocalDescription"].forEach((function(t){const i=r[t];r[t]=function(){const t=arguments;return e.getCapabilities("video").then((function(){return i.apply(i,t)}))}}));const t=r.setRemoteDescription;r.setRemoteDescription=function(i){return e.getCapabilities("video").then((function(e){const n=e.codecs,r=kU.parse(i.sdp);return r.media.forEach((function(e){if("video"===e.type&&(e.rtp.some((function(e){return n.some((function(t){return e.codec.toLowerCase()===t.mimeType}))}))?function(e){TO(e,{codec:"h264",rate:9e4},(function(e){if(e.fmtp){const t=new SO,i=new SO(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((function(e){if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n="42C02A"),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}(e):e.port=0),!function(e){return"RTP/SAVPF"!==e.protocol}(e)){const t=OO(r);t?e.crypto=t.crypto:e.port||r.media.some((function(t){return!!t.port&&(e.crypto=t.crypto,!0)}))}})),i.sdp=kU.write(r),t(i)}))}}(),function(){const e=r.createAnswer;r.createAnswer=function(){const t=arguments;return e.apply(r,t).then((function(e){if(!r.localDescription?.sdp)return e;const t=kU.parse(r.localDescription.sdp),n=[];if(t.media.forEach((function(e){FU.forEach((function(t){TO(e,t,(function(e){n.push(e)}))}))})),n.length){const t=kU.parse(e.sdp);let r=!1;t.media.forEach((function(e){n.forEach((function(t){TO(e,{codec:t.rtp.codec,rate:t.rtp.rate},(function(e){e.rtp.payload!==t.rtp.payload&&(e.rtp.payload=t.rtp.payload,r=!0)}))}))})),r&&(e=new i({type:e.type,sdp:kU.write(t)}))}return e}))}}(),function(){const e=r.createOffer;r.createOffer=function(t){const i=arguments;return t&&t.offerToReceiveVideo>1&&(t.offerToReceiveVideo=1),e.apply(r,i)}}(),r.getSenders&&r.addTrack&&r.removeTrack||(r.getSenders=function(){return t.slice()},r.addTrack=function(e,i){if(!e||!i)throw new Error("both media track and stream need to be provided");r.getLocalStreams().some((function(e){return e.id===i.id}))||r.addStream(i);let n=t.find((function(t){return t.track.id===e.id}));return n||(n=new s(e,i),t.push(n)),n},r.removeTrack=function(e){r.getLocalStreams().filter((function(t){return t.id===e._stream.id})).forEach((function(e){r.removeStream(e)})),Qi(t,(t=>t===e))}),r}var BU=e=>UU.bind(null,e),VU=class{constructor(e){const t=e.configProvider.config.useSdpCapabilitiesLegacySession,i=e.configProvider.config.noRequiredCodecsWorkaround;this.RTCRtpReceiver=DU(e,t,i),this.SdpTransform=CU,this.RTCPeerConnection=BU(this.RTCRtpReceiver),this.RTCSessionDescription=xU()}};function HU(){function e(){throw new Error("unsupported platform")}this.SdpTransform=e,this.RTCPeerConnection=e,this.RTCSessionDescription=e,this.RTCRtpReceiver=e,this.RTCRtpSender=e}var $U=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.activeSpeakerManager=i,this.contributingSourcesProvider=n,this.lastSources=[],this.emptySourcesCount=0,this.poll=()=>{const e=this.contributingSourcesProvider?.getContributingSources();if(!e)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(e.filter((e=>{const t=this.lastSources.find((t=>t.source===e.source));return!t||t.timestamp!==e.timestamp})).map((e=>e.source))),this.updateLastSources(e),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(e){e?this.stopPolling():this.startPolling()}updateContributingSources(e){this.activeSpeakerManager.onContributingSourcesChanged(e)}startPolling(e=this.configProvider.config.webrtcContributingSourcesPollingInterval){!this.timer&&this.contributingSourcesProvider&&(this.logger.safe.info("Polling started"),this.timer=window.setTimeout(this.poll,e))}stopPolling(){this.timer&&(this.logger.safe.info("Polling stopped"),window.clearTimeout(this.timer),this.timer=void 0)}updateLastSources(e){this.lastSources=e.map((e=>({source:e.source,timestamp:e.timestamp})))}},jU=class{constructor(e,t,i,n){this.logger=e,this.peerConnection=t,this.logDiagnosticsError=i,this.sessionDiagnostics=n}getContributingSources(){try{if(!this.peerConnection?.getReceivers)return;const e=this.peerConnection.getReceivers().find((e=>"audio"===e.track.kind));return e?e.getContributingSources?.():[]}catch(e){return this.logger.safe.error("Failed to get contributing sources",e),void(this.logDiagnosticsError&&this.sessionDiagnostics&&(this.sessionDiagnostics.contributingSourcesError=`${e}`))}}},GU=class{constructor(e){this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.localSsrcs=new Map,this.ssrcGenerator=new WO,this.logger=e.logger.createChild("MM"),this.configProvider=e.configProvider,this.numVideoChannels=e.numVideoChannels}fromOffer(e,t){e.media.forEach((e=>{if(e.type===Gi.MEDIA_TYPE.audio)Gi.MODALITY.audio in t&&this.addMediaEntity(Gi.MODALITY.audio);else if(e.type===Gi.MEDIA_TYPE.video){if(Gi.MODALITY.video in t)for(let e=0;e<this.numVideoChannels;e++)this.addMediaEntity(Gi.MODALITY.video);Gi.MODALITY.sharing in t&&this.addMediaEntity(Gi.MODALITY.sharing)}else e.type===Gi.MEDIA_TYPE.data&&Gi.MODALITY.data in t&&this.addMediaEntity(Gi.MODALITY.data)}))}fromRemote(e,t){e.media.forEach(((e,i)=>{const n=MO(e);if(NO(e)||!(n in t))this.mediaEntities[i]?this.mediaEntities[i].disable():this.addDisabledMediaEntity(n),this.mediaEntities[i].setRemoteStreamId(null),this.mediaEntities[i].setRemoteTrackId(null);else{if(this.mediaEntities[i]?this.mediaEntities[i].update(n,e.mid||this.generateMid(i)):this.addMediaEntity(n,e.mid||this.generateMid(i)),e.msid)this.mediaEntities[i].setRemoteStreamId(e.msid.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(e.msid.split(" ")[1]);else if(e.ssrcs){const t=e.ssrcs.find((e=>"msid"===e.attribute));t?(this.mediaEntities[i].setRemoteStreamId(t.value.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(t.value.split(" ")[1])):this.logger.safe.warn(`No ssrc msid for media of type ${e.type} with mid ${e.mid}`)}const t=e.xSourceStreamId||this.generateSourceStreamId(i);this.mediaEntities[i].setXSourceStreamId(t)}}))}isEmpty(){return 0===this.mediaEntities.length}addMediaEntity(e,t){this.createMediaEntity(e,t||this.generateMid(this.mediaEntities.length))}addDisabledMediaEntity(e){this.createMediaEntity(e)}getMediaEntities(){return this.mediaEntities}createMediaEntity(e,t){const i=XO.create(this.configProvider,e,t);return this.mediaEntities.push(i),i}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[]}syncModalities(e,t,i){this.disableModalities(t),i||(this.enableModalities(t),this.addModalities(t))}enableModalities(e){this.mediaEntities.forEach(((t,i)=>{t.getModality()in e&&t.isDisabled()&&t.update(t.getModality(),this.generateMid(i))}))}disableModalities(e){this.mediaEntities.forEach((t=>{t.getModality()in e||t.disable()}))}setRollbackUpdateHandler(e){}addModalities(e){const t={};this.mediaEntities.map((e=>e.getModality())).forEach((e=>{t[e]=!0}));for(const i in e)i in t||this.addMediaEntity(i)}setLocalTracksInfo(e){this.mediaTracks=e,this.updateLocalSsrc(this.mediaTracks)}getLocalTracksInfo(){return this.mediaTracks}getLocalSsrcs(){return this.localSsrcs}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?t.setLocalTrackId(e.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)})))}updateMediaEntitiesWithActivityState(e,t){}backup(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[]}rollback(){this.mediaEntities=this.mediaEntitiesBackup}generateSourceStreamId(e){return e+10}generateMid(e){return`media_${e}`}updateLocalSsrc(e){e.forEach((e=>{if(!this.localSsrcs.get(e.modality)){const t=this.ssrcGenerator.nextVideoStreamSsrc().min;this.logger.safe.debug(`Ssrc updated for modality: ${e.modality}: ${t}`),this.localSsrcs.set(e.modality,t)}}))}},qU=p(ye()),zU=class{constructor(e,t,i,n,r){this.logger=e,this.RtcDescType=t,this.sessionDescription=i,this.negotiationQueue=n,this.mediaManager=r}configure(e){this.peerConnection=e}renegotiateNow(){return this.renegotiate(null,!0)}renegotiate(e,t=!1,i="local"){if(!this.peerConnection)throw new Error("trying to renegotiate without a peerConnection");const n="local"===i?this.createNegotiationTaskForHaveLocalOffer(e):this.createNegotiationTaskForHaveRemoteOffer();return t?(this.logger.safe.info(`forced ${i} renegotiation starting`),Promise.resolve(n())):this.negotiationQueue.add(n)}normalizeRemoteSdpSDES(e,t){if(t.media[0].crypto)e.media.forEach((e=>{delete e.fingerprint,delete e.setup,e.crypto=e.crypto.filter((e=>t.media[0].crypto.some((t=>t.id===e.id)))).slice(0,1)})),e.fingerprint&&delete e.fingerprint;else{const t=this.mediaManager.getMediaEntities().find((e=>void 0!==e.getExtension("setup")));e.media.forEach((e=>{const i=t?.getExtension("setup")||"actpass";"actpass"===e.setup&&(e.setup="active"===i?"passive":"active")}))}}normalizeRemoteSdpExtensions(e,t){e.media.forEach(((e,i)=>{const n=new Set(t.media[i].ext?.map((e=>e.value))||[]);e.ext=e.ext?.filter((e=>n.has(e.value)))}))}createNegotiationTaskForHaveLocalOffer(e){return async()=>{let t=this.peerConnection.remoteDescription.sdp;const i=this.peerConnection.localDescription.sdp;this.logger.safe.info(`local renegotiation starting remoteSdp=${!!t} localSdp=${!!i}`);const n=qU.parse(t),r=qU.parse(i);this.normalizeRemoteSdpSDES(n,r),this.normalizeRemoteSdpExtensions(n,r),t=qU.write(n);let s=new this.RtcDescType({sdp:t,type:"answer"});e&&e.forEach((e=>{s=e.modifyDescriptor(s)}));try{this.logger.safe.info("creating offer");const e=await this.peerConnection.createOffer(),t=this.sessionDescription.createLocalOffer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"offer"});this.logger.safe.info("setting local description"),this.logger.unsafe.debug(`local description, sdp: ${i.sdp}`),await this.peerConnection.setLocalDescription(i),this.logger.safe.info("setting remote description"),this.logger.unsafe.debug(`remote description, sdp: ${s.sdp}`),await this.peerConnection.setRemoteDescription(s),this.logger.safe.debug("local renegotiation done")}catch(e){throw this.logger.safe.error("local renegotiation failed: ",e.toString()),e}}}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 e=await this.peerConnection.createAnswer();this.logger.safe.info("applying answer");const t=this.sessionDescription.createLocalAnswer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"answer"});this.logger.safe.info("setting [answer] local description"),this.logger.unsafe.debug(`[answer] local description, sdp: ${i.sdp}`),await this.peerConnection.setLocalDescription(i),this.logger.safe.info("local answer for renegotiation is done")}catch(e){throw this.logger.safe.error("local answer for renegotiation failed: ",e.toString()),e}}}},WU=15e3,KU=class{constructor(e,t,i){this.settings=e,this.listener=t,this.logger=i,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(e){const t=Hn.Send.getResolutionByFs(e);t!==this.maxResolution&&(this.logger.safe.info(`Setting max resolution: ${t}`),this.maxResolution=t,this.lastSendBW&&this.processEstimatedBandwidth(this.lastSendBW))}updateEstimatedSendBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Send BW: ${e}`),this.processEstimatedBandwidth(e))}resetCurrentResolution(){this.currentResolution=null}getCurrentResolution(){return this.currentResolution?.fs}setCurrentResolution(e){this.currentResolution=e}applyRes(e){this.pendingResolution=e,this.coolingDown&&(!this.currentResolution||e.fs>this.currentResolution.fs)||(this.coolingDown=!0,this.logger.safe.info(`Changing resolution to ${e}`),this.listener&&this.listener.onResolutionChanged(e.fs).then((t=>{t?(e===this.pendingResolution&&(this.pendingResolution=null),this.coolingDown&&!this.currentResolution&&(this.coolingDown=!1),this.currentResolution=e,this.cooldown()):(this.logger.safe.info("Unable to apply resolution at the moment"),this.cooldown(5e3))})).catch((e=>{this.logger.safe.error(`Error while applying new resolution: ${JSON.stringify(e)}`),this.pendingResolution=null})))}cooldown(e=WU){!this.active||this.coolingDown&&this.cooldownEnd-Date.now()>WU||(this.cooldownTimer&&clearTimeout(this.cooldownTimer),this.coolingDown=!0,this.cooldownEnd=Date.now()+WU,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)}),e))}proposeResolution(e){let t=e;this.maxResolution&&this.maxResolution.fs<t.fs&&(t=this.maxResolution),this.currentResolution&&t.fs===this.currentResolution.fs||this.applyRes(t)}processEstimatedBandwidth(e){const{lowRes:t,highRes:i}=Hn.Send.getResolutionForBitrate(e),n=e<this.lastSendBW?i:t;e<this.lastSendBW&&n&&this.currentResolution&&this.currentResolution.fs<n.fs||(n&&this.proposeResolution(n),this.lastSendBW=e)}};function JU(e,t){const i=t.config.maxBandwidthInKbpsFallback>0?t.config.maxBandwidthInKbpsFallback:Math.floor(Number.MAX_SAFE_INTEGER/1e3),n=1e3*((t.mediaConfig.maxBandwidthInKbps||i)-(t.config.audioBandwidthInKbps||0)),r=e.transport?.selectedCandidatePair?.availableOutgoingBitrate??0;return Math.min(n,r)}var YU=class extends Vi{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.lastReportedAgo=1/0,this._forceUpdate=!1}forceUpdate(){this._forceUpdate=!0}onBandwidthChanged(e){this._forceUpdate?this.updateBandwidth(e,"forceUpdate"):this.processEstimatedBandwidth(e)}processEstimatedBandwidth(e){if(this.lastReportedAgo++,!e||this.bandwidth===e)return;const t=this.configProvider.config.webrtcSendBandwidthIgnoredUpdateLimit,i=this.configProvider.config.webrtcSendBandwidthThreshold,n=this.lastReportedAgo===1/0,r=!t&&!i,s=t&&this.lastReportedAgo>=t,a=i&&Math.abs((e-this.bandwidth)/this.bandwidth)>=i,o=this.configProvider.config.webrtcSendBandwidthAlwaysReportAfterDrop&&e<this.bandwidth;if(n||r||s||a||o){const t=+n|+r<<1|+s<<2|+a<<3|+o<<4,i=this.getUpdateReason(t);this.updateBandwidth(e,i)}}updateBandwidth(e,t){this.bandwidth=e,this.logger.safe.debug(`Updating send bandwidth: ${this.bandwidth}, reason: ${t}`),this.notifySendBandwidthChanged()}notifySendBandwidthChanged(){this._forceUpdate=!1,this.event("onSendBandwidthChanged").raise(this.bandwidth),this.lastReportedAgo=0}getUpdateReason(e){return 1&e?"firstReport":2&e?"throttlingDisabled":4&e?"noReportsForTooLong":8&e?"bigMovement":22&e?"drop":"none"}},QU=class{constructor(e,t,i,n,r,s,a){this.listener=e,this.statisticsGatherer=t,this.diagnostics=i,this.logger=n,this.configProvider=r,this.isSimulcastEnabled=a,this.serialQueue=new tk(this.logger),this.modality=Gi.MODALITY.video;const o=s.maxResolution?{maxFs:s.maxResolution.fs}:null;this.validator=new yD(this.logger.createChild("CapsValidator"),o),this.resolutionManager=new KU(s,this,this.logger.createChild("rm")),this.statisticsGatherer.on("onStatisticsChanged",(e=>this.onStatisticsChanged(e))),this.statisticsGatherer.on("onDiagnosticUpdated",(e=>this.onDiagnosticUpdated(e)))}async setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.causeId=e;const n=this.validator.ensureValidity(t[0]);this.streamSenderParams={...t[0],...n},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(e){this.resolutionManager.setCurrentResolution(e)}async onResolutionChanged(e){return this.applyCapabilities(this.getParamsToApply(e))}dispose(){this.resolutionManager.dispose(),this.resolutionManager=null}async applyCapabilities(e){return e?this.lastAppliedSenderParams===e?(this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}`),!0):(this.logger.safe.info(`Capabilities to apply: ${JSON.stringify(e)}`),this.lastAppliedSenderParams=e,this.listener.onReceiveCapabilitiesChanged(this.modality,this.causeId,[e])):(this.logger.safe.error("Send capabilities are not set. Cannot apply constraints"),!1)}getParamsToApply(e){if(!this.streamSenderParams)return null;const t=e||this.resolutionManager.getCurrentResolution();if(!t||this.streamSenderParams.maxFs<=t)return this.streamSenderParams;const i=tn(this.streamSenderParams);return i.maxFs=t,i}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.resolutionManager.updateEstimatedSendBandwidth(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){try{if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!e.video?.send?.length||!e.video.send[0])return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth");const t=JU(e.video.send[0],this.configProvider);this.resolutionManager.updateEstimatedSendBandwidth(t)}}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}};m([Uk()],QU.prototype,"applyCapabilities",1);var ZU=class{constructor(e,t,i,n,r){this.modality=e,this.listener=t,this.statisticsGatherer=i,this.diagnostics=n,this.isSimulcastEnabled=r}setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.listener.onReceiveCapabilitiesChanged(this.modality,e,t)}dispose(){}resetCurrentResolution(){}getCurrentResolution(){return null}setCurrentResolution(e){}},XU=class{constructor(e,t,i,n,r,s){this.logger=e,this.settings=t,this.listener=i,this.statsGatherer=n,this.diagnostics=r,this.configProvider=s,this.mediaSourceModels=[],this.pendingCapabilities=new Map}dispose(){this.mediaSourceModels.forEach((e=>{e.handler&&(e.handler.dispose(),e.handler=null)})),this.mediaSourceModels=null}updateRegisteredSources(e){this.logger.safe.info(`Local media params updated: ${JSON.stringify(e)}`);const t=[];this.mediaSourceModels.forEach((e=>t.push(e.sourceId)));const i=e.map((e=>e.sourceId)),n=hn(t,i);this.removeSourcesWithIds(n);const r=hn(i,t);this.addSourcesWithIds(r,e)}setMaxCapabilities(e,t){for(const i of e){if(!i.capabilities.length)continue;if(!i.sourceId){this.logger.safe.info(`SourceId is not defined to apply recv capabilities: ${JSON.stringify(i)}`);continue}const e=this.getModelWithSourceId(i.sourceId);if(!e){this.logger.safe.info(`Model is not registered for sourceId: ${i.sourceId}`),this.configProvider.config.enableCachingFMTP&&this.pendingCapabilities.set(i.sourceId,i);continue}this.logger.safe.info(`Capabilities handler found for sourceId: ${i.sourceId}`);const n=this.getOrCreateHandlerForModel(e,i.isSimulcast);n?n.setMaxCapabilities(i.causeId||t,i.capabilities):this.logger.safe.info(`Handler is not found for sourceId: ${i.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 e=Array.from(this.pendingCapabilities.values());this.setMaxCapabilities(e),this.pendingCapabilities.clear()}clearPendingCapabilities(){this.pendingCapabilities.clear()}resetCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));e?.handler&&e.handler.resetCurrentResolution()}getCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));return e?.handler?e.handler.getCurrentResolution():this.currentResolution?.fs}setCurrentResolution(e){const t=this.mediaSourceModels.find((e=>e.modality===Gi.MODALITY.video));t?.handler?t.handler.setCurrentResolution(e):this.currentResolution=e}getOrCreateHandlerForModel(e,t){return e.handler||(e.handler=this.getCapabilitiesHandler(e.modality,t)),e.handler}addSourcesWithIds(e,t){e.forEach((e=>{const i=t.find((t=>t.sourceId===e));this.registerSource(e,i.modality)}))}removeSourcesWithIds(e){e.forEach((e=>this.unregisterSource(e)))}registerSource(e,t){this.logger.safe.info(`SourceId ${e} registered with mediaType: ${t}`),this.mediaSourceModels.push({modality:t,sourceId:e})}unregisterSource(e){const t=this.mediaSourceModels.find((t=>t.sourceId===e));t?(t.handler&&t.handler.dispose(),this.mediaSourceModels.splice(this.mediaSourceModels.indexOf(t),1),this.logger.safe.info(`SourceId ${e} unregistered`)):this.logger.safe.info(`Model doesn't exist with sourceId ${e}`)}getModelWithSourceId(e){return this.mediaSourceModels.find((t=>t.sourceId===e))}getCapabilitiesHandler(e,t){if(e===Gi.MODALITY.audio)return null;if(e===Gi.MODALITY.video&&!t&&this.settings.customBwEstimationEnabled){const e=new QU(this.listener,this.statsGatherer,this.diagnostics,this.logger.createChild("ach"),this.configProvider,this.settings,t);return this.currentResolution&&e.setCurrentResolution(this.currentResolution),e}return new ZU(e,this.listener,this.statsGatherer,this.diagnostics,t)}},eB=class extends Vi{constructor(e,t,i,n,r,s){super(e),this.logger=e,this.multiParty=t,this.configProvider=i,this.mediaManager=n,this.statsGatherer=r,this.diagnostics=s,this.rendererResolutions=new Map,this.rendererResolutionsApplied=new Map,this.rendererResolutionMax=new Map,this.hasPendingLimitResolutionUpdate=!1,this.spotlightedRenderers=[]}addRenderer(e){this.rendererResolutions.set(e,{width:0,height:0}),e.on("onRendererSizeChanged",((e,t)=>{this.onRendererSizeChanged(e,t)})),this.scheduleUpdateLimitedResolutions()}removeRenderer(e){this.rendererResolutions.delete(e),this.rendererResolutionsApplied.delete(e),this.rendererResolutionMax.delete(e),this.scheduleUpdateLimitedResolutions()}clearRenderers(){this.rendererResolutions.clear(),this.rendererResolutionsApplied.clear(),this.rendererResolutionMax.clear()}getMaxAllowedVideoFS(){const e=this.getMaxHeightFromConfig(this.sizedRenderersCount);return this.getMaxFSForHeight(e)}limitResolutionOnPoorPerformance(e){const t=this.getRendererByMsi(e);if(!t)return;const i=t.resolution.height>t.resolution.width,n=Hn.Recv.getNextLowerResolution(t.resolution.width,t.resolution.height);if(!n)return;const r={width:i?n.height:n.width,height:i?n.width:n.height};this.rendererResolutionMax.set(t.renderer,r),this.diagnostics?.registerResolutionChangeRequest({ts:Date.now(),msi:t.renderer.getMsi(),res:r}),this.logger.safe.info(`Poor perf. Limiting resolution for renderer msi: ${t.renderer.getMsi()} from ${t.resolution.height}p to ${r.height}p`),this.onRendererSizeChanged(t.renderer,r)}get renderersCount(){return this.rendererResolutions.size}get sizedRenderersCount(){return this.configProvider.config.excludeUnsizedRenderersFromMultiviewResolutionLimits?[...this.rendererResolutions.values()].filter((e=>e.height>0)).length:this.renderersCount}getMaxFSForHeight(e){return this.limitMaxFS(Hn.Recv.getMaxFsForHeight(e))}getRendererByMsi(e){for(const[t,i]of this.rendererResolutions.entries())if(t.getMsi()===e)return{renderer:t,resolution:i};return null}applyRendererResolution(e,t){this.setMaxFSCapabilities(e,t),this.rendererResolutionsApplied.set(e,t);const i=e.getMediaStream()&&e.getMediaStream().getVideoTracks();i?.[0]&&this.statsGatherer.setPreferredResolution(i[0].id,t,e.getModality())}onRendererSizeChanged(e,t){this.rendererResolutions.set(e,t),this.scheduleUpdateLimitedResolutions()}scheduleUpdateLimitedResolutions(){this.hasPendingLimitResolutionUpdate||(this.hasPendingLimitResolutionUpdate=!0,window.setTimeout((()=>{this.hasPendingLimitResolutionUpdate=!1;const e=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((e=>e.getMsi()))}, max spotlight height: ${this.configProvider.config.maxSpotlightResolution}`);for(const[t,i]of this.rendererResolutions.entries()){if(!i.height)continue;const n=e.get(t.getMsi()),r=this.limitRendererResolution(t,n||i),s=this.rendererResolutionsApplied.get(t);(!s||s.height!==r.height||s.width!==r.width)&&this.applyRendererResolution(t,r)}}),this.configProvider.config.multiviewResolutionLimitUpdateThrottleDelay))}findSpotlightedRenderers(){if(this.sizedRenderersCount<=1||!this.configProvider.config.isSpotlightEnabled)return[];let e=!1,t=0;for(const[i,n]of this.rendererResolutions.entries())n.height&&n.height!==t&&(t&&(e=!0),t=n.height);if(!e)return[];const i=new Gg(((e,t)=>e.resolution.width>t.resolution.width));for(const[e,t]of this.rendererResolutions.entries())i.enqueue({renderer:e,resolution:t});const n=[];let r=this.configProvider.config.maxNumberOfPinnedVideos;for(;r;){const e=i.peek()?.resolution?.width,t=[];for(;i.peek()?.resolution?.width===e;)t.push(i.dequeue().renderer);if(!(r-t.length>=0))break;r-=t.length,n.push(...t)}return n}getMaxHeightFromConfig(e,t=!1){return t?this.configProvider.config.maxSpotlightResolution:this.configProvider.config.multiviewResolutionLimits[`${e}`]||this.configProvider.config.multiviewResolutionLimits.more}getMaxHeight(e){const t=this.spotlightedRenderers.some((t=>t.getMsi()===e.getMsi()));let i=this.getMaxHeightFromConfig(this.sizedRenderersCount,t);const n=this.rendererResolutionMax.get(e);return n&&(i=Math.min(i,Math.min(n.height,n.width))),i}limitRendererResolution(e,t){const i=this.getMaxHeight(e);if(!i)return t;if(t.height>t.width&&t.width>i){const e=i/t.width;return{height:Math.ceil(t.height*e),width:i,limited:!0}}if(t.width>t.height&&t.height>i){const e=i/t.height;return{height:i,width:Math.ceil(t.width*e),limited:!0}}return t}setMaxFSCapabilities(e,t){const i=e.getMediaStream();if(!i)return void this.logger.safe.warn("renderer has no stream attached");const n=this.mediaManager.getMediaEntityByRemoteStreamId(i.id);if(!n?.getLocalRecvCapabilities())return void this.logger.safe.warn(`no capabilities for provided modality: ${e.getModality()}`);const r=t.limited?this.getMaxFSForHeight(t.height):this.getMaxFS(t.width,t.height),s=n.getLocalRecvCapabilities();s.setMaxFS(r,(()=>{if(this.logger.safe.info(`updated max-fs video capability to ${r} for renderer msi: ${e.getMsi()}`),this.multiParty&&this.configProvider.config.webrtcMultiPartyRecvVideoSignaling){const t=e.getMsi(),n=s.buildFmtp();this.event("onSourceRequestRequired").raise(i.id,t,n)}else this.event("onNegotiationRequired").raise()}))}getMaxFS(e,t){return this.limitMaxFS(Hn.Recv.getMaxFsForHeight(t))}limitMaxFS(e){return this.multiParty?Math.min(e,this.configProvider.config.webrtcMultiPartyRecvVideoMaxFS):Math.min(e,this.configProvider.config.webrtcRecvVideoMaxFS)}groupMaxRenderersResolutionsByMsi(){const e=new Map;return this.rendererResolutions.forEach(((t,i)=>{const n=i.getMsi(),r=e.get(n);(!r||t.width>r.width&&t.height>r.height)&&e.set(n,t)})),e}},tB=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.getModality=t,this.isRendering=!1,this.currentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0}captureRawStatistics(e){const t=e.googFrameRateDecoded,i=e.googFrameRateReceived,n=e.bytesReceived;void 0!==n&&this.getModality()!==Gi.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateBitrate(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}updateRenderingTracker(e){const t=e.extensions.frameRateDecoded||0,i=e.extensions.frameRateReceived||0,n=e.extensions.bitrate;void 0!==n&&this.getModality()!==Gi.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateLowBitrateDuration(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Gi.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}calculateLowBitrateDuration(e,t){e/1e3<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}calculateBitrate(e,t){const i=8*(e-this.lastBytesRecv);this.lastBytesRecv=e,this.calculateLowBitrateDuration(i,t)}setIsRendering(e){const t=this.currentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted;t!==this.isRendering&&(this.isRendering=t,this.event("onIsRenderingChanged").raise(this.isRendering))}},iB=class extends Vi{constructor(e,t,i){super(),this.videoElement=e,this.configProvider=t,this.getTimeToFirstFrame=i,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 e=this.videoElement.currentTime,t=e===this.prevCurrentTime,i=this.videoElement.webkitDecodedFrameCount,n=void 0===i||i===this.prevDecodedFrameCount;if(this.prevCurrentTime=e,this.prevDecodedFrameCount=i,-1!==this.getTimeToFirstFrame())if(t&&n){const e=Date.now();this.currentFreezeDuration+=e-this.prevTimestamp,this.prevTimestamp=e}else{if(this.currentFreezeDuration>this.configProvider.config.freezeMinDuration){const e=this.calcFreeze();this.event("onFreezeEnded").raise(e)}this.currentFreezeDuration=0}this.prevTimestamp=Date.now()}getEndOfTheFreeze(){let e=0;return this.currentFreezeDuration>0&&(e=this.calcFreeze(),this.currentFreezeDuration=0),e}dispose(){const e=this.getEndOfTheFreeze();this.event("onFreezeEnded").raise(e),clearInterval(this.freezeDurationTimer)}calcFreeze(){const e=Date.now()-this.prevTimestamp;return this.currentFreezeDuration+e}},nB=class extends Vi{constructor(e,t,i,n){super(),this.videoElement=e,this.minInterval=t,this.maxInterval=i,this.window=Mp.window,this.devicePixelRatio=n&&window.devicePixelRatio||1,this.originalVideoElementSize={width:e.offsetWidth,height:e.offsetHeight},this.initializeSizeTracking()}get width(){return this.originalVideoElementSize.width*this.devicePixelRatio}get height(){return this.originalVideoElementSize.height*this.devicePixelRatio}initializeSizeTracking(){const e=Math.floor(Math.random()*Math.abs(this.maxInterval-this.minInterval))+this.minInterval;this.elementSizeTrackingRef=this.window.setInterval((()=>{this.videoElementSizeChanged()&&(this.saveCurrentVideoElementSize(),this.raiseChanged())}),e)}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}},rB=class extends dk{constructor(e,t,i,n,r,s){super(r,e.createChild("remote"),t),this.diagnostics=i,this.subscriptionManager=n,this.sessionDiagnostics=s,this.disposed=!1,this.currentIsRendering=!1,this.startTimeTTFF=0,this.timeToFirstFrame=-1,this.isTimeToFirstFrameReported=!1,this.configProvider.config.freezeIntervalFrequency&&(this.freezeTracker=new iB(this.getVideoElement(),this.configProvider,(()=>this.timeToFirstFrame)),this.freezeTracker.on("onFreezeEnded",(e=>{this.diagnostics?.addFreezeDuration(e),this.event("onFreezeEnded").raise(e)}))),this.configProvider.config.isRenderingBasedOnRawStatistics&&(this.isRenderingTracker=new tB(this.configProvider,this.getModality.bind(this)),this.isRenderingChangedSubscription=this.isRenderingTracker.on("onIsRenderingChanged",(e=>{this.setIsRendering(e)}))),this.overlayStats=new ok(this.configProvider.config.showStatsInCall,r,this)}getEndOfTheFreeze(){return this.freezeTracker?.getEndOfTheFreeze()}resetTimeToFirstFrameFlag(){this.isTimeToFirstFrameReported=!1}setIsRendering(e){this.currentIsRendering!==e&&(this.currentIsRendering=e,this.captureIsRenderingEvent(e))}updateStatsOverlay(e,t){this.overlayStats.setStats(e,t)}updateIsRenderingTracker(e){this.isRenderingTracker?.updateRenderingTracker(e)}subscribeVideoAsync(e,t){return this.timeToFirstFrameSinceSubscriptionStart=Date.now(),new Promise(((i,n)=>{this.modality=t?Gi.MODALITY.sharing:Gi.MODALITY.video,this.diagnostics&&(this.diagnostics.msi=e,this.diagnostics.modality=this.modality),this.trackElementSizeChange(),this.unsubscribe(),this.on("onVideoSizeChanged",((t,i)=>{if(this.modality===Gi.MODALITY.video&&this.sessionDiagnostics?.registerResolutionChangeEvent({ts:Date.now(),msi:e,res:{width:t,height:i}}),this.isTimeToFirstFrameReported)return;if(-1===this.timeToFirstFrame){const e=Date.now();this.timeToFirstFrame=e-this.startTimeTTFF,this.timeToFirstFrameSinceSubscriptionStart=Date.now()-this.timeToFirstFrameSinceSubscriptionStart}const n=this.getTrackId();n&&(this.diagnostics.timeToFirstFrameSinceSubscriptionStart=this.timeToFirstFrameSinceSubscriptionStart,this.diagnostics.timeToFirstFrame=this.timeToFirstFrame,this.sizeTracker?.triggerVideoElementSizeChange(),this.event("onVideoStarted").raise(this.timeToFirstFrame,this.timeToFirstFrameSinceSubscriptionStart,n),this.isTimeToFirstFrameReported=!0)})),this.on("onVideoRendererStateChanged",(e=>{this.diagnostics.addStateChange(e)}));const r=this.subscriptionManager.subscribeVideo(this.modality,e);this.subscription=r,this.logger.safe.info(`subscribing renderer to type: ${r.modality} msi: ${r.msi}`),r.setOnMediaStreamChangedHandler((e=>{const t=this.getMediaStream();this.attachMediaStream(e),e&&(this.startTimeTTFF=Date.now());const n=this.getTrackId();n&&this.diagnostics&&(this.diagnostics.trackId=n),this.logger.safe.info(`subscribed renderer to type: ${r.modality} msi: ${r.msi} on stream #${e?e.id:"none"}`),e&&t!==e&&this.sizeTracker?.triggerVideoElementSizeChange(),i()})),r.setOnErrorHandler((t=>{this.logger.safe.error(`failed to subscribe renderer ${tt(t)}`),"webRtcSession cleanup"===JSON.stringify(t)&&(this.logger.safe.info(`Retry to subscribe to video stream with msi: ${e}. Previous session was cleaned up`),this.subscriptionManager.streamChangedByMsi(e),i()),n(t)}))}))}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 e=this.modality===Gi.MODALITY.sharing,t=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMin:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,i=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMax:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax;t&&i?(this.sizeTracker=new nB(this.getVideoElement(),t,i,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(e){this.diagnostics&&(this.diagnostics.isRendering=e),this.event("onIsRenderingChanged").raise(e,this.getModality(),this.getTrackId())}},sB=class{constructor(e,t,i,n,r,s){this.logger=e,this.configProvider=t,this.statsGatherer=i,this.sessionDiagnostics=n,this.remoteVideoResolutionManager=r,this.domOverrides=s,this.remoteRendererSubscriptions=new Map,this.diagnostics=n?.newRemoteVideoManagerDiagnostics()}createRenderer(e,t,i){const n=new rB((i??this.logger).createChild("videorenderer"),this.configProvider,this.diagnostics?.newRendererDiagnostics(),t,e,this.sessionDiagnostics);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(n.getVideoElement()),this.addRenderer(n),n}moveRenderers(e){this.renderers.forEach((t=>{t.resetTimeToFirstFrameFlag(),e.addRenderer(t),this.removeRenderer(t)}))}getMaxAllowedVideoFS(){return this.remoteVideoResolutionManager.getMaxAllowedVideoFS()}dispose(){this.renderers.forEach((e=>e.resetTimeToFirstFrameFlag())),this.renderers.forEach((e=>{const t=e.getTrackId(),i=e.getEndOfTheFreeze();this.statsGatherer.setFreezeDuration(i,t)})),this.remoteRendererSubscriptions.forEach(((e,t)=>{t.dispose(),e.forEach((e=>e.dispose()))})),this.remoteRendererSubscriptions.clear(),this.remoteVideoResolutionManager.clearRenderers()}processStatsReport(e){this.configProvider.config.isRenderingBasedOnRawStatistics&&this.onDiagnosticUpdated(e),this.updateOverlayStats(e)}processLegacyStats(e){this.configProvider.config.isRenderingBasedOnRawStatistics||this.renderers.forEach((t=>{const i=t.getTrackId();if(e.remoteVideoStreams[i]){const n=e.remoteVideoStreams[i].isRendering;void 0!==n&&t.setIsRendering(n)}}))}playVideo(){this.renderers.forEach((e=>e.playVideo()))}get renderers(){return Array.from(this.remoteRendererSubscriptions,(([e])=>e))}addRenderer(e){this.remoteRendererSubscriptions.set(e,this.subscribeOnEvents(e)),this.logger.safe.info("Added renderer to manager"),this.remoteVideoResolutionManager.addRenderer(e)}generateVideoRecvStats(e){const t=new Map,i=e=>{e?.forEach((e=>{const i=e.track?.trackIdentifier??e.inboundRTP.trackIdentifier;t.set(i,e)}))};return i(e.sharing?.recv),i(e.video?.recv),t}updateOverlayStats(e){const t=this.generateVideoRecvStats(e);this.renderers.forEach((i=>{const n=i.getTrackId();t.has(n)&&e.audio?.recv?.length&&i.updateStatsOverlay(t.get(n),e.audio.recv[0])}))}onDiagnosticUpdated(e){const t=[...e.video?.recv??[],...e.sharing?.recv??[]];if(t.length){const e=new Map;t.forEach((t=>{e.set(t.track?.trackIdentifier,t)})),this.renderers.forEach((t=>{const i=t.getTrackId();e.has(i)&&t.updateIsRenderingTracker(e.get(i))}))}}subscribeOnEvents(e){return[e.on("onRendererDisposed",(e=>this.onRendererDisposed(e))),e.on("onVideoStarted",((e,t,i)=>this.onVideoStarted(e,t,i))),e.on("onFreezeEnded",(t=>{const i=e.getTrackId();this.statsGatherer.setFreezeDuration(t,i)})),e.on("onIsRenderingChanged",((e,t,i)=>this.statsGatherer.setIsRendering(e,t,i)))]}onRendererDisposed(e){this.logger.safe.debug("Renderer removed from manager"),this.removeRenderer(e),this.domOverrides.onMediaElementRemoved&&this.domOverrides.onMediaElementRemoved(e.getVideoElement())}removeRenderer(e){this.remoteRendererSubscriptions.get(e).forEach((e=>e.dispose())),this.remoteRendererSubscriptions.delete(e),this.remoteVideoResolutionManager.removeRenderer(e)}onVideoStarted(e,t,i){this.statsGatherer.setTimeToFirstFrame(e,t,i)}},aB=class extends Vi{constructor(e,t,i){super(),this.configProvider=t,this.callDeviceManager=i,this.lastFramerateInput=-1,this.trackInfo=[],this.timeoutId=null,this.logger=e.createChild("localStreamWatcher"),this.callDeviceManagerSub=i.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, updating subscriptions"),this.handleDeviceManagerChange()}))}get effectsManager(){return this.callDeviceManager.getDeviceManager("Video").effectsManager}startWatching(e,t){(this.configProvider.config.videoCaptureFreezeTimeout||t)&&(this.trackInfo=e,this.performanceMonitor=t,this.configProvider.config.videoCaptureFreezeTimeout&&(this.videoEffectManagerSubscription||(this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e))))))}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(e){this.callDeviceManagerSub?.dispose(),super.dispose(e),this.stopWatching()}onDiagnosticUpdated(e){if(!this.trackInfo.length||!e.video?.send?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Updating local video stream watcher");const t=e.video?.send[0],i=[];let n,r=0;[t,...t.altLayouts??[]].forEach((e=>{const t=e.mediaSource,s=t?.framesPerSecond??0;this.trackInfo.some((e=>e.trackId===t.trackIdentifier))&&((!n||r<s)&&(n=t,r=s),this.performanceMonitor&&i.push(e.outboundRTP))})),this.performanceMonitor?.monitor(i),this.configProvider.config.videoCaptureFreezeTimeout&&(n?r!==this.lastFramerateInput&&(0===r?this.scheduleCaptureFreezeStart(n.trackIdentifier,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${n.trackIdentifier}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=r):this.logger.safe.warn("WebRTC Stats for send video not found"))}onStatisticsChanged(e){if(!this.trackInfo.length||!this.configProvider.config.videoCaptureFreezeTimeout)return;let t;Object.keys(e.localVideoStreams).forEach((i=>{const n=e.localVideoStreams[i];this.trackInfo.some((e=>e.trackId===n.trackId))&&(!t||t.frameRateInput<n.frameRateInput)&&(t=n)})),t?t.frameRateInput!==this.lastFramerateInput&&(0===t.frameRateInput?this.scheduleCaptureFreezeStart(t.trackId,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${t.trackId}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=t.frameRateInput):this.logger.safe.warn("WebRTC Stats for send video not found")}onVideoFreezeDetected(e){this.logger.info(`onVideoCaptureFreeze, webcam freeze detected trackId: ${e}`),this.event("onVideoCaptureFreeze").raise(!1,!0)}scheduleCaptureFreezeStart(e,t){this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,this.logger.safe.info(`onVideoCaptureFreeze start for trackId: ${e} (isWebcamStream: ${t})`),this.event("onVideoCaptureFreeze").raise(!0,t)}),this.configProvider.config.videoCaptureFreezeTimeout)}disposeTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleDeviceManagerChange(){this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e)))}},oB=class{constructor(e){this.queue=[],this.logger=e}cleanup(){this.queue.forEach((e=>{e.reject({notSent:e.tones})})),this.queue=[]}waitForNotification(e){return e?(this.logger.unsafe.info("sending dtmf tones: ",e),new Promise(((t,i)=>{this.queue.push({tones:e,resolve:t,reject:i})}))):Promise.reject(new Error("invalid input"))}toneSent(e){this.queue[0]&&(e===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 '${e}'`)),this.queue.shift(),this.toneSent(e)))}},lB=class{constructor(e){this.webRtcSender=null,this.configProvider=e.configProvider,this.queue=new oB(e.logger)}sendDtmf(e,t){return e?.getSenders?(this.syncSender(e),this.webRtcSender?(this.webRtcSender.ontonechange=this.onToneChange.bind(this),this.webRtcSender.insertDTMF(this.webRtcSender.toneBuffer+t,this.configProvider.config.dtmf.toneDuration,this.configProvider.config.dtmf.toneGap),this.queue.waitForNotification(t)):Promise.reject(new Error("not available"))):Promise.reject(new Error("bad peerConnection"))}canSendDtmf(e){return!!e?.getSenders&&(this.syncSender(e),!!this.webRtcSender&&this.webRtcSender.canInsertDTMF)}dispose(){this.queue.cleanup()}syncSender(e){const t=e.getSenders().filter((e=>e.track&&"audio"===e.track.kind)).filter((e=>e.dtmf?.canInsertDTMF))[0];this.webRtcSender&&t&&t.dtmf!==this.webRtcSender&&(this.webRtcSender.ontonechange=null,this.queue.cleanup()),this.webRtcSender=t?t.dtmf:null}onToneChange(e){e.tone&&this.queue.toneSent(e.tone)}},cB=e=>new lB(e),dB=class extends Vi{constructor(e,t,i,n,r){super(i),this.pc=e,this.cryptoMethod=t,this.logger=i,this.configProvider=n,this.diagnostics=r,this.iceConnectionStateInternal="new",this.isWaitingAcceptProvisionalInternal=!1,this.state="new",this.toBeCalledOnConnected=[],this.toBeCalledOnProvisionalConnected=[],this.handleSignalingStateChange=()=>{const e=this.pc.signalingState,t=this.signalingStateInternal;if(this.logger.safe.info(`RTCPeerConnection onsignalingstatechange signalingState: ${this.signalingStateInternal} -> ${e}`),this.signalingStateInternal=e,this.diagnostics.signalingState=e,this.event("signalingStateChanged").raise(this.signalingStateInternal,t,be()),!this.configProvider.config.useDtlsTrasportConnectionCheck||this.transport||1!==this.cryptoMethod||this.hasPcConnectionState)return;const i=this.pc.getReceivers().find((e=>!!e.transport));this.transport=i?.transport,this.transport&&(this.transport.onstatechange=this.handleDtlsTransportStateChange)},this.handleIceConnectionStateChange=()=>{const e=this.pc.iceConnectionState;this.logger.safe.info(`RTCPeerConnection oniceconnectionstatechange iceConnectionState: ${e} pc.signalingState: ${this.pc.signalingState}`),this.iceConnectionStateInternal=e,this.diagnostics.iceConnectionState=e,this.event("iceConnectionStateChanged").raise(this.iceConnectionStateInternal,be()),this.shouldRaise(0)&&this.updateState(e)},this.handleConnectionStateChange=()=>{const e=this.pc.connectionState;this.logger.safe.info(`RTCPeerConnection onconnectionStatechange connectionState: ${e} pc.signalingState: ${this.pc.signalingState}`),this.connectionStateInternal=e,this.diagnostics.connectionState=e,this.event("connectionStateChanged").raise(this.connectionStateInternal,be()),this.shouldRaise(1)&&this.updateState(e)},this.handleDtlsTransportStateChange=()=>{const e=this.transport.state;this.logger.safe.info(`RTCDtlsTransport onstatechange state: ${e} pc.signalingState: ${this.pc.signalingState}`),this.dtlsStateInternal=e,this.diagnostics.dtlsTransportState=e,this.event("dtlsTransportStateChanged").raise(this.dtlsStateInternal,be()),this.shouldRaise(3)&&this.updateState(e)},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(e){this.isWaitingAcceptProvisionalInternal!==e&&(this.logger.safe.debug(`isProvisional set ${this.isWaitingAcceptProvisionalInternal} -> ${e}`),this.isWaitingAcceptProvisionalInternal=e,this.diagnostics.provisional=e,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(e,t="unknown",i=!1,n=!0){return this.diagnostics.scheduleDoOnConnected(e,t,i,n),n&&this.isConnected&&(i||!this.isWaitingAcceptProvisionalInternal)?(this.logger.safe.info(`Running callback immediately ${t}`),this.diagnostics.runDoOnConnected(e,!0),void e()):i?(this.logger.safe.info(`Queuing provisional connected callback '${t}'`),void this.toBeCalledOnProvisionalConnected.push(e)):(this.logger.safe.info(`Queuing connected callback '${t}'`),void this.toBeCalledOnConnected.push(e))}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(e,t=!0){if(t&&(this.statePrevious=this.state),this.state=e,this.event("stateChanged").raise(this.state,this.statePrevious,be()),this.diagnostics.transportState=e,this.isConnected){if(!this.isWaitingAcceptProvisionalInternal&&this.toBeCalledOnConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnConnected.length} callbacks on connected`);this.toBeCalledOnConnected.length;){const e=this.toBeCalledOnConnected.shift();this.diagnostics.runDoOnConnected(e),e()}if(this.toBeCalledOnProvisionalConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnProvisionalConnected.length} callbacks on provisional connected`);this.toBeCalledOnProvisionalConnected.length;){const e=this.toBeCalledOnProvisionalConnected.shift();this.diagnostics.runDoOnConnected(e),e()}}}shouldRaise(e){switch(e){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=${e}`),!1}}},uB=class{constructor(e,t,i,n,r,s){this.logger=e,this.emulator=t,this.qualityManager=i,this.diagnostics=n,this.configProvider=r,this.statsGatherer=s,this.previousSequenceNumber=new Map,this.modifiers=this.configProvider.mediaConfig.simulcastSessionEnabled?[]:[new Zx(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider)]}dispose(){this.cleanupDevToolsInjector(),this.modifiers&&(this.modifiers.forEach((e=>e.dispose())),this.modifiers=null),this.emulator=null,this.logger=this.logger.createChild("DISPOSED")}handleMessage(e){const t=e.controlInfo[0].sourceId;if(this.previousSequenceNumber.has(t)&&e.sequenceNumber<this.previousSequenceNumber.get(t))return this.statsGatherer.addVideoControlMessage(!0),this.diagnostics?.addVideoControlMessage(!0),this.logger.safe.info(`Discarded old media stream control message for sourceId ${t}: (${JSON.stringify(e)})`),Promise.resolve();this.previousSequenceNumber.set(t,e.sequenceNumber),this.statsGatherer.addVideoControlMessage(),this.diagnostics?.addVideoControlMessage(),this.configProvider.config.enableDevtoolsAPI&&this.injectFmtpHandler(e);const i={controlVideoStreaming:e};return this.configureResolution(i),this.modifiers.length?(this.modifiers.forEach((e=>e.setVideoControlMessage(i))),this.emulator.renegotiate(this.modifiers)):Promise.resolve()}configureResolution(e){this.logger.safe.info(`Signaling FMTP: ${JSON.stringify(e.controlVideoStreaming)}`);const t=String(e.controlVideoStreaming.sequenceNumber),i=e.controlVideoStreaming.controlInfo[0].fmtParamsList,n=e.controlVideoStreaming.controlInfo[0].fmtParams,r=i&&this.configProvider.config.webrtcFmtParamListSupported?this.parseFmtParamsList(i):[this.parseFmtParams(n)],s=+e.controlVideoStreaming.controlInfo[0].sourceId,a=[{causeId:t,isSimulcast:r.some((e=>void 0!==e.rid))||r.length>1,capabilities:r,sourceId:s}];this.qualityManager.setMaxCapabilities(a)}parseFmtParamsList(e){return e.map((e=>this.parseFmtParams(e)))}parseFmtParams(e){const t=new SO(e);return{maxFs:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Gi.VIDEO_CAPABILITIES.MAX_BR_PATH),ssrc:+t.get(Gi.VIDEO_CAPABILITIES.SSRC_PATH),rid:t.get(Gi.VIDEO_CAPABILITIES.RID_PATH),keyframe:this.shouldGenerateKeyFrame(t),vlaDebug:t.get(Gi.VIDEO_CAPABILITIES.VLA_DEBUG)}}shouldGenerateKeyFrame(e){return e.get(Gi.VIDEO_CAPABILITIES.KEYFRAME_PATH)?!!+e.get(Gi.VIDEO_CAPABILITIES.KEYFRAME_PATH):this.configProvider.config.webrtcAllowRestoreKeyframe}injectFmtpHandler(e){const t=window;t?.webMA&&(t.webMA.fmtp||(t.webMA.fmtp={handleMessage:this.handleMessage.bind(this)}),t.webMA.fmtp.lastFmtp=e)}cleanupDevToolsInjector(){const e=window;e?.webMA&&delete e.webMA.fmtp}},hB=(e=>(e[e.ThreeStreamSimulcast=0]="ThreeStreamSimulcast",e[e.HardwareEncoder=1]="HardwareEncoder",e[e.Encode1080P=2]="Encode1080P",e[e.BroadcastMode=3]="BroadcastMode",e))(hB||{}),gB=class extends Vi{constructor(e,t){super(t),this.mediaType=e,this.logger=t,this.features={}}notify(){super.raiseChanged()}find(e){var t;return(t=this.features)[e]??(t[e]={})}set(e,t,i){const n=this.find(e);let r=!1;return void 0!==t&&n.server!==t&&(this.logger.safe.info(`Server support for [${this.mediaType}][${hB[e]}] changed from ${n.server} to ${t}`),n.server=t,r=!0),void 0!==i&&n.client!==i&&(this.logger.safe.info(`Client support for [${this.mediaType}][${hB[e]}] changed from ${n.client} to ${i}`),n.client=i,r=!0),r}toggleServer(e,t){return!!this.set(e,t,void 0)&&(this.notify(),!0)}toggleClient(e,t){return!!this.set(e,void 0,t)&&(this.notify(),!0)}toggle(e,t){return!!this.set(e,t,t)&&(this.notify(),!0)}hasAnySupport(e){const t=this.find(e);return!0===t.client||!0===t.server}hasFullSupport(e){const t=this.find(e);return!0===t.client&&!0===t.server}hasClientSupport(e){return!0===this.find(e).client}hasServerSupport(e){return!0===this.find(e).server}},pB=class extends Vi{constructor(e){super(e),this.logger=e,this.modalities={Video:new gB("Video",this.logger),ScreenShare:new gB("ScreenShare",this.logger)},this.blocked=new Set;for(const e of Object.keys(this.modalities))this.modalities[e].changed((()=>{this.notify(this.modalities[e],!1)}))}notify(e,t){this.blocked.has(e.mediaType)&&!0!==t||(this.blocked.add(e.mediaType),this.logger.safe.info(`Notify: ${e.mediaType}`),this.event("onVideoFeaturesChanged").raise(e),this.blocked.delete(e.mediaType))}manageFeatureSupport(e){for(const e of Object.values(this.modalities))this.blocked.add(e.mediaType);e();for(const e of[...this.blocked])this.notify(this.modalities[e],!0)}get(e){if(!this.modalities[e])throw this.logger.safe.error(`Unsupported media type: ${e}`),new Error(`Unsupported media type: ${e}`);return this.modalities[e]}},mB=class e{constructor(e){this.configProvider=e}getVideoControlMessage(t,i,n){const r={controlVideoStreaming:{sequenceNumber:++e.sequence,globalTimeStamp:(new Date).toString(),controlInfo:[{control:"start",sourceId:i,streamMsid:t}]}};return n&&(r.controlVideoStreaming.controlInfo[0].fmtParams=vO(n)),r}getSourceRequestMessage(t,i,n,r){if(!n)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const s={sourceId:i,streamMsid:t,fmtParams:n};return s.subStreamIndex=r,{type:"sr",controlVideoStreaming:{sequenceNumber:++e.sequence,controlInfo:s}}}getSignalingSourceRequestMessage(t,i,n,r,s){if(!r)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const a={sourceId:i,streamMsid:t,fmtParams:r};return a.subStreamIndex=s,{applyChannelParameters:{multiChannelParameter:{mids:[n],mediaParameter:JSON.stringify({controlVideoStreaming:{sequenceNumber:++e.sequence,controlInfo:a}})}}}}getBandwidthInfoMessage(e){return{type:"ssbwe",BwMessage:e}}getMaxVideoSendCapabilitiesMessage(e){const{streamMIDs:t,capabilities:i,useMax:n,sendMaxFs:r,sendMaxMbps:s}=e;let a=Ln(i.maxWidth),o=Ln(i.maxHeight);n&&(a=o=Math.max(a,o));const l={[Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH]:i.maxFps,[Gi.VIDEO_CAPABILITIES.MAX_WIDTH]:a,[Gi.VIDEO_CAPABILITIES.MAX_HEIGHT]:o};return r&&(l[Gi.VIDEO_CAPABILITIES.MAX_FS_PATH]=i.maxFs),s&&(l[Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=i.maxMbps),{applyChannelParameters:{multiChannelParameter:{mids:t,mediaParameter:JSON.stringify({maxVideoSendCapabilities:{caps:l}})}}}}getMaxVideoSendCapabilitiesContent(e,t,i,n){const r={};if(i){let e=Ln(i.maxWidth),t=Ln(i.maxHeight);this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight&&(e=t=Math.max(e,t)),r[Gi.VIDEO_CAPABILITIES.MAX_WIDTH]=e,r[Gi.VIDEO_CAPABILITIES.MAX_HEIGHT]=t,r[Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH]=i.maxFps,this.configProvider.config.maxSendVideoCapabilities.sendMaxFs&&(r[Gi.VIDEO_CAPABILITIES.MAX_FS_PATH]=i.maxFs),this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps&&(r[Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=i.maxMbps)}else n&&[Gi.VIDEO_CAPABILITIES.MAX_WIDTH,Gi.VIDEO_CAPABILITIES.MAX_HEIGHT,Gi.VIDEO_CAPABILITIES.MAX_FPS_PATH,Gi.VIDEO_CAPABILITIES.MAX_FS_PATH,Gi.VIDEO_CAPABILITIES.MAX_MBPS_PATH].forEach((e=>{n[e]&&(r[e]=n[e])}));const s=e.getSimulcastContext();let a,o,l,c;if(s&&s.config.layerScaleFactors.length>2&&(a=s.config.layerScaleFactors.length,o=s.config.layerScaleFactors.length,t.hasClientSupport(0)||(o=2),this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&i&&i.maxFs<this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&(o=2)),void 0!==a&&(r[Gi.VIDEO_CAPABILITIES.MAX_STREAMS]=a),void 0!==o&&(r[Gi.VIDEO_CAPABILITIES.MAX_LAYERS]=o),t.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnServer){const e=this.configProvider.config.broadcastMode;e.priorityLayoutMinFS&&e.priorityLayoutMinFPS&&(c=e.priorityLayoutMinFS,c*=e.priorityLayoutMinFPS),e.priorityLayoutMinBitrate&&(l=e.priorityLayoutMinBitrate)}return l&&(r[Gi.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_BITRATE]=l),c&&(r[Gi.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_MBPR]=c),t.hasClientSupport(1)&&this.configProvider.config.preferredHardwareLadderType&&(r[Gi.VIDEO_CAPABILITIES.LADDER_TYPE]=this.configProvider.config.preferredHardwareLadderType),r}getMultiChannelParametersMessage(e,t){return{applyChannelParameters:{multiChannelParameter:{mids:e,mediaParameter:JSON.stringify(t)}}}}};mB.sequence=0;var fB=mB,vB=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.sender=i,this.mediaControlPlane=n,this.messageGenerator=new fB(this.configProvider),this.lastVideoSendMaxCapabilities={}}sendSourceRequest(e,t,i,n,r){if(this.configProvider.config.useApplyChannelParametersForSourceRequests){const s=this.messageGenerator.getSourceRequestMessage(e,t,n,r),a=this.messageGenerator.getSignalingSourceRequestMessage(e,t,i,n,r);return this.sendMessage("ApplyChannelParametersSourceRequest",s,a)}const s=this.messageGenerator.getVideoControlMessage(e,t,n?.[0]);return this.sendMessage("ControlVideoStreaming",s)}sendMaxVideoSendCapabilities(e,t){const i=this.messageGenerator.getMaxVideoSendCapabilitiesMessage({streamMIDs:e,capabilities:t,sendMaxFs:this.configProvider.config.maxSendVideoCapabilities.sendMaxFs,sendMaxMbps:this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps,useMax:this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight});return this.sendMessage("ApplyChannelParametersVideoCapabilities",i)}async sendBandwidthInfo(e){const t=this.messageGenerator.getBandwidthInfoMessage(e);return this.mediaControlPlane?.sendMsg(t)}sendMaxVideoSendCapabilitiesV2(e,t,i){if(void 0===this.lastVideoSendMaxCapabilities[e.getMid()]){if(!i)return this.logger.safe.info("Skip sending empty max-capabilities message"),Promise.resolve();this.lastVideoSendMaxCapabilities[e.getMid()]={}}const n=this.messageGenerator.getMaxVideoSendCapabilitiesContent(e,t,i,this.lastVideoSendMaxCapabilities[e.getMid()]);if(i||!an(this.lastVideoSendMaxCapabilities[e.getMid()],n)){this.lastVideoSendMaxCapabilities[e.getMid()]=n;const t=this.messageGenerator.getMultiChannelParametersMessage([e.getMid()],{maxVideoSendCapabilities:{caps:n}});return this.sendMessage("ApplyChannelParametersVideoCapabilities",t)}return this.logger.safe.info("Skip sending duplicate max-capabilties message"),Promise.resolve()}async sendMessage(e,t,i){let n;return"ApplyChannelParametersSourceRequest"===e&&(n=t.controlVideoStreaming.sequenceNumber),this.logger.safe.info(`sending video control message: ${JSON.stringify(t)}`),this.sender.send(e,t,n,i)}},SB=0,yB=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc-"+ ++SB),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.webrtcAdapter=(e=>void 0!==Mp.window.webkitRTCPeerConnection?new VU(e):new HU)({global:this.context.maContext,configProvider:this.configProvider}),this.iceHostCandidateOnly=this.multiParty&&un("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new GU({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:!1}),this.sessionDescription=wL.build({sdpTransform:new this.webrtcAdapter.SdpTransform(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=un("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new Yx({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.stats=new vU(this.logger.createChild("stats"),this.configProvider,void 0,this.mediaManager,this.multiParty),this.maxResolution=this.multiParty?Hn.Send.getResolutionByFs(this.configProvider.config.webrtcMultipartyMaxScalingFs):Hn.Send.getResolutionByFs(this.configProvider.config.webrtcMaxScalingFs),this.qualityManager=new XU(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:(e,t,i)=>this.applyCapabilitiesForModality(e,t,i)},this.stats,void 0,this.configProvider),this.localVideoStreamWatcher=new aB(this.logger,this.configProvider,this.context.callDeviceManager),this.activeSpeakerManager=new Jx(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager")),this.senders={},this.negotiationQueue=new tk(this.logger),this.negotiationEmulator=new zU(this.logger.createChild("negotiationEmulator"),this.webrtcAdapter.RTCSessionDescription,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.streamConfigurationHandler=new uB(this.logger,this.negotiationEmulator,this.qualityManager,null,this.configProvider,this.stats),this.mediaMessageController=new vB(this.logger,this.configProvider,{send:this.context.sendWebRtcMediaNotificationAsyncCallback}),this.toBeCalledAfterConnected=[],this.iceTransportPolicy=this.configProvider.config.iceTransportPolicyForced||this.context.config.iceTransportPolicy||Gi.ICE_TRANSPORT_POLICY.all,this.isMuteHold=!1,this.peerConnection=null,this.mediaStreams=new Map,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new Kt,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=cB({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=un("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new cO(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.remoteVideoResolutionManager=new eB(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.stats),this.remoteVideoManager=new sB(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 Kt,this.ssrcGenerator=new WO,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=e.getUfdManager(),this.stats.on("onStatisticsChanged",(e=>{this.remoteVideoManager.processLegacyStats(e),this.localVideoStreamWatcher?.onStatisticsChanged(e),this.updateQualityLevels(e)})),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),this.setSubsForSubscriptionManager(),this.localVideoStreamWatcher.on("onVideoCaptureFreeze",(e=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"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(e,t){}setParticipantSpatialAudioPositions(e,t){}getAcceptedTypes(){return this.allowedMediaContentType}clone(t=!1){const i=tn(this.context);i.config=tn(this.context.config),i.config.webrtcMediaContentType=this.mediaContentType,i.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,t?i.config.isConference=!0:(i.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(i.config.webrtcIceGatheringTimeoutIncreased=!0));const n=new e(i,this.callId,this.callback);return this.relayManagerProvider&&(n.relayManagerProvider=this.relayManagerProvider),n.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,n}setInternals(e){e.subscriptionManager&&(this.subscriptionManager&&this.subscriptionManager.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setStreamProvider({getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager&&e.remoteVideoManager.moveRenderers(this.remoteVideoManager)}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.stats.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.stats.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,s)=>this.stats.addSubscriptionEvent(e,t,i,n,null,r,s))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.stats.addSubscriptionEvent(e,t,i,n,r)))]}move(e,t){e.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager}),e.muteHold(this.isMuteHold,t),this.doAudioMute?e.muteInputAsync(t):e.unmuteInputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMuteAsync with mute state ${t}, audio stream exists: ${!!this.audioStream}`),"Audio"===e&&this.audioStream?this.audioStream.setMuted(t,i):"Video"===e&&this.videoStream?this.videoStream.setMuted(t,i):"ScreenShare"===e&&this.displayStream&&this.displayStream.setMuted(t,i),this.updateQualityLevels(this.stats.getLastStatistics())}setCallConstraints(e,t){return Promise.reject(new Error("Not supported"))}configureModalitiesAsync(e,t){const i=this.configuredModalitiesPromise.then((()=>{if(!e||!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const i=!this.configuredModalities||!em(e,this.negotiatedModalities);return this.configuredModalities=e,this.logger.safe.info(`[${t}] configure modalities`,`audio: ${e.audio}`,`video: ${e.video}`,`sharing: ${e.sharing}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?this.peerConnection.signalingState:"-"}`,`needNewRenegotiation: ${i}`),i&&this.triggerRenegotiation(!1,t),this.configuredModalities}));return this.configuredModalitiesPromise=i.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${tt(e)}`)})).then((()=>{})),i.then((()=>{}))}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}getSubscriptionManager(){return null}createAudioElement(e){}createOfferAsync(e){const t=this.negotiationQueue.add((()=>new Promise((t=>{this.logger.safe.info(`[${e}] 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[Gi.MODALITY.data]&&this.multiParty&&(this.offeredModalities[Gi.MODALITY.data]=Gi.MEDIA_STATE.inactive),Yp(this.offeredModalities)&&!Xi(this.negotiatedModalities)&&Object.keys(this.offeredModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.offeredModalities[e]})),t(this.updatePeerConnectionStreamsAsync(this.offeredModalities,!0,!0,e).then((()=>{const t=this.createNegotiationConstraints(this.offeredModalities);return this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)} constraints: ${JSON.stringify(t)}`),this.peerConnection.createOffer(t)})).then((t=>{this.logger.unsafe.debug(`[${e}] create [offer] offer from peer connection`,"sdp:",t.sdp);const i=this.sessionDescription.createLocalOffer(t.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(e),this.stats.startWaitingForStreamStart(this.offeredModalities);const n=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"offer"});return this.setupIceGatheringTimeout(e),Promise.all([this.peerConnection.setLocalDescription(n),this.iceCandidatesDeferred.promise])})).then((()=>{const t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);t.updateModalities(this.offeredModalities),this.checkIceCandidates(t);const i=t.toOffer();this.logger.unsafe.debug("CREATE OFFER","sdp:",i);const n={blob:i,contentType:this.mediaContentType};return""===this.configProvider.config.webrtcRequiredFeatures||this.multiParty||(n.requiredFeatures=this.configProvider.config.webrtcRequiredFeatures),this.configProvider.countryCode&&(n.clientLocation=this.configProvider.countryCode),this.doRetargetIfNeeded(n,t,e),n})))}))),e);return this.resetNegotiationQueue(e),t}processOfferAsync(e,t){const i=this.negotiationQueue.add((()=>new Promise((i=>{const n=e.blob;if(this.logger.unsafe.debug(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&(on(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),e.requiredFeatures){const t=this.configProvider.config.webrtcRejectedFeatures.split(",");ln(e.requiredFeatures.split(","),t)}this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.canTriggerRenegotiation=!1,this.offeredModalities=qp(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 r=Promise.resolve(this.offeredModalities);if(Wp(this.offeredModalities.video)||Kp(this.offeredModalities.video)||Wp(this.offeredModalities.sharing)||Kp(this.offeredModalities.sharing)){const e=this.offeredDescription.getVideoCodecs();r=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((i=>{if(!i.codecs.some((t=>e.some((e=>t.mimeType===e))))){this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`);const e=tn(this.offeredModalities);return this.disabledModalities.video=e.video,this.disabledModalities.sharing=e.sharing,e.video=void 0,e.sharing=void 0,e}return this.offeredModalities})).catch((e=>(this.logger.safe.error(`[${t}] failed to get video capability ${tt(e)}`),this.offeredModalities)))}i(r.then((e=>(this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(e)}`),e))))}))),t);return this.resetNegotiationQueue(t),i}createAnswerAsync(e,t){return new Promise((i=>{if(e)return void i({blob:"",contentType:this.mediaContentType});this.logger.safe.info(`[${t}] 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 n=Qp(this.offeredModalities,this.negotiatingModalities);const r=this.offeredDescription.clone();i(this.updatePeerConnectionStreamsAsync(n,!0,!1,t).then((()=>this.handleCodecSwitchUnsupported(t))).then((()=>{this.offeredDescription.setModalities(n);const e=this.offeredDescription.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources();const i=new this.webrtcAdapter.RTCSessionDescription({sdp:e,type:"offer"});return this.updateDescriptor(i,r),this.logger.unsafe.info(`[${t}] create [answer] set remote description`,"negotiated:",n,"sdp:",i.sdp),this.peerConnection.setRemoteDescription(i)})).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.updatePeerConnectionStreamsAsync(n,!1,!0,t)))).then((()=>(this.handleSharingRecvCapabilities(r),this.handleVideoRecvCapabilities(r)))).then((()=>this.peerConnection.createAnswer())).then((e=>{this.logger.unsafe.debug(`[${t}] create [answer] answer from peer connection`,"sdp:",e.sdp);const i=this.sessionDescription.createLocalAnswer(e.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(t),this.stats.startWaitingForStreamStart(n);const r=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"answer"});return this.setupIceGatheringTimeout(t),Promise.all([this.peerConnection.setLocalDescription(r),this.iceCandidatesDeferred.promise])})).then((()=>{const e=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);e.updateModalities(n),this.checkIceCandidates(e);const i=e.toAnswer();n=e.getModalities(),Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,n)||this.triggerRenegotiation(!0,t),this.setNegotiatedModalities(n),this.stats.sessionInfo.setBweType(e.getBweType()),this.logger.unsafe.debug("CREATE ANSWER","sdp:",i);const r={blob:i,contentType:this.mediaContentType};return this.configProvider.countryCode&&(r.clientLocation=this.configProvider.countryCode),r})))}))}processAnswerAsync(e,t,i){const n=e.blob;if(this.logger.unsafe.debug(i?"PROCESS PRANSWER":"PROCESS ANSWER","sdp:",n),i)return this.logger.safe.info(`[${t}] process [pranswer] ignored`),Promise.resolve();this.mediaContentType=e.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType);const r=this.sessionDescription.createRemoteAnswer(n),s=r.clone(),a=qp(r.getModalities());this.setNegotiatedModalities(a),r.setModalities(this.negotiatedModalities);const o=r.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources(),this.stats.sessionInfo.setBweType(r.getBweType());const l=new this.webrtcAdapter.RTCSessionDescription({sdp:o,type:"answer"});return this.updateDescriptor(l,s),this.logger.unsafe.info(`[${t}] process [answer] set remote description`,"negotiated:",this.negotiatedModalities,"sdp:",l.sdp),this.peerConnection.setRemoteDescription(l).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.negotiatedModalities))).then((()=>(this.handleSharingRecvCapabilities(s),this.handleVideoRecvCapabilities(s)))).then((e=>{e&&this.triggerRenegotiation(!0,t)}))}completeNegotiationAsync(e){return new Promise((t=>{this.mediaManager.commit();const i=this.configuredModalities,n=this.forceMediaStreamUpdate&&!Yp(this.negotiatedModalities)||!Xp(this.configProvider,i,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,r=!n;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${r} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),n&&this.triggerRenegotiation(!1,e),this.negotiationCompletedPromise.resolve(),t({isComplete:r,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})}))}rejectNegotiationAsync(e,t,i=!1){return Promise.resolve().then((()=>{if(this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${tt(e)} 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(`[${t}] rolling back local description`),this.configProvider.config.webrtcHandleRollback?(this.logger.safe.info(`[${t}] rolling back using local renegotiation`),this.negotiationEmulator.renegotiateNow().then((()=>{this.logger.safe.info(`[${t}] rolling back using local complete`)}))):this.peerConnection.setLocalDescription(new this.webrtcAdapter.RTCSessionDescription({type:"rollback"}));this.logger.safe.error(`[${t}] 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((e=>{this.removeTrackByMediaType(e),this.disposeStreamByMediaType(e)})),this.registerLocalStreams()})).then((()=>(i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})))}startMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}completeMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}rejectMediaDescriptionsUpdateAsync(e,t){return Promise.reject(new Error("Not supported"))}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){return this.terminated||(this.statisticsReport=this.statisticsReport.then((()=>this.stats.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))),this.statisticsReport}getLastKnownStats(e=!1){return this.stats.getReport(!1,e)}muteHold(e,t){this.isMuteHold=e;const i=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing].filter((e=>Wp(this.negotiatedModalities[e])&&(e!==Gi.MODALITY.audio||!this.doAudioMute)));for(const n of i)this.setMute(sm(n),e,t)}async muteInputAsync(e){this.doAudioMute=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.doAudioMute=!1,this.setMute("Audio",!1,e)}muteOutputAsync(e){return this.audioRenderer.setMuted(!0,e),Promise.resolve()}unmuteOutputAsync(e){return this.audioRenderer.setMuted(!1,e),Promise.resolve()}async getSpeakerVolume(e){return this.audioRenderer.getSpeakerVolume(e)}async setSpeakerVolume(e,t){return this.audioRenderer.setSpeakerVolume(e,t)}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(e=be()){const t=new Kt;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}onDeviceEvent(e){this.stats.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&(this.audioRenderer&&this.audioRenderer.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),Yp(this.negotiatedModalities)||(this.forceMediaStreamUpdate=!0,this.triggerRenegotiation(!0)))}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.stats.setTerminated(),this.canTriggerRenegotiation=!1,this.cleanUp(e);try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${tt(t)}`)}finally{this.stats.dispose(),this.terminated=!0}}processNotification(e,t){"DominantSpeakerInfo"===e&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(t.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===e&&this.streamConfigurationHandler.handleMessage(t)}cleanUp(e){this.negotiationQueue.dispose(),this.localVideoStreamWatcher.dispose(),this.remoteVideoManager.dispose(),this.resetPeerConnection(e),this.subscriptionManagerSubs.forEach((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(e){this.logger.safe.info(`[${e}] 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(e),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(e=be()){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new Kt,e)}setNegotiationPromise(e,t=be()){this.terminated||(this.negotiationCompletedPromise=e,this.negotiationQueue.add(this.negotiationCompletedPromise,t))}updateQualityLevels(e){if(!e)return;this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel});const t=!(!e.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",t?"Bad":"Good")}triggerRenegotiation(e,t=be()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(t)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(e){if(!this.configuredModalities)throw new Error(e)}addTrack(e,t,i){if(!e)return;const n=this.modalityByMediaType(i);if(this.logger.safe.info(`add media track kind: ${e.kind} id: ${e.id}`),this.senders[n])throw new Error("track already created, modality:"+n+", kind:"+e.kind+", id:"+e.id);"closed"!==this.peerConnection.iceConnectionState&&(this.senders[n]=this.peerConnection.addTrack(e,t))}registerMediaSources(){const e=[];if(this.mediaStreams.forEach(((t,i)=>{const n={sourceId:this.getSourceIdForStream(t),defaultSSRC:this.ssrcs[i].min,modality:this.modalityByMediaType(i)};e.push(n)})),this.qualityManager.updateRegisteredSources(e),this.videoStream){const e=this.videoStream.getResolution();this.qualityManager.setCurrentResolution(new Bn(e.width,e.height))}}updateStream(e,t){return e.start().then((()=>{try{const i=this.mediaStreams.get(t);if(i&&e.isSameStream(i))return e.dispose(),null;if(this.updateSsrcRangeForMediaType(t),this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),!this.peerConnection)return e.dispose(),null;if(this.addTrack(e.rawTrack,e.rawStream,t),e.onApplyConstraints=i=>{this.removeTrackByMediaType(t),i.then((()=>{this.addTrack(e.rawTrack,e.rawStream,t),this.registerLocalStreams(),this.mediaManager.updateMediaEntitiesWithLocalTracks()}))},this.mediaStreams.set(t,e),"Video"===t){const e=[this.getMediaTrackInfo(t)];this.localVideoStreamWatcher.startWatching(e)}}catch(i){throw this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),e.dispose(),i}}))}getSourceIdForStream(e){const t=e.rawStream.getTracks()[0].id,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}updatePeerConnectionStreamsAsync(e,t,i,n){const r=Wp(this.negotiatedModalities.audio),s=Wp(this.negotiatedModalities.video),a=Wp(this.negotiatedModalities.sharing),o=Yp(this.negotiatedModalities),l=Wp(e.audio),c=Wp(e.video),d=Wp(e.sharing),u=Yp(e);return o||u||(this.stats.onSendersChanged("Audio",l),this.stats.onSendersChanged("Video",c),this.stats.onSendersChanged("ScreenShare",d)),this.assurePeerConnectionAsync(n).then((async()=>{if(this.logger.safe.info("updatePeerConnectionStreamsAsync","pc state",this.peerConnection.signalingState,"hold","[",o,"->",u,"]","audio","[",r,"->",l,"]","video","[",s,"->",c,"]","sharing","[",a,"->",d,"]"),o!==u){if(this.videoStream&&this.videoStream.setHold(u),this.audioStream&&this.audioStream.setHold(u),this.displayStream&&this.displayStream.setHold(u),u)return;if(!u&&this.audioStream){this.removeTrackByMediaType("Audio");const e=this.audioStream.clone();this.audioStream.dispose(),this.mediaStreams.set("Audio",e),this.addTrack(this.audioStream.rawStream.getAudioTracks()[0],this.audioStream.rawStream,"Audio")}}if((r!==l||s!==c||a!==d||this.forceMediaStreamUpdate)&&(i&&(this.forceMediaStreamUpdate=!1),t&&(this.logger.safe.info("not using any media(track api) track, remove all senders"),l||(this.removeTrackByMediaType("Audio"),this.disposeStreamByMediaType("Audio")),i&&c||(this.removeTrackByMediaType("Video"),this.disposeStreamByMediaType("Video")),i&&d||(this.removeTrackByMediaType("ScreenShare"),this.disposeStreamByMediaType("ScreenShare"))),i)){const e=[];if(c){const t=await this.deviceManager.getVideoStream(!1);e.push(this.updateStream(t,"Video"))}if(d){const t=this.deviceManager.getDisplayStream();e.push(this.updateStream(t,"ScreenShare"))}if(l){const t=await this.deviceManager.getAudioStream(!1);e.push(this.updateStream(t,"Audio").then((()=>{this.audioStream.setMuted(this.doAudioMute)})))}return Promise.all(e).then((()=>this.registerLocalStreams()))}}))}getMediaTrackInfo(e){const t=this.modalityByMediaType(e),i=this.mediaStreams.get(e).rawStream.getTracks()[0].id;return i||this.logger.safe.error(`No media track for modality found: ${t}`),{trackId:i,modality:t}}getSsrcRangeForMediaType(e){const t={min:1,max:1};switch(e){case"Audio":return this.ssrcGenerator.nextAudioStreamSsrc();case"Video":case"ScreenShare":return this.ssrcGenerator.nextVideoStreamSsrc();default:return t}}updateSsrcRangeForMediaType(e){"Video"!==e&&"ScreenShare"!==e||(this.ssrcs[e]=this.ssrcGenerator.nextVideoStreamSsrc())}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!1,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}registerLocalStreams(){const e=[];this.mediaStreams.forEach(((t,i)=>{e.push(this.getMediaTrackInfo(i))})),this.mediaManager.setLocalTracksInfo(e)}handleVideoRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&Kp(e.getModalities().video)){if(this.videoStream){const t=e.getVideoRecvCapabilities();if(!t)return this.logger.safe.error("No fmt params found for video modality"),Promise.resolve(!1);const i=this.generateReceiveCapabilities(t,this.videoStream);this.qualityManager.setMaxCapabilities([i])}this.logger.safe.error("remote endpoint didn't specify video receive capability")}return Promise.resolve(!1)}handleSharingRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&Kp(e.getModalities().sharing)&&this.displayStream){const t=e.getSharingRecvCapabilities();if(!t)return void this.logger.safe.error("No fmt params found for sharing modality");const i=this.generateReceiveCapabilities(t,this.displayStream);this.qualityManager.setMaxCapabilities([i])}}generateReceiveCapabilities(e,t){const i={ssrc:0,rid:"0",keyframe:!1,...e},n={causeId:be(),isSimulcast:!1,sourceId:this.getSourceIdForStream(t),capabilities:[i]};return this.logger.safe.info(`Generated receive capabilities for stream ${t.id}: ${JSON.stringify(n)}`),n}updateDescriptor(e,t){const i=t.getVideoRecvCapabilities(),n={sourceId:0,streamMsid:0,bandwidth:0};if(i&&this.videoStream&&!this.displayStream&&(n.sourceId=this.getSourceIdForStream(this.videoStream),n.streamMsid=this.videoStream.id,n.bandwidth=i.maxBr?i.maxBr:Number.MAX_VALUE),n.bandwidth>0){n.bandwidth=Math.floor(n.bandwidth/1200);const t=new Zx(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider);t.setControlItem(n),t.modifyDescriptor(e)}}removeTrackByMediaType(e){return this.removeTracksByModality(this.modalityByMediaType(e))}modalityByMediaType(e){switch(e){case"Audio":return Gi.MODALITY.audio;case"Video":return Gi.MODALITY.video;case"ScreenShare":return Gi.MODALITY.sharing;default:throw new Error(`Modality is not defined for media type: ${e}`)}}removeTracksByModality(e){this.forceKeyFramePromise&&"sharing"===e?this.forceKeyFramePromise.then((()=>{this.removeTracksByModality(e)})):e in this.senders&&(this.logger.safe.info(`remove sender track kind: ${this.senders[e].track.kind} track id: ${this.senders[e].track.id}`),"closed"!==this.peerConnection.iceConnectionState&&this.peerConnection.removeTrack(this.senders[e]),delete this.senders[e])}handleCodecSwitchUnsupported(e){return this.offeredDescription.isCodecSwitchSupported()?Promise.resolve():this.webrtcAdapter.RTCRtpReceiver.getCapabilities(Gi.MEDIA_TYPE.audio).then((e=>{const t=e.codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(t)})).catch((t=>{this.logger.safe.error(`[${e}] failed to set primary codec based on audio capability ${tt(t)}`)}))}disposeStreamByMediaType(e){const t=this.mediaStreams.get(e);t&&(this.mediaStreams.delete(e),t.dispose(),"Video"===e&&this.localVideoStreamWatcher.stopWatching())}disposeStreams(){this.mediaStreams.forEach(((e,t)=>this.disposeStreamByMediaType(t)))}assurePeerConnectionAsync(e){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 t={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};this.peerConnectionPromise=this.relayManagerProvider.getRelayManager().queryRelaysAsync(t).then((t=>{if(this.terminated)throw new Error("session already disposed");const i={optional:[]},n=Fx(t,this.configProvider.config),r=this.configureCrypto(i);this.configureCpuThreshold(i),this.logger.safe.info("create peer connection");const s=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle",a=this.peerConnection=new this.webrtcAdapter.RTCPeerConnection({iceServers:n,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,bundlePolicy:s,sdpSemantics:"plan-b",audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===r,offerExtmapAllowMixed:!1},i);this.negotiationEmulator.configure(a),this.stats.initialize(a),this.stats.sessionInfo.setIceServers(n),this.stats.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.stats.sessionInfo.setBundlePolicy(s);const o=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video"),l=this.webrtcAdapter.RTCRtpSender.getCapabilities("video");this.stats.setH264AvailableProfiles(o),this.stats.setSupportedH264Profiles(l,o),a.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${a.signalingState}`)},a.onsignalingstatechange=()=>{this.stats.sessionInfo.setSignalingConnectionState(a.signalingState),this.logger.safe.info(`onsignalingstatechange signalingState: ${a.signalingState}`)},a.onicecandidateerror=e=>{const[t,i]=[e.address,e.port];this.logger.safe.warn(`On ICE candidate error ${e.url} | ${t}:${i}: code ${e.errorCode}: ${e.errorText}`),this.isConnected()&&!this.iceCandidatesDeferred.isPending||this.stats.addIceCandidateError({address:t,port:+i,url:e.url,errorCode:e.errorCode,errorText:e.errorText})};const c=e=>{if(!this.isConnected())return this.logger.safe.info("onaddstream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>c(e)));const t=e.stream;this.logger.safe.info(`onaddstream stream: ${t.id}`);let i=this.mediaManager.getMediaEntityByRemoteStreamId(t.id);if(i||(this.logger.safe.info(`cannot find media entity with stream id ${t.id} trying to fallback`),t.getAudioTracks()[0]&&(i=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.audio)[0])),i){const e=this.createReceiveStream(t,i);this.receiveStreamCollection.add(e)}else this.logger.safe.error(`could not find media entity for an added stream: ${t.id}`)};a.onaddstream=c,a.ontrack=e=>{this.logger.safe.info(`ontrack track: ${e.track}`)};const d=e=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>d(e)));this.logger.safe.info(`onremovestream stream: ${e.stream.id}`),this.receiveStreamCollection.remove(e.stream.id)};a.onremovestream=d,a.onicecandidate=t=>{const i=t.candidate;if(i){const t=rm(i.candidate);this.logger.safe.info(`[${e}] onicecandidate candidate: prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1&&(this.stats.sessionInfo.setRelayCandidateInfo({priority:i.priority||i.candidate.split(" ")[3],time:Date.now()-this.iceRelayCandidatesGatherStartTime}),this.relayCandidateGathered=!0)}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const r=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,s=this.iceHostCandidateOnly||0===n.length;if(!i&&r||s){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.isConnected(),a.iceConnectionState,a.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.stats.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},a.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${a.iceGatheringState}`)},a.oniceconnectionstatechange=()=>{const e=be();if(!this.terminated){if(this.stats.sessionInfo.setIceConnectionState(a.iceConnectionState),this.logger.safe.info(`[${e}] oniceconnectionstatechange iceConnectionState: ${a.iceConnectionState} pc.signalingState: ${a.signalingState}`),"connected"===a.iceConnectionState||"completed"===a.iceConnectionState)this.onTransportConnected(e);else if("failed"===a.iceConnectionState){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${e}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(e);this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},e),this.configProvider.config.webrtcCloseAfterIceFailure&&a.close(),this.onTransportFailed()}"disconnected"===a.iceConnectionState?(this.onTransportDisconnected(e),this.startIceDisconnectedTimer(e)):this.clearIceDisconnectedTimer()}},this.multiParty&&(this.contributingSources=new $U(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new jU(this.logger.createChild("ContributingSourcesProvider"),a)))}))}return this.peerConnectionPromise}configureCrypto(e){let t=!1;const i=gm(this.context.configProvider,this.context.config.isPstnCall);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.stats.sessionInfo.setOfferedSrtpInfo(e),t=!e.dtls||e.sdes&&i}else t=i;return t&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1})),this.stats.sessionInfo.setNegotiatedSrtpInfo({dtls:!t,sdes:!!t}),t?0:1}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(e){if(this.logger.safe.info(`[${e}] audio transport connected`),this.stats.clearIceCandidateErrors(),!this.terminated)for(this.callbacks.onAudioStateChanged(Gi.STREAMING_STATE.active,e),this.callbacks.onTransportConnected&&this.callbacks.onTransportConnected(e);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}onTransportDisconnected(e){this.callbacks.onTransportDisconnected&&this.callbacks.onTransportDisconnected(e)}onTransportFailed(){this.callbacks.onTransportFailed&&this.callbacks.onTransportFailed()}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise CONSTANTS.MEDIAthis._ERROR.iceConnectionError`),this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=be()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}createNegotiationConstraints(e){function t(e){return!!e&&(Kp(e)||"inactive"===e)}return{offerToReceiveAudio:t(e.audio),offerToReceiveVideo:t(e.video)||t(e.sharing)}}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Kt}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Gi.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&("connected"===this.peerConnection.iceConnectionState||"completed"===this.peerConnection.iceConnectionState))return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}doRetargetIfNeeded(e,t,i){const n=t.isIceRestart();this.logger.safe.info(`[${i}] ICE restart: ${n}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&n&&!this.multiParty&&t.getSrtpInfo().sdes&&(e.newOffer=!0)}getAddedMediaTypes(e,t){e||(e={}),t||(t={});const i=[];return CB(e.audio,t.audio)&&i.push("Audio"),CB(e.video,t.video)&&i.push("Video"),CB(e.sharing,t.sharing)&&i.push("ScreenShare"),i}applyCapabilitiesForModality(e,t,i){return e===Gi.MODALITY.video?this.applyCapabilitiesForVideo(t,i[0]):e===Gi.MODALITY.sharing?this.applyCapabilitiesForSharing(t,i[0]):Promise.resolve(!1)}applyCapabilitiesForSharing(e,t){return this.displayStream?this.applyCapabilities(this.displayStream,t).then((i=>(this.stats.onMaxCapabilitiesApplied({causeId:e,modality:Gi.MODALITY.sharing,capabilities:[t]}),this.configProvider.config.webrtcAllowRestoreKeyframe?this.forceKeyframe(this.senders[Gi.MODALITY.sharing]).then((()=>i)):Promise.resolve(i)))):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no sharing stream is sent, no renegotiation`),Promise.resolve(!1))}forceKeyframe(e){if(!e)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 t=e.track;return this.forceKeyFramePromise=e.replaceTrack(null).then((()=>e.replaceTrack(t))).then((()=>{this.forceKeyFramePromise=null,this.logger.safe.info("Restoring keyframe finished")})).catch((e=>{this.forceKeyFramePromise=null,this.logger.safe.error(`Restoring keyframe failed: ${e}`),delete this.senders[Gi.MODALITY.sharing]})),this.forceKeyFramePromise}applyCapabilitiesForVideo(e,t){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,e,t):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no video is sent, no renegotiation`),Promise.resolve(!0))}scheduleApplyCapabilities(e,t,i){this.logger.safe.info("Queueing local renegotiation...");let n=!1;return this.negotiationQueue.add((()=>(this.logger.safe.info("############# LOCAL RENEGOTIATION START #############"),this.applyCapabilities(e,i).then((()=>{this.stats.onMaxCapabilitiesApplied({causeId:t,modality:Gi.MODALITY.video,capabilities:[i]}),n=!0})))),t),this.negotiationEmulator.renegotiate().then((()=>(this.logger.safe.info(`############# LOCAL RENEGOTIATION END. RESULT: ${n} #############`),n)))}applyCapabilities(e,t){return e?(this.logger.safe.info(`Changing resolution to ${JSON.stringify(t)}`),e.applyCapabilities(t)):(this.logger.safe.info(`Resolution ${JSON.stringify(t)} ignored, no stream is being sent`),Promise.resolve(!1))}onOptimalVideoReceiversCountChanged(e){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e)}getStreams(){return this.receiveStreamCollection.getStreams()}onStreamsChanged(e){this.streamsChangedListener=e}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(e){Gi.MODALITY.audio===e.getModality()&&(this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.play(e.getMediaStream())),this.notifyStreamsChanged()}streamRemoved(e){Gi.MODALITY.audio===e.getModality()&&this.audioRenderer.getStream()===e.getMediaStream()&&this.audioRenderer.stop(),this.notifyStreamsChanged()}setNegotiatedModalities(e){this.negotiatedModalities=e,this.stats.sessionInfo.setNegotiatedModalities(e)}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}createAudioRenderer(){this.audioRenderer=new ek(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 e=this.peerConnection;return e&&("connected"===e.iceConnectionState||"completed"===e.iceConnectionState)}isFailed(){return this.peerConnection&&("failed"===this.peerConnection.iceConnectionState||"closed"===this.peerConnection.iceConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(e,t){const i=this.configProvider.config.addFmtpToInitialSubscription?t.getLocalRecvCapabilities():null,n=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&t.getModality()!==Gi.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null;return new aO(e,null,t.getModality(),+t.getXSourceStreamId(),this,i,n)}requestSource(e,t,i){if(!this.multiParty)return Promise.resolve();const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);return!this.isMuteHold&&this.negotiatedModalities[n.getModality()]!==Gi.MEDIA_STATE.inactive||-1===t?this.negotiationCompletedPromise.isPending?this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>this.requestSource(e,t,i))):Promise.resolve().then((()=>this.mediaMessageController.sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex()))):Yt(10).then((()=>this.requestSource(e,t,i)))}getSessionConfig(){return this.configProvider}getUnmixedAudioProvider(){return null}};function CB(e,t){return!Wp(e)&&Wp(t)}var TB={build:(e,t,i)=>new yB(e,t,i)},EB=Z,bB=class extends Vi{constructor(e,t){super(t),this.logger=t,this.id=-1,this.parentId=-1,this.rawStream=null,this.rawTrack=null,this.deviceId=null,this.mediaType=e}start(){return this.logger.safe.debug("start"),Promise.resolve()}clone(){return this.logger.safe.debug("clone"),this}setMuted(e,t){this.logger.safe.debug("setMuted")}setHold(e){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(e){return this.logger.safe.debug("isSameStream"),e===this}applyCapabilities(e){return this.logger.safe.debug("applyCapabilities"),Promise.resolve(!1)}onApplyConstraints(e){this.logger.safe.debug("onApplyConstraints")}update(e){this.logger.safe.debug("update")}isActive(){return!1}isDisposed(){return!1}},_B=class e extends Vi{constructor(e,t,i,n,r){super(r),this.callDeviceManager=e,this.configProvider=t,this.sessionConfig=i,this.serialQueue=n,this.logger=r,this.mediaStreams={Audio:null,Video:null,ScreenShare:null},this.streamSubscriptions=new Map,this.deviceManagerSubscriptions=[],this.isNullAudioStream=!1}get currentMediaTypes(){return en(this.mediaStreams).filter((e=>!!this.mediaStreams[e]))}async getStreams(){return this.mediaStreams}useNullAudioStreamClient(){this.isNullAudioStream=!0}async update(e,t){const i=en(e).filter((t=>e[t]));return an(i,this.currentMediaTypes)?(this.logger.safe.info("Requested modalities have not changed. Do nothing"),om(this.mediaStreams)):(this.logger.safe.info(`Starting media session with modalities: ${JSON.stringify(e)}`),await this.updateStreams(i,t),this.subscribeOnDeviceManagerEvents(),om(this.mediaStreams))}async stopAsync(){this.logger.safe.info("Stopping streams async"),this.stop()}stop(){this.logger.safe.info("Stopping streams"),this.unsubscribeFromDeviceManagerEvents(),en(this.mediaStreams).forEach((e=>this.removeStreamByType(e)))}dispose(){this.stop(),super.dispose()}async updateStreams(e,t){const i=this.getAvailableMediaTypes(),n=(0,EB.intersection)(e,i),r=en(this.mediaStreams).filter((e=>this.mediaStreams[e])),s=t?[]:hn(n,r),a=hn(r,n);s.length&&this.logger.safe.info(`Adding media streams for types: ${JSON.stringify(s)}`),await Promise.all(s.map((async e=>{await this.addStream(e,!1),this.mediaStreams[e]&&this.event("onStreamAdded").raise(e)}))),a.length&&this.logger.safe.info(`Removing media streams for types: ${JSON.stringify(a)}`),a.forEach((e=>{this.event("onStreamRemoving").raise(e),this.removeStreamByType(e)}))}getAvailableMediaTypes(){const e=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices(),t=[];return e.microphone&&t.push("Audio"),e.camera&&t.push("Video"),t.push("ScreenShare"),t}async addStream(e,t){if(this.mediaStreams[e])return void this.logger.safe.warn(`Stream with type: ${e} is already registered`);const i=await this.getStream(e,t);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i}removeStreamByType(e){const t=this.mediaStreams[e];t?(this.unsubscribeFromMediaStreamEvents(t),t.dispose(),this.mediaStreams[e]=null):this.logger.safe.warn(`Stream with type: ${e} is not registered`)}async updateStream(e,t,i=!1){i&&"Audio"===e?await this.updateStreamWithEffect(e):(this.removeStreamByType(e),await this.addStream(e,t)),this.event("onStreamUpdated").raise(e)}async updateStreamWithEffect(e){const t=this.mediaStreams[e];t&&this.unsubscribeFromMediaStreamEvents(t);const i=await this.getStreamByMediaType(e,!0);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`updateStreamWithEffect. Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i,t?.dispose()}subscribeOnMediaStreamEvents(e){if(this.streamSubscriptions.has(e))return;const t=[];t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),this.streamSubscriptions.set(e,t)}unsubscribeFromMediaStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}async getStream(e,t){const i=this.mediaStreams[e];return i?(this.logger.safe.info(`Stream exists with id: ${i.id}, type: ${e}`),i):this.getStreamByMediaType(e,t)}async getStreamByMediaType(e,t){switch(e){case"Audio":return this.isNullAudioStream?new bB("Audio",this.logger.createChild("NullStreamClient")):this.getDeviceManagerByType("Audio").getAudioStream(t,"sessionStream");case"Video":return this.getDeviceManagerByType("Video").getVideoStream(t,"sessionStream",!1,this.sessionConfig.outgoingVideoMaxFS);case"ScreenShare":return this.getDeviceManagerByType("ScreenShare").getDisplayStream("sessionStream");default:throw new Error(`Media type is not supported: ${e}`)}}getMediaTypeForStream(e){const t=Object.keys(this.mediaStreams).find((t=>this.mediaStreams[t]===e));return t||this.logger.safe.error(`Media type is not found for stream: ${tt(e)}`),t}subscribeOnDeviceManagerEvents(){if(0!==this.deviceManagerSubscriptions.length)return;if(this.callDeviceManager.isVirtualDeviceEnabled){const e=this.callDeviceManager.on("onSelectedVirtualDevicesChanged",((e,t)=>{const i=e;if(!e.camera){this.logger.info("Virtual DeviceID for camera is undefined, falling back to default device");const{camera:e}=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices();i.camera=e}this.callDeviceManager.isModalityEnabled("Video")&&t.camera!==i.camera&&(this.logger.info("Updating stream for camera"),this.updateStreamForVirtualDeviceChange("Video")),this.callDeviceManager.isModalityEnabled("ScreenShare")&&t.screenshare!==i.screenshare&&(this.logger.info("Updating stream for screenshare"),this.updateStreamForVirtualDeviceChange("ScreenShare"))}));this.deviceManagerSubscriptions.push(e)}const e=this.callDeviceManager.getDefaultDeviceManager();this.deviceManagerSubscriptions.push(e.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),e.on("onStreamUpdateRequested",((e,t)=>this.requestStreamUpdate(e,!1,t))),e.on("onAudioSharingToggled",(e=>this.onAudioSharingToggled(e))))}unsubscribeFromDeviceManagerEvents(){0!==this.deviceManagerSubscriptions.length&&(this.deviceManagerSubscriptions.forEach((e=>e.dispose())),this.deviceManagerSubscriptions=[])}getMediaTypesToUpdate(e,t){const i=[];return this.currentMediaTypes.some((e=>"Audio"===e))&&e.microphone&&e.microphone!==t.microphone&&i.push("Audio"),!this.callDeviceManager.getSelectedDevices().camera&&this.currentMediaTypes.some((e=>"Video"===e))&&e.camera&&e.camera!==t.camera&&i.push("Video"),i}removeStream(e){const t=this.getMediaTypeForStream(e);this.removeStreamByType(t)}async onSelectedDevicesChanged(t,i){if(this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t,i))return void this.logger.safe.info("Device list is empty, permission workaround enabled");const n=this.getMediaTypesToUpdate(t,i);this.logger.safe.info(`Media types to update: ${JSON.stringify(n)}`),await Promise.all(n.map((e=>this.updateStream(e,!1))))}async onAudioSharingToggled(e){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&e)return this.updateStream("ScreenShare",!0)}async requestStreamUpdate(e,t,i=!1){if(this.currentMediaTypes.some((t=>t===e))||t)return this.logger.safe.debug(`UpdateStream with media type: ${e}, force: ${t}`),this.updateStream(e,t,i);this.logger.safe.debug(`Stream with media type: ${e} is not active. Do nothing`)}onStreamError(e,t){this.removeStream(e)}onStreamDisposing(e){this.removeStream(e)}static isDeviceListEmpty(e,t){return!e.camera&&!e.microphone||!t.microphone&&!t.camera}getDeviceManagerByType(e){return this.callDeviceManager.getDeviceManager(e)}async updateStreamForVirtualDeviceChange(e){return this.updateStream(e,!1)}};m([Uk()],_B.prototype,"getStreams",1),m([Uk()],_B.prototype,"update",1),m([Uk()],_B.prototype,"stopAsync",1),m([Uk()],_B.prototype,"onSelectedDevicesChanged",1),m([Uk()],_B.prototype,"onAudioSharingToggled",1),m([Uk()],_B.prototype,"requestStreamUpdate",1),m([Uk()],_B.prototype,"updateStreamForVirtualDeviceChange",1);var IB=_B,wB=Z,AB=[5e4,1e6,15e5,2e6,25e5,375e4,4e6],PB=[7e4,2e5,4e5,8e5,15e5,2499990,25e5],RB=class{constructor(e){this.logger=e,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladders={}}setAvailableBandwidth(e){this.availableBandwidth=e,this.logger.safe.debug(`Total available bandwidth updated: ${e}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(e,t){this.logger.safe.debug(`Receiver maxBr set: ${e}/${t}`),this.receivers.set(e,t),this.updateLayouts()}getReceiverCapabilities(){const e={};for(const t of Object.keys(this.receivers)){const i=this.receivers.get(t);i&&(e[t]=i)}return e}removeReceiver(e){this.logger.safe.debug(`Receiver maxBr removed: ${e}`),this.receivers.delete(e),this.updateLayouts()}getLayouts(){return this.currentLayout}setLadder(e,t){this.ladders[e]=t}updateLayouts(){const e=this.generateLayouts();(0,wB.isEqual)(e,this.currentLayout)||(this.currentLayout=e,this.logger.safe.debug(`Bandwidth distribution updated: ${tt(e)}`))}generateLayouts(){const e={},t={};for(const i of Object.keys(this.ladders)){const n=this.receivers.get(i);n&&(t[i]=n||Number.MAX_SAFE_INTEGER,e[i]=0)}let i=this.availableBandwidth,n=0;const r=()=>{if(!i)return!1;for(const e of Object.values(t))if(e)return!0;return!1};for(;r();){for(const r of Object.keys(e)){const s=this.ladders[r];let a=s[n]||s[s.length-1];a=Math.min(a,i,t[r]),e[r]+=a,i-=a,t[r]-=a}n++}return e}};function MB(e,t){const i=e.config.bandwidthAllocatorV2;let n=[],r=-1;for(const e of i.videoLadders)(t>=e.maxFS&&r<e.maxFS||-1===r)&&(n=e.ladder,r=e.maxFS);return n}var DB=class{constructor(e){this.logger=e,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladder=[],this.priority=[]}getReceiverCapabilities(){const e={};for(const t of Object.keys(this.receivers)){const i=this.receivers.get(t);i&&(e[t]=i)}return e}setAvailableBandwidth(e){this.availableBandwidth=e,this.logger.safe.debug(`Total available bandwidth updated: ${e}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(e,t){this.logger.safe.debug(`Receiver maxBr set: ${e}/${t}`),this.receivers.set(e,t),this.updateLayouts()}removeReceiver(e){this.logger.safe.debug(`Receiver maxBr removed: ${e}`),this.receivers.delete(e),this.updateLayouts()}getLayouts(){return this.currentLayout}setPriority(...e){this.priority=e}setLadder(e,t){this.logger.safe.info(`Set ladder for ${e}: ${JSON.stringify(t)}`);for(const t of this.ladder)delete t[e];-1===this.priority.indexOf(e)&&this.priority.push(e);for(let i=0;i<t.length;++i)i>=this.ladder.length&&this.ladder.push({}),this.ladder[i][e]=t[i]}updateLayouts(){const e=this.generateLayouts();(0,wB.isEqual)(e,this.currentLayout)||(this.currentLayout=e,this.logger.safe.debug(`Bandwidth distribution updated: ${tt(e)}`))}generateLayouts(){const e={};let t=this.availableBandwidth;for(const t of this.priority)this.receivers.get(t)&&(e[t]=0);for(let i=0;i<this.ladder.length&&t;++i){const n=this.ladder[i];for(const i of this.priority){const r=n[i];if(r&&this.receivers.get(i)){const n=Math.max(0,Math.min(r-e[i],t));t-=n,e[i]+=n}}}if(t){const i=t;let n=0;for(const e of this.priority)n+=this.receivers.get(e)??0;for(const r of this.priority){const s=this.receivers.get(r);if(s){const a=Math.min(t,Math.ceil(s*i/n));a&&this.logger.safe.info(`[AllocateSurplus][${r}] ${e[r]} + ${s} | ${t}`),t-=a,e[r]+=a}}}return e}},kB=class{constructor(e,t,i){this.timeout=t,this.logger=i,this.isFirstTimeDeferred=!0,this.internalCallback=t=>{this.logger.safe.debug(`Trigger reason: ${t}`),e()}}invoke(e){this.logger.safe.debug(`Schedule shouldDefer: ${e}`),this.isFirstTimeDeferred?e?(this.isFirstTimeDeferred=!1,this.startTimer()):(this.stopTimer(),this.internalCallback("request")):this.timeoutId&&e||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"))}},OB=class{constructor(e){this.logger=e,this.currentFrameSize=Hn.Send.initialResolution.fs}setAvailableBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Available bandwidth updated ${e}`),this.processEstimatedBandwidth(e))}setMaxFrameSize(e){this.logger.safe.debug(`SetMaxFrameSize ${e}`),e!==this.maxFrameSize?(this.maxFrameSize=e,this.lastSendBW?(this.logger.safe.debug(`Setting max frame size: ${e}`),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: ${e}`)}getFrameSize(){return this.currentFrameSize}processEstimatedBandwidth(e){if(this.logger.safe.debug(`Process estimated bandwidth ${e}`),0===e)return this.lastSendBW=0,void this.proposeResolution(0);const{lowRes:t,highRes:i}=Hn.Send.getResolutionForBitrate(e);this.logger.safe.debug("low",t,"hi",i);const n=e<this.lastSendBW?i.fs:t.fs;e<this.lastSendBW&&this.currentFrameSize<n?this.logger.safe.debug(`proposed resolution is above the existing one, so we should stay on the current resolution, last bw: ${e}`):(n&&this.proposeResolution(n),this.logger.safe.debug(`Updating last bw: ${e}`),this.lastSendBW=e)}proposeResolution(e){this.logger.safe.debug(`Propose resolution ${e}`);const t=this.maxFrameSize?Math.min(e,this.maxFrameSize):e;t!==this.currentFrameSize&&(this.currentFrameSize=t,this.logger.safe.debug(`Proposed new frame size: ${t} based on bandwidth: ${this.lastSendBW}`))}},NB=1e8,LB=[{bwe:2e5,param:5e5},{bwe:5e5,param:12e5},{bwe:8e5,param:25e5},{bwe:12e5,param:4e6}],xB=[{bwe:2e5,param:240},{bwe:3e5,param:405},{bwe:5e5,param:920},{bwe:9e5,param:2040}],FB=(e,t,i)=>{for(const n of i)if(t<n.bwe)return Math.min(e,n.param);return e},UB=(e,t,i=LB)=>FB(e,t,i),BB=(e,t,i=xB)=>FB(e,t,i),VB=class extends Vi{constructor(e,t,i){super(t),this.configProvider=e,this.logger=t,this.layoutsNumber=i,this.totalBandwidth=NB,this.totalBandwidthMax=0,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),this.outputLayouts=null,super.dispose()}setAvailableBandwidth(e){this.storeAvailableBandwidth(e),this.inputLayouts?(this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.debug("Layouts are not set. Skip update")}setLayouts(e,t){this.storeAvailableBandwidth(t),e.length===this.layoutsNumber?(this.logger.safe.debug(`Set layouts: ${JSON.stringify(e)}`),this.inputLayouts=this.getPrioritizedLayouts(e),this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.warn(`Incorrect number of layouts! ${JSON.stringify(e)}, expected ${this.layoutsNumber}`)}getLayouts(){return this.inputLayouts}getPrioritizedLayouts(e){return e}checkForChangesAndNotify(){const e=this.getLayouts();an(this.outputLayouts,e)?this.logger.safe.debug("Layout has not changed, skip update"):(this.outputLayouts=e.slice(),this.event("onLayoutsChanged").raise())}storeAvailableBandwidth(e){this.logger.safe.debug(`Set available bandwidth: ${e}`),this.totalBandwidth=e,this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth)}},HB=class extends VB{constructor(e,t){super(e,t,2),this.resolutionManager=new OB(this.logger.createChild("BWEControlledResolutionManager"))}getLayouts(){return this.hiFiLayout?[this.loFiLayout,this.hiFiLayout]:[this.loFiLayout]}dispose(){super.dispose(),this.resolutionManager=null}getHighLayoutBandwidth(e){const t=this.inputLayouts?.[0].maxBr||0,i=Math.max(e-t,0);this.logger.safe.debug(`Setting available bandwidth for layouts. High: ${i}, low: ${t||"not set"}, total: ${e}`);const n=this.configProvider.config.specCompliantSimulcast?.allowedBweOvershootRatio||1;return Math.floor(i*n)}recalculateLayouts(){const e=this.hiFiLayout,t=this.getHighLayoutBandwidth(this.totalBandwidth);this.resolutionManager.setAvailableBandwidth(t),this.resolutionManager.setMaxFrameSize(this.inputLayouts[1].maxFs),this.loFiLayout=this.getMinimalLayoutParams(this.inputLayouts),this.hiFiLayout=this.getHighLayoutParams(this.inputLayouts,t,this.loFiLayout),this.loFiLayout=this.adjustLowLayoutBasedOnHighLayout(this.hiFiLayout,this.loFiLayout,e)}adjustLowLayoutBasedOnHighLayout(e,t,i){return this.configProvider.config.useMediaQualityControllerForceKeyFrame&&!e&&i&&(this.logger.safe.debug("Forcing kayframe on low layout due to disabling high layout"),t.keyframe=!0),e?(t.maxBr===e.maxBr&&t.maxBr--,t):t}getPrioritizedLayouts(e){return e.sort(((e,t)=>e.maxFs-t.maxFs?e.maxFs-t.maxFs:e.maxFps-t.maxFps))}getHighLayoutParams(e,t,i){const n=e[1];if(n.maxBr<=t)return this.logger.safe.debug(`High layout bandwidth suits requested caps. Applying as-is: ${JSON.stringify(n)}`),n;const r={...e[1],maxFs:this.resolutionManager.getFrameSize(),maxBr:Math.min(t,e[1].maxBr),maxFps:e[1].maxFps},s=r.maxBr<i.maxBr||r.maxFs<i.maxFs||r.maxFs===i.maxFs&&r.maxFps<=i.maxFps,a=`Potential high layout: ${JSON.stringify(r)}`;return!this.hiFiLayout&&s?(this.logger.safe.debug(`High layout is already disabled. Do nothing. ${a}`),null):this.hiFiLayout&&s?(this.logger.safe.debug(`High layout gets disabled. ${a}`),null):(this.hiFiLayout&&an(r,this.hiFiLayout)?this.logger.safe.debug(`High layout has not been changed. Do nothing. ${a}`):this.hiFiLayout?this.logger.safe.debug(`High layout updated. ${a}`):this.logger.safe.debug(`High layout enabled. ${a}`),r)}getMinimalLayoutParams(e){const t=Math.min(e[0].maxBr,e[1].maxBr),i=this.configProvider.config.specCompliantSimulcast.maxBrControlEnabled?UB(t,this.totalBandwidth,this.configProvider.config.specCompliantSimulcast.bitrateToBweTable):t;return{...e[0],maxBr:i,maxFps:Math.min(e[0].maxFps,e[1].maxFps),maxFs:Math.min(e[0].maxFs,e[1].maxFs)}}},$B=class extends VB{constructor(e,t,i){super(t,i,1),this.couldLimitFs=e}getLayouts(){return[this.layout]}recalculateLayouts(){let e=this.inputLayouts[0].maxFs;if(this.configProvider.config.specCompliantSimulcast.allowResLimit&&this.couldLimitFs&&this.totalBandwidthMax){const t=this.configProvider.config.specCompliantSimulcast.fsToBweTable;e=BB(this.inputLayouts[0].maxFs,this.totalBandwidthMax,t)}const t=this.configProvider.config.specCompliantSimulcast.bitrateToBweTable,i=UB(this.inputLayouts[0].maxBr,this.totalBandwidth,t);this.layout={...this.inputLayouts[0],maxFs:e,maxBr:i}}},jB=class extends Vi{constructor(e){super(e),this.logger=e,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(e){this.logger.safe.debug(`Available bandwidth updated ${e}`)}setLayouts(e,t){this.layouts=e,this.setAvailableBandwidth(t)}getLayouts(){return this.layouts}},GB=(e,t)=>e.maxFs===t.maxFs?e.maxFps===t.maxFps?e.maxBr-t.maxBr:e.maxFps-t.maxFps:e.maxFs-t.maxFs,qB=(e,t)=>e.maxFs===t.maxFs?e.maxFps-t.maxFps:e.maxFs-t.maxFs,zB=class extends Vi{constructor(e,t,i){super(i),this.settings=e,this.configProvider=t,this.logger=i,this.totalBandwidthMax=0,this.totalBandwidth=NB,this.inputLayouts=null,this.outputLayouts=null,this.maxOutputLayers=0,this.ladder=[],this.settings.ladder?this.ladder.push(...this.settings.ladder):this.ladder.push(...Hn.Send.getResolutions())}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(e){this.updateAvailableBandwidth(e),this.update()}setLayouts(e,t){this.inputLayouts=e,this.updateAvailableBandwidth(t),this.update()}getLayouts(){return this.outputLayouts??[]}updateAvailableBandwidth(e){this.totalBandwidth!==Math.max(1,e)&&(this.logger.safe.debug(`Available bandwidth updated ${e}`),this.totalBandwidth=Math.max(1,e),this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth))}debug(e,t,...i){let n;const r=e=>({FS:e.maxFs,FPS:e.maxFps,BR:e.maxBr,KF:e.keyframe?"1":"0",id:`rid:${e.rid}`??0});n=Array.isArray(t)?t.map(r):r(t),this.logger.safe.info(`${e}: <${i.map((e=>JSON.stringify(e))).join("><")}> ${JSON.stringify(n)}`)}update(){const e=this.settings.allowedOvershoot||1,t=this.adjustLayout(this.inputLayouts,this.totalBandwidth*e);if(an(this.outputLayouts,t))this.logger.safe.debug("Layout has not changed, skip update");else{if(this.settings.allowLayerBitrateOverlap&&t.length&&t.length<this.inputLayouts.length&&(this.setMinimumQuality(t[0],this.inputLayouts),this.debug("SetMinimumQuality",t[0])),this.outputLayouts&&this.settings.forceKeyFrameWhenLayerIsRemoved&&this.outputLayouts.length>t.length)for(const e of t)this.logger.safe.debug(`Force key frame for rid:${e.rid}`),e.keyframe=!0;this.outputLayouts=t,this.maxOutputLayers=Math.max(this.maxOutputLayers,this.outputLayouts.length),this.event("onLayoutsChanged").raise()}}adjustLayout(e,t){const i=[];if(e.length){if(e=e.map((e=>Object.assign({},e))).sort(GB),this.debug("OriginalLayout",e),this.settings.minFrameSizeForSimulcast?.length>1){const t=this.settings.minFrameSizeForSimulcast;3===e.length&&2===t?.length&&e[e.length-1].maxFs<t[1]&&this.debug("DisableLowResStream",e.pop())}for(this.settings.highPriorityLayoutMinFS&&e.length>1&&e[e.length-1].maxFs>=this.settings.highPriorityLayoutMinFS&&this.settings.lowPriorityLayoutMaxFS?.length&&this.limitResolutionOnLowerSimulcastStreams(e);e.length>0&&t>0;){const n=e.shift();this.debug("Next",n,t),this.settings.allowLayerBitrateOverlap||this.setMinimumQuality(n,e);let r=t-n.maxBr;if(i.length>0){if(r<0&&this.degradeBitrateOrResolution(n,t)&&(this.debug("DegradeBitrateOrResolution",n),r=t-n.maxBr),r>=0){let e=!1;for(const t of i)if(e=qB(t,n)>=0,this.settings.allowLayerBitrateOverlap||n.maxBr<t.maxBr&&(e=!0),e){this.debug("Drop",n,i.length);break}e||(i.push(n),this.debug("Accept",n,i.length))}}else i.push(n),this.debug("Accept",n,i.length);t=r}this.debug("AdjustedLayout",i,t)}if(1===i.length)if(this.settings.minSinglecastBitrate||this.settings.singlecastLadder){const e=Math.max(this.settings.minSinglecastBitrate??this.totalBandwidth,this.totalBandwidth);this.settings.forceSinglecastLadder&&this.settings.singlecastLadder?this.forceLadder(i[0],e,this.settings.singlecastLadder)&&this.debug("ForceSinglecastLadder",i[0],e):i[0].maxBr>e&&this.degradeBitrateOrResolution(i[0],e,this.settings.singlecastLadder)&&this.debug("DegradeSinglecast",i[0],e)}else{if(this.settings.limitMaxResolution&&this.maxOutputLayers<=1){const e=this.configProvider.config.specCompliantSimulcast?.fsToBweTable;i[0].maxFs=BB(i[0].maxFs,this.totalBandwidthMax,e),this.debug("LimitMaxFS",i[0],this.totalBandwidthMax)}if(this.settings.limitMaxBitrate){const e=this.configProvider.config.specCompliantSimulcast?.bitrateToBweTable;i[0].maxBr=UB(i[0].maxBr,this.totalBandwidth,e),this.debug("LimitMaxBitrate",i[0],this.totalBandwidth)}}return i}limitResolutionOnLowerSimulcastStreams(e){const t=e.pop();if(1===e.length){const t=this.settings.lowPriorityLayoutMaxFS[0];this.degradeResolutionTo(e[0],t)&&this.debug("DegradeResolutionTo",e[0],0,t)}else{const t=[...this.settings.lowPriorityLayoutMaxFS];t.sort(),e.splice(Math.min(2,t.length));for(let i=0;i<e.length;++i)this.degradeResolutionTo(e[i],t[i])&&this.debug("DegradeResolutionTo",e[i],i,t[i])}e.push(t)}setMinimumQuality(e,t){for(const i of t)e.maxBr=Math.min(i.maxBr,e.maxBr),e.maxFs=Math.min(i.maxFs,e.maxFs),e.maxFps=Math.min(i.maxFps,e.maxFps),e.maxMbps=e.maxFs*e.maxFps}degradeResolutionTo(e,t){for(;e.maxFs>t;)if(!this.degradeResolution(e))return!1;return!0}degradeResolution(e){const t=this.mapLayoutToLadder(e);if(t>=this.ladder.length)return!1;if(t>0){const i=this.ladder[t-1];return e.maxBr=Math.min(e.maxBr,i.maxBitrate),e.maxMbps=i.fs*i.fps,e.maxFps=i.fps,e.maxFs=i.fs,!0}return!1}degradeBitrateOrResolution(e,t,i){i??(i=this.ladder);const n=this.mapLayoutToLadder(e,i);if(n>=i.length)return!1;if(t>=i[n].minBitrate)return e.maxBr=t,!0;let r=n;for(;r>0;){const n=i[--r];if(t>=n.minBitrate)return e.maxMbps=n.fs*n.fps,e.maxFps=n.fps,e.maxFs=n.fs,e.maxBr=Math.min(t,n.maxBitrate),!0}return!1}forceLadder(e,t,i){i??(i=this.ladder);const n=this.mapLayoutToLadder(e,i);if(n>=i.length)return!1;let r=Math.min(t,e.maxBr);if(r>=i[n].minBitrate){const t=i[n];return r=Math.min(r,t.maxBitrate),(e.maxMbps!==t.fs*t.fps||e.maxBr!==r)&&(e.maxMbps=t.fs*t.fps,e.maxFps=t.fps,e.maxFs=t.fs,e.maxBr=r,!0)}return this.degradeBitrateOrResolution(e,r,i)}mapLayoutToLadder(e,t){let i=0,n=0;for(t??(t=this.ladder);n<t.length&&!(t[n].fs>e.maxFs)&&!(t[n].fs===e.maxFs&&t[n].fps>e.maxFps);)i=n++;return i}},WB=class extends Vi{constructor(e,t,i,n){super(n),this.supportSingleBwControl=e,this.firstTime=t,this.configProvider=i,this.logger=n,this.multiStream=!1,this.wasMultistream=!0,this.deferredOperation=new kB((()=>this.updateStrategy()),this.configProvider.config.layoutControlTimeout,this.logger.createChild("DeferredOperation")),this.simulcastStrategySettings=void 0,this.wasMultistream=!1,this.createStrategy(this.multiStream,this.firstTime)}configure(e){const t=this.isMultiStream(e);this.multiStream!==t&&(this.multiStream=t,this.simulcastStrategySettings||this.deferredOperation.invoke(this.multiStream&&!this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled))}onFeaturesChanged(e){const t={},i=this.configProvider.config.specCompliantSimulcast;let n=!1;e.hasServerSupport(0)&&(n=!0),e.hasClientSupport(2)&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&(n=!0),e.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&(n=!0),t.limitMaxBitrate=i?.maxBrControlEnabled,t.limitMaxResolution=i?.allowResLimit,t.allowedOvershoot=i?.allowedBweOvershootRatio,t.forceKeyFrameWhenLayerIsRemoved=this.configProvider.config.useMediaQualityControllerForceKeyFrame,n&&t.limitMaxResolution&&(t.limitMaxResolution=this.firstTime&&!this.wasMultistream),e.hasClientSupport(2)&&(e.hasClientSupport(1)||(t.highPriorityLayoutMinFS=this.configProvider.config.video1080p?.software?.highPriorityLayoutMinFS,t.lowPriorityLayoutMaxFS=this.configProvider.config.video1080p?.software?.lowPriorityLayoutMaxFS),t.minSinglecastBitrate=this.configProvider.config.video1080p?.minSinglecastBitrate,this.configProvider.config.video1080p?.singlecastLayoutLadder&&(t.singlecastLadder=Un(this.configProvider.config.video1080p.singlecastLayoutLadder)),t.forceSinglecastLadder=this.configProvider.config.video1080p?.forceSinglecastLadder),e.hasClientSupport(3)&&(t.highPriorityLayoutMinFS=this.configProvider.config.broadcastMode?.priorityLayoutMinFS,t.lowPriorityLayoutMaxFS=this.configProvider.config.broadcastMode?.lowPriorityLayoutMaxFS),e.hasServerSupport(0)&&(t.minSinglecastBitrate=t.minSinglecastBitrate??i?.minSinglecastBitrate,t.allowLayerBitrateOverlap=i?.allowLayerBitrateOverlap,i?.singlecastLadder&&(t.singlecastLadder=t.singlecastLadder??Un(i?.singlecastLadder)),i.dropLowResolutionHigherStreams&&(t.minFrameSizeForSimulcast=i.video?.minFsForSimulcast)),!!this.simulcastStrategySettings===n&&an(t,this.simulcastStrategySettings)||(n?(this.logger.safe.info(`[SLCS] Configure [${this.simulcastStrategySettings?"existing":"initial"}][${this.wasMultistream}]: ${JSON.stringify(t)}`),this.simulcastStrategySettings=t):(this.simulcastStrategySettings&&this.logger.safe.info("[SLCS] Disable"),this.simulcastStrategySettings=void 0),this.deferredOperation.invoke(!1))}setLayouts(e,t){an(this.latestLayouts,e)&&this.latestBandwidth===t?this.logger.safe.debug("Layouts and bandwidth are not changed. Skipping update"):(this.latestLayouts=e,this.latestBandwidth=t,this.strategy.setLayouts(this.latestLayouts,t))}setAvailableBandwidth(e){this.latestBandwidth!==e?(this.strategy.setAvailableBandwidth(e),this.latestBandwidth=e):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(e){return e>1}createStrategy(e,t=!1){this.strategy=this.getNewStrategy(e,t),this.strategy.on("onLayoutsChanged",(()=>{this.wasMultistream=this.wasMultistream||this.isMultiStream(this.strategy.getLayouts().length),this.event("onLayoutsChanged").raise()}))}getNewStrategy(e,t){return this.simulcastStrategySettings?new zB(this.simulcastStrategySettings,this.configProvider,this.logger.createChild("SimulcastLayoutControlStrategy")):e?new HB(this.configProvider,this.logger.createChild("BWEControlledStrategy")):this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled&&this.supportSingleBwControl?new $B(t,this.configProvider,this.logger.createChild("BWEControlledStrategySingle")):new jB(this.logger.createChild("NoControlStrategy"))}},KB=class extends Vi{constructor(e,t,i){super(t),this.configProvider=e,this.logger=t,this.videoFeatures=i,this.bandwidthAllocator=null,this.sendBandwidthCalculator=new YU(this.configProvider,this.logger.createChild("SendBandwidthCalculator")),this.layoutProviders=new Map,this.hadLayoutProvider=new Set,this.useNewBandwidthAllocator=!1,this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator=function(e,t){const i=new RB(e.createChild("BandwidthAllocator"));return i.setLadder("ScreenShare",t.config.sharingBitrateLadderOverride||AB),i.setLadder("Video",t.config.videoBitrateLadderOverride||PB),i}(this.logger,this.configProvider),this.sendBandwidthCalculator.on("onSendBandwidthChanged",(e=>this.onAvailableBandwidthChanged(e))),this.configProvider.config.sendBandwidthSeedValue&&this.bandwidthAllocator.setAvailableBandwidth(this.configProvider.config.sendBandwidthSeedValue),this.useVideoFeatures("Video")&&this.videoFeatures.on("onVideoFeaturesChanged",(e=>{if(this.useVideoFeatures(e.mediaType)){const t=this.layoutProviders.get(e.mediaType);t&&t.onFeaturesChanged(e)}if(!this.useNewBandwidthAllocator&&this.configProvider.config.bandwidthAllocatorV2.enableAllocator){let t=!1;e.hasServerSupport(0)&&(t=!0),e.hasClientSupport(2)&&this.configProvider.config.video1080p?.useNewBandwidthAllocator&&(t=!0),t&&this.switchBandwidthAllocator()}}))}dispose(){this.bandwidthAllocator=null,this.layoutProviders.forEach((e=>e.dispose())),this.layoutProviders.clear(),this.layoutProviders=null,super.dispose()}addReceiver(e,t){this.logger.safe.debug(`Set receiver max capabilities for ${e}: ${JSON.stringify(t)}`),this.configureProviders(e,t.length);const i=t.map((e=>e.maxBr)).reduce(((e,t)=>e+t));if(this.useNewBandwidthAllocator&&"Video"===e&&this.layoutProviders.has("ScreenShare")&&this.configProvider.config.bandwidthAllocatorV2.enableDynamicVideoLadder){const e=Math.max(...t.map((e=>e.maxFs)));e>this.highestVideoMaxFsWithSharingEnabled&&(this.highestVideoMaxFsWithSharingEnabled=e,this.bandwidthAllocator.setLadder("Video",MB(this.configProvider,e)))}this.bandwidthAllocator.addReceiverCapability(e,i);const n=this.bandwidthAllocator.getLayouts();this.layoutProviders.get(e).setLayouts(t,n[e]),this.updateBandwidthDistribution()}removeReceiver(e){this.logger.safe.debug(`Removing receiver for ${e}`),this.layoutProviders.get(e)?.dispose(),this.layoutProviders.delete(e),this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator.removeReceiver(e),this.updateBandwidthDistribution()}getLayouts(e){return this.layoutProviders.get(e).getLayouts()}onStatisticsChanged(e){this.sendBandwidthCalculator.onBandwidthChanged(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){e.video?.send?.length&&e.video?.send[0]&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth"),this.sendBandwidthCalculator.onBandwidthChanged(JU(e.video.send[0],this.configProvider)))}useVideoFeatures(e){return!("Video"!==e||!this.configProvider.config.specCompliantSimulcast?.enableSimulcastLayoutControlStrategy&&!this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&!this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy)}switchBandwidthAllocator(){const e=function(e,t){const i=new DB(e.createChild("BandwidthAllocator2"));return i.setPriority("ScreenShare","Video"),i.setLadder("ScreenShare",t.config.bandwidthAllocatorV2.sharingLadder),i.setLadder("Video",MB(t,t.config.bandwidthAllocatorV2.defaultVideoMaxFS)),i}(this.logger,this.configProvider);e.setAvailableBandwidth(this.bandwidthAllocator.getAvailableBandwidth());const t=this.bandwidthAllocator.getReceiverCapabilities();for(const i of Object.keys(t))e.addReceiverCapability(i,t[i]);this.useNewBandwidthAllocator=!0,this.bandwidthAllocator=e,this.updateBandwidthDistribution()}configureProviders(e,t){if(!this.layoutProviders.has(e)){const t=this.createProvider(e);this.layoutProviders.set(e,t)}this.useVideoFeatures(e)&&t>2&&this.videoFeatures.get(e).toggleServer(0,!0),this.layoutProviders.get(e).configure(t)}createProvider(e){const t=new WB("Video"===e,!this.hadLayoutProvider.has(e),this.configProvider,this.logger.createChild(`LG:${e}`));return t.on("onLayoutsChanged",(()=>{const i=t.getLayouts();this.logger.safe.debug(`New layouts generated: ${JSON.stringify(i)}`),this.event("onLayoutsUpdated").raise(e)})),this.hadLayoutProvider.add(e),this.useVideoFeatures(e)&&t.onFeaturesChanged(this.videoFeatures.get(e)),t}onAvailableBandwidthChanged(e){this.bandwidthAllocator.setAvailableBandwidth(e),this.updateBandwidthDistribution()}adjustBandwidthDistribution(e,t){const i=new Map;t?(i.set("ScreenShare",this.configProvider.config.bandwidthAllocatorV2?.sharing?.remote),i.set("Video",this.configProvider.config.bandwidthAllocatorV2?.video?.remote)):(i.set("ScreenShare",this.configProvider.config.bandwidthAllocatorV2?.sharing?.local),i.set("Video",this.configProvider.config.bandwidthAllocatorV2?.video?.local));const n=function(e,t){const i=Object.keys(e).filter((t=>e[t]>0)).length>1;for(const n of Object.keys(e)){const r=t.get(n);if(void 0===e[n])continue;if(!r?.minValue&&!r?.minValueMixedMode)continue;const s=i?r?.minValueMixedMode:r?.minValue;e[n]=Math.max(s??r?.minValue??0,e[n])}return e}({...e},i);for(const i of["Video","ScreenShare"])n[i]!==e[i]&&this.logger.safe.info(`Adjusted ${t?"remote":"local"} ${i} BWE from ${e[i]} to ${n[i]}`);return n}updateBandwidthDistribution(){const e=this.bandwidthAllocator.getLayouts();let t;t=e,this.useNewBandwidthAllocator&&(t=this.adjustBandwidthDistribution(e,!1));for(const[e,i]of Object.entries(t))this.layoutProviders.get(e)?.setAvailableBandwidth(i);this.configProvider.config.mediaControlPlaneConfig?.enableSendBandwidthNotificationsEnabled&&(t=e,this.useNewBandwidthAllocator&&(t=this.adjustBandwidthDistribution(e,!0)),this.event("onBandwidthAllocationUpdated").raise(t))}},JB=Z;function YB(e,t,i){if("Video"!==e||!i)return i;const{maxBitrate:n,maxResolution:r,maxFramerate:s}=t.config.outgoingVideoLimit??{},a=n??1/0;let o=r?jn(r):1/0,l=s??1/0;return t.config.sendVideoCapabilityManager?.isEnabled&&(o=1/0,l=1/0),a===1/0&&o===1/0&&l===1/0?i:i.map((e=>({...e,maxFs:Ki(e.maxFs,o),maxBr:Ki(e.maxBr,a),maxFps:Ki(e.maxFps,l)})))}var QB=new Set(["maintain-framerate","maintain-resolution","balanced"]),ZB=class{constructor(e,t){this.configProvider=e,this.logger=t}async setActive(e,t){const i=this.getSenderParameters(e);return i.encodings[0].active=t,this.setSenderParameters(e,i,"setActive")}getScaleFactor(e,t){if(!t.width||!t.height)return this.logger.safe.warn("Stream resolution is not set yet. Cannot calculate scale factor. Returning 1"),1;const i=Hn.Send.getResolutionByFs(e);let n=Math.min(t.width,t.height)/i.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(t)} and new Fs: ${e} as ${n}`),n<1&&(this.logger.safe.warn("Scale factor cannot be less than 1! Limiting to 1"),n=1),n}async generateKeyFrameIfNeeded(e,t){if(!t.track)return void this.logger.safe.info("No track attached. Skipping");const i=this.getSenderParameters(t),n=e.filter((e=>e.keyframe)).map((e=>e.rid));if(0!==n.length&&i.encodings.some((e=>e.active)))if(this.configProvider.config.useKeyFrameApi){const e=[];i.encodings.forEach((t=>{!t.active||t.rid&&!n.includes(t.rid)?e.push({keyFrame:!1}):e.push({keyFrame:!0})})),await this.setSenderParameters(t,i,"generateKeyFrameAPI",!0,{encodingOptions:e})}else{const e=i.encodings.map(((e,t)=>e.active?e.rid&&!n.includes(e.rid)?null:{idx:t,factor:e.scaleResolutionDownBy||1}:null)).filter((e=>e));for(const t of e)i.encodings[t.idx].scaleResolutionDownBy=t.factor*this.configProvider.config.forceKeyFrameV2ScaleFactor;this.logger.safe.debug(`Restoring keyframe starting. Update scaleResolutionDownBy for encodings: ${JSON.stringify(i.encodings)}`),await this.setSenderParameters(t,i,"generateKeyFrameStart");const r=this.getSenderParameters(t);for(const t of e)r.encodings[t.idx].scaleResolutionDownBy=t.factor;await this.setSenderParameters(t,r,"generateKeyFrameEnd"),this.logger.safe.debug(`Restoring keyframe completed. Set scaleResolutionDownBy back for encodings: ${JSON.stringify(r.encodings)}`)}else this.logger.safe.info("No keyframes needed. Skipping")}getSenderParameters(e){const t=e.getParameters();if(t.encodings?.length||(t.encodings=[{}]),this.configProvider.config.reuseLastSetParameters&&this.lastSetEncodings){this.logger.safe.info(`Override returned encodings ${JSON.stringify(t.encodings)}`);const e=(0,JB.merge)((0,JB.cloneDeep)(t.encodings),this.lastSetEncodings);this.logger.safe.info(`Overrided encodings ${JSON.stringify(e)}`),t.encodings=e}return t}async setSenderParameters(e,t,i,n=!0,r){try{await e.setParameters(t,r),this.logger.safe.info(`${i}: Parameters applied for sender: encodings: ${JSON.stringify(t.encodings)}, degradationPreference: ${t.degradationPreference}`),this.lastSetEncodings=t.encodings}catch(e){const r=`${i}: setParameters failed. Parameters: ${JSON.stringify(t.encodings)}, error: ${tt(e)}`;if(this.logger.safe.error(r),n)throw new Error(r)}}getAdjustedBitrate(e,t){let i=e||0;const{maxBitrate:n}=Hn.Send.getBitrateForResolution(t.width,t.height);return i=Math.min(i||n,n),i}async updateStreamParameters(e,t,i){if(e.getCurrentConstraints().withEffect&&t?.maxFs){const i=Hn.Send.getResolutionByFs(t.maxFs),n={width:i.width,height:i.height};this.logger.safe.info(`Applying video constrains for video effetcs ${JSON.stringify(n)}`),e.resetEffectsOutputConstraints(n)}i&&await e.applyCapabilities(t)}augmentDegradationPreference(e,t){QB.has(t)&&e.degradationPreference!==t&&(e.degradationPreference=t,this.logger.safe.info(`degradationPreference changed to: ${e.degradationPreference}`))}async setEncodingsActiveState(e,t,i){this.logger.safe.info(i);const n=this.getSenderParameters(e);return n.encodings.forEach((e=>e.active=t)),this.setSenderParameters(e,n,i)}},XB=class{constructor(e,t,i){this.config=e,this.configProvider=t,this.logger=i,this.capabilitiesHelper=new ZB(this.configProvider,this.logger)}get streamResolution(){return this.stream?.getCurrentConstraints().withEffect?this._streamResolutionFromCapabilities:this._streamResolution}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this._streamResolution=e.getResolution(),this._streamResolutionFromCapabilities=this._streamResolution}setActive(e){return this.capabilitiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,JB.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):(this.defaultCapabilities=(0,JB.cloneDeep)(e),this.currentCapabilities=(0,JB.cloneDeep)(e),await this.applyLastCapabilities(),await this.capabilitiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender))}async updateStreamQualityParams(e,t,i){if(e&&!(0,JB.isEqual)(this.streamResolution,e))return this._streamResolution=e,this._streamResolutionFromCapabilities=e,this.logger.safe.info(`Stream params changed: ${JSON.stringify(e)}@${t}@${i} id: ${this.rtpSender.track?.id}`),this.applyLastCapabilities();this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(){return Em(this.configProvider,this.stream)||bm(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=YB(this.stream.mediaType,this.configProvider,this.defaultCapabilities),await this.applyStreamCapabilities(this.currentCapabilities);const e=this.capabilitiesHelper.getSenderParameters(this.rtpSender),t=(0,JB.cloneDeep)(e);return this.currentCapabilities.forEach((t=>{const i=this.getEncondingIndexForRid(t.rid,e.encodings);this.updateEncodingsWithCaps(e.encodings[i],t)})),this.capabilitiesHelper.augmentDegradationPreference(e,this.configProvider.config.degradationPreference),this.updateActiveStates(e,this.currentCapabilities),this.logger.safe.info(`Encoding params new: ${JSON.stringify(e.encodings)}, old: ${JSON.stringify(t.encodings)}`),this.capabilitiesHelper.setSenderParameters(this.rtpSender,e,"applyCapabilities")}async applyCallConstraints(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities()}async applyStreamCapabilities(e){if("Video"!==this.stream.mediaType||!e.length)return;let t=e[0];for(const i of e)t.maxFs<i.maxFs&&(t=i);if(e.length>1){const i=this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast;if(t=(0,JB.cloneDeep)(t),i?.length>0)for(let n=0;n<i.length;++n)e.length>n+1&&(t.maxFs=Math.max(i[n]||0,t.maxFs),t.maxFps=Math.max(...e.map((e=>e.maxFps))))}const i=this.configProvider.config.specCompliantSimulcast.video.useApplyConstraints;await this.capabilitiesHelper.updateStreamParameters(this.stream,t,i),i&&(this._streamResolution=this.stream.getResolution())}getEncondingIndexForRid(e,t){if(!e)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const i=t.findIndex((t=>t.rid===e));return i<0||i-1>this.config.layerScaleFactors.length?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):i}updateEncodingsWithCaps(e,t){e?(e.maxBitrate=t.maxBr,e.scaleResolutionDownBy=this.capabilitiesHelper.getScaleFactor(t.maxFs,this.streamResolution),e.maxFramerate=t.maxFps,this.config.defaultScalabilityMode&&(e.scalabilityMode=this.config.defaultScalabilityMode)):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(t)}`)}updateActiveStates(e,t){const i=e.encodings.map((e=>e.rid)),n=i.filter((e=>t.some((t=>e===t.rid)))),r=hn(i,n);n.forEach((t=>this.changeEncodingState(e,t,!0))),r.forEach((t=>this.changeEncodingState(e,t,!1)))}changeEncodingState(e,t,i){const n=e.encodings.find((e=>e.rid===t));n?n.active=i:this.logger.safe.error(`Encoding not found for RID: ${t}`)}},eV=class{constructor(e,t){this.configProvider=e,this.logger=t,this.capabilitiesHelper=new ZB(this.configProvider,this.logger)}get params(){return this.currentCapabilities?.find((e=>"1"===e.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(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities(3)}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this.streamResolution=e.getResolution()}setActive(e){return this.capabilitiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,JB.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):1===e.length?(this.defaultCapabilities=(0,JB.cloneDeep)(e),this.currentCapabilities=(0,JB.cloneDeep)(e),await this.applyLastCapabilities(0),await this.capabilitiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender)):this.logger.safe.error("Incorrect number of sender params!")}async updateStreamQualityParams(e,t,i){if(e&&!(0,JB.isEqual)(this.streamResolution,e))return this.streamResolution=e,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(e)}@${t}`),this.applyLastCapabilities(i);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(e){this.logger.safe.info(`Replace sender with track: ${e.id}`),await this.rtpSender.replaceTrack(e),this.logger.safe.info("replaceTrack completed"),Em(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),bm(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 Em(this.configProvider,this.stream)||bm(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(e){this.currentCapabilities?(this.currentCapabilities=YB(this.stream.mediaType,this.configProvider,this.defaultCapabilities),this.logger.safe.info(`Applying params: ${JSON.stringify(this.params)}`),await this.applyParams(this.params,e),await this.applyBitrate(this.params.maxBr)):this.logger.safe.debug("Capabilities are not yet set, nothing to apply")}applyBitrate(e){let t=e||0;return"Video"===this.stream.mediaType&&(t=this.capabilitiesHelper.getAdjustedBitrate(t,this.streamResolution)),this.setSingleEncodingParameters(this.rtpSender,{maxBitrate:t},"applyBitrate",!1)}async applyParams(e,t){if(this.useSetParameter)return this.setSingleEncodingParameters(this.rtpSender,{scaleResolutionDownBy:this.capabilitiesHelper.getScaleFactor(e.maxFs,this.streamResolution),maxFramerate:e.maxFps},"applyParams");2!==t&&await this.capabilitiesHelper.updateStreamParameters(this.stream,e,!0)}async setSingleEncodingParameters(e,t,i,n=!0){const r=this.capabilitiesHelper.getSenderParameters(e);return(0,JB.merge)(r.encodings[0],t),0===r.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?r.encodings[0].maxBitrate=void 0:delete r.encodings[0].maxBitrate),this.capabilitiesHelper.augmentDegradationPreference(r,this.configProvider.config.degradationPreference),this.capabilitiesHelper.setSenderParameters(this.rtpSender,r,i,n)}},tV=class{constructor(e,t,i){this.transitionStates=e,this.logger=i,this.stateCurrent=t}get state(){return this.stateCurrent}isDestinationStateValid(e){return this.transitionStates[this.stateCurrent].indexOf(e)>-1}setState(e){return this.isDestinationStateValid(e)?(this.stateCurrent=e,!0):(e!==this.stateCurrent&&this.logger.safe.info(`Invalid state transition ${this.stateCurrent} -> ${e}`),!1)}isCurrentStateMatchedWith(e){return this.stateCurrent===e||(this.logger.safe.info(`State does not match. Current: ${this.stateCurrent} required: ${e}`),!1)}},iV=class extends Vi{constructor(e,t){super(e),this.logger=e,this.configProvider=t,this.audioContext=new Mp.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(e){if(!e.rawStream)return;if(this.streamNodeMap.has(e.rawStream))return;const t=e.on("onStreamClientDisposing",(()=>{this.removeSourceStream(e.rawStream),t.dispose()}));this.logger.safe.info(`Add stream: ${e.rawStream.id}, track: ${nV(e.rawStream).id}`),this.addStream(e.rawStream,e.mediaType)}getDestinationTrack(){return nV(this.destination.stream)}dispose(){super.dispose(),this.unsubscribeFromMediaTrackEvents(this.getDestinationTrack());for(const e of this.streamNodeMap.keys())this.removeSourceStream(e);this.audioContext.close(),this.audioContext=null}addStream(e,t="Audio"){const i=this.audioContext.createMediaStreamSource(e);i.connect(this.destination),this.streamNodeMap.set(e,{mediaType:t,sourceNode:i})}removeSourceStream(e){const t=this.streamNodeMap.get(e);t&&(this.logger.safe.info(`Remove stream: ${e.id}, track: ${nV(e).id}`),t.sourceNode.disconnect(),this.streamNodeMap.delete(e))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.id} unmuted`)}}unsubscribeFromMediaTrackEvents(e){e.onended=null,e.onmute=null,e.onunmute=null}};function nV(e){return e.getAudioTracks()[0]}var rV=class extends Vi{constructor(e,t,i,n,r,s,a){super(),this.mediaConnection=e,this.contextStream=i,this.logger=n,this.configProvider=r,this.encStreamsManager=s,this.capabilitiesManager=a,this.isMuted=!1,this.isActiveInternal=!1,this.stream=t.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(e){return this.capabilitiesManager.applyCallConstraints(e)}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(e){this.configProvider.config.applySenderParamsBeforeStart||await this.start();try{await this.capabilitiesManager.setCapabilities(e)}catch(e){this.logger.safe.error(`Error setting capabilities: ${tt(e)}`)}await this.start()}updateStreamQualityParams(e,t,i){return this.capabilitiesManager.updateStreamQualityParams(e,t,i)}setMuted(e,t,i){this.isMuted=e,this.stream.setMuted(e,t),e&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(e),!this.configProvider.config.requestNewStreamOnUnmute||e||i||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(e,t){if(this.configProvider.config.holdSkipActivation)return;const i=!e;this.logger.safe.info(`[${t}] change isActive state to ${i}`);try{return this.capabilitiesManager.setActive(i)}catch(e){const n=this.configProvider.config.holdRetryActivationDelay;if(n>=0)return this.logger.safe.info(`[${t}] retrying after delay of ${n}`),await Yt(n),this.logger.safe.info(`[${t}] change isActive state to ${i}, second attempt`),this.capabilitiesManager.setActive(i);throw e}}async setMainStream(e){return this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=e.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(e){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(e),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((e=>e.active)).map((e=>+e.rid))}isActive(){return this.sender&&(Em(this.configProvider,this.stream)||bm(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(e){this.logger.safe.warn(`Error removing sender: ${tt(e)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${tt(e)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.rawTrack,this.contextStream,am(this.stream.mediaType))}addStreamTransforms(){const e=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);e&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new Tf(this.logger.createChild("SendAudioPayload")),e.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&e.addTransform(new Sf(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 iV(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 e=this.sender.getParameters();return e.encodings?.length||(e.encodings=[{}]),e}subscribeOnStreamClientMuted(){this.configProvider.config.recoverOnStreamUnmute&&(this.onStreamClientMutedSubscription=this.stream.on("onStreamClientMuted",(async(e,t)=>{t||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}},sV=class e extends Vi{constructor(t,i,n,r,s,a,o,l,c,d,u){super(),this.mediaConnection=t,this.mainStream=i,this.contextStream=n,this.mediaType=r,this.serialQueue=s,this.logger=a,this.configProvider=o,this.isAlwaysActive=l,this.encStreamsManager=c,this.simulcastContext=d,this.sendVideoCapabilityManager=u,this.isMuted=!1,this.isHold=!1,this.previousParameters=[],this.state=new tV(e.transitionStates,"NotStarted",this.logger.createChild("state")),this.pendingStream=null,this.pendingParams=null,this.lastAppliedParams=null,this.subscribeOnQualityUpdates(this.mainStream),u&&this.sendVideoCapabilityManager.on("onCapabilitiesChanged",(e=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(e),this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly&&this.lastAppliedParams&&!this.pendingParams&&this.updateParameters(this.lastAppliedParams)}))}async start(){this.state.setState("Started")&&(this.sender=new rV(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 e=async()=>{this.configProvider.config.enableCachingFMTPDelay>0&&(this.logger.safe.info("Applying delay before applying pending parameters"),await Yt(this.configProvider.config.enableCachingFMTPDelay)),this.logger.safe.info("Apply pending parameters");const e=this.updateParametersInternal(this.pendingParams);return this.pendingParams=null,e};this.configProvider.config.enableCachingFMTPAwait?(this.logger.safe.info("Apply pending parameters"),await e()):(this.logger.safe.info("Apply pending parameters in background"),e().catch((e=>this.logger.safe.error("Error applying pending parameters",e))))}}updateStream(e){return this.updateStreamInternal(e)}async addAdditionalStream(e){return this.sender.addAdditionalStream(e)}async updateParameters(e){if(this.state.isCurrentStateMatchedWith("Active"))return this.updateParametersInternal(e);this.configProvider.config.enableCachingFMTP?(this.logger.safe.info("Postpone params update until sender is activated"),this.pendingParams=e):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(e,t){if(this.isHold!==e)return this.logger.safe.info(`[${t}] Setting hold to: ${e}`),this.isHold=e,this.sender.setHold(e,t);this.logger.safe.info(`[${t}] Already in hold=${e} state`)}setMuted(e,t,i){this.logger.safe.info(`[${t}] Setting muted to: ${e}`),this.isMuted=e,this.sender.setMuted(this.isMuted,t,i),!this.isMuted&&"Audio"===this.mediaType&&this.state.isCurrentStateMatchedWith("Active")&&this.sender.start()}getActiveStreamIndexes(){return this.sender?this.sender.getActiveStreamIndexes():[]}getTrackInfo(){return{modality:am(this.mediaType),trackId:this.sender.trackId}}applyCallConstraints(e){return this.sendVideoCapabilityManager?.applyCallConstraints(e),this.sender.applyCallConstraints(e)}getCapabilitiesManager(e){return e?.shouldUseSimulcast()?new XB(e.config,this.configProvider,this.logger.createChild("SimCapMgrV2")):new eV(this.configProvider,this.logger.createChild("SnglCapMgrV2"))}async updateStreamInternal(e){return this.logger.info(`updateStreamInternal(): id: ${e.id}, parentId: ${e.parentId}), mediaType: ${this.mediaType}`),this.state.isCurrentStateMatchedWith("Active")?this.mainStream!==e?(this.logger.safe.debug(`Switching streams: ${this.mainStream.parentId}:${this.mainStream.id} -> ${e.parentId}:${e.id}`),this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=e,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(e))}async updateParametersInternal(e){if(this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly){this.lastAppliedParams=e;const t=this.sendVideoCapabilityManager?.getCapabilities();t&&(e=e.map((e=>{const i={...e};return i.maxFs>t.maxFs&&(this.logger.safe.info(`Reducing SSRC:${i.ssrc} video FS from ${i.maxFs} to ${t.maxFs}`),i.maxFs=t.maxFs),i.maxFps>t.maxFps&&(this.logger.safe.info(`Reducing SSRC:${i.ssrc} video FPS from ${i.maxFps} to ${t.maxFps}`),i.maxFps=t.maxFps),i})))}await this.sender.setCapabilities(e),function(e,t){const i=[];return e.forEach((e=>{t.some((t=>((e,t)=>e.ssrc===t.ssrc)(e,t)))||i.push(e)})),0===i.length&&e.length===t.length}(this.previousParameters,e)||(this.previousParameters=e,this.event("onSendersChanged").raise(this,!0))}setPendingStream(e){this.pendingStream=e;const t=e.on("onStreamClientDisposing",(()=>{this.pendingStream===e&&(this.pendingStream=null,t.dispose())}))}subscribeOnQualityUpdates(e){this.sub=e.on("onStreamQualityChanged",((e,t,i,n)=>this.updateStreamQualityParams(t,i,n)))}updateStreamQualityParams(e,t,i){return i===vh.EffectQualityChangeReason.Performance&&this.notifyMaxVideoSendCapabilitiesChanged({resolution:e,fps:t}),this.sender.updateStreamQualityParams(e,t,2)}unsubscribeFromQualityEvents(){this.sub?.dispose(),this.sub=null}notifyMaxVideoSendCapabilitiesChanged(e){if(!["Video","ScreenShare"].includes(this.mediaType))return;const{width:t,height:i}=e?.resolution??this.mainStream.getResolution(),n=e?.fps??this.mainStream.getFrameRate();if(!t||!i||!n)return;const r=new Bn(t,i),s={maxFs:r.fs,maxMbps:r.fs*n,maxFps:n,maxWidth:r.width,maxHeight:r.height};this.logger.safe.info(`Capabilities for ${this.mediaType} stream: ${JSON.stringify(s)}`),this.sendVideoCapabilityManager?this.sendVideoCapabilityManager.manage(s,!e):this.event("onMaxVideoSendCapabilitiesChanged").raise(s)}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()}};sV.transitionStates={NotStarted:["Started","Disposed"],Started:["Active","Disposed"],Active:["NotStarted","Disposed"],Disposed:[]},m([Uk()],sV.prototype,"start",1),m([Uk()],sV.prototype,"activate",1),m([Uk()],sV.prototype,"updateStream",1),m([Uk()],sV.prototype,"addAdditionalStream",1),m([Uk()],sV.prototype,"updateParameters",1),m([Uk()],sV.prototype,"terminateAsync",1),m([Uk()],sV.prototype,"setHold",1),m([Uk()],sV.prototype,"updateStreamQualityParams",1);var aV=sV,oV=class{constructor(e){this.durationThreshold=e,this.signals={}}track(e,t){void 0===this.signals[e]&&(this.signals[e]={wasNotified:!1}),this.signals[e].currentTime=_n(),!!this.signals[e].currentState!=!!t&&(this.signals[e].currentState=t,this.signals[e].lastChanged=this.signals[e].currentTime,this.signals[e].wasNotified=!1)}update(e){const t=[];for(const t of Object.keys(e))void 0===this.signals[t]&&(this.signals[t]={wasNotified:!1});for(const t of Object.keys(this.signals))this.track(t,e[t]);for(const e in this.signals){const i=this.signals[e];if(void 0!==i.currentState){if(i.wasNotified)continue;i.currentTime-i.lastChanged>=this.durationThreshold&&(i.wasNotified=!0,t.push(i.currentState))}}return t}},lV=class extends Vi{constructor(e,t){super(),this.logger=e,this.timeout=-1,this.signals=new oV(t.performanceMonitor.durationThreshold??3e3),this.config={monitorQualityLimitationReasons:t.performanceMonitor?.monitorQualityLimitationReasons,monitorMaxFS:t.performanceMonitor?.monitorMaxFS,mitigationTimeout:t.performanceMonitor?.mitigation?.timeout,startupDelay:t.performanceMonitor?.startupDelay}}key(e,t){return`${e.rid}:${t}`}suspend(e){e>0&&(this.logger.safe.info(`Suspending for ${(e/1e3).toFixed(1)} seconds`),this.timeout=_n()+e)}acceptLayout(e){return e.some((e=>void 0===e.rid))?(this.logger.safe.info("Ignore layout with missing RID"),!1):!(this.caps&&Math.max(0,...e.map((e=>e.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(e){this.logger.safe.info(`Max capabilities updated: ${JSON.stringify(e)}`),this.caps&&e.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=e}updateLayout(e){if((e||this.layout)&&this.logger.safe.info(`New layout: ${JSON.stringify(e)}`),e&&this.acceptLayout(e)){if((e=e.map((e=>Object.assign({},e)))).sort(((e,t)=>e.maxFs===t.maxFs?e.maxFps===t.maxFps?e.maxBr-t.maxBr:e.maxFps-t.maxFps:e.maxFs-t.maxFs)),this.layout?.length)for(let t=0;t<e?.length;++t){const i=e[t],n=this.layout.find((e=>e.rid===i.rid));n&&n.maxFs!==i.maxFs&&(this.logger.safe.info(`Reset '${this.key(n,"FS")}'`),this.signals.track(this.key(n,"FS"),void 0))}this.layout=e,-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(e){const t={};let i=0;if(!this.layout||this.layout.length<1||e.length<this.layout.length||this.timeout>_n())return void this.signals.update(t);for(this.timeout>0&&(this.logger.safe.info("Resuming"),this.timeout=0),i=0;i<this.layout.length;++i){const n=this.layout[i],r=e.find((e=>e.rid===n.rid));if(r){const e=Math.ceil(r.frameWidth/Gi.MACROBLOCK_SIZE)*Math.ceil(r.frameHeight/Gi.MACROBLOCK_SIZE);if(this.config.monitorQualityLimitationReasons){const e=r.qualityLimitationReason;-1!==this.config.monitorQualityLimitationReasons.indexOf(`${e}`)&&(t[this.key(n,"QL")]={layout:n,type:"QL",expected:"none",actual:e})}this.config.monitorMaxFS&&e<n.maxFs&&(t[this.key(n,"FS")]={layout:n,type:"FS",expected:n.maxFs,actual:e})}}const n=this.signals.update(t).map((e=>{const t=Object.assign({},e);return t.layout=this.layout?.find((e=>e.rid===t.layout.rid))??t.layout,t}));n.length&&(this.logger.safe.info(`Raise event: ${JSON.stringify(n)}`),this.event("onVideoQualityDegraded").raise(n))}},cV=class extends Vi{constructor(e,t,i,n){super(e),this.logger=e,this.configProvider=t,this.diagnostics=i,this.videoFeatureManager=n,this.activeModalities=new Set,this.callbacks=[];const r=this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation??{};this.config={allowDisabling1080pSinglecast:r.enableFor1080pSinglecast,allowDisabling1080pSimulcast:r.enableFor1080pSimulcast,allowDisablingThreeStreamSimulcast:r.enableForThreeStreamSimulcast,allowReversals:r.enableReversals}}hasSoftwareEncodedVideoAndSharing(){return!this.videoFeatureManager.get("Video").hasClientSupport(1)&&!this.videoFeatureManager.get("ScreenShare").hasClientSupport(1)&&this.hasActiveSenders("Video","ScreenShare")}hasActiveSenders(...e){return e.every((e=>this.activeModalities.has(e)))}getAdaptationInfo(e,t){return{description:e,activeModalities:[...this.activeModalities],isTransient:t&&this.config.allowReversals}}notify(e){this.logger.safe.warn(`${e.description} activeModalities: ${e.activeModalities.join("/")} isTansient: ${e.isTransient}`),this.diagnostics.registerLocalVideoPerformanceEvent(e)}schedule(e,t,i){this.callbacks.push({mediaType:e,state:t,callback:i})}override(e,t,i){this.configProvider.config[e]=t,this.logger.safe.info(`Overwriting ${e} with ${this.configProvider.config[e]}. Reason: ${i}`)}disable1080pSoftwareEncode(e){const t=this.videoFeatureManager.get("Video");if(!e.find((e=>e.maxFs===Gi.MAX_FS_1080P)))return!1;if(!t.hasClientSupport(2))return!1;if(t.hasClientSupport(1))return!1;if(1===e.length&&!this.config.allowDisabling1080pSinglecast)return this.logger.safe.info("Will not disable 1080p for singlecast"),!1;if(e.length>1&&!this.config.allowDisabling1080pSimulcast)return this.logger.safe.info("Will not disable 1080p for simulcast"),!1;const i=this.configProvider.config.performanceFallbackMaxFsFor1080pSend,n={},r={webrtcCameraOpenFs:this.configProvider.config.webrtcCameraOpenFs,maxCameraFsViaCallConstraints:this.configProvider.config.maxCameraFsViaCallConstraints,webrtcVideoCapabilityMaxFS:this.configProvider.config.webrtcVideoCapabilityMaxFS};for(const e in r)r[e]>0&&(n[e]=Math.min(i,r[e]));const s=Object.keys(n);if(s.some((e=>r[e]!==n[e]))){s.forEach((e=>{this.override(e,n[e],"mitigating 1080p performance issues")})),this.event("onNewStreamNeeded").raise(n.webrtcCameraOpenFs);const e=this.getAdaptationInfo("Disabled software 1080p",this.hasSoftwareEncodedVideoAndSharing());return e.isTransient&&this.schedule("ScreenShare",!1,(()=>{s.forEach((e=>{this.override(e,r[e],"removing mitigation for 1080p performance issues")})),this.event("onNewStreamNeeded").raise(),this.notify(this.getAdaptationInfo("Re-enabled software 1080p",!0))})),this.notify(e),!0}return!1}disableThreeStreamSimulcast(e){const t=this.videoFeatureManager.get("Video");if(3!==e.length)return!1;if(!this.config.allowDisablingThreeStreamSimulcast)return this.logger.safe.info("Will not disable 3-stream simulcast"),!1;if(t.hasClientSupport(1))return!1;if(t.hasFullSupport(0)){const e=this.getAdaptationInfo("Disabled 3-stream simulcast",this.hasSoftwareEncodedVideoAndSharing());return t.toggleClient(0,!1),e.isTransient&&this.schedule("ScreenShare",!1,(()=>{t.toggleClient(0,!0),this.notify(this.getAdaptationInfo("Re-enabled Three stream simulcast",!0))})),this.notify(e),!0}return!1}updateSenderState(e,t){if(t===this.activeModalities.has(e))return;t?this.activeModalities.add(e):this.activeModalities.delete(e);const i=this.callbacks.filter((i=>i.mediaType===e&&i.state===t));this.callbacks=this.callbacks.filter((i=>i.mediaType!==e||i.state!==t));for(const e of i)e.callback()}mitigatePerformanceIssue(e){return!!this.disable1080pSoftwareEncode(e)||!!this.disableThreeStreamSimulcast(e)}},dV=class{constructor(e,t,i){this.callback=e,this.logger=t,this.settings=i,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()}},uV=class extends Vi{constructor(e,t,i,n){super(e),this.logger=e,this.configProvider=t,this.frameSizeLimits={},this.initialMaxFS=this.configProvider.config.webrtcCameraOpenFs,this.subs=[],this.cadence=new dV(this.commitCallConstraints.bind(this),this.logger.createChild("Cadence"),this.configProvider.config.sendVideoCapabilityManager?.constraintsCadence),this.configProvider.config.enableVideoFeatureManager&&i&&(this.features=i.get("Video"),this.subs.push(i.on("onVideoFeaturesChanged",(e=>{"Video"===e.mediaType&&this.onFeaturesChanged(e)})))),n&&this.subs.push(n.on("onNewStreamNeeded",(e=>{this.limitFrameSize("Performance",e),this.updateConstraintsAndNotify()}))),this.configProvider.config.video1080p?.software?.isEnabled&&this.limitFrameSize("Software1080P",Gi.MAX_FS_1080P),this.settings=this.configProvider.config.sendVideoCapabilityManager,this.settings.defaultFS&&(this.initialMaxFS=this.settings.defaultFS);const r=this.getCallConstraints().maxFS;r&&r!==this.initialMaxFS&&(this.logger.safe.info(`Detected initial resolution opt-in: ${this.initialMaxFS} => ${r}`),this.limitFrameSize("Opt-In",r))}getCapabilities(){if(this.appliedCapabilities)return{...this.appliedCapabilities}}applyCallConstraints(e){this.lastCauseId=e,this.cadence.trigger()}manage(e,t){t&&(this.streamConstraints={maxFPS:e.maxFps,maxFS:e.maxFs},this.features&&this.streamConstraints.maxFS>=Gi.MAX_FS_1080P&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&this.features.toggleClient(2,!0)),this.requestedCapabilities={...e},this.updateConstraintsAndNotify()}dispose(e){for(const t of this.subs)t.dispose(e);this.subs=[],this.cadence.dispose(),super.dispose()}onFeaturesChanged(e){const t=(t,i)=>{this.limitFrameSize(hB[t],e.hasClientSupport(t)?i:void 0)};t(1,this.configProvider.config.hardwareEncodedVideoMaxFS),t(3,this.configProvider.config.broadcastMode?.maxVideoFS),this.updateConstraintsAndNotify()}getCallConstraints(){const e=this.configProvider.config.outgoingVideoLimit,t={},i="number"==typeof e?e:e?.maxResolution;return i&&(t.maxFS=jn(i)),t.maxFPS="number"==typeof e?void 0:e?.maxFramerate,t}commitCallConstraints(){this.limitFrameSize("Opt-In",this.getCallConstraints().maxFS,this.lastCauseId),this.updateConstraintsAndNotify()}buildCapabilities(){const e={...this.requestedCapabilities};if(this.constraints?.maxFS<e.maxFs||this.constraints?.maxFPS<e.maxFps){e.maxFps=Ki(this.constraints.maxFPS,e.maxFps),e.maxFs=Ki(this.constraints.maxFS,e.maxFs);const t={...Hn.Send.getResolutionByFs(e.maxFs)};e.maxMbps=t.fs*e.maxFps,e.maxWidth=t.width,e.maxHeight=t.height}return e}limitFrameSize(e,t,i){this.frameSizeLimits[e]!==t&&(i?this.logger.safe.info(`[${i}] FS limit for '${e}' changed from ${this.frameSizeLimits[e]} to ${t}`):this.logger.safe.info(`FS limit for '${e}' changed from ${this.frameSizeLimits[e]} to ${t}`),this.frameSizeLimits[e]=t)}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 e=this.getCallConstraints(),t={};let i=!1;for(const e of this.settings.priorityOrder)if(this.frameSizeLimits[e]>0){i=-1!==this.settings.allowOptIn.indexOf(e),t.maxFS=this.frameSizeLimits[e],this.logger.safe.info(`Using FS ${t.maxFS} from '${e}'. Opt-In is ${i?"allowed":"not allowed"}`);break}if(void 0===t.maxFS&&(t.maxFS=this.initialMaxFS,i=this.settings.maxFS>this.initialMaxFS),t.maxFPS=e.maxFPS,this.frameSizeLimits["Opt-In"]>0){const e=this.frameSizeLimits["Opt-In"];(e<t.maxFS||i)&&(this.logger.safe.info(`Applying opt-in: ${t.maxFS} => ${e}`),t.maxFS=e)}if(this.streamConstraints&&(this.logger.safe.debug(`Applying stream constraints: ${JSON.stringify(this.streamConstraints)} to ${JSON.stringify(t)}`),t.maxFS&&(t.maxFS=Ki(t.maxFS,this.streamConstraints.maxFS)),t.maxFPS&&(t.maxFPS=Ki(t.maxFPS,this.streamConstraints.maxFPS))),t.maxFS===this.constraints?.maxFS&&t.maxFPS===this.constraints?.maxFPS||(this.logger.safe.info(`Final constraints changed from ${JSON.stringify(this.constraints)} to ${JSON.stringify(t)}`),this.constraints=t),this.constraints&&this.requestedCapabilities){if(this.appliedCapabilities){const e=this.buildCapabilities();return e.maxFs!==this.appliedCapabilities.maxFs||e.maxFps!==this.appliedCapabilities.maxFps}return!0}return!1}},hV=class extends Vi{constructor(e,t,i,n,r,s,a,o,l,c,d){super(t),this.mediaManager=e,this.logger=t,this.callDeviceManager=i,this.configProvider=n,this.sessionConfig=r,this.statisticsGatherer=s,this.diagnostics=a,this.qmDiagnostics=o,this.isMultiparty=l,this.encStreamsManager=c,this.videoFeatureManager=d,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 tk(this.logger),this.streamsProvider=new IB(this.callDeviceManager,this.configProvider,this.sessionConfig,this.serialQueue,this.logger.createChild("StreamsProvider")),this.streamProviderSubscriptions=[this.streamsProvider.on("onStreamAdded",(e=>this.onStreamUpdated(e,!1))),this.streamsProvider.on("onStreamUpdated",(e=>this.onStreamUpdated(e,!0)))],this.localVideoStreamWatcher=new aB(this.logger,this.configProvider,this.callDeviceManager),this.localVideoStreamWatcherSub=this.localVideoStreamWatcher.on("onVideoCaptureFreeze",((e,t)=>this.onVideoCaptureFreeze(e,t))),this.configProvider.config.useMediaQualityController&&(this.mediaQualityController=new KB(this.configProvider,this.logger.createChild("MQC"),this.videoFeatureManager),this.mediaQualityController.on("onLayoutsUpdated",(e=>{const t=this.mediaQualityController.getLayouts(e);return this.logger.safe.debug(`Update layouts for ${e}: ${JSON.stringify(t)}`),"Video"===e&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(t),this.updateParameters(this.lastCauseId,e,t)})),this.mediaQualityController.on("onBandwidthAllocationUpdated",(e=>{this.event("onBandwidthAllocationChanged").raise(e)}))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor&&(this.simulcastPerformanceMonitor=new lV(this.logger.createChild("SPM"),this.configProvider.config.specCompliantSimulcast),this.simulcastPerformanceMonitor.on("onVideoQualityDegraded",(e=>this.onVideoQualityDegraded(e)))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation&&(this.simulcastPerformanceAdaptationManager=new cV(this.logger.createChild("SPAM"),this.configProvider,this.diagnostics,this.videoFeatureManager),this.simulcastPerformanceAdaptationManager.on("onNewStreamNeeded",(e=>{this.configProvider.config.sendVideoCapabilityManager?.isEnabled||(this.sessionConfig.outgoingVideoMaxFS=e,this.streamsProvider.requestStreamUpdate("Video",!0))})))}dispose(){this.senders.forEach(((e,t)=>{this.event("onSendStreamChanged").raise(null,t),this.configProvider.config.disposeSendersSync?e.dispose():e.terminateAsync()})),this.senders.clear(),this.senderSubs.forEach((e=>e.forEach((e=>e.dispose())))),this.senderSubs.clear(),this.streamProviderSubscriptions.forEach((e=>e.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(e){this.logger.safe.debug(`Registering RTP sender manager ${e}`),this.mediaConnection=e}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(e,t,i,n){n?.mark("startUpdateStreams");let r=function(e,t=!0){const i={Audio:Wp(e.audio),Video:Wp(e.video),ScreenShare:Wp(e.sharing)};return t||(i.Data=Wp(e.data)),i}(e,this.configProvider.config.streamModalitiesExcludeData);const s=!!(1&t),a=!!(2&t),o=!!(4&t);o&&(r={Audio:!0,Video:!1,Data:!1,ScreenShare:!1});const l=o?Promise.resolve(r):this.streamsProvider.update(r,s);let c,d;return a||o?(delete r.Data,c=tn(r),d=s?void 0:c):(c=await l,d=c),this.logger.safe.info(`[${i}] Streams updated, modalities requested: ${JSON.stringify(r)} (flags: ${t}), result: ${JSON.stringify(c)}`),n?.markAndMeasure("startUpdateStreams","updateStreamsWithModalities"),await this.updateSenders(d,i),n?.markAndMeasure("updateStreamsWithModalities","updateSenders"),a&&(this.streamsPromise=(async()=>{const t=await l;return this.streamsPromise=void 0,await this.updateSenders(t,i),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(t,e)})()),this.applyMuteState(i,!0),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(c,e)}mergeAndSaveModalities(e,t){this.previousMediaModalities=tn(e);const i=tn(t);return qi(t,((t,n)=>{const r=sm(n);Wp(t)&&!e[r]&&(i[n]=zp(t))})),i}async activate(e){this.logger.safe.info(`[${e}] activate senders`),await Promise.all([...this.senders.values()].map((async e=>e.activate()))),this.setAndUpdateLocalTracksInfo(!1)}applyCallConstraints(e){const t=this.senders.get("Video");return t?t.applyCallConstraints(e):(this.logger.info(`[${e}] Caching call constraints until sender is created`),this.callConstraintsCauseId=e,this.applyCallConstraintsDeferred=new Kt,this.applyCallConstraintsDeferred.promise)}async applyCapabilities(e,t,i){this.logger.safe.info(`[${e}] Applying incoming ${t} FMTP: ${JSON.stringify(i)}`);const n=sm(t);this.lastCauseId=e;let r=i;return this.mediaQualityController&&(this.mediaQualityController.addReceiver(n,i),r=this.mediaQualityController.getLayouts(n)),this.simulcastPerformanceAdaptationManager?.updateSenderState(n,!0),this.updateParameters(e,n,r)}getLocalMediaSources(){const e=this.getTracksInfo(),t=[];return e.forEach((e=>{t.some((t=>t.modality===e.modality))||t.push({sourceId:this.getSourceIdForTrack(e),modality:e.modality})})),t}setMuted(e,t,i){this.muted.set(e,t),this.applyMuteState(i,!1)}async setHold(e,t){await Promise.all([...this.senders.values()].map((async i=>i.setHold(e,t))))}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.mediaQualityController?.onStatisticsChanged(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher||this.localVideoStreamWatcher.onStatisticsChanged(e)}onDiagnosticUpdated(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation&&this.mediaQualityController?.onDiagnosticUpdated(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher&&this.localVideoStreamWatcher.onDiagnosticUpdated(e)}async updateParameters(e,t,i){try{const n=this.senders.get(t);n?await n.updateParameters(i):this.logger.safe.info(`[${this.lastCauseId}] Capabilities ignored ${JSON.stringify(i)}, no ${JSON.stringify(t)} sender`),this.logger.safe.debug(`[${e}] Capabilities completed`);const r={modality:am(t),causeId:e,capabilities:i};this.statisticsGatherer.onMaxCapabilitiesApplied(r),this.qmDiagnostics.onMaxCapabilitiesApplied(r)}catch(n){const r=tt(n);this.logger.safe.error(`[${e}] Error applying capabilities ${r}`);const s={modality:am(t),causeId:e,capabilities:i,error:r};this.statisticsGatherer.onMaxCapabilitiesApplied(s),this.qmDiagnostics.onMaxCapabilitiesApplied(s)}}applyMuteState(e,t){for(const[i,n]of this.muted)this.senders.get(i)&&this.senders.get(i).setMuted(n,e,t)}setAndUpdateLocalTracksInfo(e){const t=this.getTracksInfo();this.logger.safe.debug(`Local tracks info: ${JSON.stringify(t)}`),this.mediaManager.setLocalTracksInfo(t),e&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statisticsGatherer.updateStatsWithLocalSsrcTrackInfo())}getTracksInfo(){const e=[];return this.senders.forEach((t=>e.push(t.getTrackInfo()))),e}async updateSenders(e,t=be()){const i=await this.streamsProvider.getStreams(),n=e||om(i);this.logger.safe.info(`[${t}] Updating senders with modalities: ${JSON.stringify(n)}, override: ${!!e}`),await Promise.all(en(n).map((async e=>{const i=n[e];if(i===this.previousMediaModalities[e])return;if(!i)return this.logger.safe.info(`[${t}] Removing sender for ${JSON.stringify(e)}`),void await this.removeSender(e);const r=(await this.streamsProvider.getStreams())?.[e];if(await this.createAndStartSender(r,e),this.logger.safe.info(`[${t}] Sender for ${JSON.stringify(e)} is added`),this.applyCallConstraintsDeferred&&"Video"===e){const t=this.senders.get("Video");try{await t.applyCallConstraints(this.callConstraintsCauseId),this.applyCallConstraintsDeferred.resolve()}catch(e){this.applyCallConstraintsDeferred.reject(e)}this.applyCallConstraintsDeferred=void 0,this.callConstraintsCauseId=void 0}await this.addAudioSharingStream(r),this.event("onSendStreamChanged").raise(r,e)}))),this.logger.safe.info(`[${t}] Senders updated. Enabled: ${JSON.stringify(Object.keys(n).filter((e=>n[e])))}`)}createCapabilityManager(e,t){if("Video"===e&&this.configProvider.config.sendVideoCapabilityManager?.isEnabled)return new uV(t.createChild("SVCM"),this.configProvider,this.videoFeatureManager,this.simulcastPerformanceAdaptationManager)}createAndStartSender(e,t){if(this.senders.get(t))return this.logger.safe.error(`Sender already created, modality: ${JSON.stringify(t)}`),this.senders.get(t).start();const i=this.mediaManager.getMediaEntitiesByModality(am(t))[0],n=i?.getSimulcastContext(),r=!this.configProvider.config.specCompliantSimulcast?.disableTilde&&!!n?.shouldUseSimulcast(),s="Audio"===t||!this.isMultiparty||r,a=this.logger.createChild(`Sender_${JSON.stringify(t)}:${this.senderId++}`),o=this.createCapabilityManager(t,a),l=new aV(this.mediaConnection,e||new bB(t,this.logger.createChild("tempStream")),new MediaStream,t,this.serialQueue,a,this.configProvider,s,this.encStreamsManager,n,o);this.senders.set(t,l);const c=[l.on("onSendersChanged",((e,t)=>this.onSenderStateChanged(e,t))),l.on("onNewStreamNeeded",(()=>this.streamsProvider.requestStreamUpdate(t,!0))),l.on("onMaxVideoSendCapabilitiesChanged",(e=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(t,e),"Video"===t&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateMaxCapabilities(e)}))];return this.senderSubs.set(l,c),l.start()}async removeSender(e){const t=this.senders.get(e);t&&(this.senders.delete(e),this.event("onSendStreamChanged").raise(null,e),await t.terminateAsync(),this.senderSubs.get(t).forEach((e=>e.dispose())),this.senderSubs.delete(t),this.logger.safe.info(`Removed sender with mediaType: ${JSON.stringify(e)}`)),this.mediaQualityController?.removeReceiver(e),this.simulcastPerformanceAdaptationManager?.updateSenderState(e,!1),"Video"===e&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(void 0)}getSourceIdForTrack(e){const t=e.trackId,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}onVideoCaptureFreeze(e,t){e||(t?this.qmDiagnostics.registerWebcamFreeze():this.qmDiagnostics.registerProcessedStreamFreeze()),this.event("onVideoCaptureFreeze").raise(e)}onVideoQualityDegraded(e){const t=this.mediaQualityController?.getLayouts("Video")??[];let i=!1;for(const n of e)if(this.logger.safe.warn(`rid:${n.layout.rid} ${n.type} degraded - expected: ${n.expected}, actual: ${n.actual}`),!i&&this.simulcastPerformanceAdaptationManager)switch(n.type){case"QL":"cpu"===n.actual&&(i=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(t));break;case"FS":"1"===n.layout.rid&&(i=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(t))}i&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.onMitigationApplied()}async onStreamUpdated(e,t){if(!this.senders.has(e))return void this.logger.safe.warn(`Sender with media type ${e} does not exist, do not update media stream`);let i=(await this.streamsProvider.getStreams())[e];if(i||(this.logger.safe.info(`Stream is missing for mediaType: ${e}, using fake stream...`),i=new bB(e,this.logger.createChild("NullStreamClient"))),i.isDisposed())return void this.logger.safe.info(`Stream is already disposed for mediaType: ${e}`);this.event("onSendStreamChanged").raise(i,e);const n=this.senders.get(e);await this.addAudioSharingStream(i),await n.updateStream(i),this.logger.safe.debug(`Stream updated for mediaType: ${e}, updated: ${t}`),this.setAndUpdateLocalTracksInfo(t)}onSenderStateChanged(e,t){if(this.mediaManager.updateMediaEntitiesWithActivityState(e.mediaType,e.getActiveStreamIndexes()),this.statisticsGatherer.onSendersChanged(e.mediaType,t),"Video"===e.mediaType)if(t){const e=this.getTracksInfo().filter((e=>e.modality===Gi.MODALITY.video));this.localVideoStreamWatcher.startWatching(e,this.simulcastPerformanceMonitor)}else this.localVideoStreamWatcher.stopWatching()}async addAudioSharingStream(e){"ScreenShare"===e?.mediaType&&e?.hasAudio()&&(this.logger.safe.info("Adding audio stream from sharing to audio sender"),await(this.senders.get("Audio")?.addAdditionalStream(e)))}},gV=class{constructor(e,t,i,n,r){this.recvStream=e,this.mainTrack=t,this.receiveStreamCollection=i,this.logger=n,this.settings=r,this.removeOtherTracks(t),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(e){return this.recvStream.requestSource(e)}getSourceStreamId(){return this.recvStream.getSourceStreamId()}getSubstreamIndex(){return this.recvStream.getSubstreamIndex()}removeOtherTracks(e){this.settings.onAddTrackRemoveOtherTracks&&this.stream.getTracks().forEach((t=>{t.id!==e.id&&this.stream.removeTrack(t)}))}subscribeOnStreamEvents(){const e=e=>this.logger.safe.info(`${e} track: ${this.mainTrack.id}, stream: ${this.stream.id}`);this.stream.onremovetrack=()=>{e("onremovetrack"),this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onended=()=>{e("onended"),this.settings.removeRecvStreamOnEnded&&this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onmute=()=>e("onmute"),this.mainTrack.onunmute=()=>e("onunmute")}unsubscribeFromStreamEvents(){this.stream.onremovetrack=null,this.mainTrack.onended=null,this.mainTrack.onmute=null,this.mainTrack.onunmute=null}},pV=class{constructor(e){this.startTimestamp=0,this.totalTime=0,this.lastActiveTime=0,this.id=e}},mV=class{constructor(e){this.speakersHistory=[],this.sources=[],this.configProvider=e.configProvider,this.ping=this.setupTimer()}setSources(e=[]){const t=e.map(this.getOrCreateSource.bind(this)),i=this.excludeSources(this.sources,t);t.forEach((e=>{this.isAlreadyActive(e)||this.updateSourceTimestamp(e),this.updateSourceLastActiveTime(e)})),i.forEach((e=>{this.updateTotalTime(e),this.resetStartTimestamp(e)})),this.ping||(this.ping=this.setupTimer())}setOnDominantSpeakerChanged(e){this.callback=e}dispose(){this.clearTimer(),this.sources=null,this.callback=null}excludeSources(e,t){return e.filter((e=>!t.some((t=>e.id===t.id))))}trigger(){if(!this.hasAnyoneSpoken())return void this.clearTimer();const e=this.sources.map(this.updateTotalTime).sort(((e,t)=>t.totalTime-e.totalTime||t.lastActiveTime-e.lastActiveTime)).map((e=>e.id)).slice(0,this.configProvider.config.ovcMaxCount);e.length&&!an(this.speakersHistory,e)&&(this.speakersHistory=e,this.callback&&this.callback(this.speakersHistory,"client")),this.sources.map(this.resetTotalTime).filter(this.isAlreadyActive).forEach(this.updateSourceTimestamp)}isAlreadyActive(e){return!!e.startTimestamp}setupTimer(){return window.setInterval(this.trigger.bind(this),this.configProvider.config.activeSpeaker.timeToPromote)}clearTimer(){this.ping&&(clearInterval(this.ping),this.ping=null)}getOrCreateSource(e){if(this.isExist(e))return this.sourceById(e);{const t=new pV(e);return this.sources.push(t),t}}isExist(e){return this.sources.some((t=>e===t.id))}hasAnyoneSpoken(){return this.sources.some((e=>0!==e.startTimestamp||0!==e.totalTime))}sourceById(e){return this.sources.find((t=>e===t.id))}updateSourceTimestamp(e){e.startTimestamp=Date.now()}updateSourceLastActiveTime(e){e.lastActiveTime=Date.now()}updateTotalTime(e){return e.startTimestamp&&(e.totalTime+=Date.now()-e.startTimestamp),e}resetStartTimestamp(e){return e.startTimestamp=0,e}resetTotalTime(e){return e.totalTime=0,e}},fV=class extends Vi{constructor(e,t){super(),this.configProvider=e,this.logger=t,this.bandwidthEstimationAvailable=!1,this.smoothingWindow=[],this.totalSamples=0,this.isStarted=!1,this.maxCountStatic=this.configProvider.config.ovcMaxCount,this.previousParticipantsCount=0,this.isMcpSrAvailable=!1;const i=window.navigator;this.updateStaticConstraint(i.hardwareConcurrency,this.configProvider.config.ovcAvailableConcurrencyForBiggerGrid,4),this.updateStaticConstraint(i.deviceMemory,this.configProvider.config.ovcMemoryForBiggerGrid,4),this.throttler=new vV(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(e){this.bandwidthConstrainedOvc=this.getOVCEstimate(e),this.payload={bandwidth:e,reason:0},this.throttler.setValue(this.getOvcValue(),0)}updateParticipantCount(e){if(!this.configProvider||e===this.previousParticipantsCount)return;const t=this.configProvider.config.ovcXLParticipantsCount;e>t&&this.previousParticipantsCount<=t&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountXL),e<=t&&this.previousParticipantsCount>t&&(this.configProvider.config.multiStreamSupported&&this.isMcpSrAvailable?this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream:this.maxCountStatic=this.configProvider.config.ovcMaxCount),this.previousParticipantsCount=e,this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2)}setPerfConstrainedValue(e){this.perfConstrainedOvc=e,this.logger.safe.info(`Setting perfConstrainedOvc to ${e}`),this.payload&&this.getOvcValue()===e&&(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(e){this.bandwidthEstimationAvailable||(this.bandwidthEstimationAvailable=this.isStarted&&e>0&&(this.totalSamples++>=this.configProvider.config.ovcIgnoreFirstSamples||Math.floor(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver>=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount));let t=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount;return this.bandwidthEstimationAvailable&&(t=Math.floor(this.sampleSmoothed(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver)),t}getOvcValue(){return Math.max(1,Math.min(this.bandwidthConstrainedOvc??this.maxCountStatic,this.perfConstrainedOvc??this.maxCountStatic,this.maxCountStatic))}sampleSmoothed(e){if(this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples?this.smoothingWindow.shift():this.smoothingWindow.length===this.configProvider.config.ovcSlidingWindowSamples-1&&(this.smoothingWindow=this.smoothingWindow.map((()=>e))),this.smoothingWindow.push(e),this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples){const e=this.smoothingWindow.slice().sort(),t=Yi(e);return e[e.length-1]-(e[e.length-1]-t*(1-this.configProvider.config.ovcSlidingWindowPercentile))}return e}updateStaticConstraint(e,t,i){e&&e<t&&(this.maxCountStatic=Math.min(this.maxCountStatic,i))}},vV=class extends Vi{constructor(e,t,i){super(e),this.logger=e,this.throttleDownCooldown=t,this.throttleUpCooldown=i,this.wasRampingUp=!0,this.lastUpdateTime=0}get value(){return this.lastValue}setValue(e,t){if(e===this.lastValue)return;const i=e>this.lastValue,n=void 0!==this.lastValue&&i!==this.wasRampingUp?i?this.throttleUpCooldown:this.throttleDownCooldown:-1,r=Date.now();r-this.lastUpdateTime<n&&(2!==t||i)||(void 0!==this.lastValue&&(this.lastUpdateTime=r,this.wasRampingUp=i),this.logger.safe.info(`optimal video receivers count updated ${this.lastValue} -> ${e}, reason: ${t}`),this.lastValue=e,this.raiseChanged())}},SV=class e{constructor(e,t=30){this.logger=e,this.maxEventNum=t,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(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{e&&Sn(this.report,{timeStamp:Date.now(),value:e},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 Cn(this.report)}getCurrentCpuSample(){return new Promise(((t,i)=>{this.started&&t(Cn(this.report)),this.isSupported()||i("Not supported"),this.port=window.chrome.runtime.connect(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{this.stop(),e||i("Not supported"),t({timeStamp:Date.now(),value:e})}))}))}clearStats(){this.report=[]}};SV.extensionID="nkeimhogjdpnpccoofpliimaahmaaome",SV.extensionName="processCpu";var yV=SV,CV=class{constructor(e){this.logger=e,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((e=>{e.forEach((t=>{"cpu"===t.source&&this.currentCpuState!==t.state&&(this.logger.safe.debug(`CPU pressure state changed: ${JSON.stringify(e)}`),this.currentCpuState=t.state)}))}),{sampleRate:1})}catch(e){throw this.logger.safe.error(`Error while creating pressure observer: ${e}`),e}this.started=!0,this.cpuObserver?.observe("cpu")}}stop(){this.started=!1,this.cpuObserver?.disconnect()}},TV=class extends Vi{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,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&&CV.isSupported()&&(this.cpuPressureObserver=new CV(this.logger)),this.configProvider.config.diagnostics.performanceMonitoring.useCpuSample&&(this.cpuMetricCollector=new yV(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=KD.getStrategy(this.configProvider),this.started=!0,this.cpuPressureObserver?.start(),this.subs.push(this.statsGatherer.on("onDiagnosticUpdated",(e=>this.processStats(e)))))}stop(){this.logger.safe.debug("Stopping RemoteVideoPerformanceCalculator"),this.started=!1,this.subs.forEach((e=>{e.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(e){try{if(this.paused)return;if(!e.video?.recv?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Calculating remote video performance"),e.video?.recv?.forEach((async t=>{const i=t.renderer?.msi;if(!this.perfTrackerMap.has(i)){const e={id:t.mediaEntity?.remoteTrackId,decodeTimeTracker:new XM(this.trackInterval),macroblockLossTracker:new XM(this.trackInterval),macroblockMaxLossTracker:0,freezeDurationPercent:0,frameHeight:0,frameWidth:0,rendererFps:new XM(this.trackInterval),incomingFps:new XM(this.trackInterval),framesReceived:0,framesDecoded:0,decoder:"",msi:i};this.perfTrackerMap.set(i,e)}const n=this.perfTrackerMap.get(i);if(t.inboundRTP.totalDecodeTime&&t.inboundRTP.framesDecoded){const e=mn(t.inboundRTP.totalDecodeTime/t.inboundRTP.framesDecoded*1e3,2);n.decodeTimeTracker.captureSample(e)}const r=t.extensions?.macroblockRateStats?.macroblockRateDecoderLossPercent;n.macroblockLossTracker.captureSample(r),n.macroblockMaxLossTracker=t.extensions?.macroblockRateStats?.macroblockRateMaxDecoderLossPercent,t.extensions?.duration&&(n.freezeDurationPercent=t.extensions?.totalFreezeDuration/t.extensions?.duration*100),n.frameHeight=t.inboundRTP.frameHeight||0,n.frameWidth=t.inboundRTP.frameWidth||0,void 0!==t.extensions?.frameRateDecoded&&void 0!==t.inboundRTP.framesPerSecond&&t.extensions?.frameRateDecoded<=this.rendererFpsCap&&t.inboundRTP.framesPerSecond<=this.rendererFpsCap&&(n.rendererFps.captureSample(t.extensions?.frameRateDecoded),n.incomingFps.captureSample(t.inboundRTP.framesPerSecond)),t.inboundRTP.framesReceived&&t.inboundRTP.framesDecoded&&(n.framesReceived=t.inboundRTP.framesReceived,n.framesDecoded=t.inboundRTP.framesDecoded),n.decoder=t.inboundRTP.decoderImplementation,n.rendererFps.isReportComplete()&&n.incomingFps.isReportComplete()&&n.decodeTimeTracker.isReportComplete()&&(this.paused=!0,await this.checkQuality(n,e.perfCounters,e.video?.recv?.length),this.paused=!1)}))}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}async checkQuality(e,t,i){if(!i)return;const n=[];let r;try{r=await(this.cpuMetricCollector?.getCurrentCpuSample())}catch{this.logger.safe.debug("CPU sampling is not supported")}const s={ts:Date.now(),trackId:e.id,decodeTime:e.decodeTimeTracker.getReport(),macroblockLossPercent:e.macroblockLossTracker.getReport(),macroblockMaxLossPercent:e.macroblockMaxLossTracker,freezeDurationPercent:e.freezeDurationPercent,perfCounters:t,cpuUsage:r,rendererFps:e.rendererFps.getReport(),incomingFps:e.incomingFps.getReport(),framesDecoded:e.framesDecoded,framesReceived:e.framesReceived,msi:e.msi,frameHeight:e.frameHeight,decoder:e.decoder};n.push(s);const a=this.calculatorStrategy.checkQuality(e);if(0===a){if(this.logger.safe.debug(`Bad perf detected for msi ${e.msi}: ${JSON.stringify(n)}`),this.configProvider.config.diagnostics.performanceMonitoring.usePerfConstrainedOvc&&!Hn.Recv.getNextLowerResolution(e.frameWidth,e.frameHeight)){const e=Math.max(i-1,1);return this.logger.info(`Min resolution reached, decreasing OVC to: ${e}`),this.diagnostics.registerVideoPerformanceEvent(n,1,e),this.event("calculatorStateChanged").raise(2,{ovc:e}),void this.perfTrackerMap.clear()}this.diagnostics.registerVideoPerformanceEvent(n,1),this.event("calculatorStateChanged").raise(1,{msi:e.msi})}2===a&&(this.diagnostics.registerVideoPerformanceEvent(n,0),this.logger.safe.debug(`Good perf detected for msi ${e.msi}: ${JSON.stringify(n)}`),this.event("calculatorStateChanged").raise(0,{msi:e.msi})),this.perfTrackerMap.delete(e.msi)}},EV=class extends Vi{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,this.calculators=new Map,this.subs=[]}on(e,t){switch(e){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(e),handler:t}})}addCalculator(e){let t=this.calculators.get(e);if(!t){switch(e){case 0:if(!this.configProvider.config.diagnostics.performanceMonitoring.enableRemoteVideoCalculator)return;t=new TV(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("RemoteVideoPerformanceCalculator"));break;case 2:if(!this.configProvider.config.enableOptimalVideoCount)return;t=new fV(this.configProvider,this.logger.createChild("OptimalVideoCountCalculator"));break;case 1:throw new Error("Not implemented")}this.subs.push(t.on("calculatorStateChanged",((t,i)=>{this.handleChanged(e,t,i)}))),this.calculators.set(e,t)}}startCalculator(e){this.logger.safe.debug(`adding calculator with id ${e}`);const t=this.calculators.get(e);t&&t.start()}stopCalculator(e){this.logger.safe.debug(`stopping calculator with id ${e}`);const t=this.calculators.get(e);t&&t.stop()}processNotification(e,t){switch(e){case"BandwidthNotification":this.calculators.get(2)?.processEstimatedBandwidth(t.bw);break;case"ParticipantCountChanged":this.calculators.get(2)?.updateParticipantCount(t.count);break;case"McpSourceRequestsAvailable":this.calculators.get(2)?.mcpSourceRequestsAvailable();break;default:this.logger.safe.info(`Notification message handler not found for type: ${e}`)}}dispose(){super.dispose(),this.calculators.forEach((e=>{e.dispose()})),this.subs.forEach((e=>{e.dispose()}))}handleChanged(e,t,i){switch(this.logger.info(`calculatorStateChanged ${t}: calculatorType ${e} ${JSON.stringify(i)}`),e){case 0:if(2===t){this.calculators.get(2)?.setPerfConstrainedValue(i?.ovc);break}this.configProvider.config.diagnostics.performanceMonitoring.enableLowerResolution&&this.event("onIncomingVideoQualityChanged").raise(t,i?.msi);break;case 2:this.event("onOptimalVideoCountChanged").raise(i?.ovc,i?.ovcPayload)}}},bV=Z,_V=class{constructor(e){this.configProvider=e,this.outboundNetworkQuality="Good",this.inboundNetworkQuality="Good",this.jitterAccumulator=new $M(this.configProvider.config.webrtcJitterWindowSize),this.healedRatioAccumulator=new $M(this.configProvider.config.webrtcHealedRatioWindowSize),this.jitterStateProcessor=new GF(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),this.lossRateStateProcessor=new GF(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime)}processReport(e){e.audio?.recv?.length&&(this.inboundNetworkQuality=this.processInboundSample((0,bV.last)(e.audio.recv))),e.audio?.send?.length&&(this.outboundNetworkQuality=this.processOutboundSample((0,bV.last)(e.audio.send)))}getInboundNetworkQuality(){return this.inboundNetworkQuality}getOutboundNetworkQuality(){return this.outboundNetworkQuality}processInboundSample(e){const t=this.inboundNetworkQuality,{totalSamplesReceived:i}=e.inboundRTP,{healedRatio:n}=e.extensions??{};null!=n&&this.healedRatioAccumulator.add(n);const r=(0,bV.mean)(this.healedRatioAccumulator.items);return!i||i<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality?t:r&&this.healedRatioAccumulator.isFull?this.determineInboundQualityLevel(r):t}determineInboundQualityLevel(e){const t=this.inboundNetworkQuality,i=this.configProvider.config.webrtcStatNetworkDetectionHysteresis,n=this.configProvider.config.webrtcStatNetworkDetectionBadLevel,r=this.configProvider.config.webrtcStatNetworkDetectionGoodLevel;return e<r-i/2?"Good":e<r+i/2?"Good"===t?"Good":"Poor":e<n-i/2?"Poor":e<n+i/2?"Bad"===t?"Bad":"Poor":"Bad"}processOutboundSample(e){const t=this.outboundNetworkQuality,{packetsSent:i,timestamp:n}=e.outboundRTP,{jitter:r}=e.remoteInboundRTP??{},{lossRate:s}=e.extensions??{};if(!i||i<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return t;null!=r&&this.jitterAccumulator.add(r);const a=(0,bV.mean)(this.jitterAccumulator.items),o=this.jitterAccumulator.isFull?this.jitterStateProcessor.onSample(a,n):"Good",l=s?this.lossRateStateProcessor.onSample(s,n):"Good";return"Good"===o&&"Good"===l?"Good":"Bad"}},IV=Z,wV=class{constructor(e){this.configProvider=e,this.speechWindow=new $M(e.config.webrtcSpeakingWhileMutedDetectionWindow)}processReport(e){if(!e.audio?.send?.length)return!1;const t=e.audio.send[0],{rawInputVolume:i,callIsMuted:n}=t.extensions??{},{audioLevel:r}=t.mediaSource??{},{useAudioAnalyzer:s,webrtcSpeakingWhileMutedDetectionLevel:a}=this.configProvider.config;if(!n)return this.speechWindow.clear(),!1;const o=s?i:r;return null!=o&&this.speechWindow.add(o),!!this.speechWindow.isFull&&(0,IV.mean)(this.speechWindow.items)>a}},AV=class{constructor(e){this.context=e,this.cname=sn()}toLocal(e,t,i){return this.modify({sdpSource:0,sdpType:i},e,t)}toOffer(e,t,i){return this.modify({sdpSource:1,sdpType:"offer"},e,t,i)}toAnswer(e,t,i){return this.modify({sdpSource:1,sdpType:"answer"},e,t,i)}toRemote(e,t,i,n,r=!1){return this.modify({sdpSource:2,sdpType:n,isOrWasProvisional:r},e,t,i)}modify(e,t,i,n){const r=new nN(this.context,i,n,this.cname).build(e),s=nn(t);return r.modify(s),s}},PV=class{get sdp(){return this.originalDescription.sdp}set sdp(e){this.originalDescription=new Mp.window.RTCSessionDescription({sdp:e,type:this.originalDescription.type})}get type(){return this.originalDescription.type}set type(e){this.originalDescription=new Mp.window.RTCSessionDescription({sdp:this.originalDescription.sdp,type:e})}constructor(e){this.originalDescription=new Mp.window.RTCSessionDescription(e)}toJSON(){return this.originalDescription.toJSON()}},RV=class{constructor(e,t,i,n,r,s,a,o,l,c,d){this.logger=e,this.configProvider=t,this.diagnostics=i,this.reinvitelessContext=n,this.mediaManager=r,this.audioCodecManager=s,this.ufdManager=a,this.sessionContext=o,this.qualityManager=l,this.streamSendersManager=c,this.callbacks=d,this.negotiationQueue=new tk(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=DU({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.mediaContentTypeInternal=un("webrtcMediaContentType",this.sessionContext.config,this.configProvider.config),this.allowedMediaContentTypeInternal=un("webrtcAllowedMediaContentType",this.sessionContext.config,this.configProvider.config).concat(),this.useNGC1webrtcContentType=un("useNGC1webrtcContentType",this.sessionContext.config,this.configProvider.config),this.negotiationCompletedDefer=new Kt,this.iceCandidatesDeferred=new Kt,this.iceCandidateReceivedInternal=!1,this.initialNegotiationCompleted=!1,this.terminated=!1,this.sessionDescription=wL.build({sdpTransform:new AV(this.sessionContext),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:{unifiedPlanEnabled:!0,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}),this.negotiationEmulator=new zU(this.logger.createChild("negotiationEmulator"),PV,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(e){this.isRollbackSupported=e}set iceCandidateReceived(e){this.iceCandidateReceivedInternal=e}get mediaContentType(){return this.useNGC1webrtcContentType?Gi.CONTENT_TYPE.SDP_NGC:this.mediaContentTypeInternal}setInternals(e,t,i){this.logger.safe.debug(`Setting internals tm: ${!!e} tsp: ${!!t} dc: ${!!i}`),this.transceiverManager=e,this.transportStateProvider=t,this.dataChannel=i}terminate(e){this.logger.safe.info(`[${e}] terminating`),this.terminated=!0,this.canTriggerRenegotiation=!1,this.negotiatedModalitiesInternal={},this.resetCandidateGathering(e),this.negotiationCompletedDefer.reject("webRtcSession cleanup"),this.negotiationQueue.dispose()}pauseNegotiations(e=be()){const t=new Kt;return this.negotiationCompletedDefer.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}async configureModalities(e,t,i){return this.configureModalitiesPromise=(async()=>{if(await this.configureModalitiesPromise,!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const n=tn(e),r=tn(this.negotiatedModalities);this.configProvider.config.alwaysNegotiateDataChannel&&(delete n.data,delete r.data);const s=!this.configuredModalities||!em(n,r);this.logger.safe.info(`[${t}] configureModalities ${tt(this.configuredModalities)} -> ${tt(e)} (${s?`update from ${tt(this.negotiatedModalities)}`:"fulfilled"})`),this.configuredModalities=e,s&&!this.updateSendStreamsReinviteless(t,i)&&(this.configProvider.config.removeSendersOnConfigureModalities&&!Yp(this.configuredModalities)&&await this.streamSendersManager.update(e,1,t),this.triggerRenegotiation(!1,t,i))})(),this.configureModalitiesPromise.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${tt(e)}`)})),this.configureModalitiesPromise}async completeNegotiation(e){this.mediaManager.commit();let t=Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,this.negotiatedModalities)&&!this.triggerRenegotiationFlag;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${t} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`);let i=this.negotiatedModalities;if(this.streamSendersManager.pendingStreamsPromise){this.logger.safe.info(`[${e}] Waiting for stream acquisitions to complete...`);const n=await this.streamSendersManager.pendingStreamsPromise;this.streamSendersManager.clearStreamsPromise(),this.logger.safe.info(`[${e}] Stream acquisitions completed: ${tt(n)}`),Xp(this.configProvider,n,this.negotiatingModalities,this.negotiatedModalities)||(this.logger.safe.warn(`[${e}] Some streams were not acquired successfully, considering the negotiation as incomplete`),i=n,t=!1)}return t||this.triggerRenegotiation(!1,e),this.initialNegotiationCompleted=!0,this.negotiationCompletedDefer.resolve(),{isComplete:t,activeModalities:i,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal}}async rejectNegotiation(e,t,i=!1){let n;this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${tt(e)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.qualityManager.clearPendingCapabilities();const r=nm(this.negotiatedModalities,this.negotiatingModalities);this.logger.safe.debug(`[${t}] configured modalities for rollback: ${JSON.stringify(r)}`),this.transceiverManager?.syncTransceivers(r),this.sessionContext.getSmallCallTelemetry()?.setEventType("rejectNegotiation"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const s=Yp(r);Yp(this.negotiatedModalities)!==s&&await this.streamSendersManager.setHold(s,t),s?this.logger.safe.info(`[${t}] Hold is configured. Not updating streams`):await this.streamSendersManager.update(r,0,t);const a=this.transportStateProvider?.signalingState;if("have-local-offer"===a){n={},this.logger.safe.info(`[${t}] rolling back local description`);try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRollback){n.type="LocalRN",this.logger.safe.info(`[${t}] rolling back using local renegotiation`);const e=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(e,!0),this.logger.safe.info(`[${t}] rolling back using local complete`)}else this.logger.safe.info(`[${t}] rolling back using rollback`),n.type="Rollback",await this.callbacks.setLocalDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error: ${tt(e)}`),n.error=e}}else if("have-remote-offer"===a){n={};try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRemoteRollback){n.type="RemoteRN",this.logger.safe.info(`[${t}] applying answer for remote renegotiation`);const e=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(e,!0,"remote")}else this.logger.safe.info(`[${t}] rolling back using rollback on remote description`),n.type="Rollback",await this.callbacks.setRemoteDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error: ${tt(e)}`),n.error=e}}else this.callbacks.hasPC()&&this.logger.safe.error(`[${t}] cannot rollback local description in current state: ${this.transportStateProvider.signalingState}`);return this.canTriggerRenegotiation=!0,this.negotiationCompletedDefer.reject("negotiation rejected"),i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:r,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal,rollback:n}}triggerRenegotiation(e,t=be(),i){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired(t,i)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}configureCrypto(e,t){let i=!1;const n=gm(this.configProvider,t);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.diagnostics.offeredSrtp=e,i=!e.dtls||e.sdes&&n}else i=n;return i&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1})),this.diagnostics.negotiatedSrtp={dtls:!i,sdes:!!i},i?0:1}createOffer(e,t){const i=this.negotiationQueue.add((()=>this.createOfferAsync(e,t)),e);return this.resetNegotiationQueue(e),i}processOffer(e,t){const i=this.negotiationQueue.add((()=>this.processOfferAsync(e,t)),t);return this.resetNegotiationQueue(t),i}async createAnswer(e,t){if((this.sessionContext.config.isPstnCall?!this.configProvider.config.createProvisionalAnswer.enabledPstn:!this.configProvider.config.createProvisionalAnswer.enabled)&&e)return this.logger.safe.info("createAnswer(): Ignoring provisional answer"),{blob:"",contentType:this.mediaContentType};const i=e?"pranswer":"answer",n=e?"createProvisionalAnswerAsync":"createAnswerAsync",r=this.diagnostics.getTimerTracker(n,{first:!0});if(r.mark("start"),this.logger.safe.info(`[${t}] create [${i}] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),!this.configuredModalities)throw new Error("no configured modalities to create answer for");let s=this.negotiatingModalities=Qp(this.offeredModalities,this.configuredModalities);await this.callbacks.assurePC(t,r.clone("assurePeerConnectionAsync"));const a=this.transportStateProvider.isWaitingAcceptProvisional;if(this.transportStateProvider.isWaitingAcceptProvisional=e,r.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${t}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),!this.offeredDescription.isCodecSwitchSupported())try{const e=(await this.capabilityGatherer.getCapabilities(Gi.MEDIA_TYPE.audio)).codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(e)}catch(e){this.logger.safe.error(`[${t}] failed to set primary codec based on audio capability ${tt(e)}`)}r.markAndMeasure("assurePeerConnectionAsync","handleCodecSwitchUnsupported"),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.offeredDescription.setModalities(s),await this.detectSendProfileSupport();const o=this.offeredDescription.toRemote(e||a);this.configProvider.config.createProvisionalAnswer.streamsBeforeSetFullRD&&!e&&a&&["have-remote-offer","stable"].includes(this.transportStateProvider.signalingState)&&!this.initialNegotiationCompleted&&(this.logger.safe.info(`[${t}] create [${i}] provisional was applied, requesting streams and activating senders before set remote description is finished`),await this.updateStreamSenders(r,t,e,s)),this.logger.unsafe.info(`[${t}] create [${i}] set remote description', 'negotiated:`,s,"sdp:",o),await this.callbacks.setRemoteDescription({sdp:o,type:"offer"}),r.markAndMeasure("handleCodecSwitchUnsupported","setRemoteDescription"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data),await this.updateStreamSenders(r,t,e,s),r.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),r.markAndMeasure("setRemoteDescription","assureStreamsAndDataChannel"),this.callbacks.onTransportInitialized();const l=this.configProvider.config.createProvisionalAnswer.setProperAnswerType?await this.callbacks.createAnswer({type:i}):await this.callbacks.createAnswer();r.markAndMeasure("assureStreamsAndDataChannel","createAnswer"),this.logger.unsafe.info(`[${t}] create [${i}] answer from peer connection type: ${l.type}, sdp:`,l.sdp);const c=this.sessionDescription.createLocalAnswer(l.sdp);this.hasIceCandidates(c)||this.resetCandidateGathering(t),this.callbacks.startWaitingForStreamStart(s),this.setupIceGatheringTimeout(t);const d=c.toLocal();this.logger.unsafe.info(`[${t}] create [${i}] set local description sdp:`,d),await this.callbacks.setLocalDescription({sdp:d,type:this.configProvider.config.createProvisionalAnswer.setProperAnswerType?i:"answer"}),r.markAndMeasure("createAnswer","sLD"),await this.iceCandidatesDeferred.promise,r.markAndMeasure("sLD","candidates");const u=this.sessionDescription.createLocalAnswer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(u),u.updateModalities(s),this.checkIceCandidates(u),e&&this.configProvider.config.createProvisionalAnswer.forceRecvonly&&(this.logger.safe.info(`[${t}] create [${i}] munge returned local sdp to recvonly modalities`),u.forceRecvonly());const h=u.toAnswer();this.audioCodecManager.decoder?.setRecvPayloads(u.getPayloadsForMedia(Gi.MEDIA_TYPE.audio)),this.checkAudioCodecNegotiated(t),e?this.logger.safe.debug(`[${t}] create [${i}] skip stream senders manager activation`):(this.logger.safe.debug(`[${t}] create [${i}] activating stream senders manager`),await this.streamSendersManager.activate(t)),r.markAndMeasure("candidates","streamSendersManagerActivate"),e?this.logger.safe.debug(`[${t}] create [${i}] skip updating sources and capabilities`):(this.logger.safe.debug(`[${t}] create [${i}] updating sources and capabilities`),this.callbacks.updateLocalMediaSources(),this.applyReceiveCapabilities(t)),s=u.getModalities(),this.reinvitelessContext.enabled&&(s=nm(this.negotiatingModalities,s)),Xp(this.configProvider,this.configuredModalities,this.negotiatingModalities,s)||this.triggerRenegotiation(!0,t),this.negotiatedModalities=s,this.diagnostics.bweType=u.getBweType(),this.logger.unsafe.info(`[${t}] CREATE ANSWER`,"sdp:",h);const g={blob:h,contentType:this.mediaContentType};return this.configProvider.countryCode&&(g.clientLocation=this.configProvider.countryCode),this.reinvitelessContext.enabled&&(g.mediaDescriptions=this.getMediaDescriptions(s)),this.callbacks.setBWSeed(g),r.markAndMeasure("start",n),g}async detectSendProfileSupport(){if(this.configProvider.config.preferredH264VideoSendProfile||this.configProvider.config.preferredH264SharingSendProfile){let e=this.capabilityGatherer;this.configProvider.config.learnCodecSendCapabilitiesFromSenderApi&&(e=DU({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0));const t=await e.getCapabilities("video"),i=this.mediaManager.getMediaEntities().filter((e=>{const t=e.getModality();return t===Gi.MEDIA_TYPE.video||t===Gi.MEDIA_TYPE.sharing})).filter((e=>e.isEnabled()));for(const e of t.codecs)if(e.sdpFmtpLine&&e.mimeType.toLocaleLowerCase().includes("h264")){const t=e.sdpFmtpLine.match(/profile-level-id=([a-fA-F0-9]{6})/);2===t?.length&&i.forEach((e=>e.addSupportedSendProfile("H264",t[1])))}}}async updateStreamSenders(e,t,i,n){this.transceiverManager.syncTransceivers(n),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)}));const r=Yp(this.negotiatingModalities);if(Yp(this.negotiatedModalities)!==r&&(e?.mark("startConfigureHold"),await this.streamSendersManager.setHold(r,t),e?.markAndMeasure("startConfigureHold","configureHold")),r)this.logger.safe.info(`[${t}] Hold is configured. Not updating streams`);else{let r=this.configProvider.config.negotiationParallelStreamAcquisitionCreateAnswer&&!this.initialNegotiationCompleted?2:0;i&&(r=4),await this.streamSendersManager.update(n,r,t),e?.markAndMeasure("configureHold","updateStreams")}}configureBroadcastScenario(e,t){const i=this.configProvider.config.broadcastMode;this.diagnostics.meetingScenario=e.meetingScenario,(i?.prioritizeLayoutOnServer||i?.prioritizeLayoutOnClient||i?.maxSessionBandwidthKbps)&&e.meetingScenario&&i.townHallScenarioNames?.length&&-1!==i.townHallScenarioNames.map((e=>e.toLowerCase())).indexOf(e.meetingScenario.toLowerCase())&&(this.sessionContext.config.isTownHall=!0,this.diagnostics.isTownHall=!0,i?.maxSessionBandwidthKbps&&this.configProvider.overrideMaxSessionBandwidth(i.maxSessionBandwidthKbps)&&(this.logger.safe.info(`Adjusting maxSessionBandwidth for TownHall: ${this.configProvider.mediaConfig.maxBandwidthInKbps}`),this.triggerRenegotiation(!0,t)))}async processAnswer(e,t,i,n=!1){try{const r=e.blob;this.logger.unsafe.debug(i?`[${t}] PROCESS PRANSWER`:`[${t}] PROCESS ANSWER`,"sdp:",r);const s=i?"pranswer":"answer";if(i&&(!function(e,t=!1){const i=!e.configProvider.config.acceptProvisionalAnswerFromPstnOnly||t;return e.config.isPstnCall?e.configProvider.config.acceptProvisionalAnswerPstn&&i:e.configProvider.config.acceptProvisionalAnswer}(this.sessionContext,n)||"have-local-offer"!==this.transportStateProvider.signalingState))return void this.logger.safe.info(`[${t}] process [${s}] ignored`);this.configureBroadcastScenario(e,t);const a=this.diagnostics.getTimerTracker(i?"processProvisionalAnswerAsync":"processAnswerAsync",{first:!0});a.mark("start");const o=this.sessionDescription.createRemoteAnswer(r);let l=qp(o.getModalities());this.reinvitelessContext.enabled&&(l=nm(this.offeredModalities,l)),o.setModalities(l),await this.detectSendProfileSupport();const c=o.toRemote();if(i||(this.useNGC1webrtcContentType||(this.mediaContentType=e.contentType),-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType),Yp(l)||(await this.streamSendersManager.update(l,1,t),a.markAndMeasure("start","streamSendersManagerUpdate"),Wp(this.offeredModalities.data)&&!l.data&&this.dataChannel?.disable()),this.negotiatedModalities=l,this.callbacks.updateLocalMediaSources(),this.diagnostics.bweType=o.getBweType()),this.callbacks.onTransportInitialized(),this.logger.unsafe.info(`[${t}] process [${s}] set remote description`,"negotiated:",l,"sdp:",c),a.mark("startSetRemoteDescription"),await this.callbacks.setRemoteDescription({sdp:c,type:s}),a.markAndMeasure("startSetRemoteDescription","setRemoteDescription"),i)return;await this.streamSendersManager.activate(t),a.markAndMeasure("setRemoteDescription","streamSendersManagerActivate"),this.applyReceiveCapabilities(t),this.checkAudioCodecNegotiated(t),this.transceiverManager.syncTransceivers(l),a.markAndMeasure("start","processAnswerAsync")}catch(e){if(i)return void this.logger.safe.warn(`Error thrown during pranswer generation, ignoring: ${tt(e)}`);throw e}}async createOfferAsync(e,t){const i=this.diagnostics.getTimerTracker("createOfferAsync",{first:!0});if(i.mark("start"),this.logger.safe.info(`[${e}] 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(e,i.clone("assurePeerConnectionAsync")),i.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${e}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),Yp(this.negotiatingModalities)&&!Xi(this.negotiatedModalities)&&Object.keys(this.negotiatingModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.negotiatingModalities[e]})),this.transceiverManager?.assureTransceivers(this.negotiatingModalities),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const n=Yp(this.negotiatingModalities);let r;Yp(this.negotiatedModalities)!==n&&(i?.mark("startConfigureHold"),await this.streamSendersManager.setHold(n,e),i?.markAndMeasure("startConfigureHold","configureHold")),n?(this.logger.safe.info(`[${e}] Hold is configured. Not updating streams`),r=this.negotiatingModalities):(r=await this.streamSendersManager.update(this.negotiatingModalities,this.configProvider.config.negotiationParallelStreamAcquisitionCreateOffer&&!this.initialNegotiationCompleted?2:0,e),i?.markAndMeasure("configureHold","updateStreams"),this.dataChannel&&this.negotiatingModalities.data&&(r.data=this.negotiatingModalities.data)),i.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),this.offeredModalities=r,!mm(this.sessionContext)&&this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[Gi.MODALITY.data]&&this.sessionContext.config?.isConference&&(this.offeredModalities[Gi.MODALITY.data]=Gi.MEDIA_STATE.inactive),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)}`);const s=await this.callbacks.createOffer();i.markAndMeasure("assureStreamsAndDataChannel","createOffer"),this.logger.unsafe.info(`[${e}] create [offer] offer from peer connection, sdp: ${s.sdp}`);const a=this.sessionDescription.createLocalOffer(s.sdp);this.hasIceCandidates(a)||this.resetCandidateGathering(e),this.callbacks.startWaitingForStreamStart(r),this.setupIceGatheringTimeout(e);const o=a.toLocal();this.logger.unsafe.info(`[${e}] create [offer] set local description`,"sdp:",o),await this.callbacks.setLocalDescription({sdp:o,type:"offer"}),i.markAndMeasure("createOffer","sLD"),await this.iceCandidatesDeferred.promise,i.markAndMeasure("sLD","candidates");const l=this.sessionDescription.createLocalOffer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(l),l.updateModalities(this.offeredModalities),this.checkIceCandidates(l);const c=l.toOffer();this.logger.unsafe.info(`[${e}] CREATE OFFER`,"sdp:",c);const d={blob:c,contentType:this.mediaContentType};""===this.configProvider.mediaConfig.webrtcRequiredFeatures||this.sessionContext.config.isConference||(d.requiredFeatures=this.configProvider.mediaConfig.webrtcRequiredFeatures),this.audioCodecManager.decoder?.setRecvPayloads(l.getPayloadsForMedia(Gi.MEDIA_TYPE.audio)),this.configProvider.countryCode&&(d.clientLocation=this.configProvider.countryCode),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)}));const u=a.isIceRestart();return this.logger.safe.info(`[${e}] ICE restart: ${u}`),this.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&u&&!this.sessionContext.config.isConference&&a.getSrtpInfo().sdes&&(d.newOffer=!0),this.reinvitelessContext.enabled&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),d.mediaDescriptions=this.getMediaDescriptions(this.offeredModalities)),t&&(d.negotiationTag=t),this.callbacks.setBWSeed(d),i.markAndMeasure("start","createOfferAsync"),d}async processOfferAsync(e,t){const i=this.diagnostics.getTimerTracker("processOfferAsync",{first:!0});i.mark("start"),this.mediaManager.backup();const n=e.blob;if(this.logger.unsafe.info(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&!this.useNGC1webrtcContentType&&(on(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),this.configureBroadcastScenario(e,t),this.offerOriginator&&this.offerOriginator!==e.originator&&this.configProvider.config.rejectIncompatibleOriginator)throw{detail:"mediaContent.originator is different on renegotiation",type:Gi.MEDIA_ERROR.incompatibleOriginator};if(this.offerOriginator=e.originator,e.requiredFeatures){const t=this.configProvider.mediaConfig.webrtcRejectedFeatures.split(",");ln(e.requiredFeatures.split(","),t)}if(this.initiatorInternal=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.configProvider.config.multiStreamSupported){const e=function(e){const t=e.match(/a=x-multi-stream:(\d+)/);if(t)return parseInt(t[1])}(n),i=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;this.configProvider.mediaConfig.multiStreamChannelsOffered=e,e<i&&(this.logger.safe.info(`Received ${e} multi stream channels, ${i} channels supported`),this.triggerRenegotiation(!0,t))}this.canTriggerRenegotiation=!1,this.offeredModalities=qp(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 r=this.configProvider.config.removeUnsupportedVideoModality?this.offeredModalities:tn(this.offeredModalities);if(Wp(this.offeredModalities.video)||Kp(this.offeredModalities.video)||Wp(this.offeredModalities.sharing)||Kp(this.offeredModalities.sharing)){const n=this.offeredDescription.getVideoCodecs();try{i.mark("startGetCapabilities");const e=await this.capabilityGatherer.getCapabilities("video");i.markAndMeasure("startGetCapabilities","getCapabilities"),e.codecs.some((e=>n.some((t=>e.mimeType===t&&this.configProvider.config.primaryVideoCodecs.includes(t)))))||(this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`),this.disabledModalities.video=r.video,this.disabledModalities.sharing=r.sharing,delete r.video,delete r.sharing)}catch(e){this.logger.safe.error(`[${t}] failed to get video capability ${tt(e)}`)}}return(!mm(this.sessionContext)&&(Wp(this.offeredModalities.data)||Kp(this.offeredModalities.data))||"Failed"===this.dataChannel?.state)&&(this.logger.safe.info(`[${t}] Supressing data modality as data channel is not possible`),r=tn(r),delete r.data),i.markAndMeasure("start","processOfferAsync"),this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(r)}`),r}async startMediaDescriptionsUpdate(e,t){this.dataChannel?.updateDataModalityState(this.reinvitelessRequestedModalities?.data);const i=Yp(this.negotiatedModalities),n=Yp(this.reinvitelessRequestedModalities);return i!==n&&await this.streamSendersManager.setHold(n,e),n?this.reinvitelessAppliedModalities=this.reinvitelessRequestedModalities:(this.reinvitelessAppliedModalities=await this.streamSendersManager.update(this.reinvitelessRequestedModalities,0,e),this.dataChannel&&this.reinvitelessRequestedModalities.data&&(this.reinvitelessAppliedModalities.data=this.reinvitelessRequestedModalities.data)),this.callbacks.updateLocalMediaSources(),await this.streamSendersManager.activate(e),this.getMediaDescriptions(this.reinvitelessAppliedModalities,t)}async completeMediaDescriptionsUpdate(e){this.logger.safe.info(`[${e}] complete media descriptions update`),this.negotiatedModalities=this.reinvitelessAppliedModalities;const t=this.reinvitelessAppliedModalities,i=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:t,requestedModalities:i}}async rejectMediaDescriptionsUpdate(e,t=!1){this.logger.safe.info(`[${e}] reject media descriptions update`),t&&(this.logger.safe.info(`[${e}] trigger renegotiation after failed media descriptions update`),this.triggerRenegotiation(!1,e));const i=await this.streamSendersManager.update(this.negotiatedModalities,1,e),n=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:i,requestedModalities:n}}getMediaDescriptions(e,t){if(Yp(e))return{};const i=[];for(const t of this.mediaManager.getMediaEntities()){if(!t.getExtension("reinviteless"))continue;const n=e[t.getModality()],r={mid:t.getMid(),direction:!t.getLocalTrackId()&&Wp(n)?zp(n):n};i.push(r)}return{descriptions:i,negotiationTag:t}}updateSendStreamsReinviteless(e,t){if(Xi(this.negotiatedModalities)||Yp(this.negotiatedModalities)||Yp(this.configuredModalities))return!1;this.reinvitelessRequestedModalities=tn(this.negotiatedModalities);for(const[e,t]of Object.entries(this.configuredModalities)){const i=this.mediaManager.getMediaEntitiesByModality(e)[0];i?.getExtension("reinviteless")&&(this.reinvitelessRequestedModalities[e]=t)}return!an(this.reinvitelessRequestedModalities,this.negotiatedModalities)&&(this.callbacks.onUpdateMediaDescriptionsRequired(e,t),an(this.reinvitelessRequestedModalities,this.configuredModalities))}checkAudioCodecNegotiated(e){const t=this.audioCodecManager.negotiationCompleted();if(this.audioCodecManager.decoder?.getUnmixedAudioProvider()?.configured){const i=t?"Good":"Bad";this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable",i,"Audio",!0,e)}}fixLocalDescription(e){this.configProvider.config.insertFakeCandidateIfNeeded&&(this.iceCandidateReceivedInternal||!this.iceCandidateReceivedInternal&&this.transportStateProvider.isIceConnected)&&(this.diagnostics.fakeCandidate=e.insertFakeCandidateIfNeeded()),e.fixDataModality()}applyReceiveCapabilities(e){const t=this.mediaManager.getMediaEntities().map((e=>e.getRemoteRecvCapabilities()));this.sessionContext.config?.isConference?this.qualityManager.setPendingCapabilities():this.qualityManager.setMaxCapabilities(t,e)}resetNegotiationQueue(e){this.negotiationCompletedDefer.reject("promise expired"),this.setNegotiationPromise(new Kt,e)}setNegotiationPromise(e,t=be()){this.terminated||(this.negotiationCompletedDefer=e,this.negotiationQueue.add(this.negotiationCompletedDefer,t))}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Gi.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&this.transportStateProvider.isIceConnected)return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.sessionContext.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=window.setTimeout((()=>{this.iceCandidatesTimer=void 0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Kt,this.iceCandidateReceivedInternal=!1}set offeredModalities(e){this.offeredModalitiesInternal=e,this.diagnostics.offeredModalities=e}set negotiatedModalities(e){this.logger.safe.info(`setNegotiatedModalities ${JSON.stringify(e)}`),this.negotiatedModalitiesInternal=e,this.diagnostics.negotiatedModalities=e}set configuredModalities(e){this.configuredModalitiesInternal=e}set mediaContentType(e){this.mediaContentTypeInternal=e}},MV=class{constructor(e){this.mcpConfig=e,this.data={sourceRequestsSignaling:{},sourceRequestsMCP:{},fallbackMCPMessagesCounter:0,sourceRequestsResponses:{},errors:[]}}setRecord(e,t,i){const n={sequenceNumber:t,timestamp:Date.now(),sourceId:i?.sourceId,fmtp:i?.fmtParams};e.records??(e.records=[]),Sn(e.records,n,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperation(e,t){var i;(i=this.data.sourceRequestsSignaling)[e]??(i[e]={counter:0}),this.data.sourceRequestsSignaling[e].counter++}recordMCPOperation(e,t,i){var n;(n=this.data.sourceRequestsMCP)[e]??(n[e]={counter:0}),this.data.sourceRequestsMCP[e].counter++,this.mcpConfig.verboseTelemetry&&this.setRecord(this.data.sourceRequestsMCP[e],t,i)}recordError(e,t){const i=[Date.now(),t,e];Sn(this.data.errors,i,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperationDuration(e,t){const i=this.data.sourceRequestsSignaling[e]?.records?.find((e=>e.sequenceNumber===t));i&&(i.duration=Date.now()-i.timestamp)}recordMCPMessageFallback(e,t){if(this.data.fallbackMCPMessagesCounter++,this.mcpConfig.verboseTelemetry){const i=this.data.sourceRequestsMCP[t]?.records?.find((t=>t.sequenceNumber===e));i&&(i.fallback=!0,i.fallbackTimestamp=Date.now())}}recordSrResultReceived(e,t,i){var n;if(this.mcpConfig.verboseTelemetry){const n=this.data.sourceRequestsMCP[i]?.records?.find((e=>e.sequenceNumber===t));n&&(n.duration=Date.now()-n.timestamp,n.result=e)}(n=this.data.sourceRequestsResponses)[e]??(n[e]=0),this.data.sourceRequestsResponses[e]++}getObjectRef(){return this.data}},DV=class{constructor(e){this.mcpConfig=e,this.storage={createTime:Date.now(),startedCount:0,stoppedCount:0,clientCapabilities:[],events:[]},this.sourceRequestSenderDiagnostics=new MV(this.mcpConfig)}get getSourceRequestSenderDiagnostics(){return this.sourceRequestSenderDiagnostics}logStarted(){if(this.storage.startedCount++,this.storage.startedCount>5)return;const e={startedTs:kV(this.storage.createTime),mpCapabilities:{},sentMessages:{},recvMessages:{},sentFailed:0,recvFailed:0,cachedDshReceived:!1};this.storage.events.push(e),this.lastEventConnecting=!0}logStopped(){this.storage.stoppedCount++;const e=this.getCurrentDCSessionEvent();e&&(e.stoppedTs=kV(this.storage.createTime)),this.lastEventConnecting=!1}logSentMsg(e){var t,i;const n=this.getCurrentDCSessionEvent();n&&((t=n.sentMessages)[i=e.type]??(t[i]=0),n.sentMessages[e.type]++)}logReceivedMsg(e){var t,i;this.lastEventConnecting=!1;const n=this.getCurrentDCSessionEvent();n&&((t=n.recvMessages)[i=e.type]??(t[i]=0),n.recvMessages[e.type]++,"dsh"!==e.type||n.handshakeDuration||(n.cachedDshReceived=!0))}logHandshakeStarted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeStartedTs=Date.now()),this.storage.clientCapabilities=e}logHandshakeCompleted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeDuration||(t.handshakeDuration=kV(t.handshakeStartedTs)),t.mpCapabilities.send=e.send_capabilities,t.mpCapabilities.recv=e.receive_capabilities)}logHandshakeFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeDuration=kV(t.handshakeStartedTs),t.handshakeFailedWithError=e)}logSentFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.sentFailed++,t.lastSentFailed={ts:kV(this.storage.createTime),error:e})}logRecvFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.recvFailed++,t.lastRecvFailed={ts:kV(this.storage.createTime),error:e})}logTimeout(){if(this.storage.startedCount>=5&&!this.lastEventConnecting)return;const e={timeoutTs:Date.now()},t=this.getCurrentDCSessionEvent();t&&(e.handshakeStartedTs=t.handshakeStartedTs),this.lastEventConnecting&&this.storage.events.pop(),this.storage.events.push(e),this.lastEventConnecting=!1}getReport(){const e=this.sourceRequestSenderDiagnostics.getObjectRef();return this.storage.sourceRequestsReport=e,this.storage}getCurrentDCSessionEvent(){const e=this.storage.events[this.storage.events.length-1];return this.storage.startedCount<=5&&void 0!==e?.startedTs?e:null}};function kV(e){return Date.now()-e}var OV=class extends gt{constructor(e,t,i){super(),this.dataChannel=e,this.logger=t,this.mcpConfig=i,this.mcpState="Created",this.handshakeTimeout=null,this.telemetryLogger=new DV(this.mcpConfig),this.mcpSupportedFeatures={sourceRequestsEnabled:!1,sourceRequestsResponseEnabled:!1,dominantSpeakerHistoryEnabled:this.mcpConfig?.enableDominantSpeakerHistory,senderSideBandwidthEstimationEnabled:!1},this.subscribeToDataChannel()}getTelemetryLogger(){return this.telemetryLogger}mcpFeaturesSupported(e){return this.mcpSupportedFeatures[e]}switchMcpFeature(e,t){this.logger.warn(`Switching ${e} to ${t}`),this.mcpSupportedFeatures[e]=t}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(e){return this.sendMsgInternal(e)}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",((e,t,i)=>this.processIncomingData(e,i)))}onDataChannelStateChanged(){switch(this.dataChannel.state){case"Connected":this.onDCStarted();break;case"Closed":case"Destroyed":this.onDCStopped()}}async startHandshake(){try{this.mcpState="Handshaking";const e=[];this.mcpConfig.enableDominantSpeakerHistory&&e.push("dsh"),this.mcpConfig.enableBweNotifications&&e.push("bwe"),this.mcpConfig.enableSourceRequests&&e.push("sr"),this.mcpConfig.enableSendBandwidthNotificationsEnabled&&e.push("ssbwe"),this.telemetryLogger.logHandshakeStarted(e),this.logger.info(`Send syn, client capabilities: ${JSON.stringify(e)}`),await this.sendMsgInternal({type:"syn",client_capabilities:e}),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(e){this.logger.error(`Handshake failed with: ${tt(e)}`),this.telemetryLogger.logHandshakeFailed(tt(e))}}async sendMsgInternal(e){const t=Array.isArray(e)?e:[e],i=(new TextEncoder).encode(JSON.stringify(t)),n=new Uint8Array(1+i.length);n[0]=1,n.set(i,1);try{await this.dataChannel.sendMessage(18,void 0,n,[4294967292]);for(const e of t)this.telemetryLogger.logSentMsg(e)}catch(e){throw this.logger.error(`Send failed: ${tt(e)}`),this.telemetryLogger.logSentFailed(tt(e)),e}}processIncomingData(e,t){if(18!==e)return;if(1!==t[0]){const e=`Unsupported header version ${t[0]}`;return this.logger.info(e),void this.telemetryLogger.logRecvFailed(e)}const i=new DataView(t.buffer,1);let n;try{const e=(new TextDecoder).decode(i);n=JSON.parse(e)}catch(e){return this.logger.error(`Failed to parse received data, error ${tt(e)}`),void this.telemetryLogger.logRecvFailed(tt(e))}for(const e of n)switch(this.telemetryLogger.logReceivedMsg(e),e.type){case"syn":break;case"ack":this.processAckMsg(e);break;case"bwe":this.processBweMsg(e);break;case"dsh":this.processDshMsg(e);break;case"sr_res":this.processSrResMsg(e);break;default:{const t=`Unsupported msg type ${e.type}`;this.logger.error(t),this.telemetryLogger.logRecvFailed(t)}}}processDshMsg(e){this.mcpConfig.enableDominantSpeakerHistory&&(this.logger.debug(`DSH received: ${JSON.stringify(e)}`),this.event("mpDshChanged").raise(e.history))}processSrResMsg(e){this.mcpConfig.enableSourceRequests&&this.event("mpSrResReceived").raise(e.sequenceNumber,e.result),this.mcpState="Active"}processBweMsg(e){this.mcpConfig.enableBweNotifications&&this.event("mpSendBandwidthChanged").raise(e.bw)}processAckMsg(e){this.telemetryLogger.logHandshakeCompleted(e),this.logger.info(`Ack received: ${JSON.stringify(e)}`),this.switchMcpFeature("dominantSpeakerHistoryEnabled",!(!this.mcpConfig.enableDominantSpeakerHistory||!e.send_capabilities?.includes("dsh"))),this.switchMcpFeature("sourceRequestsEnabled",!(!this.mcpConfig.enableSourceRequests||!e.receive_capabilities?.includes("sr"))),this.switchMcpFeature("sourceRequestsResponseEnabled",!(!this.mcpConfig.enableSourceRequests||!e.send_capabilities?.includes("sr_res"))),this.switchMcpFeature("senderSideBandwidthEstimationEnabled",!(!this.mcpConfig.enableSendBandwidthNotificationsEnabled||!e.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"}},NV=class{constructor(e,t,i){this.mediaControlPlane=e,this.sendSignalingMessage=t,this.logger=i,this.pendingSourceRequests=new Map,this.mediaControlPlane&&(this.diagnostics=this.mediaControlPlane.getTelemetryLogger().getSourceRequestSenderDiagnostics,this.mediaControlPlane.on("mpSrResReceived",((e,t)=>this.onMsgReceived(e,t))))}mapToSignalingOperation(e){switch(e){case"ApplyChannelParametersSourceRequest":case"ApplyChannelParametersVideoCapabilities":return 0;case"ControlVideoStreaming":return 1;default:return this.logger.error("Unknown send operation"),null}}send(e,t,i,n){switch(e){case"ApplyChannelParametersSourceRequest":return this.sendMcpMessage(e,t,i,n);case"ApplyChannelParametersVideoCapabilities":case"ControlVideoStreaming":return this.sendSignalingMessage?(this.diagnostics?.recordSignalingOperation(e),this.sendSignalingMessage(this.mapToSignalingOperation(e),t)):Promise.reject(new Error("no signaling session"));default:return this.logger.warn(`Unable to send message reason: Operation unknown ${e}`),Promise.reject(new Error("Unable to send message"))}}setResendingMechanism(e,t,i,n){const r=window.setTimeout((()=>{this.logger.warn(`Timed out message ${e}, sending message through signaling`),this.resendPendingMessageThroughSignaling(e,n)}),this.mediaControlPlane?.getConfig().sourceRequestsMessagesTimeout);this.pendingSourceRequests.set(e,{sequenceNumber:e,timeoutId:r,deferred:t,message:i,operation:n})}isAllowedToSendMcpMessage(){if(!this.mediaControlPlane)return!1;const e=this.mediaControlPlane.getMcpState(),t=this.mediaControlPlane.getConfig();return"Created"!==e&&("Handshaking"===e?t.sendBeforeAck&&t.enableSourceRequests:"Active"===e&&this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled"))}isResendingMechanismRequired(e){return this.mediaControlPlane.getConfig().setResendingMechanism&&"ApplyChannelParametersSourceRequest"===e}async sendMcpMessage(e,t,i,n){if(this.isAllowedToSendMcpMessage()){const r=new Kt;this.isResendingMechanismRequired(e)&&this.setResendingMechanism(i,r,n,e);try{return this.diagnostics.recordMCPOperation(e,i,t.controlVideoStreaming?.controlInfo),await this.mediaControlPlane.sendMsg(t),this.logger.info(`Sending ${t.type} by MCP sequenceNumber:${i}`),this.isResendingMechanismRequired(e)?r.promise:Promise.resolve()}catch(t){const n=tt(t);this.diagnostics.recordError(n,i),this.logger.error(`sendMsgInternal failed with error: ${n}`),this.isResendingMechanismRequired(e)&&this.clearPendingSourceRequestTimeout(i)}}if(!this.sendSignalingMessage)throw new Error("no signaling session");return this.diagnostics?.recordSignalingOperation(e),this.logger.info(`Sending SR by signaling sequenceNumber:${i}`),this.sendSignalingMessage(this.mapToSignalingOperation(e),n)}async resendPendingMessageThroughSignaling(e,t){this.diagnostics.recordMCPMessageFallback(e,t);const i=this.pendingSourceRequests.get(e);try{this.diagnostics.recordSignalingOperation(i.operation),await this.sendSignalingMessage(this.mapToSignalingOperation(i.operation),i.message),i.deferred.resolve()}catch{this.logger.warn(`Failed to resend source request via signaling ${e}`),i.deferred.reject(new Error("Sending source request failed via signaling"))}finally{this.clearPendingSourceRequestTimeout(e)}}clearPendingSourceRequestTimeout(e){const t=this.pendingSourceRequests.get(e);t&&(this.pendingSourceRequests.delete(e),clearTimeout(t.timeoutId))}onMsgReceived(e,t){this.logger.info(`Received SR result: ${t} for sequenceNumber: ${e}`);const i=this.pendingSourceRequests.get(e);if(i){switch(this.diagnostics.recordSrResultReceived(t,e,i.operation),t){case"ok":case"duplicate":case"out_of_order":i.deferred.resolve();break;default:i.deferred.reject(`SequenceNumber: ${e} failed with ${t}!`)}this.clearPendingSourceRequestTimeout(e)}else this.logger.warn(`No pending SR found for sequenceNumber: ${e}`)}},LV=0,xV=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc2-"+ ++LV),this.videoFeatureManager=new pB(this.logger.createChild("VFM")),this.ufdManager=this.context.getUfdManager(),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.capabilityGatherer=DU({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.reinvitelessContext=function(e,t){const i=(t?e?.maxReinvitelessMediaForVideoMultiparty:e?.maxReinvitelessMediaForVideo1on1)||0,n=(t?e?.maxReinvitelessMediaForVBSSMultiparty:e?.maxReinvitelessMediaForVBSS1on1)||0;return{enabled:i>0||n>0,maxStreamsForModality:{video:i,sharing:n}}}(this.context.config.reinvitelessConfig,this.multiParty),this.iceHostCandidateOnly=this.multiParty&&un("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new tN({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:this.multiParty,reinviteltessContext:this.reinvitelessContext}),this.receiveStreamCollection=new Yx({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.diagnostics=this.context.diagnostics,this.qmDiagnostics=this.diagnostics.newQualityManagerDiagnostics(),this.statsGatherer=new vU(this.logger.createChild("stats"),this.configProvider,this.diagnostics,this.mediaManager,this.multiParty),this.networkQualityDiagnostics=new _V(this.configProvider),this.speechDetectionDiagnostics=new wV(this.configProvider),this.qualityManager=new XU(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,customBwEstimationEnabled:this.configProvider.config.webrtcEnabledCustomBwEstimationForVideo},this,this.statsGatherer,this.qmDiagnostics,this.configProvider),this.activeSpeakerManager=new Jx(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=cB({logger:this.logger,configProvider:this.configProvider}),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new cO(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e},this.diagnostics.newSubscriptionManagerDiagnostics()),this.remoteVideoResolutionManager=new eB(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.statsGatherer,this.diagnostics),this.remoteVideoManager=new sB(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.statsGatherer,this.diagnostics,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.encStreamsManager=new zm(this.configProvider,this.context.maContext.getEncodedStreamsWorkerProvider?.(),this.logger.createChild("EncodedStreamsManager")),this.streamSendersManager=new hV(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 Mg(this.logger.createChild("rawIncomingAudioStream")),this.useNullAudioStream=!1,this.audioCodecManager=new hf(this.encStreamsManager,this.logger,this.configProvider),this.perfMonitorSubs=[],this.performanceMonitor=new EV(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("PerformanceMonitor")),this.negotiation=new RV(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:(e,t)=>this.callbacks.onNegotiationRequired?.(e,t),onUpdateMediaDescriptionsRequired:(e,t)=>this.callbacks.onUpdateMediaDescriptionsRequired?.(e,t),updateLocalMediaSources:this.updateLocalMediaSources.bind(this),assurePC:this.assurePeerConnectionAsync.bind(this),hasPC:()=>!!this.peerConnection,createOffer:e=>this.peerConnection.createOffer(e),createAnswer:e=>this.peerConnection.createAnswer(e),setLocalDescription:e=>this.peerConnection.setLocalDescription(e),getLocalDescription:()=>this.peerConnection.localDescription,setRemoteDescription:e=>this.peerConnection.setRemoteDescription(e),setBWSeed:this.setBWSeed.bind(this),onTransportInitialized:()=>this.callbacks.onTransportInitialized(),startWaitingForStreamStart:e=>{this.statsGatherer.startWaitingForStreamStart(e)},getRollbackModifier:e=>new Xx(this.peerConnection,this.configProvider,e)}),this.streamConfigurationHandler=new uB(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",(e=>this.processStatsReport(e))),this.statsGatherer.on("onStatisticsChanged",(e=>this.processLegacyStats(e))),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.negotiation.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),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 mV({configProvider:this.configProvider})),this.perfMonitorSubs.push(this.performanceMonitor.on("onIncomingVideoQualityChanged",((e,t)=>{this.onIncomingVideoQualityChanged(e,t)}))),this.configProvider.config.webrtcVideoScaling&&(this.perfMonitorSubs.push(this.performanceMonitor.on("onOptimalVideoCountChanged",((e,t)=>{this.onOptimalVideoCountChanged(e,t)}))),this.onOptimalVideoCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)),this.configProvider.config.setBWSeed&&(this.bandwidthCache=new hD(this.configProvider)),this.diagnostics.reinvitelessContext=this.reinvitelessContext,this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&this.videoFeatureManager.manageFeatureSupport((()=>{if(this.detectVideoFeatures(),this.configProvider.config.enableDevtoolsAPI){const e=window?.webMA;e?.initVideoFeatures&&e.initVideoFeatures(this.videoFeatureManager)}}))}initializeMediaControlPlane(e){const t=this.dataChannel.getDataChannel(e);t?(this.mediaControlPlane=new OV(t,this.logger.createChild("MediaControlPlane"),this.configProvider.config.mediaControlPlaneConfig),this.mediaControlPlane.on("mpSendBandwidthChanged",(e=>{this.performanceMonitor.processNotification("BandwidthNotification",{bw:e}),this.bandwidthCache?.saveSeed(e),this.statsGatherer.addReportedReceiveBandwidth(e),this.diagnostics.addReportedReceiveBandwidth(e)})),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",(e=>{this.activeSpeakerManager.onDominantSpeakerHistoryChanged(e,"server")}))):this.logger.safe.error(`[${e}] Unable to initialize MediaControlPlane due to datachannel creation failure`)}getMediaControlPlaneInstance(){return this.mediaControlPlane}getAcceptedTypes(){return this.negotiation.allowedMediaContentType}clone(t,i){const n=tn(this.context);n.config=tn(this.context.config),n.config.webrtcMediaContentType=this.negotiation.mediaContentType,n.config.webrtcAllowedMediaContentType=this.negotiation.allowedMediaContentType,n.configProvider=i,n.diagnostics=this.context.diagnostics?.newNativeSession(!1),t?(n.config.isConference=!0,n.config.isPstnCall=!1):(n.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(n.config.webrtcIceGatheringTimeoutIncreased=!0));const r=new e(n,this.callId,this.callback);return this.useNullAudioStream&&r.useNullAudioStreamClient(),this.relayManagerProvider&&(r.relayManagerProvider=this.relayManagerProvider),r.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,r}async setCallConstraints(e,t){const i=this.configProvider.setCallConstraints(e);if(this.logger.safe.info(`[${t}] Setting call constraints ${JSON.stringify(i)}, enableDynamicCallConstraints: ${this.configProvider.config.enableDynamicCallConstraints}`),this.configProvider.config.enableDynamicCallConstraints)try{await this.streamSendersManager.applyCallConstraints(t),this.configProvider.addCallConstraintsTelemetryEvent(i,"applied")}catch(e){throw this.logger.safe.error(`Error while applying constraints: ${e}`),e}else this.configProvider.addCallConstraintsTelemetryEvent(i,"applied");return i}setInternals(e,t){this.logger.safe.info(`[${t}] Setting internals from previous session`),this.diagnostics.commitNativeSession(),e.subscriptionManager&&(this.subscriptionManager?.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setDiagnostics(this.diagnostics.newSubscriptionManagerDiagnostics()),this.subscriptionManager.setStreamProvider({getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e}),this.subscriptionManager.setLogger(this.logger.createChild("subs")),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager?.moveRenderers(this.remoteVideoManager),e.rawIncomingAudioStreamManager&&this.rawIncomingAudioStreamManager.updateHandlers(e.rawIncomingAudioStreamManager.handlerMap),this.audioRenderer.getStream()&&this.rawIncomingAudioStreamManager.streamChanged(this.audioRenderer.getStream())}setSubsForDeviceManager(){const e=this.getVideoDeviceManager();this.configProvider.config.enablePlayVideoOnStreamUnmuteWorkaround&&this.deviceManagerSubs.push(e.on("onAudioStreamMuted",(t=>{t||(this.remoteVideoManager.playVideo(),e.getLocalVideoRenderers().forEach((e=>e.playVideo())))})))}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.statsGatherer.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.statsGatherer.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,s)=>this.onSubscriptionChanged(e,t,i,n,r,s))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.statsGatherer.addSubscriptionEvent(e,t,i,n,r)))]}onSubscriptionChanged(e,t,i,n,r,s){t===Gi.MODALITY.video&&(2===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount()),3===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount())),this.statsGatherer.addSubscriptionEvent(e,t,i,n,null,r,s)}setSubsForStreamManagerEvents(){this.streamSendersManager.on("onSendStreamChanged",((e,t)=>{this.statsGatherer.updateSendStream(e,t),e?.hasAudio()&&this.diagnostics.setAudioSendStream(e,t),this.diagnostics.setPresentationAudioOnScreenSharing(e,t)})),this.streamSendersManager.on("onVideoCaptureFreeze",(e=>{this.transportStateProvider.isConnected&&!this.transportStateProvider.isWaitingAcceptProvisional&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"Bad":"Good","Video")})),this.streamSendersManager.on("onMaxVideoSendCapabilitiesChanged",((e,t)=>this.onMaxVideoSendCapabilitiesChanged(e,t))),this.streamSendersManager.on("onBandwidthAllocationChanged",(e=>this.onSendBandwidthChanged(e)))}move(e,t){this.logger.safe.info(`[${t}] moving to new session`),e.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager,rawIncomingAudioStreamManager:this.rawIncomingAudioStreamManager},t),e.muteHold(this.isMuteHold,t),this.isAudioInputMuted?e.muteInputAsync(t):e.unmuteInputAsync(t),this.isAudioOutputMuted?e.muteOutputAsync(t):e.unmuteOutputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.rawIncomingAudioStreamManager=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMute for ${e} with mute state ${t}`),this.streamSendersManager.setMuted(e,t,i),this.processLegacyStats(this.statsGatherer.getLastStatistics())}getConfiguredModalities(){return this.negotiation.configuredModalities}getDisabledModalities(){return this.negotiation.disabledModalities}createAudioElement(e){this.configProvider.config.devices.setSinkImmediately&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.assureAudioElement(e)}useNullAudioStreamClient(){this.useNullAudioStream=!0,this.streamSendersManager.useNullAudioStreamClient()}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){if(this.statsGatherer&&!this.statsGatherer.isDisposed){if(this.audioCodecManager){const e=this.audioCodecManager.getSessionEvents();this.statsGatherer.sessionInfo.setAudioCodecEvents(e),this.diagnostics.audioCodecEvents=e}this.statisticsReport=this.statisticsReport.then((()=>this.statsGatherer.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))}return this.statisticsReport}getLastKnownStats(e){return this.statsGatherer.getReport(!1,e)}muteHold(e,t){this.logger.safe.info(`[${t}] set muteHold state ${e}`),this.isMuteHold=e;const i=[Gi.MODALITY.audio,Gi.MODALITY.video,Gi.MODALITY.sharing].filter((e=>Wp(this.negotiation.negotiatedModalities[e])&&(e!==Gi.MODALITY.audio||!this.isAudioInputMuted)));for(const n of i)this.setMute(sm(n),e,t)}async muteInputAsync(e){this.isAudioInputMuted=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.isAudioInputMuted=!1,this.setMute("Audio",!1,e)}async muteOutputAsync(e){return this.isAudioOutputMuted=!0,this.audioCodecManager.decoder?.disableStreamsMixer(!0),this.audioRenderer?.setMuted(!0,e)}async unmuteOutputAsync(e){return this.isAudioOutputMuted=!1,this.audioCodecManager.decoder?.disableStreamsMixer(!1),this.audioRenderer?.setMuted(!1,e)}async getSpeakerVolume(e){return this.audioRenderer?.getSpeakerVolume(e)||0}async setSpeakerVolume(e,t){return this.audioRenderer?.setSpeakerVolume(e,t)}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}onDeviceEvent(e){this.statsGatherer.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&this.audioRenderer?.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId())}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.statsGatherer.setTerminated(),this.diagnostics.terminate(),this.perfMonitorSubs.forEach((e=>e?.dispose())),this.performanceMonitor.dispose(),this.terminated=!0,this.negotiation.terminate(e),await(this.audioCodecManager.decoder?.storeApiRecording()),this.rawIncomingAudioStreamManager?.dispose(),this.remoteVideoManager.dispose(),this.dataChannel&&(this.dataChannel.dispose(),this.dataChannel=null),this.logger.safe.info(`[${e}] 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((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.deviceManagerSubs.forEach((e=>e.dispose())),this.callDeviceManagerSub?.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated();try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${tt(t)}`)}finally{this.statsGatherer.dispose()}}getIncomingRawAudioStream(e){this.logger.info("IRawStream for incoming audio stream requested");const t=this.audioRenderer.getStream();return this.rawIncomingAudioStreamManager.createIRawStreamClient(t,e)}getUnmixedAudioProvider(){return this.audioCodecManager.decoder?.getUnmixedAudioProvider()}configureSpatialAudio(e,t){this.configProvider.mediaConfig.spatialAudioEnabled=e,this.audioCodecManager.configureSpatialAudio(e,t)||this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable","Bad","Audio",!0,t)}setParticipantSpatialAudioPositions(e,t){if(!this.audioCodecManager?.decoder||!this.getUnmixedAudioProvider()?.configured)throw this.logger.safe.error(`[${t}] setParticipantSpatialAudioPositions is called while MUCH audio decoder is not created or not enabled`),"setParticipantSpatialAudioPositions not allowed";this.audioCodecManager.decoder?.setParticipantSpatialAudioPositions(e)}processNotification(e,t){"McpSourceRequestsAvailable"===e&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),"DominantSpeakerInfo"===e&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(t.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===e&&this.streamConfigurationHandler.handleMessage(t),this.performanceMonitor.processNotification(e,t)}processStatsReport(e){try{if(this.remoteVideoManager.processStatsReport(e),this.configProvider.config.diagnostics.features.useNewNetworkUFD){this.networkQualityDiagnostics.processReport(e);const t=this.networkQualityDiagnostics.getInboundNetworkQuality();this.ufdManager.signalEvent("NetworkRecvQuality",t);const i=this.networkQualityDiagnostics.getOutboundNetworkQuality();this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":i)}this.ufdManager.signalEvent("DeviceSpeakWhileMuted",this.speechDetectionDiagnostics.processReport(e)?"Bad":"Good"),this.streamSendersManager.onDiagnosticUpdated(e);for(const t of this.getVideoDeviceManager().getLocalVideoRenderers())t.onDiagnosticUpdated(e)}catch(e){this.logger.error("Failed to processes diagnostics update: "+e)}}processLegacyStats(e){e&&(this.remoteVideoManager.processLegacyStats(e),this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.configProvider.config.diagnostics.features.useNewNetworkUFD||(this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel})),this.streamSendersManager.onStatisticsChanged(e))}assurePeerConnectionAsync(e,t){return this.peerConnectionPromise??(this.peerConnectionPromise=this.getPeerConnectionPromise(e,t)),this.peerConnectionPromise}async getPeerConnectionPromise(e,t){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info(`[${e}] fetching relay details from RelayManager...`);const i={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};t.mark("startQueryRelaysAsync");const n=await this.relayManagerProvider.getRelayManager().queryRelaysAsync(i);if(t.markAndMeasure("startQueryRelaysAsync","queryRelaysAsync"),this.terminated)throw new Error("session already disposed");const r={optional:[]},s=Fx(n,this.configProvider.config),a=this.negotiation.configureCrypto(r,this.context.config.isPstnCall);this.configureCpuThreshold(r),this.logger.safe.info("create peer connection");const o="unified-plan",l=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle";try{this.peerConnection=new Mp.window.RTCPeerConnection({iceServers:s,rtcpMuxPolicy:"require",iceTransportPolicy:this.configProvider.getIceTransportPolicy(),iceCandidatePoolSize:this.configProvider.config.iceCandidatePoolSize,bundlePolicy:l,sdpSemantics:o,audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===a,encodedInsertableStreams:!!this.configProvider.config.useInsertableStreams},r)}catch(e){throw e.code===DOMException.INVALID_STATE_ERR&&this.ufdManager.signalEvent("NoNetwork","Bad"),e}const c=this.peerConnection;this.negotiation.rollbackSupported=1===a&&this.context.configProvider.userAgentConfig.isBrowserRollbackSupported,this.negotiation.negotiationEmulator.configure(c),this.statsGatherer.initialize(c),this.statsGatherer.sessionInfo.setIceServers(s),this.statsGatherer.sessionInfo.setIceTransportPolicy(this.configProvider.getIceTransportPolicy()),this.statsGatherer.sessionInfo.setSdpSemantics(o),this.statsGatherer.sessionInfo.setBundlePolicy(l),this.diagnostics.iceServers=s,this.diagnostics.iceTransportPolicy=this.configProvider.getIceTransportPolicy(),this.diagnostics.sdpSemantics=o,this.diagnostics.bundlePolicy=l,await this.checkVideoCodecsSupport(),t.markAndMeasure("queryRelaysAsync","checkVideoCodecsSupport"),c.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${c.signalingState}`)},c.onicecandidateerror=e=>{const t=e,[i,n]=[t.address,t.port];if(this.logger.safe.warn(`On ICE candidate error ${t.url} | ${i}:${n}: code ${t.errorCode}: ${t.errorText}`),!this.transportStateProvider.isConnected||this.negotiation.iceCandidatesDefer.isPending){const e={address:i,port:+n,url:t.url,errorCode:t.errorCode,errorText:t.errorText};this.statsGatherer.addIceCandidateError(e),this.diagnostics.addIceCandidateError(e)}},c.onaddstream=e=>{this.logger.safe.info(`onaddstream stream: ${e.stream.id}`)};const d=(e,t,i,n)=>{this.logger.safe.info(`ontrack processing ${e.kind}: ${t.id}`);let r=t.active;if(!t.active&&this.configProvider.config.useInactiveAudioTrack&&"audio"===e.kind&&(this.logger.safe.warn("ontrack override forcing to use inactive audio stream"),r=!0),!r||"stopped"===n?.currentDirection||n?.stopped)return void this.logger.safe.info("ontrack ignore non active stream");let s=this.mediaManager.getMediaEntityByRemoteStreamId(t.id);if(s||(this.logger.safe.info(`cannot find media entity with stream id ${t.id} trying to fallback`),t.getAudioTracks()[0]&&(s=this.mediaManager.getMediaEntitiesByModality(Gi.MODALITY.audio)[0])),s){const n=this.createReceiveStream(t,i,e,s);s.setRemoteTrackId(e.id),this.addReceiveStreamTransforms(i,s.getModality()),this.receiveStreamCollection.add(n)}else this.logger.safe.error(`could not find media entity for an added stream: ${t.id}`)};c.ontrack=e=>{const{track:t,receiver:i,transceiver:n}=e,r=e.streams[0]??new MediaStream([t]),s=()=>d(t,r,i,n);if((!this.configProvider.config.addAudioStreamBeforeConnection||Gi.TRACK_KIND.audio!==t.kind)&&!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`ontrack queueing to be run once connected ${t.kind}: ${r.id}`),void this.transportStateProvider.doOnConnected(s,"ontrack",!1);s()},c.onremovestream=e=>{this.logger.safe.info(`onremovestream ${e.stream.id}`),this.transportStateProvider.doOnConnected((()=>this.receiveStreamCollection.remove(e.stream.id)),"onremovestream")},c.onicecandidate=t=>{const i=t.candidate;if(i){const t=rm(i.candidate);if(this.logger.safe.info(`[${e}] onicecandidate candidate: component:${t.component} protocol:${t.protocol} prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),"1"!==t.component)return;if(this.negotiation.iceCandidateReceived=!0,this.statsGatherer.sessionInfo.setCandidateDetails(t),this.diagnostics.setCandidateDetails(t),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1){const e={priority:i.priority?.toString()||t.priority,time:Date.now()-this.negotiation.iceRelayGatheringStartTime};this.statsGatherer.sessionInfo.setRelayCandidateInfo(e),this.diagnostics.relayCandidateInfo=e,this.relayCandidateGathered=!0}}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.negotiation.iceCandidatesDefer.isPending)return;const n=!this.context.config.webrtcIceGatheringTimeoutIncreased||this.configProvider.config.emptyIceCandidateMarksGatheredAnswerer&&!this.negotiation.initiator,r=this.iceHostCandidateOnly||0===s.length;if(!i&&n||r){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.transportStateProvider.isConnected,this.transportStateProvider.iceConnectionState,this.transportStateProvider.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.negotiation.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.negotiation.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},c.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${c.iceGatheringState}`)},this.transportStateProvider=new dB(c,a,this.logger.createChild("TransportStateProvider"),this.configProvider,this.diagnostics.newTransportStateDiagnostics()),this.transportStateProvider.on("stateChanged",((i,n,r)=>{if(this.terminated)return;const s=this.wasConnected?r:e;if(this.statsGatherer.sessionInfo.setIceConnectionState(i),"connecting"===i&&t.mark("transportConnecting"),"connected"===i||"completed"===i)t.markAndMeasure("transportConnecting","transportConnected"),this.onTransportConnected(s);else if("failed"===i||"closed"===i&&"failed"!==n){if(this.negotiation.iceCandidatesDefer.isPending)return this.logger.safe.info(`[${s}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(s);this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},s),this.configProvider.config.webrtcCloseAfterIceFailure&&c.close(),this.callbacks.onTransportFailed?.()}"disconnected"===i?(this.callbacks.onTransportDisconnected?.(e),this.startIceDisconnectedTimer(s)):this.clearIceDisconnectedTimer()})),this.transportStateProvider.on("signalingStateChanged",((t,i,n)=>{this.configProvider.config.reconnectOnPcClose&&!this.terminated&&"closed"===t&&this.transportStateProvider.isTransportConnected&&this.raiseError({type:Gi.MEDIA_ERROR.unexpectedClose,detail:"PeerConnection is closed"},n),"have-remote-pranswer"===i&&"stable"===t&&this.configProvider.config.webrtcPranswerWaitFinalAnswer&&this.transportStateProvider.isTransportConnected&&(this.logger.safe.info(`[${n}] remote final answer, activating audio`),this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e))})),this.transceiverManager=new Hm(this.logger,this.peerConnection,this.mediaManager,this.context,this.reinvitelessContext),this.streamSendersManager.registerRtpSenderManager(this.transceiverManager),mm(this.context)&&!this.dataChannel&&(this.dataChannel=new ep(this.peerConnection,this.diagnostics,this.logger,this.configProvider),this.callback.onDataChannelUpdated?.(this.dataChannel),this.multiParty&&this.initializeMediaControlPlane(e)),this.sourceRequestSender=new NV(this.mediaControlPlane,this.context.sendWebRtcMediaNotificationAsyncCallback,this.logger.createChild("SourceRequestSender")),this.mediaMessageController=new vB(this.logger.createChild("SourceRequester"),this.configProvider,this.sourceRequestSender,this.mediaControlPlane),this.negotiation.setInternals(this.transceiverManager,this.transportStateProvider,this.dataChannel),this.multiParty&&(this.contributingSources=new $U(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new jU(this.logger.createChild("ContributingSourcesProvider"),c,this.configProvider.config.diagnostics.features.logContributingSourcesError,this.diagnostics))),t.mark("startInitialize"),await this.encStreamsManager.initialize(),t.markAndMeasure("startInitialize","encStreamsManagerInitialize");const u=this.encStreamsManager.isWorkerLoaded();this.initAudioCodec(u),this.statsGatherer.sessionInfo.setEncodedStreamWorkerLoaded(u),this.diagnostics.encodedStreamWorker=u}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.negotiation.iceCandidatesDefer.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.negotiation.iceCandidatesDefer.resolve())}detectVideoFeatures(){const e=this.videoFeatureManager.get("Video"),t=this.configProvider.config.specCompliantSimulcast;if(t?.enableSimulcastLayoutControlStrategy&&t?.video?.layerScaleFactors?.length>2&&e.toggleClient(0,!0),this.context.config.isTownHall){const t=this.configProvider.config.broadcastMode;(t?.prioritizeLayoutOnServer||t?.prioritizeLayoutOnClient)&&e.toggleClient(3,!0),t?.maxSessionBandwidthKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps)}const i=this.mediaManager.getMediaEntitiesByModality("video"),n=this.configProvider.config.preferredH264VideoSendProfile;n?.startsWith("64")&&i.length>0&&i[0].isSendProfileSupported("H264",n)&&e.toggleClient(1,!0)}onTransportConnected(e){if(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),!this.terminated){if(this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`[${e}] transport connected provisional`),this.configProvider.config.createProvisionalAnswer.audioState&&this.callbacks.onAudioStateChanged?.(this.configProvider.config.createProvisionalAnswer.audioState,e),void(this.configProvider.config.createProvisionalAnswer.connectTransport&&this.callbacks.onTransportConnected?.(e));this.logger.safe.info(`[${e}] audio transport connected`),this.wasConnected=!0,this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval&&"have-remote-pranswer"===this.transportStateProvider.signalingState?this.handleEarlyMediaAudioState(e):this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e),this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&(this.videoFeatureManager.manageFeatureSupport((()=>{this.detectVideoFeatures()})),this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2&&this.videoFeatureManager.on("onVideoFeaturesChanged",(e=>{if("Video"===e.mediaType&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2){const t=this.mediaManager.getMediaEntitiesByModality("video");t.length>0&&this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(t[0],e)}}))),this.callbacks.onTransportConnected?.(e)}}async getAudioSenderStats(e=.5){const t=this.peerConnection?.getSenders().filter((e=>"audio"===e.track?.kind))[0];if(!t)return Promise.resolve(void 0);try{const i=Jt(1e3*e,"Unable to get audio receiver stats report");t.getStats().then(i.resolve,i.reject);const n=await i.promise;for(const e of n.values())if("outbound-rtp"===e.type)return Promise.resolve(e)}catch(e){return this.logger.safe.error(`Error getting audio sender stats: ${tt(e)}`),Promise.resolve(void 0)}return Promise.resolve(void 0)}handleEarlyMediaAudioState(e){const t=this.peerConnection.getReceivers().filter((e=>"audio"===e.track.kind))[0];if(!t)return this.logger.safe.warn(`[${e}] Connected transport with provisional answer with no audio receiver`),void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.started,e);const i=this.configProvider.config.webrtcPranswerMediaPollingTimeout,n=this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval;this.logger.safe.info(`[${e}] Starting polling for early media audio stats`);const r=async()=>{try{if(!this.canPollAudioStats())return;let s;this.logger.safe.debug(`[${e}] Polling audio receiver stats to detect early media start`);const a=Jt(i,"Unable to get audio receiver stats report");t.getStats().then(a.resolve,a.reject);const o=await a.promise;this.diagnostics.registerEarlyMediaPoll();for(const e of o.values())if("inbound-rtp"===e.type){s=e;break}if(!this.canPollAudioStats())return void this.logger.safe.info(`[${e}] Finished polling early media audio stats, terminated: ${!this.terminated}`);if((this.configProvider.config.webrtcPranswerCheckAudioEnergy?s?.totalAudioEnergy:s?.bytesReceived)>this.configProvider.config.webrtcPranswerAudioThreshold)return this.logger.safe.info(`[${e}] Finished polling early media audio stats, activating audio`),void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);this.logger.safe.info(`[${e}] No audio data received yet, polling again in ${n}ms`),setTimeout(r,n)}catch(t){const i=tt(t);if(this.logger.safe.error(`[${e}] Error polling stats for pranswer: ${i}. Will stop polling: ${this.configProvider.config.webrtcPranswerStopPollingAfterError}`),this.diagnostics.addStatsError("WebrtcSession::earlyMediaPolling",i),this.configProvider.config.webrtcPranswerStopPollingAfterError)return void this.callbacks.onAudioStateChanged?.(Gi.STREAMING_STATE.active,e);setTimeout(r,n)}};setTimeout(r,this.configProvider.config.webrtcPranswerWaitIntervalBeforePolling)}canPollAudioStats(){return!this.terminated&&"have-remote-pranswer"===this.transportStateProvider.signalingState}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise ${Gi.MEDIA_ERROR.iceConnectionError}`),this.raiseError({type:Gi.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=be()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}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(e){if(Gi.MODALITY.audio===e.getModality()&&(this.webrtcAudioRecvStream=e.getMediaStream(),await this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),await this.updateAudioRendererStream(this.webrtcAudioRecvStream)),this.configProvider.config.mapSsrcToTrackForStats){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);this.statsGatherer.setSsrcTrackPair(t.getRemoteSsrc(),t.getRemoteTrackId())}this.notifyStreamsChanged()}async updateAudioRendererStream(e){await this.audioRenderer.play(e),this.rawIncomingAudioStreamManager.streamChanged(e)}streamRemoved(e){if(Gi.MODALITY.audio===e.getModality())this.audioRenderer.getStream()===e.getMediaStream()&&(this.audioRenderer.stop(),this.rawIncomingAudioStreamManager.streamChanged(null)),this.webrtcAudioRecvStream=null;else if(Gi.MODALITY.video===e.getModality()){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);t?.getLocalRecvCapabilities()?.resetToInitial()}this.clearReceiveStreamTransforms(e.getReceiver()),e.dispose(),this.notifyStreamsChanged()}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(e,t,i,n){const r=this.configProvider.config.addFmtpToInitialSubscription?n.getLocalRecvCapabilities():null,s=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&n.getModality()!==Gi.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null,a=new aO(e,t,n.getModality(),+n.getXSourceStreamId(),this,r,s,n.getSubstreamIndex());return new gV(a,i,this.receiveStreamCollection,this.logger.createChild("RecvStream"),this.configProvider.config)}async requestSource(e,t,i){if(!this.multiParty)return;const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);if((this.isMuteHold||this.negotiation.negotiatedModalities[n.getModality()]===Gi.MEDIA_STATE.inactive)&&-1!==t)return await Yt(10),this.requestSource(e,t,i);if(this.negotiation.negotiationCompletedPromise.isPending)try{await this.negotiation.negotiationCompletedPromise.promise}catch(e){this.logger.safe.info("source request should be sent even if negotiation rejected",e)}if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional){this.logger.safe.info("requestSource is postponed till transport is connected");const e=new Kt;this.transportStateProvider.doOnConnected((()=>e.resolve()),"requestSource"),await e.promise}return this.mediaMessageController.sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex())}async onReceiveCapabilitiesChanged(e,t,i){if(!this.streamSendersManager)return!1;try{return await this.streamSendersManager.applyCapabilities(t,e,i),!0}catch(e){return!1}}onOptimalVideoCountChanged(e,t){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e),this.diagnostics.addOvcSubscriptionReport(e,this.subscriptionManager?.getSubscriptionsCount(),t)}async onSendBandwidthChanged(e){if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional||!this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled"))return;const t=[],i=Object.keys(e);for(const n of i){const i=this.mediaManager.getMediaEntitiesByModality(am(n)).filter((e=>e.isEnabled()&&null!==e.getLocalTrackId()));if(0===i.length||0===e[n])return;t.push({streamMsid:i[0].getXSourceStreamId(),bw:e[n]})}await this.mediaMessageController.sendBandwidthInfo(t),this.diagnostics.reportedSendBandwidthLayouts(e)}onMaxVideoSendCapabilitiesChanged(e,t){("Video"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForVideo||"ScreenShare"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForSharing)&&this.transportStateProvider.doOnConnected((()=>this.notifyMaxVideoCapabilitiesChanged(e,t)),"maxCapabilities")}notifyMaxVideoCapabilitiesChanged(e,t){const i=am(e),n=this.mediaManager.getMediaEntitiesByModality(i)[0];if(!n)return;const r=n.getMid();"Video"===e&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2?this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(n,this.videoFeatureManager.get("Video"),t):this.mediaMessageController.sendMaxVideoSendCapabilities([r],t)}createAudioRenderer(){this.audioRenderer=new ek(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",((e,t,i)=>this.onAudioPlaybackError(e,t,i))),this.audioRenderer.on("onAudioStateChanged",((e,t)=>this.deviceManager.effectsManager.setAecRefStream(e,t)))}onAudioPlaybackError(e,t,i){const n={type:t,detail:i,isAudio:!0};this.ufdManager.signalDeviceEvent(1,"Bad","Audio"),this.deviceManager.raiseTelemetryEvent("reconnect_on_audio_playback_error",{error:e,mediaError:t,message:i}),this.context.reconnectRetry&&this.configProvider.config.audioRendererFailedRetryCodes?.includes(e)&&(this.logger.warn(`Reconnect required, attempt No: ${this.context.reconnectRetry}`),this.context.reconnectRetry--,this.raiseError(n))}getSessionConfig(){return this.configProvider}getLocalMediaTrackId(e){const t=this.mediaManager.getLocalTracksInfo(),i=am(e),n=t.find((e=>e.modality===i));return n?n.trackId:null}addReceiveStreamTransforms(e,t){const i=this.encStreamsManager.initTransformsCollection(e,"Receiver",sm(t));i&&t!==Gi.MODALITY.audio&&this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&i.addTransform(new Sf(this.logger.createChild(`RecvStreamAnalyzer [${t}/${e.track.id}]`)))}clearReceiveStreamTransforms(e){this.encStreamsManager.clearTransformsCollection(e)}async checkVideoCodecsSupport(){try{const e=await this.capabilityGatherer.getCapabilities("video");this.statsGatherer.setH264AvailableProfiles(e);const t=DU({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0),i=await t.getCapabilities("video"),n=DU({global:this.context.maContext},!1),r=await n.getCapabilities("video");this.statsGatherer.setSupportedH264Profiles(i,r);const s=await Vp.isCodecsSupported(this.configProvider.config.hevcCodecs);this.diagnostics.videoCapabilities=e,this.diagnostics.setSupportedH264Profiles(i,r),this.diagnostics.isCodecsSupported=s;const a=new Set(e?.codecs?.map((e=>e.mimeType.toLocaleLowerCase()))||[]);for(const e of this.configProvider.config.requiredVideoCodecs)if(!a.has(e)){this.ufdManager.signalEvent("NoRequiredVideoCodecs","Bad","Video");break}}catch(e){this.logger.safe.error(`failed to get video capability ${tt(e)}`)}}setBWSeed(e){if(!this.bandwidthCache)return;const t=this.bandwidthCache.getSeed();e.applyChannelParameters={multiChannelParameter:{mids:this.configProvider.config.bwSeedOptions.mids,mediaParameter:JSON.stringify({sendSideBWSeed:{seedValueBitsPerSec:t}})}},this.diagnostics.sentBWSeed=t}getSubscriptionManager(){return this.subscriptionManager}initAudioCodec(e){this.audioCodecManager.init(e,this.isAudioOutputMuted),this.audioCodecManager.encoder?.on("codecChanged",(e=>this.statsGatherer.setAudioEncoderCodecName(e)));const t=this.audioCodecManager.decoder;t&&(t.on("usedDecoderChanged",(e=>{this.updateAudioRendererStream(e?t.stream:this.webrtcAudioRecvStream),this.statsGatherer.setAudioDecoderStatsProvider(e?t.getStatsProvider():void 0),this.contributingSources?.useCustomCodec(e)})),t.on("contributingSourcesChanged",(e=>this.contributingSources?.updateContributingSources(e))),this.audioCodecManager.on("negotiationNeeded",(e=>this.negotiation.triggerRenegotiation(!0,e))))}onIncomingVideoQualityChanged(e,t){1===e&&this.remoteVideoResolutionManager.limitResolutionOnPoorPerformance(t)}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((e=>e.dispose())),this.logger.info("New subscriptions for deviceManager created"),this.setSubsForDeviceManager()}))}updateLocalMediaSources(){this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statsGatherer.updateStatsWithLocalSsrcTrackInfo();const e=this.streamSendersManager.getLocalMediaSources();this.qualityManager.updateRegisteredSources(e)}},FV={build:(e,t,i)=>new xV(e,t,i)},UV=class{constructor(e,t,i,n,r,s,a,o){this.logger=e,this.context=t,this.configProvider=i,this.diagnostics=n,this.ufdManager=r,this.deviceManager=s,this.capabilities=a,this.midCallTelemetry=o,this.activeSessions=[],this.pendingDeviceTelemetryEvents=[],this.pendingVideoEffectsTelemetryEvents=[],this.pendingAudioEffectsTelemetryEvents=[],this.callsCount=0,this.mediaConfig={},this.configProvider.on("configUpdated",(()=>this.configApplied())),this.deviceManager.on("onDeviceTelemetryEvent",(e=>this.onDeviceTelemetryEvent(e))),this.deviceManager.on("onVideoEffectsTelemetryEvent",(e=>this.onVideoEffectsTelemetryEvent(e))),this.deviceManager.on("onAudioEffectsTelemetryEvent",(e=>this.onAudioEffectsTelemetryEvent(e)))}createSession(e,t,i,n,r,s){const a=(0,Ix.merge)({},this.mediaConfig,s);this.configProvider.setMediaConfiguration(a);const o=this.configProvider.getConfigView(i?.isConference),l=this.logger,c=t.correlationId,d=this.diagnostics.newSession(o,c,this.logger.createChild("sessionDiagnostics"));r?.setDiagnosticsReport(this.diagnostics.reportGenerator);const u={getLogger:()=>l,getUfdManager:()=>this.ufdManager,sendWebRtcMediaNotificationAsyncCallback:(e,i)=>t.sendWebRtcMediaNotificationAsync(e,i),maContext:this.context,config:i??{},configProvider:o,diagnostics:d.newNativeSessionDiag(),reconnectRetry:o.config.audioRendererFailedReconnectTimes,callDeviceManager:n,getSmallCallTelemetry:()=>r},h=(o.mediaConfig.simulcastSessionEnabled?FV:TB).build(u,c,e),g=new Kx(o,++this.callsCount,d);g.setMediaQosEnabled(!!a.enableMediaQoS),g.setPortRangeConfigured(!!a.mediaPortRanges);const p=new $x(h,c,u,e,g,this.configProvider,d);for(p.on("onTerminated",(e=>this.onSessionTerminated(e))),this.activeSessions.push(p),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector=Ax.getInstance(this.logger.createChild("WebRtcInternals"),o),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length);this.pendingDeviceTelemetryEvents.length>0;)p.registerDeviceTelemetryEvent(this.pendingDeviceTelemetryEvents.pop());for(;this.pendingVideoEffectsTelemetryEvents.length>0;)p.registerVideoEffectsTelemetryEvent(this.pendingVideoEffectsTelemetryEvents.pop());for(;this.pendingAudioEffectsTelemetryEvents.length>0;)p.registerAudioEffectsTelemetryEvent(this.pendingAudioEffectsTelemetryEvents.pop());return p}getDeviceManager(){return this.deviceManager}getCapabilities(){return this.capabilities}getScreenSharingManager(){return new Mx(this.deviceManager)}updateConfig(e,t,i,n){this.configProvider.updateConfig(e,t,i,n)}getConfig(){return this.configProvider.config}getConfigProvider(){return this.configProvider}setMediaConfig(e){(0,Ix.merge)(this.mediaConfig,e),this.diagnostics.mediaConfig=this.mediaConfig}getMediaLogs(){return this.webRtcInternalsCollector?this.webRtcInternalsCollector.collect():Promise.resolve("")}getDiagnosticsData(){return this.diagnostics.rootRef}dispose(e){return Promise.all([...this.activeSessions.map((async t=>{await t.terminate(e,{}).catch((()=>{})),t.dispose()}))]).then((()=>{}),(()=>{}))}handleSendMidCallTelemetry(e){this.midCallTelemetry?.on("sendMidCallTelemetry",e)}configApplied(){window&&(this.configProvider.config.enableDevtoolsAPI?window.webMA||this.injectDevtoolsAPI():window.webMA&&delete window.webMA)}injectDevtoolsAPI(){const e=[],t={config:{addOverride:(e,t)=>this.configProvider.setConsoleOverride(e,t),setOverrides:e=>this.configProvider.setConsoleOverrides(e),clearOverride:e=>this.configProvider.clearConsoleOverride(e),clearAllOverrides:()=>this.configProvider.clearAllConsoleOverrides(),setPlatformConstraints:e=>this.configProvider.setCallConstraints(e),setCallConstraints:e=>{this.activeSessions.length&&this.activeSessions[this.activeSessions.length-1].setCallConstraints(e,"webMA")},setRelayConfigOverride:e=>this.context.getRelayManager().setRelayOverride(e),manageVideoFeatures:t=>{e.push(t)}},diagnosticsReport:this.diagnostics.reportGenerator,initVideoFeatures:t=>{e.forEach((e=>{e(((e,i,n)=>{let r;const s=hB[n];return void 0!==s&&(("video"===i||"sharing"===i)&&(r=t.get("Video")),void 0!==r)&&(e?(r.toggleServer(s,!0),!0):(r.toggleClient(s,!0),!0))}))}))},deviceManager:{setAudioProcessingFlags:e=>this.deviceManager.setAudioProcessingFlags(e)},ufdManager:{raiseUFD:(e,t="Bad",i="Video")=>this.ufdManager.signalEvent(e,t,i)}};window.webMA=t}onDeviceTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerDeviceTelemetryEvent(e))):this.pendingDeviceTelemetryEvents.push(e)}onVideoEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerVideoEffectsTelemetryEvent(e))):this.pendingVideoEffectsTelemetryEvents.push(e)}onAudioEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerAudioEffectsTelemetryEvent(e))):this.pendingAudioEffectsTelemetryEvents.push(e)}onSessionTerminated(e){Qi(this.activeSessions,(t=>t===e)),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length),0===this.activeSessions.length&&this.ufdManager.reset()}},BV=class{static build(e,t,i,n,r,s,a,o){return new UV(e,t,i,n,r,s,a,o)}};BV.constants=Gi,BV.helper=Bp;var VV=class extends gt{constructor(e,t,i){super(),this.logger=e,this.callbacks=t,this.deviceManagerDiagnostics=i,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(e){if(this.logger.info(`getWorkerFunction, loaderName: ${e}`),!this.callbacks?.createGenericWebRTCWorker)switch(e){case"encoded-stream":return this.callbacks?.createEncodedStreamsWorker;case"wasmcv":return this.callbacks?.createWasmCVWorker;default:return}switch(e){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,getEncodedStreamsTimerWorklet:this.callbacks?.audioWorklet?.getEncodedStreamsTimerWorklet}:this.callbacks?.audioWorklet}create(e){let t;try{t=this.callbacks.createGenericWebRTCWorker()}catch(e){return}const i=Date.now(),n=i=>{const r=JSON.stringify(i);this.logger.error(`Worker ${JSON.stringify(e)} error: ${r}`),this.deviceManagerDiagnostics?.registerWorkerEvent({timestamp:Date.now(),workerType:e.msg,msg:"generic-worker-error",payload:r}),t.removeEventListener("error",n),this.event("onLoadError").raise(e.msg)},r=s=>{let a;"wasm-worker-loaded"===s?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(e)} event: ${JSON.stringify(s.data)}`),a={timestamp:Date.now(),workerType:e.msg,workerLoadTimeMs:Date.now()-i,msg:JSON.stringify(s?.data?.msg),payload:JSON.stringify(s?.data?.payload)},t.removeEventListener("message",r)),"wasm-worker-load-error"===s?.data?.msg&&n(s),a&&this.deviceManagerDiagnostics?.registerWorkerEvent(a)};return t.addEventListener("error",n),t.addEventListener("message",r),t.postMessage(e),t}},HV=class e{constructor(e,t,i){this.workerProvider=e,this.workerUrl=t,this.workletUrl=i}static async create(t,i){const n=t.getWorkerFunction("encoded-stream"),r=!n&&i?await i.getWorkerUrl():void 0;try{const i=await(t.audioWorklet?.getEncodedStreamsTimerWorklet?.());return new e(n,r,i)}catch(t){return new e(n,r,void 0)}}getTimerWorkletUrl(){return this.workletUrl}getWorker(e){try{if(e.safe.info("creating worker"),this.workerProvider)return this.workerProvider();if(this.workerUrl)return e.safe.warn("WasmLoader didn't provide worker function, falling back to legacy worker provider"),new Worker(this.workerUrl);e.safe.error("no worker provider")}catch(t){e.safe.error(`failed to create worker ${tt(t)}`)}return null}},$V=class{constructor(){this.data={count:{}}}registerQualityChangedEvent(e){var t,i,n;(t=this.data.count)[i=Rf(e)]??(t[i]={});const r=this.data.count[Rf(e)];r[n=e.value.toLowerCase()]??(r[n]=0),r[e.value.toLowerCase()]++}getObjectRef(){return this.data}},jV=class{constructor(e,t,i){this.mediaAgents=[],e.logger??(e.logger=new iv),e.domOverrides??(e.domOverrides={}),this.config=e;const n=e.mediaSettings;(function(e=""){const t=e.match(new RegExp("^SkypeSpaces/(\\d+)/"));t?.length&&Object.values(wp).includes(t[1])&&(Tp=t[1]),"undefined"!=typeof window&&"undefined"!=typeof navigator&&(void 0!==navigator.webkitGetUserMedia&&"undefined"!=typeof webkitRTCPeerConnection&&Ap()?(window.RTCPeerConnection=webkitRTCPeerConnection,navigator.getUserMedia=(e,t,i)=>{const n=e=>{e?.deviceId?.exact&&(e.mandatory||(e.mandatory={}),e.mandatory.sourceId=e.deviceId.exact,delete e.deviceId)};return e&&(n(e.audio),n(e.video)),navigator.webkitGetUserMedia(e,t,i)}):Ip&&Rp())})(e.clientInformation),this.logger=new _x(e.safeLogger?.createChild("MA",n.debug),e.logger.createChild("MA",n.debug)),this.configProvider=new rO(this.logger.createChild("configProvider"),i,n);const r=new fk(this.configProvider),s=new $V;this.mediaAgentDiagnostics=new bx(this.configProvider,r,s),this.ufdManager=new sv(this.logger.createChild("UFD"),this.configProvider,s),this.wasmLoader=new VV(this.logger.createChild("WasmLoader"),e.createWasmWorkerCbs,r),this.deviceManager=new Kk(this.logger.createChild("DeviceManager"),this.configProvider,r,e.domOverrides,this.ufdManager,e.webcvProvider,e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.wasmLoader),this.capabilities=new nv(this.configProvider),Hn.initialize(this.configProvider),t.on("OnECSChanged",(()=>{const e=t.getEcsConfig("SkypeWebMedia","mediaAgent");e?this.configProvider.updateConfig(e,t.ETag,t.getEcsConfig("ConfigIDs","SkypeWebMedia"),t.getEcsConfig("Headers","CountryCode")):this.logger.warn("No SkypeWebMedia.mediaAgent config.")}))}getDeviceManager(){return this.deviceManager}async buildAgent(e,t,i){if(!Vp.hasMediaApi())throw[new GV(`${e} not supported by media agent provider`,"not_supported")];if(this.config?.detectH264Support&&!await Vp.hasH264CodecSupport(this.config.logger))throw[new GV("H264 is not supported","not_supported")];const n=await HV.create(this.wasmLoader,this.config.encodedStreamsWorkerProvider),r={getRelayManager:()=>t.getOrCreateRelayManager(),getWebCVProvider:()=>this.config.webcvProvider,getWasmDnsProvider:()=>this.config.wasmdnsProvider,getWasmAecProvider:()=>this.config.wasmaecProvider,getWasmVqeProvider:()=>this.config.wasmVqeProvider,getEncodedStreamsWorkerProvider:()=>n,domOverrides:this.config.domOverrides,configProvider:this.configProvider};t.setConfigProvider(this.configProvider);const s=BV.build(this.logger,r,this.configProvider,this.mediaAgentDiagnostics,this.ufdManager,this.deviceManager,this.capabilities,i);return s.constants=BV.constants,this.mediaAgents.push(s),s}async dispose(e){return Promise.all([this.deviceManager.dispose(),this.ufdManager.dispose(),this.configProvider.dispose(),this.capabilities.dispose(),...this.mediaAgents.map((t=>t.dispose(e)))]).then((()=>{this.mediaAgents=[]}))}},GV=class extends Error{constructor(e,t="failure"){super(e),this.reason=t}},qV=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(e){const t=Ot.getBrowserInfo(),i=this.supportedPlatforms.get(t.name);if(e&&i&&Ot.isVersionGreaterOrEqual(i))return 1;if(e&&!i){if(Ot.isEngine("Chromium","ChromiumAVD"))return 2;const e=this.experimentalPlatforms.get(t.name);if(e&&Ot.isVersionGreaterOrEqual(e))return 2}return 0}},zV=class extends gt{constructor(e,t,i){super(),this.relayManagerProvider=e,this.configProvider=t,this.logger=i,this.currentInfo={},this.currentAreaContent={},this.isEnabled=!1,this.isEnabled=this.configProvider.config.enableE911,t.on("configUpdated",(()=>{const e=this.isEnabled;this.isEnabled=this.configProvider.config.enableE911,!this.isEnabled||e===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(e,t){if(this.isEnabled)switch(this.logger.info(`Client info for ${e} set`),e){case 3:this.mergeClientAreaInfo(JSON.parse(t));break;case 1:break;case 2:this.mergeClientNetworkInfo(JSON.parse(t))}}mergeClientAreaInfo(e){const t=JSON.stringify(this.currentAreaContent);this.currentAreaContent.geoCoordinates=e.geoCoordinates,rn(this.currentAreaContent),JSON.stringify(this.currentAreaContent)!==t&&this.raiseChanged()}mergeClientNetworkInfo(e){if(0===Object.keys(e).length){const e=Object.keys(this.currentInfo).length+Object.keys(this.currentAreaContent).length;return this.currentInfo={},this.currentAreaContent={},void(e>0&&this.raiseChanged())}const t=this.currentInfo.bssid!==e.bssid||this.currentInfo.bssidv6!==e.bssidv6||this.currentInfo.mac!==e.mac||this.currentInfo.macv6!==e.macv6||this.currentInfo.subnetLengthIpv4!==e.subnetLengthIpv4||this.currentInfo.subnetLengthIpv6!==e.subnetLengthIpv6,i=this.currentInfo.e911;this.currentInfo.bssid=e.bssid,this.currentInfo.bssidv6=e.bssidv6,this.currentInfo.e911=e.e911,this.currentInfo.mac=e.mac,this.currentInfo.macv6=e.macv6,this.currentInfo.subnetLengthIpv4=e.subnetLengthIpv4,this.currentInfo.subnetLengthIpv6=e.subnetLengthIpv6,rn(this.currentInfo),t?this.probeForIP("clientNetworkInfoChanged").then((e=>{e||this.raiseChanged()})):JSON.stringify(i)!==JSON.stringify(e.e911)&&this.raiseChanged()}async probeForIP(e){return this.probingPromise?(this.logger.info(`Probing already in progress, tried to start for: ${e}`),this.probingPromise):(this.probingPromise=this.probeForIPInternal(e),this.probingPromise.then((e=>(this.probingPromise=void 0,e))).catch((e=>(this.probingPromise=void 0,this.logger.error(`E911 probing failed: ${tt(e)}`),!1))))}async probeForIPInternal(e){this.logger.info(`Probing for public IP address: ${e}`);const t=await this.ensureProber();if(await t.ensureOnline(),t.ipFromRelay){if((this.currentInfo.ipv4||this.currentInfo.ipv6)!==t.ipFromRelay)return delete this.currentInfo.ipv4,delete this.currentInfo.ipv6,this.currentInfo[Hp.test(t.ipFromRelay)?"ipv4":"ipv6"]=t.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 e=Ux(await this.relayManagerProvider.getOrCreateRelayManager().queryRelaysAsync({relayType:"turn"}),this.configProvider.config);return this.prober=new xx(e,new _x(this.logger.createChild("Prober"),this.logger.createChild("ProberUnsafe"))),this.prober}},WV=class extends gt{constructor(e){super(),this.ecsFilters=e,this.config=null}get ETag(){return this.etag}async setEcsConfig(e){this.config=JSON.parse(e.ecsBlob),this.etag=e.etag,this.event("OnECSChanged").raise()}async setUserEcsServerUrl(e,t){throw new Error("Not implemented")}async getUserEcsServerUrl(e){throw new Error("Not implemented")}async setActiveUserForEcs(e){throw new Error("Not implemented")}async getEcsQueryParameters(){const e={CLRelease:"2025.07.01.15"},t="_TS_BUILC_VERSION_".replace("C","D"),i=this.ecsFilters?.["UserInfo.Ring"]?.value,n=this.getTeamsExperience();e.CLRelease===t&&(e.CLRelease="9999.99"),i&&(e.audienceGroup=i,e.teamsRing=i),n&&(e.Experience=n),"vdi3"===this.ecsFilters?.vdi?.value&&(e.vdi="vdi3");const r=Ot.getBrowserInfo();return e.BrowserName=r.name,e.BrowserEngine=r.engine,e.BrowserVersion=r.version,e.FormFactor=r.formFactor,e.OsName=r.osName,e.OsVer=r.osVersion,Vp.hardwareConcurrency&&(e.CPUCount=Vp.hardwareConcurrency),JSON.stringify(e)}async ecsGetUserQueryParameters(e){return this.getEcsQueryParameters()}async shouldTriggerCQF(e,t,i){throw new Error("Not implemented")}getEcsConfig(e,t){const i=this.config?.[e];return t?i?.[t]:i}createEcsConfiguration(){return new class{constructor(e){this.provider=e}getBoolean(e,t){return this.provider.getEcsConfig(e,t)}getNumber(e,t){return this.provider.getEcsConfig(e,t)}getString(e,t){const i=this.provider.getEcsConfig(e,t);return JSON.stringify(i)}}(this)}getTeamsExperience(){return!0===this.ecsFilters?.isTeams2?.value?"teams2":!1===this.ecsFilters?.isTeams2?.value?"teams1":void 0}},KV=class{constructor(e){this._sharingSource=e}getId(){return this._sharingSource.getId()}getDeviceId(){return this._sharingSource.getDeviceId()}getType(){return this.mapSharingSourceType(this._sharingSource.getType())}getPreview(e,t,i){return Promise.reject("not implemented")}getPreviewAsync(e,t){return this._sharingSource.getPreviewAsync(e,t)}getDescription(){return this._sharingSource.getDescription()}getIcon(e,t){return this._sharingSource.getIcon(e,t)}getBounds(){}mapSharingSourceType(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 3;default:throw new Error("Invalid sharing source type")}}},JV=class extends gt{constructor(e){super(),this._screenSharingManager=e,this._screenSharingManager.onScreensChanged((()=>{this.event("screensChanged").raise()}))}enumerateScreensAsync(){return this._screenSharingManager.enumerateScreensAsync().then((e=>e.map((e=>new KV(e)))))}enumerateWindowsAsync(){return this._screenSharingManager.enumerateWindowsAsync().then((e=>e.map((e=>new KV(e)))))}enumerateCamerasAsync(){return this._screenSharingManager.enumerateCamerasAsync().then((e=>e.map((e=>new KV(e)))))}},YV=Q;function QV(e,t){return null==e?t:e}function ZV(e,t){return e||t}var XV,eH=class{constructor(e,t,i,n){this.signalingAgentConfig=e,this.ecsProvider=t,this.logger=i,this.telemetryLogger=n,this.ecsProvider.on("OnECSChanged",(()=>this.onEcsUpdate())),this.signalingAgentConfig.clientInformation+="/TsCallingVersion=2025.07.01.15/Ovb=8962f6ae8324f6a345d7997ae8f276ff81198956",this.signalingAgentConfig.piiScrubber={omit:YV.pii.Omit,mri:YV.pii.Mri},this.signalingAgent=new lh(this.getSignalingAgentConfig())}getSignalingAgent(){return this.signalingAgent}onEcsUpdate(){const e=this.ecsProvider.getEcsConfig("SkypeCalling");this.logger.info(`onEcsUpdate, ecsTag=${this.ecsProvider.ETag||""}, ecsConfig=${JSON.stringify(e)}`),this.signalingAgentConfig=((e,t)=>{if(!t)return e;const i={...e};if(t.ngIncoming&&t.ngOutgoing){const n=function(e,t){return t&&e?"enabled":e?"recvOnly":!1===e&&!1===t?"disabled":void 0}(t.ngIncoming.isVBSSEnabled,t.ngOutgoing.isVBSSEnabled);i.cloudScreenSharingFlag=QV(n,e.cloudScreenSharingFlag)}return t.ngOutgoing&&(i.emergencyCallCountry=function(e,t){return!1===e?"":t}(t.ngOutgoing.isEmergencyCallingEnabled,e.emergencyCallCountry),i.isGVCOutgoingEnabled=QV(t.ngOutgoing.isGVCEnabled,e.isGVCOutgoingEnabled),i.brokerEnabledOutgoing=QV(t.ngOutgoing.isBrokerEnabled,e.brokerEnabledOutgoing)),t.ngIncoming&&(i.isGVCJoiningEnabled=QV(t.ngIncoming.isGVCEnabled,e.isGVCJoiningEnabled),i.brokerEnabledIncoming=QV(t.ngIncoming.isBrokerEnabled,e.brokerEnabledIncoming)),i.conversationServiceUrl=ZV(t.conversationServiceUrl,e.conversationServiceUrl),i.uploadLogRequestUrl=ZV(t.uploadLogRequestUrl,e.uploadLogRequestUrl),i.isConversationServiceUrlFromEcs=!!t.conversationServiceUrl,i.isUploadLogRequestUrlFromEcs=!!t.uploadLogRequestUrl,i.callingTokenLogicalUrl=ZV(t.callingTokenLogicalUrl,e.callingTokenLogicalUrl),i.doHostlessCalling=QV(t.allowHostlessCalls,e.doHostlessCalling),i.supportsCompressedServicePayload=QV(t.supportCompressedTrouterPayload,e.supportsCompressedServicePayload),i.brokerRequestBatching=QV(t.allowBrokerSubscribeBatching,e.brokerRequestBatching),i.brokerExclusively=QV(t.brokerExclusively,e.brokerExclusively),i.handleMediaOfferFromPushNotification=QV(t.handleMediaOfferFromPushNotification,e.handleMediaOfferFromPushNotification),i.handleNewOfferRequest=QV(t.handleNewOfferRequest,e.handleNewOfferRequest),i.sendProgressFromCC=QV(t.sendProgressFromCC,e.sendProgressFromCC),i.useInternalHttpDispatcher=QV(t.webInternalHttpDispatcher,e.useInternalHttpDispatcher),(t.webInternalHttpDispatcherConfigNetworkRequest||e.requestTypeHttpDispatcherConfigMap)&&(t.webInternalHttpDispatcherConfigNetworkRequest=t.webInternalHttpDispatcherConfigNetworkRequest||{},e.requestTypeHttpDispatcherConfigMap=e.requestTypeHttpDispatcherConfigMap||{},i.requestTypeHttpDispatcherConfigMap={...e.requestTypeHttpDispatcherConfigMap,...t.webInternalHttpDispatcherConfigNetworkRequest}),(t.operationTypeHttpDispatcherConfigMap||e.operationTypeHttpDispatcherConfigMap)&&(t.operationTypeHttpDispatcherConfigMap=t.operationTypeHttpDispatcherConfigMap||{},e.operationTypeHttpDispatcherConfigMap=e.operationTypeHttpDispatcherConfigMap||{},i.operationTypeHttpDispatcherConfigMap={...e.operationTypeHttpDispatcherConfigMap,...t.operationTypeHttpDispatcherConfigMap}),(t.csaTimeoutConfiguration||e.csaTimeoutConfiguration)&&(t.csaTimeoutConfiguration=t.csaTimeoutConfiguration||{},e.csaTimeoutConfiguration=e.csaTimeoutConfiguration||{},i.csaTimeoutConfiguration={...e.csaTimeoutConfiguration,...t.csaTimeoutConfiguration}),i.autoJoinOnConflict=QV(t.autoJoinOnConflict,e.autoJoinOnConflict),i.enableQuickSendAcceptanceAck=QV(t.enableQuickSendAcceptanceAck,e.enableQuickSendAcceptanceAck),i.supportMediaRetargetWhileIncomingRenegotiation=QV(t.supportMediaRetargetWhileIncomingRenegotiation,e.supportMediaRetargetWhileIncomingRenegotiation),i.enableCallEstablishmentTimeoutsForStartJoinCall=QV(t.enableCallEstablishmentTimeoutsForStartJoinCall,e.enableCallEstablishmentTimeoutsForStartJoinCall),i.callingServiceSupportsCAETokens=QV(t.callingServiceSupportsCAETokens,e.callingServiceSupportsCAETokens),i.callingServiceSupportsAADTokens=QV(t.callingServiceSupportsAADTokens,e.callingServiceSupportsAADTokens),i.aadTokenExpirationTimeInSeconds=QV(t.aadTokenExpirationTimeInSeconds,e.aadTokenExpirationTimeInSeconds),i.caeTokenExpirationTimeInSeconds=QV(t.caeTokenExpirationTimeInSeconds,e.caeTokenExpirationTimeInSeconds),i.disableTokenMigrationHeader=QV(t.disableTokenMigrationHeader,e.disableTokenMigrationHeader),i.enablePublishTokenTelemetry=QV(t.enablePublishTokenTelemetry,e.enablePublishTokenTelemetry),i.refreshTimeBeforeTokenTimeoutInSeconds=QV(t.refreshTimeBeforeTokenTimeoutInSeconds,e.refreshTimeBeforeTokenTimeoutInSeconds),i.forceClearExpiredTokens=QV(t.forceClearExpiredTokens,e.forceClearExpiredTokens),i.enableRefreshToken=QV(t.enableRefreshToken,e.enableRefreshToken),i.enableAsyncDisablePreheat=QV(t.enableAsyncDisablePreheat,e.enableAsyncDisablePreheat),i.forceLowercaseHttpHeaders=QV(t.forceLowercaseHttpHeaders,e.forceLowercaseHttpHeaders),i.enableResolveScreenSharingWhenNegotiationComplete=QV(t.enableResolveScreenSharingWhenNegotiationComplete,e.enableResolveScreenSharingWhenNegotiationComplete),i.maxReinvitelessMediaForVideoForWeb=QV(t.maxReinvitelessMediaForVideoForWeb,e.maxReinvitelessMediaForVideoForWeb),i.maxReinvitelessMediaForVBSSForWeb=QV(t.maxReinvitelessMediaForVBSSForWeb,e.maxReinvitelessMediaForVBSSForWeb),i.enableRefreshTokenRetry=QV(t.enableRefreshTokenRetry,e.enableRefreshTokenRetry),i.enableRefreshTokenRetryInSeconds=QV(t.enableRefreshTokenRetryInSeconds,e.enableRefreshTokenRetryInSeconds),i.enableConversationTypeUpdateOnCallEnd=QV(t.enableConversationTypeUpdateOnCallEnd,e.enableConversationTypeUpdateOnCallEnd),i.supportMissingTokenTypesInResponse=QV(t.supportMissingTokenTypesInResponse,e.supportMissingTokenTypesInResponse),i.useSkypeTokenWhenNoAuthenticateHeader=QV(t.useSkypeTokenWhenNoAuthenticateHeader,e.useSkypeTokenWhenNoAuthenticateHeader),i.enableAutoPromotion=QV(t.enableAutoPromotion,e.enableAutoPromotion),i.enableTokenCache=QV(t.enableTokenCache,e.enableTokenCache),i.enableBatchedSendMessageStatus=QV(t.enableBatchedSendMessageStatus,e.enableBatchedSendMessageStatus),i.enableBatchedReceiveMessage=QV(t.enableBatchedReceiveMessage,e.enableBatchedReceiveMessage),i.enableTokenCacheForGenericTokenAPI=QV(t.enableTokenCacheForGenericTokenAPI,e.enableTokenCacheForGenericTokenAPI),i.disableRealTimeModeFromRoster=QV(t.disableRealTimeModeFromRoster,e.disableRealTimeModeFromRoster),i.enableLongOutgoing1To1SetupTimeoutForWeb=QV(t.enableLongOutgoing1To1SetupTimeoutForWeb,e.enableLongOutgoing1To1SetupTimeoutForWeb),i.checkAttendeeRoleInCreateContentSharing=QV(t.checkAttendeeRoleInCreateContentSharing,e.checkAttendeeRoleInCreateContentSharing),i.enableSpecificErrorCodesForCallEnd=QV(t.enableSpecificErrorCodesForCallEnd,e.enableSpecificErrorCodesForCallEnd),i.enableSplitConversationEndUrl=QV(t.enableSplitConversationEndUrl,e.enableSplitConversationEndUrl),i.enableFetchRequestWithKeepAlive=QV(t.enableFetchRequestWithKeepAlive,e.enableFetchRequestWithKeepAlive),i.enableFetchApi=QV(t.enableFetchApi,e.enableFetchApi),i.enableFetchApiForBeacon=QV(t.enableFetchApiForBeacon,e.enableFetchApiForBeacon),i})(this.signalingAgentConfig,e),this.signalingAgentConfig.ecsEtag=this.ecsProvider.ETag,this.signalingAgent.updateSignalingAgentConfig(this.getSignalingAgentConfig())}getSignalingAgentConfig(){return this.signalingAgentConfig.oneDsTelemetryLogger=this.telemetryLogger,this.signalingAgentConfig}},tH=p(Z),iH="blkVal",nH="length",rH="rdOnly",sH="notify",aH="warnToConsole",oH="throwInternal",lH="setDf",cH="watch",dH="logger",uH="apply",hH="push",gH="hdlr",pH="identifier",mH="isInitialized",fH="getPlugin",vH="time",SH="processNext",yH="unload",CH="createNew",TH="teardown",EH="messageId",bH="message",_H="isAsync",IH="diagLog",wH="_doTeardown",AH="update",PH="getNext",RH="setNextPlugin",MH="userAgent",DH="nodeType",kH="replace",OH="isChildEvt",NH="getCtx",LH="setCtx",xH="complete",FH="",UH="core",BH="extensionConfig",VH="processTelemetry",HH="getPerfMgr",$H=/-([a-z])/g,jH=/([^\w\d_$])/g,GH=/^(\d+[\w\d_$])/;function qH(e){var t=e;return t&&jv(t)&&(t=(t=(t=t[kH]($H,(function(e,t){return t.toUpperCase()})))[kH](jH,"_"))[kH](GH,(function(e,t){return"_"+t}))),t}function zH(e,t){return!(!e||!t)&&-1!==Ny(e,t)}function WH(e,t,i,n,r){e&&t&&i&&(!1!==r||Bv(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return Gv(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][uH](n,e)}}(i,n))}var KH="JSON",JH=null,YH=null;function QH(){return Boolean(typeof JSON===ov&&JSON||null!==qS(KH))}var ZH=4294967296,XH=4294967295,e$=123456789,t$=987654321,i$=!1,n$=e$,r$=t$;function s$(e){var t=0,i=qS("crypto")||qS("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&XH),0===t&&function(){var e=ZS();if(e&&(e[MH]!==YH||null===JH)){var t=((YH=e[MH])||FH).toLowerCase();JH=zH(t,"msie")||zH(t,"trident/")}return JH}()&&(i$||function(){try{var e=2147483647&Sy();!function(e){e<0&&(e>>>=0),n$=e$+e&XH,r$=t$-e&XH,i$=!0}((Math.random()*ZH^e)+e)}catch(e){}}(),t=function(){var e=((r$=36969*(65535&r$)+(r$>>16)&XH)<<16)+(65535&(n$=18e3*(65535&n$)+(n$>>16)&XH))>>>0&XH;return e>>>=0}()&XH),0===t&&(t=Math.floor(ZH*Math.random()|0)),e||(t>>>=0),t}var a$="3.3.1",o$="."+function(e){void 0===e&&(e=22);for(var t=s$()>>>0,i=0,n=FH;n[nH]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(s$()<<2&4294967295|3&t)>>>0,i=0);return n}(6),l$=0;function c$(e){return 1===e[DH]||9===e[DH]||!+e[DH]}function d$(e,t){return void 0===t&&(t=!1),qH(e+l$+++(t?"."+a$:FH)+o$)}function u$(e){return e&&qv(e)&&(e.isVal||e.fb||tS(e,"v")||tS(e,"mrg")||tS(e,"ref")||e.set)}function h$(e,t,i){var n,r=i.dfVal||Hv;if(t&&i.fb){var s=i.fb;zv(s)||(s=[s]);for(var a=0;a<s[nH];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,uS(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function g$(e,t,i){var n,r=i;return i&&u$(i)&&(r=h$(e,t,i)),r&&(u$(r)&&(r=g$(e,t,r)),zv(r)?(n=[])[nH]=r[nH]:_y(r)&&(n={}),n&&(iS(r,(function(i,r){r&&u$(r)&&(r=g$(e,t,r)),n[i]=r})),r=n)),r}function p$(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;u$(h)?(r=h.isVal,s=h.set,c=h[rH],d=h[iH],o=h.mrg,!(l=h.ref)&&Bv(l)&&(l=!!o),a=h$(e,t,h)):a=n,d&&e[iH](t,i);var g=!0,p=t[i];!p&&Vv(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?g$(e,t,a):a:(_y(u)||zv(a))&&o&&a&&(_y(a)||zv(a))&&iS(a,(function(t,i){p$(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[rH](t,i)}var m$=ry("[[ai_dynCfg_1]]"),f$=ry("[[ai_blkDynCfg_1]]"),v$=ry("[[ai_frcDynCfg_1]]");function S$(e){var t;return e&&(zv(e)?(t=[])[nH]=e[nH]:_y(e)&&(t={}),t)?(iS(e,(function(e,i){t[e]=S$(i)})),t):e}function y$(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[v$])||i[f$]||(n=_y(i)||zv(i))),n}function C$(e){pS("InvalidAccess:"+e)}var T$=["push","pop","shift","unshift","splice"],E$=function(e,t,i,n){e&&e[oH](3,108,"".concat(i," [").concat(t,"] failed - ")+hS(n))};function b$(e,t){var i=Xv(e,t);return i&&i.get}function _$(e,t,i,n){if(t){var r=b$(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===dy(r.h,t)&&r.h[hH](t),e.trk(t,r))},clr:function(e){var t=dy(r.h,e);-1!==t&&r.h.splice(t,1)}},s=!0,a=!1;function o(){s&&(a=a||y$(o,e,n),n&&!n[m$]&&a&&(n=w$(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},oS(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&C$("["+i+"] is read-only:"+hS(t)),s&&(a=a||y$(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){iS(n,(function(e){n[e]=l?l[e]:void 0}));try{iS(l,(function(t,i){_$(e,n,t,i)})),l=n}catch(t){E$((e.hdlr||{})[dH],i,"Assigning",t),a=!1}}else n&&n[m$]&&iS(n,(function(t){var i=b$(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&y$(o,e,l);!c&&d&&(l=w$(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function I$(e,t,i,n){if(t){var r=b$(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(_y(e)||zv(e)))try{e[f$]=!0}catch(e){}}(t)}catch(t){E$((e.hdlr||{})[dH],i,"Blocking",t)}try{_$(e,t,i,t[i]),r=b$(t,i)}catch(t){E$((e.hdlr||{})[dH],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function w$(e,t,i,n){try{iS(t,(function(i,n){_$(e,t,i,n)})),t[m$]||(sS(t,m$,{get:function(){return e[gH]}}),function(e,t,i){zv(t)&&cy(T$,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[uH](this,n);return w$(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){E$((e.hdlr||{})[dH],i,n,t)}return t}var A$="[[ai_",P$="]]";function R$(e,t,i){var n,r=function(e){if(e){var t=e[m$]||e;if(t.cfg&&(t.cfg===e||t.cfg[m$]===t))return t}return null}(t);if(r)return r;var s,a=d$("dyncfg",!0),o=t&&!1!==i?t:S$(t),l=((n={uid:null,cfg:o})[dH]=e,n[sH]=function(){s[sH]()},n.set=function(t,i,n){try{t=_$(s,t,i,n)}catch(t){E$(e,i,"Setting value",t)}return t[i]},n[lH]=function(e,t){return t&&iS(t,(function(t,i){p$(l,e,t,i)})),e},n[cH]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return oS(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return I$(s,e,t,(i={},i[0]=!0,i))[t]},n[rH]=function(e,t){var i;return I$(s,e,t,(i={},i[1]=!0,i))[t]},n[iH]=function(e,t){var i;return I$(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{Bv(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return oS(l,"uid",{c:!1,e:!1,w:!1,v:a}),w$(s=function(e){var t,i,n=ny(A$+"get"+e.uid+P$),r=ny(A$+"ro"+e.uid+P$),s=ny(A$+"rf"+e.uid+P$),a=ny(A$+"blkVal"+e.uid+P$),o=ny(A$+"dtl"+e.uid+P$),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(cy(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[lH].bind(e),ref:e.ref.bind(e),rdOnly:e[rH].bind(e)})}catch(t){var s=e[dH];throw s&&s[oH](1,107,hS(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c.cancel(),c=null;var t=[];if(cy(e,(function(e){if(e&&(e[o]&&(cy(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[hH](e)}})),l)try{u()}catch(e){t[hH](e)}t[nH]>0&&function(e,t){XV||(XV=vy("AggregationError",(function(e,t){t[nH]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw cy(t,(function(e,t){i+="\n".concat(t," > ").concat(hS(e))})),new XV(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[iH]=a,t[gH]=e,t.add=function(e){if(e&&e.h[nH]>0){l||(l=[]),c||(c=Vy((function(){c=null,u()}),0));for(var t=0;t<e.h[nH];t++){var i=e.h[t];i&&-1===dy(l,i)&&l[hH](i)}}},t[sH]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===dy(i,t)&&i[hH](t)}},i=t}(l),o,"config","Creating"),l}function M$(e,t,i,n){var r=R$(i,e||{},n);return t&&r[lH](r.cfg,t),r}function D$(e,t,i){var n=e[m$]||e;return!n.cfg||n.cfg!==e&&n.cfg[m$]!==n?(function(e,t){e?(e[aH](t),e[oH](2,108,t)):C$(t)}(i,"Not dynamic - "+hS(e)),M$(e,null,i)[cH](t)):n[cH](t)}var k$,O$=null;var N$="warnToConsole",L$={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},x$=((k$={})[0]=null,k$[1]="errorToConsole",k$[2]=N$,k$[3]="debugToConsole",k$);function F$(e){return e?'"'+e[kH](/\"/g,FH)+'"':FH}function U$(e,t){var i=typeof console!==lv?console:qS("console");if(i){var n="log";i[e]&&(n=e),Gv(i[n])&&i[n](t)}}var B$=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[EH]=e,r[bH]=(i?"AI: ":"AI (Internal): ")+e;var s=FH;QH()&&(s=(QH()?JSON||qS(KH):null).stringify(n));var a=(t?" message:"+F$(t):FH)+(n?" props:"+F$(s):FH);r[bH]+=a}return e.dataType="MessageData",e}();function V$(e,t){return(e||{})[dH]||new H$(t)}var H$=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};TC(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[EH];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[hH](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new B$(23,c,!1);e.queue[hH](u),1===t?e.errorToConsole(c):e[aH](c)}}}function d(e,i){var n=function(e){var t=O$;return t||!0===e.disableDbgExt||(t=O$||function(){var e=qS("Microsoft");return e&&(O$=e.ApplicationInsights),O$}()),t?t.ChromeDbgExt:null}(t||{});n&&n[IH]&&n[IH](e,i)}a=function(t){return D$(M$(t,L$,e).cfg,(function(e){var t=e.cfg;i=t.loggingLevelConsole,n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[oH]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new B$(n,r,o,a);if(s)throw hS(u);var h=x$[t]||N$;if(Bv(u[bH]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[EH];!l[g]&&i>=t&&(e[h](u[bH]),l[g]=!0)}else i>=t&&e[h](u[bH]);c(t,u)}},e.debugToConsole=function(e){U$("debug",e),d("warning",e)},e[aH]=function(e){U$("warn",e),d("warning",e)},e.errorToConsole=function(e){U$("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[yH]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function $$(e,t,i,n,r,s){void 0===s&&(s=!1),function(e){return e||new H$}(e)[oH](t,i,n,r,s)}var j$="ctx",G$="ParentContextKey",q$="ChildrenContextKey",z$=function(){function e(t,i,n){var r,s=this;s.start=Sy(),s.name=t,s[_H]=n,s[OH]=function(){return!1},Gv(i)&&oS(s,"payload",{g:function(){return!r&&Gv(i)&&(r=i(),i=null),r}}),s[NH]=function(t){return t?t===e[G$]||t===e[q$]?s[t]:(s[j$]||{})[t]:null},s[LH]=function(t,i){t&&(t===e[G$]?(s[t]||(s[OH]=function(){return!0}),s[t]=i):t===e[q$]?s[t]=i:(s[j$]=s[j$]||{})[t]=i)},s[xH]=function(){var t=0,i=s[NH](e[q$]);if(zv(i))for(var n=0;n<i[nH];n++){var r=i[n];r&&(t+=r[vH])}s[vH]=Sy()-s.start,s.exTime=s[vH]-t,s[xH]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),W$="CoreUtils.doPerf";function K$(e,t,i,n,r){if(e){var s=e;if(s[HH]&&(s=s[HH]()),s){var a=void 0,o=s[NH](W$);try{if(a=s.create(t(),n,r)){if(o&&a[LH]&&(a[LH](z$[G$],o),o[NH]&&o[LH])){var l=o[NH](z$[q$]);l||(l=[],o[LH](z$[q$],l)),l[hH](a)}return s[LH](W$,a),i(a)}}catch(e){a&&a[LH]&&a[LH]("exception",e)}finally{a&&s.fire(a),s[LH](W$,o)}}}return i()}function J$(){var e=function(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=FH,n=0;n<4;n++)i+=t[15&(e=s$())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&s$())|0];return DS(i,0,8)+DS(i,9,4)+"4"+DS(i,13,3)+r+DS(i,16,3)+DS(i,19,12)}();return MS(e,0,8)+"-"+MS(e,8,12)+"-"+MS(e,12,16)+"-"+MS(e,16,20)+"-"+MS(e,20)}var Y$=function(){var e={id:d$("_aiData-plugin."+a$),accept:function(e){return c$(e)},get:function(t,i,n,r){var s=t[e.id];return s?s[qH(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{c$(t)&&oS(t,e.id,{e:!1,v:i})}catch(e){}}return i}(e,t))[qH(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return e}();function Q$(e){return Y$.get(e,"state",{},!0)}var Z$,X$="_hasRun",ej="_getTelCtx",tj=0;function ij(e,t,i,n){var r=null,s=[];t||(t=M$({},null,i[dH])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[fH]()===i)return e;e=e[PH]()}return aj([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[PH]():null,!e){var t=s;t&&t[nH]>0&&(cy(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){$$(i[dH],2,73,"Unexpected Exception during onComplete - "+hS(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return V$(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&iS(i,(function(e,i){if(Vv(n[e])){var r=t.cfg[e];!r&&Vv(r)||(n[e]=r)}p$(t,n,e,i)})),t[lH](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&Vv(s[i])?!a[i]&&Vv(a[i])||(r=a[i]):r=s[i],r||!Vv(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[fH]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[hH]({func:e,self:Bv(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[BH];!s&&i&&(s={}),r[BH]=s,(s=t.ref(r,BH))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function nj(e,t,i,n){var r=M$(t),s=ij(e,r,i,n),a=s.ctx;return a[SH]=function(e){var t=s._next();return t&&t[VH](e,a),!t},a[CH]=function(e,t){return void 0===e&&(e=null),zv(e)&&(e=aj(e,r.cfg,i,t)),nj(e||a[PH](),r.cfg,i,t)},a}function rj(e,t,i){var n=M$(t.config),r=ij(e,n,t,i),s=r.ctx;return s[SH]=function(e){var t=r._next();return t&&t[yH](s,e),!t},s[CH]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=aj(e,n.cfg,t,i)),rj(e||s[PH](),t,i)},s}function sj(e,t,i){var n=M$(t.config),r=ij(e,n,t,i).ctx;return r[SH]=function(e){return r.iterate((function(t){Gv(t[AH])&&t[AH](r,e)}))},r[CH]=function(e,i){return void 0===e&&(e=null),zv(e)&&(e=aj(e,n.cfg,t,i)),sj(e||r[PH](),t,i)},r}function aj(e,t,i,n){var r=null,s=!n;if(zv(e)&&e[nH]>0){var a=null;cy(e,(function(e){if(s||n!==e||(s=!0),s&&e&&Gv(e[VH])){var o=function(e,t,i){var n,r=null,s=Gv(e[VH]),a=Gv(e[RH]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=Q$(e);return!n[TH]&&!n.disabled&&(a&&e[RH](r),e[VH](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[SH](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=Q$(e),s=e[UH]||r[UH];!e||s&&s!==t.core()||r[TH]||(r[UH]=null,r[TH]=!0,r[mH]=!1,e[TH]&&!0===e[TH](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[_H])||t[SH](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=Q$(e),s=e[UH]||r[UH];!e||s&&s!==t.core()||r[TH]||e[AH]&&!0===e[AH](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[SH](i)},_id:n=e?e[pH]+"-"+e.priority+"-"+tj++:"Unknown-0-"+tj++,_setNext:function(e){r=e}};function l(){var n;return e&&Gv(e[ej])&&(n=e[ej]()),n||(n=nj(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[pH]:"TelemetryPluginChain",d=t[X$];return d||(d=t[X$]={}),t.setNext(r),e&&K$(t[UH](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:FH;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||$$(t[IH](),1,73,"Plugin ["+c+"] failed during "+s+" - "+hS(e)+", run flags: "+hS(d))}}),a,o),l}return CS(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?aj([n],t,i):r}var oj,lj="getPlugin",cj=((Z$={})[BH]={isVal:function(e){return!Vv(e)},v:{}},Z$),dj=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||nj(null,{},a[UH]);t=n&&n[lj]?r[CH](null,n[lj]):r[CH](null,n)}return t}function l(e,t,r){M$(e,cj,V$(t)),!r&&t&&(r=t.getProcessTelContext()[PH]());var s=n;n&&n[lj]&&(s=n[lj]()),a[UH]=t,i=nj(r,e,t,s)}function c(){t=!1,a[UH]=null,i=null,n=null,s=function(){var e=[];return{run:function(t){var i=e;e=[],cy(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){$$(t,2,73,"Unloading:"+hS(e))}}))},add:function(t){t&&ly(e,t)}}}(),r=function(){var e=[];return{add:function(t){t&&e[hH](t)},run:function(t,i){cy(e,(function(e){try{e(t,i)}catch(e){$$(t[IH](),2,73,"Unexpected error calling unload handler - "+hS(e))}})),e=[]}}}()}c(),TC(e,a,(function(e){e.initialize=function(e,i,n,r){l(e,i,r),t=!0},e[TH]=function(t,i){var a,o=e[UH];if(o&&(!t||o===t[UH]())){var l,d=!1,u=t||rj(null,o,n&&n[lj]?n[lj]():n),h=i||((a={reason:0})[_H]=!1,a);return e[wH]&&!0===e[wH](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[IH]()),!0===l&&u[SH](h),c())}},e[AH]=function(t,i){var r=e[UH];if(r&&(!t||r===t[UH]())){var s,a=!1,o=t||sj(null,r,n&&n[lj]?n[lj]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[PH]()))}},WH(e,"_addUnloadCb",(function(){return r}),"add"),WH(e,"_addHook",(function(){return s}),"add"),oS(e,"_unloadHooks",{g:function(){return s}})})),a[IH]=function(e){return o(e)[IH]()},a[mH]=function(){return t},a.setInitialized=function(e){t=e},a[RH]=function(e){n=e},a[SH]=function(e,t){t?t[SH](e):n&&Gv(n[VH])&&n[VH](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),uj="timings",hj="processTelemetryStart";function gj(e){if(e){var t=Ny(e,"-");if(t>-1)return kS(e,t)}return""}(oj={})[0]=0,oj[2]=6,oj[1]=1,oj[3]=7,oj[4098]=6,oj[4097]=1,oj[4099]=7;var pj,mj,fj=ky;function vj(e){return e>0}function Sj(e){return Kv(e)&&e>=1&&e<=2}(mj=pj||(pj={}))[mj.LocalStorage=1]="LocalStorage",mj[mj.SessionStorage=2]="SessionStorage",mj[mj.IndexedDb=3]="IndexedDb";var yj="result",Cj="DBError: Unable to open database",Tj="Database is not open",Ej="DBError: Failed to delete the database",bj=["indexedDB"],_j=Gv,Ij=jv,wj=0;function Aj(e,t){qS("QUnit")&&console&&console.log(" ["+function(e){return e&&e.toISOString()||""}(new Date)+"]: IndexedDbHelper ["+e+"] "+t)}function Pj(e,t,i){e&&e.warnToConsole("IndexedDbHelper ["+t+"] "+i)}function Rj(e,t,i,n){return function(r){i(new Error(t)),Aj(e,"["+n+"] event rejected")}}var Mj=[];function Dj(e,t){for(var i=null,n=0;n<Mj.length;n++)if((i=Mj[n]).name===e)return i;return i={name:e,sch:yE(eE,"IndexedDbHelper["+e+"]"),dbHdl:[],add:function(t){i.dbHdl.push(t),Aj(e,"- dbOpened (add) -- hdls ["+i.dbHdl.length+"]")},remove:function(t){for(var n=i.dbHdl,r=0;r<n.length;r++)if(n[r]===t){n.splice(r,1);break}Aj(e,"- dbClosed (remove) -- hdls ["+i.dbHdl.length+"]")},isOpen:function(){return i.dbHdl.length>0},openHdl:function(){return i.dbHdl.length>0?i.dbHdl[0]:null}},Mj.push(i),i}var kj=function(){function e(t){var i=wj++,n=0;TC(e,this,(function(e){var r=function(){var e=GS()||{},t=null;if(e)try{for(var i=0;i<bj.length;i++)if((t=e[bj[i]])&&_j(t.open))return t}catch(e){t=null}return t||null}()||null;function s(e,r,s){var l=e.db,c=n++;Aj(e.dbName,"["+i+":"+c+"] txn.open - "+r+" -- "+s);var d=l.transaction(r,"readwrite");return d.onabort=function(){Pj(t,e.dbName,"["+i+":"+c+"] txn.onabort - "+r+" -- "+s+" -- "+hS(d.error))},d.onerror=function(){Pj(t,e.dbName,"["+i+":"+c+"] txn.onerror - "+r+" -- "+s)},d.oncomplete=function(){Aj(e.dbName,"["+i+":"+c+"] txn.oncomplete - "+r+" -- "+s)},{db:e,store:d.objectStore(r),tx:d,tbl:r,openCursor:function(t,i){return o(e,r,t,i)},newTransaction:function(t){return a(e,r,t)}}}function a(e,t,i){if(!e||!e.db)return sE(new Error(Tj));try{var n=i(s(e,t,"openStore"));return Qv(n)?n:rE(n)}catch(e){return sE(e)}}function o(e,t,i,n){if(!e||!e.db)return sE(new Error(Tj));var r=null;return i&&Ij(i)?r=new Oj(i):i&&i.isMatch&&(r=i),eE((function(i,a){var o=[],l=null,c=null;r&&r.keyRange&&(c=r.keyRange());var d=s(e,t,"openCursor");(l=c?d.store.openCursor(c):d.store.openCursor()).onerror=Rj(d.db.dbName,"DBError: Failed to Open Cursor",a,"openCursor"),l.onsuccess=function(e){var t=e.target[yj];if(t){var s={store:d,cursor:t,continue:function(){t.continue()},done:function(){i(o)}},l=t.value;if(!r||r.isMatch(l))if(n)try{switch(n(s,l,o)){case 2:i(o);break;case 1:break;default:s.continue()}}catch(e){a(e)}else o.push(l),s.continue();else s.continue()}else i(o)}}))}function l(e,t,i,n){return Dj(e).sch.queue(i,t,n)}e.isAvailable=function(){return!!r},e.openDb=function(e,i,n,s){return l(e,"openDb",(function(l){return eE((function(c,d){var u=!1;function h(t,n,r,s,l){var c={db:n,dbName:e,dbVersion:i,ctx:null,isNew:s,txn:r?r.transaction:null};return l||(c.openStore=function(e,t){return a(c,e,t)},c.openCursor=function(e,t,i){return o(c,e,t,i)}),c}function g(i,r){var s=Dj(e);s.add(i),i.onabort=function(n){Pj(t,e,"onabort -- closing the Db"),s.remove(i)},i.onerror=function(n){Pj(t,e,"onerror -- closing the Db"),s.remove(i)},i.onclose=function(n){Pj(t,e,"onclose -- closing the Db"),s.remove(i)},i.onversionchange=function(n){Pj(t,e,"onversionchange -- force closing the Db"),i.close(),s.remove(i)};var a,o=null;s.dbHdl.length>0&&(o=s.dbHdl[0]),a=h(0,o,r,u);try{HT(n(a),c,d)}catch(e){d(e)}}var p=Dj(e);if(null==r)d(new Error("No available storage factory"));else if(p.isOpen()){var m=h(0,p.openHdl(),null,!1);HT(n(m),c,d)}else{var f=r.open(e,i);f.onblocked=function(i){Pj(t,e,"Db Open Blocked event ["+l+"] - "+(f.error||"")),d(new Error(Cj))},f.onerror=function(i){Pj(t,e,"Db Open Error event ["+l+"] - "+(f.error||"")),d(new Error(Cj))},f.onupgradeneeded=function(t){Aj(e,"Db Open Create/Upgrade needed event ["+l+"]");try{var i=t.target[yj];if(!i)return void d(new Error(Cj));!function(e,t){var i=h(0,e,t,!0,!0);if(s)u=!0,VT(s(i),(function(e){if(e.rejected)try{t.transaction&&t.transaction.abort()}finally{d(e.reason)}else i.txn||(i.txn=t.transaction)}));else try{t.transaction&&t.transaction.abort()}finally{d(new Error("DBError: Database upgrade required"))}}(i,f)}catch(t){Rj(e,Cj,d,l)(t)}},f.onsuccess=function(e){var t=e.target[yj];t?g(t,f):d(new Error(Cj))}}}))}))},e.closeDb=function(e){l(e,"closeDb",(function(t){var i=Dj(e),n=i.dbHdl,r=n.length;if(r>0){for(var s=0;s<r;s++)n[s].close();i.dbHdl=[]}return 1})).catch((function(e){}))},e.deleteDb=function(e){return null!=r&&l(e,"deleteDb",(function(i){var n=Dj(e),s=n.dbHdl,a=s.length;if(a>0){Pj(t,e,"Db is open ["+a+"] force closing");for(var o=0;o<a;o++)s[o].close();n.dbHdl=[]}return eE((function(n,s){setTimeout((function(){try{Aj(e,"["+i+"] starting");var a=r.deleteDatabase(e);a.onerror=function(n){Pj(t,e,"["+i+"] error!!"),s(new Error(Ej))},a.onblocked=function(n){Pj(t,e,"["+i+"] blocked!!"),s(new Error(Ej))},a.onupgradeneeded=function(n){Pj(t,e,"["+i+"] upgrade needed!!"),s(new Error(Ej))},a.onsuccess=function(t){Aj(e,"["+i+"] complete"),n(!0)},Aj(e,"["+i+"] started")}catch(n){Pj(t,e,"["+i+"] threw - "+n),s(new Error(Ej+" - "+n))}}),0)}))}))},e.getDbDetails=function(e){return l(e,"getDbDetails",(function(t){return null!=r&&r.databases?eE((function(t,i){r.databases().then((function(n){for(var r=0;r<n.length;r++)if(n[r].name===e)return void t(n[r]);i(new Error("DBError: Database does not exist"))}),i)})):sE(new Error("DBError: Feature not supported"))}),2e3)}}))}return e.__ieDyn=1,e}(),Oj=function(){function e(t){var i=[],n=null;TC(e,this,(function(e){e.keyRange=function(){return n},e.parseQuery=function(t){if(i=[],t)for(var r=t.split(";"),s=0;s<r.length;s++){var a=r[s],o=a.indexOf("=");if(-1!==o){var l=a.substring(0,o),c=a.substring(o+1);0===l.indexOf("#")&&(l=l.substring(1),n||(n=IDBKeyRange.bound(c,c+"￿"))),e.startsWith(l,c)}}},e.startsWith=function(e,t){i.push({name:e,value:t,type:0})},e.contains=function(e,t){i.push({name:e,value:t,type:1})},e.isMatch=function(e){if(!i||0===i.length)return!0;if(!e)return!1;for(var t=0;t<i.length;t++){var n=i[t],r=e[n.name];if(r)if(0===n.type){if(0!==r.indexOf(n.value))return!1}else if(1===n.type&&-1===r.indexOf(n.value))return!1}return!0},t&&e.parseQuery(t)}))}return e.__ieDyn=1,e}(),Nj=6048e5,Lj="DBError: Unable to add event",xj="Evts",Fj="iKey",Uj=Sj;function Bj(){return(new Date).getTime()}function Vj(e){return e.openStore(Fj,(function(t){return eE((function(i,n){var r={iKey:e.ctx.iKey,tm:Bj()},s=t.store.put(r);s.onsuccess=function(e){i(s.result.toString())},s.onerror=function(e){n(new Error(Lj))},s.onerror=function(e,t){return function(e){return t(new Error("DBError: Unable to update iKey"))}}(0,n)}))}))}function Hj(e){for(var t=[],i=2;i>=1;i--)for(var n=0;n<e.length;n++){var r=e[n];r&&r.evt.persistence===i&&t.push(r.evt)}return t}function $j(e){return function(t){return e.continue()}}function jj(e){var t=e.cursor.delete();return t.onerror=$j(e),t.onsuccess=$j(e),1}function Gj(e,t,i){return e.openCursor(xj,t,(function(e,t,n){return i(t)?(n.push(t),jj(e)):0}))}function qj(e,t){return eE((function(i,n){(function(e){return eE((function(t,i){var n=!1;e.openCursor(Fj,null,(function(e,t,i){var r=t.tm;return Bj()-r<Nj?0:(n=!0,2)})).then((function(){if(n){var r={};Gj(e,null,(function(e){if(!e||!e.evt||!e.evt.iKey)return!0;var t=e.tm;return Bj()-t>Nj||(r[e.evt.iKey]=1,!1)})).then((function(){var n=[];e.openCursor(Fj,null,(function(e,t,i){var s=t.tm;return Bj()-s<Nj||r[t.iKey]?0:(n.push(t),jj(e))})).then((function(){t(n)}),i)}),i)}else t([])}),i)}))})(e).then((function(){(function(e,t){return e.openCursor(xj,"#key="+e.ctx.iKeyPrefix(),(function(i,n){var r=n.key;if(0===r.indexOf(e.ctx.iKeyPrefix())&&-1===r.indexOf(e.ctx.evtKeyPrefix())&&function(e,t){var i=e.tm;return Bj()-i>t}(n,t)){n.key=e.ctx.evtKeyPrefix()+n.id;var s=i.store.store.put(n);return s.onerror=$j(i),s.onsuccess=function(e){try{jj(i)}catch(e){i.continue()}},1}return 0}))})(e,t).then(i,i)}),n)}))}var zj=function(){function e(t,i){TC(e,this,(function(e){var n=null,r=null,s="Unknown",a=null,o=null,l=null,c=-1,d=0,u=6e5;function h(e){return n.openDb(r,1,(function(t){return eE((function(i,n){var r={iKey:s,storageId:a,iKeyPrefix:function(){return o},evtKeyPrefix:function(){return l}};t.ctx=r,HT(Vj(t),(function(){HT(e(t),i,n)}),n)}))}),(function(e){return eE((function(t,i){(function(e){e.objectStoreNames.contains(xj)||e.createObjectStore(xj,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),e.objectStoreNames.contains(Fj)||e.createObjectStore(Fj,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})})(e.db),t()}))}))}function g(e,t,i){return eE((function(n,r){function s(t,i){(function(e,t){return eE((function(i,n){var r=0,s=e.ctx.evtKeyPrefix();function a(){i(r)}function o(e,t){return eE((function(i){var n=e.store.delete(t.key);n.onsuccess=function(e){r++,i()},n.onerror=function(e){i()}}))}e.openCursor(xj,"#key="+s,(function(e,i,n){return i.evt.persistence<=t&&0===i.key.indexOf(s)&&(function(e,t){for(var i=0;i<e.length;i++)if(t.tm<e[i].tm)return void e.splice(i,0,t);e.push(t)}(n,i),n.length>10&&n.splice(n.length-1,1)),0})).then((function(t){0!==t.length?e.openStore(xj,(function(e){for(var i=[],n=0;n<t.length;n++)i.push(o(e,t[n]));return nE(i).then(a,a)})):a()}),(function(){i(0)}))}))})(e,t).then((function(e){e>0&&(d-=e),i(e)}),(function(e){i(0)}))}function a(e){n(t.evt)}function o(){e.openStore(xj,(function(o){var l=o.store.put(t);l.onsuccess=function(r){i&&Vj(e).then(a,a),d++,n(t.evt)},l.onerror=function(a){function o(i){0===i&&r(new Error(Lj)),g(e,t,!1).then((function(e){n(t.evt)}),(function(){r(new Error(Lj))}))}i?s(1,(function(e){e>0?o(e):t.evt.persistence>=2?s(2,(function(e){o(e)})):r(new Error(Lj))})):r(new Error(Lj))}}))}c>0&&d>=c?s(1,(function(e){0===e?t.evt.persistence>=2?s(2,(function(e){o()})):r(new Error(Lj)):o()})):o()}))}e.id=t,e.initialize=function(t){var d=t.itemCtx.diagLog();if(!(n=new kj(d)).isAvailable())return n=null,!1;var g=t.itemCtx.getCfg(),p=t.storageConfig;s=g.instrumentationKey||s,a=e.id||t.id||J$(),l=(o=s+"::")+a+"::",u=p.accessThresholdInMs||u;var m=D$(p,(function(){c=p.maxStorageItems;var t=p.indexedDbName;r&&t!==r&&r&&VT(e.clear(),(function(e){r=t,h((function(e){return e.isNew?[]:qj(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null}))})),r=t}));return i&&i.add(m),h((function(e){return e.isNew?[]:qj(e,u)})).then((function(e){}),(function(e){d.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),n=null})),!0},e._getDbgPlgTargets=function(){return[r]},e.supportsSyncRequests=function(){return!1},e.getAllEvents=function(){return null!=n&&n.isAvailable()?h((function(e){return eE((function(t,i){(function(e,t){return e.openCursor(xj,t,(function(e,t,i){return i.push(t),0}))})(e,"#key="+e.ctx.evtKeyPrefix()).then((function(e){d=e.length,t(Hj(e))}),i)}))})):[]},e.addEvent=function(e,t,i){return null!=n&&n.isAvailable()?(t.id=t.id||J$(),Uj(t.persistence)||(t.persistence=1),h((function(i){var n=e||t.id,r={key:i.ctx.evtKeyPrefix()+n,id:n,evt:t,tm:Bj(),v:1};return g(i,r,!0)}))):t},e.removeEvents=function(e){if(null==n||!n.isAvailable())return[];var t=[];return eE((function(i,n){h((function(i){return i.openCursor(xj,"#key="+i.ctx.iKey,(function(i,n,r){if(-1!==function(e,t){for(var i=t.length,n=0;n<i;n++)if(e===t[n].id)return n;return-1}(n.id,e)){var s=i.cursor.delete();return s.onerror=$j(i),s.onsuccess=function(){t.push(n.evt),i.continue()},1}return 0}))})).then((function(e){d-=t.length,i(t)}),(function(e){d-=t.length,i(t)}))}))},e.clear=function(){return null!=n&&n.isAvailable()?eE((function(e,t){h((function(e){return Gj(e,"#key="+e.ctx.evtKeyPrefix(),(function(t){return 0===t.key.indexOf(e.ctx.evtKeyPrefix())}))})).then((function(t){d=0,e(Hj(t))}),t)})):[]},e.moveStaleEvents=function(){h((function(e){return qj(e,u)}))},e.teardown=function(){n&&n.closeDb(r)}}))}return e.__ieDyn=1,e}(),Wj="Version";function Kj(e,t){if(e)for(var i=vS(e),n=0;n<i.length;n++){var r=i[n];if(!t(e[r],r))break}}function Jj(e){var t=!0;return Kj(e,(function(e,i){return e&&(t=!1),t})),t}function Yj(e,t){for(var i=1,n=0,r=function(){var e=[],r=t[i];if(Kj(r,(function(t,i){return e.push(i),++n<10})),n>0){for(var s=0;s<e.length;s++)delete r[e[s]];return{value:!0}}i++};i<=e&&n<10;){var s=r();if("object"==typeof s)return s.value}return n>0}var Qj=Sj,Zj=function(){function e(t,i,n){TC(e,this,(function(e){var r=null,s="AWTEvents",a=null,o=null,l=null,c=5e6,d=6e5,u=null,h=null;function g(e,t){return{key:e,db:t}}function p(e,t){void 0===t&&(t=!0);var i=null;if(r){var n=r.getItem(e);if(n)try{i=JSON.parse(n)}catch(t){r.removeItem(e)}}return t&&!i&&(i={events:{1:{},2:{},3:{}},lastAccessTime:0}),g(e,i)}function m(e,t){void 0===t&&(t=!0);var i=!0,n=e.db;if(n){t&&(n.lastAccessTime=(new Date).getTime());for(var s=1;s<=2;s++)if(!Jj(n.events[s])){i=!1;break}}try{if(i)r&&r.removeItem(e.key);else{var a=JSON.stringify(n);if(a.length>c)return!1;r&&r.setItem(e.key,a)}}catch(e){return!1}return!0}function f(e){var t=[],i=p(e,!1),n=i.db;if(n){var s=n.events;try{for(var a=1;a<=2;a++)Kj(s[a],(function(e,i){return e&&t.push(e),!0}))}catch(e){}r&&r.removeItem(i.key)}return t}function v(){if(r){for(var e=r.getItem(u),t=[],i=p(h),n=!1,a=0;a<r.length;a++){var o=r.key(a);if(0===o.indexOf(s)&&o!==u){if("3"!==e){t.push(g(o,null));continue}var c=p(o,!1),f=c.db;if(f){if((new Date).getTime()-f.lastAccessTime>d){for(var v=1,S=function(){var e=f.events[v],t=i.db.events[v];Kj(e,(function(i,n){return(gj(i.iKey)||i.iKey)===l&&(t[n]=i,delete e[n]),!0})),v++};v<=2;)S();n=!0,t.push(c)}}else t.push(g(o,null))}}for(a=0;a<t.length;a++)m(t[a],!1);n&&m(i),r.setItem(u,"3")}}e.id=i,r=function(e){var t=GS()||{},i=null;try{if(i=t[e]){var n="__storage_test__";i.setItem(n,n),i.removeItem(n)}}catch(e){(function(e,t){var i=!1;return t instanceof DOMException&&(22!==t.code&&"QuotaExceededError"!==t.name&&1014!==t.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||e&&0!==e.length&&(i=!0)),i})(i,e)||(i=null)}return i}(t)||null,e._getDbgPlgTargets=function(){return[s,c]},e.initialize=function(t){if(!r)return!1;var i=t.storageConfig;a=e.id||t.id||J$(),o=t.itemCtx.getCfg().instrumentationKey,l=gj(o)||o,d=i.accessThresholdInMs?i.accessThresholdInMs:d;var g=D$(i,(function(){c=i.maxStorageSizeInBytes;var t=i.storageKey;s&&t!==s&&VT(e.clear(),(function(e){h=(s=t)+"."+a,u=s+Wj,v()}))}));return n&&n.add(g),s=i.storageKey,h=s+"."+a,u=s+Wj,v(),!0},e.supportsSyncRequests=function(){return!0},e.getAllEvents=function(){try{var e=[],t=p(h,!1).db;if(t)for(var i=t.events,n=2;n>=1;n--)Kj(i[n],(function(t){return t&&(gj(t.iKey)||t.iKey)===l&&e.push(t),!0}));return e}catch(e){return sE(e)}},e.addEvent=function(e,t,i){try{var n=p(h);t.id=t.id||J$(),Qj(t.persistence)||(t.persistence=1);for(var r=t.persistence,s=t.id,a=n.db.events;;){if(a[r][s]=t,m(n))return t;if(delete a[r][s],!Yj(r,a))return sE(new Error("Unable to free up event space"))}}catch(e){return sE(e)}},e.removeEvents=function(e){try{var t=p(h,!1),i=t.db;if(i){var n=i.events;try{for(var r=0;r<e.length;++r){var s=e[r];delete n[s.persistence][s.id]}if(m(t))return e}catch(e){}e=f(t.key)}return e}catch(e){return sE(e)}},e.clear=function(){try{var e=[],t=p(h,!1),i=t.db;if(i){for(var n=i.events,r=function(t){var i=n[t];Kj(i,(function(t){return t&&(gj(t.iKey)||t.iKey)===l&&(delete i[t.id],e.push(t)),!0}))},s=2;s>=1;s--)r(s);m(t)}return e}catch(e){return sE(e)}},e.teardown=function(){try{var e=p(h,!1),t=e.db;t&&(t.lastAccessTime=0,m(e,!1))}catch(e){}},e.moveStaleEvents=function(){v()}}))}return e.__ieDyn=1,e}(),Xj=Sj,eG=SS({maxStorageSizeInBytes:{isVal:vj,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:Xj,v:1},providers:[pj.LocalStorage,pj.IndexedDb],indexedDbName:"AppInsightEvents.1",maxStorageItems:{isVal:vj,v:void 0}}),tG=function(e){function t(){var i=e.call(this)||this;return i.identifier="LocalStorage",i.priority=1009,i.version="4.3.1",TC(t,i,(function(e,t){var i,n,r,s;function a(){i=!1,n=!1,r=null,s=[]}function o(e,t){r||(r=yE(eE,"LocalStorage")),r.queue((function(e){return t(e)}),e).catch((function(e){}))}function l(t){K$(e.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){o("sendToNext",(function(i){return VT(t.provider.getAllEvents(),(function(i){for(var n=i.value||[],r=0;r<n.length;r++)try{var s=n[r];(gj(s.iKey)||s.iKey)===t.tenantId&&e.processNext(s,t.coreRootCtx.createNew())}catch(e){}}))}))}),(function(){return{iKeyConfig:t}}))}function c(t,i){K$(e.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){o("removeEvents",(function(e){var n=[];if(cy(i,(function(e){(gj(e.iKey)||e.iKey)===t.tenantId&&n.push(e)})),n.length>0)return VT(t.provider.removeEvents(n),(function(e){}))}))}),(function(){return{iKeyConfig:t,events:i}}))}function d(t){var i=new zj(void 0,e._unloadHooks);return i.initialize(t)||(i=null),i}function u(t,i){var n=new Zj(t,void 0,e._unloadHooks);return n.initialize(i)||(n=null),n}function h(e){for(var t=e.storageConfig.providers,i=null,n=0;!i&&n<t.length&&n<5;)switch(t[n++]){case pj.LocalStorage:i=u("localStorage",e);break;case pj.SessionStorage:i=u("sessionStorage",e);break;case pj.IndexedDb:i=d(e)}return i}function g(t,i,n,r){var a=!1;if(cy(s,(function(e){if(e.iKey===t.instrumentationKey)return a=!0,-1})),!a){var o=null;e._addHook(D$(t,(function(n){var r=nj(null,n.cfg,i);o=r.getExtCfg(e.identifier,eG);var a=!1,d=null,u=t.instrumentationKey;if(cy(s,(function(e){if(e.iKey===u)return a=!0,d=e,-1})),a&&d){var p=o.providers,m=d.preProviders;(function(e,t){if(e.length!==t.length)return!1;var i=!0;return cy(e,(function(e,n){if(e!==t[n])return i=!1,-1})),i})(p,m)||VT(g.clear(),(function(e){if(!e.rejected)try{var t=s.indexOf(d);-1!==t&&s.splice(t,1);var n=h(d.providerContext);d.provider=n,d.preProviders=p.slice();var r=d.preListener;r&&i.removeNotificationListener(r);var a={eventsSent:function(e){c(d,e)},eventsDiscarded:function(e,t){c(d,e)}};d.preListener=a,s.push(d),i.addNotificationListener(a),l(d)}catch(e){}}))}})));var d=function(t,i,n,r){t&&(t.extensionConfig=t.extensionConfig||[]),!r&&i&&(r=i.getProcessTelContext().getNext());var s=null,a=e._getTelCtx().getNext();return a&&(s=a.getPlugin()),nj(r,t,i,s)}(t,i,0,r),u={itemCtx:d,storageConfig:o,id:e.id};if(!jv(t.instrumentationKey))return;var g=h(u),p={iKey:t.instrumentationKey,tenantId:gj(t.instrumentationKey)||t.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:d,providerContext:u,provider:g,preProviders:o.providers.slice()};if(g){Xj(o.minPersistenceLevel||-1)&&(p.minPersistenceCacheLevel=o.minPersistenceLevel);var m={eventsSent:function(e){c(p,e)},eventsDiscarded:function(e,t){c(p,e)}};p.preListener=m,s.push(p),i.addNotificationListener(m),l(p)}else s.push(p)}}a(),e.initialize=function(e,n,s,a){K$(n,(function(){return"LocalStorageChannel.initialize"}),(function(){i||(t.initialize(e,n,s),t.setInitialized(!1),i=!0,r=yE(eE,"LocalStorage")),g(e,n,0,a)}),(function(){return{coreConfig:e,core:n,extensions:s,pluginChain:a}}))},e.processTelemetry=function(t,r){var a=t;if(i&&!n){r=e._getTelCtx(r),function(e,t){var i=e;i[uj]=i[uj]||{},i[uj][hj]=i[uj][hj]||{},i[uj][hj][t]=fj()}(t,e.identifier);var l=null;cy(s,(function(e){e.iKey===t.iKey&&(l=e)}));var c=l?l.provider:null;if(a.sync||!c)return void e.processNext(a,r);a.id=a.id||J$(),Sj(a.persistence)||(a.persistence=1),function(e,t){return!(t.sync||t.persistence<e.minPersistenceCacheLevel)}(l,a)&&o("processTelemetry",(function(e){return c.addEvent(a.id,a,r)}))}e.processNext(a,r)},e.pause=function(){n=!0},e.resume=function(){K$(e.core,(function(){return"LocalStorageChannel:resume"}),(function(){n=!1,cy(s,(function(e){e.provider&&l(e)}))}))},e._doTeardown=function(e,t){cy(s,(function(e){var t=e.provider;t&&t.teardown()})),a()},e.flush=function(e,t,i){},e._getDbgPlgTargets=function(){return[s]},e._sendStale=function(e){cy(s,(function(t){if(t&&t.iKey===e&&t.provider)return t.provider.moveStaleEvents(),l(t),-1}))}})),i}return jy(t,e),t.__ieDyn=1,t}(dj),iG="LocalStorage",nG=class{constructor(e,t,i,n,r,s){this.logger=e,this.configProvider=t,this.clientInfo=i,this.contextProvider=n,this.accountCollectorURL=r,this.envOverride=s,this.manager=new LM,this.managerConfig=this.createConfigForManager(),this.currentTransmitProfile=Gi.REPORTING_PROFILE.RT_PROFILE,this.initManager(),this.uiVersion=this.getUiVersion(),this.configProvider.on("configUpdated",(()=>this.updateChannelConfig()))}createLogger(e,t){return new rG(e,this.manager,this.logger,this.configProvider,this.uiVersion,t,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 e=this.clientInfo.match(/^.*?\/(\d+\/)(.*?)\/.*$/);return e?e[1]+e[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:(e,t)=>this.logDiscardedEvents(e,t),eventsSent:e=>this.logSentEvents(e)}),this.setTransmitProfile()}initLocalStorageChannel(){if(!this.configProvider.config.useLocalStorageForOneDs)return;const e=new tG;this.managerConfig.channels.push([e]);const t={storageKey:"TsCalling",accessThresholdInMs:this.configProvider.config.oneDSLocalStorage.accessThresholdInMs??6e5};this.managerConfig.extensionConfig[iG]=t}logDiscardedEvents(e,t){let i="discarded events:";e.forEach((e=>i=`${i+e.name};`)),this.logger.info(`${i} reason:${t}`)}logSentEvents(e){let t=`sent events: ${e[0]?.data?.CorrelationId&&un("value",e[0].data.CorrelationId)}:`;e.forEach((e=>{t=`${t+e.name};`})),this.logger.info(`${t}`)}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}},rG=class{constructor(e,t,i,n,r,s,a,o){this.tenant=e,this.manager=t,this.logger=i,this.configProvider=n,this.uiVersion=r,this.eventLatency=s,this.contextProvider=a,this.envOverride=o,this.instanceConfig={extensions:[],extensionConfig:{}};const{oneDSLocalStorage:l,oneDSNotificationManager:c}=this.configProvider.config;c.blockEventsDiscardedNotifications&&this.blockEventsDiscarded(),c.blockNotificationsOnPageUnload&&this.blockNotificationListenersOnPageUnload(),l.sendStaleEvents&&this.sendStaleEvents()}sendEvent(e){this.setEnvPropertiesToEveryEvent();const t=e.props,i={};switch(this.logger.info(`preparing event for delivery: ${e.props?.CorrelationId??""}/${e.eventName}`),this.tenant){case"signaling":t.SkypeId&&(i.user_id={value:t.SkypeId,kind:10},i.Skype_InitiatingUser_Username={value:t.SkypeId,kind:10},i.SkypeId={value:t.SkypeId,kind:10},delete t.SkypeId),this.uiVersion&&(i.ui_version={value:this.uiVersion,kind:0});break;case"media":case"tlePlayer":this.uiVersion&&(i.uiVersion={value:this.uiVersion,kind:0});break;case"realtimeMedia":this.uiVersion&&(i["AppInfo.Version"]={value:this.uiVersion,kind:0})}for(const e of Object.keys(t)){const n=t[e];i[e]={value:n?.value??n,kind:n?.piiKind??0}}const n={name:e.eventName,data:i,latency:this.eventLatency,persistence:Kw.Normal,sync:this.configProvider.config.oneDSEventSendType};this.configProvider.config.smallCallTelemetry.enable&&"mdsc_webrtc_call_session"===n.name&&(n.sync=this.configProvider.config.smallCallTelemetry.eventSendType),this.logger.info(`about to send event ${JSON.stringify(tH.omit(n,["LocalUser","TargetUser"]))}`),this.applicationInsights.track(n)}sendStaleEvents(){this.logger.info("preparing to send stalled telemetry events");const e=this.applicationInsights.getPlugin(iG).plugin;e._sendStale&&e._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 e=!1;const t=()=>{e=!0};window.addEventListener("beforeunload",t),window.addEventListener("unload",t),window.addEventListener("pagehide",t),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?t():e=!1})),this.applicationInsights.getNotifyMgr().listeners.forEach((t=>{const{eventsSent:i,eventsDiscarded:n}=t;i&&(t.eventsSent=t=>{e?this.logger.info("1DS eventSent was not raised due to page unload"):i(t)}),n&&(t.eventsDiscarded=(t,i)=>{e?this.logger.log("1DS eventsDiscarded was not raised due to page unload"):n(t,i)})}))}blockEventsDiscarded(){this.applicationInsights.getNotifyMgr().listeners.forEach((e=>{e.eventsDiscarded=(e,t)=>{this.logger.log(`1DS eventsDiscarded with reason ${t} was not raised due to configuration`)}}))}setEnvPropertiesToEveryEvent(){const e=this.contextProvider?.();if(!an(this.ctx,e)&&(this.ctx=e,this.ctx))if(this.envOverride){for(const e of Object.keys(this.envOverride||{}))if(this.ctx[e]){const t=this.ctx[e].piiKind??0,i=Dn(this.ctx[e].value);this.manager.getPropertyManager().setProperty(this.envOverride[e],{value:i,kind:t})}}else for(const e of Object.keys(this.ctx)){const t=this.ctx[e].piiKind??0,i=Dn(this.ctx[e].value);this.manager.getPropertyManager().setProperty(e,{value:i,kind:t})}}},sG=class extends Error{constructor(e,t=1){super(e),this.callSupport=t}};function aG(e){let t={};return e.telemetryLoggers?t=e.telemetryLoggers:e.telemetryService?.getGenericTelemetryLogger&&e.telemetryTenants?Object.keys(e.telemetryTenants).forEach((i=>t[i]=e.telemetryService.getGenericTelemetryLogger(e.telemetryTenants[i]))):e.telemetryService&&(e.telemetryService.sendEvents||e.telemetryService.getCallingAdapter)&&(e.telemetryService.sendEvents&&(t.media={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}},t.tlePlayer={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}}),e.telemetryService?.sendRealTimeEvents&&(t.realtimeMedia={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendRealTimeEvents([t])}}),e.telemetryService.getCallingAdapter&&(t.signaling={sendEvent(t){e.telemetryService.getCallingAdapter().sendEvent(t.eventName,t.props)}})),t}var oG=class e extends gt{constructor(e,t){super(),this._config=e,this._ecsProvider=t,this.callRegistries=[],this._logger=new ct(this._config.logger).createChild("PluginlessStack"),this._platformManager=new qV,this._waitForAccountConfiguration=new Kt,this.platformCallConstraintsProvider=new tr(this._logger.createChild("PlatformConstraintsProvider"))}async initializeMediaAgent(e){if(this._mediaAgent)throw new sG("Media agent is already initialized");let t,i=null;if(!this._mediaAgentProvider)throw new sG("PluginlessStack initialize MediaAgent error, Media Stack not initialized",i);try{this._relayManagerProvider=new pr(e,this._signalingAgentProvider,this._ecsProvider,this._logger),t=await this._mediaAgentProvider.buildAgent(this._config.platformType,this._relayManagerProvider,this._midCallTelemetry)}catch(e){i=e.some((e=>"incompatible_version"===e.reason))?2:1}if(!this._config.usePlatformSupportApi&&!this._config.callSettings?.useLwjForAllCalls){if(i)throw new sG("PluginlessStack initialization failed",i);{const e=(new qV).getPlatformSupportLevel(!0);if(1!==e&&2!==e)throw new sG("PluginlessStack initialization failed",1)}}t?(this._screenSharingManager=new JV(t.getScreenSharingManager()),this._waitForAccountConfigurationTimeout=window.setTimeout((()=>{this._waitForAccountConfiguration.resolve(void 0),this._waitForAccountConfigurationTimeout=void 0}),3e4),this._oneDsTelemetryLoggers=function(e,t,i,n,r,s){const a={signaling:[],media:[],tlePlayer:[],realtimeMedia:[]};let o={signaling:{sendEvent:e=>a.signaling.push(e)},media:{sendEvent:e=>a.media.push(e)},tlePlayer:{sendEvent:e=>a.tlePlayer.push(e)},realtimeMedia:{sendEvent:e=>a.realtimeMedia.push(e)},gtcAudit:{sendEvent:e=>a.realtimeMedia.push(e)}};return t.getConfigReceivedOrTimeout().then((async()=>{let l=(await r)?.serviceUrls?.OneDsCollectorUrl;if(l=l??t.config.collectorUrl,l){const r=new nG(e,t,i,n,l);o.signaling=r.createLogger("signaling",t.config.eventLatency),o.media=r.createLogger("media",t.config.eventLatency),o.tlePlayer=r.createLogger("tlePlayer",t.config.eventLatency),o.gtcAudit=r.createLogger("gtcAudit",Ww.Immediate);const s=new nG(e,t,i,n,l,{"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"});o.realtimeMedia=s.createLogger("realtimeMedia",t.config.eventLatencyRealTime)}else o=aG(s);for(const[e,t]of Object.entries(a))for(const i of t)o[e].sendEvent(i)})),o}(this._logger.createChild("OneDsLogger"),t.getConfigProvider(),e.clientInformation,this._config.telemetryContextProvider,this._waitForAccountConfiguration.promise,this._config),t.getConfigProvider().config.useOneDsLogger&&(this.signalingLoggerAdapter={sendEvent:(e,t)=>{const i={eventName:e,props:t};this._oneDsTelemetryLoggers.signaling.sendEvent(i)}}),this._mediaAgent=t,this._e911=new zV(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 xi}async initializeSignalingAgentProvider(e){this._trouterService=e.trouterService,this._signalingAgentProvider=((e,t,i,n)=>new eH(e,t,i,n))(e.signalingAgentConfig,this._ecsProvider,this._config.logger,this.signalingLoggerAdapter)}static async build(t,i,n){try{const r=new e({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.logger,telemetryLoggers:t.telemetryLoggers,telemetryService:t.telemetryService,telemetryTenants:t.telemetryTenants,telemetryContextProvider:t.telemetryContextProvider,platformType:t.platformType,callSettings:t.callSettings,usePlatformSupportApi:t.usePlatformSupportApi,clientInformation:t.signalingAgentConfig.clientInformation,vdi3diagnostics:t.vdi3diagnostics},i);return r.initializeMediaProvider({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.mediaAgentFactoryConfig.logger,safeLogger:t.mediaAgentFactoryConfig.safeLogger,webcvProvider:t.mediaAgentFactoryConfig.webcvProvider,wasmdnsProvider:t.mediaAgentFactoryConfig.wasmdnsProvider,wasmaecProvider:t.mediaAgentFactoryConfig.wasmaecProvider,wasmVqeProvider:t.mediaAgentFactoryConfig.wasmVqeProvider,createWasmWorkerCbs:t.mediaAgentFactoryConfig.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.mediaAgentFactoryConfig.encodedStreamsWorkerProvider,clientInformation:t.signalingAgentConfig.clientInformation}),r.setMidCallTelemetry(n),r.initializeSignalingAgentProvider({signalingAgentConfig:t.signalingAgentConfig,trouterService:t.trouterService}),await r.initializeMediaAgent({httpRequestDispatcher:t.mediaAgentFactoryConfig.httpRequestDispatcher,tokenProvider:t.mediaAgentFactoryConfig.tokenProvider,configProvider:t.mediaAgentFactoryConfig.configProvider,appStateProvider:t.mediaAgentFactoryConfig.appStateProvider,clientInformation:t.signalingAgentConfig.clientInformation,trapTokenCredentialsProvider:t.mediaAgentFactoryConfig.trapTokenCredentialsProvider,relayManager:t.mediaAgentFactoryConfig.relayManager}),r}catch(t){throw t instanceof sG?t:new sG(`${t}`)}}static async buildBaseStack(t,i){const n=new e(t,i);return n.initializeMediaProvider({detectH264Support:t.detectH264Support,domOverrides:t.domOverrides,mediaSettings:t.mediaSettings,logger:t.logger,safeLogger:t.safeLogger,webcvProvider:t.webcvProvider,wasmdnsProvider:t.wasmdnsProvider,wasmaecProvider:t.wasmaecProvider,wasmVqeProvider:t.wasmVqeProvider,createWasmWorkerCbs:t.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.encodedStreamsWorkerProvider,clientInformation:t.clientInformation}),n}async init(){}async dispose(e=be()){const t=this._logger.createFnLogger("dispose",e);t.info("Dispose"),this._ecsProvider.dispose(),this._e911?.dispose();const i=e=>{t.warn("Failed:",e)},n=this.callRegistries.map((t=>t.dispose(e).catch(i)));await Promise.all(n),await this._mediaAgentProvider.dispose(e),t.info("media agent is disposed"),this.callRegistries=[],t.info("call registries are disposed"),this._screenSharingManager&&(this._screenSharingManager.dispose(e),this._screenSharingManager=void 0,t.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(e,t=be()){const i=e?Le(e.id):void 0,n=this._logger.createFnLogger(`createCallRegistry[identity=${i}]`,t),r=this.callRegistries.find((t=>t.identity===e.id));return r&&!r.isDisposing?(n.info(`callRegistry already exists for ${Le(e.id)}`),r):(r?.isDisposing&&await r.disposePromise,this._createCallRegistry(e))}createCompositor(e){throw new Error("Method not implemented.")}_createCallRegistry(e){if(!this._trouterService)throw new sG("Unable to create call registry, trouter service undefined");if(!this._mediaAgent)throw new sG("Unable to create call registry, media agent undefined");if(!this._signalingAgentProvider)throw new sG("Unable to create call registry, signaling agent undefined");const t=new Hf(this._trouterService,this._signalingAgentProvider,this._mediaAgent,this._logger,aG(this._config),this._ecsProvider,e,this._oneDsTelemetryLoggers,this._config.vdi3diagnostics);return t.on("disposed",(()=>{this.callRegistries.splice(this.callRegistries.indexOf(t),1)})),t.on("accountConfigurationReceived",(e=>{this._waitForAccountConfiguration.isPending&&(this._waitForAccountConfiguration.resolve(e),window.clearTimeout(this._waitForAccountConfigurationTimeout)),this._relayManagerProvider.getOrCreateRelayManager().setDefaultRelayConfig(e.relayConfig),this._relayManagerProvider.getOrCreateRelayManager().setClientSupportsGenericTokenApi(e.clientSupportsGenericTokenAPI)})),t.on("locationInfoSet",((e,t)=>{this._e911?.setClientInfo(e,t)})),this._relayManagerProvider.getOrCreateRelayManager(),this.callRegistries.push(t),t}initializeMediaProvider(e){const t=(0,lt.assign)({},e);this._mediaAgentProvider=new jV(t,this._ecsProvider,this.platformCallConstraintsProvider),this._deviceManager=new qf(this._mediaAgentProvider.getDeviceManager())}setMidCallTelemetry(e){this._midCallTelemetry=e}getDeviceManager(){return this._deviceManager}async getDeviceManagerAsync(){return this._deviceManager}createDeviceManager(e){return this._deviceManager}getScreenSharingManager(){return this._screenSharingManager}getSetup(){}getEcsProvider(){return this._ecsProvider}async getEcsProviderAsync(){return this._ecsProvider}getCallFeedback(){return null}getAiMdp(){return null}fireIntent(e,t){}getVersion(){return{build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"}}async getVersionAsync(){return{build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"}}getMediaStatus(){return null}getVideoCapabilityLimits(){return null}async setMediaConfig(e){this._mediaAgent.setMediaConfig(e)}async getE911Info(){return this._e911?.getInfo()}setPlatformCallConstraints(e){this.platformCallConstraintsProvider.setConstraints(e)}getPlatformSupportLevel(){return this._platformManager.getPlatformSupportLevel(!!this._mediaAgent)}async getPlatformSupportLevelAsync(){return this.getPlatformSupportLevel()}getLiveStreamClient(){return new Li(this._ecsProvider.createEcsConfiguration(),this._logger.createChild("LiveStreamClient"),(()=>aG(this._config).tlePlayer))}createVoipCallCoordinator(){}async setLogFileName(e,t,i){throw new Error("not supported")}aggregateDiagnosticLogs(e){return Promise.reject("not supported")}submitBrbReport(e,t){return Promise.reject("not supported")}extendBrbFeedback(e,t){return Promise.reject("not supported")}async addOcclusion(e,t,i,n,r,s){}async removeOcclusion(e,t,i,n){}async flushLogs(){throw new Error("not supported")}getDebugDump(){return this._mediaAgent&&function(e){if(!e)return null;const t=Ue("[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 function(e){if(!e)return null;const t=Ue("[U|u]ser[N|n]ame|[O|o]rg[I|i]d");return e.replace(t,Be(De))}(e.replace(t,Be((()=>"<redacted>"))))}(JSON.stringify(this._mediaAgent.getDiagnosticsData()))}async getStageCapability(){throw new Error("not supported")}async getAiCameraCapability(){throw new Error("not supported")}createAiCameraManager(){throw new Error("not supported")}async disposeMediaAgent(e=be()){if(!this._mediaAgent)throw new sG("_mediaAgent is not initialized");await(this._mediaAgent?.dispose(e)),this._mediaAgent=null}async updateSignalingAgentProviderConfig(e){if(!this._signalingAgentProvider)throw new sG("_signalingAgentProvider not initialized");this._trouterService=e.trouterService,this._signalingAgentProvider.getSignalingAgent().updateSignalingAgentConfig(e.signalingAgentConfig)}},lG={build(e,t=!0){const i=e.telemetryContextProvider?.(),n=new WV(i),r=new Xf;return t&&function(e,t,i){if(!zf.RootToolsManager.isDelegateSet()){const n=new ev(e.telemetryService,t);if(zf.RootToolsManager.setDelegate(n),n.on("onMidCallTelemetry",(e=>i.send(e))),e.logger){const t=new Kf(e.logger);zf.LogFactory.instance().addAppender(t)}}e.logger=new Ae("JS.TsCalling.Pluginless",!0),e.mediaAgentFactoryConfig.logger=new Ae("JS.TsCalling.MediaAgentUnsafe",!1),e.mediaAgentFactoryConfig.safeLogger=new Ae("JS.TsCalling.MediaAgent",!0),e.signalingAgentConfig.logger=new Ae("JS.TsCalling.SignalingAgent",!0)}(e,n,r),oG.build(e,n,r)},buildBaseStack(e){const t=e.telemetryContextProvider?.(),i=new WV(t);return oG.buildBaseStack(e,i)},getVersion:()=>({build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"})},cG=[{className:xf,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:Hf,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:Ug,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:qf,props:["getPermissionState","getPermissionStateAsync","isAudioOutputSelectionSupported","askDevicePermission","enumerateDevicesAsync","getPreferredCamera","selectDevices","getSelectedDevices","startPreview","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:WV,props:["setEcsConfig","setUserEcsServerUrl","getUserEcsServerUrl","setActiveUserForEcs","getEcsQueryParameters","ecsGetUserQueryParameters","shouldTriggerCQF"]},{className:Fp,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:Bg,props:["contentSharingState","contentSharingStatus","contentSharingTerminationReason","contentSharingIdentity","contentSharingGuid","startContentSharing","joinContentSharing","updateContentSharingSessionState","takeContentSharingControl","updateContentSharingParticipantStateToViewer","stopContentSharing","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:tp,props:["addHandler","removeHandler","updateNegotiationTag"]},{className:Ng,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:Og,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:oG,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"])}];return"object"==typeof n.exports&&(n.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||undefined===i||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(n=Object.getOwnPropertyDescriptor(t,i))||n.enumerable});return e})(n.exports,i)),n.exports},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e["skype-calling-pluginless"]=n():i["skype-calling-pluginless"]=n(i["@skype/rt-js-bindings"],i.lodash)}}),f={};((e,t)=>{for(var i in t)a(e,i,{get:t[i],enumerable:!0})})(f,{ShellTrouter:()=>up,monitor:()=>Cg,stackFactory:()=>dp,tsCallingChannel:()=>hp}),r.exports=(e=>h(a({},"__esModule",{value:!0}),e))(f);var v=()=>{const e=new Array(36);for(let t=0;t<e.length;t++)e[t]=Math.floor(16*Math.random());return e[14]=4,e[19]=e[19]&=-5,e[19]=e[19]|=8,e[8]=e[13]=e[18]=e[23]="-",e.map((e=>e.toString(16))).join("")},S=(e=21)=>{let t="";const i=crypto.getRandomValues(new Uint8Array(e));for(let n=0;n<e;n++)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&i[n]];return t},y=class{constructor(e,t){this.logger=e,this.transportConfig=t,this._state=3,this.listeners=new Map}get state(){return this._state}get config(){return this.transportConfig||{}}addEventListener(e,t){this.logger.log(`Event listener added, type: ${e}`);const i=this.listeners.get(e)||new Set;i.add(t),this.listeners.set(e,i)}removeEventListener(e,t){this.logger.log(`Event listener removed, type: ${e}`),this.listeners.get(e)?.delete(t),0===this.listeners.get(e)?.size&&this.listeners.delete(e)}handleMessage(e){const t=JSON.parse(e),i=t.type;this.listeners.get(i)?.forEach((e=>{e(t)}))}},C=class extends y{constructor(e,t){if(super(e,t),this.logger=e,!window.chrome?.webview)throw new Error("chrome.webview is undefined");this._state=1,window.chrome.webview.addEventListener("message",this.handleEvent.bind(this))}dispatchEvent(e){window.chrome.webview.postMessage(e)}handleEvent(e){const t=e.data;t&&super.handleMessage(JSON.stringify(t))}},T=class extends y{constructor(e,t){super(e,t),this.updateTransportState()}get tsCallingChannel(){return navigator.mediaDevices?.tsCallingChannel}dispatchEvent(e){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(JSON.stringify(e)):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(e){e.detail?.message&&super.handleMessage(e.detail.message)}initTsCallingChannel(){if(this.config.tsCallingChannel?.connectionUrl){const e=new URL(this.config.tsCallingChannel.connectionUrl);e.searchParams.set("transportConfig",JSON.stringify(this.config)),this.logger.log(`connectionUrl: ${e}`),this.dispatchEvent({WebViewRemotingControlChannel:{url:e.toString()}})}else this.logger.warn("tsCallingLoaderUrl was not passed in config.")}},E=Z;function b(e,t,i,n=0){(function(e,t,i=0){e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t)})(e,0===i?0:i-1,n),0!==i&&e.push(t)}var _=e=>{try{return(new TextEncoder).encode(e).length/1024}catch(t){return e.length/1024}},I=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new w(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",function(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}(e))}}))}},w=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,E.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},A=class extends I{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}async onAsync(e,t){return this.on(e,t)}async onceAsync(e,t,i){return this.once(e,t,i)}async changedAsync(e,t){return this.changed(e,t)}async disposeAsync(e){this.dispose(e)}},P=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((e,t)=>{this.resolveInt=e,this.rejectInt=t}))}get resolve(){return e=>{this.isPendingInt=!1,this.resolveInt(e),this.clearTimeout()}}get reject(){return e=>{this.isPendingInt=!1,this.rejectInt(e),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(e,t=`deferred timed out after ${e}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(t)}),e))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function R(e,t=`deferred timed out after ${e}ms`){const i=new P;return i.setTimeout(e,t),i}var M=class{constructor(){this.rttStat=[],this.transportEventStat=[],this.channel=new Map,this.historyLength=100}registerRtt(e){b(this.rttStat,{rtt:e,timestamp:Date.now()},this.historyLength)}markEvent(e,t){b(this.transportEventStat,{eventName:e,timestamp:Date.now(),payload:t},this.historyLength)}setLastPingReceived(){this.lastPingReceived=Date.now()}setLastPingSent(){this.lastPingSent=Date.now()}reportChannelAdded(e){this.channel.set(e,{channelId:e,createdAt:Date.now()})}reportChannelTerminated(e){const t=this.channel.get(e);t&&(t.terminatedAt=Date.now())}getStats(e){let t=this.rttStat,i=this.transportEventStat;return e&&(t=this.rttStat.filter((t=>t.timestamp>=e)),i=this.transportEventStat.filter((t=>t.timestamp>=e))),{rttStat:t,transportEventStat:i,lastPingReceived:this.lastPingReceived,lastPingSent:this.lastPingSent,channelStat:Array.from(this.channel.values())}}clear(){this.rttStat=[],this.transportEventStat=[]}},D=class{constructor(e){this.statManager=e}getReport(e){const{rttStat:t,transportEventStat:i,lastPingSent:n,lastPingReceived:r,channelStat:s}=this.statManager.getStats(e);return{Transport_rttStat:JSON.stringify(t),Transport_transportEventStat:JSON.stringify(i),Transport_lastPingSent:n,Transport_lastPingReceived:r,Transport_channelStat:JSON.stringify(s)}}},k=3e4,O=3,N=3e4,L=1e3,x=200,F="1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",U="https://ic3.events.data.microsoft.com/OneCollector/1.0/",B=3e4,V=class{constructor(e,t,i){this.transport=e,this.statManager=t,this.logger=i,this.onConnectionCallbackPool=new Set,this.handShakeReqAck=new Map,this.CONNECTION_TIMEOUT=k,this.CONNECTION_RETRY_COUNT=O,this.synEvetListener=async e=>{if(this.onConnectionCallbackPool.has(e.reqId))this.logger.log(`Callback for ${e.reqId} already processed`);else{this.onConnectionCallbackPool.add(e.reqId);try{await(this.onSynCallback?.(e))}catch(e){this.logger.log("Callback errored.",e)}finally{this.onConnectionCallbackPool.delete(e.reqId)}}},this.ackEvetListener=e=>{this.onAckCallback?.(e)},this.transport.addEventListener("syn",this.synEvetListener),this.transport.addEventListener("ack",this.ackEvetListener)}async establish(e){const t=Date.now();this.statManager.markEvent("handShakeInitiated",e);const{resolve:i,promise:n}=R(this.CONNECTION_TIMEOUT,"Request timedout"),r=v();this.handShakeReqAck.set(r,i),this.transport.dispatchEvent({type:"syn",payload:e,reqId:r});const s=globalThis.setInterval((()=>{this.transport.dispatchEvent({type:"syn",payload:e,reqId:r})}),this.CONNECTION_TIMEOUT/this.CONNECTION_RETRY_COUNT);return this.onAckCallback=e=>{const i=Date.now();this.statManager.markEvent("handShakeSuccess",{duration:i-t}),this.handShakeReqAck.get(e.reqId)?.(),this.handShakeReqAck.delete(e.reqId)},this.establishPromise=n.finally((()=>{globalThis.clearInterval(s),this.establishPromise=void 0})),this.establishPromise}onConnection(e){const t=Date.now();this.onSynCallback=async i=>{await e(i.payload),this.transport.dispatchEvent({type:"ack",reqId:i.reqId});const n=Date.now();this.statManager.markEvent("handShakeSuccess",{duration:n-t,handshakePayload:i.payload})}}dispose(){this.transport.removeEventListener("syn",this.synEvetListener),this.transport.removeEventListener("ack",this.ackEvetListener),this.handShakeReqAck.clear(),this.onConnectionCallbackPool.clear()}},H=class{constructor(e){this.logger=e}start(e,t){if(this.intervalWorker=new $(this.logger.createChild("WorkerBasedTimer")),!this.intervalWorker)throw new Error("Failed to initialize worker");this.intervalWorker.setInterval(e,t)}stop(){this.intervalWorker?.clearInterval(),this.intervalWorker?.disposeTimerWorker?.()}},$=class{constructor(e){this.logger=e,this.timerId=S(),this.workerMessageHandler=e=>{if("ping"===e.data.type)return this.onPing();this.logger.debug(`Msg from worker: ${JSON.stringify(e)}`)},this.workerErrorHandler=e=>{this.logger.error(`Error from worker: ${JSON.stringify(e)}`)},this.createWorker()}setInterval(e,t){this.logger.debug(`Starting id: ${this.timerId}`),this.callback=e,this.timeout=t,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 e=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(e)),this.doWork.addEventListener("message",this.workerMessageHandler),this.doWork.addEventListener("error",this.workerErrorHandler),this.logger.debug("Initialized")}catch(e){throw this.logger.debug(`Worker creation failed: ${JSON.stringify(e)}`),e}}},j=class extends A{constructor(e,t=N,i){super(),this.transport=e,this.transportTimeout=t,this.logger=i,this.heartbeats=new Map,this.monitorInterval=L,this.scheduler=new H(this.logger),this.start(),e.addEventListener("ping",(e=>{this.handleTransportPing(e)})),e.addEventListener("pong",(e=>{this.handleTransportPong(e)}))}async waitForTransport(){if(1===this.transport.state)return Promise.resolve();const{resolve:e,promise:t}=R(this.transportTimeout,`Unable to establish transport in ${this.transportTimeout}s`),i=globalThis.setInterval((()=>{1===this.transport.state&&e()}),200);return t.finally((()=>{globalThis.clearInterval(i)}))}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 e=()=>{this.sendHeartbeat(),this.checkTransportState()};try{this.scheduler.start(e,this.monitorInterval)}catch(t){this.logger.error(t),this.logger.log("Fallback to setInterval"),this.monitorIntervalId=globalThis.setInterval(e,this.monitorInterval)}}sendHeartbeat(){const e=Math.random();this.heartbeats.set(e,Date.now()),this.transport.dispatchEvent({type:"ping",eventId:e})}handleTransportPing({eventId:e}){this.transport.dispatchEvent({type:"pong",eventId:e})}handleTransportPong({eventId:e}){void 0!==this.heartbeats.get(e)&&(this.heartbeats.delete(e),this.lastAckTime=Date.now())}checkTransportState(){this.lastAckTime&&Date.now()-this.lastAckTime>this.transportTimeout&&(this.stop(),this.event("connectionTerminated").raise())}},G=class extends j{constructor(e,t,i=3e4,n){super(t,i,n),this.statManager=e,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(e){const t=this.heartbeats.get(e.eventId);void 0!==t&&(super.handleTransportPong(e),this.statManager.registerRtt(Date.now()-t),this.statManager.setLastPingReceived())}},q=class{constructor(e){this.modifiers=e,this.hasModifier=this.modifiers.length>0}transform(e){if(!this.hasModifier)return[{chunk:e,index:0}];const t=this.modifiers.reduce(((e,t)=>t.modify(e)),e);return Array.isArray(t)?t.map(((e,t)=>({chunk:e,index:t}))):[{chunk:t,index:0}]}rebuild(e){if(!this.hasModifier)return e[0].chunk;const t=[];return e.forEach((({index:e,chunk:i})=>{t[e]=i})),this.modifiers.slice().reverse().reduce(((e,t)=>t.reconstruct(e)),t)}},z=class{constructor(e,t){if(this.config=t,!(t.chunkSize&&t.chunkSize>0))throw new Error(`Invalid chunkSize given: ${t.chunkSize}`);e.warn(`chunkSize set to ${t.chunkSize} bytes`)}modify(e){const t=e.length,i=this.config.chunkSize,n=Math.ceil(t/i),r=[];for(let t=0;t<n;t++){const n=e.substring(t*i,(t+1)*i);r.push(n)}return r}reconstruct(e){return e.reduce(((e,t)=>e+t),"")}},W=class{constructor(e,t){this.logger=e,this.config=t,this.reconstructionBuffers=new Map,this.receivedIndexes=new Map,this.messageTransformer=new q(this.config.chunkSize?[new z(this.logger,this.config)]:[])}dispatchMessage(e,t){const i=e.type,n=v(),r=this.messageTransformer.transform(JSON.stringify(e)),s=r.length;r.forEach((e=>t({type:i,messageId:n,totalChunks:s,message:e})))}onMessageReceived(e){const t=e.messageId,i=e.totalChunks;this.reconstructionBuffers.has(t)||(this.reconstructionBuffers.set(t,[]),this.receivedIndexes.set(t,new Set));const n=this.reconstructionBuffers.get(t),r=this.receivedIndexes.get(t);if(r.has(e.message.index)||(r.add(e.message.index),n.push(e.message)),n.filter((e=>!!e)).length===i){const e=this.messageTransformer.rebuild(n);return this.reconstructionBuffers.delete(t),this.receivedIndexes.delete(t),e}return null}},K=class extends y{constructor(e,t){super(t,e.config),this.transport=e,this.logger=t,this.handleTransportEvent=this.handleEvent.bind(this),this.messageTransformHandler=new W(t.createChild("MessageTransformHandler"),this.config.messageConfig||{})}dispatchEvent(e){this.messageTransformHandler.dispatchMessage(e,this.transport.dispatchEvent.bind(this.transport))}get state(){return this.transport.state}addEventListener(e,t){this.listeners.has(e)||this.transport.addEventListener(e,this.handleTransportEvent),super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t),this.listeners.has(e)&&0!==this.listeners.get(e)?.size||this.transport.removeEventListener(e,this.handleTransportEvent)}handleEvent(e){const t=this.messageTransformHandler.onMessageReceived(e);t&&super.handleMessage(t)}dispose(){this.listeners.forEach(((e,t)=>{e.forEach((e=>this.transport.removeEventListener(t,e)))})),this.listeners.clear()}},J=class extends y{constructor(e,t,i){super(i,t.config),this.channelId=e,this.transport=t,this.handleTransportEvent=this.handleEvent.bind(this)}get state(){return this.transport.state}dispatchEvent(e){this.transport.dispatchEvent({...e,$$channelId:this.channelId})}addEventListener(e,t){this.listeners.has(e)||this.transport.addEventListener(e,this.handleTransportEvent),super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t),this.listeners.has(e)&&0!==this.listeners.get(e)?.size||this.transport.removeEventListener(e,this.handleTransportEvent)}handleEvent(e){if(e.$$channelId===this.channelId){delete e.$$channelId;const t=e.type;this.listeners.get(t)?.forEach((t=>{t(e)}))}}dispose(){this.listeners.forEach(((e,t)=>{this.transport.removeEventListener(t,this.handleTransportEvent)})),this.listeners.clear()}},Y=class extends A{constructor(e,t){super(),this.transportExt=e,this.logger=t,this.statManager=new M,this.transportTelemetryProvider=new D(this.statManager),this.channels=new Map,this.transport=new K(this.transportExt,this.logger),this.handShakeService=new V(this.transport,this.statManager,this.logger),this.transportHealthCheck=new G(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(e){await this.handShakeService.establish(e),this.logger.log("connection established")}async onConnection(e){this.handShakeService.onConnection(e),this.logger.log("new connection callback set")}createChannel(e){const t=this.logger.createChild(`Channel:${e}`),i=new J(e,this.transport,t);return this.statManager.reportChannelAdded(e),new j(i,this.transport.config?.transportConnectionTimeout,t.createChild("ChannelHealthCheck")).on("connectionTerminated",(()=>{this.statManager.reportChannelTerminated(e),this.logger.log(`Connection terminated, channelId: ${e}`),this.channels.delete(e),i.dispose(),this.event("connectionTerminated").raise(e)})),this.channels.set(e,i),i}get telemetryProvider(){return this.transportTelemetryProvider}dispose(){this.transport.dispose(),this.handShakeService.dispose(),this.channels.forEach((e=>e.dispose())),this.logger.info("Dispose: Transport Manager")}},X="object",ee="undefined",te="prototype",ie=Object,ne=ie[te];function re(e,t){return e||t}function se(e,t){return e[t]}var ae,oe=void 0,le=null,ce="function",de="object",ue="prototype",he="__proto__",ge="undefined",pe="constructor",me="Symbol",fe="length",ve="name",Se="call",ye="toString",Ce=re(Object),Te=se(Ce,ue),Ee=re(String),be=se(Ee,ue),_e=re(Math),Ie=re(Array),we=se(Ie,ue),Ae=se(we,"slice");function Pe(e,t){try{return{v:e.apply(this,t)}}catch(e){return{e}}}function Re(e){return function(t){return typeof t===e}}function Me(e){var t="[object "+e+"]";return function(e){return!(!e||function(e){return Te[ye].call(e)}(e)!==t)}}function De(e){return typeof e===ge||e===ge}function ke(e){return e===le||De(e)}function Oe(e){return!!e||e!==oe}function Ne(e){return!ae&&(ae=["string","number","boolean",ge,"symbol","bigint"]),e!==de&&-1!==ae.indexOf(e)}var Le=Re("string"),xe=Re(ce);function Fe(e){return!(!e&&ke(e)||!e||typeof e!==de)}var Ue=se(Ie,"isArray"),Be=Me("Date"),Ve=Re("number"),He=Re("boolean"),$e=Me("Error");function je(e){return!!(e&&e.then&&xe(e.then))}function Ge(e){return!(!e||function(e,t){var i=Pe(e);return i.e?t:i.v}((function(){return!(e&&0+e)}),!e))}var qe=se(Ce,"getOwnPropertyDescriptor");function ze(e,t){return!!e&&Te.hasOwnProperty[Se](e,t)}var We=re(se(Ce,"hasOwn"),(function(e,t){return ze(e,t)||!!qe(e,t)}));function Ke(e,t,i){if(e&&Fe(e))for(var n in e)if(We(e,n)&&-1===t[Se](i||e,n,e[n]))break}var Je={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function Ye(e){var t={};if(t[Je.c]=!0,t[Je.e]=!0,e.l){t.get=function(){return e.l.v};var i=qe(e.l,"v");i&&i.set&&(t.set=function(t){e.l.v=t})}return Ke(e,(function(e,i){t[Je[e]]=De(i)?t[Je[e]]:i})),t}var Qe=se(Ce,"defineProperty"),Ze=se(Ce,"defineProperties");function Xe(e,t,i){return Qe(e,t,Ye(i))}function et(e,t){var i={};return Ke(t,(function(e,t){i[e]=Ye(t)})),Ze(e,i)}function tt(e,t,i,n,r){var s={};return Ke(e,(function(e,n){it(s,e,t?n:e,r),it(s,n,i?n:e,r)})),n?n(s):s}function it(e,t,i,n){Qe(e,t,{value:i,enumerable:!0,writable:!!n})}var nt=re(Ee);function rt(e,t){var i="",n=Te[ye][Se](e);"[object Error]"===n&&(e={stack:nt(e.stack),message:nt(e.message),name:nt(e.name)});try{i=(i=JSON.stringify(e,le,t?"number"==typeof t?t:4:oe))&&i.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||nt(e)}catch(e){i=" - "+rt(e,t)}return n+": "+i}function st(e){throw new Error(e)}function at(e){throw new TypeError(e)}var ot=se(Ce,"freeze"),lt=se(Ce,"assign"),ct=se(Ce,"keys");function dt(e){return ot&&Ke(e,(function(e,t){(Ue(t)||Fe(t))&&dt(t)})),ht(e)}var ut,ht=re(ot,(function(e){return e})),gt=re(se(Ce,"getPrototypeOf"),(function(e){return e[he]||le})),pt=tt({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},0,0,ht),mt="__tsUtils$gblCfg";function ft(){var e;return typeof globalThis!==ge&&(e=globalThis),e||typeof self===ge||(e=self),e||typeof window===ge||(e=window),e||typeof i===ge||(e=i),e}function vt(){if(!ut){var e=Pe(ft).v||{};ut=e[mt]=e[mt]||{}}return ut}var St=yt;function yt(e,t,i){var n=t&&t[e];return function(t){var r=t&&t[e]||n;if(r||i){var s=arguments;return(r||i).apply(t,r?Ae[Se](s,1):s)}at('"'+nt(e)+'" not defined for '+rt(t))}}var Ct=se(_e,"max"),Tt=St("slice",be),Et=St("substring",be),bt=yt("substr",be,(function(e,t,i){return ke(e)&&at("Invalid "+rt(e)),i<0?"":((t=t||0)<0&&(t=Ct(t+e[fe],0)),De(i)?Tt(e,t):Tt(e,t,t+i))}));function _t(e,t){return Et(e,0,t)}var It,wt,At,Pt="_urid";function Rt(e){return{description:nt(e),toString:function(){return me+"("+e+")"},_polyfill:!0}}function Mt(e){var t=function(){if(!It){var e=vt();It=e.gblSym=e.gblSym||{k:{},s:{}}}return It}();if(!We(t.k,e)){var i=Rt(e),n=ct(t.s).length;i[Pt]=function(){return n+"_"+i[ye]()},t.k[e]=i,t.s[i[Pt]()]=nt(e)}return t.k[e]}function Dt(){At=vt()}function kt(e){return Qe({toJSON:function(){return e}},"v",{value:e})}var Ot,Nt="window";function Lt(e,t){var i;return function(){return!At&&Dt(),(!i||At.lzy)&&(i=kt(Pe(e,t).v)),i.v}}function xt(e){return!At&&Dt(),(!Ot||!1===e||At.lzy)&&(Ot=kt(Pe(ft).v||le)),Ot.v}function Ft(e,t){var i=Ot&&!1!==t?Ot.v:xt(t);return i&&i[e]?i[e]:e===Nt?jt():le}function Ut(){return!!$t()}var Bt,Vt,Ht,$t=Lt(Ft,["document"]),jt=Lt(Ft,[Nt]),Gt=Lt(Ft,["navigator"]),qt=Lt((function(){return!!Pe((function(){return process&&(process.versions||{}).node})).v}));function zt(){return Bt=kt(Pe(Ft,[me]).v)}function Wt(e){var t=(At.lzy?0:Bt)||zt();return t.v?t.v[e]:oe}function Kt(e,t){var i=pt[e];!At&&Dt();var n=(At.lzy?0:Bt)||zt();return n.v?n.v[i||e]:t?oe:function(e){var t;!wt&&(wt={});var i=pt[e];return i&&(t=wt[i]=wt[i]||Rt(me+"."+i)),t}(e)}function Jt(e,t){!At&&Dt();var i=(At.lzy?0:Bt)||zt();return i.v?i.v(e):t?le:Rt(e)}function Yt(e){return!At&&Dt(),((Vt=(At.lzy?0:Vt)||kt(Pe(Wt,["for"]).v)).v||Mt)(e)}function Qt(e){return!!e&&xe(e.next)}function Zt(e,t,i){if(e&&(Qt(e)||(!Ht&&(Ht=kt(Kt(3))),e=e[Ht.v]?e[Ht.v]():null),Qt(e))){var n=oe,r=oe;try{for(var s=0;!(r=e.next()).done&&-1!==t[Se](i||e,r.value,s,e);)s++}catch(t){n={e:t},e.throw&&(r=le,e.throw(n))}finally{try{r&&!r.done&&e.return&&e.return(r)}finally{if(n)throw n.e}}}}function Xt(e,t,i){return e.apply(t,i)}function ei(e,t){return!De(t)&&e&&(Ue(t)?Xt(e.push,e,t):Qt(t)||function(e){return!function(e){return e===le||!Oe(e)}(e)&&xe(e[Kt(3)])}(t)?Zt(t,(function(t){e.push(t)})):e.push(t)),e}function ti(e,t,i){if(e)for(var n=e[fe]>>>0,r=0;r<n&&(!(r in e)||-1!==t[Se](i||e,e[r],r,e));r++);}var ii=St("indexOf",we);function ni(e,t,i){return(e&&e.slice||Ae).apply(e,Ae[Se](arguments,1))}var ri,si=yt("includes",we,(function(e,t,i){return-1!==ii(e,t,i)})),ai=re(se(Ce,"create"),(function(e){if(!e)return{};var t=typeof e;function i(){}return t!==de&&t!==ce&&at("Prototype must be an Object or function: "+rt(e)),i[ue]=e,new i}));function oi(e,t){return(Ce.setPrototypeOf||function(e,t){var i;!ri&&(ri=kt(((i={})[he]=[],i instanceof Array))),ri.v?e[he]=t:Ke(t,(function(t,i){return e[t]=i}))})(e,t)}function li(e,t){t&&(e[ve]=t)}function ci(){return(Date.now||di)()}function di(){return(new Date).getTime()}var ui,hi,gi,pi=yt("trim",be,function(e){return function(t){return ke(t)&&at("strTrim called ["+rt(t)+"]"),t&&t.replace&&(t=t.replace(e,"")),t}}(/^\s+|(?=\s)\s+$/g));function mi(e){if(!e||typeof e!==de)return!1;gi||(gi=!jt()||jt());var t=!1;if(e!==gi){hi||(ui=Function[ue][ye],hi=ui[Se](Ce));try{var i=gt(e);(t=!i)||(ze(i,pe)&&(i=i[pe]),t=i&&typeof i===ce&&ui[Se](i)===hi)}catch(e){}}return t}function fi(e){return e.value&&Ci(e),!0}var vi=[function(e){var t=e.value;if(Ue(t)){var i=e.result=[];return i.length=t.length,e.copyTo(i,t),!0}return!1},Ci,function(e){return e.type===ce},function(e){var t=e.value;return!!Be(t)&&(e.result=new Date(t.getTime()),!0)}];function Si(e,t,i,n){var r=i.handler,s=i.path?n?i.path.concat(n):i.path:[],a={handler:i.handler,src:i.src,path:s},o=typeof t,l=!1,c=!1;t&&o===de?l=mi(t):c=t===le||Ne(o);var d={type:o,isPrim:c,isPlain:l,value:t,result:t,path:s,origin:i.src,copy:function(t,n){return Si(e,t,n?a:i,n)},copyTo:function(t,i){return yi(e,t,i,a)}};return d.isPrim?r&&r[Se](i,d)?d.result:t:function(e,t,i,n){var r;return ti(e,(function(e){if(e.k===t)return r=e,-1})),r||(r={k:t,v:t},e.push(r),n(r)),r.v}(e,t,0,(function(e){Xe(d,"result",{g:function(){return e.v},s:function(t){e.v=t}});for(var t=0,n=r;!(n||(t<vi.length?vi[t++]:fi))[Se](i,d);)n=le}))}function yi(e,t,i,n){if(!ke(i))for(var r in i)t[r]=Si(e,i[r],n,r);return t}function Ci(e){var t=e.value;if(t&&e.isPlain){var i=e.result={};return e.copyTo(i,t),!0}return!1}function Ti(e,t,i,n,r,s,a){return function(e,t){return ti(t,(function(t){!function(e,t){yi([],e,t,{handler:void 0,src:t,path:[]})}(e,t)})),e}(function(e){return Si([],e,{handler:void 0,src:e})}(e)||{},Ae[Se](arguments))}var Ei=function(e){return function(t){return t[e]}}(fe),bi=yt("endsWith",be,(function(e,t,i){Le(e)||at("'"+rt(e)+"' is not a string");var n=Le(t)?t:nt(t),r=!De(i)&&i<e[fe]?i:e[fe];return Et(e,r-n[fe],r)===n})),_i=St("indexOf",be),Ii=yt("startsWith",be,(function(e,t,i){Le(e)||at("'"+rt(e)+"' is not a string");var n=Le(t)?t:nt(t),r=i>0?i:0;return Et(e,r,r+n[fe])===n})),wi="ref",Ai="unref",Pi="hasRef";function Ri(e,t,i){var n=Ue(t),r=n?t.length:0,s=(r>0?t[0]:n?oe:t)||setTimeout,a=(r>1?t[1]:oe)||clearTimeout,o=i[0];i[0]=function(){l.dn(),Xt(o,oe,Ae[Se](arguments))};var l=function(e,t){var i,n=!0,r=e?t(le):le;function s(){return n=!1,r&&r[Ai]&&r[Ai](),i}function o(){r&&function(e){Xt(a,oe,[e])}(r),r=le}function l(){return r=t(r),n||s(),i}return(i={cancel:o,refresh:l})[Pi]=function(){return r&&r[Pi]?r[Pi]():n},i[wi]=function(){return n=!0,r&&r[wi]&&r[wi](),i},i[Ai]=s,{h:i=Qe(i,"enabled",{get:function(){return!!r},set:function(e){!e&&r&&o(),e&&!r&&l()}}),dn:function(){r=le}}}(e,(function(e){if(e){if(e.refresh)return e.refresh(),e;Xt(a,oe,[e])}return Xt(s,oe,i)}));return l.h}function Mi(e,t){return Ri(!0,oe,Ae[Se](arguments))}(xt()||{}).Symbol,(xt()||{}).Reflect;var Di,ki=function(e,t){return(ki=ie.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)};function Oi(e,t){function i(){this.constructor=e}"function"!=typeof t&&null!==t&&at("Class extends value "+String(t)+" is not a constructor or null"),ki(e,t),e[te]=null===t?ai(t):(i[te]=t[te],new i)}function Ni(e,t){for(var i=0,n=t.length,r=e.length;i<n;i++,r++)e[r]=t[i];return e}var Li="constructor",xi="prototype",Fi="function",Ui="_dynInstFuncs",Bi="_isDynProxy",Vi="_dynClass",Hi="_dynInstChk",$i=Hi,ji="_dfOpts",Gi="_unknown_",qi="__proto__",zi="_dyn"+qi,Wi="__dynProto$Gbl",Ki="_dynInstProto",Ji="useBaseInst",Yi="setInstFuncs",Qi=Object,Zi=Qi.getPrototypeOf,Xi=Qi.getOwnPropertyNames,en=xt(),tn=en[Wi]||(en[Wi]={o:(Di={},Di[Yi]=!0,Di[Ji]=!0,Di),n:1e3});function nn(e){return e&&(e===Qi[xi]||e===Array[xi])}function rn(e){return nn(e)||e===Function[xi]}function sn(e){var t;if(e){if(Zi)return Zi(e);var i=e[qi]||e[xi]||(e[Li]?e[Li][xi]:null);t=e[zi]||i,ze(e,zi)||(delete e[Ki],t=e[zi]=e[Ki]||e[zi],e[Ki]=i)}return t}function an(e,t){var i=[];if(Xi)i=Xi(e);else for(var n in e)"string"==typeof n&&ze(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function on(e,t,i){return t!==Li&&typeof e[t]===Fi&&(i||ze(e,t))&&t!==qi&&t!==xi}function ln(e){at("DynamicProto: "+e)}function cn(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function dn(e,t,i,n,r){if(!nn(e)){var s=i[Ui]=i[Ui]||ai(null);if(!nn(s)){var a=s[t]=s[t]||ai(null);!1!==s[$i]&&(s[$i]=!!r),nn(a)||an(i,(function(t){on(i,t,!1)&&i[t]!==n[t]&&(a[t]=i[t],delete i[t],(!ze(e,t)||e[t]&&!e[t][Bi])&&(e[t]=function(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&ze(i,Vi)){var s=e[Ui]||ai(null);if((r=(s[i[Vi]]||ai(null))[t])||ln("Missing ["+t+"] "+Fi),!r[Hi]&&!1!==s[$i]){for(var a=!ze(e,t),o=sn(e),l=[];a&&o&&!rn(o)&&!cn(l,o);){var c=o[t];if(c){a=c===n;break}l.push(o),o=sn(o)}try{a&&(e[t]=r),r[Hi]=1}catch(e){s[$i]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=sn(t)[e]),typeof n!==Fi&&ln("["+e+"] is not a "+Fi),n}(t,e,i)).apply(this,arguments)};return i[Bi]=1,i}(e,t)))}))}}}function un(e,t){return ze(e,xi)?e.name||t||Gi:((e||{})[Li]||{}).name||t||Gi}function hn(e,t,i,n){ze(e,xi)||ln("theClass is an invalid class definition.");var r=e[xi];(function(e,t){if(Zi){for(var i=[],n=sn(t);n&&!rn(n)&&!cn(i,n);){if(n===e)return!0;i.push(n),n=sn(n)}return!1}return!0})(r,t)||ln("["+un(e)+"] not in hierarchy of ["+un(t)+"]");var s=null;ze(r,Vi)?s=r[Vi]:(s="_dynCls$"+un(e,"_")+"$"+tn.n,tn.n++,r[Vi]=s);var a=hn[ji],o=!!a[Ji];o&&n&&void 0!==n[Ji]&&(o=!!n[Ji]);var l=function(e){var t=ai(null);return an(e,(function(i){!t[i]&&on(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[Bi]&&n){var s=e[Ui]||{};!1!==s[$i]&&(r=(s[t[Vi]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var s=ai(null);an(i,(function(e){s[e]=r(t,i,e)}));for(var a=sn(e),o=[];a&&!rn(a)&&!cn(o,a);)an(a,(function(e){!s[e]&&on(a,e,!Zi)&&(s[e]=r(t,a,e))})),o.push(a),a=sn(a);return s}(r,t,l,o));var c=!!Zi&&!!a[Yi];c&&n&&(c=!!n[Yi]),dn(r,s,t,l,!1!==c)}hn[ji]=tn.o;var gn,pn=function(e){return tt(e,1,0,ht)},mn=function(e){return function(e){var t={};return Ke(e,(function(e,i){it(t,e,i[1]),it(t,i[0],i[1])})),ht(t)}(e)},fn=pn({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),vn="toLowerCase",Sn="blkVal",yn="length",Cn="rdOnly",Tn="notify",En="warnToConsole",bn="throwInternal",_n="setDf",In="watch",wn="logger",An="apply",Pn="push",Rn="splice",Mn="hdlr",Dn="cancel",kn="initialize",On="identifier",Nn="removeNotificationListener",Ln="addNotificationListener",xn="isInitialized",Fn="getNotifyMgr",Un="getPlugin",Bn="pollInternalLogs",Vn="name",Hn="time",$n="processNext",jn="getProcessTelContext",Gn="enabled",qn="stopPollingInternalLogs",zn="unload",Wn="onComplete",Kn="version",Jn="loggingLevelConsole",Yn="createNew",Qn="teardown",Zn="messageId",Xn="message",er="isAsync",tr="diagLog",ir="_doTeardown",nr="update",rr="getNext",sr="setNextPlugin",ar="protocol",or="userAgent",lr="split",cr="nodeType",dr="replace",ur="type",hr="handler",gr="status",pr="getResponseHeader",mr="getAllResponseHeaders",fr="isChildEvt",vr="data",Sr="getCtx",yr="setCtx",Cr="complete",Tr="urlString",Er="sendPOST",br="headers",_r="timeout",Ir="setRequestHeader",wr="traceId",Ar="spanId",Pr="traceFlags",Rr="Promise",Mr="rejected";function Dr(e,t){return kr(e,(function(e){return t?t({status:"fulfilled",rejected:!1,value:e}):e}),(function(e){return t?t({status:Mr,rejected:!0,reason:e}):e}))}function kr(e,t,i,n){var r=e;try{if(je(e))(t||i)&&(r=e.then(t,i));else try{t&&(r=t(e))}catch(e){if(!i)throw e;r=i(e)}}finally{n&&function(e,t){t&&(je(e)?e.finally?e.finally(t):e.then((function(e){return t(),e}),(function(e){throw t(),e})):t())}(r,n)}return r}var Or,Nr=["pending","resolving","resolved",Mr],Lr="dispatchEvent";function xr(e){var t;return e&&e.createEvent&&(t=e.createEvent("Event")),!!t&&t.initEvent}var Fr,Ur,Br,Vr="unhandledRejection",Hr=Vr.toLowerCase(),$r=[],jr=0;function Gr(e){return xe(e)?e.toString():rt(e)}function qr(e,t,i){var n,r,s=ni(arguments,3),a=0,o=!1,l=[],c=jr++,d=!1,u=null;function h(t,i){try{return $r.push(c),d=!0,u&&u.cancel(),u=null,e((function(e,r){l.push((function(){try{var s=2===a?t:i,o=De(s)?n:xe(s)?s(n):s;je(o)?o.then(e,r):s?e(o):3===a?r(o):e(o)}catch(e){r(e)}})),o&&p()}),s)}finally{$r.pop()}}function g(){return Nr[a]}function p(){if(l.length>0){var e=l.slice();l=[],d=!0,u&&u.cancel(),u=null,t(e)}}function m(e,t){return function(i){if(a===t){if(2===e&&je(i))return a=1,void i.then(m(2,1),m(3,1));a=e,o=!0,n=i,p(),d||3!==e||u||(u=Mi(f,10))}}}function f(){if(!d)if(d=!0,qt())process.emit(Vr,n,r);else{var e=jt()||xt();!Fr&&(Fr=kt(Pe(Ft,[Rr+"RejectionEvent"]).v)),function(e,t,i,n){var r=$t();!Or&&(Or=kt(!!Pe(xr,[r]).v));var s=Or.v?r.createEvent("Event"):n?new Event(t):{};if(i&&i(s),Or.v&&s.initEvent(t,!1,!0),s&&e[Lr])e[Lr](s);else{var a=e["on"+t];if(a)a(s);else{var o=Ft("console");o&&(o.error||o.log)(t,rt(s))}}}(e,Hr,(function(e){return Xe(e,"promise",{g:function(){return r}}),e.reason=n,e}),!!Fr.v)}}return Qe(r={then:h,catch:function(e){return h(void 0,e)},finally:function(e){var t=e,i=e;return xe(e)&&(t=function(t){return e&&e(),t},i=function(t){throw e&&e(),t}),h(t,i)}},"state",{get:g}),!At&&Dt(),!!((At.lzy?0:Bt)||zt()).v&&(r[Kt(11)]="IPromise"),r.toString=function(){return"IPromise "+g()+(o?" - "+Gr(n):"")},function(){xe(i)||at(Rr+": executor is not a function - "+Gr(i));var e=m(3,0);try{i.call(r,m(2,0),e)}catch(t){e(t)}}(),r}function zr(e,t){return qr(zr,function(e){var t=Ve(e)?e:0;return function(e){Mi((function(){!function(e){ti(e,(function(e){try{e()}catch(e){}}))}(e)}),t)}}(t),e,t)}function Wr(e,t){!Ur&&(Ur=kt(Pe(Ft,[Rr]).v||null));var i=Ur.v;if(!i)return zr(e);xe(e)||at(Rr+": executor is not a function - "+rt(e));var n=0,r=new i((function(t,i){e((function(e){n=2,t(e)}),(function(e){n=3,i(e)}))}));return Qe(r,"state",{get:function(){return Nr[n]}}),r}function Kr(e,t){return!Br&&(Br=kt(Wr)),Br.v.call(this,e,t)}var Jr=function(e){return function(t){var i=ni(arguments,1);return e((function(e,i){try{var n=[],r=1;Zt(t,(function(t,s){t&&(r++,kr(t,(function(t){n[s]=t,0==--r&&e(n)}),i))})),0==--r&&e(n)}catch(e){i(e)}}),i)}}(Kr),Yr=void Kt(11),Qr="",Zr="channels",Xr="core",es="createPerfMgr",ts="disabled",is="extensionConfig",ns="extensions",rs="processTelemetry",ss="priority",as="eventsSent",os="eventsDiscarded",ls="eventsSendRequest",cs="perfEvent",ds="offlineEventsStored",us="offlineBatchSent",hs="offlineBatchDrop",gs="getPerfMgr",ps="domain",ms="path",fs=/-([a-z])/g,vs=/([^\w\d_$])/g,Ss=/^(\d+[\w\d_$])/;function ys(e){return!ke(e)}function Cs(e){var t=e;return t&&Le(t)&&(t=(t=(t=t[dr](fs,(function(e,t){return t.toUpperCase()})))[dr](vs,"_"))[dr](Ss,(function(e,t){return"_"+t}))),t}function Ts(e,t){return!(!e||!t)&&-1!==_i(e,t)}function Es(e){return e&&e.toISOString()||""}function bs(e){return $e(e)?e[Vn]:Qr}function _s(e,t,i,n,r){var s=i;return e&&((s=e[t])===i||r&&!r(s)||n&&!n(i)||(s=i,e[t]=s)),s}function Is(e,t,i,n,r){e&&t&&i&&(!1!==r||De(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return xe(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][An](n,e)}}(i,n))}function ws(e,t,i,n){return e&&t&&Fe(e)&&Ue(i)&&ti(i,(function(i){Le(i)&&Is(e,i,t,i,n)})),e}function As(e){return e&&lt&&(e=ie(lt({},e))),e}function Ps(e,t,i,n,r,s){var a=arguments,o=a[0]||{},l=a[yn],c=!1,d=1;for(l>0&&He(o)&&(c=o,o=a[d]||{},d++),Fe(o)||(o={});d<l;d++){var u=a[d],h=Ue(u),g=Fe(u);for(var p in u)if(h&&p in u||g&&We(u,p)){var m=u[p],f=void 0;if(c&&m&&((f=Ue(m))||mi(m))){var v=o[p];f?Ue(v)||(v=[]):mi(v)||(v={}),m=Ps(c,v,m)}void 0!==m&&(o[p]=m)}}return o}function Rs(e){try{return e.responseText}catch(e){}return null}function Ms(e,t){return e?"XMLHttpRequest,Status:"+e[gr]+",Response:"+Rs(e)||0:t}function Ds(e,t){return t&&(Ve(t)?e=[t].concat(e):Ue(t)&&(e=t.concat(e))),e}var ks="withCredentials";function Os(e,t,i){if(!e[i]&&t&&t[pr]){var n=t[pr](i);n&&(e[i]=pi(n))}return e}function Ns(e,t){var i={};return e[mr]?i=function(e){var t={};return Le(e)&&ti(pi(e)[lr](/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=pi(e.substring(0,i))[vn](),r=pi(e.substring(i+1));t[n]=r}else t[pi(e)]=1}})),t}(e[mr]()):t&&(i=Os(i,e,"time-delta-millis"),i=Os(i,e,"kill-duration"),i=Os(i,e,"kill-duration-seconds")),i}var Ls="JSON",xs="XMLHttpRequest",Fs=null,Us=null,Bs=null,Vs=null;function Hs(e,t){var i=!1;if(e){try{if(!(i=t in e)){var n=e[te];n&&(i=t in n)}}catch(e){}if(!i)try{i=!De((new e)[t])}catch(e){}}return i}function $s(e){return typeof location===X&&location?location:Ft("location")}function js(){return Boolean(typeof JSON===X&&JSON||null!==Ft(Ls))}function Gs(){var e=Gt();return!(!e||!e.product)&&"ReactNative"===e.product}function qs(){var e=Gt();if(e&&(e[or]!==Us||null===Fs)){var t=((Us=e[or])||Qr)[vn]();Fs=Ts(t,"msie")||Ts(t,"trident/")}return Fs}function zs(e){return null!==Vs&&!1!==e||(Vs=!!Gt()&&Boolean(Gt().sendBeacon)),Vs}function Ws(e){var t=!1;try{t=!!Ft("fetch");var i=Ft("Request");t&&e&&i&&(t=Hs(i,"keepalive"))}catch(e){}return t}function Ks(){var e=!1;try{e=!!Ft(xs)}catch(e){}return e}var Js=4294967296,Ys=4294967295,Qs=123456789,Zs=987654321,Xs=!1,ea=Qs,ta=Zs;function ia(e){var t=0,i=Ft("crypto")||Ft("msCrypto");return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&Ys),0===t&&qs()&&(Xs||function(){try{var e=2147483647&ci();!function(e){e<0&&(e>>>=0),ea=Qs+e&Ys,ta=Zs-e&Ys,Xs=!0}((Math.random()*Js^e)+e)}catch(e){}}(),t=function(){var e=((ta=36969*(65535&ta)+(ta>>16)&Ys)<<16)+(65535&(ea=18e3*(65535&ea)+(ea>>16)&Ys))>>>0&Ys;return e>>>=0}()&Ys),0===t&&(t=Math.floor(Js*Math.random()|0)),e||(t>>>=0),t}function na(e){void 0===e&&(e=22);for(var t=ia()>>>0,i=0,n=Qr;n[yn]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(ia()<<2&4294967295|3&t)>>>0,i=0);return n}var ra="3.2.1",sa="."+na(6),aa=0;function oa(e){return 1===e[cr]||9===e[cr]||!+e[cr]}function la(e,t){return void 0===t&&(t=!1),Cs(e+aa+++(t?"."+ra:Qr)+sa)}function ca(e){var t={id:la("_aiData-"+(e||Qr)+"."+ra),accept:function(e){return oa(e)},get:function(e,i,n,r){var s=e[t.id];return s?s[Cs(i)]:(r&&((s=function(e,t){var i=t[e.id];if(!i){i={};try{oa(t)&&Xe(t,e.id,{e:!1,v:i})}catch(e){}}return i}(t,e))[Cs(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return t}function da(e){return e&&Fe(e)&&(e.isVal||e.fb||We(e,"v")||We(e,"mrg")||We(e,"ref")||e.set)}function ua(e,t,i){var n,r=i.dfVal||Oe;if(t&&i.fb){var s=i.fb;Ue(s)||(s=[s]);for(var a=0;a<s[yn];a++){var o=s[a],l=t[o];if(r(l)?n=l:e&&(r(l=e.cfg[o])&&(n=l),e.set(e.cfg,nt(o),l)),r(n))break}}return!r(n)&&r(i.v)&&(n=i.v),n}function ha(e,t,i){var n,r=i;return i&&da(i)&&(r=ua(e,t,i)),r&&(da(r)&&(r=ha(e,t,r)),Ue(r)?(n=[])[yn]=r[yn]:mi(r)&&(n={}),n&&(Ke(r,(function(i,r){r&&da(r)&&(r=ha(e,t,r)),n[i]=r})),r=n)),r}function ga(e,t,i,n){var r,s,a,o,l,c,d,u,h=n;da(h)?(r=h.isVal,s=h.set,c=h[Cn],d=h[Sn],o=h.mrg,!(l=h.ref)&&De(l)&&(l=!!o),a=ua(e,t,h)):a=n,d&&e[Sn](t,i);var g=!0,p=t[i];!p&&ke(p)||(u=p,g=!1,r&&u!==a&&!r(u)&&(u=a,g=!0),s&&(g=(u=s(u,a,t))===a)),g?u=a?ha(e,t,a):a:(mi(u)||Ue(a))&&o&&a&&(mi(a)||Ue(a))&&Ke(a,(function(t,i){ga(e,u,t,i)})),e.set(t,i,u),l&&e.ref(t,i),c&&e[Cn](t,i)}var pa=Yt("[[ai_dynCfg_1]]"),ma=Yt("[[ai_blkDynCfg_1]]"),fa=Yt("[[ai_frcDynCfg_1]]");function va(e){var t;return e&&(Ue(e)?(t=[])[yn]=e[yn]:mi(e)&&(t={}),t)?(Ke(e,(function(e,i){t[e]=va(i)})),t):e}function Sa(e){if(e){var t=e[pa]||e;if(t.cfg&&(t.cfg===e||t.cfg[pa]===t))return t}return null}function ya(e,t,i){var n=!1;return i&&!e[t.blkVal]&&((n=i[fa])||i[ma]||(n=mi(i)||Ue(i))),n}function Ca(e){at("InvalidAccess:"+e)}var Ta=["push","pop","shift","unshift","splice"],Ea=function(e,t,i,n){e&&e[bn](3,108,"".concat(i," [").concat(t,"] failed - ")+rt(n))};function ba(e,t){var i=qe(e,t);return i&&i.get}function _a(e,t,i,n){if(t){var r=ba(t,i);r&&r[e.prop]?t[i]=n:function(e,t,i,n){var r={n:i,h:[],trk:function(t){t&&t.fn&&(-1===ii(r.h,t)&&r.h[Pn](t),e.trk(t,r))},clr:function(e){var t=ii(r.h,e);-1!==t&&r.h[Rn](t,1)}},s=!0,a=!1;function o(){s&&(a=a||ya(o,e,n),n&&!n[pa]&&a&&(n=wa(e,n,i,"Converting")),s=!1);var t=e.act;return t&&r.trk(t),n}o[e.prop]={chng:function(){e.add(r)}},Xe(t,r.n,{g:o,s:function(l){if(n!==l){o[e.ro]&&!e.upd&&Ca("["+i+"] is read-only:"+rt(t)),s&&(a=a||ya(o,e,n),s=!1);var c=a&&o[e.rf];if(a)if(c){Ke(n,(function(e){n[e]=l?l[e]:Yr}));try{Ke(l,(function(t,i){_a(e,n,t,i)})),l=n}catch(t){Ea((e.hdlr||{})[wn],i,"Assigning",t),a=!1}}else n&&n[pa]&&Ke(n,(function(t){var i=ba(n,t);if(i){var r=i[e.prop];r&&r.chng()}}));if(l!==n){var d=l&&ya(o,e,l);!c&&d&&(l=wa(e,l,i,"Converting")),n=l,a=d}e.add(r)}}})}(e,t,i,n)}return t}function Ia(e,t,i,n){if(t){var r=ba(t,i),s=r&&!!r[e.prop],a=n&&n[0],o=n&&n[1],l=n&&n[2];if(!s){if(l)try{!function(e){if(e&&(mi(e)||Ue(e)))try{e[ma]=!0}catch(e){}}(t)}catch(t){Ea((e.hdlr||{})[wn],i,"Blocking",t)}try{_a(e,t,i,t[i]),r=ba(t,i)}catch(t){Ea((e.hdlr||{})[wn],i,"State",t)}}a&&(r[e.rf]=a),o&&(r[e.ro]=o),l&&(r[e.blkVal]=!0)}return t}function wa(e,t,i,n){try{Ke(t,(function(i,n){_a(e,t,i,n)})),t[pa]||(Qe(t,pa,{get:function(){return e[Mn]}}),function(e,t,i){Ue(t)&&ti(Ta,(function(n){var r=t[n];t[n]=function(){for(var n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var a=r[An](this,n);return wa(e,t,i,"Patching"),a}}))}(e,t,i))}catch(t){Ea((e.hdlr||{})[wn],i,n,t)}return t}var Aa="[[ai_",Pa="]]";function Ra(e){var t,i,n=Jt(Aa+"get"+e.uid+Pa),r=Jt(Aa+"ro"+e.uid+Pa),s=Jt(Aa+"rf"+e.uid+Pa),a=Jt(Aa+"blkVal"+e.uid+Pa),o=Jt(Aa+"dtl"+e.uid+Pa),l=null,c=null;function d(t,n){var r=i.act;try{i.act=t,t&&t[o]&&(ti(t[o],(function(e){e.clr(t)})),t[o]=[]),n({cfg:e.cfg,set:e.set.bind(e),setDf:e[_n].bind(e),ref:e.ref.bind(e),rdOnly:e[Cn].bind(e)})}catch(t){var s=e[wn];throw s&&s[bn](1,107,rt(t)),t}finally{i.act=r||null}}function u(){if(l){var e=l;l=null,c&&c[Dn](),c=null;var t=[];if(ti(e,(function(e){if(e&&(e[o]&&(ti(e[o],(function(t){t.clr(e)})),e[o]=null),e.fn))try{d(e,e.fn)}catch(e){t[Pn](e)}})),l)try{u()}catch(e){t[Pn](e)}t[yn]>0&&function(e,t){gn||(gn=function(e,t,i){var n=i||Error,r=n[ue][ve],s=Error.captureStackTrace;return function(e,t,i){function n(){this[pe]=t,Pe(Xe,[this,ve,{v:e,c:!0,e:!1}])}return Pe(Xe,[t,ve,{v:e,c:!0,e:!1}]),(t=oi(t,i))[ue]=i===le?ai(i):(n[ue]=i[ue],new n),t}(e,(function(){var i=this,a=arguments;try{Pe(li,[n,e]);var o=Xt(n,i,Ae[Se](a))||i;if(o!==i){var l=gt(i);l!==gt(o)&&oi(o,l)}return s&&s(o,i[pe]),t&&t(o,a),o}finally{Pe(li,[n,r])}}),n)}("AggregationError",(function(e,t){t[yn]>1&&(e.errors=t[1])})));var i="Watcher error(s): ";throw ti(t,(function(e,t){i+="\n".concat(t," > ").concat(rt(e))})),new gn(i,t||[])}(0,t)}}return(t={prop:n,ro:r,rf:s})[Sn]=a,t[Mn]=e,t.add=function(e){if(e&&e.h[yn]>0){l||(l=[]),c||(c=Mi((function(){c=null,u()}),0));for(var t=0;t<e.h[yn];t++){var i=e.h[t];i&&-1===ii(l,i)&&l[Pn](i)}}},t[Tn]=u,t.use=d,t.trk=function(e,t){if(e){var i=e[o]=e[o]||[];-1===ii(i,t)&&i[Pn](t)}},i=t}function Ma(e,t,i){var n,r=Sa(t);if(r)return r;var s,a=la("dyncfg",!0),o=t&&!1!==i?t:va(t),l=((n={uid:null,cfg:o})[wn]=e,n[Tn]=function(){s[Tn]()},n.set=function(t,i,n){try{t=_a(s,t,i,n)}catch(t){Ea(e,i,"Setting value",t)}return t[i]},n[_n]=function(e,t){return t&&Ke(t,(function(t,i){ga(l,e,t,i)})),e},n[In]=function(e){return function(e,t){var i={fn:t,rm:function(){i.fn=null,e=null,t=null}};return Xe(i,"toJSON",{v:function(){return"WatcherHandler"+(i.fn?"":"[X]")}}),e.use(i,t),i}(s,e)},n.ref=function(e,t){var i;return Ia(s,e,t,(i={},i[0]=!0,i))[t]},n[Cn]=function(e,t){var i;return Ia(s,e,t,(i={},i[1]=!0,i))[t]},n[Sn]=function(e,t){var i;return Ia(s,e,t,(i={},i[2]=!0,i))[t]},n._block=function(e,t){s.use(null,(function(i){var n=s.upd;try{De(t)||(s.upd=t),e(i)}finally{s.upd=n}}))},n);return Xe(l,"uid",{c:!1,e:!1,w:!1,v:a}),wa(s=Ra(l),o,"config","Creating"),l}function Da(e,t,i,n){var r=Ma(i,e||{},n);return t&&r[_n](r.cfg,t),r}function ka(e,t,i){var n=e[pa]||e;return!n.cfg||n.cfg!==e&&n.cfg[pa]!==n?(function(e,t){e?(e[En](t),e[bn](2,108,t)):Ca(t)}(i,"Not dynamic - "+rt(e)),Da(e,null,i)[In](t)):n[In](t)}function Oa(e,t){if(e&&e[zn])return e[zn](t)}function Na(e,t,i){var n;return i||(n=Kr((function(e){i=e}))),e&&Ei(e)>0?Dr(Oa(e[0],t),(function(){Na(ni(e,1),t,i)})):i(),n}var La="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function xa(e){return{mrg:!0,v:e}}function Fa(e){return{isVal:Le,v:nt(e||Qr)}}var Ua,Ba,Va=[as,os,ls,cs],Ha=null;function $a(e,t){return function(){var i=arguments,n=ja(t);if(n){var r=n.listener;r&&r[e]&&r[e][An](r,i)}}}function ja(e){var t=Ha;return t||!0===e.disableDbgExt||(t=Ha||function(){var e=Ft("Microsoft");return e&&(Ha=e.ApplicationInsights),Ha}()),t?t.ChromeDbgExt:null}var Ga="warnToConsole",qa={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},za=((Ba={})[0]=null,Ba[1]="errorToConsole",Ba[2]=Ga,Ba[3]="debugToConsole",Ba);function Wa(e){return e?'"'+e[dr](/\"/g,Qr)+'"':Qr}function Ka(e,t){var i=typeof console!==ee?console:Ft("console");if(i){var n="log";i[e]&&(n=e),xe(i[n])&&i[n](t)}}var Ja=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[Zn]=e,r[Xn]=(i?"AI: ":"AI (Internal): ")+e;var s=Qr;js()&&(s=(js()?JSON||Ft(Ls):null).stringify(n));var a=(t?" message:"+Wa(t):Qr)+(n?" props:"+Wa(s):Qr);r[Xn]+=a}return e.dataType="MessageData",e}();function Ya(e,t){return(e||{})[wn]||new Xa(t)}var Qa,Za,Xa=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,s,a,o=0,l={};hn(e,this,(function(e){function c(t,i){if(!(o>=r)){var s=!0,a="AITR_"+i[Zn];if(l[a]?s=!1:l[a]=!0,s&&(t<=n&&(e.queue[Pn](i),o++,d(1===t?"error":"warn",i)),o===r)){var c="Internal events throttle limit per PageView reached for this app.",u=new Ja(23,c,!1);e.queue[Pn](u),1===t?e.errorToConsole(c):e[En](c)}}}function d(e,i){var n=ja(t||{});n&&n[tr]&&n[tr](e,i)}a=function(t){return ka(Da(t,qa,e).cfg,(function(e){var t=e.cfg;i=t[Jn],n=t.loggingLevelTelemetry,r=t.maxMessageLimit,s=t.enableDebug}))}(t||{}),e.consoleLoggingLevel=function(){return i},e[bn]=function(t,n,r,a,o){void 0===o&&(o=!1);var u=new Ja(n,r,o,a);if(s)throw rt(u);var h=za[t]||Ga;if(De(u[Xn]))d("throw"+(1===t?"Critical":"Warning"),u);else{if(o){var g=+u[Zn];!l[g]&&i>=t&&(e[h](u[Xn]),l[g]=!0)}else i>=t&&e[h](u[Xn]);c(t,u)}},e.debugToConsole=function(e){Ka("debug",e),d("warning",e)},e[En]=function(e){Ka("warn",e),d("warning",e)},e.errorToConsole=function(e){Ka("error",e),d("error",e)},e.resetInternalMessageCount=function(){o=0,l={}},e.logInternalMessage=c,e[zn]=function(e){a&&a.rm(),a=null}}))}return e.__ieDyn=1,e}();function eo(e){return e||new Xa}function to(e,t,i,n,r,s){void 0===s&&(s=!1),eo(e)[bn](t,i,n,r,s)}function io(e,t){eo(e)[En](t)}var no,ro="toGMTString",so="toUTCString",ao="cookie",oo="expires",lo="isCookieUseDisabled",co="disableCookiesUsage",uo="_ckMgr",ho=null,go=null,po=null,mo={},fo={},vo=((Qa={cookieCfg:xa((Za={},Za[ps]={fb:"cookieDomain",dfVal:ys},Za.path={fb:"cookiePath",dfVal:ys},Za.enabled=Yr,Za.ignoreCookies=Yr,Za.blockedCookies=Yr,Za)),cookieDomain:Yr,cookiePath:Yr})[co]=Yr,Qa);function So(){!no&&(no=function(){var e={};return!At&&Dt(),e.b=At.lzy,Qe(e,"v",{configurable:!0,get:function(){var t=$t();return At.lzy||Qe(e,"v",{value:t}),e.b=At.lzy,t}}),e}())}function yo(e){return!e||e.isEnabled()}function Co(e,t){return!!(t&&e&&Ue(e.ignoreCookies))&&-1!==ii(e.ignoreCookies,t)}function To(e,t){var i=t[Gn];if(ke(i)){var n=void 0;De(e[lo])||(n=!e[lo]),De(e[co])||(n=!e[co]),i=n}return i}function Eo(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=t.cookieCfg;i=n&&n[uo]?n[uo]:bo(t)}return i||(i=function(e,t){var i=bo[uo]||fo[uo];return i||(i=bo[uo]=bo(e,t),fo[uo]=i),i}(t,(e||{})[wn])),i}function bo(e,t){var i,n,r,s,a,o,l,c,d;e=Da(e||fo,null,t).cfg,a=ka(e,(function(t){t[_n](t.cfg,vo),n=t.ref(t.cfg,"cookieCfg"),r=n[ms]||"/",s=n[ps],o=!1!==To(e,n),l=n.getCookie||Po,c=n.setCookie||Ro,d=n.delCookie||Ro}),t);var u=((i={isEnabled:function(){var i=!1!==To(e,n)&&o&&_o(t),r=fo[uo];return i&&r&&u!==r&&(i=yo(r)),i},setEnabled:function(e){o=!1!==e,n[Gn]=e},set:function(e,t,i,a,o){var l=!1;if(yo(u)&&!function(e,t){return!!(t&&e&&Ue(e.blockedCookies)&&-1!==ii(e.blockedCookies,t))||Co(e,t)}(n,e)){var d={},h=pi(t||Qr),g=_i(h,";");if(-1!==g&&(h=pi(_t(t,g)),d=Io(Et(t,g+1))),_s(d,ps,a||s,Ge,De),!ke(i)){var p=qs();if(De(d[oo])){var m=ci()+1e3*i;if(m>0){var f=new Date;f.setTime(m),_s(d,oo,wo(f,p?ro:so)||wo(f,p?ro:so)||Qr,Ge)}}p||_s(d,"max-age",Qr+i,null,De)}var v=$s();v&&"https:"===v[ar]&&(_s(d,"secure",null,null,De),null===go&&(go=!function(e){return!(!Le(e)||!Ts(e,"CPU iPhone OS 12")&&!Ts(e,"iPad; CPU OS 12")&&!(Ts(e,"Macintosh; Intel Mac OS X 10_14")&&Ts(e,"Version/")&&Ts(e,"Safari"))&&(!Ts(e,"Macintosh; Intel Mac OS X 10_14")||!bi(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!Ts(e,"Chrome/5")&&!Ts(e,"Chrome/6")&&(!Ts(e,"UnrealEngine")||Ts(e,"Chrome"))&&!Ts(e,"UCBrowser/12")&&!Ts(e,"UCBrowser/11"))}((Gt()||{})[or])),go&&_s(d,"SameSite","None",null,De)),_s(d,ms,o||r,null,De),c(e,Ao(h,d)),l=!0}return l},get:function(e){var t=Qr;return yo(u)&&!Co(n,e)&&(t=l(e)),t},del:function(e,t){var i=!1;return yo(u)&&(i=u.purge(e,t)),i},purge:function(e,i){var n,r=!1;if(_o(t)){var s=((n={})[ms]=i||"/",n[oo]="Thu, 01 Jan 1970 00:00:01 GMT",n);qs()||(s["max-age"]="0"),d(e,Ao(Qr,s)),r=!0}return r}})[zn]=function(e){a&&a.rm(),a=null},i);return u[uo]=u,u}function _o(e){if(null===ho){ho=!1,!no&&So();try{var t=no.v||{};ho=void 0!==t[ao]}catch(t){to(e,2,68,"Cannot access document.cookie - "+bs(t),{exception:rt(t)})}}return ho}function Io(e){var t={};return e&&e[yn]&&ti(pi(e)[lr](";"),(function(e){if(e=pi(e||Qr)){var i=_i(e,"=");-1===i?t[e]=null:t[pi(_t(e,i))]=pi(Et(e,i+1))}})),t}function wo(e,t){return xe(e[t])?e[t]():null}function Ao(e,t){var i=e||Qr;return Ke(t,(function(e,t){i+="; "+e+(ke(t)?Qr:"="+t)})),i}function Po(e){var t=Qr;if(!no&&So(),no.v){var i=no.v[ao]||Qr;po!==i&&(mo=Io(i),po=i),t=pi(mo[e]||Qr)}return t}function Ro(e,t){!no&&So(),no.v&&(no.v[ao]=e+"="+t)}var Mo={perfEvtsSendAll:!1};function Do(e){e.h=null;var t=e.cb;e.cb=[],ti(t,(function(e){Pe(e.fn,[e.arg])}))}function ko(e,t,i,n){ti(e,(function(e){e&&e[t]&&(i?(i.cb[Pn]({fn:n,arg:e}),i.h=i.h||Mi(Do,0,i)):Pe(n,[e]))}))}var Oo=function(){function e(t){var i,n;this.listeners=[];var r=[],s={h:null,cb:[]},a=Da(t,Mo);n=a[In]((function(e){i=!!e.cfg.perfEvtsSendAll})),hn(e,this,(function(e){Xe(e,"listeners",{g:function(){return r}}),e[Ln]=function(e){r[Pn](e)},e[Nn]=function(e){for(var t=ii(r,e);t>-1;)r[Rn](t,1),t=ii(r,e)},e[as]=function(e){ko(r,as,s,(function(t){t[as](e)}))},e[os]=function(e,t){ko(r,os,s,(function(i){i[os](e,t)}))},e[ls]=function(e,t){ko(r,ls,t?s:null,(function(i){i[ls](e,t)}))},e[cs]=function(e){e&&(!i&&e[fr]()||ko(r,cs,null,(function(t){e[er]?Mi((function(){return t[cs](e)}),0):t[cs](e)})))},e[ds]=function(e){e&&e[yn]&&ko(r,ds,s,(function(t){t[ds](e)}))},e[us]=function(e){e&&e[vr]&&ko(r,us,s,(function(t){t[us](e)}))},e[hs]=function(e,t){if(e>0){var i=t||0;ko(r,hs,s,(function(t){t[hs](e,i)}))}},e[zn]=function(e){var t,i=function(){n&&n.rm(),n=null,r=[],s.h&&s.h[Dn](),s.h=null,s.cb=[]};if(ko(r,"unload",null,(function(i){var n=i[zn](e);n&&(t||(t=[]),t[Pn](n))})),t)return Kr((function(e){return Dr(Jr(t),(function(){i(),e()}))}));i()}}))}return e.__ieDyn=1,e}(),No="ctx",Lo="ParentContextKey",xo="ChildrenContextKey",Fo=function(){function e(t,i,n){var r,s=this;s.start=ci(),s[Vn]=t,s[er]=n,s[fr]=function(){return!1},xe(i)&&Xe(s,"payload",{g:function(){return!r&&xe(i)&&(r=i(),i=null),r}}),s[Sr]=function(t){return t?t===e[Lo]||t===e[xo]?s[t]:(s[No]||{})[t]:null},s[yr]=function(t,i){t&&(t===e[Lo]?(s[t]||(s[fr]=function(){return!0}),s[t]=i):t===e[xo]?s[t]=i:(s[No]=s[No]||{})[t]=i)},s[Cr]=function(){var t=0,i=s[Sr](e[xo]);if(Ue(i))for(var n=0;n<i[yn];n++){var r=i[n];r&&(t+=r[Hn])}s[Hn]=ci()-s.start,s.exTime=s[Hn]-t,s[Cr]=function(){}}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),Uo=function(){function e(t){this.ctx={},hn(e,this,(function(e){e.create=function(e,t,i){return new Fo(e,t,i)},e.fire=function(e){e&&(e[Cr](),t&&xe(t[cs])&&t[cs](e))},e[yr]=function(t,i){t&&((e[No]=e[No]||{})[t]=i)},e[Sr]=function(t){return(e[No]||{})[t]}}))}return e.__ieDyn=1,e}(),Bo="CoreUtils.doPerf";function Vo(e,t,i,n,r){if(e){var s=e;if(s[gs]&&(s=s[gs]()),s){var a=void 0,o=s[Sr](Bo);try{if(a=s.create(t(),n,r)){if(o&&a[yr]&&(a[yr](Fo[Lo],o),o[Sr]&&o[yr])){var l=o[Sr](Fo[xo]);l||(l=[],o[yr](Fo[xo],l)),l[Pn](a)}return s[yr](Bo,a),i(a)}}catch(e){a&&a[yr]&&a[yr]("exception",e)}finally{a&&s.fire(a),s[yr](Bo,o)}}}return i()}function Ho(){var e=$o();return Et(e,0,8)+"-"+Et(e,8,12)+"-"+Et(e,12,16)+"-"+Et(e,16,20)+"-"+Et(e,20)}function $o(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=Qr,n=0;n<4;n++)i+=t[15&(e=ia())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&ia())|0];return bt(i,0,8)+bt(i,9,4)+"4"+bt(i,13,3)+r+bt(i,16,3)+bt(i,19,12)}function jo(e,t,i){return!(!e||e[yn]!==t||e===i||!e.match(/^[\da-f]*$/i))}function Go(e){return jo(e,32,"00000000000000000000000000000000")}function qo(e){return jo(e,16,"0000000000000000")}var zo=ca("plugin");function Wo(e){return zo.get(e,"state",{},!0)}function Ko(e,t){for(var i,n=[],r=null,s=e[rr]();s;){var a=s[Un]();if(a){r&&r[sr]&&a[rs]&&r[sr](a);var o=!!(i=Wo(a))[xn];a[xn]&&(o=a[xn]()),o||n[Pn](a),r=a,s=s[rr]()}}ti(n,(function(n){var r=e[Xr]();n[kn](e.getCfg(),r,t,e[rr]()),i=Wo(n),n[Xr]||i[Xr]||(i[Xr]=r),i[xn]=!0,delete i[Qn]}))}function Jo(e){return e.sort((function(e,t){var i=0;if(t){var n=t[rs];e[rs]?i=n?e[ss]-t[ss]:1:n&&(i=-1)}else i=e?1:-1;return i}))}var Yo,Qo="_hasRun",Zo="_getTelCtx",Xo=0;function el(e,t,i,n){var r=null,s=[];t||(t=Da({},null,i[wn])),null!==n&&(r=n?function(e,t,i){for(;e;){if(e[Un]()===i)return e;e=e[rr]()}return rl([i],t.config||{},t)}(e,i,n):e);var a={_next:function(){var e=r;if(r=e?e[rr]():null,!e){var t=s;t&&t[yn]>0&&(ti(t,(function(e){try{e.func.call(e.self,e.args)}catch(e){to(i[wn],2,73,"Unexpected Exception during onComplete - "+rt(e))}})),s=[])}return e},ctx:{core:function(){return i},diagLog:function(){return Ya(i,t.cfg)},getCfg:function(){return t.cfg},getExtCfg:function(e,i){var n=o(e,!0);return i&&Ke(i,(function(e,i){if(ke(n[e])){var r=t.cfg[e];!r&&ke(r)||(n[e]=r)}ga(t,n,e,i)})),t[_n](n,i)},getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var s=o(e,!1),a=t.cfg;return!s||!s[i]&&ke(s[i])?!a[i]&&ke(a[i])||(r=a[i]):r=s[i],r||!ke(r)?r:n},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=a._next();){var i=t[Un]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&s[Pn]({func:e,self:De(t)?a.ctx:t,args:i})}}};function o(e,i){var n=null,r=t.cfg;if(r&&e){var s=r[is];!s&&i&&(s={}),r[is]=s,(s=t.ref(r,is))&&(!(n=s[e])&&i&&(n={}),s[e]=n,n=t.ref(s,e))}return n}return a}function tl(e,t,i,n){var r=Da(t),s=el(e,r,i,n),a=s.ctx;return a[$n]=function(e){var t=s._next();return t&&t[rs](e,a),!t},a[Yn]=function(e,t){return void 0===e&&(e=null),Ue(e)&&(e=rl(e,r.cfg,i,t)),tl(e||a[rr](),r.cfg,i,t)},a}function il(e,t,i){var n=Da(t.config),r=el(e,n,t,i),s=r.ctx;return s[$n]=function(e){var t=r._next();return t&&t[zn](s,e),!t},s[Yn]=function(e,i){return void 0===e&&(e=null),Ue(e)&&(e=rl(e,n.cfg,t,i)),il(e||s[rr](),t,i)},s}function nl(e,t,i){var n=Da(t.config),r=el(e,n,t,i).ctx;return r[$n]=function(e){return r.iterate((function(t){xe(t[nr])&&t[nr](r,e)}))},r[Yn]=function(e,i){return void 0===e&&(e=null),Ue(e)&&(e=rl(e,n.cfg,t,i)),nl(e||r[rr](),t,i)},r}function rl(e,t,i,n){var r=null,s=!n;if(Ue(e)&&e[yn]>0){var a=null;ti(e,(function(e){if(s||n!==e||(s=!0),s&&e&&xe(e[rs])){var o=function(e,t,i){var n,r=null,s=xe(e[rs]),a=xe(e[sr]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:function(t,i){c(i=i||l(),(function(i){if(!e||!s)return!1;var n=Wo(e);return!n[Qn]&&!n[ts]&&(a&&e[sr](r),e[rs](t,i),!0)}),"processTelemetry",(function(){return{item:t}}),!t.sync)||i[$n](t)},unload:function(t,i){c(t,(function(){var n=!1;if(e){var r=Wo(e),s=e[Xr]||r[Xr];!e||s&&s!==t.core()||r[Qn]||(r[Xr]=null,r[Qn]=!0,r[xn]=!1,e[Qn]&&!0===e[Qn](t,i)&&(n=!0))}return n}),"unload",(function(){}),i[er])||t[$n](i)},update:function(t,i){c(t,(function(){var n=!1;if(e){var r=Wo(e),s=e[Xr]||r[Xr];!e||s&&s!==t.core()||r[Qn]||e[nr]&&!0===e[nr](t,i)&&(n=!0)}return n}),"update",(function(){}),!1)||t[$n](i)},_id:n=e?e[On]+"-"+e[ss]+"-"+Xo++:"Unknown-0-"+Xo++,_setNext:function(e){r=e}};function l(){var n;return e&&xe(e[Zo])&&(n=e[Zo]()),n||(n=tl(o,t,i)),n}function c(t,i,s,a,o){var l=!1,c=e?e[On]:"TelemetryPluginChain",d=t[Qo];return d||(d=t[Qo]={}),t.setNext(r),e&&Vo(t[Xr](),(function(){return c+":"+s}),(function(){d[n]=!0;try{var e=r?r._id:Qr;e&&(d[e]=!1),l=i(t)}catch(e){var a=!r||d[r._id];a&&(l=!0),r&&a||to(t[tr](),1,73,"Plugin ["+c+"] failed during "+s+" - "+rt(e)+", run flags: "+rt(d))}}),a,o),l}return ht(o)}(e,t,i);r||(r=o),a&&a._setNext(o),a=o}}))}return n&&!r?rl([n],t,i):r}function sl(){var e=[];return{add:function(t){t&&e[Pn](t)},run:function(t,i){ti(e,(function(e){try{e(t,i)}catch(e){to(t[tr](),2,73,"Unexpected error calling unload handler - "+rt(e))}})),e=[]}}}function al(){var e=[];return{run:function(t){var i=e;e=[],ti(i,(function(e){try{(e.rm||e.remove).call(e)}catch(e){to(t,2,73,"Unloading:"+rt(e))}}))},add:function(t){t&&ei(e,t)}}}var ol,ll="getPlugin",cl=((Yo={})[is]={isVal:ys,v:{}},Yo),dl=function(){function e(){var t,i,n,r,s,a=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||tl(null,{},a[Xr]);t=n&&n[ll]?r[Yn](null,n[ll]):r[Yn](null,n)}return t}function l(e,t,r){Da(e,cl,Ya(t)),!r&&t&&(r=t[jn]()[rr]());var s=n;n&&n[ll]&&(s=n[ll]()),a[Xr]=t,i=tl(r,e,t,s)}function c(){t=!1,a[Xr]=null,i=null,n=null,s=al(),r=sl()}c(),hn(e,a,(function(e){e[kn]=function(e,i,n,r){l(e,i,r),t=!0},e[Qn]=function(t,i){var a,o=e[Xr];if(o&&(!t||o===t[Xr]())){var l,d=!1,u=t||il(null,o,n&&n[ll]?n[ll]():n),h=i||((a={reason:0})[er]=!1,a);return e[ir]&&!0===e[ir](u,h,g)?l=!0:g(),l}function g(){d||(d=!0,r.run(u,i),s.run(u[tr]()),!0===l&&u[$n](h),c())}},e[nr]=function(t,i){var r=e[Xr];if(r&&(!t||r===t[Xr]())){var s,a=!1,o=t||nl(null,r,n&&n[ll]?n[ll]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?s=!0:d(),s}function d(){a||(a=!0,l(o.getCfg(),o.core(),o[rr]()))}},Is(e,"_addUnloadCb",(function(){return r}),"add"),Is(e,"_addHook",(function(){return s}),"add"),Xe(e,"_unloadHooks",{g:function(){return s}})})),a[tr]=function(e){return o(e)[tr]()},a[xn]=function(){return t},a.setInitialized=function(e){t=e},a[sr]=function(e){n=e},a[$n]=function(e,t){t?t[$n](e):n&&xe(n[rs])&&n[rs](e,null)},a._getTelCtx=o}return e.__ieDyn=1,e}(),ul=function(e){function t(){var i,n,r=e.call(this)||this;function s(){i=0,n=[]}return r.identifier="TelemetryInitializerPlugin",r.priority=199,s(),hn(t,r,(function(e,t){e.addTelemetryInitializer=function(e){return function(e,t,i){var n={id:t,fn:i};return ei(e,n),{remove:function(){ti(e,(function(t,i){if(t.id===n.id)return e[Rn](i,1),-1}))}}}(n,i++,e)},e[rs]=function(t,i){(function(e,t,i){for(var n=!1,r=e[yn],s=0;s<r;++s){var a=e[s];if(a)try{if(!1===a.fn[An](null,[t])){n=!0;break}}catch(e){to(i,2,64,"Telemetry initializer failed: "+bs(e),{exception:rt(e)},!0)}}return!n})(n,t,i?i[tr]():e[tr]())&&e[$n](t,i)},e[ir]=function(){s()}})),r}return Oi(t,e),t.__ieDyn=1,t}(dl),hl="Plugins must provide initialize method",gl="SDK is still unloading...",pl=dt(((ol={cookieCfg:{}})[ns]={rdOnly:!0,ref:!0,v:[]},ol[Zr]={rdOnly:!0,ref:!0,v:[]},ol[is]={ref:!0,v:{}},ol[es]=Yr,ol.loggingLevelConsole=0,ol.diagnosticLogInterval=Yr,ol));function ml(e,t){return new Uo(t)}function fl(e,t){var i=!1;return ti(t,(function(t){if(t===e)return i=!0,-1})),i}function vl(e,t,i,n){i&&Ke(i,(function(i,r){n&&mi(r)&&mi(t[i])&&vl(e,t[i],r,n),n&&mi(r)&&mi(t[i])?vl(e,t[i],r,n):e.set(t,i,r)}))}function Sl(e,t){var i=null,n=-1;return ti(e,(function(e,r){if(e.w===t)return i=e,n=r,-1})),{i:n,l:i}}var yl=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P;hn(e,this,(function(e){function R(e){return w&&w[Gn]||P||(e||n&&n.queue[yn]>0)&&(A||(A=!0,j(t[In]((function(e){var t=e.cfg.diagnosticLogInterval;t&&t>0||(t=1e4);var i=!1;w&&(i=w[Gn],w[Dn]()),(w=function(e,t){return Ri(!1,oe,Ae[Se](arguments))}(F,t)).unref(),w[Gn]=i})))),w[Gn]=!0),w}function M(){var e={};_=[];var t=function(t){t&&ti(t,(function(t){if(t[On]&&t[Kn]&&!e[t.identifier]){var i=t[On]+"="+t[Kn];_[Pn](i),e[t.identifier]=t}}))};t(h),u&&ti(u,(function(e){t(e)})),t(d)}function D(){i=!1,(t=Da({},pl,e[wn])).cfg[Jn]=1,Xe(e,"config",{g:function(){return t.cfg},s:function(t){e.updateCfg(t,!1)}}),Xe(e,"pluginVersionStringArr",{g:function(){return _||M(),_}}),Xe(e,"pluginVersionString",{g:function(){return I||(_||M(),I=_.join(";")),I||Qr}}),Xe(e,"logger",{g:function(){return n||(n=new Xa(t.cfg),t[wn]=n),n},s:function(e){t[wn]=e,n!==e&&(Oa(n,!1),n=e)}}),e[wn]=new Xa(t.cfg),b=[];var y=e.config[ns]||[];y.splice(0,y[yn]),ei(y,b),p=new ul,r=[],Oa(s,!1),s=null,a=null,o=null,Oa(l,!1),l=null,c=null,d=[],u=null,h=null,g=!1,m=null,f=la("AIBaseCore",!0),v=sl(),C=null,T=null,S=al(),E=[],I=null,_=null,P=!1,w=null,A=!1}function k(){var i=tl(L(),t.cfg,e);return i[Wn](R),i}function O(t){var i=function(e,t,i){var n,r=[],s=[],a={};return ti(i,(function(t){(ke(t)||ke(t[kn]))&&st(hl);var i=t[ss],n=t[On];t&&i&&(ke(a[i])?a[i]=n:io(e,"Two extensions have same priority #"+i+" - "+a[i]+", "+n)),!i||i<500?r[Pn](t):s[Pn](t)})),(n={})[Xr]=r,n[Zr]=s,n}(e[wn],0,d);c=null,I=null,_=null,h=Jo(ei(h=(u||[])[0]||[],i[Zr]));var n=ei(Jo(i[Xr]),h);b=ht(n);var r=e.config[ns]||[];r.splice(0,r[yn]),ei(r,b);var s=k();h&&h[yn]>0&&Ko(s[Yn](h),n),Ko(s,n),t&&V(t)}function N(e){var t=null,i=null,n=[];return ti(b,(function(t){if(t[On]===e&&t!==p)return i=t,-1;t.getChannel&&n[Pn](t)})),!i&&n[yn]>0&&ti(n,(function(t){if(!(i=t.getChannel(e)))return-1})),i&&(t={plugin:i,setEnabled:function(e){Wo(i)[ts]=!e},isEnabled:function(){var e=Wo(i);return!e[Qn]&&!e[ts]},remove:function(e,t){var n;void 0===e&&(e=!0);var r=[i],s=((n={reason:1})[er]=e,n);x(r,s,(function(e){e&&O({reason:32,removed:r}),t&&t(e)}))}}),t}function L(){if(!c){var i=(b||[]).slice();-1===ii(i,p)&&i[Pn](p),c=rl(Jo(i),t.cfg,e)}return c}function x(i,n,r){if(i&&i[yn]>0){var s=il(rl(i,t.cfg,e),e);s[Wn]((function(){var e=!1,t=[];ti(d,(function(n,r){fl(n,i)?e=!0:t[Pn](n)})),d=t,I=null,_=null;var n=[];u&&(ti(u,(function(t,r){var s=[];ti(t,(function(t){fl(t,i)?e=!0:s[Pn](t)})),n[Pn](s)})),u=n),r&&r(e),R()})),s[$n](n)}else r(!1)}function F(){if(n&&n.queue){var t=n.queue.slice(0);n.queue[yn]=0,ti(t,(function(t){var i,n=((i={})[Vn]=m||"InternalMessageId: "+t[Zn],i.iKey=T,i[Hn]=Es(new Date),i.baseType=Ja.dataType,i.baseData={message:t[Xn]},i);e.track(n)}))}}function U(e,t,i,n){var r=1,s=!1,a=null;function o(){r--,s&&0===r&&(a&&a[Dn](),a=null,t&&t(s),t=null)}return n=n||5e3,h&&h[yn]>0&&k()[Yn](h).iterate((function(t){if(t.flush){r++;var s=!1;t.flush(e,(function(){s=!0,o()}),i)||s||(e&&null==a?a=Mi((function(){a=null,o()}),n):o())}})),s=!0,o(),!0}function B(){var i;j(t[In]((function(t){if(t.cfg.enablePerfMgr){var n=t.cfg[es];i!==n&&(n||(n=ml),function(e,t,i){var n;e?!(n=e[t])&&ke(n)&&(n=De(i)?{}:i,e[t]=n):n=De(i)?{}:i}(t.cfg,es,n),i=n,o=null),a||o||!xe(n)||(o=n(e,e[Fn]()))}else o=null,i=null})))}function V(t){var i=nl(L(),e);i[Wn](R),e._updateHook&&!0===e._updateHook(i,t)||i[$n](t)}function H(t){var i=e[wn];i?(to(i,2,73,t),R()):st(t)}function $(t){var i=e[Fn]();i&&i[os]([t],2)}function j(e){S.add(e)}D(),e._getDbgPlgTargets=function(){return[b]},e[xn]=function(){return i},e[kn]=function(r,a,o,l){g&&st(gl),e[xn]()&&st("Core cannot be initialized more than once"),r=(t=Da(r,pl,o||e[wn],!1)).cfg,j(t[In]((function(e){T=e.cfg.instrumentationKey;var t=e.ref(e.cfg,is);Ke(t,(function(i){e.ref(t,i)})),ke(T)&&st("Please provide instrumentation key")}))),y=function(e,t,i,n){return t.add(e[In]((function(e){var t=e.cfg.disableDbgExt;!0===t&&n&&(i[Nn](n),n=null),i&&!n&&!0!==t&&(n=function(e){if(!Ua){Ua={};for(var t=0;t<Va[yn];t++)Ua[Va[t]]=$a(Va[t],e)}return Ua}(e.cfg),i[Ln](n))}))),n}(t,S,(s=l)&&e[Fn](),y),B(),e[wn]=o;var c=r[ns];if((d=[])[Pn].apply(d,Ni(Ni([],a),c)),u=r[Zr],O(null),h&&0!==h[yn]||st("No "+Zr+" available"),u&&u[yn]>1){var p=e[Un]("TeeChannelController");p&&p.plugin||to(n,1,28,"TeeChannel required")}(function(e,t,i){ti(t,(function(t){var n=ka(e,t.w,i);delete t.w,t.rm=function(){n.rm()}}))})(r,E,n),E=null,i=!0,e.releaseQueue(),e[Bn]()},e.getChannels=function(){var e=[];return h&&ti(h,(function(t){e[Pn](t)})),ht(e)},e.track=function(t){Vo(e[gs](),(function(){return"AppInsightsCore:track"}),(function(){null===t&&($(t),st("Invalid telemetry item")),!t[Vn]&&ke(t[Vn])&&($(t),st("telemetry name required")),t.iKey=t.iKey||T,t[Hn]=t[Hn]||Es(new Date),t.ver=t.ver||"4.0",!g&&e[xn]()?k()[$n](t):r[Pn](t)}),(function(){return{item:t}}),!t.sync)},e[jn]=k,e[Fn]=function(){return s||(s=new Oo(t.cfg),e._notificationManager=s),s},e[Ln]=function(t){e.getNotifyMgr()[Ln](t)},e[Nn]=function(e){s&&s[Nn](e)},e.getCookieMgr=function(){return l||(l=bo(t.cfg,e[wn])),l},e.setCookieMgr=function(e){l!==e&&(Oa(l,!1),l=e)},e[gs]=function(){return a||o||null},e.setPerfMgr=function(e){a=e},e.eventCnt=function(){return r[yn]},e.releaseQueue=function(){if(i&&r[yn]>0){var e=r;r=[],ti(e,(function(e){k()[$n](e)}))}},e[Bn]=function(e){return m=e||null,P=!1,w&&w[Dn](),R(!0)},e[qn]=function(){P=!0,w&&w[Dn](),F()},ws(e,(function(){return p}),["addTelemetryInitializer"]),e[zn]=function(t,r,a){var o;void 0===t&&(t=!0),i||st("SDK is not initialized"),g&&st(gl);var c,d=((o={reason:50})[er]=t,o.flushComplete=!1,o);t&&!r&&(c=Kr((function(e){r=e})));var u=il(L(),e);return u[Wn]((function(){S.run(e[wn]),Na([l,s,n],t,(function(){D(),r&&r(d)}))}),e),F(),U(t,(function(t){d.flushComplete=t,g=!0,v.run(u,d),e[qn](),u[$n](d)}),6,a),c},e[Un]=N,e.addPlugin=function(e,t,i,n){if(!e)return n&&n(!1),void H(hl);var r=N(e[On]);if(r&&!t)return n&&n(!1),void H("Plugin ["+e[On]+"] is already loaded!");var s={reason:16};function a(t){d[Pn](e),s.added=[e],O(s),n&&n(!0)}if(r){var o=[r.plugin];x(o,{reason:2,isAsync:!!i},(function(e){e?(s.removed=o,s.reason|=32,a()):n&&n(!1)}))}else a()},e.updateCfg=function(i,n){var r;if(void 0===n&&(n=!0),e[xn]()){r={reason:1,cfg:t.cfg,oldCfg:Ti({},t.cfg),newConfig:Ti({},i),merge:n},i=r.newConfig;var s=t.cfg;i[ns]=s[ns],i[Zr]=s[Zr]}t._block((function(e){var t=e.cfg;vl(e,t,i,n),n||Ke(t,(function(n){We(i,n)||e.set(t,n,Yr)})),e[_n](t,pl)}),!0),t[Tn](),r&&V(r)},e.evtNamespace=function(){return f},e.flush=U,e.getTraceCtx=function(e){return C||(C=function(){var e={};return{getName:function(){return e[Vn]},setName:function(t){e[Vn]=t},getTraceId:function(){return e[wr]},setTraceId:function(t){Go(t)&&(e[wr]=t)},getSpanId:function(){return e[Ar]},setSpanId:function(t){qo(t)&&(e[Ar]=t)},getTraceFlags:function(){return e[Pr]},setTraceFlags:function(t){e[Pr]=t}}}()),C},e.setTraceCtx=function(e){C=e||null},e.addUnloadHook=j,Is(e,"addUnloadCb",(function(){return v}),"add"),e.onCfgChange=function(n){return function(e){return Xe({rm:function(){e.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(e)+">"}})}(i?ka(t.cfg,n,e[wn]):function(e,t){var i=Sl(e,t).l;return i||(i={w:t,rm:function(){var i=Sl(e,t);-1!==i.i&&e[Rn](i.i,1)}},e[Pn](i)),i}(E,n))},e.getWParam=function(){return Ut()||t.cfg.enableWParam?0:-1}}))}return e.__ieDyn=1,e}(),Cl="",Tl="&NoResponseBody=true",El="POST",bl=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p=0;hn(e,this,(function(e,m){var f=!0;function v(e,t){to(n,2,26,"Failed to send telemetry.",{message:e}),y(t,400,{})}function S(e){v("No endpoint url is provided for the batch",e)}function y(e,t,i,n){try{e&&e(t,i,n)}catch(e){}}function C(e,t){var i=Gt(),n=e[Tr];if(!n)return S(t),!0;n=e[Tr]+(h?Tl:Cl);var s=e[vr],a=r?s:new Blob([s],{type:"text/plain;charset=UTF-8"});return i.sendBeacon(n,a)}function T(e,t,i){var a=e[vr];try{if(a)if(C(e,t))!function(e,t){y(t,200,{},"")}(0,t);else{var l=s&&s.beaconOnRetry;l&&xe(l)?l(e,t,C):(o&&o[Er](e,t,!0),to(n,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(e){r&&io(n,"Failed to send telemetry using sendBeacon API. Ex:"+rt(e)),y(t,r?0:400,{},Cl)}}function E(e,i,n){var a,o,l,c=e[br]||{};!n&&t&&(a=Kr((function(e,t){o=e,l=t}))),r&&n&&e.disableXhrSync&&(n=!1);var d=e[Tr];if(!d)return S(i),void(o&&o(!1));var u=function(e,t,i,n,r,s){function a(e,t,i){try{e[t]=i}catch(e){}}void 0===n&&(n=!1),void 0===r&&(r=!1);var o=new XMLHttpRequest;return n&&a(o,"Microsoft_ApplicationInsights_BypassAjaxInstrumentation",n),i&&a(o,ks,i),o.open(e,t,!r),i&&a(o,ks,i),!r&&s&&a(o,"timeout",s),o}(El,d,f,!0,n,e[_r]);function h(t){var n=s&&s.xhrOnComplete;if(n&&xe(n))n(t,i,e);else{var a=Rs(t);y(i,t[gr],Ns(t,r),a)}}return r||u[Ir]("Content-type","application/json"),ti(ct(c),(function(e){u[Ir](e,c[e])})),u.onreadystatechange=function(){r||(h(u),4===u.readyState&&o&&o(!0))},u.onload=function(){r&&h(u)},u.onerror=function(e){y(i,r?u[gr]:400,Ns(u,r),r?Cl:Ms(u)),l&&l(e)},u.ontimeout=function(){y(i,r?u[gr]:500,Ns(u,r),r?Cl:Ms(u)),o&&o(!1)},u.send(e[vr]),a}function b(e,i,n){var a,o,l,c,d=e[Tr],u=e[vr],m=r?u:new Blob([u],{type:"application/json"}),v=new Headers,C=u[yn],T=!1,E=!1,b=e[br]||{},_=((a={method:El,body:m})[La]=!0,a);e.headers&&ct(e.headers)[yn]>0&&(ti(ct(b),(function(e){v.append(e,b[e])})),_[br]=v),f&&r&&(_.credentials="include"),n&&(_.keepalive=!0,p+=C,r?2===e._sendReason&&(T=!0,h&&(d+=Tl)):T=!0);var I=new Request(d,_);try{I[La]=!0}catch(e){}if(!n&&t&&(o=Kr((function(e,t){l=e,c=t}))),!d)return S(i),void(l&&l(!1));function w(e){y(i,r?0:400,{},r?Cl:e)}function A(e,t,n){var r=e[gr],a=s.fetchOnComplete;a&&xe(a)?a(e,i,n||Cl,t):y(i,r,{},n||Cl)}try{Dr(fetch(r?d:I,r?_:null),(function(t){if(n&&(p-=C,C=0),!E)if(E=!0,t.rejected)w(t.reason&&t.reason[Xn]),c&&c(t.reason);else{var i=t.value;try{r||i.ok?r&&!i.body?(A(i,null,Cl),l&&l(!0)):Dr(i.text(),(function(t){A(i,e,t.value),l&&l(!0)})):(w(i.statusText),l&&l(!1))}catch(t){w(rt(t)),c&&c(t)}}}))}catch(e){E||(w(rt(e)),c&&c(e))}return T&&!E&&(E=!0,y(i,200,{}),l&&l(!0)),r&&!E&&e[_r]>0&&g&&g.set((function(){E||(E=!0,y(i,500,{}),l&&l(!0))}),e[_r]),o}function _(e,t,i){var a=jt(),o=new XDomainRequest,l=e[vr];o.onload=function(){var i=Rs(o),n=s&&s.xdrOnComplete;n&&xe(n)?n(o,t,e):y(t,200,{},i)},o.onerror=function(){y(t,400,{},r?Cl:function(e){return e?"XDomainRequest,Response:"+Rs(e)||0:void 0}(o))},o.ontimeout=function(){y(t,500,{})},o.onprogress=function(){};var c=a&&a.location&&a.location[ar]||"",d=e[Tr];if(d){if(!r&&0!==d.lastIndexOf(c,0)){var u="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return to(n,2,40,". "+u),void v(u,t)}var h=r?d:d[dr](/^(https?:)/,"");o.open(El,h),e[_r]&&(o[_r]=e[_r]),o.send(l),r&&i?g&&g.set((function(){o.send(l)}),0):o.send(l)}else S(t)}function I(){p=0,i=!1,t=!1,n=null,r=null,s=null,a=null,o=null,l=!1,c=!1,d=!1,u=!1,h=!1,g=null}I(),e[kn]=function(t,r){n=r,i&&to(n,1,28,"Sender is already initialized"),e.SetConfig(t),i=!0},e._getDbgPlgTargets=function(){return[i,r,a,t]},e.SetConfig=function(e){try{if(s=e.senderOnCompleteCallBack||{},a=!!e.disableCredentials,r=!!e.isOneDs,t=!!e.enableSendPromise,l=!!e.disableXhr,c=!!e.disableBeacon,d=!!e.disableBeaconSync,g=e.timeWrapper,h=!!e.addNoResponse,u=!!e.disableFetchKeepAlive,o={sendPOST:E},r||(f=!1),a){var i=$s();i&&i.protocol&&"file:"===i.protocol[vn]()&&(f=!1)}return!0}catch(e){}return!1},e.getSyncFetchPayload=function(){return p},e.getSenderInst=function(e,t){return e&&e[yn]?function(e,t){for(var i,n=0,r=null,s=0;null==r&&s<e[yn];)n=e[s],l||1!==n?2!==n||!Ws(t)||t&&u?3!==n||!zs()||(t?d:c)||(r=T):r=b:(null===Bs&&(Bs=typeof XDomainRequest!==ee)&&Ks()&&(Bs=Bs&&!Hs(Ft(xs),"withCredentials")),Bs?r=_:Ks()&&(r=E)),s++;return r?((i={_transport:n,_isSync:t})[Er]=r,i):null}(e,t):null},e.getFallbackInst=function(){return o},e[ir]=function(e,t){I()}}))}return e.__ieDyn=1,e}(),_l="attachEvent",Il="addEventListener",wl="detachEvent",Al="removeEventListener",Pl="events",Rl="visibilitychange",Ml="pagehide",Dl="pageshow",kl="unload",Ol="beforeunload",Nl=la("aiEvtPageHide"),Ll=la("aiEvtPageShow"),xl=/\.[\.]+/g,Fl=/[\.]+$/,Ul=1,Bl=ca("events"),Vl=/^([^.]*)(?:\.(.+)|)/;function Hl(e){return e&&e[dr]?e[dr](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Qr):e}function $l(e,t){var i;if(t){var n=Qr;Ue(t)?(n=Qr,ti(t,(function(e){(e=Hl(e))&&("."!==e[0]&&(e="."+e),n+=e)}))):n=Hl(t),n&&("."!==n[0]&&(n="."+n),e=(e||Qr)+n)}var r=Vl.exec(e||Qr)||[];return(i={})[ur]=r[1],i.ns=(r[2]||Qr).replace(xl,".").replace(Fl,Qr)[lr](".").sort().join("."),i}function jl(e,t,i){void 0===i&&(i=!0);var n=Bl.get(e,Pl,{},i),r=n[t];return r||(r=n[t]=[]),r}function Gl(e,t,i,n){e&&t&&t[ur]&&(e[Al]?e[Al](t[ur],i,n):e[wl]&&e[wl]("on"+t[ur],i))}function ql(e,t,i,n){for(var r=t[yn];r--;){var s=t[r];s&&(i.ns&&i.ns!==s.evtName.ns||n&&!n(s)||(Gl(e,s.evtName,s[hr],s.capture),t[Rn](r,1)))}}function zl(e,t){return t?$l("xx",Ue(t)?[e].concat(t):[e,t]).ns[lr]("."):e}function Wl(e,t,i,n,r){var s;void 0===r&&(r=!1);var a=!1;if(e)try{var o=$l(t,n);if((a=function(e,t,i,n){var r=!1;return e&&t&&t[ur]&&i&&(e[Il]?(e[Il](t[ur],i,n),r=!0):e[_l]&&(e[_l]("on"+t[ur],i),r=!0)),r}(e,o,i,r))&&Bl.accept(e)){var l=((s={guid:Ul++,evtName:o})[hr]=i,s.capture=r,s);jl(e,o.type)[Pn](l)}}catch(e){}return a}function Kl(e,t,i,n,r){if(void 0===r&&(r=!1),e)try{var s=$l(t,n),a=!1;(function(e,t,i){if(t[ur])ql(e,jl(e,t[ur]),t,i);else{var n=Bl.get(e,Pl,{});Ke(n,(function(n,r){ql(e,r,t,i)})),0===ct(n)[yn]&&Bl.kill(e,Pl)}})(e,s,(function(e){return!((!s.ns||i)&&e[hr]!==i||(a=!0,0))})),a||Gl(e,s,i,r)}catch(e){}}function Jl(e,t,i,n){var r=!1;return t&&e&&e[yn]>0&&ti(e,(function(e){e&&(i&&-1!==ii(i,e)||(r=function(e,t,i){var n=!1,r=jt();r&&(n=Wl(r,e,t,i),n=Wl(r.body,e,t,i)||n);var s=$t();return s&&(n=Wl(s,e,t,i)||n),n}(e,t,n)||r))})),r}function Yl(e,t,i){e&&Ue(e)&&ti(e,(function(e){e&&function(e,t,i){var n=jt();n&&(Kl(n,e,t,i),Kl(n.body,e,t,i));var r=$t();r&&Kl(r,e,t,i)}(e,t,i)}))}function Ql(e,t,i){var n=zl(Nl,i),r=Jl([Ml],e,t,n);return t&&-1!==ii(t,Rl)||(r=Jl([Rl],(function(t){var i=$t();e&&i&&"hidden"===i.visibilityState&&e(t)}),t,n)||r),!r&&t&&(r=Ql(e,null,i)),r}function Zl(e,t,i){var n=zl(Ll,i),r=Jl([Dl],e,t,n);return!(r=Jl([Rl],(function(t){var i=$t();e&&i&&"visible"===i.visibilityState&&e(t)}),t,n)||r)&&t&&(r=Zl(e,null,i)),r}var Xl,ec="",tc="version",ic="properties",nc="initialize",rc="logger",sc="timings",ac="pollInternalLogs",oc="value",lc="kind",cc="length",dc="processTelemetryStart",uc="1DS-Web-JS-4.2.1",hc=ne.hasOwnProperty,gc=((Xl={})[0]=0,Xl[2]=6,Xl[1]=1,Xl[3]=7,Xl[4098]=6,Xl[4097]=1,Xl[4099]=7,Xl);function pc(e){return!(e===ec||ke(e))}function mc(e,t,i){var n=-1;if(!De(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=gc[Tc(e)]||-1;-1!==n&&-1!==r?n|=r:6===r&&(n=r)}return n}function fc(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||ec}function vc(e){void 0===e&&(e="D");var t=Ho();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,ec)),t}function Sc(e,t,i,n,r){var s={},a=!1,o=0,l=arguments[cc],c=arguments;for(He(c[0])&&(a=c[0],o++);o<l;o++)Ke(c[o],(function(e,t){a&&t&&Fe(t)?Ue(t)?(s[e]=s[e]||[],ti(t,(function(t,i){t&&Fe(t)?s[e][i]=Sc(!0,s[e][i],t):s[e][i]=t}))):s[e]=Sc(!0,s[e],t):s[e]=t}));return s}var yc=function(){return ci()};function Cc(e,t){var i=e;i[sc]=i[sc]||{},i[sc][dc]=i[sc][dc]||{},i[sc][dc][t]=yc()}function Tc(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===X&&(t=4,Ue(e)?(t=4096,e[cc]>0&&(t|=Tc(e[0]))):hc.call(e,"value")&&(t=8192|Tc(e[oc])))}return t}function Ec(e){return e>0}var bc=dt({endpointUrl:"https://browser.events.data.microsoft.com/OneCollector/1.0/",propertyStorageOverride:{isVal:function(e){return!e||e.getProperty&&e.setProperty||st("Invalid property storage override passed."),!0}}}),_c=function(e){function t(){var i=e.call(this)||this;return hn(t,i,(function(e,t){e[nc]=function(i,n,r,s){Vo(e,(function(){return"AppInsightsCore.initialize"}),(function(){try{t[nc](Da(i,bc,r||e[rc],!1).cfg,n,r,s)}catch(t){var a=e[rc],o=rt(t);-1!==o.indexOf("channels")&&(o+="\n - Channels must be provided through config.channels only!"),to(a,1,514,"SDK Initialization Failed - no telemetry will be sent: "+o)}}),(function(){return{config:i,extensions:n,logger:r,notificationManager:s}}))},e.track=function(i){Vo(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n[sc]=n[sc]||{},n[sc].trackStart=yc(),function(e){return!!(e&&Ve(e)&&e>=1&&e<=4)}(n.latency)||(n.latency=1);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=uc;var s=n.baseData=n.baseData||{};s[ic]=s[ic]||{};var a=s[ic];a[tc]=a[tc]||e.pluginVersionString||ec}t.track(n)}),(function(){return{item:i}}),!i.sync)},e[ac]=function(e){return t[ac](e||"InternalLog")}})),i}return Oi(t,e),t.__ieDyn=1,t}(yl),Ic=pn({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),wc=pn({Normal:1,Critical:2}),Ac="REAL_TIME",Pc="",Rc="drop",Mc="requeue",Dc="no-cache, no-store",kc="application/x-json-stream",Oc="cache-control",Nc="content-type",Lc="client-version",xc="client-id",Fc="time-delta-to-apply-millis",Uc="upload-time",Bc="apikey",Vc="AuthMsaDeviceTicket",Hc="WebAuthToken",$c="AuthXToken",jc="msfpc",Gc="trace",qc="user",zc="allowRequestSending",Wc="firstRequestSent",Kc="shouldAddClockSkewHeaders",Jc="getClockSkewHeaderValue",Yc="setClockSkew",Qc="length",Zc="concat",Xc="iKey",ed="count",td="events",id="push",nd="split",rd="splice",sd="toLowerCase",ad="hdrs",od="useHdrs",ld="initialize",cd="setTimeoutOverride",dd="clearTimeoutOverride",ud="overrideEndpointUrl",hd="avoidOptions",gd="enableCompoundKey",pd="disableXhrSync",md="disableFetchKeepAlive",fd="useSendBeacon",vd="alwaysUseXhrOverride",Sd="serializeOfflineEvt",yd="getOfflineRequestDetails",Cd="createPayload",Td="createOneDSPayload",Ed="payloadBlob",bd="headers",_d="_thePayload",Id="urlString",wd="batches",Ad="sendType",Pd="addHeader",Rd="canSendRequest",Md="sendQueuedRequests",Dd="isCompletelyIdle",kd="setUnloading",Od="sendSynchronousBatch",Nd="_transport",Ld="getWParam",xd="isBeacon",Fd="timings",Ud="isTeardown",Bd="isSync",Vd="data",Hd="_sendReason",$d="setKillSwitchTenants",jd="_backOffTransmission",Gd="identifier",qd="eventsLimitInMem",zd="autoFlushEventsLimit",Wd="baseData",Kd="sendAttempt",Jd="latency",Yd="sync";function Qd(e){var t=(e.ext||{}).intweb;return t&&pc(t[jc])?t[jc]:null}function Zd(e){for(var t=null,i=0;null===t&&i<e[Qc];i++)t=Qd(e[i]);return t}var Xd=function(){function e(t,i){var n=i?[][Zc](i):[],r=this,s=Zd(n);r[Xc]=function(){return t},r.Msfpc=function(){return s||Pc},r[ed]=function(){return n[Qc]},r[td]=function(){return n},r.addEvent=function(e){return!!e&&(n[id](e),s||(s=Qd(e)),!0)},r[nd]=function(i,r){var a;if(i<n[Qc]){var o=n[Qc]-i;ke(r)||(o=r<o?r:o),a=n[rd](i,o),s=Zd(n)}return new e(t,a)}}return e.create=function(t,i){return new e(t,i)},e}(),eu=function(){function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",s=!1;hn(e,this,(function(e){e[zc]=function(){return t},e[Wc]=function(){n&&(n=!1,s||(t=!1))},e[Kc]=function(){return i},e[Jc]=function(){return r},e[Yc]=function(e){s||(e?(r=e,i=!0,s=!0):i=!1,t=!0)}}))}return e.__ieDyn=1,e}(),tu=function(){function e(){var t={};hn(e,this,(function(e){e[$d]=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&ti(e,(function(e){t[id](pi(e))})),t}(e[nd](","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),s=0;s<n[Qc];++s)t[n[s]]=ci()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=pi(e);return void 0!==i[n]&&i[n]>ci()||(delete i[n],!1)}}))}return e.__ieDyn=1,e}();function iu(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)}var nu,ru=2e6,su=Math.min(ru,65e3),au="metadata",ou="f",lu=/\./,cu=function(){function e(t,i,n,r,s,a){var o="data",l="baseData",c=!!r,d=!0,u=i,h={},g=!!a,p=s||mc;hn(e,this,(function(e){function i(e,t){var i=h[e];return void 0===i&&(e.length>=7&&(i=Ii(e,"ext.metadata")||Ii(e,"ext.web")),h[e]=i),i}function r(e,t,s,a,o,l,d){Ke(e,(function(e,h){var g=null;if(h||pc(h)){var p=s,m=e,f=o,v=t;if(c&&!a&&lu.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var T=S[C];v=v[T]=v[T]||{},p+="."+T,f&&f.push(T)}m=S[y-1]}}if(g=a&&i(p)||!u||!u.handleField(p,m)?function(e,t,i){if(!t&&!pc(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||Ue(t))t={value:t};else if("object"!==n||hc.call(t,"value")){if(ke(t[oc])||t[oc]===ec||!Le(t[oc])&&!Ve(t[oc])&&!He(t[oc])&&!Ue(t[oc]))return null}else t={value:i?JSON.stringify(t):t};if(Ue(t[oc])&&!function(e){return e[cc]>0}(t[oc]))return null;if(!ke(t[lc])){if(Ue(t[oc])||!function(e){return 0===e||e>0&&e<=13||32===e}(t[lc]))return null;t[oc]=t[oc].toString()}return t}(m,h,n):u.value(p,m,h,n)){var E=g.value;if(v[m]=E,l&&l(f,m,g),d&&"object"==typeof E&&!Ue(E)){var b=f;b&&(b=b.slice()).push(m),r(h,E,p+"."+m,a,b,l,d)}}}}))}e.createPayload=function(e,t,i,n,r,s){return{apiKeys:[],payloadBlob:Pc,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendType:s,sendReason:r}},e.appendPayload=function(i,n,r){var s=i&&n&&!i.overflow;return s&&Vo(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),s=i.payloadBlob,a=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?su:ru,g=0,p=0;g<t.length;){var m=t[g];if(m){if(a>=r){i.overflow=n.split(g);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(s.length+v>u){i.overflow=n.split(g);break}s&&(s+="\n"),s+=f,++p>20&&(bt(s,0,1),p=0),o=!0,a++}else f?l.push(m):c.push(m),t.splice(g,1),g--}g++}if(l.length>0&&i.sizeExceed.push(Xd.create(n.iKey(),l)),c.length>0&&i.failedEvts.push(Xd.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=s,i.numEvents=a;var S=n.iKey();-1===ii(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),s},e.getEventBlob=function(e){try{return Vo(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+function(e){if(e){var t=_i(e,"-");if(t>-1)return _t(e,t)}return ec}(e.iKey);var i,n={};g||(i=function(e,t,i){!function(e,t,i,n,r){if(r&&t){var s=e(r.value,r.kind,r.propertyType);if(s>-1){var a=t[au];a||(a=t[au]={f:{}});var o=a[ou];if(o||(o=a[ou]={}),i)for(var l=0;l<i.length;l++){var c=i[l];o[c]||(o[c]={f:{}});var d=o[c][ou];d||(d=o[c][ou]={}),o=d}o=o[n]={},Ue(r.value)?o.a={t:s}:o.t=s}}}(p,n,e,t,i)});var s=e.ext;s&&(t.ext=n,Ke(s,(function(e,t){r(t,n[e]={},"ext."+e,!0,null,null,!0)})));var a=t[o]={};a.baseType=e.baseType;var c=a[l]={};return r(e.baseData,c,l,!1,[l],i,d),r(e.data,a,o,!1,[],i,d),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))}return e.__ieDyn=1,e}();function du(e,t){return{set:function(i,n){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return function(e,t,i){return Ri(!0,e,Ae[Se](arguments,1))}([e,t],i,n,r)}}}var uu="sendAttempt",hu="?cors=true&"+Nc[sd]()+"="+kc,gu=((nu={})[1]=Mc,nu[100]=Mc,nu[200]="sent",nu[8004]=Rc,nu[8003]=Rc,nu),pu={},mu={};function fu(e,t,i){pu[e]=t,!1!==i&&(mu[t]=e)}function vu(e,t){var i=!1;if(e&&t){var n=ct(e);if(n&&n[Qc]>0)for(var r=t[sd](),s=0;s<n[Qc];s++){var a=n[s];if(a&&ze(t,a)&&a[sd]()===r){i=!0;break}}}return i}function Su(e,t,i,n){t&&i&&i[Qc]>0&&(n&&pu[t]?(e[ad][pu[t]]=i,e[od]=!0):e.url+="&"+t+"="+i)}fu(Vc,Vc,!1),fu(Lc,Lc),fu(xc,"Client-Id"),fu(Bc,Bc),fu(Fc,Fc),fu(Uc,Uc),fu($c,$c);var yu,Cu=function(){function e(t,i,n,r){var s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R,M,D,k,O,N,L,x=!1;hn(e,this,(function(e){function F(e,t){try{return L&&L.getSenderInst(e,t)}catch(e){}return null}function U(e,t,i){var n=Rs(e);H(t,200,{},n),ne(n)}function B(e,t,i,n){var r={},s=e[bd];s&&s.forEach((function(e,t){r[t]=e})),function(e,i,n){H(t,e,i,n),ne(n)}(e.status,r,i||Pc)}function V(e,t,i){var n=Rs(e);H(t,e.status,Ns(e,!0),n),ne(n)}function H(e,t,i,n){try{e(t,i,n)}catch(e){to(u,2,518,rt(e))}}function $(e,t,i){var n=200,r=e[_d],s=e[Id]+(A?"&NoResponseBody=true":Pc);try{var a=Gt();if(r){var o=!!g.getPlugin("LocalStorage"),l=[],c=[];ti(r[wd],(function(e){if(l&&e&&e[ed]()>0)for(var t=e[td](),i=0;i<t[Qc];i++){if(!a.sendBeacon(s,S.getEventBlob(t[i]))){l[id](e[nd](i));break}c[id](e[i])}else l[id](e[nd](0))})),c[Qc]>0&&(r.sentEvts=c),o||re(l,8003,r[Ad],!0)}else n=0}catch(e){io(u,"Failed to send telemetry using sendBeacon API. Ex:"+rt(e)),n=0}finally{H(t,n,{},Pc)}}function j(e){return 2===e||3===e}function G(e){return T&&j(e)&&(e=2),e}function q(){return!o&&c<i}function z(){var e=v;return v=[],e}function W(e,t,i){var n=!1;return e&&e[Qc]>0&&!o&&h[t]&&S&&(n=0!==t||q()&&(i>0||l[zc]())),n}function K(e){var t={};return e&&ti(e,(function(e,i){t[i]={iKey:e[Xc](),evts:e[td]()}})),t}function J(e,i,n,r,s){if(e&&0!==e[Qc])if(o)re(e,1,r);else{r=G(r);try{var l=e,c=0!==r;Vo(g,(function(){return"HttpManager:_sendBatches"}),(function(o){o&&(e=e.slice(0));for(var l=[],d=null,u=yc(),g=h[r]||(c?h[1]:h[0]),p=g&&g[Nd],m=w&&(T||j(r)||3===p||g._isSync&&2===p);W(e,r,i);){var f=e.shift();f&&f[ed]()>0&&(a.isTenantKilled(f[Xc]())?l[id](f):(d=d||S[Cd](i,n,c,m,s,r),S.appendPayload(d,f,t)?null!==d.overflow&&(e=[d.overflow][Zc](e),d.overflow=null,Z(d,u,yc(),s),u=yc(),d=null):(Z(d,u,yc(),s),u=yc(),e=[f][Zc](e),d=null)))}d&&Z(d,u,yc(),s),e[Qc]>0&&(v=e[Zc](v)),re(l,8004,r)}),(function(){return{batches:K(l),retryCount:i,isTeardown:n,isSynchronous:c,sendReason:s,useSendBeacon:j(r),sendType:r}}),!c)}catch(e){to(u,2,48,"Unexpected Exception sending batch: "+rt(e))}}}function Y(e,t){var i={url:s,hdrs:{},useHdrs:!1};t?(i[ad]=Sc(i[ad],f),i.useHdrs=ct(i.hdrs)[Qc]>0):Ke(f,(function(e,t){mu[e]?Su(i,mu[e],t,!1):(i[ad][e]=t,i[od]=!0)})),Su(i,xc,"NO_AUTH",t),Su(i,Lc,uc,t);var n=Pc;ti(e.apiKeys,(function(e){n[Qc]>0&&(n+=","),n+=e})),Su(i,Bc,n,t),Su(i,Uc,ci().toString(),t);var r=function(e){for(var t=0;t<e.batches[Qc];t++){var i=e[wd][t].Msfpc();if(i)return encodeURIComponent(i)}return Pc}(e);if(pc(r)&&(i.url+="&ext.intweb.msfpc="+r),l[Kc]()&&Su(i,Fc,l[Jc](),t),g[Ld]){var a=g[Ld]();a>=0&&(i.url+="&w="+a)}for(var o=0;o<m[Qc];o++)i.url+="&"+m[o].name+"="+m[o].value;return i}function Q(e,t,i){e[t]=e[t]||{},e[t][d.identifier]=i}function Z(e,t,i,n){if(e&&e.payloadBlob&&e.payloadBlob[Qc]>0){var r=!!R,s=h[e.sendType];!j(e[Ad])&&e[xd]&&2===e.sendReason&&(s=h[2]||h[3]||s);var a=E;(e.isBeacon||3===s[Nd])&&(a=!1);var o=Y(e,a);a=a||o[od];var d=yc();Vo(g,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var h=0;h<e.batches[Qc];h++)for(var m=e[wd][h][td](),f=0;f<m[Qc];f++){var v=m[f];if(y){var S=v[Fd]=v[Fd]||{};Q(S,"sendEventStart",d),Q(S,"serializationStart",t),Q(S,"serializationCompleted",i)}v[uu]>0?v[uu]++:v[uu]=1}re(e[wd],1e3+(n||0),e[Ad],!0);var C={data:e[Ed],urlString:o.url,headers:o[ad],_thePayload:e,_sendReason:n,timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};a&&(vu(C[bd],Oc)||(C[bd][Oc]=Dc),vu(C[bd],Nc)||(C[bd][Nc]=kc));var T=null;s&&(T=function(t){l[Wc]();var i=function(t,i){X(t,i,e,n)},r=e[Ud]||e[Bd];try{s.sendPOST(t,i,r),M&&M(C,t,r,e[xd])}catch(e){io(u,"Unexpected exception sending payload. Ex:"+rt(e)),H(i,0,{})}}),Vo(g,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(T)if(0===e[Ad]&&c++,r&&!e.isBeacon&&3!==s[Nd]){var t={data:C[Vd],urlString:C[Id],headers:Sc({},C[bd]),timeout:C.timeout,disableXhrSync:C[pd],disableFetchKeepAlive:C[md]},i=!1;Vo(g,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{R(t,(function(e){i=!0,p||e[_d]||(e[_d]=e[_d]||C[_d],e[Hd]=e[Hd]||C[Hd]),T(e)}),e.isSync||e[Ud])}catch(e){i||T(C)}}))}else T(C)}))}),(function(){return{thePayload:e,serializationStart:t,serializationCompleted:i,sendReason:n}}),e[Bd])}e.sizeExceed&&e.sizeExceed[Qc]>0&&re(e.sizeExceed,8003,e[Ad]),e.failedEvts&&e.failedEvts[Qc]>0&&re(e.failedEvts,8002,e[Ad])}function X(e,t,i,r){var s=9e3,o=null,d=!1,u=!1;try{var h=!0;if(typeof e!==ee){if(t){l[Yc](t["time-delta-millis"]);var g=t["kill-duration"]||t["kill-duration-seconds"];ti(a[$d](t["kill-tokens"],g),(function(e){ti(i[wd],(function(t){if(t[Xc]()===e){o=o||[];var n=t[nd](0);i.numEvents-=n[ed](),o[id](n)}}))}))}if(200==e||204==e)return void(s=200);(!function(e){return!(e>=300&&e<500&&429!=e||501==e||505==e)}(e)||i.numEvents<=0)&&(h=!1),s=9e3+e%1e3}if(h){s=100;var p=i.retryCnt;0===i[Ad]&&(p<n?(d=!0,ie((function(){0===i[Ad]&&c--,J(i[wd],p+1,i[Ud],T?2:i[Ad],5)}),T,iu(p))):(u=!0,T&&(s=8001)))}}finally{d||(l[Yc](),te(i,s,r,u)),re(o,8004,i[Ad])}}function te(t,i,n,r){try{r&&d[jd]();var s=t[wd];200===i&&(s=t.sentEvts||t[wd],r||t[Bd]||d._clearBackOff(),function(e){if(y){var t=yc();ti(e,(function(e){e&&e[ed]()>0&&function(e,t){y&&ti(e,(function(e){Q(e[Fd]=e[Fd]||{},"sendEventCompleted",t)}))}(e[td](),t)}))}}(s)),re(s,i,t[Ad],!0)}finally{0===t[Ad]&&(c--,5!==n&&e.sendQueuedRequests(t[Ad],n))}}function ie(e,t,i){t?e():O.set(e,i)}function ne(e){var t=D;try{for(var i=0;i<t[Qc];i++)try{t[i](e)}catch(e){to(u,1,519,"Response handler failed: "+e)}if(e){var n=JSON.parse(e);pc(n.webResult)&&pc(n.webResult[jc])&&C.set("MSFPC",n.webResult[jc],31536e3)}}catch(e){}}function re(e,t,i,n){if(e&&e[Qc]>0&&r){var s=r[function(e){var t=gu[e];return pc(t)||(t="oth",e>=9e3&&e<=9999?t="rspFail":e>=8e3&&e<=8999?t=Rc:e>=1e3&&e<=1999&&(t="send")),t}(t)];if(s){var a=0!==i;Vo(g,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){ie((function(){try{s.call(r,e,t,a,i)}catch(e){to(u,1,74,"send request notification failed: "+e)}}),n||a,0)}),(function(){return{batches:K(e),reason:t,isSync:a,sendSync:n,sendType:i}}),!a)}}}!function(){var e;s=null,a=new tu,o=!1,l=new eu,x=!1,c=0,d=null,u=null,h=null,g=null,p=!0,m=[],f={},v=[],S=null,y=!1,C=null,T=!1,E=!1,b=e,_=e,I=e,w=e,A=e,P=[],R=e,M=e,D=[],k=!1,O=du(),N=!1,L=null}(),e[ld]=function(e,t,i){k||(g=t,C=t.getCookieMgr(),u=(d=i).diagLog(),ei(P,ka(e,(function(e){var n,r=e.cfg,a=e.cfg.extensionConfig[i.identifier];O=du(a[cd],a[dd]),pc(r.anonCookieName)?function(e,t,i){for(var n=0;n<e[Qc];n++)if(e[n].name===t)return void(e[n].value=i);e[id]({name:t,value:i})}(m,"anoncknm",r.anonCookieName):function(e){for(var t=0;t<e[Qc];t++)if("anoncknm"===e[t].name)return void e[rd](t,1)}(m),R=a.payloadPreprocessor,M=a.payloadListener;var o=a.httpXHROverride,l=a[ud]?a[ud]:r.endpointUrl;s=l+hu,E=!!De(a[hd])||!a[hd],y=!a.disableEventTimings;var c=a.valueSanitizer,d=a.stringifyObjects,f=!!r[gd];De(a[gd])||(f=!!a[gd]),b=a.xhrTimeout,_=!!a[pd],I=!!a[md],A=!1!==a.addNoResponse,N=!!a.excludeCsMetaData,t.getPlugin("LocalStorage")&&(I=!0),x=!Gs(),S=new cu(g,c,d,f,mc,N),ke(a[fd])||(x=!!a[fd]);var v=function(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!1,disableXhr:!1,disableBeacon:!x,disableBeaconSync:!x,disableFetchKeepAlive:I,timeWrapper:O,addNoResponse:A,senderOnCompleteCallBack:{xdrOnComplete:U,fetchOnComplete:B,xhrOnComplete:V,beaconOnRetry:$}}}catch(e){}return null}();L?L.SetConfig(v):(L=new bl)[ld](v,u);var C=o,T=a[vd]?o:null,P=a[vd]?o:null,D=[3,2];if(!o){p=!1;var k=[];Gs()?(k=[2,1],D=[2,1,3]):k=[1,2,3],(o=F(k=Ds(k,a.transports),!1))||io(u,"No available transport to send events"),C=F(k,!0)}T||(T=F(D=Ds(D,a.unloadTransports),!0)),w=!p&&(x&&zs()||!I&&Ws(!0)),(n={})[0]=o,n[1]=C||F([1,2,3],!0),n[2]=T||C||F([1],!0),n[3]=P||F([2,3],!0)||C||F([1],!0),h=n}))),k=!0)},e.addResponseHandler=function(e){return D[id](e),{rm:function(){var t=D.indexOf(e);t>=0&&D[rd](t,1)}}},e[Sd]=function(e){try{if(S)return S.getEventBlob(e)}catch(e){}return Pc},e[yd]=function(){try{return Y(S&&S[Cd](0,!1,!1,!1,1,0),E)}catch(e){}return null},e[Td]=function(e,i){try{var n=[];ti(e,(function(e){i&&(e=As(e));var t=Xd.create(e[Xc],[e]);n[id](t)}));for(var r=null;n[Qc]>0&&S;){var s=n.shift();s&&s[ed]()>0&&(r=r||S[Cd](0,!1,!1,!1,1,0),S.appendPayload(r,s,t))}var a=Y(r,E),o={data:r[Ed],urlString:a.url,headers:a[ad],timeout:b,disableXhrSync:_,disableFetchKeepAlive:I};return E&&(vu(o[bd],Oc)||(o[bd][Oc]=Dc),vu(o[bd],Nc)||(o[bd][Nc]=kc)),o}catch(e){}return null},e._getDbgPlgTargets=function(){return[h[0],a,S,h]},e[Pd]=function(e,t){f[e]=t},e.removeHeader=function(e){delete f[e]},e[Rd]=function(){return q()&&l[zc]()},e[Md]=function(e,t){De(e)&&(e=0),T&&(e=G(e),t=2),W(v,e,0)&&J(z(),0,!1,e,t||0)},e[Dd]=function(){return!o&&0===c&&0===v[Qc]},e[kd]=function(e){T=e},e.addBatch=function(e){if(e&&e[ed]()>0){if(a.isTenantKilled(e[Xc]()))return!1;v[id](e)}return!0},e.teardown=function(){v[Qc]>0&&J(z(),0,!0,2,2),ti(P,(function(e){e&&e.rm&&e.rm()})),P=[]},e.pause=function(){o=!0},e.resume=function(){o=!1,e[Md](0,4)},e[Od]=function(e,t,i){e&&e[ed]()>0&&(ke(t)&&(t=1),T&&(t=G(t),i=2),J([e],0,!1,t,i||0))}}))}return e.__ieDyn=1,e}(),Tu=1e4,Eu="eventsDiscarded",bu=void 0,_u=dt({eventsLimitInMem:{isVal:Ec,v:Tu},immediateEventLimit:{isVal:Ec,v:500},autoFlushEventsLimit:{isVal:Ec,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:function(e){return e&&e.sendPOST},v:bu},overrideInstrumentationKey:bu,overrideEndpointUrl:bu,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:bu,clearTimeoutOverride:bu,payloadPreprocessor:bu,payloadListener:bu,disableEventTimings:bu,valueSanitizer:bu,stringifyObjects:bu,enableCompoundKey:bu,disableOptimizeObj:!1,transports:bu,unloadTransports:bu,useSendBeacon:bu,disableFetchKeepAlive:bu,avoidOptions:!1,xhrTimeout:bu,disableXhrSync:bu,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:Ve,v:6},maxUnloadEventRetryAttempts:{isVal:Ve,v:2},addNoResponse:bu,excludeCsMetaData:bu}),Iu=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="4.2.1";var r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w,A,P,R=!1,M=[],D=!1,k=0,O=0,N={},L=Ac;return hn(t,n,(function(e,t){function n(){(function(e,t){Yl([Ol,kl,Ml],null,t)})(0,T),function(e,t){var i=zl(Nl,t);Yl([Ml],null,i),Yl([Rl],null,i)}(0,T),function(e,t){var i=zl(Ll,t);Yl([Dl],null,i),Yl([Rl],null,i)}(0,T)}function x(e){var t="";return e&&e[Qc]&&ti(e,(function(e){t&&(t+="\n"),t+=e})),t}function F(e){var t="";try{V(e),t=u[Sd](e)}catch(e){}return t}function U(e){"beforeunload"!==(e||jt().event).type&&(S=!0,u[kd](S)),K(2,2)}function B(e){S=!1,u[kd](S)}function V(e){e.ext&&e.ext[Gc]&&delete e.ext[Gc],e.ext&&e.ext[qc]&&e.ext[qc].id&&delete e.ext[qc].id,v&&(e.ext=As(e.ext),e[Wd]&&(e[Wd]=As(e[Wd])),e[Vd]&&(e[Vd]=As(e[Vd])))}function H(e,t){if(e[Kd]||(e[Kd]=0),e[Jd]||(e[Jd]=1),V(e),e[Yd])if(c||D)e[Jd]=3,e[Yd]=!1;else if(u)return v&&(e=As(e)),void u[Od](Xd.create(e[Xc],[e]),!0===e[Yd]?1:e[Yd],3);var i=e[Jd],n=O,r=a;4===i&&(n=k,r=s);var o=!1;if(n<r)o=!Q(e,t);else{var l=1,d=20;4===i&&(l=4,d=1),o=!0,function(e,t,i,n){for(;i<=t;){var r=J(e,t,!0);if(r&&r[ed]()>0){var s=r[nd](0,n),a=s[ed]();if(a>0)return 4===i?k-=a:O-=a,ae(Eu,[s],fn.QueueFull),!0}i++}return Z(),!1}(e[Xc],e[Jd],l,d)&&(o=!Q(e,t))}o&&se(Eu,[e],fn.QueueFull)}function $(e,t,i){var n=X(e,t,i);return u[Md](t,i),n}function j(){return O>0}function G(){if(m>=0&&X(m,0,f)&&u[Md](0,f),k>0&&!l&&!D){var e=N[L][2];e>=0&&(l=z((function(){l=null,$(4,0,1),G()}),e))}var t=N[L][1];!o&&!r&&t>=0&&!D&&(j()?o=z((function(){o=null,$(0===d?3:1,0,1),d++,d%=2,G()}),t):d=0)}function q(){i=null,R=!1,M=[],r=null,D=!1,k=0,s=500,O=0,a=Tu,N={},L=Ac,o=null,l=null,c=0,d=0,h={},g=0,w=!1,p=0,m=-1,f=null,v=!0,S=!1,y=6,C=2,T=null,A=null,P=!1,E=du(),u=new Cu(500,2,1,{requeue:ne,send:oe,sent:le,drop:ce,rspFail:de,oth:ue}),ie(),h[4]={batches:[],iKeyMap:{}},h[3]={batches:[],iKeyMap:{}},h[2]={batches:[],iKeyMap:{}},h[1]={batches:[],iKeyMap:{}},he()}function z(e,t){0===t&&c&&(t=1);var i=1e3;return c&&(i=iu(c-1)),E.set(e,t*i)}function W(){return null!==o&&(o.cancel(),o=null,d=0,!0)}function K(e,t){W(),r&&(r.cancel(),r=null),D||$(1,e,t)}function J(e,t,i){var n=h[t];n||(n=h[t=1]);var r=n.iKeyMap[e];return!r&&i&&(r=Xd.create(e),n.batches[id](r),n.iKeyMap[e]=r),r}function Y(t,i){u[Rd]()&&!c&&(g>0&&O>g&&(i=!0),i&&null==r&&e.flush(t,(function(){}),20))}function Q(e,t){v&&(e=As(e));var i=e[Jd],n=J(e[Xc],i,!0);return!!n.addEvent(e)&&(4!==i?(O++,t&&0===e[Kd]&&Y(!e.sync,p>0&&n[ed]()>=p)):k++,!0)}function Z(){for(var e=0,t=0,i=function(i){var n=h[i];n&&n[wd]&&ti(n[wd],(function(n){4===i?e+=n[ed]():t+=n[ed]()}))},n=1;n<=4;n++)i(n);O=t,k=e}function X(t,i,n){var r=!1,s=0===i;return!s||u[Rd]()?Vo(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=4;i>=t;){var n=h[i];n&&n.batches&&n.batches[Qc]>0&&(ti(n[wd],(function(t){u.addBatch(t)?r=r||t&&t[ed]()>0:e=e[Zc](t[td]()),4===i?k-=t[ed]():O-=t[ed]()})),n[wd]=[],n.iKeyMap={}),i--}e[Qc]>0&&se(Eu,e,fn.KillSwitch),r&&m>=t&&(m=-1,f=0)}),(function(){return{latency:t,sendType:i,sendReason:n}}),!s):(m=m>=0?Math.min(m,t):t,f=Math.max(f,n)),r}function ee(e,t){$(1,0,t),Z(),te((function(){e&&e(),M[Qc]>0?r=z((function(){r=null,ee(M.shift(),t)}),0):(r=null,G())}))}function te(e){u[Dd]()?e():r=z((function(){r=null,te(e)}),.25)}function ie(){(N={})[Ac]=[2,1,0],N.NEAR_REAL_TIME=[6,3,0],N.BEST_EFFORT=[18,9,0]}function ne(t,i){var n=[],r=y;S&&(r=C),ti(t,(function(t){t&&t[ed]()>0&&ti(t[td](),(function(t){t&&(t[Yd]&&(t[Jd]=4,t[Yd]=!1),t[Kd]<r?(Cc(t,e[Gd]),H(t,!1)):n[id](t))}))})),n[Qc]>0&&se(Eu,n,fn.NonRetryableStatus),S&&K(2,2)}function re(t,i){var n=I||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){to(e.diagLog(),1,74,t+" notification failed: "+i)}}function se(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[Qc]>0&&re(e,[t][Zc](i))}function ae(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t[Qc]>0&&ti(t,(function(t){t&&t[ed]()>0&&re(e,[t.events()][Zc](i))}))}function oe(e,t,i){e&&e[Qc]>0&&re("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])}function le(e,t){ae("eventsSent",e,t),G()}function ce(e,t){ae(Eu,e,t>=8e3&&t<=8999?t-8e3:fn.Unknown)}function de(e){ae(Eu,e,fn.NonRetryableStatus),G()}function ue(e,t){ae(Eu,e,fn.Unknown),G()}function he(){p=_?0:Math.max(1500,a/6)}q(),e._getDbgPlgTargets=function(){return[u,i]},e[ld]=function(r,o,l){Vo(o,(function(){return"PostChannel:initialize"}),(function(){t[ld](r,o,l),I=o.getNotifyMgr();try{T=zl(la(e[Gd]),o.evtNamespace&&o.evtNamespace()),e._addHook(ka(r,(function(t){var r=t.cfg,l=tl(null,r,o);i=l.getExtCfg(e[Gd],_u),E=du(i[cd],i[dd]),v=!i.disableOptimizeObj&&!!Ft("chrome"),b=i.ignoreMc1Ms0CookieProcessing,function(e){var t=e[Ld];e[Ld]=function(){var i=0;return b&&(i|=2),i|t.call(e)}}(o),a=i[qd],s=i.immediateEventLimit,g=i[zd],y=i.maxEventRetryAttempts,C=i.maxUnloadEventRetryAttempts,_=i.disableAutoBatchFlushLimit,he(),A=i.overrideInstrumentationKey,P=!!i.disableTelemetry,w&&n();var c=r.disablePageUnloadEvents||[];w=function(e,t,i){return function(e,t,i,n){var r=!1;return t&&e&&Ue(e)&&!(r=Jl(e,t,i,n))&&i&&i[yn]>0&&(r=Jl(e,t,null,n)),r}([Ol,kl,Ml],e,t,i)}(U,c,T),w=Ql(U,c,T)||w,w=Zl(B,r.disablePageShowEvents,T)||w}))),u[ld](r,e.core,e)}catch(t){throw e.setInitialized(!1),t}}),(function(){return{theConfig:r,core:o,extensions:l}}))},e.processTelemetry=function(t,i){Cc(t,e[Gd]),i=i||e._getTelCtx(i);var n=t;P||R||(A&&(n[Xc]=A),H(n,!0),S?K(2,2):G()),e.processNext(n,i)},e.getOfflineSupport=function(){try{var e=u&&u[yd]();if(u)return{getUrl:function(){return e?e.url:null},serialize:F,batch:x,shouldProcess:function(e){return!P},createPayload:function(e){return null},createOneDSPayload:function(e){if(u[Td])return u[Td](e,v)}}}catch(e){}return null},e._doTeardown=function(e,t){K(2,2),R=!0,u.teardown(),n(),q()},e.setEventQueueLimits=function(e,t){i[qd]=a=Ec(e)?e:Tu,i[zd]=g=Ec(t)?t:0,he();var n=O>e;if(!n&&p>0)for(var r=1;!n&&r<=3;r++){var s=h[r];s&&s[wd]&&ti(s[wd],(function(e){e&&e[ed]()>=p&&(n=!0)}))}Y(!0,n)},e.pause=function(){W(),D=!0,u.pause()},e.resume=function(){D=!1,u.resume(),G()},e._loadTransmitProfiles=function(e){W(),ie(),L=Ac,G(),Ke(e,(function(e,t){var i=t[Qc];if(i>=2){var n=i>2?t[2]:0;if(t[rd](0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t[id](n),N[e]=t}}))},e.flush=function(e,t,i){var n;if(void 0===e&&(e=!0),!D)if(i=i||1,e)t||(n=Kr((function(e){t=e}))),null==r?(W(),X(1,0,i),r=z((function(){r=null,ee(t,i)}),0)):M[id](t);else{var s=W();$(1,1,i),t&&t(),s&&G()}return n},e.setMsaAuthTicket=function(e){u[Pd](Vc,e)},e.setAuthPluginHeader=function(e){u[Pd](Hc,e)},e.removeAuthPluginHeader=function(){u.removeHeader(Hc)},e.hasEvents=j,e._setTransmitProfile=function(e){L!==e&&void 0!==N[e]&&(W(),L=e,G())},ws(e,(function(){return u}),["addResponseHandler"]),e[jd]=function(){c<4&&(c++,W(),G())},e._clearBackOff=function(){c&&(c=0,W(),G())}})),n}return Oi(t,e),t.__ieDyn=1,t}(dl),wu="locale",Au="ver",Pu="name",Ru=mn({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"]}),Mu=mn({id:[0,"id"],ver:[1,Au],appName:[2,Pu],locale:[3,wu],expId:[4,"expId"],env:[5,"env"]}),Du=mn({domain:[0,"domain"],browser:[1,"browser"],browserVer:[2,"browserVer"],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),ku=mn({locale:[0,wu],localId:[1,"localId"],id:[2,"id"]}),Ou=mn({osName:[0,Pu],ver:[1,Au]}),Nu=mn({ver:[0,Au],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),Lu=mn({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,"serviceName"]}),xu=mn({popSample:[0,"popSample"],eventFlags:[1,"eventFlags"]}),Fu=mn({tz:[0,"tz"]}),Uu=mn({sessionId:[0,"sesId"]}),Bu=mn({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),Vu=mn({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),Hu=mn({traceId:[0,"traceID"],traceName:[1,Pu],parentId:[2,"parentID"]}),$u=mn({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function ju(){return void 0===yu&&(yu=!!qu(0)),yu}function Gu(){return ju()?qu(0):null}function qu(e){var t,i,n=null;try{var r=xt();if(!r)return null;i=new Date,(n=0===e?r.localStorage:r.sessionStorage)&&xe(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}function zu(){return this.getId()}function Wu(e){this.setId(e)}var Ku=function(){function e(){hn(e,this,(function(e){e.setId=function(t){e.customId=t},e.getId=function(){return Le(e.customId)?e.customId:e.automaticId}}))}return e._staticInit=void Xe(e.prototype,"id",{g:zu,s:Wu}),e}(),Ju="ai_session",Yu=function(){function e(t,i,n){var r,s,a,o=Ya(t),l=Eo(t);hn(e,this,(function(t){var c=ka(i,(function(){a=i,t.config=a}));function d(){var e=l.get(s());if(e&&xe(e.split))u(e);else{var i=function(e,t){var i=Gu();if(null!==i)try{return i.getItem(t)}catch(t){yu=!1,to(e,1,503,"Browser failed read of local storage. "+t)}return null}(o,s());i&&u(i)}t.automaticSession.getId()||h()}function u(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){to(o,1,510,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&to(o,2,517,"AI session renewal date is 0, session will be reset.")}function h(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid;!De(n)&&n?He(n)?e.setId(vc()):e.setId(vc(n)):e.setId(na(a.idLength||22)),e.acquisitionDate=i,e.renewalDate=i,g(e.getId(),e.acquisitionDate,e.renewalDate),ju()||to(o,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function g(e,i,n){var a=i+t.config.sessionExpirationMs,o=n+t.config.sessionRenewalMs,c=new Date,d=[e,i,n];a<o?c.setTime(a):c.setTime(o);var u=t.config.cookieDomain||null;l.set(s(),d.join("|")+";expires="+c.toUTCString(),null,u),r=(new Date).getTime()}n&&n.add(c),s=function(){return t.config.namePrefix?Ju+t.config.namePrefix:Ju},t.automaticSession=new Ku,t.update=function(){t.automaticSession.getId()||d();var i=t.automaticSession,n=t.config,s=(new Date).getTime(),a=s-i.acquisitionDate>n.sessionExpirationMs,o=s-i.renewalDate>n.sessionRenewalMs;a||o?h():(!r||s-r>e.cookieUpdateInterval)&&(i.renewalDate=s,g(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;!function(e,t,i){!function(e,t,i){var n=Gu();if(null!==n)try{return n.setItem(t,i),!0}catch(t){yu=!1,to(e,1,504,"Browser failed write to local storage. "+t)}}(o,s(),[e,t,i].join("|"))}(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.cookieUpdateInterval=6e4,e}(),Qu=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function Zu(e,t){void 0===t&&(t=Qu);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)Xu(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function Xu(e,t){if(void 0===t&&(t=Qu),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}function eh(){return this.getExpId()}var th=function(){function e(t,i,n){var r,s=null,a=Qu.slice(0),o=null;hn(e,this,(function(e){if(function(t){var s=ka(t,(function(){r=i&&i.getCookieMgr(),o=t||{},e.env=o.env||function(e){var t,i={},n=$t();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var s=t[r];s.name&&0===s.name.toLowerCase().indexOf(e)&&(i[s.name.replace(e,"")]=s.content)}}return i}("awa-").env}));n&&n.add(s)}(t),Ut()){var l=$t().documentElement;l&&(e.locale=l.lang)}function c(e){e!==s&&(s=Zu(e,a))}e.getExpId=function(){return o.expId?function(e){return c(e),s}(o.expId):(c(fc(r,"Treatments")),s)}}))}return e.validateAppExpId=Zu,e._staticInit=void Xe(e.prototype,"expId",{g:eh}),e}(),ih=function(){},nh=function(){};function rh(){return this.getMsfpc()}function sh(){return this.getAnid()}var ah=function(){function e(t,i,n){var r;hn(e,this,(function(e){(function(t){var s=ka(t,(function(){r=i&&i.getCookieMgr();var n=t||{};n.serviceName&&(e.serviceName=n.serviceName)}));n&&n.add(s)})(t),e.getMsfpc=function(){return fc(r,"MSFPC")},e.getAnid=function(){return fc(r,"ANON").slice(0,34)}}))}var t;return e._staticInit=(Xe(t=e.prototype,"msfpc",{g:rh}),void Xe(t,"anid",{g:sh})),e}(),oh=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},lh={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},ch={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},dh="([\\d,_,.]+)",uh="Unknown",hh=[{r:lh.WINPHONE,os:"Windows Phone"},{r:lh.WINRT,os:"Windows RT"},{r:lh.WIN,os:"Windows"},{r:lh.IOS,os:"iOS"},{r:lh.ANDROID,os:"Android"},{r:lh.LINUX,os:"Linux"},{r:lh.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:lh.OSX,os:"Mac OS X"}];function gh(e,t){var i=e.match(new RegExp(t+" ([\\d,.]+)"));return i?ch[i[1]]?ch[i[1]]:i[1]:uh}function ph(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null}var mh=function(e,t){var i=null,n=null,r=null,s=null,a=ka(e,(function(){if((e||{}).populateOperatingSystemInfo){var t=Gt()||{},r=e.userAgent||t.userAgent||"",s=(e.userAgentData||{}).platform||(t.userAgentData||{}).platform;if(r){var a=function(e){for(var t=0;t<hh.length;t++){var i=hh[t];if(i.r&&e.match(i.r))return i.os;if(i.s&&-1!==e.indexOf(i.s))return i.os}return uh}(r.toLowerCase());i=a,n=function(e,t){return"Windows"===t?gh(e,"Windows NT"):"Android"===t?gh(e,t):"Mac OS X"===t?function(e){var t=e.match(new RegExp("Mac OS X "+dh));if(t){var i=t[1].replace(/_/g,".");if(i){var n=ph(i);return n?i.split(n)[0]:i}}return uh}(e):"iOS"===t?function(e){var t=e.match(new RegExp("OS "+dh));if(t){var i=t[1].replace(/_/g,".");if(i){var n=ph(i);return n?i.split(n)[0]:i}}return uh}(e):uh}(r,a)}i&&i!==uh||!Le(s)||(i=s)}}));t&&t.add(a),Xe(this,"name",{s:function(e){r=e},g:function(){return r||i}}),Xe(this,"ver",{s:function(e){s=e},g:function(){return s||n}})},fh="MicrosoftApplicationsTelemetryDeviceId",vh=function(){function e(t,i,n){var r,s=0;hn(e,this,(function(e){e.seq=s,e.epoch=ia(!1).toString(),e.getSequenceId=function(){return++s};var a=ka(t,(function(t){r=i&&i.getCookieMgr();var n=t.cfg.propertyStorageOverride;if(r.isEnabled()||n){var s=function(e,t,i){return t?t.getProperty(i)||"":fc(e,i)}(r,n,fh);s||(s=Ho()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(r,n,fh,s),e.installId=s}else r.purge(fh)}));n&&n.add(a)}))}return e.__ieDyn=1,e}(),Sh=function(e,t,i,n,r){var s=this;s.traceId=t||$o();var a=ka(e,(function(){var t=e;if(t.enableDistributedTracing&&!i&&(i=$o().substring(0,16)),s.parentId=s.parentId||i,t.enableApplicationInsightsTrace&&!n){var r=$s();r&&r.pathname&&(n=r.pathname)}s.name=s.name||n}));r&&r.add(a)},yh="setLocalId";function Ch(){return this.getLocalId()}function Th(e){this[yh](e)}var Eh=function(){function e(t,i,n,r){var s,a,o;hn(e,this,(function(l){if(function(i){var c=ka(i,(function(){if(o=n&&n.getCookieMgr(),s=i,a=null,o&&o.isEnabled()&&(d(),s.enableApplicationInsightsUser)){var r=fc(o,e.userCookieName);if(r){var c=r.split(e.cookieSeparator);c.length>0&&(l.id=c[0])}if(!l.id){l.id=na(t&&!De(t.idLength)?t.idLength:22);var u=Es(new Date);l.accountAcquisitionDate=u;var h=[l.id,u],g=s.cookieDomain?s.cookieDomain:void 0;o.set(e.userCookieName,h.join(e.cookieSeparator),31536e3,g)}}}));r&&r.add(c)}(i),"undefined"!=typeof navigator){var c=navigator;l.locale=c.userLanguage||c.language}function d(){if(!s.hashIdentifiers&&!s.dropIdentifiers){var e=fc(o,"MUID");e&&(a="t:"+e)}return a}l.getLocalId=function(){return a||d()},l[yh]=function(e){a=e}}))}return e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void Xe(e.prototype,"localId",{g:Ch,s:Th}),e}(),bh=function(e,t){var i=this;i.popSample=100;var n=ka(e,(function(){i.eventFlags=0,e.hashIdentifiers&&(i.eventFlags=1048576|i.eventFlags),e.dropIdentifiers&&(i.eventFlags=2097152|i.eventFlags),e.scrubIpOnly&&(i.eventFlags=4194304|i.eventFlags)}));t&&t.add(n)},_h=["Required","Analytics","SocialMedia","Advertising"],Ih="([\\d,.]+)",wh="Unknown",Ah="Edg/",Ph=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:Ah,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"}],Rh=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function Mh(e,t){return t.indexOf(e)>-1}function Dh(e,t){for(var i=0;i<t.length;i++)if(e==t[i].brand)return t[i].version;return null}function kh(){return this.getUserConsent()}var Oh=function(){function e(t,i,n){var r=Eo(i),s=t||{},a=null,o=null,l=null,c=null,d=null,u=null,h=null;hn(e,this,(function(e){!function(e){var t=ka(e,(function(){if((s=e).populateBrowserInfo){var t=s.userAgent,i=(s.userAgentData||{}).brands;if(t!==a||i!==o){if(!t||!i||0===i.length){var n=Gt();n&&(t=t||n.userAgent||"",i=i||(n.userAgentData||{}).brands)}(function(e,t){if(Ue(t))try{for(var i=0;i<Rh.length;i++){var n=Dh(Rh[i].br,t);if(n)return d=Rh[i].b,void(u=n)}}catch(e){}if(e){var r=function(e){if(e)for(var t=0;t<Ph.length;t++)if(Mh(Ph[t].ua,e))return Ph[t].b;return wh}(e);d=r,u=function(e,t){return"MSIE"===t?function(e){var t=e.match(new RegExp("MSIE "+Ih));if(t)return t[1];var i=e.match(new RegExp("rv:"+Ih));return i?i[1]:void 0}(e):function(e,t){"Safari"===e?e="Version":"Edge"===e&&Mh(Ah,t)&&(e="Edg");var i=t.match(new RegExp(e+"/"+Ih));return i||"Opera"===e&&(i=t.match(new RegExp("OPR/"+Ih)))?i[1]:wh}(t,e)}(e,r)}})(t,i),a=t,o=i}}h=He(s.gpcDataSharingOptIn)?s.gpcDataSharingOptIn:null}));n&&n.add(t)}(t);var i=$s();if(i){var g=i.hostname;g&&(e.domain="file:"===i.protocol?"local":g)}var p=function(){var e={h:0,w:0},t=jt();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e}();e.screenRes=p.w+"X"+p.h,e.getUserConsent=function(){return s.userConsented||!!fc(r,s.userConsentCookieName||"MSCC")},e.getUserConsentDetails=function(){var e=null;try{var t=s.callback;if(t&&t.userConsentDetails){var i=t.userConsentDetails();if(i){e=s.disableConsentDetailsSanitize?i:{};for(var n=0;n<_h.length;n++){var r=_h[n];e[r]=i[r]||!1}}}return null!==h&&((e=e||{}).GPC_DataSharingOptIn=!!h),e?JSON.stringify(e):null}catch(e){}},et(e,{userConsent:{g:e.getUserConsent},browser:{s:function(e){l=e},g:function(){return l||d}},browserVer:{s:function(e){c=e},g:function(){return c||u}},gpcDataSharingOptIn:{g:function(){return h},s:function(e){h=He(e)?e:null,s.gpcDataSharingOptIn=h}}})}))}return e._staticInit=void Xe(e.prototype,"userConsent",{g:kh}),e}();function Nh(e,t,i,n,r){var s=t.ext[Ru[e]];if(s)try{Ke(n,(function(e,t){if(Le(t)||Ve(t)||He(t)){var n=s[i[e]];!r&&(n||Le(n)||Ve(n)||He(n))&&(t=n),s[i[e]]=t}}))}catch(e){}return s}var Lh,xh=function(){function e(t,i,n,r){hn(e,this,(function(e){e.app=new th(i,n,r),e.cloud=new ih,e.user=new Eh(t,i,n,r),e.os=new mh(i,r),e.web=new Oh(i,n,r);var s=new vh(t,n,r),a=new ah(i,n,r),o=new bh(i,r);e.loc=new oh,e.device=new nh;var l=new Yu(n,i,r);e.session=new Ku;var c=void 0,d=function(e,t){var i=e||{};return{getName:function(){return i.name},setName:function(e){t&&t.setName(e),i.name=e},getTraceId:function(){return i.traceId},setTraceId:function(e){t&&t.setTraceId(e),Go(e)&&(i.traceId=e)},getSpanId:function(){return i.parentId},setSpanId:function(e){t&&t.setSpanId(e),qo(e)&&(i.parentId=e)},getTraceFlags:function(){return i.traceFlags},setTraceFlags:function(e){t&&t.setTraceFlags(e),i.traceFlags=e}}}(new Sh(i,c,c,c,r),g()),u=!(i||{}).eventContainExtFields;function h(){var t=e.session;if(t&&Le(t.customId))return t.customId;l.update();var i=l.automaticSession;if(i){var n=i.getId();n&&Le(n)&&(t.automaticId=n)}return t.automaticId}function g(){var e=d;return n&&n.getTraceCtx&&(e=n.getTraceCtx(!1)||d),e}e.getTraceCtx=function(){return d},e.getSessionId=h,e.applyApplicationContext=function(t){var i,n=e.app;Nh(4,t,Mu,((i={})[0]=n.id,i[1]=n.ver,i[2]=n.name,i[3]=n.locale,i[4]=n.getExpId(),i[5]=n.env,i),u)},e.applyUserContext=function(t){var i,n=e.user;Nh(0,t,ku,((i={})[1]=n.getLocalId(),i[0]=n.locale,i[2]=n.id,i),u)},e.applyWebContext=function(t){var i,n=e.web;Nh(3,t,Du,((i={})[0]=n.domain,i[1]=n.browser,i[2]=n.browserVer,i[3]=n.screenRes,i[5]=n.getUserConsentDetails(),i[4]=n.getUserConsent(),i),u)},e.applyOsContext=function(t){var i,n=e.os;Nh(5,t,Ou,((i={})[0]=n.name,i[1]=n.ver,i),u)},e.applySdkContext=function(e){var t;Nh(6,e,Nu,((t={})[2]=s.installId,t[1]=s.getSequenceId(),t[3]=s.epoch,t),u)},e.applyIntWebContext=function(e){var t;Nh(7,e,Lu,((t={})[0]=a.getMsfpc(),t[1]=a.getAnid(),t[2]=a.serviceName,t),u)},e.applyUtcContext=function(e){var t,i=((t={})[0]=o.popSample,t);o.eventFlags>0&&(i[1]=o.eventFlags),Nh(8,e,xu,i,u)},e.applyLocContext=function(t){var i;Nh(9,t,Fu,((i={})[0]=e.loc.tz,i),u)},e.applySessionContext=function(e){var t;Nh(4,e,Uu,((t={})[0]=h(),t),u)},e.applyDeviceContext=function(t){var i,n=e.device;Nh(1,t,Bu,((i={})[0]=n.localId,i[2]=n.make,i[3]=n.model,i[1]=n.deviceClass,i),u)},e.applyCloudContext=function(t){var i,n=e.cloud;Nh(10,t,Vu,((i={})[0]=n.role,i[1]=n.roleInstance,i[2]=n.roleVer,i),u)},e.applyAITraceContext=function(e){var t;if(i.enableApplicationInsightsTrace){var n=g();n&&Nh(2,e,Hu,((t={})[0]=n.getTraceId(),t[1]=n.getName(),t[2]=n.getSpanId(),t),!1)}},e.applyDistributedTraceContext=function(e){var t,i=g();if(i){var n=((t={})[0]=i.getTraceId(),t[1]=i.getSpanId(),t),r=i.getTraceFlags();ke(r)||(n[2]=r),Nh(11,e,$u,n,!1)}}}))}return e.__ieDyn=1,e}(),Fh=[Ru[4],Ru[0],Ru[3],Ru[5],Ru[6],Ru[7],Ru[8],Ru[9],Ru[1],Ru[2],Ru[11],Ru[10]],Uh=dt({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:Fa(),userAgentData:xa({brands:Lh,mobile:Lh,platform:Lh}),userConsentCookieName:Fa(),userConsented:!1,serviceName:Fa(),env:Fa(),expId:Fa(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:Fa(),namePrefix:Fa(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:xa({userConsentDetails:null}),gpcDataSharingOptIn:Lh,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),Bh=function(e){function t(){var i,n,r,s=e.call(this)||this;return s.identifier="SystemPropertiesCollector",s.priority=3,s.version="4.2.1",hn(t,s,(function(e,t){function s(){i=null,n={}}function a(t){var n=e.identifier,s=e.core;e._addHook(ka(t,(function(){var e=tl(null,t,s);r=e.getExtCfg(n,Uh)}))),i=new xh(t,r,s,e._unloadHooks),s&&s.setTraceCtx&&s.setTraceCtx(i.getTraceCtx())}s(),e.initialize=function(e,i,n){t.initialize(e,i,n),a(e)},e.processTelemetry=function(t,s){Cc(t,e.identifier),s=e._getTelCtx(s);var a=t.ext=t.ext?t.ext:{};t.data=t.data?t.data:{},ti(Fh,(function(e){a[e]=a[e]||{}})),i&&(i.applyUtcContext(t),i.applyApplicationContext(t),i.applyUserContext(t),i.applyWebContext(t),i.applyOsContext(t),i.applySdkContext(t),i.applyIntWebContext(t),i.applyLocContext(t),i.applySessionContext(t),i.applyDeviceContext(t),r.enableApplicationInsightsTrace&&i.applyAITraceContext(t),r.enableDistributedTracing&&i.applyDistributedTraceContext(t),i.applyCloudContext(t)),ti(ct(a),(function(e){0===ct(a[e]).length&&delete a[e]})),function(e,t){e&&Ke(e,(function(e,i){t[e]||(t[e]=i)}))}(n,t.data),e.processNext(t,s)},e.getPropertiesContext=function(){return i},e.setProperty=function(e,t){n[e]=t},e._doTeardown=function(e,t){var n=(e||{}).core();if(n&&n.getTraceCtx&&i){var r=n.getTraceCtx(!1);r&&r===i.getTraceCtx()&&n.setTraceCtx(null)}s()},e._getDbgPlgTargets=function(){return[r]}})),s}return Oi(t,e),t.__ieDyn=1,t}(dl),Vh=function(e){this._setOverride=function(t,i){e.setOverride(t,i)},this._getOverride=function(t){return e.getOverride(t)}},Hh=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setId=function(e){s._setOverride(Mu.id,e)},s.getId=function(){return s._getOverride(Mu.id)},s.setVer=function(e){s._setOverride(Mu.ver,e)},s.getVer=function(){return s._getOverride(Mu.ver)},s.setName=function(e){s._setOverride(Mu.appName,e)},s.getName=function(){return s._getOverride(Mu.appName)},s.setLocale=function(e){s._setOverride(Mu.locale,e)},s.getLocale=function(){return s._getOverride(Mu.locale)},s.setEnv=function(e){s._setOverride(Mu.env,e)},s.getEnv=function(){return s._getOverride(Mu.env)},s.setExpId=function(e){s._setOverride(Mu.expId,th.validateAppExpId(e))},s.getExpId=function(){return s._getOverride(Mu.expId)};var a=ka(i,(function(){i&&(De(i.env)||s.setEnv(i.env),ke(i.expId)||s.setExpId(i.expId))}));return n&&n.add(a),r}return Oi(t,e),t}(Vh),$h=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setRole=function(e){n._setOverride(Vu.role,e)},n.getRole=function(){return n._getOverride(Vu.role)},n.setRoleInstance=function(e){n._setOverride(Vu.roleInstance,e)},n.getRoleInstance=function(){return n._getOverride(Vu.roleInstance)},n.setRoleVer=function(e){n._setOverride(Vu.roleVer,e)},n.getRoleVer=function(){return n._getOverride(Vu.roleVer)},i}return Oi(t,e),t}(Vh),jh=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setProperty=function(e,t){n._setOverride(e,t)},n.getProperty=function(e){return n._getOverride(e)},i}return Oi(t,e),t}(Vh),Gh=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(Bu.localId,e)},n.getLocalId=function(){return n._getOverride(Bu.localId)},n.setDeviceClass=function(e){n._setOverride(Bu.deviceClass,e)},n.getDeviceClass=function(){return n._getOverride(Bu.deviceClass)},n.setMake=function(e){n._setOverride(Bu.make,e)},n.getMake=function(){return n._getOverride(Bu.make)},n.setModel=function(e){n._setOverride(Bu.model,e)},n.getModel=function(){return n._getOverride(Bu.model)},i}return Oi(t,e),t}(Vh),qh=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setTz=function(e){n._setOverride(Fu.tz,e)},n.getTz=function(){return n._getOverride(Fu.tz)},i}return Oi(t,e),t}(Vh),zh=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r,a=null;s.setOsName=function(e){s._setOverride(Ou.osName,e)},s.getOsName=function(){return s._getOverride(Ou.osName)},s.setVer=function(e){s._setOverride(Ou.ver,e)},s.getVer=function(){return s._getOverride(Ou.ver)};var o=ka(i,(function(){!a&&i.userAgent&&i.populateOperatingSystemInfo&&(a=new mh(i,n)),a&&(s.setOsName(a.name),s.setVer(a.ver))}));return n&&n.add(o),r}return Oi(t,e),t}(Vh);function Wh(e,t){if(e)for(var i=0;i<t.length;i++){var n=t[i];ke(e[n])&&(e[n]={}),e=e[n]}return e}var Kh,Jh,Yh=function(e){var t=this,i=[];t.setOverride=function(e,t){e&&i.push({key:e,value:t})},t.hasOverride=function(e){var t=!1;return ti(i,(function(i){i.key===e&&(t=!0)})),t},t.getOverride=function(e){var t;return ti(i,(function(i){i.key===e&&(t=i.value)})),t},t.applyOverrides=function(t,n){if(i.length>0)try{var r=Wh(t,e);ti(i,(function(e){!function(e,t,i){if(e&&t){var n=t.split("."),r=n[n.length-1];n.length>1&&(e=Wh(e,n.slice(0,-1))),ke(i)?De(e[r])||delete e[r]:e[r]=i}}(r,e.key,e.value)}))}catch(e){}}},Qh=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(ku.localId,e)},n.getLocalId=function(){return n._getOverride(ku.localId)},n.setLocale=function(e){n._setOverride(ku.locale,e)},n.getLocale=function(){return n._getOverride(ku.locale)},n.setId=function(e){n._setOverride(ku.id,e)},n.getId=function(){return n._getOverride(ku.id)},i}return Oi(t,e),t}(Vh),Zh=function(e){function t(t,i,n){var r=e.call(this,t)||this,s=r;s.setDomain=function(e){s._setOverride(Du.domain,e)},s.getDomain=function(){return s._getOverride(Du.domain)},s.setBrowser=function(e){s._setOverride(Du.browser,e)},s.getBrowser=function(){return s._getOverride(Du.browser)},s.setBrowserVer=function(e){s._setOverride(Du.browserVer,e)},s.getBrowserVer=function(){return s._getOverride(Du.browserVer)},s.setScreenRes=function(e){s._setOverride(Du.screenRes,e)},s.getScreenRes=function(){return s._getOverride(Du.screenRes)},s.setUserConsent=function(e){s._setOverride(Du.userConsent,e)},s.getUserContext=function(){return s._getOverride(Du.userConsent)};var a=ka(i,(function(){i&&(De(i.userConsented)||s.setUserConsent(i.userConsented))}));return n&&n.add(a),r}return Oi(t,e),t}(Vh),Xh="ext",eg=function(e,t,i,n){var r=this,s={};function a(e){for(var t="",i=0;i<e.length;i++)t&&(t+="_"),t+=e[i];return De(s[t])&&(s[t]=new Yh(e)),t?s[t]:null}r.data=new jh(a(["data"])),r.app=new Hh(a([Xh,Ru.AppExt]),t,n),r.user=new Qh(a([Xh,Ru.UserExt])),r.os=new zh(a([Xh,Ru.OSExt]),t,n),r.web=new Zh(a([Xh,Ru.WebExt]),t,n),r.device=new Gh(a([Xh,Ru.DeviceExt])),r.loc=new qh(a([Xh,Ru.LocExt])),r.cloud=new $h(a([Xh,Ru.CloudExt])),r.applyOverrides=function(e,t){var i=ct(s);i&&i.length>0&&ti(i,(function(i){s[i].applyOverrides(e,t)}))}},tg=void 0,ig=dt({env:tg,expId:tg,populateOperatingSystemInfo:!1,userAgent:tg,userAgentData:xa({brands:tg,mobile:tg,platform:tg}),userConsented:tg}),ng="OverridePropertiesPlugin",rg=function(e){function t(){var i=e.call(this)||this;i.identifier=ng,i.priority=4,i.version="4.2.1";var n=null;return hn(t,i,(function(e,t){e.initialize=function(i,n,r){t.initialize(i,n,r),e._baseInit(i,n,r)},e.processTelemetry=function(t,n){Cc(t,i.identifier),n=e._getTelCtx(n);var r=e.getOverrideContext();r&&r.applyOverrides(t,n),e.processNext(t,n)},e._baseInit=function(t,r,s){n=new eg(t,i._getTelCtx().getExtCfg(i.identifier,ig),r,e._unloadHooks)},e.setProperty=function(e,t){n&&n.data.setProperty(e,t)},e.getOverrideContext=function(){return n}})),i}return Oi(t,e),t.__ieDyn=1,t}(dl),sg="_dropInst",ag=["channelConfiguration","propertyStorageOverride"];function og(e,t){if(t)for(var i=ct(t),n=0;n<i.length;n++){var r=i[n];We(e,r)||Ii(r,"Symbol(")||(e[r]=t[r])}}function lg(e,t,i){var n;return Xe(e,t,{g:function(){return function(e){return e===le||Ne(typeof e)}(i)?i:(Ue(i)?(Ue(n)||(n=[]),n.length=i.length):Fe(n)||(n={}),Ke(i,(function(e,t){Ii(e,"Symbol(")||lg(n,e,t)})),n)}})}function cg(e,t){var i=null;if(t){t.endpointUrl&&(i=t.endpointUrl);var n=(t.extensionConfig||{})[e]||{};n.overrideEndpointUrl&&(i=n.overrideEndpointUrl)}return i}var dg=dt({cookieCfg:{},channelConfiguration:xa({}),propertyConfiguration:xa({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:xa({}),createPerfMgr:Jh,loggingLevelConsole:0}),ug=dt({propertyConfiguration:xa({}),cookieCfg:xa({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:xa((Kh={},Kh[ng]=xa({}),Kh)),createPerfMgr:Jh,loggingLevelConsole:0}),hg=function(e){function t(i,n){var r=e.call(this)||this;return hn(t,r,(function(e,t){function r(e){var t=[];return e&&ti(e,(function(e){e.iKey===i&&t.push(e)})),t}function s(t){if(e[t]&&e.listeners)for(var i=0;i<e.listeners.length;i++){var n=e.listeners[i];if(n&&n[t])return!0}return!1}var a={eventsSent:function(t){if(s("eventsSent")){var i=r(t);i.length>0&&e.eventsSent(i)}},eventsDiscarded:function(t,i){if(s("eventsDiscarded")){var n=r(t);n.length>0&&e.eventsDiscarded(n,i)}},eventsSendRequest:function(t,i){s("eventsSendRequest")&&e.eventsSendRequest(t,i)},perfEvent:function(t){s("perfEvent")&&e.perfEvent(t)}};n.addNotificationListener(a)})),r}return Oi(t,e),t.__ieDyn=1,t}(Oo),gg=function(){function e(){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m=null,f=null;hn(e,this,(function(e){function v(){t=Da({},dg,null),i=[],n=null,r=null,s=[],a=[],o={},l=null,c=null,d=null,h=null,g=null,p=!1,t.cfg.loggingLevelConsole=1,u=new Xa(t.cfg),Xe(e,"sharedConfig",{g:function(){return p&&C(),t.cfg}})}function S(e,i){var n;if(void 0===i&&(i=null),e){(!function(e){return e.pause&&e.teardown&&e.flush}(e)?s:a).push(e);var r=e.identifier,o=t.cfg.extensionConfig;t.setDf(o,((n={})[r]={ref:!0,v:i||{}},n))}return e}function y(e){var n=t.cfg;i=[],l=S(new Bh,n.propertyConfiguration),i.push(l),n.extensions&&ti(n.extensions,(function(e){xe(e)||S(e)})),e&&ti(e,(function(e){e&&!xe(e)&&i.push(S(e))}))}function C(){n||(p||to(e.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),t.cfg.instrumentationKey=t.cfg.instrumentationKey||"_not_defined_",r=new Oo,(n=new pg(e,e.diagLog(),r)).initialize(t.cfg,i),n.isInitialized()&&(et((t=Sa(n.config)).cfg,{channelConfiguration:{g:function(){return t.cfg.extensionConfig[c.identifier]}},propertyConfiguration:{g:function(){return t.cfg.extensionConfig[l.identifier]}}}),c&&(d=cg(c.identifier,t.cfg))),m&&n.setCookieMgr(m))}function T(i,n){var r=[],s=t.cfg,a={};if(Ke(s.extensionConfig,(function(e,t){e===c.identifier||e===l.identifier||Ii(e,"Symbol(")||(e!==ng?lg(a,e,t):(a[e]={},og(a[e],t)))})),n){n.extensions&&n.extensions.length>0&&(r=ei(r,n.extensions));var o=n.extensionConfig;o&&(We(o,c.identifier)&&ct(o).length>0&&to(e.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),og(a,o))}var d={instrumentationKey:i,channels:E(n),extensions:r,extensionConfig:a};return og(d,n),d}function E(e){var i=t.cfg,n=[[]];return i.channels&&ti(i.channels,(function(e,t){xe(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),e&&e.channels&&ti(e.channels,(function(e,t){xe(e)||(n[t]=n[t]||[],n[t]=n[t].concat(e))})),n}function b(e){var t=[];return i&&i.length>0&&(t=t.concat(i)),e&&e.length>0&&(t=t.concat(e)),t}v(),e.diagLog=function(){return u||(u=new Xa(t.cfg)),u},e.getCookieMgr=function(){return C(),m||n.getCookieMgr()},e.setCookieMgr=function(e){m=e,n&&n.setCookieMgr(e)},e.getPerfMgr=function(){return g||t&&t.cfg.enablePerfMgr&&(g=f||new Uo(e.getNotifyMgr())),g},e.setPerfMgr=function(e){f=e,g=e},e.create=function(i,r){p?to(e.diagLog(),2,514,"Shared Manager has already been initialized."):(t=Da(function(e){if(e&&Ue(e.extensionConfig)){var t=e.extensionConfig,i={};Ke(t,(function(e,t){xe(t)||Ii(e,"Symbol(")||(i[e]=t)})),e.extensionConfig=i}return e}(i?Ps({},i):{}),dg,null),n=null,function(){var e=t.cfg,i=e.channels,n=new Iu,r=n.identifier,s=!1;c=null,d=null,ti(i,(function(e){s||ti(e,(function(e){if(!xe(e)&&(S(e),e.identifier===r))return c=e,s=!0,-1}))})),s||(c=S(n,e.channelConfiguration),i.length>0?ei(i[0],c):e.channels.push([c]))}(),y(r),p=!0)},e.getInst=function(e){return(o[e]||{}).inst},e.newInst=function(i,s,a){var l=e.getInst(i);if(l)return to(e.diagLog(),2,514,"Instance already exists for ["+i+"]"),l;if(C(),n.isInitialized()){var u=T(i,s);if(c){var h=cg(c.identifier,u);d&&h&&d!==h&&to(e.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+d+"] is different from configured ["+h+"] shared will be used!")}var g=new hg(i,r);if(l=new pg(e,e.diagLog(),g),o[i]={iKey:i,inst:l,notifyMgr:g},l.setPerfMgr(e.getPerfMgr()),l.initialize(u,b(a)),l.isInitialized()){var p=l.config;et(p,{propertyConfiguration:{g:function(){return p.extensionConfig[ng]}}});try{delete p.endpointUrl,delete p.channelConfiguration,delete p.propertyStorageOverride}catch(t){to(e.diagLog(),2,108,"Failed to remove unused defaults!")}Ke(t.cfg,(function(e,t){We(p,e)||Ii(e,"Symbol(")||si(ag,e)||lg(p,e,t)}))}else to(e.diagLog(),2,520,"Failed to initialize new instance!"),l=null,delete o[i]}return l},e.getSharedPlugin=function(e){C();var t=null,i=n.getPlugin(e);return i&&(t=i.plugin),t},e.getPropertyManager=function(){return C(),l},e.getPostChannel=function(){return C(),c},e.getNotifyMgr=function(){return h||(h=new Oo),h},e.unload=function(e,t,i){var r,s=ct(o),a=s.length+1,l={reason:50,isAsync:e,flushComplete:!1};function c(e,i){0==--a&&(v(),t&&t(i))}return e&&!t&&(r=Kr((function(e){t=e}))),n&&(ti(s,(function(t){!function(e,t,i,n){var r=o[e];r&&(r.inst&&r.inst.isInitialized()?r.inst.unload(t,(function(e){i&&i(0,e)}),n):i&&i(0,{reason:50,isAsync:t,flushComplete:!1}))}(t,e,(function(e,t){c(0,t)}),i)})),n.isInitialized()&&(n.unload(e,(function(e){c(0,l=e)}),i),n=null)),c(0,l),r},e.addUnloadHook=function(e){C(),n.addUnloadHook(e)},e.addSharedPlugin=function(e,t,i,r){return C(),n.addPlugin(e,t,i,r)},e.updateCfg=function(e,t){return C(),n.updateCfg(e,t)},e.evtNamespace=function(){return C(),n.evtNamespace()},e.addUnloadCb=function(e){C(),n.addUnloadCb(e)},e.onCfgChange=function(e){return C(),n.onCfgChange(e)},e[sg]=function(e){e&&o.iKey&&delete o[e]}}))}return e.__ieDyn=1,e}(),pg=function(e){function t(i,n,r){var s,a=e.call(this)||this,o=i;return hn(t,a,(function(e,t){e.getSharedPropertyManager=function(){return o.getPropertyManager()},e.getSharedPostChannel=function(){return o.getPostChannel()},e.getOverridePropertyManager=function(){return s},e.initialize=function(i,a){Vo(e,(function(){return"ApplicationInsights:initialize"}),(function(){var o=[s=new rg];a&&(o=o.concat(a));var l=i.propertyConfiguration||{};if(i.propertyConfiguration)try{delete i.propertyConfiguration}catch(e){i.propertyConfiguration={}}i.extensionConfig=i.extensionConfig||{},i.extensionConfig[s.identifier]=l,i=Da(i,ug,n||e.logger,!1).cfg;try{t.initialize(i,o,n,r)}catch(t){to(e.logger,1,514,"Failed to initialize SDK."+rt(t))}}),(function(){return{config:i,extensions:a}}))},e.unload=function(i,n,r){return o[sg]&&o[sg]((e.config||{}).instrumentationKey),t.unload(i,n,r)}})),a}return Oi(t,e),t.__ieDyn=1,t}(_c),mg=class{constructor(e=F,t=U,i=x){this.tenantToken=e,this.onedsCollectorURL=t,this.eventsLimitInMem=i,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 gg,this.initManager()}sendEvent(e,t){const i=this.manager.getInst(this.tenantToken)??this.manager.newInst(this.tenantToken),n={};for(const t of Object.keys(e))n[t]={value:e[t]};const r={name:t||this.DB_NAME,data:n,latency:Ic.Normal,persistence:wc.Normal};i.track(r)}sendRealTimeEvent(e){this.sendEvent(e,this.DB_NAME_REALTIME)}sendTerminatedTelemetrEvent(e){this.sendEvent(e,this.DB_NAME_TERMINATED)}initManager(){const e={propertyConfiguration:{populateBrowserInfo:!0,populateOperatingSystemInfo:!0},channelConfiguration:{eventsLimitInMem:this.eventsLimitInMem},endpointUrl:this.onedsCollectorURL,enableCompoundKey:!0};this.manager.create(e,[])}},fg=class{constructor(e){this.logger=e,this.realTimeTelemetryStarted=!1,this.telemetryLogger=new mg,this.sessionStat=new Map,this.realTimeTelemetryInterval=B}setConfig(e,t,i,n){this.logger.log(`Setting telemetry config:\n tenantToken: ${e?"****":"undefined"},\n onedsCollectorURL: ${t}, \n eventsLimitInMem: ${i}, \n realTimeTelemetryInterval: ${n}`),this.realTimeTelemetryInterval=n??this.realTimeTelemetryInterval,this.telemetryLogger=new mg(e,t,i)}addSession(e){this.sessionStat.has(e.id)||this.sessionStat.set(e.id,e)}getSession(e){return this.sessionStat.get(e)}sendTelemetry(e){if(!this.sessionStat.has(e))return void this.logger.log(`Invalid session if ${e}`);const t=this.sessionStat.get(e);this.telemetryLogger.sendEvent(t.getReport())}startRealtimeTelemetry(){this.realTimeTelemetryStarted||(this.realTimeTelemetryStarted=!0,this.sendRealTimeTelemetry())}stopRealtimeTelemetry(){this.realTimeTelemetryStarted=!1}sendLastGatheredTelemetry(e){if(e){const t=this.sessionStat.get(e);t&&this.telemetryLogger.sendTerminatedTelemetrEvent(t.getReport())}else this.sessionStat.forEach((e=>{this.telemetryLogger.sendTerminatedTelemetrEvent(e.getReport())}))}removeSession(e){this.sessionStat.delete(e)}clear(){this.sessionStat.clear()}sendRealTimeTelemetry(){this.realTimeTelemetryStarted&&(this.logger.info("Sending real time telemetry"),this.sessionStat.forEach((e=>{this.telemetryLogger.sendRealTimeEvent(e.getReportForRealTime())})),setTimeout((()=>{this.sendRealTimeTelemetry()}),B))}},vg=class{constructor(e,t,i,n){this.id=e,this.logger=t,this.getRpcTelemetry=i,this.getTransportTelemetry=n,this.metricsMap=new Map,this.startTime=Date.now(),this.stacksCreatedAt=[],this.connectionTerminatedAt=void 0}startTimer(e){const t=this.metricsMap.get(e)??new Sg(this.logger);t.start(),this.metricsMap.has(e)||this.metricsMap.set(e,t)}stopTimer(e){this.metricsMap.get(e)?.stop()}setTsCallingVersion(e){this.tsCallingVersion=e}addStack(){b(this.stacksCreatedAt,Date.now(),10)}setConnectionTerminatedAt(){this.connectionTerminatedAt=Date.now()}},Sg=class{constructor(e){this.logger=e}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}}},yg=new class{constructor(){this.onConnectionTerminatedCallbacks=new Set}onConnectionTerminated(e){this.onConnectionTerminatedCallbacks.add(e)}setChannel(e){this.channelId=e}addTransportManager(e){this.sessionInitializedAt=Date.now(),this.transportEvent?.dispose(),this.transportEvent=e.on("connectionTerminated",(e=>{this.channelId&&e!==this.channelId||(this.lastSesstionTerminatedAt=Date.now(),this.onConnectionTerminatedCallbacks.forEach((e=>e())))}))}getStat(){return{lastSesstionTerminatedAt:this.lastSesstionTerminatedAt,sessionInitializedAt:this.sessionInitializedAt}}},Cg=new class{constructor(e){this.remoteStackHealthCheck=e}onConnectionTerminated(e){this.remoteStackHealthCheck.onConnectionTerminated(e)}getStat(){return this.remoteStackHealthCheck.getStat()}}(yg);function Tg(e,t){return e.shellify(t)}var Eg="$$marshalled",bg="$$ref",_g=e=>"object"==typeof e&&null!==e&&bg in e,Ig=e=>e[bg],wg=class{constructor(e){this.marshallers=e}pack(e){const t=this.findMarshaller(e);return t?((e,t)=>({[Eg]:{type:e,properties:t}}))(t.type,t.marshall(e)):e}unpack(e){const t=this.findUnmarshaller(e);return t?t.unmarshall((e=>e[Eg].properties)(e)):e}findMarshaller(e){return this.marshallers.find((t=>t.canMarshall(e)))}findUnmarshaller(e){return this.marshallers.find((t=>t.canUnmarshall(e)))}},Ag=class{constructor(e,t,i){this.logger=e,this.uniqueIdFactory=t,this.config=i,this.finalizationRegistry=new FinalizationRegistry((e=>{this.logger.info("Reference garbage collected",e),this.refIdToRef.delete(e)})),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(e,t=this.uniqueIdFactory.getNextRefId()){if(void 0!==e){if(this.hasByRef(e))return this.getRefId(e);try{return this.refIdToRef.set(t,new WeakRef(e)),this.refToRefId.set(e,t),this.finalizationRegistry.register(e,t),t}catch(t){return void this.logger.error("Error when saving a reference",e,t)}}}getRef(e){if(void 0!==e)return this.refIdToRef.get(e)?.deref()}getRefId(e){return this.refToRefId.get(e)}hasByRef(e){return this.refToRefId.has(e)}hasByRefId(e){return!!this.refIdToRef.has(e)&&void 0!==this.getRef(e)}removeByRefId(e){const t=this.refIdToRef.get(e)?.deref();this.refIdToRef.delete(e),t&&this.refToRefId.delete(t)}removeByRef(e){const t=this.refToRefId.get(e);this.refToRefId.delete(e),t&&this.refIdToRef.delete(t)}saveShellRef(e){this.shellRefs.add(e)}isShellByRef(e){return this.shellRefs.has(e)}isShellByRefId(e){const t=this.getRef(e);return void 0!==t&&this.shellRefs.has(t)}toReferenced(e){return this.hasByRef(e)?(e=>({[bg]:e}))(this.getRefId(e)):e}fromReferenced(e){return _g(e)?this.getRef(Ig(e)):e}},Pg=class{getNextExecutionId(){return S(8)}getNextRefId(){return S(10)}},Rg={timeout:5e4},Mg=class{constructor(e,t,i){this.logger=e,this.uniqueIdFactory=t,this.pool=new Map,this.timeout=i.timeout}setTimeout(e){this.logger.info(`timeout set to, ${e}`),this.timeout=e}create(){const e=this.uniqueIdFactory.getNextExecutionId(),{promise:t,resolve:i,reject:n}=R(this.timeout,JSON.stringify("timeout"));return this.pool.set(e,[i,n]),[e,t.finally((()=>{this.logger.debug(`removing execution ${e} from pool`),this.pool.delete(e)}))]}getExecutionHandlers(e){const t=this.pool.get(e);if(!t)throw this.logger.error(`no execution with id ${e} is waiting for result.`),new Error(`no execution with id ${e} is waiting for result.`);return t}dispose(){this.pool.forEach((([,e])=>e(new Error("Transport closed")))),this.pool.clear()}},Dg=class{canUnmarshall(e){return((e,t)=>!("object"!=typeof t||null===t||!(e=>Eg in e)(t))&&t[Eg].type===e)(this.type,e)}},kg=class extends Dg{constructor(e,t){super(),this.logger=e,this.referenceManager=t}ensureRefSaved(e){this.referenceManager.hasByRef(e)||(this.logger.warn("Value not saved before marshalling, saving"),this.referenceManager.saveRef(e))}ensureRefExists(e){if(!this.referenceManager.hasByRefId(e.refId)){this.logger.info("Value does not exist, creating shell");const t=this.createShellRef(e);this.referenceManager.saveRef(t,e.refId),this.referenceManager.saveShellRef(t)}}},Og=class extends kg{marshall(e){return this.ensureRefSaved(e),{refId:this.referenceManager.getRefId(e),entries:this.marshallEntries(e)}}unmarshall(e){this.ensureRefExists(e);const t=this.referenceManager.getRef(e.refId);return this.unmarshallEntries(t,e.entries),t}},Ng=class extends Dg{constructor(){super(...arguments),this.type="error"}marshall(e){return{message:e.message,stack:e.stack,name:e.name,cause:e.cause}}unmarshall(e){const t=new Error(e.message);return t.stack=e.stack,t.name=e.name,t.cause=e.cause,t}canMarshall(e){return e instanceof Error}},Lg=class extends Og{constructor(){super(...arguments),this.type="array"}canMarshall(e){return Array.isArray(e)}createShellRef(){return new Array}marshallEntries(e){return e.map(((e,t)=>[t,this.referenceManager.toReferenced(e)]))}unmarshallEntries(e,t){e.length=0;for(const[i,n]of t)e[i]=this.referenceManager.fromReferenced(n);return e}},xg=class extends kg{constructor(e,t,i){super(e,t),this.execute=i,this.type="function"}marshall(e){return this.ensureRefSaved(e),{refId:this.referenceManager.getRefId(e)}}unmarshall(e){return this.ensureRefExists(e),this.referenceManager.getRef(e.refId)}canMarshall(e){return"function"==typeof e}createShellRef(){const e=this.execute,t=function(...i){return e(t,i,this)};return t}},Fg=(e,t,i)=>{try{return e.value??e.get?.call(t)}catch(e){return void i?.warn("Failed to read property value",e)}},Ug=Object.getPrototypeOf({});function*Bg(e,t){let i=e;const{allowedObjectNames:n,deniedNames:r,deniedValues:s}=t,a=new Set(r),o=e=>Array.from(t.deniedInstances).some((t=>e instanceof t)),l=i?n.get(i)??n.get(i.constructor):void 0;do{if(0!==l?.size){for(const t of Object.getOwnPropertyNames(i)){if(a.has(t))continue;if(l&&!l.has(t))continue;const n=Object.getOwnPropertyDescriptor(i,t),r=Fg(n,e);o(r)||s.has(r)||(a.add(t),yield[t,n])}i=Reflect.getPrototypeOf(i)}else i=Reflect.getPrototypeOf(i)}while(i&&i!==Ug)}var Vg=class extends kg{constructor(e,t,i){super(e,t),this.propertyCollectionConfig=i,this.type="object"}marshall(e){this.ensureRefSaved(e);const t=this.referenceManager.getRefId(e),i=Object.create(null);for(const[t,n]of Bg(e,this.propertyCollectionConfig))i[t]=this.referenceManager.toReferenced(Fg(n,e,this.logger));return{refId:t,properties:i}}unmarshall(e){const{refId:t,properties:i}=e;this.ensureRefExists(e);const n=this.referenceManager.getRef(t);if(void 0===n&&this.logger.warn("reference lost. refId=",t),void 0===i)return this.logger.info("no properties to be applied. refId=",t),n;for(const[e,t]of Bg(n,this.propertyCollectionConfig)){const n=i[e];void 0!==n&&_g(n)&&this.referenceManager.saveRef(t.value,Ig(n))}for(const[e,t]of Object.entries(i))Reflect.defineProperty(n,e,{value:this.referenceManager.fromReferenced(t),enumerable:!0,writable:!0,configurable:!0});return n}canMarshall(e){return"object"==typeof e&&null!==e}createShellRef(){return{}}},Hg=class{constructor(e,t,i,n){this.logger=e,this.referenceManager=t,this.propertyCollectionConfig=i,this.worldRootRef=n}ingestRefs(e){const t=new Set(e);t.add(this.worldRootRef);for(const[,e]of this.referenceManager.getRefs())this.referenceManager.isShellByRef(e)||t.add(e.deref());t.delete(void 0);const i=Array.from(t);if(0===i.length)return void this.logger.info("nothing to ingest");this.logger.info("ingesting references");const n=new Set;for(;i.length;){const e=i.pop();if(null!==e&&!("object"!=typeof e&&"function"!=typeof e||this.isNotAllowedByPropertyCollectionConfig(e)||n.has(e)||(n.add(e),this.referenceManager.saveRef(e),"function"==typeof e)))if(e instanceof Map)for(const[t,n]of e.entries())i.push(t,n);else if(e instanceof Set||Array.isArray(e))i.push(...e.values());else for(const[,t]of Bg(e,this.propertyCollectionConfig)){const n=Fg(t,e,this.logger);n&&i.push(n)}}}isNotAllowedByPropertyCollectionConfig(e){if(this.propertyCollectionConfig.deniedValues.has(e))return!0;for(const t of this.propertyCollectionConfig.deniedInstances)if(e instanceof t)return!0;return!1}},$g=class{constructor(){this.requests=[],this.historyLength=100}registerStat(e){b(this.requests,e,this.historyLength)}getStats(e){let t=this.requests;return e&&(t=this.requests.filter((({timestamp:t})=>t>=e))),{requests:t,avgRtt:this.getAverage(t,"rtt"),avgRequestSize:this.getAverage(t,"requestSize"),avgResponseSize:this.getAverage(t,"responseSize"),medianRtt:this.getMedian(t,"rtt"),medianRequestSize:this.getMedian(t,"requestSize"),medianResponseSize:this.getMedian(t,"responseSize")}}clear(){this.requests=[]}getMedian(e,t){const i=e.map((e=>e[t])),n=e.length;if(0===n)return 0;const r=[...i].sort(),s=Math.floor(n/2);return n%2==0?(r[s-1]+r[s])/2:r[s]}getAverage(e,t){return 0===e.length?0:e.reduce(((e,i)=>e+i[t]),0)/e.length}},jg=class{constructor(e){this.rpcStatsManager=e}getReport(e){const{requests:t,avgRtt:i,avgRequestSize:n,avgResponseSize:r,medianRtt:s,medianRequestSize:a,medianResponseSize:o}=this.rpcStatsManager.getStats(e);return{RPC_requests:JSON.stringify(t),RPC_avgRtt:i,RPC_avgRequestSize:n,RPC_avgResponseSize:r,RPC_medianRtt:s,RPC_medianRequestSize:a,RPC_medianResponseSize:o}}},Gg=class{constructor(){this.failed=!1,this.steps=new Map,this.startTime=Date.now()}startStep(e){this.steps.set(e,{start:Date.now(),end:void 0})}endStep(e){const t=this.steps.get(e);if(!t)return;const i=t.start;this.steps.set(e,{start:i,end:Date.now()})}setRequestBody(e){this.requestBody=JSON.stringify(e)}setResponseBody(e){this.responseBody=JSON.stringify(e)}markFailed(){this.failed=!0}getStat(){return{timestamp:this.startTime,rtt:Date.now()-this.startTime,requestSize:_(this.requestBody||""),responseSize:_(this.responseBody||""),steps:Array.from(this.steps).map((([e,{start:t,end:i}])=>({name:e,duration:i?i-t:void 0}))),failed:this.failed}}},qg=class{constructor(e,t,i,n,r){this.logger=e,this.transport=t,this.remoteExecutionStorage=i,this.snapshotManager=n,this.referenceExtractor=r,this.synchronized=new P,this.transport.addEventListener("sync-state",(e=>{this.handleSynchronizeState(e)})),this.transport.addEventListener("sync-state-result",(e=>{this.handleSynchronizeStateResult(e)})),this.transport.addEventListener("sync-state-request",(e=>{this.handleSynchronizeStateRequest(e)}))}async waitForSynchronization(){return this.logger.info("waiting for remote sync to be completed"),this.transport.dispatchEvent({type:"sync-state-request"}),this.synchronized.promise}async synchronize(e=[]){this.logger.info("writing remote state"),this.referenceExtractor.ingestRefs(e);const t=this.snapshotManager.create(),[i,n]=this.remoteExecutionStorage.create();this.transport.dispatchEvent(((e,t)=>({type:"sync-state",executionId:e,payload:{snapshot:t}}))(i,t)),this.logger.info(`Execution[${i}]: waiting to be resolved`),await n}handleSynchronizeState(e){this.logger.info("updating state from remote");const t=e.payload.snapshot;this.snapshotManager.apply(t),this.transport.dispatchEvent((e=>({type:"sync-state-result",executionId:e}))(e.executionId)),this.synchronized.resolve()}handleSynchronizeStateResult(e){this.logger.info("remote state updated");const[t]=this.remoteExecutionStorage.getExecutionHandlers(e.executionId);t()}handleSynchronizeStateRequest(e){this.logger.info("received request to update remote"),this.synchronize()}},zg=class{constructor(e,t,i,n,r,s,a,o){this.logger=e,this.transport=t,this.remoteExecutionStorage=i,this.snapshotManager=n,this.payloadManager=r,this.referenceManager=s,this.referenceExtractor=a,this.statManager=o,this.executionTelemetry=new Map,this.transport.addEventListener("remote-execute-by-ref",(e=>{this.handleExecuteByRefRequest(e)})),this.transport.addEventListener("remote-execute-result",(e=>{this.handleExecuteResult(e)}))}async executeByRef(e,t,i){const[n,r]=this.remoteExecutionStorage.create(),s=new Gg;this.executionTelemetry.set(n,s),this.logger.info(`[${n}]: start execution by reference`);const a=this.referenceManager.saveRef(e),o=this.referenceManager.saveRef(t),l=this.referenceManager.saveRef(i);this.logger.info(`[${n}]: creating event: target[${a}]="${e.name}"; args=[${o}]; context[${l}];`),s.startStep("ReferenceUpdate"),this.referenceExtractor.ingestRefs([e,t,i]),s.endStep("ReferenceUpdate"),s.startStep("SnapshotCreated");const c=this.snapshotManager.create();s.endStep("SnapshotCreated"),this.logger.info(`[${n}]: snapshot created`);const d=((e,t,i,n,r,s=!1)=>({type:"remote-execute-by-ref",executionId:e,queued:s,payload:{target:t,args:n,context:i,snapshot:r}}))(n,a,l,o,c);s.setRequestBody(d),this.transport.dispatchEvent(d);try{this.logger.info(`[${n}]: waiting to be resolved`),s.startStep("RemoteExecution");const e=await r;if(s.endStep("RemoteExecution"),this.logger.info(`[${n}]: remote execution resolved`),void 0===e)return void this.logger.info(`[${n}]: skip unpacking, as response is undefined`);s.startStep("ReponseUnpack");const t=this.payloadManager.unpack(e);return s.endStep("ReponseUnpack"),this.logger.info(`[${n}]: response unpacked`),t}catch(e){if(s.markFailed(),e instanceof Error)throw this.logger.error(`[${n}]: internal error:`,e),e;s.startStep("ReponseUnpack");const t=this.payloadManager.unpack(e);throw s.endStep("ReponseUnpack"),this.logger.error(`[${n}]: remote error:`,t),t}finally{queueMicrotask((()=>{this.statManager.registerStat(s.getStat()),this.executionTelemetry.delete(n)}))}}async handleExecuteByRefRequest(e){const t=e.executionId,{target:i,args:n,context:r,snapshot:s}=e.payload;try{this.logger.info(`[${t}]: local execute start`),this.snapshotManager.apply(s);const a=this.referenceManager.getRef(i);if(!a)throw this.logger.error(`[${t}]: unknown local target[${i}]`),new Error("Unknown execution target");const o=this.referenceManager.getRef(r),l=this.referenceManager.getRef(n)??[];this.logger.info(`[${t}]: executing on local target[${i}]="${a.name}" with context[${r}] and arguments[${n}]`);const c=await Reflect.apply(a,o,l);this.logger.info(`[${t}]: local result:`,c),this.referenceExtractor.ingestRefs([l,o,c]),this.transport.dispatchEvent((({executionId:e},t)=>({type:"remote-execute-result",executionId:e,payload:{result:t,snapshot:this.snapshotManager.create()}}))(e,this.payloadManager.pack(c)))}catch(i){this.logger.error(`[${t}]: local failed with error:`,i),this.referenceExtractor.ingestRefs([i]),this.transport.dispatchEvent((({executionId:e},t,i)=>({type:"remote-execute-result",executionId:e,payload:{error:t instanceof Error?t.message:t,snapshot:i}}))(e,this.payloadManager.pack(i),this.snapshotManager.create()))}}handleExecuteResult(e){const{executionId:t,payload:i}=e;this.executionTelemetry.get(t)?.setResponseBody(i);const n=e.payload.snapshot;this.logger.info(`[${t}]: handling execution result`),this.snapshotManager.apply(n);const[r,s]=this.remoteExecutionStorage.getExecutionHandlers(t);"error"in i?s(i.error):r(i.result)}},Wg=class extends Og{constructor(){super(...arguments),this.type="map"}canMarshall(e){return e instanceof Map}createShellRef(){return new Map}marshallEntries(e){return Array.from(e.entries()).map((([e,t])=>[this.referenceManager.toReferenced(e),this.referenceManager.toReferenced(t)]))}unmarshallEntries(e,t){e.clear();for(const[i,n]of t)e.set(this.referenceManager.fromReferenced(i),this.referenceManager.fromReferenced(n));return e}},Kg=class extends Og{constructor(){super(...arguments),this.type="set"}canMarshall(e){return e instanceof Set}createShellRef(){return new Set}marshallEntries(e){return Array.from(e.values()).map((e=>this.referenceManager.toReferenced(e)))}unmarshallEntries(e,t){e.clear();for(const i of t)e.add(this.referenceManager.fromReferenced(i));return e}},Jg=class{constructor(e,t,i){this.logger=e,this.referenceManager=t,this.payloadManager=i}getReferences(){const e=[];for(const[t,i]of this.referenceManager.getRefs()){const n=i.deref();void 0!==n?this.referenceManager.isShellByRef(n)||e.push([t,this.payloadManager.pack(n)]):this.logger.warn("Reference garbage collected. refId=",t)}return e}applyReferences(e){for(const[t,i]of e)this.referenceManager.saveRef(this.payloadManager.unpack(i),t);for(const[t,i]of e)this.referenceManager.saveRef(this.payloadManager.unpack(i),t)}},Yg=class extends Jg{constructor(e,t,i){super(e,t,i),this.lastSentReferences=[],this.lastRecvReferences=[]}create(){this.logger.info("creating snapshot");const e=this.getReferences();if(!this.lastSentReferences.length){this.logger.info("no previous snapshot available, creating full snapshot"),this.lastSentReferences=e;const t={"+":e};return this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(t)),t}this.logger.info("previous snapshot available, creating delta snapshot");const t=new Map(this.lastSentReferences),i=new Map(e),n={"-":[],"+":[],"*":[]};for(const e of new Set([...t.keys(),...i.keys()]))this.referenceManager.isShellByRefId(e)||(!t.has(e)||i.has(e)?t.has(e)||!i.has(e)?t.has(e)&&i.has(e)&&JSON.stringify(t.get(e))!==JSON.stringify(i.get(e))&&n["*"].push([e,i.get(e)]):n["+"].push([e,i.get(e)]):n["-"].push(e));return this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(n)),this.lastSentReferences=e,n}apply(e){this.logger.info("applying snapshot"),this.logger.debug(JSON.stringify(e)),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 t=new Map(this.lastRecvReferences);for(const i of e["-"]??[])this.referenceManager.removeByRefId(i),t.delete(i);for(const[i,n]of e["+"]??[])t.set(i,n);for(const[i,n]of e["*"]??[])t.set(i,n);this.lastRecvReferences=Array.from(t.entries()),this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(this.lastRecvReferences)),this.applyReferences(this.lastRecvReferences)}},Qg=class extends Dg{constructor(e,t){super(),this.type=e,this.value=t}marshall(e){}unmarshall(){return this.value}canMarshall(e){return e===this.value}},Zg=e=>"BigInt64Array"===e[Symbol.toStringTag]||"BigUint64Array"===e[Symbol.toStringTag],Xg=class e extends kg{constructor(){super(...arguments),this.type="typedArray"}marshall(e){return this.ensureRefSaved(e),{refId:this.referenceManager.getRefId(e),type:e[Symbol.toStringTag],values:Zg(e)?Array.from(e).map((e=>e.toString())):Array.from(e),byteOffset:e.byteOffset,bufferType:e.buffer[Symbol.toStringTag],bufferByteLength:e.buffer.byteLength}}unmarshall(e){this.ensureRefExists(e);const t=this.referenceManager.getRef(e.refId),i=Zg(t)?BigInt:Number;for(const[n,r]of e.values.entries())t[n]=i(r);return t}createShellRef(t){if(!e.TYPED_ARRAY_CONSTRUCTOR.has(t.type))throw new Error(`Unknown typed array type: ${t.type}`);const i=e.TYPED_ARRAY_CONSTRUCTOR.get(t.type);return"SharedArrayBuffer"===t.bufferType&&this.logger.error("SharedArrayBuffers are mostly disabled, consider using ArrayBuffer instead"),new i(new ArrayBuffer(t.bufferByteLength),t.byteOffset)}canMarshall(t){if("object"!=typeof t||null===t)return!1;if(Symbol.toStringTag in t){const i=t[Symbol.toStringTag];return"string"==typeof i&&e.TYPED_ARRAY_CONSTRUCTOR.has(i)}return!1}};Xg.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 ep=Xg,tp={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])},ip=class{constructor(e,t,i,n=new Pg){this.transport=e,this.logger=t,this.config=i,this.uniqueIdFactory=n,this.statManager=new $g,this.rpcTelemetryProvider=new jg(this.statManager),this.propertyCollectionConfig={...tp,...this.config?.propertyCollectionConfig},this.referenceManager=new Ag(this.logger.createChild("ReferenceManager"),this.uniqueIdFactory,{disableWeakRefs:this.config?.disableWeakRefs}),this.referenceExtractor=new Hg(this.logger.createChild("ReferenceExtractor"),this.referenceManager,this.propertyCollectionConfig,this.config?.worldRootRef),this.payloadManager=new wg([new Ng,new Qg("globalThis",globalThis),new Qg("document",document),new Wg(this.logger.createChild("MapMarshaller"),this.referenceManager),new Kg(this.logger.createChild("SetMarshaller"),this.referenceManager),new Lg(this.logger.createChild("ArrayMarshaller"),this.referenceManager),new ep(this.logger.createChild("TypedArrayMarshaller"),this.referenceManager),new xg(this.logger.createChild("FunctionMarshaller"),this.referenceManager,((e,t,i)=>this.executeByRef(e,t,i))),new Vg(this.logger.createChild("ObjectMarshaller"),this.referenceManager,this.propertyCollectionConfig)]),this.snapshotManager=new Yg(this.logger.createChild("SnapshotManager"),this.referenceManager,this.payloadManager),this.remoteExecutionStorage=new Mg(this.logger.createChild("RemoteExecutionStorage"),this.uniqueIdFactory,{...Rg,timeout:this.config?.remoteExecutionTimeout??Rg.timeout}),this.remoteExecutionService=new zg(this.logger.createChild("RemoteExecutionService"),this.transport,this.remoteExecutionStorage,this.snapshotManager,this.payloadManager,this.referenceManager,this.referenceExtractor,this.statManager),this.synchronizer=new qg(this.logger.createChild("StateSynchronizer"),this.transport,this.remoteExecutionStorage,this.snapshotManager,this.referenceExtractor)}get telemetryProvider(){return this.rpcTelemetryProvider}waitForSynchronization(){return this.synchronizer.waitForSynchronization()}synchronize(...e){return this.synchronizer.synchronize(e)}setRequestTimeout(e){this.remoteExecutionStorage.setTimeout(e)}getPropertyCollectionConfig(){return this.propertyCollectionConfig}saveRef(e,t){return this.referenceManager.saveRef(t,e),t}shellify(e){if("object"==typeof e){this.referenceManager.saveShellRef(e);for(const[t,i]of Bg(e,this.getPropertyCollectionConfig()))"function"==typeof i.value&&(Reflect.defineProperty(e,t,{value:new Proxy(i.value,{apply:(i,n,r)=>this.executeByRef(Reflect.get(e,t),r,n)})}),this.referenceManager.saveShellRef(Reflect.get(e,t))),i.get;return e}if("function"==typeof e){const t=new Proxy(e,{apply:(e,i,n)=>this.executeByRef(t,n,i)});return t}throw new Error("Unsupported type")}async executeByRef(e,t,i){return this.remoteExecutionService.executeByRef(e,t,i)}dispose(){this.logger.info("Disposing RPCService"),this.remoteExecutionStorage.dispose(),this.referenceManager.dispose(),this.statManager.clear()}},np=class extends vg{constructor(){super(...arguments),this.namespace="Shell"}getReport(){const e=this.metricsMap.get("TimeToEstablishConnection")?.getReport();return{NameSpace:this.namespace,SessionId:this.id,TsCallingVersion:this.tsCallingVersion,Session_StartTime:this.startTime,EstablishConnection_StartTime:e?.startTime,EstablishConnection_Duration:e?.duration,...this.getRpcTelemetry(),...this.getTransportTelemetry()}}getReportForRealTime(){return{NameSpace:this.namespace,...this.getRpcTelemetry(),...this.getTransportTelemetry()}}},rp=Q,sp=Z,ap=class e{constructor(e,t,i=""){this.ulLogComponent=e,this.ulSafeComponent=t,this._getPrefix=(0,sp.isFunction)(i)?i:()=>i,this.logComponent=rp.LogFactory.instance().component(this.ulLogComponent),rp.LogFactory.instance().declareComponentSafe(this.ulLogComponent,t)}createChild(t){const i=(0,sp.isFunction)(t)?t:()=>t;return new e(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${i()}`:i()))}log(...e){this._apply((e=>this.logComponent.debug2(null,e)),e)}debug(...e){this._apply((e=>this.logComponent.debug4(null,e)),e)}info(...e){this._apply((e=>this.logComponent.debug1(null,e)),e)}warn(...e){this._apply((e=>this.logComponent.warn(null,e)),e)}error(...e){this._apply((e=>this.logComponent.error(null,e)),e)}_apply(e,t=[]){this._addPrefix(t),e(t.map((e=>e instanceof DOMException?e.toString():e)).map((e=>(0,sp.isObject)(e)?JSON.stringify(e):e)).join(", "))}_addPrefix(e){if(e&&e[0]){const t=`${this._getPrefix()} ${e[0]}`;e[0]=t}}},op=g(p()),lp=class{constructor(){this.fallbackLogger=new ap("RemoteStackFactory",!0),this.telemetry=new fg(this.logger),this.healthCheck=yg}async build(e){return this.callingLogger??(this.callingLogger=e.logger.createChild("RemoteStackFactory")),this.remoteStackFactory??(this.remoteStackFactory=await this.getFactory(e.vdi3Config)),this.remoteStackFactory.build(this.getRemoteStackConfig(e))}async buildBaseStack(e){return this.callingLogger??(this.callingLogger=e.logger.createChild("RemoteStackFactory")),this.remoteStackFactory??(this.remoteStackFactory=await this.getFactory(e.vdi3Config)),this.remoteStackFactory.buildBaseStack(this.getRemoteBaseStackConfig(e))}getVersion(){return{build:"2025.07.01.15",ovb:"8962f6ae8324f6a345d7997ae8f276ff81198956"}}async getFactory(e){const{transport:t,telemetryConfig:i,pluginlessUrl:n,cdnUrl:r}=e;if(!t)throw new Error("transport is required for remote stack");const s=v(),a=this.logger.createChild(`Channel:${s}`);this.transportManager??(this.transportManager=new Y(t,this.logger.createChild("TransportManager"))),this.healthCheck.addTransportManager(this.transportManager),this.transportManager.on("connectionTerminated",(()=>{a.log("Connection terminated, disposing."),this.dispose()})),this.healthCheck.setChannel(s),i&&this.telemetry.setConfig(i.tenantToken,i.onedsCollectorURL,i.eventsLimitInMem,i.realTimeTelemetryInterval);const o=new np(s,a.createChild("Telemetry"),(()=>this.rpcSession?.telemetryProvider.getReport()),(()=>this.transportManager?.telemetryProvider.getReport()));this.telemetry.addSession(o);const l={tsCallingVersion:this.getVersion().build,channelId:s,pluginlessUrl:n,cdnUrl:r,telemetryConfig:i};a.log(`Initiating connection with payload: ${JSON.stringify(l)}`),o.startTimer("TimeToEstablishConnection"),await this.transportManager.initiateConnection(l),o.stopTimer("TimeToEstablishConnection");const c=new ip(this.transportManager.createChannel(s),a.createChild("RPCService"),{remoteExecutionTimeout:t.config?.remoteExecutionTimeout,disableWeakRefs:!0});this.rpcSession=c,e.shellTrouter&&c.saveRef("shell-trouter",Tg(c,e.shellTrouter)),c.saveRef("remote-telemetry-provider",{getReport:async e=>({transport:this.transportManager.telemetryProvider.getReport(e),rpc:c.telemetryProvider.getReport(e)})});const d=c.saveRef("pluginless-stack",Tg(c,{build:e=>{throw new Error("Should be executed rmotely")},buildBaseStack:e=>{throw new Error("Should be executed rmotely")}}));return await c.waitForSynchronization(),this.telemetry.sendTelemetry(s),this.telemetry.startRealtimeTelemetry(),d}getRemoteStackConfig(e){const t=e.logger,{vdi3Config:{trouterSettings:i},stackType:n,...r}=e;if(!i)throw new Error("Trouter setting is required for remoteStack");const s=(0,op.default)(r);this.removeHttpDispatcher(s),this.removeLogger(s),this.removeTrouterService(s),this.sanitizeTelemetryConfig(s.telemetryService,t),this.removeEffectConfigProvider(s.mediaAgentFactoryConfig);const a={...s,trouterSettings:i};return t.log(`RemoteStackConfig: ${JSON.stringify(a)}`),a}getRemoteBaseStackConfig(e){const t=e.logger,{vdi3Config:i,stackType:n,...r}=e,s=(0,op.default)(r);return this.removeHttpDispatcher(s),this.removeLogger(s),this.sanitizeTelemetryConfig(s.telemetryService,t),t.log(`baseStackConfig: ${JSON.stringify(s)}`),s}sanitizeTelemetryConfig(e,t){e.getCallingAdapter&&(delete e.getCallingAdapter,t.warn("getCallingAdapter not supported")),e.getGenericTelemetryLogger&&(delete e.getGenericTelemetryLogger,t.warn("getGenericTelemetryLogger not supported"))}removeLogger(e){delete e.logger;const t=e;delete t.signalingAgentConfig?.logger,delete t.mediaAgentFactoryConfig?.logger,delete t.mediaAgentFactoryConfig?.safeLogger,delete t.imageRendererConfig?.callingLogger}removeHttpDispatcher(e){delete e.imageRendererConfig?.httpRequestDispatcher;const t=e;delete t.signalingAgentConfig?.httpRequestDispatcher,delete t.mediaAgentFactoryConfig?.httpRequestDispatcher}removeTrouterService(e){delete e.trouterService,delete e.signalingAgentConfig.trouterServiceProvider}removeEffectConfigProvider(e){delete e.wasmVqeProvider,delete e.webcvProvider,delete e.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}},cp=g(m()),dp=new class{constructor(){this.remotedPluginlessStackFactory=new lp}async build(e){return this.getStackFactory(e.stackType).build(e)}async buildBaseStack(e){return this.getStackFactory(e.stackType).buildBaseStack(e)}getStackFactory(e){return 1===e?this.remotedPluginlessStackFactory:cp.pluginlessStackFactory}getVersion(){return cp.pluginlessStackFactory.getVersion()}},up=class{async state(){throw new Error("Should be executed remotely")}async onStateChanged(e){throw new Error("Should be executed remotely")}async offStateChanged(e){throw new Error("Should be executed remotely")}async getTrouterUrlAsync(){throw new Error("Should be executed remotely")}},hp=(e,t)=>((e,t,i={})=>{if("WebView"===e)return new C(t,i);if("TsCallingChannel"===e)return new T(t,i);throw new Error(`Transport type: ${e} not valid`)})("TsCallingChannel",t,e);return"object"==typeof r.exports&&(r.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||undefined===i||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(n=Object.getOwnPropertyDescriptor(t,i))||n.enumerable});return e})(r.exports,n)),r.exports}))}));class PO{constructor(e,t,i){this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((i=>{void 0!==e[i]&&(t[i]=e[i])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=i;const n=vy().calling.applicationSettingsUrls;this._trouterSettings={version:`3617/${FS()}`,productName:"AcsWeb",trouterServiceUrl:n.Public_TrouterServiceUrl,registrarServiceUrl:n.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:"AcsWeb",pnhTemplate:"AcsWeb_2.0",environment:"Prod",platform:CD()},this._JsCsaConfig={languageCode:"en",emergencyCallCountry:"",autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:i.proxyfyUrl(n.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:i.proxyfyUrl(n.Public_MdnTrapServiceUrl),tokenUrl:i.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[n.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[n.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:n.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 r=FS();r.includes("alpha")||r.includes("alpharc")||r.includes("beta")||r.includes("betarc")||(r.includes("stable")||r.includes("stablerc"))&&(this._JamaSettings.maxNumberOfPinnedVideos=1)}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){const e=bD();let t=this._JamaSettings;return"Mobile"==e.formFactor&&(t={...t,...this._JamaSettingsMobile}),t}getClientInformation(){const e=vy().telemetry.reportSdkUaToService,t=vy().telemetry.reportEnvToService;return`ACSWeb(3617/${FS()})`+(t?`/${function(){const e=bD();return`os=${_D()}; osVer=${ID()}; browser=${e.name}; browserVer=${e.version}; formFactor=${e.formFactor};`}()}`:"")+(e?`/(${this.sdkDiagnosticInformation})`:"")}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||vy().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info("Update ECS settings");const i=vy().calling.applicationSettingsUrls,n=vy().calling.applicationSettingsEudbUrls,r=e&&Dy(e.identityType,e.region);if(e?.identityType==wv.Enterprise)r?(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=i.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case Of.Public:r&&(this._trouterSettings.trouterServiceUrl=n.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Public_MdnTrapRelayTurnUrl_EUDB);break;case Of.GccHigh:this._trouterSettings.trouterServiceUrl=i.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.GccHigh_RegistrarServiceUrl);break;case Of.Dod:this._trouterSettings.trouterServiceUrl=i.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.Dod_RegistrarServiceUrl);break;case Of.AirGap08:this._trouterSettings.trouterServiceUrl=i.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap08_RegistrarServiceUrl);break;case Of.AirGap09:this._trouterSettings.trouterServiceUrl=i.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap09_RegistrarServiceUrl)}if(t)this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===wv.Enterprise)r?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case Of.Public:r&&(this._trouterSettings.trouterServiceUrl=n.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Public_MdnTrapRelayTurnUrl_EUDB);break;case Of.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.GccHigh_MdnTrapRelayTurnUrl;break;case Of.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.Dod_MdnTrapRelayTurnUrl;break;case Of.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap08_ConversationServiceUrl);break;case Of.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap09_ConversationServiceUrl)}}assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push("SkypeCalling"),e?.MDN_TRAP||t.push("MDN_TRAP"),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push("SkypeWebMedia.mediaAgent"):t.push("SkypeWebMedia"),e?.TrouterJScriptClient||t.push("TrouterJScriptClient"),t.length>0){const e=new le({defaultError:ee.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(", ")]});throw this._logger.error(e.message),e}}}var RO=G((function(e,t){var i;i=()=>{return e={659:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var i,n=new Promise((function(t,n){fetch(e).then((function(e){void 0!==i&&clearTimeout(i),t(e)})).catch((function(e){void 0!==i&&clearTimeout(i),n(e)}))}));if(0!==t){var r=new Promise((function(n,r){i=setTimeout(r,t,new Error("Fetch for '".concat(e.url,"' timed out")))}));return Promise.race([n,r])}return n},t.toJson=function(e){try{return JSON.stringify(e)}catch(t){return"Unable to serialize object of type ".concat(typeof e)}};var i=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}();t.Timespan=i},912:function(e,t,i){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__assign||function(){return s=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s.apply(this,arguments)},a=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var l=i(659),c=["skype","aad","cae"],d=function(e){function t(t){var i=e.call(this,t)||this;return i.name="CancelationError",i}return r(t,e),t}(Error),u=function(){function e(t,i,n){this.logger=t,this.maxBackoffInMs=i,this.initialDelay=n,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise((function(e,t){t(new d("Cancelled"))}));var i=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(e," for ").concat(i," milliseconds with ID ").concat(this.id)),new Promise((function(n,r){t.cancelFunc=r,t.timerHandle=setTimeout((function(){t.logger.info("[RegistrarClient] Back off for ".concat(e," with ID ").concat(t.id," complete")),t.timerHandle=void 0,n()}),i)}))},e.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new d("Cancelled"))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*Math.pow(2,this.backoffCount)*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),h=function(){function e(e,t,i){var n;this.logger=e,this.tokenProvider=t,this.options=i,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===i.maxRetriesForGetToken||null===i.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:i.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(n=i.proxyUrlRewrite)&&void 0!==n?n:function(e){return e}}return e.prototype.setTelemetryLogger=function(e){this.eventLogger=e},e.prototype.register=function(e,t){return a(this,void 0,void 0,(function(){return o(this,(function(i){switch(i.label){case 0:return[4,this.performRegistration(e,t,"pr_set_registration")];case 1:return i.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return a(this,void 0,void 0,(function(){var e;return o(this,(function(t){switch(t.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),e=new Request(this.proxyUrlRewrite("".concat(this.options.registrarUrl,"/").concat(this.options.registrationId)),{method:"DELETE",mode:"cors",headers:new Headers(s(s({},this.options.extraRegistrationHeaders),{accept:"application/json, text/javascript"}))}),[4,this.callRegistrar(e,"pr_delete_registration")];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return a(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.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 e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t,i){return a(this,void 0,void 0,(function(){var n,r;return o(this,(function(a){switch(a.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:"",transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(s(s({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0,l.toJson)(n)}),[4,this.callRegistrar(r,i)];case 1:return a.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new u(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return a(this,void 0,void 0,(function(){var t,i,n,r,s,a,l;return o(this,(function(o){switch(o.label){case 0:t=this.startBackoff(),i=0,o.label=1;case 1:return o.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new token"),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:c,wwwAuthenticateHeader:e,purpose:"registrar"})];case 2:return n=o.sent(),this.stopBackoff(t),[2,n];case 3:r=o.sent(),o.label=4;case 4:return o.trys.push([4,6,,7]),i++,s=JSON.stringify(r),i>this.maxRetriesForGetToken?(a="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(s),this.logger.error(a),this.stopBackoff(t),[2,Promise.reject(a)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(i," Error: ").concat(s)),[4,t.delay("Fetching a new token")]);case 5:return o.sent(),[3,8];case 6:throw l=o.sent(),this.stopBackoff(t),l;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e,t){var i,n,r;return a(this,void 0,void 0,(function(){var s,a,d,u,h,g,p,m,f,v,S,y,C,T,E,b;return o(this,(function(o){switch(o.label){case 0:return s=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:c,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:a=o.sent(),this.setTokenHeader(e,a),d=new l.Timespan,u=0,o.label=2;case 2:h=void 0,o.label=3;case 3:return o.trys.push([3,10,15,16]),g=e.clone(),[4,(0,l.fetchWithTimeout)(g,this.options.requestTimeoutMs)];case 4:return 401!==(h=o.sent()).status?[3,8]:++u>this.maxRetriesForGetToken?(p="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText),this.logger.error(p),this.stopBackoff(s),[2,Promise.reject(p)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(u,". Request '").concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText)),m=null!==(n=null===(i=h.headers)||void 0===i?void 0:i.get("www-authenticate"))&&void 0!==n?n:void 0,f=this.setTokenHeader,v=[e],[4,this.getToken(m)]);case 5:return f.apply(this,v.concat([o.sent()])),u>1?[4,s.delay("Registrar call retry after 401")]:[3,7];case 6:o.sent(),o.label=7;case 7:return[3,22];case 8:if(h.status>=500&&h.status<600)throw new Error("Fetch for '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText));o.label=9;case 9:return[3,16];case 10:S=o.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(S)),o.label=11;case 11:return o.trys.push([11,13,,14]),[4,s.delay("Registrar call retry")];case 12:return o.sent(),[3,22];case 13:throw y=o.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(s),y;case 14:return[3,16];case 15:return this.sendTelemetryEvent(t,e,h,d),[7];case 16:return this.stopBackoff(s),h.ok?[2,h]:[3,17];case 17:C=void 0,o.label=18;case 18:return o.trys.push([18,20,,21]),E=(T=JSON).stringify,[4,h.json()];case 19:return C=E.apply(T,[o.sent()]),[3,21];case 20:return o.sent(),C="no details",[3,21];case 21:throw b="Fetch for '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText," (").concat(C,", MS-CV: ").concat(null===(r=h.headers)||void 0===r?void 0:r.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(b)),new Error(b);case 22:return[3,2];case 23:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete("X-Skypetoken"),e.headers.delete("Authorization"),e.headers.delete("X-MS-Migration"),t.tokenType.toLowerCase()){case"skype":e.headers.set("X-Skypetoken",t.token);break;case"aad":case"cae":e.headers.set("Authorization","Bearer ".concat(t.token));break;default:throw new Error("unsupported token type: ".concat(t.tokenType))}!1===this.options.usingLegacyTokenApi&&e.headers.set("X-MS-Migration","True")},e.prototype.sendTelemetryEvent=function(e,t,i,n){if(void 0!==this.eventLogger){var r={name:e,properties:{url:{value:t.url},result_code:{value:void 0!==i?i.status:0},begin_timestamp:{value:n.startTime},elapsed:{value:n.duration}}};this.eventLogger.logEvent(r)}},e}();t.RegistrarClient=h,t.createRegistrarClient=function(e,t,i){return new h(e,t,i)}}},t={},function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}(912);var e,t},e.exports=i()})),MO=G((function(e,t){var i;i=e=>(()=>{var t={983:(e,t,i)=>{!function(e,t){var i=e;i.version="0.9.6",i.protocol=1,i.transports=[],i.j=[],i.sockets={},i.connect=function(e,n){var r,s,a=i.util.parseUri(e);t&&t.location&&(a.protocol=a.protocol||t.location.protocol.slice(0,-1),a.host=a.host||(t.document?t.document.domain:t.location.hostname),a.port=a.port||t.location.port),r=i.util.uniqueUri(a);var o={host:a.host,secure:"https"==a.protocol,port:a.port||("https"==a.protocol?443:80),query:a.query||""};return i.util.merge(o,n),!o["force new connection"]&&i.sockets[r]||(s=new i.Socket(o)),!o["force new connection"]&&s&&(i.sockets[r]=s),s=s||i.sockets[r],o["skipped handshake data"]?s.of(""):s.of(a.path.length>1?a.path:"")}}((e=i.nmd(e)).exports,void 0===i.g?window:i.g);var n=e.exports;!function(e,t){var i=e.util={},n=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];i.parseUri=function(e){for(var t=n.exec(e||""),i={},s=14;s--;)i[r[s]]=t[s]||"";return i},i.uniqueUri=function(e){var i=e.protocol,n=e.host,r=e.port;return"document"in t?(n=n||document.domain,r=r||("https"==i&&"https:"!==document.location.protocol?443:document.location.port)):(n=n||"localhost",r||"https"!=i||(r=443)),(i||"http")+"://"+n+":"+(r||80)},i.query=function(e,t){var n=i.chunkQuery(e||""),r=[];for(var s in i.merge(n,i.chunkQuery(t||"")),n)n.hasOwnProperty(s)&&r.push(s+"="+n[s]);return r.length?"?"+r.join("&"):""},i.chunkQuery=function(e){for(var t,i={},n=e.split("&"),r=0,s=n.length;r<s;++r)(t=n[r].split("="))[0]&&(i[t[0]]=t[1]);return i};var s=!1;i.load=function(e){if("document"in t&&"complete"===document.readyState||s)return e();i.on(t,"load",e,!1)},i.on=function(e,t,i,n){e.attachEvent?e.attachEvent("on"+t,i):e.addEventListener&&e.addEventListener(t,i,n)},i.request=function(e){if(e&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!e||i.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}return null},"undefined"!=typeof window&&i.load((function(){s=!0})),i.defer=function(e){if(!i.ua.webkit||"undefined"!=typeof importScripts)return e();i.load((function(){setTimeout(e,100)}))},i.merge=function(e,t,n,r){var s,a=r||[],o=void 0===n?2:n;for(s in t)t.hasOwnProperty(s)&&i.indexOf(a,s)<0&&("object"==typeof e[s]&&o?i.merge(e[s],t[s],o-1,a):(e[s]=t[s],a.push(t[s])));return e},i.mixin=function(e,t){i.merge(e.prototype,t.prototype)},i.inherit=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.intersect=function(e,t){for(var n=[],r=e.length>t.length?e:t,s=e.length>t.length?t:e,a=0,o=s.length;a<o;a++)~i.indexOf(r,s[a])&&n.push(s[a]);return n},i.indexOf=function(e,t,i){var n=e.length;for(i=i<0?i+n<0?0:i+n:i||0;i<n&&e[i]!==t;i++);return n<=i?-1:i},i.toArray=function(e){for(var t=[],i=0,n=e.length;i<n;i++)t.push(e[i]);return t},i.ua={},i.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var e=new XMLHttpRequest}catch(e){return!1}return null!=e.withCredentials}(),i.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent)}(void 0!==n?n:e.exports,void 0===i.g?window:i.g),function(e,t){function i(){}e.EventEmitter=i,i.prototype.on=function(e,i){return this.$events||(this.$events={}),this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(i):this.$events[e]=[this.$events[e],i]:this.$events[e]=i,this},i.prototype.addListener=i.prototype.on,i.prototype.once=function(e,t){var i=this;function n(){i.removeListener(e,n),t.apply(this,arguments)}return n.listener=t,this.on(e,n),this},i.prototype.removeListener=function(e,i){if(this.$events&&this.$events[e]){var n=this.$events[e];if(t.util.isArray(n)){for(var r=-1,s=0,a=n.length;s<a;s++)if(n[s]===i||n[s].listener&&n[s].listener===i){r=s;break}if(r<0)return this;n.splice(r,1),n.length||delete this.$events[e]}else(n===i||n.listener&&n.listener===i)&&delete this.$events[e]}return this},i.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},i.prototype.listeners=function(e){return this.$events||(this.$events={}),this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},i.prototype.emit=function(e){if(!this.$events)return!1;var i=this.$events[e];if(!i)return!1;var n=Array.prototype.slice.call(arguments,1);if("function"==typeof i)i.apply(this,n);else{if(!t.util.isArray(i))return!1;for(var r=i.slice(),s=0,a=r.length;s<a;s++)r[s].apply(this,n)}return!0}}(void 0!==n?n:e.exports,void 0!==n?n:e.parent.exports),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw new Error("JSON not available")}(void 0!==n?n:e.exports,"undefined"!=typeof JSON?JSON:void 0),function(e,t){var i=e.parser={},n=i.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],r=i.reasons=["transport not supported","client not handshaken","unauthorized"],s=i.advice=["reconnect"],a=t.JSON,o=t.util.indexOf;i.encodePacket=function(e){var t=o(n,e.type),i=e.id||"",l=e.endpoint||"",c=e.ack,d=null;switch(e.type){case"error":var u=e.reason?o(r,e.reason):"",h=e.advice?o(s,e.advice):"";""===u&&""===h||(d=u+(""!==h?"+"+h:""));break;case"message":""!==e.data&&(d=e.data);break;case"event":var g={name:e.name};e.args&&e.args.length&&(g.args=e.args),d=a.stringify(g);break;case"json":d=a.stringify(e.data);break;case"connect":e.qs&&(d=e.qs);break;case"ack":d=e.ackId+(e.args&&e.args.length?"+"+a.stringify(e.args):"")}var p=[t,i+("data"==c?"+":""),l];return null!=d&&p.push(d),p.join(":")},i.encodePayload=function(e){var t="";if(1==e.length)return e[0];for(var i=0,n=e.length;i<n;i++)t+="<22>"+e[i].length+"<22>"+e[i];return t};var l=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;i.decodePacket=function(e){if(!(o=e.match(l)))return{};var t=o[2]||"",i=(e=o[5]||"",{type:n[o[1]],endpoint:o[4]||""});switch(t&&(i.id=t,o[3]?i.ack="data":i.ack=!0),i.type){case"error":var o=e.split("+");i.reason=r[o[0]]||"",i.advice=s[o[1]]||"";break;case"message":i.data=e||"";break;case"event":try{var c=a.parse(e);i.name=c.name,i.args=c.args}catch(e){}i.args=i.args||[];break;case"json":try{i.data=a.parse(e)}catch(e){}break;case"connect":i.qs=e||"";break;case"ack":if((o=e.match(/^([0-9]+)(\+)?(.*)/))&&(i.ackId=o[1],i.args=[],o[3]))try{i.args=o[3]?a.parse(o[3]):[]}catch(e){}break;case"disconnect":i.reason=e}return i},i.decodePayload=function(e){if("<22>"==e.charAt(0)){for(var t=[],n=1,r="";n<e.length;n++)"<22>"==e.charAt(n)?(t.push(i.decodePacket(e.substr(n+1).substr(0,r))),n+=Number(r)+1,r=""):r+=e.charAt(n);return t}return[i.decodePacket(e)]}}(void 0!==n?n:e.exports,void 0!==n?n:e.parent.exports),function(e,t){function i(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=i,t.util.mixin(i,t.EventEmitter),i.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),""!==e){var i=t.parser.decodePayload(e);if(i&&i.length)for(var n=0,r=i.length;n<r;n++)this.onPacket(i[n])}return this},i.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),"heartbeat"==e.type?this.onHeartbeat():("connect"==e.type&&""==e.endpoint&&this.onConnect(),"error"==e.type&&"reconnect"==e.advice&&(this.isOpened=!1),this.socket.onPacket(e),this)},i.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},i.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},i.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},i.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},i.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},i.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},i.prototype.onHeartbeat=function(e){this.packet({type:"heartbeat"})},i.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},i.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},i.prototype.prepareUrl=function(e){var i=this.socket.options;if(i["skipped handshake data"])return i.rewriteUrlForProxy(i["skipped handshake data"].websocketUrl+(e||""));var n=this.scheme()+"://"+i.host+":"+i.port+"/"+i.resource+"/"+t.protocol+"/"+this.name+"/"+this.sessid+(e||"");return i.rewriteUrlForProxy(n)},i.prototype.ready=function(e,t){t.call(this)},i.prototype.clearEventHandlers=function(){return this}}(void 0!==n?n:e.exports,void 0!==n?n:e.parent.exports),function(e,t,i){function n(e){if(this.options={port:80,secure:!1,document:"document"in i&&document,resource:"socket.io",transports:t.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},t.util.merge(this.options,e),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()||t.util.ua.hasCORS)){var n=this;t.util.on(i,"unload",(function(){n.disconnectSync()}),!1)}this.options["auto connect"]&&this.connect()}function r(){}e.Socket=n,t.util.mixin(n,t.EventEmitter),n.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),""!==e&&this.namespaces[e].packet({type:"connect"})),this.namespaces[e]},n.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},n.prototype.handshake=function(e){var i=this,n=this.options;if(!i.disconnected){var s=n.rewriteUrlForProxy(["http"+(n.secure?"s":"")+":/",n.host+":"+n.port,n.resource,t.protocol,t.util.query(this.options.query,"t="+ +new Date)].join("/"));if(this.isXDomain()&&!t.util.ua.hasCORS){var a=document.getElementsByTagName("script")[0],o=document.createElement("script");o.src=s+"&jsonp="+t.j.length,a.parentNode.insertBefore(o,a),t.j.push((function(e){d(e),o.parentNode.removeChild(o)}))}else{var l=t.util.request();l.open("GET",s,!0);var c=this.options.requestHeaders;void 0!==c&&Object.keys(c).forEach((function(e){l.setRequestHeader(e,c[e])})),l.onreadystatechange=function(){4==l.readyState&&(l.onreadystatechange=r,200==l.status?d(l.responseText):!i.reconnecting&&i.onError(l.responseText))},l.send(null)}}function d(t){t instanceof Error?i.onError(t.message):e.apply(null,t.split(":"))}},n.prototype.getTransport=function(e){for(var i,n=e||this.transports,r=0;i=n[r];r++)if(t.Transport[i]&&t.Transport[i].check(this)&&(!this.isXDomain()||t.Transport[i].xdomainCheck()))return new t.Transport[i](this,this.sessionid);return null},n.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var i=this,n=function(n,r,s,a){function o(){if(!i.connected&&!i.disconnected)if(i.connecting=!1,clearTimeout(i.connectTimeoutTimer),i.options["try multiple transports"]){for(;i.remainingTransports.length>0&&i.remainingTransports.splice(0,1)[0]!=i.transport.name;);i.remainingTransports.length?l(i.remainingTransports):i.publish("connect_failed")}else i.publish("connect_failed")}function l(e){if(i.transport&&(i.transport.clearTimeouts(),i.transport.clearEventHandlers()),i.transport=i.getTransport(e),!i.transport||i.disconnected)return i.publish("connect_failed");i.transport.ready(i,(function(){i.connecting=!0,i.publish("connecting",i.transport.name),i.transport.open(o),i.options["connect timeout"]&&(i.connectTimeoutTimer=setTimeout((function(){o()}),i.options["connect timeout"]))}))}i.sessionid=n,i.closeTimeout=1e3*s+2e3,i.heartbeatTimeout=1e3*r+2e3,i.transports=a?t.util.intersect(a.split(","),i.options.transports):i.options.transports,i.setHeartbeatTimeout(),i.remainingTransports=i.transports.slice(0),l(i.transports),i.once("connect",(function(){clearTimeout(i.connectTimeoutTimer),e&&"function"==typeof e&&e()}))};if(this.options["skipped handshake data"]){var r=this.options["skipped handshake data"];n("v4c-"+(new Date).getTime(),r.timeout,r.timeout,"websocket")}else this.handshake(n);return this},n.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},n.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},n.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},n.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted")),this.disconnected=!0,this},n.prototype.disconnectSync=function(){var e=t.util.request(),i=this.resource+"/"+t.protocol+"/"+this.sessionid;e.open("GET",i,!0),this.onDisconnect("booted")},n.prototype.isXDomain=function(){var e=i.location.port||("https:"==i.location.protocol?443:80);return this.options.host!==i.location.hostname||this.options.port!=e},n.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},n.prototype.onOpen=function(){this.open=!0},n.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},n.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},n.prototype.onError=function(e){e&&e.advice&&"reconnect"===e.advice&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",e&&e.reason?e.reason:e)},n.prototype.onDisconnect=function(e){var t=this.connected,i=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||i)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish("disconnect",e),"booted"!=e&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish("close_during_connecting",e))},n.prototype.reconnect=function(){this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var e=this,t=this.options["max reconnection attempts"],i=this.options["try multiple transports"],n=this.options["reconnection limit"];function r(){if(e.connected){for(var t in e.namespaces)e.namespaces.hasOwnProperty(t)&&""!==t&&e.namespaces[t].packet({type:"connect"});e.publish("reconnect",e.transport.name,e.reconnectionAttempts)}clearTimeout(e.reconnectionTimer),e.removeListener("connect_failed",s),e.removeListener("connect",s),e.reconnecting=!1,delete e.reconnectionAttempts,delete e.reconnectionDelay,delete e.reconnectionTimer,delete e.redoTransports,e.options["try multiple transports"]=i}function s(){if(e.reconnecting)return e.connected?r():e.connecting&&e.reconnecting?e.reconnectionTimer=setTimeout(s,1e3):void(e.reconnectionAttempts++>=t?e.redoTransports?(e.publish("reconnect_failed"),r()):(e.on("connect_failed",s),e.options["try multiple transports"]=!0,e.transport=e.getTransport(),e.redoTransports=!0,e.connect()):(e.reconnectionDelay<n&&(e.reconnectionDelay*=2),e.connect(),e.publish("reconnecting",e.reconnectionDelay,e.reconnectionAttempts),e.reconnectionTimer=setTimeout(s,e.reconnectionDelay)))}this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(s,this.reconnectionDelay),this.on("connect",s)}}(void 0!==n?n:e.exports,void 0!==n?n:e.parent.exports,void 0===i.g?window:i.g),function(e,t){function i(e,t){this.socket=e,this.name=t||"",this.flags={},this.json=new n(this,"json"),this.ackPackets=0,this.acks={}}function n(e,t){this.namespace=e,this.name=t}e.SocketNamespace=i,t.util.mixin(i,t.EventEmitter),i.prototype.$emit=t.EventEmitter.prototype.emit,i.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},i.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},i.prototype.send=function(e,t){var i={type:this.flags.json?"json":"message",data:e};return"function"==typeof t&&(i.id=++this.ackPackets,i.ack=!0,this.acks[i.id]=t),this.packet(i)},i.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),i=t[t.length-1],n={type:"event",name:e};return"function"==typeof i&&(n.id=++this.ackPackets,n.ack="data",this.acks[n.id]=i,t=t.slice(0,t.length-1)),n.args=t,this.packet(n)},i.prototype.disconnect=function(){return""===this.name?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},i.prototype.onPacket=function(e){var i=this;function n(){i.packet({type:"ack",args:t.util.toArray(arguments),ackId:e.id})}switch(e.type){case"connect":this.$emit("connect");break;case"disconnect":""===this.name?this.socket.onDisconnect(e.reason||"booted"):this.$emit("disconnect",e.reason||"");break;case"message":case"json":var r=["message",e.data];"data"==e.ack?r.push(n):e.ack&&this.packet({type:"ack",ackId:e.id}),this.$emit.apply(this,r);break;case"event":r=[e.name].concat(e.args),"data"==e.ack&&r.push(n),this.$emit.apply(this,r);break;case"ack":this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case"error":e.advice?this.socket.onError(e):"unauthorized"==e.reason?this.$emit("connect_failed",e.reason):this.$emit("error",e.reason)}},n.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},n.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(void 0!==n?n:e.exports,void 0!==n?n:e.parent.exports),function(e,t,i){function n(e){t.Transport.apply(this,arguments)}function r(){}e.websocket=n,t.util.inherit(n,t.Transport),n.prototype.name="websocket",n.prototype.open=function(e){var n,r=t.util.query(this.socket.options.query),s=this;return this.connectErrorCallback=e,n||(n=i.MozWebSocket||i.WebSocket),this.websocket=new n(this.prepareUrl(r)),this.websocket.onopen=function(){s.onOpen(),s.socket.setBuffer(!1)},this.websocket.onmessage=function(e){s.onData(e.data)},this.websocket.onclose=function(){s.onClose(),s.socket.setBuffer(!0)},this.websocket.onerror=function(e){s.onError(e)},this},n.prototype.send=function(e){return this.websocket.send(e),this},n.prototype.payload=function(e){for(var t=0,i=e.length;t<i;t++)this.packet(e[t]);return this},n.prototype.close=function(){return this.websocket.close(),this},n.prototype.onError=function(e){void 0!==this.connectErrorCallback&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},n.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},n.check=function(){return"WebSocket"in i&&!("__addTask"in WebSocket)||"MozWebSocket"in i},n.xdomainCheck=function(){return!0},n.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=r),this},t.transports.push("websocket")}(void 0!==n?n.Transport:e.exports,void 0!==n?n:e.parent.exports,void 0===i.g?window:i.g),function(e,t,i){function n(e){e&&t.Transport.apply(this,arguments)}function r(){}e.XHR=n,t.util.inherit(n,t.Transport),n.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},n.prototype.payload=function(e){for(var i=[],n=0,r=e.length;n<r;n++)i.push(t.parser.encodePacket(e[n]));this.send(t.parser.encodePayload(i))},n.prototype.send=function(e){return this.post(e),this},n.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),i.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=r,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=r,200==this.status?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},n.prototype.close=function(){return this.onClose(),this},n.prototype.request=function(e){var i=t.util.request(this.socket.isXDomain()),n=t.util.query(this.socket.options.query,"t="+ +new Date);i.open(e||"GET",this.prepareUrl(n),!0);var r=this.socket.options.requestHeaders;if(void 0!==r&&Object.keys(r).forEach((function(e){i.setRequestHeader(e,r[e])})),"POST"==e)try{i.setRequestHeader?i.setRequestHeader("Content-type","text/plain;charset=UTF-8"):i.contentType="text/plain"}catch(e){}return i},n.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},n.check=function(e,n){try{var r=t.util.request(n),s=i.XDomainRequest&&r instanceof XDomainRequest,a=(e&&e.options&&e.options.secure?"https:":"http:")!=i.location.protocol;if(r&&(!s||!a))return!0}catch(e){}return!1},n.xdomainCheck=function(){return n.check(null,!0)},n.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=r),this}}(void 0!==n?n.Transport:e.exports,void 0!==n?n:e.parent.exports,void 0===i.g?window:i.g),function(e,t,i){function n(){t.Transport.XHR.apply(this,arguments)}function r(){}e["xhr-polling"]=n,t.util.inherit(n,t.Transport.XHR),t.util.merge(n,t.Transport.XHR),n.prototype.name="xhr-polling",n.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},n.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),i.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=r,this.onerror=r,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),void 0!==e.connectErrorCallback&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=r,200==this.status?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),void 0!==e.connectErrorCallback&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},n.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r;try{this.xhr.abort()}catch(e){}this.xhr=null}},n.prototype.ready=function(e,i){var n=this;t.util.defer((function(){i.call(n)}))},n.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r),this},t.transports.push("xhr-polling")}(void 0!==n?n.Transport:e.exports,void 0!==n?n:e.parent.exports,void 0===i.g?window:i.g),t.io=n},659:function(e,t){var i=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=t.fetchWithTimeout=t.calculateExpireTsInSec=t.calculateTtlInSec=t.toJson=void 0,t.toJson=function(e){try{return JSON.stringify(e)}catch(t){return"Unable to serialize object of type ".concat(typeof e)}},t.calculateTtlInSec=function(e){var t=Math.round((new Date).getTime()/1e3);return void 0!==e&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round((new Date).getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return i(this,void 0,void 0,(function(){var i,r,s;return n(this,(function(n){return r=new Promise((function(t,n){fetch(e).then((function(e){clearTimeout(i),t(e)})).catch((function(e){clearTimeout(i),n(e)}))})),0!==t?(s=new Promise((function(n,r){var s=new URL(e.url),a=new Error("".concat(e.method," ").concat(s.origin).concat(s.pathname," timed out"));i=setTimeout(r,t,a)})),[2,Promise.race([r,s])]):[2,r]}))}))};var r=function(){function e(e){this.base=void 0!==e?e:this.createCorrelationVectorBase(),this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return"".concat(this.base,".").concat(this.extension)},e.prototype.createCorrelationVectorBase=function(){for(var e="",t=0;t<21;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+".charAt(Math.floor(64*Math.random()));return e+"AQgw".charAt(Math.floor(4*Math.random()))},e}();t.CorrelationVector=r;var s=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}();t.Timespan=s},396:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var n,r=i(659),s=i(509),a=i(642);t.ResponseData=function(e){this.id=e,this.status=200,this.headers={},this.body=""},function(e){e.Connected="trouter_js_client_connected",e.Disconnected="trouter_js_client_disconnected",e.Error="trouter_js_client_error",e.Progress="trouter_js_client_progress",e.Response="trouter_js_client_response",e.Request="trouter_js_client_request",e.CheckConnection="trouter_js_client_check_connection",e.Registration="trouter_js_client_registration",e.Unregistration="trouter_js_client_unregistration"}(n||(t.ClientEventName=n={}));var o=function(e,t,i,n,r){this.stepName=e,this.operation=t,this.delta=i,this.ts=n,this.error=r};t.TrackerStep=o,t.Properties=function(){};var l=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0},c=function(){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},d=function(){function e(e,t,i,n,s,o,d){this.clientId=t,this.clientInfo=i,this.getServerState=n,this.endpointId=s,this.clientCorrelationID=o,this.environment=d,this.logger=new a.Logger("ConnectionTracker",e),this.clientCorrelationID=void 0!==o?o:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new r.Timespan,this.eventLogSettings=new c,this.connectedInfo=new l}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(n.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){void 0!==this.progressTimeout&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),void 0!==this.eventLogSettings.sendProgressTimeoutSecs&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:"timeout",timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=""},e.prototype.copyProperties=function(e,t){for(var i=0,n=Object.keys(t);i<n.length;i++){var r=n[i];void 0!==t[r]&&(e[r.replace(/-/g,"_")]={value:t[r]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,i){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&void 0!==this.eventLogger){var n=this.getServerState(),a={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,r.toJson)(i)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:s.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:n.connectionId},connectedClientId:{value:n.connectedClientId},domId:{value:n.domId},url:{value:n.url},ttlInSecs:{value:n.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(a.properties,t),this.eventLogger.logEvent(a)}}catch(t){this.logger.warn("error in sending event ".concat(e,": ").concat((0,r.toJson)(t)))}},e.prototype.createStep=function(e,t,i){return new o(e,t,this.beginTimestamp.duration,Date.now(),i)},e.prototype.addStep=function(e,t,i){if(!1!==this.eventLogSettings.enabled&&(0===this.steps.length&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,i)),++this.totalStepCount,void 0!==this.eventLogSettings.numberOfStepsToMaintain&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var r=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(n.Progress,{reason:"flush"},r)}},e.prototype.trackStart=function(e){this.addStep(e,"start")},e.prototype.trackEnd=function(e){this.addStep(e,"end")},e.prototype.trackError=function(e,t,i,r){void 0===i&&(i=!0),"health"===e&&!0!==this.eventLogSettings.logHealthCheckError||"ping"===e&&!1===this.eventLogSettings.logSendPingError||(void 0===r&&(r="error"),!0===i&&this.addStep(e,r,t),this.sendTelemetry(n.Error,{},[this.createStep(e,r,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var i=this.steps.slice(0),r=this.totalStepCount,s=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(n.Connected,{stepCount:i.length,totalStepCount:r,connectionEstablishmentMs_Total:s},i),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(n.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackRequest=function(e,t){var i={};void 0!==t&&(i.hasError=!0,i.error=t);try{if(e){i.requestID=e.id,i.httpMethod=e.method,i.url=e.url,i.bodyLength=e.body.length,i.shortUrl=e.shortUrl,i.requestTimeStamp=e.startTS,i.correlationVector=e.correlationVector;for(var s=e.headers,a=0,o=Object.keys(s);a<o.length;a++){var l=o[a];i[l]=s[l]}}}catch(e){i.hasError=!0,i.error="".concat(i.error," error creating request context ").concat((0,r.toJson)(e))}this.sendTelemetry(n.Request,i,[])},e.prototype.trackResponse=function(e,t,i,s){var a={};void 0!==s&&(a.hasError=!0,a.error=s);try{if(a.responseTimestamp=void 0!==i?i.sentTS:Date.now(),e){a.requestID=e.id,a.httpMethod=e.method,a.shortUrl=e.shortUrl,a.correlationVector=e.correlationVector;for(var o=e.headers,l=0,c=Object.keys(o);l<c.length;l++){var d=c[l];a[d]=o[d]}}i&&(a.latencyMS=t,a.responseCode=i.status,a.responseLength=i.body.length)}catch(e){a.hasError=!0,a.error="".concat(a.error," error creating response context ").concat((0,r.toJson)(e))}this.sendTelemetry(n.Response,a,[])},e.prototype.sendResponseError=function(e,t,i){this.trackResponse(t,void 0,i,e)},e.prototype.close=function(){this.sendProgress({reason:"closed"}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,void 0!==e.numberOfStepsToMaintain?e.numberOfStepsToMaintain:0));var t=Math.min(3600,Math.max(55,void 0!==e.sendProgressTimeoutSecs?e.sendProgressTimeoutSecs:0));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var i=0,r=Object.keys(n).map((function(e){return n[e]}));i<r.length;i++){var s=r[i];void 0!==e[s]&&(this.eventLogSettings[s]=e[s])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}();t.ConnectionTracker=d},509:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.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"},t.CLIENT_VERSION="2025.07.01.5",t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=["skype","aad","cae"],t.USER_AUTHENTICATE_EVENT_NAME="user.authenticate"},764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0;var i=function(){function e(e,t,i){this.reason=e,this.claims=t,this.details=i}return e.fromRawReason=function(t,i){if(""===t||"dup"===t)return new e(t);try{var n=JSON.parse(t);return"object"!=typeof n||void 0===n.reason?(null==i||i.error("invalid disconnect reason format"),new e("unknown",void 0,t)):new e(n.reason,n.claims,n.details)}catch(i){return new e("disconnect",void 0,t)}},e.fromSocketIoEventData=function(t,i){return"string"==typeof i?new e(t,void 0,i):void 0},e.prototype.toTelemetryString=function(){return"socketerror"===this.reason||"reconnecterror"===this.reason||"disconnect"===this.reason?this.details:this.reason},e}();t.DisconnectReason=i},107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0;var i=function(){function e(e,t,i){void 0===i&&(i={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=i,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var i=1+.4*(Math.random()-.5),n=1e3*Math.pow(2,e)*i;return n=Math.round(n),Math.min(t,n)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,i){var n=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 r=Date.now()-this.previousCompleteTime;r>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&r>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info("Back off for ".concat(t," with ID ").concat(this.backoffId," will be reset due to a lot of time having passed since the previous backoff (").concat(r," ms)")),this.backoffCount=0,this.previousCompleteTime=void 0)}var s=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off ".concat(t," for ").concat(s," milliseconds with ID ").concat(this.backoffId)),this.callback=function(e,r){(function(e,t,i){if(void 0===e||void 0===t)return!1;var n=Date.now()-e;return n>t*i.tolerance&&n>i.minimumWaitMs})(e,r,n.gapDetectionSettings)&&(n.logger.info("Back off for ".concat(t," with ID ").concat(n.backoffId," will be reset due to the wait (").concat(Date.now()-(null!=e?e:0)," ms) being longer than expected (").concat(r," ms)")),n.backoffCount=0),n.logger.info("Back off for ".concat(t," with ID ").concat(n.backoffId," complete, invoking handler")),n.timerHandle=void 0,n.callback=void 0,n.previousCompleteTime=Date.now(),i()};var a=Date.now();this.timerHandle=setTimeout((function(){var e;return null===(e=n.callback)||void 0===e?void 0:e.call(n,a,s)}),s)},e.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},e.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 e=this.callback;this.callback=void 0,e&&e()}},e}();t.ExponentialBackoff=i},234:(e,t)=>{var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]="Unknown",e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"}(i||(t.UserActivityState=i={})),function(e){e[e.Unknown=0]="Unknown",e[e.Connected=2]="Connected",e[e.Disconnected=3]="Disconnected",e[e.Switching=9]="Switching"}(n||(t.TrouterState=n={}))},423:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var n,r,s=i(659),a=function(){function e(e,t,i,n,r,s){this.connectionId=e,this.connectedClientId=t,this.domId=i,this.url=n,this.c2cUrlBase=r,this.expirationTsSec=s}return e.prototype.getRemainingTtlInSec=function(){return(0,s.calculateTtlInSec)(this.expirationTsSec)},e}();t.ServerState=a,function(e){e[e.Unknown=0]="Unknown",e[e.Modified=1]="Modified",e[e.Snapshot=2]="Snapshot",e[e.Connected=3]="Connected"}(n||(t.UserActivityEventReason=n={})),function(e){e[e.Unknown=0]="Unknown",e[e.Connected=2]="Connected",e[e.Disconnected=3]="Disconnected",e[e.Switching=9]="Switching",e[e.TerminalError=10]="TerminalError"}(r||(t.TrouterManagerState=r={}))},642:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var i=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug("[".concat(this.name,"] ").concat(e))},e.prototype.info=function(e){this.logger.info("[".concat(this.name,"] ").concat(e))},e.prototype.warn=function(e){this.logger.warn("[".concat(this.name,"] ").concat(e))},e.prototype.error=function(e){this.logger.error("[".concat(this.name,"] ").concat(e))},e}();t.Logger=i},619:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var n=i(509),r=i(642),s=function(){function e(e){this.messageHandlers=[],this.logger=new r.Logger("MessageHandlers",e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw new Error("Registering the same handler twice is not allowed");this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug("Clearing message handlers"),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:n.UNHANDLED_MESSAGE_ACK,isHandled:!1},i=0,r=this.messageHandlers;i<r.length;i++){var s=r[i],a=this.safeExecuteHandle(s,e);if(void 0!==a&&(void 0===a.isHandled||a.isHandled))return void 0===a.resultCode&&(a.resultCode=n.HANDLED_MESSAGE_ACK),a}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){return void this.logger.warn("Trouter message handler threw an exception: ".concat(e))}},e}();t.MessageHandlerRegistry=s},902:function(e,t){var i=this&&this.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectUrlIfPresent=t.ensureNumber=t.reconnectParamsWithoutUrls=t.adaptUrl=t.isV4ConnectEvent=t.usedProtocolAfterFallback=t.usedProtocol=void 0,t.usedProtocol=function(e,t){return"skype"===e&&"1"!==("string"==typeof(i=null==t?void 0:t.scae)?i:"number"==typeof i?i.toString():void 0)?"v4a":"v4c";var i},t.usedProtocolAfterFallback=function(e,t){return"v4c-websocket-failure"===(null==t?void 0:t.kind)?"v4a":e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,"connectparams")},t.adaptUrl=function(e,t){return"v4a"===t?e.replace(/\/v4\/c\b/,"/v4/a").replace("wss://","https://").replace("ws://","http://"):e.replace(/\/v4\/a\b/,"/v4/c").replace("https://","wss://").replace("http://","ws://")},t.reconnectParamsWithoutUrls=function(e){if(void 0!==e)return i(i({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return"string"==typeof e?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if("redirect"===(null==e?void 0:e.kind)&&void 0!==e.host){var t=e.host;return t.endsWith("/")&&(t=t.substring(0,t.length-1)),t.endsWith("/v4/c")||t.endsWith("/v4/a")||(t+="/v4/c"),t}}},235:function(e,t,i){var n=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var r=i(335),s=function(){function e(e,t,i){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=i,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,i){this.passIfRegisteredOrNotNeeded("onDownstreamRequest",e,t,i)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded("onConnected",e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){var t=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(e),t&&e.getState()===r.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,i){this.wrapped.onReconnectIsRequired(e,t,i)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded("onTrouterMessageLost",e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded("onUserActivityStateAccepted",e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded("onAudiencesSetResolved",e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,i=[],r=1;r<arguments.length;r++)i[r-1]=arguments[r];var s=this.shouldConnectionDependOnRegistration(),a=this.shouldHoldBackEvents();s&&a||this.fireHeldBackEvents(s?function(e){return"onConnected"!==e.kind}:void 0),this.isRegistered||!s||!1===a&&"onConnected"!==e?(t=this.wrapped)[e].apply(t,i):this.holdBackEvent.apply(this,n([e],i,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,i=0,n=this.heldBackEvents;i<n.length;i++){var r=n[i];(void 0===e||e(r))&&(t=this.wrapped)[r.kind].apply(t,r.args)}this.heldBackEvents=void 0===e?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}();t.RegistrationEnforcer=s;var a=function(){function e(e,t,i,n){this.wrapped=e,this.prefix=t,this.logger=i,this.onEventAction=n}return e.prototype.onEvent=function(e,t){var i;void 0!==this.onEventAction?this.onEventAction(e,t):(null!==(i=this.logger)&&void 0!==i?i:console).log("".concat(this.prefix," TracingEnforcer: ").concat(e,"(").concat(t,")"))},e.prototype.onDownstreamRequest=function(e,t,i){this.onEvent("onDownstreamRequest",JSON.stringify({request:t,response:i})),this.wrapped.onDownstreamRequest(e,t,i)},e.prototype.onConnected=function(e){this.onEvent("onConnected",e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent("onRegistered",e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent("onUnregistered",e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent("onReconnecting",e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,i){this.onEvent("onReconnectIsRequired",JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:i})),this.wrapped.onReconnectIsRequired(e,t,i)},e.prototype.onDisconnected=function(e){this.onEvent("onDisconnected",e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent("onTerminalError",JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent("onConnectionParametersUpdated",JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent("onTrouterMessageLost",JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent("onUserActivityStateAccepted",JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent("onAudiencesSetResolved",JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}();t.LoggingManagerConsumer=a},220:function(e,t){var i=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},n=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=void 0,t.addCacheAsBackupTo=function(e){var t,r=this;return function(s){return i(r,void 0,void 0,(function(){return n(this,(function(i){return s&&(t=void 0),[2,new Promise((function(i,n){e(s).then((function(e){t=e,i(e)})).catch((function(e){void 0!==t&&t.length>0&&i(t),n(e)}))}))]}))}))}}},573:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var a,o=i(673),l=i(659),c=i(396),d=i(509),u=i(764),h=i(107),g=i(234),p=i(423),m=i(642),f=i(902),v=i(335),S=i(983),y=function(){this.cv=d.CLIENT_VERSION,this.ua="",this.hr="",this.v=""},C=function(){function e(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),T="MS-CV",E=function(){function e(e,t){this.logger=t,this.cvCounter=0;var i=JSON.parse(e);this.startTS=this.safeJsonNumber(i,"startTS",0),this.url=this.safeJsonString(i,"url",""),this.shortUrl=this.safeJsonString(i,"shortUrl",""),this.body=this.safeJsonString(i,"body",""),this.headers=this.safeJsonRecord(i,"headers",{}),this.id=this.safeJsonNumber(i,"id",-1),this.method=this.safeJsonString(i,"method",""),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[T],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?"".concat(this.receivedCv,".").concat(this.cvCounter):""},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){"data"===e?this.dataCallback=t:"end"===e&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[T]=e)},e.prototype.safeJsonNumber=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("number"==typeof r[t])return r[t];if("string"==typeof r[t])return parseFloat(r[t]);null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e.prototype.safeJsonString=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("string"==typeof r[t])return r[t];null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e.prototype.safeJsonRecord=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("object"==typeof r[t])return r[t];null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e}(),b=function(){function e(e,t,i){this.request=e,this.responseData=t,this.sendResponse=i}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),_=function(e){this.name=e,this.args={},this.timeoutTimerId=0};!function(e){e[e.Configuration=0]="Configuration",e[e.ServerInitiated=1]="ServerInitiated"}(a||(t.ReconnectReason=a={}));var I=function(){function e(e,t,i,n,r,s,a,l){var u,g=this;this.options=t,this.manager=i,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.protocolSelector=a,this.audienceSubscriptionState=l,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 m.Logger("Connection",e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new h.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname);var p=new y;p.cv=d.CLIENT_VERSION,p.ua="",(null===(u=this.options)||void 0===u?void 0:u.clientInfo)&&(p.ua=this.safeString(this.options.clientInfo.ua),p.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=p,this.connectionTracker=new c.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return g.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var f=this.options.incallModeTimeoutMs>0;if(this.fsm=new v.TrouterFsm(e,this,f,this.protocolSelector),t.registration){var S={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,o.createRegistrarClient)(e,this.tokenProvider,S)}this.userActivityState=s}return e.prototype.start=function(e){this.logger.info("Starting"),this.reconnectParams=e,"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()},e.prototype.stop=function(e){this.logger.info("Stopping"),"undefined"!=typeof window&&window.navigator&&(window.removeEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener("offline",this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info("Configuration changed. Reconnection required."),this.fsm.onReconnectRequired(!1,a.Configuration))},e.prototype.checkConnection=function(e){this.logger.info("checkConnection called with ".concat(e)),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(c.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new p.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,i,n,r){var s=this;void 0===r&&(r=0),this.logger.info("Getting token ".concat(t?"with backoff":"without backoff"));var a=function(){s.connectionTracker.trackStart("token");var t={needFresh:!e,wwwAuthenticateHeader:i,supportedTokenTypes:d.SUPPORTED_TOKEN_TYPES,purpose:"trouter"};s.logger.info("Requesting token: needFresh=".concat(t.needFresh," ")+"types=[".concat(d.SUPPORTED_TOKEN_TYPES,"], ")+"wwwAuthenticateHeader is ".concat(t.wwwAuthenticateHeader?"non empty":"empty")),s.tokenProvider(t).then((function(e){s.logger.debug("".concat(e.tokenType," token is received")),s.connectionTracker.trackEnd("token"),s.fsm.onTokenReceived(e,n,s.reconnectParams)})).catch((function(t){var a=(0,l.toJson)(t.stack);if(s.logger.error("Getting token failed, will retry after timeout. Error: ".concat(a)),s.connectionTracker.trackError("token",a),!s.canRetryTokenFetchRequest(r+s.unauthorizedErrorCount))return s.connectionTracker.trackError("token","getToken retry limit hit, reached terminal error state"),s.resetTokenBackoff(),void s.fsm.onTerminalError();s.getToken(e,!0,i,n,r+1)}))};t?this.tokenBackoff.backoff("getting token",a):(this.resetTokenBackoff(),a())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for ".concat(this.timeoutOptions.connectionTimeoutMs," ms")),this.connectionTimeoutId=setTimeout((function(){e.logger.info("Connection timeout is fired"),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0)},e.prototype.startPingTimer=function(){var e=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for ".concat(this.timeoutOptions.pingTimeoutMs," ms")),this.pingTimerId=setInterval((function(){e.logger.info("Ping interval fired"),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport ".concat(this.transportTypeName))},e.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0)},e.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},e.prototype.hasCustomRegistrationTtl=function(){var e,t;return void 0!==(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)&&0!==(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),i=t[0],n=t[1];if(i<=30||!n)return this.logger.debug("Starting registration expiration timer (TTL ".concat(i," sec)")),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn("Registration expired but the connection is still alive. Should never happen"),e.dispatchUnregistered()}),1e3*i));var r=i-30;this.logger.debug("Starting registration extension timer for ".concat(r," sec")),this.registrationTimerId=setTimeout((function(){e.logger.info("Registration extension timer fired"),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug("Registration extension did not happen in time"),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*r)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");for(var i={},n=this.allocateResult.connectparams,r=0,s=Object.keys(n);r<s.length;r++){var a=s[r];if(void 0!==n[a]){var o=n[a];"string"==typeof o||"number"==typeof o?i[a]=o:this.logger.error("signatureData[".concat(a,"] has unsupported type ").concat(typeof o))}}return i.v="v4",i.tc=encodeURI((0,l.toJson)(this.clientInfo)),i.timeout=this.timeoutOptions.pingTimeoutMs/1e3,i.auth="true",this.options.endpointId&&(i.epid=this.options.endpointId),e&&(i.userActivity=encodeURIComponent((0,l.toJson)(e))),t&&(i.audienceSubscriptionState=encodeURIComponent((0,l.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(i),!0)},e.prototype.startSocketIo=function(e){var t,i;if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var r=this.options.ioOptions?n({},this.options.ioOptions):new C,s=this.userActivityState.state!==g.UserActivityState.Unknown?this.userActivityState.increaseCvAndGetEventObject():void 0,a=null===(t=this.audienceSubscriptionState)||void 0===t?void 0:t.increaseCvAndGetEventObject();if(r["force new connection"]=!0,r.reconnect=!1,r.rewriteUrlForProxy=this.options.rewriteUrlForProxy,r.requestHeaders=n(n({},this.options.extraConnectionHeaders),w(e,this.usingLegacyTokenApi)),r.query=this.buildSocketIoUrlParams(s,a),this.logger.info("connecting to ".concat(this.allocateResult.socketio)),this.stopSocketIo(),this.socket=(null!==(i=this.options.io)&&void 0!==i?i:S).connect(this.allocateResult.socketio,r),void 0===this.socket)throw new Error("Can't create Socket.io object");this.attachSocketIoHandlers(this.socket,e,s,a)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug("clearing socket.io");try{for(var e=0,t=["connecting","connect","connect_failed","close_during_connecting","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];e<t.length;e++){var i=t[e];this.socket.removeAllListeners(i)}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0}catch(e){this.logger.error("exception in disconnecting previous socket. Error: ".concat(A(e)))}}},e.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info("dispatching registered"),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info("dispatching unregistered"),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug("dispatching downstream request");try{var i=new b(e,new c.ResponseData(e.id),(function(e,i){return t.logger.debug("sending response to downstream"),t.sendResponse(e,i)}));this.manager.onDownstreamRequest(this,e,i)}catch(e){this.logger.error("exception in socket.on message. Error : ".concat(A(e)))}},e.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info("dispatching reconnect is required by server"),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info("dispatching disconnected"),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info("dispatching terminal error"),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info("dispatching trouter message lost"),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn("counting disconnect before connection was fully established as a connection failure"),this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug("emitting processed flow tags to the server");var i=new _("trouter.processed_message_loss");i.args={droppedIndicators:e},this.sendDownstreamEvent(i,(function(){t.logger.info("emitted processed flow tags to the server")}))}catch(e){var n=A(e);this.logger.error("unable to send processed message loss event. Error: ".concat(n)),this.connectionTracker.trackError("trouter.processed_message_loss",n,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var i,r=this.options.trouterUrl,s=this.reconnectParams,a="string"==typeof(null==s?void 0:s.se)?parseInt(s.se,10):"number"==typeof(null==s?void 0:s.se)?s.se:void 0;a&&a<=Date.now()+36e5&&(this.logger.warn("Dropping expired cached connection parameters: ".concat(new Date(a))),this.reconnectParams=s=void 0),s&&s.serviceUrl!==r&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(s.serviceUrl,", now ").concat(r,")")),this.reconnectParams=s=void 0),(null==s?void 0:s.reconnectUrl)&&(r=s.reconnectUrl),i=s?n(n({},s),{serviceUrl:void 0,reconnectUrl:void 0}):null,r=(0,f.adaptUrl)(r,"v4a"),r=this.appendCorrelationIds(r,!1);var o=r=this.appendEndpointId(r,!1);i&&(r+="&".concat(this.buildQuery(i)),i.v||(r+="&v=".concat("v4"))),r=this.options.rewriteUrlForProxy(r);var c=new Request(r,{method:"POST",mode:"cors",headers:new Headers(n(n({"Content-Type":"text/plain"},this.options.extraConnectionHeaders),w(e,this.usingLegacyTokenApi)))});this.logger.info("sendAllocateRequest: POST ".concat(this.options.rewriteUrlForProxy(o)," (connectparams redacted)}")),this.connectionTracker.trackStart("allocation");var d,u=Date.now(),h=-1,g=!1;(0,l.fetchWithTimeout)(c,this.timeoutOptions.fetchTimeoutMs).then((function(e){var i;if(h=e.status,!e.ok)throw d=null!==(i=e.headers.get("www-authenticate"))&&void 0!==i?i:void 0,g="1"===e.headers.get("x-trouter-skypetoken-deprecated"),t.logger.warn("Allocation request got response status ".concat(e.status,", www-authenticate header was ").concat(d?"not empty":"empty")),new Error(e.statusText);var n=e.headers.get("content-type");if(!n||"application/json"!==n&&!n.startsWith("application/json;"))throw new Error("Content-type '".concat(n,"' is unexpected"));return t.connectionTracker.trackEnd("allocation"),e.json()})).then((function(i){t.unauthorizedErrorCount=0,t.onAllocationResponse(i,e)})).catch((function(e){t.connectingErrorsInRow++;var i="".concat(e).concat(h>=0?", status code ".concat(h):"");if(t.logger.error("".concat(t.connectingErrorsInRow," failed connecting attempt(s) in a row. ").concat(i)),t.connectionTracker.trackError("allocation",i),g){var n="Skypetoken deprecated response, not retrying any further";return t.logger.error(n),t.connectionTracker.trackError("allocation",n),void t.fsm.onTerminalError()}if(401===h&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return n="getToken retry limit hit, reached terminal error state",t.connectionTracker.trackError("allocation",n),void t.fsm.onTerminalError();if(-1!==h||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold)if(h>=400&&h<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn("".concat(t.connectingErrorsInRow," connection attempts, testing nominal service URL"));var r=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-u)-500,t.timeoutOptions.fetchTimeoutMs);return void t.testNominalUrlConnectivity(r).then((function(e){t.connectionTracker.trackProgress("nomcheck",e?"ok":"failed"),e?(t.logger.warn("Nominal service URL is reachable, erasing cached reconnect URL"),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn("Nominal service URL is not reachable either, keeping cached reconnect URL"),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}))}}else t.logger.info("Expected failure, the browser says it is not online at the moment");t.fsm.onAllocationFailed(401===h,d)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,i=this;if(e<1e3)return this.logger.warn("There is no time left to reasonably perform the nominal service URL connectivity check (".concat(e," ms), falling back to assuming that the connectivity is fine")),Promise.resolve(!0);try{var n=new URL(this.options.trouterUrl);n.pathname=n.pathname.replace(/\/v4\/.*/,"/"),n.search="?"+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:""),tc:encodeURIComponent((0,l.toJson)(this.clientInfo))}),t=new Request(this.options.rewriteUrlForProxy(n.toString()),{method:"GET",headers:{Accept:"text/plain"}})}catch(e){return this.logger.warn("Nominal service URL connectivity test request could not be created (".concat(e,"), falling back to assuming that the connectivity is fine")),Promise.resolve(!0)}return(0,l.fetchWithTimeout)(t,e).then((function(e){if(200!==e.status)throw new Error("Not 200 OK: ".concat(e.status," ").concat(e.statusText));return e.text()})).then((function(e){if("Trouter"!==e)throw new Error('Not "Trouter": '.concat(e.substring(0,16)).concat(e.length>16?"...":""));return!0})).catch((function(e){return i.logger.error("Nominal service URL connectivity test failed: ".concat(e)),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&void 0===this.pingResponseTimerId)try{this.logger.debug("emitting ping event");var t=!1;this.socket.emit("ping",(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error("Ping response timeout is fired"),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var i=A(e);this.logger.error("unable to send ping. Error: ".concat(i)),this.connectionTracker.trackError("ping",i,!1)}},e.prototype.connectV4c=function(e,t){var i,a,o,l,c,d;return r(this,void 0,void 0,(function(){var r,u,h,g;return s(this,(function(s){switch(s.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===s.sent())return[2];(r=this.options.ioOptions?n({},this.options.ioOptions):new C)["force new connection"]=!0,r.reconnect=!1,(null===(i=this.reconnectParams)||void 0===i?void 0:i.serviceUrl)&&(0,f.adaptUrl)(this.reconnectParams.serviceUrl,"v4c")!==(0,f.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),u=null!==(l=null!==(a=(0,f.redirectUrlIfPresent)(t))&&void 0!==a?a:"redirect-no-host"!==(null==t?void 0:t.kind)?null===(o=this.reconnectParams)||void 0===o?void 0:o.reconnectUrl:void 0)&&void 0!==l?l:this.options.trouterUrl,h=(0,f.adaptUrl)(u,"v4c"),r["skipped handshake data"]={timeout:70,websocketUrl:h},r.query=this.buildV4cUrlParams(),r.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName="websocket",this.socket=(null!==(c=this.options.io)&&void 0!==c?c:S).connect(this.options.trouterUrl,r),void 0===this.socket)throw new Error("failed to create Socket.io object");g=null===(d=this.audienceSubscriptionState)||void 0===d?void 0:d.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,e,void 0,g)}catch(e){this.logger.error("".concat(e)),this.connectionTracker.trackError("v4c","".concat(e)),this.fsm.onV4cException()}return[2]}}))}))},e.prototype.performV4cInitialConnectivityCheck=function(){return r(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.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 e.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])}}))}))},e.prototype.sendV4cAuthenticationEvent=function(e){var t,i={headers:n(n({},this.options.extraConnectionHeaders),w(e,this.usingLegacyTokenApi)),connectparams:(0,f.reconnectParamsWithoutUrls)(this.reconnectParams)};null===(t=this.socket)||void 0===t||t.emit(d.USER_AUTHENTICATE_EVENT_NAME,i)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info("Changing user activity state to '".concat(e.toEventJSON(),"'")),this.fsm.onSetNewUserActivityState()):(this.logger.debug("Not changing the same user activity state '".concat(e.toEventJSON(),"'")),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){if(this.userActivityState.state!==g.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var i=this.userActivityState.toEventObject(),n=this.socket.socket.options.query;if(n){var r="userActivity=".concat(encodeURIComponent((0,l.toJson)(i)));-1==n.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)?this.socket.socket.options.query=n.concat("&",r):this.socket.socket.options.query=n.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,r)}}"websocket"===this.transportTypeName&&t?e===p.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):"xhr-polling"===this.transportTypeName&&e===p.UserActivityEventReason.Modified&&this.fsm.forceReconnect("user activity/force reconnect")}},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var i=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var n=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,i);return this.fsm.forceReconnect("set audience subscription force reconnect"),n}throw new Error("set audience subscription executed on an unknown transport")},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return r(this,void 0,void 0,(function(){var i,n,r=this;return s(this,(function(s){switch(s.label){case 0:return this.logger.info("[WebSocket] Audience subscription set requested."),(i=new _("audience.subscribe")).args=e,[4,new Promise((function(n){var s=!1,a=setTimeout((function(){return s=!0,n(r.buildAudienceSubscriptionsTimeoutResponse(e))}),t);r.sendDownstreamEvent(i,(function(e,t){s||(clearTimeout(a),r.logger.debug("[Websocket] Audience subscription response: ".concat(t)),r.pendingAudienceSubscription&&r.onAudienceSubscriptionResult(t),n(t))}))}))];case 1:return n=s.sent(),this.manager.onAudiencesSetResolved(n,e.cv),[2,n]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,i){var n;return r(this,void 0,void 0,(function(){var r,a,o,l,c,d,u=this;return s(this,(function(s){switch(s.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===e.audiences.length?[2,this.handleAudienceUnsubscribeLongpoll(e.cv,i)]:[4,new Promise((function(i){var n=setTimeout((function(){return u.pendingAudienceSubscription=void 0,i(u.buildAudienceSubscriptionsTimeoutResponse(e))}),t);u.pendingAudienceSubscription={audienceSetResolve:i,timeoutId:n}}))];case 1:return r=s.sent(),this.manager.getState()===g.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?[2,r]:(null==(a=r.responses[0])?void 0:a.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST||(null==(o=r.responses.find((function(t){return t.audienceId===e.audiences[0].id})))?void 0:o.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]):(l=(null===(n=null==i?void 0:i.audienceSubscriptionModel.audienceSubscriptions[0])||void 0===n?void 0:n.id)!==(null==a?void 0:a.audienceId),i&&l&&(c=this.mapToSyntheticAudienceSubscriptionResponses(i.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200),(d=r.responses).push.apply(d,c)),this.manager.onAudiencesSetResolved(r,e.cv),[2,r])}}))}))},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e,t,i;(null===(i=null===(t=null===(e=this.socket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.options)||void 0===i?void 0:i.query)&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,""))},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var i;this.audienceSubscriptionState=void 0;var n={responses:[]};if(t){var r=this.mapToSyntheticAudienceSubscriptionResponses(t.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);(i=n.responses).push.apply(i,r)}return this.manager.onAudiencesSetResolved(n,e),n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error("Audience subscription attempt has timed out."),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,i){return e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:i}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=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 t=new l.Timespan;this.connectionTracker.trackStart("registration");var i=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:i}]}).then((function(){e.logger.info("Register request successful"),e.connectionTracker.trackEnd("registration"),e.fsm.onRegistrationSucceeded(),e.connectionTracker.sendTelemetry(c.ClientEventName.Registration,{duration:t.duration},[])})).catch((function(i){e.logger.error("Register request failed. Error: ".concat(i)),e.connectionTracker.trackError("registration",P(i)),e.fsm.onRegistrationFailed(),e.connectionTracker.sendTelemetry(c.ClientEventName.Registration,{duration:t.duration},[])}))},e.prototype.sendUnregisterRequest=function(){var e=this;this.logger.info("sending unregister request");var t=new l.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(){e.logger.info("Unregister request successful"),e.connectionTracker.trackEnd("unregistration"),e.fsm.onUnregistrationDone(),e.connectionTracker.sendTelemetry(c.ClientEventName.Unregistration,{duration:t.duration},[])})).catch((function(i){e.logger.error("Unregister request failed. Error: ".concat(i)),e.connectionTracker.trackError("unregistration",P(i)),e.fsm.onUnregistrationDone(),e.connectionTracker.sendTelemetry(c.ClientEventName.Unregistration,{duration:t.duration},[])}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug("Clearing all pending downstream events related timers");for(var t=0,i=e;t<i.length;t++){var n=i[t];this.clearSentEventTimer(Number(n))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug("Restarting incall mode timer"),this.incallModeTimerId=setTimeout((function(){e.logger.info("Call mode timer fired"),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info("Entering incall mode"),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.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},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect("force reconnect due to no registration")},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn("".concat(this.connectingErrorsInRow," connection attempts, server-side failure: erasing cached connection parameters")),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info("onSocketConnecting(".concat(e,")")),this.transportTypeName=e,this.connectionTracker.trackProgress("connecting",this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info("onSocketConnect"),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error("onSocketConnectFailed"),this.connectionTracker.trackError("connect_failed",e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,i=u.DisconnectReason.fromRawReason(e);this.logger.error("onSocketDisconnect, reason: ".concat(i.reason)),"dup"===i.reason&&"dup"===this.lastDisconnectReason&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn("Socket was closed by server as Duplicate for the second time in a row "+"after ".concat(t," 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=i.reason,this.fsm.onSocketDisconnect(i),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error("onSocketReconnect"),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error("onSocketReconnectFailed with '".concat(e,"'")),this.fsm.onSocketDisconnect(u.DisconnectReason.fromSocketIoEventData("reconnecterror",e))},e.prototype.onSocketReconnecting=function(){this.logger.error("onSocketReconnecting")},e.prototype.onSocketError=function(e){var t;this.logger.error("onSocketError with '".concat((0,l.toJson)(e),"'")),this.fsm.isConnecting()&&(this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()),this.connectionTracker.trackError("connectSocket",null!=(t=e)&&"function"==typeof t.toString?t.toString():"[".concat(typeof t,"]")),this.fsm.onSocketDisconnect(u.DisconnectReason.fromSocketIoEventData("socketerror",e))},e.prototype.onSocketMessage=function(e){var t,i,n=this;this.logger.debug("onSocketMessage");try{var r=null===(t=(i=new E(e,this.logger)).headers)||void 0===t?void 0:t["X-Microsoft-Skype-Chain-ID"],s=r?" Chain-Id ".concat(r):"";this.logger.info("Received request N ".concat(i.id).concat(s," CV ").concat(i.correlationVector," to '").concat(i.url,"'")),i.startTS=Date.now(),i.url&&this.urlPath&&i.url.startsWith(this.urlPath)&&(i.shortUrl=i.url.substring(this.urlPath.length))}catch(e){var a=A(e);return this.logger.error("unable to parse request. Error: ".concat(a)),this.connectionTracker.trackRequest(void 0,a),void this.connectionTracker.sendResponseError("unable to parse request, error: ".concat(e))}i.timeoutTimerId=setTimeout((function(){if(!i.replied){n.logger.error("Request ".concat(i.id," timed out"));var e=new c.ResponseData(i.id);e.status=504,e.headers={"Trouter-Responder":"ClientLib"},n.sendResponse(i,e),i.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(i),this.fsm.onDownstreamRequest(i)}catch(e){this.logger.error("exception in socket.on message. Error: ".concat(A(e))),this.connectionTracker.sendResponseError(P(e),i,void 0)}},e.prototype.onTrouterConnected=function(e,t,i){var r,s,a,o,c,d=this;if((0,f.isV4ConnectEvent)(e)){var u=e;this.allocateResult=n(n({},u),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(u,u.reconnectUrl),this.populateConnectionStateFields(u)}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!==(r=null==t?void 0:t.state)&&void 0!==r?r:"unknown")!==this.userActivityState.getStateString()?(this.logger.info("XHR user activity changed during connection attempt, from '".concat((0,l.toJson)(t),"' to '").concat(this.userActivityState.toEventJSON(),"', updating")),this.sendUserActivityStateIgnoreResponse()):t&&this.manager.onUserActivityStateAccepted(t.cv)):"xhr-polling"===this.transportTypeName&&t&&this.manager.onUserActivityStateAccepted(t.cv),(null===(o=null===(a=null===(s=this.socket)||void 0===s?void 0:s.socket)||void 0===a?void 0:a.options)||void 0===o?void 0:o.query)&&(this.socket.socket.options.query+="&connected=true"),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,"/");var h=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,l.calculateExpireTsInSec)((0,f.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd("connectSocket"),this.connectionTracker.trackConnected(h,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),null===(c=this.setAudienceSubscriptionsUnsafeAsync(i))||void 0===c||c.catch((function(e){return d.logger.error("Re-subscribe to audiences has failed with ".concat(e))})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info("onTrouterReconnect target: ".concat(t)),"self"===t?this.fsm.onReconnectRequired(!0,a.ServerInitiated):this.fsm.onReconnectRequired(!1,a.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug("onTrouterMessageLoss"),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.onAudienceSubscriptionResult=function(e){this.logger.info("onAudienceSubscriptionResult"),this.pendingAudienceSubscription&&(clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),this.pendingAudienceSubscription=void 0)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,l.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,i,n){var r=this;e.on("connecting",(function(e){r.onSocketConnecting(e)})),e.on("connect",(function(){r.onSocketConnect(t)})),e.on("connect_failed",(function(e){r.onSocketConnectFailed(e)})),e.on("close_during_connecting",(function(e){r.onSocketConnectFailed(e)})),e.on("disconnect",(function(e){r.onSocketDisconnect(e)})),e.on("reconnect",(function(){r.onSocketReconnect()})),e.on("reconnect_failed",(function(e){r.onSocketReconnectFailed(e)})),e.on("reconnecting",(function(){r.onSocketReconnecting()})),e.on("error",(function(e){r.onSocketError(e)})),e.on("message",(function(e){r.onSocketMessage(e)})),e.on("trouter.connected",(function(e){r.onTrouterConnected(e,i,n)})),e.on("trouter.reconnect",(function(e){r.onTrouterReconnect(e)})),e.on("trouter.message_loss",(function(e){r.onTrouterMessageLoss(e)})),e.on("audience.subscriptionresult",(function(e,t){r.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug("Browser online status update - new state: ".concat(e,", previously: ").concat(this.isNavigatorOnline)),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress("browserNet","online")):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress("browserNet","offline"))},e.prototype.onAllocationResponse=function(e,t){this.logger.info("Received allocation response ".concat(JSON.stringify(n(n({},e),{connectparams:void 0}))," (connectparams redacted)")),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,"".concat(this.allocateResult.socketio,"v4/a")),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=n({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t,i,n="string"==typeof e.ttl?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,l.calculateExpireTsInSec)(n),this.connectionId=null!==(t=e.id)&&void 0!==t?t:"",this.connectedClientId=e.ccid,this.logger.debug("connected client id set {connectedClientId:".concat(this.connectedClientId,"}")),this.c2cUrlBase=null!==(i=e.curlb)&&void 0!==i?i:"",""===this.c2cUrlBase){var r=e.surl.indexOf("://");r>=0&&(r=e.surl.indexOf("/",r+3))>=5&&":3443"===e.surl.substr(r-5,5)&&(this.c2cUrlBase=e.surl.substr(0,r-5))}},e.prototype.onPingResponse=function(){this.logger.debug("onPingResponse"),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){void 0!==this.pingResponseTimerId&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],i=0,n=Object.keys(e);i<n.length;i++){var r=n[i];void 0!==e[r]&&t.push("".concat(r,"=").concat(e[r]))}return t.join("&")},e.prototype.appendConnectedClientIds=function(e,t){var i="";e.includes("ccid=")||(i="ccid=".concat(this.connectedClientId,"&")),this.domId&&(i+="dom=".concat(this.domId,"&")),i.length>0&&(i=i.slice(0,-1));var n=t||e.includes("?")?"&":"?";return this.appendCorrelationIds(e+n+i,t)},e.prototype.appendEndpointId=function(e,t){var i=t||e.includes("?")?"&":"?";return!e.includes("epid")&&this.options.endpointId?"".concat(e).concat(i,"epid=").concat(this.options.endpointId):e},e.prototype.appendCorrelationIds=function(e,t){var i=t||e.includes("?")?"&":"?";return e.includes("cor_id")?e:"".concat(e).concat(i,"cor_id=").concat(this.options.clientCorrelationID)+"&con_num=".concat(this.clientID,"_").concat(this.connectionAttempt)},e.prototype.safeString=function(e){return"string"==typeof e?e:""},e.prototype.sendResponse=function(e,t){var i,n,r;if(e.timedout)return this.logger.error("Request ".concat(e.id," already timed out")),1;if(e.replied)return this.logger.error("Response for request ".concat(e.id," already sent")),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=null!==(i=t.headers)&&void 0!==i?i:{};var s=e.correlationVector;this.logger.info("Sending response N ".concat(e.id," CV ").concat(s," with status ").concat(t.status)),s&&(t.headers[T]=s),(null===(n=e.headers)||void 0===n?void 0:n["trouter-request"])&&(t.headers["trouter-request"]=e.headers["trouter-request"]);var a=Date.now()-e.startTS;if(t.headers["trouter-client"]=(0,l.toJson)({cd:a}),(null===(r=e.headers)||void 0===r?void 0:r["trouter-is-broadcast"])&&(t.headers["trouter-is-broadcast"]=e.headers["trouter-is-broadcast"]),!this.socket)return this.connectionTracker.sendResponseError("no socket",e,t),4;try{return this.socket.send((0,l.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,a,t),"websocket"===this.transportTypeName&&this.sendPingRequest(),0}catch(i){var o="unable to send data on response.end. Error: ".concat(A(i));return this.logger.error(o),this.connectionTracker.sendResponseError(o,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,i=new _("user.activity"),n=this.userActivityState.increaseCvAndGetEventObject();i.args=n,this.logger.debug("Sending user activity '".concat(this.userActivityState.toEventJSON(),"', remaining ").concat(e-1));var r=!1;this.sendDownstreamEvent(i,(function(){if(!0!==r&&(t.logger.info("User activity state: ".concat(n.state,", cv: ").concat(n.cv," accepted")),t.manager.onUserActivityStateAccepted(n.cv),t.clearSentEventTimer(i.timeoutTimerId),e>1)){var s=setTimeout((function(){t.clearSentEventTimer(s),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(s,"user.activity/resend")}})),i.timeoutTimerId=setTimeout((function(){t.logger.error("Activity state response timeout is fired"),r=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(i.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(i.timeoutTimerId,"user.activity/response")},e.prototype.sendUserActivityStateIgnoreResponse=function(){var e=new _("user.activity"),t=this.userActivityState.toEventObject();e.args=t,this.socket&&(this.logger.info("Sending user activity after XHR connect, ".concat(t.state,", cv: ").concat(t.cv,", treating it as accepted")),this.socket.emit(e.name,e.args),this.manager.onUserActivityStateAccepted(t.cv))},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug("Sending downstream event ".concat(e.name)),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug("registering timer ".concat(e," -> ").concat(t)),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug("clearing timer ".concat(e," -> ").concat(t)),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e,t,i=(0,l.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug("Current connectionID will expire in ".concat(i," seconds")),(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)&&i>0){var n=this.options.registration.registrarTtlSec<i;return[Math.min(this.options.registration.registrarTtlSec,i),n]}return(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)?[this.options.registration.registrarTtlSec,!1]:i>0?[i,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){void 0!==this.incallModeTimerId&&(this.logger.debug("Clearing in-call mode timer"),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&"function"==typeof e.eventLogger.logEvent?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn("Trouter client event logging disabled due to invalid configuration.")}catch(e){this.logger.warn("Trouter client event logging disabled. Error: ".concat(A(e))),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return null==t||e<t||(this.logger.warn("Reached limit on maximum number of token fetch request. Current count: ".concat(e,", retry limit: ").concat(t)),!1)},e}();function w(e,t){var i=t?void 0:{"X-MS-Migration":"True"};switch(e.tokenType.toLowerCase()){case"skype":return n({"X-Skypetoken":e.token},i);case"aad":case"cae":return n({Authorization:"Bearer ".concat(e.token)},i);default:throw new Error("unsupported token type: ".concat(e.tokenType))}}function A(e){return"object"==typeof e&&null!==e&&void 0!==e.stack?(0,l.toJson)(e.stack):'"(no error.stack)"'}function P(e){return"object"==typeof e&&null!==e&&"string"==typeof e.message?e.message:"(no error.message)"}t.TrouterConnection=I},335:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var n,r,s=i(423),a=i(642),o=i(902);!function(e){e[e.Initial=0]="Initial",e[e.RetrievingToken=1]="RetrievingToken",e[e.Allocating=2]="Allocating",e[e.Handshaking=3]="Handshaking",e[e.Connecting=4]="Connecting",e[e.AnonymousConnecting=5]="AnonymousConnecting",e[e.WebsocketAuthenticating=6]="WebsocketAuthenticating",e[e.Connected=7]="Connected",e[e.Unregistering=8]="Unregistering",e[e.TerminalError=9]="TerminalError"}(n||(t.State=n={})),function(e){e[e.Initial=0]="Initial",e[e.Registering=1]="Registering",e[e.RegisteringButResendPending=2]="RegisteringButResendPending",e[e.Retrying=3]="Retrying",e[e.Registered=4]="Registered",e[e.RegistrationDisabled=5]="RegistrationDisabled"}(r||(r={}));var l=function(){function e(e,t,i,s){this.worker=t,this.incallModeEnabled=i,this.protocolSelector=s,this.state=n.Initial,this.autoReconnect=!0,this.logger=new a.Logger("ConnectionFsm",e),this.registrationState=r.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===n.Allocating||this.state===n.Connected||this.state===n.Handshaking||this.state===n.Connecting||this.state===n.RetrievingToken||this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===n.Allocating||this.state===n.Handshaking||this.state===n.Connecting||this.state===n.AnonymousConnecting},e.prototype.start=function(){return this.state===n.Initial?(this.setState(n.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=r.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===n.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==r.Registered&&this.registrationState!==r.Registering&&this.registrationState!==r.RegisteringButResendPending||this.state===n.Unregistering?t?(this.setState(n.TerminalError),this.worker.dispatchTerminalError()):(this.setState(n.Initial),this.worker.dispatchDisconnected()):(this.registrationState=r.Initial,this.setState(n.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,i){this.state===n.RetrievingToken?"v4c"===(0,o.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,i),t)?(this.setState(n.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(n.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored("onTokenReceived")},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===n.Allocating&&this.registrationState===r.Registered&&this.worker.dispatchUnregistered(),this.state===n.Allocating?(this.setState(n.Handshaking),this.registrationState=r.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored("onAllocationSucceed"),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===n.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored("onAllocationFailed")},e.prototype.onV4cConnectivityCheckFailed=function(){this.state===n.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored("onV4cConnectivityCheckFailed")},e.prototype.onV4cException=function(){this.state!==n.AnonymousConnecting&&this.state!==n.WebsocketAuthenticating||(this.logger.error("v4c exception, falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}}))},e.prototype.onConnectingTimeout=function(){this.state===n.Allocating||this.state===n.Connecting||this.state===n.Handshaking||this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout")},e.prototype.onConnecting=function(){this.state===n.Handshaking?this.setState(n.Connecting):this.showIgnored("onConnecting")},e.prototype.onSocketConnect=function(e){this.state===n.AnonymousConnecting?(this.setState(n.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored("onSocketConnect")},e.prototype.onConnectingFailed=function(){this.state===n.Connecting?this.onConnectingTimeout():this.state===n.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?(this.logger.info("/v4/c falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}})):this.showIgnored("onConnectingFailed")},e.prototype.onSocketDisconnect=function(e){this.state===n.Handshaking||this.state===n.Connected||this.state===n.WebsocketAuthenticating?(this.state===n.Connected&&this.worker.sendDisconnectTelemetryEvent(null==e?void 0:e.toTelemetryString()),this.state===n.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null==e?void 0:e.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==n.Connected&&"dup"!==(null==e?void 0:e.reason),allowCachedToken:"unauthorized"!==(null==e?void 0:e.reason),claimsChallenge:null==e?void 0:e.claims})):this.showIgnored("onSocketDisconnect")},e.prototype.onTrouterConnected=function(){this.state===n.Connecting||this.state===n.WebsocketAuthenticating?(this.setState(n.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(s.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=r.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=r.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected")},e.prototype.onReconnectRequired=function(e,t,i){this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?void 0===i||"host"!==i.target||void 0===i.url||""===i.url?(this.logger.error("unexpected reconnect arguments: ".concat(null==i?void 0:i.target," ").concat(null==i?void 0:i.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:i.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===n.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored("onDownstreamRequest")},e.prototype.onTrouterMessageLost=function(e){this.state===n.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored("onTrouterMessageLost")},e.prototype.onPingInterval=function(){this.state===n.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval")},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout")},e.prototype.onPingResponse=function(){this.state===n.Connected||this.showIgnored("onPingResponse")},e.prototype.onRegistrationFailed=function(){this.state===n.Connected&&this.registrationState===r.Registering?(this.worker.dispatchUnregistered(),this.registrationState=r.Retrying,this.worker.startRegistrationRetryTimer()):this.state===n.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed")},e.prototype.onRetryRegistration=function(){this.state===n.Connected&&this.registrationState===r.Retrying?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration")},e.prototype.onRegistrationSucceeded=function(){this.state===n.Connected&&this.registrationState===r.Registering?(this.registrationState=r.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===n.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded")},e.prototype.onRegistrationNearExpiry=function(){this.state===n.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry")},e.prototype.onUnregistrationDone=function(){this.state===n.Unregistering?(this.setState(n.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone")},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===n.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===n.Connected&&this.registrationState===r.Registering&&(this.registrationState=r.RegisteringButResendPending)},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===n.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer")},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(s.UserActivityEventReason.Modified,this.state===n.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout")},e.prototype.forceReconnect=function(e){this.state===n.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error("Cannot proceed, reached terminal state. Switching from state '".concat(n[this.state],"' to ").concat(n[n.TerminalError])),this.stop(!0,!0),this.setState(n.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===n.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug("Ignoring event '".concat(e,"' in state '").concat(n[this.state],"'"))},e.prototype.setState=function(e){this.logger.info("Switching from state '".concat(n[this.state],"' to state '").concat(n[e],"'")),this.state!==e?this.state=e:this.logger.error("Attempt to switch to the current state '".concat(n[e],"'"))},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){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(n.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}();t.TrouterFsm=l},634:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var s=i(659),a=i(234),o=i(423),l=i(642),c=i(902),d=i(235),u=i(573),h=i(335),g=i(10),p=function(){function e(e,t){this.state=e,this.correlationVector=void 0!==t?t:s.CorrelationVector.extend()}return e.prototype.getStateString=function(){switch(this.state){case a.UserActivityState.Active:return"active";case a.UserActivityState.Inactive:return"inactive";case a.UserActivityState.Unknown:return"unknown";default:return"undefined"}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,s.toJson)(this.toEventObject())},e}();t.UserActivityObject=p;var m=function(){function e(e,t){void 0===t&&(t=s.CorrelationVector.extend()),this.audienceSubscriptionModel=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.audienceSubscriptionModel.audienceSubscriptions,cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,s.toJson)(this.toEventObject())},e}();t.AudienceSubscriptionState=m;var f=function(){function e(e,t,i,n,r,o){var d=this;this.logFunc=e,this.options=t,this.tokenProvider=i,this.usingLegacyTokenApi=n,this.listener=r,this.tokenTypeProtocolSelector=function(e,t){return d.options.forceV4aProtocol?"v4a":(0,c.usedProtocol)(e,t)},this.logger=new l.Logger("Manager",e),this.logger.info("Created TrouterManager with options ".concat((0,s.toJson)(this.options))),this.fsm=new g.TrouterManagerFsm(e,this),this.baseEndpointUrl="",this.processedMessageLoss={},this.userActivityObject=new p(a.UserActivityState.Unknown),this.protocolSelector=null!=o?o:this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,void 0!==this.firstConnection&&this.firstConnection.configure(e),void 0!==this.secondConnection&&this.secondConnection.configure(e),this.logger.info("Reconfigured TrouterManager with options ".concat((0,s.toJson)(this.options)))},e.prototype.checkConnection=function(e){void 0!==this.firstConnection&&this.firstConnection.checkConnection(e),void 0!==this.secondConnection&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return n(this,void 0,void 0,(function(){return r(this,(function(e){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])}))}))},e.prototype.getServerState=function(){if(void 0!==this.firstConnection)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===o.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?h.State[this.firstConnection.getState()]:"Unknown",t=o.TrouterManagerState[this.fsm.getInternalState()];if(this.secondConnection){var i=h.State[this.secondConnection.getState()];return"Manager ".concat(t,"; 1st ").concat(e,"; 2nd ").concat(i)}return"Manager ".concat(t,"; Connection ").concat(e)},e.prototype.startFirstConnection=function(){var e=new u.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=e,this.getConnectionCache().then((function(t){e.start(t)})).catch((function(){}))},e.prototype.startSecondConnection=function(e){var t=new u.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=t,void 0!==this.firstConnection&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?this.getConnectionCache().then((function(e){t.start(e)})).catch((function(){})):t.start()},e.prototype.stopFirstConnection=function(e){void 0!==this.firstConnection&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){void 0!==this.secondConnection&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(void 0!==this.secondConnection){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info("Closing an inactive connection in ".concat(Math.round(this.options.lingeringConnectionDelayMs/1e3),"s")),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&(this.storedFirstConnection.stop(!1),this.storedFirstConnection=void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return void 0!==this.secondConnection},e.prototype.dispatchConnected=function(){if(void 0!==this.firstConnection){var e=this.firstConnection.getServerState(),t=e.url.endsWith("/")?e.url.slice(0,-1):e.url,i={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,i)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){var e;void 0!==this.lastExpediteBackoffCallAt&&Date.now()-this.lastExpediteBackoffCallAt<(null!==(e=this.options.expediteBackoffOnStartMinimumDelayMs)&&void 0!==e?e: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())},e.prototype.onDownstreamRequest=function(e,t,i){var n={id:t.id,method:t.method,path:"/".concat(t.shortUrl),body:t.body,headers:t.headers},r={id:t.id,status:0,headers:{},body:"",send:function(){return r.status<=100||r.status>=999?3:(i.writeHead(r.status,r.headers),i.end(r.body))}};this.listener.onTrouterRequest(n,r)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,i){this.fsm.onReconnectionRequired(e===this.firstConnection,t,i)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var i,n;null===(n=(i=this.listener).onAudiencesSetResolved)||void 0===n||n.call(i,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){return this.userActivityObject=new p(e,s.CorrelationVector.extend(t)),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},e.prototype.setAudienceSubscriptionsAsync=function(e,t,i){if(this.audienceSubscriptionState=new m(e,s.CorrelationVector.extend(i)),this.secondConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on second/new connection")),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on first/current connection")),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw new Error("No connection found")},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(null==e?void 0:e.length){var i=e.filter((function(e){return void 0!==t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]}));if(i.length&&(this.logger.info("onTrouterMessageLoss - immediately acknowledging ".concat(i.length," seen dropped indicators")),this.sendProcessedDroppedIndicators(i),!(e=e.filter((function(e){return void 0===t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]}))).length))return void this.logger.info("onTrouterMessageLoss - all declared dropped indicators have been seen before");if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn("onTrouterMessageLoss - some flow tag(s) have not been processed by listeners");e.forEach((function(e){t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]=""})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn("onTrouterMessageLoss - no flow tags have been provided")},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug("Querying host's connection cache"),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return"object"==typeof t?t:void 0})).catch((function(t){return e.logger.warn("Invalid connection cache content provided: ".concat(t)),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn("Error setting external connection cache: ".concat(e))}},e.prototype.sendProcessedDroppedIndicators=function(e){void 0===this.firstConnection?void 0===this.secondConnection||this.secondConnection.sendProcessedDroppedIndicators(e):this.firstConnection.sendProcessedDroppedIndicators(e)},e.prototype.configuredTrouterManager=function(){return new d.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e}();t.TrouterManager=f},10:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var n=i(234),r=i(423),s=i(642),a=i(573),o=function(){function e(e,t){this.worker=t,this.state=r.TrouterManagerState.Unknown,this.logger=new s.Logger("ManagerFsm",e)}return e.prototype.start=function(){this.state===r.TrouterManagerState.Unknown?(this.setState(r.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info("start called in state '".concat(r.TrouterManagerState[this.state],"', expediting pending backoffs, if any")),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state!==r.TrouterManagerState.Unknown?(this.setState(r.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e)):this.showIgnored("stop")},e.prototype.getState=function(){switch(this.state){case r.TrouterManagerState.Unknown:case r.TrouterManagerState.Connected:case r.TrouterManagerState.Disconnected:case r.TrouterManagerState.Switching:return this.state;case r.TrouterManagerState.TerminalError:return n.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===r.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(r.TrouterManagerState.Switching):(this.setState(r.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored("onConnected(".concat(e,")"))},e.prototype.onRegistered=function(e){this.state!==r.TrouterManagerState.Disconnected||e?this.state!==r.TrouterManagerState.Switching||e?this.state===r.TrouterManagerState.Disconnected&&e&&(this.setState(r.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(r.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(r.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==r.TrouterManagerState.Connected&&this.state!==r.TrouterManagerState.Switching||!e?this.showIgnored("onReconnecting(".concat(e,")")):(this.setState(r.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,i){this.state===r.TrouterManagerState.Connected&&e?(this.setState(r.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===r.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===r.TrouterManagerState.Switching&&e&&i===a.ReconnectReason.Configuration?(this.logger.debug("onReconnectionRequired: switch requested while already in Switching state"),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored("onReconnectionRequired(".concat(e,")"))},e.prototype.onDisconnected=function(e){this.state==r.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==r.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(r.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored("onDisconnected(".concat(e,")"))},e.prototype.onTerminalError=function(){this.setState(r.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info("Ignoring event '".concat(e,"' in state '").concat(r.TrouterManagerState[this.state],"'"))},e.prototype.setState=function(e){this.logger.info("Switching from state '".concat(r.TrouterManagerState[this.state],"' to state '").concat(r.TrouterManagerState[e],"'")),this.state!==e?this.state=e:this.logger.error("Attempt to switch to the current state '".concat(r.TrouterManagerState[e],"'"))},e}();t.TrouterManagerFsm=o},616:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var n=i(642),r=function(){function e(e){this.logger=new n.Logger("UrlPromise",e)}return e.prototype.getPromise=function(){var e=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(t,i){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=i}))):this.logger.debug("returning existing promise"),this.pendingPromise)},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug("got url: ".concat(this.url));var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==t&&(this.logger.debug("resolving promise"),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug("aborting");var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==t&&(this.logger.debug("rejecting promise"),t(e))},e.prototype.resetUrl=function(){this.logger.debug("resetting url"),this.url=void 0},e}();t.TrouterUrlPromise=r},882:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){a.label=o[1];break}if(6===o[0]&&a.label<r[1]){a.label=r[1],r=o;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(o);break}r[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.replaceTrouterUrlBase=t.getTrouterServiceVersion=t.createTrouterService=t.TrouterService=t.UserActivityState=t.TrouterState=void 0;var a=i(509),o=i(234);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return o.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return o.UserActivityState}});var l=i(642),c=i(619),d=i(220),u=i(634),h=i(616);function g(e,t){if(!t)return e;var i=n(n({},e),{enabled:t.TelemetryEnabled});return void 0!==t.ClientTelemetryEventEnabled&&(i=n(n({},i),t.ClientTelemetryEventEnabled)),i}function p(e,t,i){var r,s,a,o,l,c,d,u,h,p,m,f,v=function(i){return e.proxyUrlRewrite?(t.info("Using rewritten URL for proxy"),e.proxyUrlRewrite(i)):i};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:v},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:g(e.telemetryConfig.settings,i),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:(null==i?void 0:i.TrouterConnectionUrl)||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl?{registrarUrl:e.trouterSettings.registrarServiceUrl,registrationId:null!==(r=e.trouterSettings.registrationId)&&void 0!==r?r:"",pnhAppId:null!==(s=e.trouterSettings.pnhAppId)&&void 0!==s?s:"",platform:null!==(a=e.trouterSettings.platform)&&void 0!==a?a:"",pnhTemplateKey:null!==(o=e.trouterSettings.pnhTemplate)&&void 0!==o?o:"",platformUIVersion:null!==(l=e.trouterSettings.platformUIVersion)&&void 0!==l?l:"",productContext:e.trouterSettings.pnhProductContext||void 0,context:null!==(c=e.trouterSettings.pnhContext)&&void 0!==c?c:"",registrarTtlSec:(null!==(d=e.trouterSettings.maxRegistrationTimeInMs)&&void 0!==d?d:0)/1e3}:void 0,connectionDependsOnRegistration:void 0===e.trouterSettings.registrarServiceUrl?function(){return!1}:null!==(u=e.trouterSettings.connectionDependsOnRegistration)&&void 0!==u?u:function(){return!1},delayEventsUntilRegistered:null!==(h=e.trouterSettings.delayEventsUntilRegistered)&&void 0!==h?h:function(){return!1},timeoutOptions:n({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:"TeamsCDL"===e.trouterSettings.productName?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:n({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:"TeamsCDL"===e.trouterSettings.productName?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:null!==(p=e.trouterSettings.incallModeTimeoutMs)&&void 0!==p?p:0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:v,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:null===(m=e.trouterSettings.updateUserActivityDuringConnectionAttempt)||void 0===m||m,initialConnectivityCheck:null===(f=e.trouterSettings.initialConnectivityCheck)||void 0===f||f,toJSON:function(){return n(n({},this),{connectionCache:this.connectionCache?{}:this.connectionCache})}}}var m=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new l.Logger("Trouter",e),this.trouterUrlPromise=new h.TrouterUrlPromise(e),this.messageHandlers=new c.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version ".concat(a.CLIENT_VERSION))}return e.prototype.start=function(e){var t;if(this.logger.info("Start"),!e.skypeTokenProvider&&!e.authTokenProvider)throw new Error("no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated");e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,d.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var i=p(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(i.forceV4aProtocol=!0);var n=function(e,t){var i,n=this;return function(a){return r(n,void 0,void 0,(function(){var n,r,o;return s(this,(function(s){switch(s.label){case 0:n=new Date,r=setInterval((function(){var t=Math.round((Date.now()-n.getTime())/6e4);e.warn("Note: Trouter auth token request promise from ".concat(n.toISOString()," has not been resolved for ").concat(t," minutes. The client is blocked from operating properly"))}),3e5),s.label=1;case 1:return s.trys.push([1,,3,4]),[4,t(a)];case 2:return o=s.sent(),a.needFresh&&o.token===i&&e.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"),i=o.token,[2,o];case 3:return clearInterval(r),[7];case 4:return[2]}}))}))}}(this.logger,null!==(t=e.authTokenProvider)&&void 0!==t?t:function(e){var t=this;return function(i){return r(t,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return t={},[4,e(i.needFresh)];case 1:return[2,(t.token=n.sent(),t.tokenType="skype",t)]}}))}))}}(e.skypeTokenProvider));void 0===this.trouterServer&&(this.trouterServer=new u.TrouterManager(this.logProvider,i,n,void 0===e.authTokenProvider,this)),void 0!==this.pendingActivityState&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info("close connection"),this.trouterUrlPromise.rejectUrl(new Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return r(this,void 0,void 0,(function(){var t=this;return s(this,(function(i){return[2,new Promise((function(i){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info("Setting ECS configuration to ".concat(JSON.stringify(t.ecsCfg))),void 0!==t.trouterServer&&void 0!==t.trouterCfg){var n=p(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(n)}i()}))]}))}))},e.prototype.checkConnection=function(e){void 0!==this.trouterServer&&this.trouterServer.checkConnection(null!=e&&e)},e.prototype.resendRegistration=function(){return r(this,void 0,void 0,(function(){return s(this,(function(e){if(!this.trouterServer)throw new Error("resendRegistration called too early");return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerListener=function(e,t){return""===t||!t.startsWith("/")||t.includes("?")||t.includes("#")?(this.logger.error("Listener path '".concat(t,"' is not valid")),!1):this.listeners[t]?(this.logger.error("Another listener is already registered for path '".concat(t,"'")),!1):(this.listeners[t]=e,this.logger.debug("Listener for path '".concat(t,"' registered")),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i];this.listeners[r]===e&&t.push(r)}if(0===t.length)return!1;for(var s=0,a=t;s<a.length;s++)r=a[s],delete this.listeners[r];return this.logger.debug("Listener for path(s) '".concat(t.join("', '"),"' unregistered")),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug("Trouter is now connected");for(var i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i];try{this.listeners[r].onTrouterConnected(t.baseEndpointUrl+r,t)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onTrouterConnected(): ").concat(e))}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(o.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug("Trouter is now disconnected"),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var i=t[e],n=this.listeners[i];if(n.onTrouterDisconnected)try{n.onTrouterDisconnected()}catch(e){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterDisconnected(): ").concat(e))}}this.notifyStateChanged(o.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var i="",n=0,r=Object.keys(this.listeners);n<r.length;n++){var s=r[n];e.path.startsWith(s)&&s.length>i.length&&(i=s)}if(""===i)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":"ClientLib"},t.send());else try{this.listeners[i].onTrouterRequest(e,t)}catch(e){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterRequest(): ").concat(e)),t.status=500,t.headers={"Trouter-Responder":"ClientLib"},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info("onTrouterMessageLoss called with tags [".concat(e,"]"));for(var t=!0,i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i],s=this.listeners[r];if(s.onTrouterMessageLoss)try{void 0===(t=s.onTrouterMessageLoss(e)&&t)&&(this.logger.error("Listener '".concat(r,"' did not return a boolean value from onTrouterMessageLoss()")),t=!1)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onTrouterMessageLoss(): ").concat(e)),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug("onTrouterUserActivityStateAccepted cv: ".concat(e));for(var t=0,i=Object.keys(this.listeners);t<i.length;t++){var n=i[t],r=this.listeners[n];if(r.onTrouterUserActivityStateAccepted)try{r.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error("Listener '".concat(n,"' threw an exception from onTrouterUserActivityStateAccepted(): ").concat(e))}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug("onAudiencesSetResolved cv: ".concat(t));for(var i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i],s=this.listeners[r];if(s.onAudiencesSetResolved)try{s.onAudiencesSetResolved(e,t)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onAudienceSubscribed(): ").concat(e))}}},e.prototype.setUserActivityState=function(e,t){if(e!==o.UserActivityState.Active&&e!==o.UserActivityState.Inactive)throw new Error("setUserActivityState called with unsupported value ".concat(e));this.logger.info("setUserActivityState called with value ".concat(o.UserActivityState[e])),this.trouterServer&&this.state()!==o.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn("setUserActivityState called before start() or after stop()"))},e.prototype.setAudienceSubscriptions=function(e,t){if(e.audienceSubscriptions.length>1)throw new Error("Only singular audience subscription is supported");if(this.trouterServer&&this.state()!==o.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw new Error("audience subscribe called before start() or after stop()")},e.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():o.TrouterState.Unknown},e.prototype.isInTerminalState=function(){return void 0!==this.trouterServer&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return void 0===this.trouterServer?"":this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(void 0!==this.trouterServer)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return void 0!==this.trouterServer?this.trouterUrlPromise.getPromise():Promise.reject(new Error("TrouterService has not been started"))},e.prototype.onStateChanged=function(e){if(this.logger.info("onStateChanged called"),void 0===e)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return void 0===e.wrappedCallback}));else{this.offStateChanged(e);var t=function(t,i){e(t,i?i.url:"")};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info("offStateChanged called");var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info("addListener called"),-1===this.stateChangedListeners.indexOf(e,0)&&void 0!==e&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info("removeListener called");var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info("registerMessageHandler is called"),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info("clearMessageHandlers is called"),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var i=this;this.logger.info("notifyStateChanged called, will forward to ".concat(this.stateChangedListeners.length," listeners")),this.stateChangedListeners.forEach((function(n){try{n(e,t)}catch(e){i.logger.error("Error in callback ".concat(e))}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var i,n=null;try{n=(i=JSON.parse(e.body))&&(i.evt||i.eventId)||null}catch(e){}var r={eventId:n,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:"")+e.path,body:i,rawBody:e.body,headers:e.headers},s=this.messageHandlers.handleMessage(r);return!!s.isHandled&&(t.status=s.resultCode,s.responseHeaders&&(t.headers=s.responseHeaders),s.responseBody&&(t.body=s.responseBody),t.send(),!0)},e}();t.TrouterService=m,t.createTrouterService=function(e){return new m(e)},t.getTrouterServiceVersion=function(){return a.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var i=e.indexOf("://");if(i>=0){var n=e.indexOf("/",i+3);if(n>=0)return t+e.substr(n)}return""}},673:t=>{t.exports=e}},i={};function n(e){var r=i[e];if(void 0!==r)return r.exports;var s=i[e]={id:e,loaded:!1,exports:{}};return t[e].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}return n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n(882)})(),e.exports=i(RO)}));class DO{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:"708a9eb9fe2646fe8f4c37b7eee2e3da-9b97485a-57b9-43a8-8177-07ca7a653a30-6706",properties:{...e.properties}})},this._logger=e.createChild("TelemetrySender"),this._telemetryLogManager=t}}function kO(e){return{registrationId:Mf(),registrarServiceUrl:e.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:e.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:e.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:e.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:e.getTrouterSettings().pnhAppId,pnhTemplate:e.getTrouterSettings().pnhTemplate,platform:e.getTrouterSettings().platform,platformUIVersion:e.getTrouterSettings().version,trouterServiceUrl:e.getTrouterSettings().trouterServiceUrl,version:e.getTrouterSettings().version,trouterConnectTimeoutInMs:e.getTrouterSettings().trouterConnectTimeoutInMs,productName:e.getTrouterSettings().productName,sessionId:Mf(),environment:e.getTrouterSettings().environment,timeoutOptions:e.getTrouterSettings().timeoutOptions}}class OO{constructor(e,t,i,n,r){this._ecsProvider=t,this._tokenProvider=i,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild("Trouter"),this._logger.info("init"),this._initialRegistrationCompleteDefer=jT(),this._telemetryLogManager=n,this._acsProxy=r}async start(e){let t;if(this._trouterService)throw this._logger.error("Trouterservice already initialized"),new le({defaultError:ee.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{const i=new Promise((async(t,i)=>{try{if(this._logger.info("Trouterservice start"),this._trouterService=MO.createTrouterService(this._logger),!this._trouterService)throw this._logger.error("Failed to create trouter service"),new le({defaultError:ee.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||"",this._options.trouterSettings.sessionId=e.sessionId);let i,n,r=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===MO.TrouterState.Connected&&(i=+new Date)})),await this._initialRegistrationCompleteDefer.promise;const s=+new Date;i=i??+new Date,n=i,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,i-r),registrarRequestCompletionTimeDeltaMs:Math.max(0,s-n)})}catch(e){i(e)}}));try{const e=WT((()=>i),25e3);t=await e}catch(e){throw 408===e.code?(this._logger.error("Signaling init timeout"),new le({defaultError:ee.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[25e3]})):(this._logger.error("Signaling init failed"),new le({defaultError:ee.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info("TrouterService onRegisteredChanged"),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){const t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info("Trouterservice stop"),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error("Trouterservice not inited")}registerMessageHandler(e){this._logger.info("Trouterservice registerMessageHandler"),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info("Trouterservice state"),this._trouterService?this._trouterService.state():MO.TrouterState.Unknown}onStateChanged(e){this._logger.info("Trouterservice onStateChanged"),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info("Trouterservice offStateChanged"),this._trouterService&&this._trouterService.offStateChanged(e)}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 kO(this._ecsProvider)}_createTrouterTelemetryConfig(e){return{eventLogger:new DO(e.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(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,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(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}}class NO{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:Fv,skypecosi_concore_web_ts_calling_in_call_session:Fv,skypecosi_concore_web_ts_calling_call_setup_session:Fv,skypecosi_concore_native_ts_calling_in_call_session:Fv,skypecosi_concore_native_ts_calling_call_setup_session:Fv,skypecosi_concore_web_pluginless_call_session:Fv,skypecosi_concore_web_pluginless_modality_session:Fv,skypecosi_concore_web_csa_conversation_callmodality:Fv,skypecosi_concore_web_ts_calling_registry:Fv,mdsc_webrtc_session:Uv,mdsc_webrtc_session_initial:Uv,live_events:Bv,mdsc_ortc_reports:Uv,mdsc_ortc_reports_initial:Uv,mdsc_rt_log:Uv},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:"",this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}}class LO{constructor(){this._timedVideoEffectProviderPromise=Iy(3e3),this._timedModelConfigPromise=Iy(3e3)}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 xO{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}}class FO{constructor(e,t){t||"function"!=typeof e.createChild?this.logger=e:this.logger=e.createChild("JS.TsCalling.RequestDispatcher"),this.proxy=t}getRequestOptions(e,t,i,n,r){return{headers:t||{},timeout:n,payload:i||null,responseType:r}}getAsync(e,t){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(e):e,t,"GET")}postAsync(e,t){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(e):e,t,"POST")}putAsync(e,t){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(e):e,t,"PUT")}removeAsync(e,t){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(e):e,t,"DELETE")}async sendRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||Mf()}][Request]`);n.info(`sending, ${i}-${e}`);const r=Date.now();let s;t.headers=t.headers||{},t.headers["content-type"]||(t.headers["content-type"]=t.contentType||"application/json");let a={url:e,start:new Date(r).toISOString(),end:"",statusCode:0,deltaTimeInMs:0,causeId:""};const o=vy().telemetry.apiCauseIdHeader;try{const l=iR.request({url:e,method:i,headers:t.headers||{},timeout:"number"==typeof t.timeout?t.timeout:45e3,data:t.payload||"",responseType:t.responseType||t.dataType||"json",withCredentials:jS(t.withCredentials,!1),cancelToken:new iR.CancelToken((e=>{s=e}))});(function(e){return!!e&&"function"==typeof e.then})(t.timeout)&&t.timeout.then((()=>{n.info("Aborting pending request"),s()}),(()=>{n.info("Timeout promise rejected, ignoring")}));const c=await l;if(n.info(`success, status=${c.status}`),t.headers[o]){const e=t.headers[o].split("-")[0];pI.getRemoveCauseIdToNetworkInfo(e)&&(a={...a,end:(new Date).toISOString(),statusCode:c.status,deltaTimeInMs:Date.now()-r,causeId:e},pI.setCauseIdToNetworkInfo(e,a))}return{response:c.data,request:c.request,duration:Date.now()-r}}catch(e){if(n.info("failed"),t.headers[o]){const i=t.headers[o].split("-")[0];pI.ifCauseIdExistsRemoveNetworkInfo(i)&&(a={...a,end:(new Date).toISOString(),statusCode:e.code,deltaTimeInMs:Date.now()-r,causeId:i},pI.setCauseIdToNetworkInfo(i,a))}if(iR.isCancel(e))throw n.info(`response=${GS(e.message)}`),{aborted:!0};throw e.response?n.info(`response=${GS(e.response)}`):e.request?n.info(`no response, request=${GS(e.request)}`):n.info(`request not made, error=${GS(e)}`),e||new Error("Request failed")}}}class UO{constructor(){this._activeEffects=[],this.eventEmitter=new OE.EventEmitter}on(e,t){if("statusChanged"!==e)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("statusChanged"!==e)throw new le({defaultError:ee.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){const t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit("statusChanged",t,this._activeEffects)}}class BO{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new OE.EventEmitter}on(e,t){if("statusChanged"!==e)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("statusChanged"!==e)throw new le({defaultError:ee.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){const i={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit("statusChanged",i,this._activeEffects,t)}}class VO{get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}}const HO={AcsCallingSDKWeb:{telemetry:{telemetryFlushTimeout:1e4},calling:{allowAccessRawMediaStream:!1,deviceSelectionTimeoutInMs:1e4}},SkypeWebMedia:{mediaAgent:{useOneDsLogger:!0}}};class $O{constructor(){this._mapping=new WeakMap,this._eventEmitter=new OE}get(e){return this._mapping.get(e)?.deref()}create(e){const t=this._createProxy(e);if(void 0===t)throw new Error("The type is not supported for proxy");return this._mapping.set(e,new WeakRef(t)),t}replaceProxyToRaw(e){if("object"==typeof e){if(Array.isArray(e))return e.map((e=>this.replaceProxyToRaw(e)));if(RI in e)return e[RI]}return e}replaceRawToProxy(e,t){if(void 0===t&&(t=new Map),"object"==typeof e){if(null===e)return e;if(t.has(e))return t.get(e);if(RI in e)return e;if(Array.isArray(e)){const i=e.map((e=>this.replaceRawToProxy(e,t)));return t.set(e,i),i}if(e instanceof Promise)return e.then((e=>this.replaceRawToProxy(e,t)));if(e instanceof ArrayBuffer||e instanceof Uint8Array||e instanceof Date||e instanceof RegExp)return e;if(this.isSupportedType(e)){let i=this.get(e);return void 0===i&&(i=this.create(e)),t.set(e,i),i}if(PI(e))return t.set(e,e),e;const i={};t.set(e,i);for(const[n,r]of Object.entries(e))i[n]=this.replaceRawToProxy(r,t);return i[RI]=e,i}return e}on(e,t){this._eventEmitter.on(e,t)}once(e,t){this._eventEmitter.once(e,t)}dispose(){this._eventEmitter.removeAllListeners()}}function jO(e,t,i,n={}){return new Proxy(e,{get:(r,s)=>{let a,o;if(s===RI)return e;if(s in t)a=t[s],o=t;else{if(!(s in e))return;a=e[s],o=e}const l=n[s]??{input:!0,output:!0};if("function"==typeof a){if(!i.isRemoteStackActive()&&o===e)throw new le({defaultError:ee.FEATURES.VDI3.REMOTE_STACK_TERMINATED});return new Proxy(a,{apply:(e,t,n)=>{const r=n.map((e=>"function"==typeof e?(...t)=>e.apply(null,i.replaceRawToProxy(t)):l.input?i.replaceProxyToRaw(e):e)),s=Reflect.apply(e,o,r);return l.output?i.replaceRawToProxy(s):s}})}return l.output?i.replaceRawToProxy(a):a},has:(i,n)=>n===RI||n in t||n in e})}class GO{constructor(e,t){this._proxyReferenceManager=e,this._tsObject=t,this._eventEmitter=new OE,this._handles=new Map}_proxyCall(e,t){const i=this._tsObject[e];if(void 0!==i)return i.apply(this._tsObject,t)}get instance(){return this._tsObject}changed(e){const t="changed";let i=this._handles.get(t);if(void 0===i){const e=(...e)=>{this._eventEmitter.emit(t,...e)};i=this._proxyCall("changedAsync",[e]),this._handles.set(t,i)}const n=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,n),{dispose:()=>{this._eventEmitter.off(t,n),0===this._eventEmitter.listenerCount(t)&&(i?.then((e=>e.disposeAsync?.())).catch(My),this._handles.delete(t))}}}on(e,t){const i=`on_${e}`;let n=this._handles.get(i);if(void 0===n){const t=(...e)=>{this._eventEmitter.emit(i,...e)};n=this._proxyCall("onAsync",[e,t]),this._handles.set(i,n)}const r=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(i,r),{dispose:()=>{this._eventEmitter.off(i,r),0===this._eventEmitter.listenerCount(i)&&(n?.then((e=>e.disposeAsync?.())).catch(My),this._handles.delete(i))}}}once(e,t){const i=`once_${e}`;let n=this._handles.get(i);if(void 0===n){const t=(...e)=>{this._eventEmitter.emit(i,...e)};n=this._proxyCall("onceAsync",[e,t]),this._handles.set(i,n)}const r=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(i,r),{dispose:()=>{this._eventEmitter.off(i,r),0===this._eventEmitter.listenerCount(i)&&(n?.then((e=>e.disposeAsync?.())).catch(My),this._handles.delete(i))}}}async changedAsync(e){const t="changed";let i=this._handles.get(t);if(void 0===i){const e=(...e)=>{this._eventEmitter.emit(t,...e)};i=this._proxyCall("changedAsync",[e]),this._handles.set(t,i)}const n=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,n),await i,{dispose:()=>{this._eventEmitter.off(t,n),0===this._eventEmitter.listenerCount(t)&&(i?.then((e=>e.disposeAsync?.())).catch(My),this._handles.delete(t))}}}async onAsync(e,t){const i=`on_${e}`;let n=this._handles.get(i);if(void 0===n){const t=(...e)=>{this._eventEmitter.emit(i,...e)};n=this._proxyCall("onAsync",[e,t]),this._handles.set(i,n)}const r=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(i,r),await n,{dispose:()=>{this._eventEmitter.off(i,r),0===this._eventEmitter.listenerCount(i)&&(n?.then((e=>e.disposeAsync?.())).catch(My),this._handles.delete(i))}}}}class qO extends GO{constructor(e,t){super(e,t),e.once("remoteStackTerminated",(()=>{this._eventEmitter.emit("changed"),this._eventEmitter.emit("on_callStateChanged")}))}get state(){return this._proxyReferenceManager.isRemoteStackActive()?this._tsObject.state:7}get callEndDiagnosticsInfo(){return this._proxyReferenceManager.isRemoteStackActive()||7===this._tsObject.state?this._tsObject.callEndDiagnosticsInfo:{callControllerCode:0,callControllerSubCode:4521,phrase:"call ended due to RDP disconnection",resultCategories:["ExpectedError"]}}get ptzHandler(){throw new le({defaultError:ee.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get broadcastMeeting(){throw new le({defaultError:ee.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get videoLayout(){throw new le({defaultError:ee.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}getIncomingRawAudioStream(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUnmixedAudioProvider(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}init(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setDeviceManager(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}forceUpdate(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}startVideo(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e,t,i,n){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}changeCropRegion(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}callSafeTransfer(e,t,i){return void 0===i&&(i={disableForwardingAndUnanswered:!1}),this._tsObject.callSafeTransfer(e,t,i)}setPlatformCallConstraints(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStage(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendLastKnownStats(){this._proxyReferenceManager.isRemoteStackActive()&&this._tsObject.sendLastKnownStats().catch((e=>{}))}}class zO extends GO{constructor(e,t){super(e,t)}getSourceIdForMediaType(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}class WO extends GO{constructor(e,t){super(e,t)}getRawStream(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}start(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}stop(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectVideoTrack(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoStreamConfig(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getStats(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}class KO extends GO{constructor(e,t){super(e,t),this._deletedCalls=[]}get calls(){return Z.difference(this._tsObject.calls,this._deletedCalls)}updateSkypeToken(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCall(e,t,i){return this._tsObject.calls.find((t=>t.callId===e))}createDownloader(e,t,i,n,r){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCall(e,t,i,n,r){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithGroupId(e,t,i,n){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithMeetingData(e,t,i,n){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}deleteCall(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}async deleteCallAsync(e,t,i){return this._proxyReferenceManager.isRemoteStackActive()?await(this._tsObject.deleteCallAsync?.apply(this._tsObject,arguments))??!1:!(!e||!this._tsObject.calls.includes(e)||(this._deletedCalls.push(e),this._eventEmitter.emit("on_callRemoved",e),0))}enableWindowUninitEventHandler(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}disableWindowUninitEventHandler(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}class JO extends GO{constructor(e,t){super(e,t)}getPermissionState(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectDevices(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSelectedDevices(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreview(e,t,i,n){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreviewRenderer(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createScreenSharingPreviewRenderer(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setBackgroundImageAsync(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getImagePropertyAsync(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}transformImageAsync(e,t,i,n){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoEffectsAsync(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoExtensibilityAsync(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoCaptureConfigAsync(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}captureVideoFrameWithoutEffectsAsync(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getRawDeviceMediaStream(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setRawMediaStream(e,t,i){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}unsetRawMediaStream(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAudioRenderer(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getPersonalizedNoiseSuppression(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}class YO extends GO{constructor(e,t){super(e,t)}getPlatformSupportLevel(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setPlatformCallConstraints(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCompositor(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallRegistry(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}cancelOperation(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDeviceManager(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createDeviceManager(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getScreenSharingManager(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getEcsProvider(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallFeedback(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getAiMdp(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVersion(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getMediaStatus(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVideoCapabilityLimits(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}fireIntent(e,t){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAllowPrivacySensitiveApis(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getLiveStreamClient(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUmsStream(e){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createVoipCallCoordinator(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDebugDump(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAiCameraManager(){throw new le({defaultError:ee.FEATURES.VDI3.METHOD_UNAVAILABLE})}}class QO extends $O{constructor(e){super(),this._logger=e.createChild("TsProxyReferenceManager"),this._mmrRdpConnectionManager=new LD(this._logger),this._mmrRdpConnectionManager.on("stateChange",(e=>{"disconnected"==e&&this._remoteStackTerminated()}))}static create(e){const t=new QO(e);return this.proxyReferenceManagers.add(t),t}static notifyRemoteStackTermination(){this.proxyReferenceManagers.forEach((e=>{e._remoteStackTerminated()}))}dispose(){this._mmrRdpConnectionManager.dispose(),QO.proxyReferenceManagers.delete(this),super.dispose()}_remoteStackTerminated(){!1!==this._isRemoteStackActive&&(this._logger.warn("remote stack is terminated"),this._isRemoteStackActive=!1,this._eventEmitter.emit("remoteStackTerminated"))}_createProxy(e){const t=AI(e);if(t!==EI.None){if(t===EI.ICall)return jO(e,new qO(this,e),this);if(t===EI.ICallParticipant)return jO(e,new zO(this,e),this);if(t===EI.ICallParticipantStream)return jO(e,new WO(this,e),this);if(t===EI.ICallRegistry)return jO(e,new KO(this,e),this);if(t===EI.IPluginlessCallingStack)return jO(e,new YO(this,e),this);if(t===EI.IDeviceManager)return jO(e,new JO(this,e),this)}}isSupportedType(e){return AI(e)!==EI.None}isRemoteStackActive(){if(void 0===this._isRemoteStackActive){const e=AO.monitor.getStat();if(!e.sessionInitializedAt)return!1;e.lastSesstionTerminatedAt&&e.lastSesstionTerminatedAt>e.sessionInitializedAt?(this._isRemoteStackActive=!1,this._eventEmitter.emit("remoteStackTerminated")):this._isRemoteStackActive=!0}return this._isRemoteStackActive}}QO.proxyReferenceManagers=new Set,AO.monitor.onConnectionTerminated((()=>{QO.notifyRemoteStackTermination()}));class ZO{constructor(){this._eventEmitter=new OE.EventEmitter,this._shellTrouter=new AO.ShellTrouter,this._state=MO.TrouterState.Unknown,this._disposeAsync=[]}async initialize(){const e=(e,t)=>{this._state=e,this._eventEmitter.emit("stateChanged",e,t)};await this._shellTrouter.onStateChanged(e),this._disposeAsync.push((async()=>{await this._shellTrouter.offStateChanged(e)}))}on(e,t){this._eventEmitter.on("stateChanged",t)}off(e,t){this._eventEmitter.off("stateChanged",t)}async dispose(){for(const e of this._disposeAsync)await e();this._eventEmitter.removeAllListeners()}state(){return this._state}get instance(){return this._shellTrouter}}var XO,eN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this._isAllowed=!1}return e.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},e.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},e.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?W.Resolved():(this._isAllowedDeferral||(this._isAllowedDeferral=W.Defer()),this._isAllowedDeferral.promise())},e}();t.default=i})),tN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this._isActive=!1}return e.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},e.prototype.isAppActive=function(){return this._isActive},e.prototype.waitForAppActive=function(){return this.isAppActive()?W.Resolved():(this._appActiveDeferral||(this._appActiveDeferral=W.Defer()),this._appActiveDeferral.promise())},e}();t.default=i})),iN=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),nN=function(){function e(e){void 0===e&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];for(var n=t._subscribers,r=n.length-1;r>=0;r--){var s=n[r].apply(null,e);if(t._allowStopPropagation&&s)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new iN(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),rN=Object.freeze({__proto__:null,SubscriptionToken:iN,default:nN}),sN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Default=0]="Default",e[e.User=1]="User"}(t.EcsConfigType||(t.EcsConfigType={}))})),aN=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})})),t}(rN),oN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._config=e,this.configUpdated=new aN.default,this._cachedConfigs={}}return e.prototype.initialize=function(){return this.updateConfigsToFetch()},e.prototype.updateConfigsToFetch=function(){var e=this,t=this._config.getConfig(),i=t.databaseInterface,n=t.configsToFetch;if(!i)return W.Resolved();for(var r=[],s=function(t){if(a._cachedConfigs[t])return"continue";r.push(i.getData(t).then((function(i){i&&(e._cachedConfigs[t]=i)})).catch((function(){return W.Resolved()})))},a=this,o=0,l=n;o<l.length;o++)s(l[o]);return W.all(r).then((function(){r.length>0&&e.configUpdated.fire()}))},e.prototype.getEcsConfig=function(){return this._cachedConfigs[sN.EcsConfigType.User]||this._cachedConfigs[sN.EcsConfigType.Default]},e.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},e.prototype.putConfig=function(e){var t=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var i=this.getEcsConfig();(i&&i.configType===e.configType||t&&i&&t.configType!==i.configType)&&this.configUpdated.fire();var n=this._config.getConfig().databaseInterface;return n?n.putData(e.configType,e):W.Resolved()},e}();t.default=i})),lN=G((function(e,t){var i=j&&j.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){}return e.prototype.initialize=function(e){if(this._config)throw new Error("ECS Configuration already initialized");this._config=e},e.prototype.getConfig=function(){if(!this._config)throw new Error("ECS Configuration not yet initialized");return this._config},e.prototype.setConfigsToFetch=function(e){if(!this._config)throw new Error("ECS Configuration not yet initialized");this._config=i(i({},this._config),{configsToFetch:e})},e.prototype.setFetchTimeout=function(e){if(!this._config)throw new Error("ECS Configuration not yet initialized");this._config=i(i({},this._config),{fetchTimeout:e})},e}();t.default=n})),cN=G((function(e,t){var i=j&&j.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.assert=function(e,t){if(!e)throw new Error(t)},t.isObject=function(e){return null!==e&&"object"==typeof e},t.isString=function(e){return"string"==typeof e},t.attempt=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];try{return e.apply(void 0,t)}catch(e){return new Error(e)}},t.remove=function(e,t){for(var i=e.length-1;i>=0;i--)e[i]===t&&e.splice(i,1)},t.clone=function(e){return Array.isArray(e)?e.map(t.clone):t.isObject(e)?Object.keys(e).reduce((function(n,r){var s;return i(i({},n),((s={})[r]=t.clone(e[r]),s))}),{}):e}})),dN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,t.DEFAULT_TIME_JITTER=.11962656472;var i=function(){function e(e,i,n,r){void 0===n&&(n=t.DEFAULT_TIME_GROW_FACTOR),void 0===r&&(r=t.DEFAULT_TIME_JITTER),this._initialTime=e,this._maxTime=i,this._growFactor=n,this._jitterFactor=r,cN.assert(this._initialTime>0,"Initial delay must be positive"),cN.assert(this._maxTime>0,"Delay upper bound must be positive"),cN.assert(this._growFactor>=0,"Ratio must be non-negative"),cN.assert(this._jitterFactor>=0,"Jitter factor must be non-negative"),this.reset()}return e.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},e.prototype.getTime=function(){return this._currentTime},e.prototype.getIncrementCount=function(){return this._incrementCount},e.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},e.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},e}();t.ExponentialTime=i})),uN=G((function(e,t){var i,n,r,s=j&&j.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),a=j&&j.__assign||function(){return a=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)};function o(e){return!!e&&0===e.indexOf("application/json")}function l(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?r.DoNotRetry:r.RetryCountedWithBackoff}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.DontCare=0]="DontCare",e[e.Low=1]="Low",e[e.Normal=2]="Normal",e[e.High=3]="High",e[e.Critical=4]="Critical"}(n=t.WebRequestPriority||(t.WebRequestPriority={})),function(e){e[e.DoNotRetry=0]="DoNotRetry",e[e.RetryUncountedImmediately=1]="RetryUncountedImmediately",e[e.RetryUncountedWithBackoff=2]="RetryUncountedWithBackoff",e[e.RetryCountedWithBackoff=3]="RetryCountedWithBackoff",e[e.PauseUntilResumed=4]="PauseUntilResumed"}(r=t.ErrorHandlingType||(t.ErrorHandlingType={})),t.DefaultOptions={priority:n.Normal},t.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},t.DefaultErrorHandler=l;var c,d=[],u=[],h=[],g=0,p=0,m=function(){function e(e,i,n,r,s){this._action=e,this._url=i,this.options=n,this._getHeaders=r,this._blockRequestUntil=s,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new dN.ExponentialTime(1e3,3e5),this._options=a(a({},t.DefaultOptions),n)}return e.prototype.getPriority=function(){return this._options.priority||n.DontCare},e.checkQueueProcessing=function(){for(var e=function(){var e=d.shift();u.push(e),(e._blockRequestUntil&&e._blockRequestUntil()||W.Resolved()).finally((function(){cN.remove(u,e)})).then((function(){h.length<t.SimpleWebRequestOptions.MaxSimultaneousRequests&&!e._aborted?(h.push(e),f._scheduleHungRequestCleanupIfNeeded(),e._fire()):e._enqueue()}),(function(t){e._respond("_blockRequestUntil rejected: "+t)}))};d.length>0&&h.length<t.SimpleWebRequestOptions.MaxSimultaneousRequests;)e()},e._scheduleHungRequestCleanupIfNeeded=function(){h.length>0&&void 0===c?c=t.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,t.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):0===h.length&&c&&(t.SimpleWebRequestOptions.clearTimeout(c),c=void 0)},e.prototype._removeFromQueue=function(){cN.remove(h,this),cN.remove(d,this)},e.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),cN.assert(e,t))},e.prototype._fire=function(){var i=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var n=cN.attempt((function(){i._xhr.open(i._action,i._url,!0)}));if(n)this._respond(n.toString());else{if(this._options.timeout){var r=p;3!==r&&(this._assertAndClean(!this._requestTimeoutTimer,"Double-fired requestTimeoutTimer"),this._requestTimeoutTimer=t.SimpleWebRequestOptions.setTimeout((function(){i._requestTimeoutTimer=void 0,i._timedOut=!0,i.abort()}),this._options.timeout)),(3===r||r<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){p=3,3===r&&(i._timedOut=!0,i._aborted=!0,i._respond("TimedOut"))})}var s=g;3!==s?(0===s&&(g=1),this._xhr.onreadystatechange=function(){i._xhr&&(3!==i._xhr.readyState||!i._options.streamingDownloadProgress||i._aborted?4===i._xhr.readyState&&(0===s&&1===g&&t.SimpleWebRequestOptions.setTimeout((function(){3!==g&&(g=2)}),1e4),i._respond()):i._options.streamingDownloadProgress(i._xhr.responseText))}):this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){i._xhr&&3===i._xhr.readyState&&i._options.streamingDownloadProgress&&!i._aborted&&i._options.streamingDownloadProgress(i._xhr.responseText)}),2!==s&&(this._xhr.onload=function(){g=3,3===s&&i._respond()},this._xhr.onerror=function(){g=3,3===s&&i._respond()}),this._xhr.onabort=function(){i._aborted=!0,i._respond("Aborted")},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var a=this._options.acceptType||"json",o=this._options.customResponseType||e._getResponseType(a),l=cN.attempt((function(){i._xhr.responseType=o}));if(l&&"json"!==o)throw l;f._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Accept",e.mapContentType(a)),this._xhr.withCredentials=!!this._options.withCredentials;var c=this.getRequestHeaders(),d={};if(Object.keys(c).forEach((function(e){var t=c[e],n=e.toLowerCase();"content-type"!==n?"accept"!==n?(i._assertAndClean(!d[n],"Setting duplicate header key: "+d[n]+" and "+e),null!=t?(d[n]=!0,f._setRequestHeader(i._xhr,i._xhrRequestHeaders,e,t)):console.warn('Tried to set header "'+e+'" on request with "'+t+'" value, header will be dropped')):i._assertAndClean(!1,"Don't set Accept with options.headers -- use it with the options.acceptType property"):i._assertAndClean(!1,"Don't set Content-Type with options.headers -- use it with the options.contentType property")})),this._options.sendData){var u=e.mapContentType(this._options.contentType||"json");f._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Content-Type",u);var h=e.mapBody(this._options.sendData,u);this._xhr.send(h)}else this._xhr.send()}},e._setRequestHeader=function(e,t,i,n){e.setRequestHeader(i,n),t[i]=n},e.mapContentType=function(e){return"json"===e?"application/json":"form"===e?"application/x-www-form-urlencoded":e},e.mapBody=function(e,t){if(o(t)){if(!cN.isString(e))return JSON.stringify(e)}else if(function(e){return!!e&&0===e.indexOf("application/x-www-form-urlencoded")}(t)){if(!cN.isString(e)&&cN.isObject(e)){var i=e;return Object.keys(i).map((function(e){return encodeURIComponent(e)+(i[e]?"="+encodeURIComponent(i[e].toString()):"")})).join("&")}}else if(function(e){return!!e&&0===e.indexOf("multipart/form-data")}(t)){if(cN.isObject(e)){var n=new FormData,r=e;return Object.keys(r).forEach((function(e){return n.append(e,r[e])})),n}cN.assert(!1,"contentType multipart/form-data must include an object as sendData")}return e},e.prototype.setUrl=function(e){this._url=e},e.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},e.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=a(a({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=a(a({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=a(a({},e),this._options.headers)),this._options.augmentHeaders&&(e=a(a({},e),this._options.augmentHeaders)),e},e.prototype.getOptions=function(){return cN.clone(this._options)},e.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(cN.remove(d,this),this._enqueue()))},e.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):cN.assert(!1,"resumeRetrying() called but not paused!")},e.prototype._enqueue=function(){var t=this;if(!this._aborted&&!(h.indexOf(this)>=0||u.indexOf(this)>=0||d.indexOf(this)>=0)){var i=d.findIndex((function(e){return e.getPriority()===t.getPriority()&&e._created>t._created||e.getPriority()<t.getPriority()}));i>-1?d.splice(i,0,this):d.push(this),e.checkQueueProcessing()}},e._getResponseType=function(e){return"blob"===e?"arraybuffer":"text/xml"===e||"application/xml"===e?"document":"text/plain"===e?"text":"json"},e._hungRequestCleanupTimerCallback=function(){c=void 0,h.filter((function(e){return!(!e._xhr||4!==e._xhr.readyState||(console.warn("SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding"),0))})).forEach((function(e){e._respond()})),f._scheduleHungRequestCleanupIfNeeded()},e}();t.SimpleWebRequestBase=m;var f=function(e){function i(t,i,n,r,s){return e.call(this,t,i,n,r,s)||this}return s(i,e),i.prototype.abort=function(){this._aborted?cN.assert(!1,"Already aborted "+this._action+" request to "+this._url):(this._aborted=!0,this._retryTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0),this._deferred?(this._respond("Aborted"),this._xhr&&this._xhr.abort()):cN.assert(!1,"Haven't even fired start() yet -- can't abort"))},i.prototype.start=function(){var e=this;return this._deferred?(cN.assert(!1,"WebRequest already started"),W.Rejected("WebRequest already started")):(this._deferred=W.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},i.prototype._respond=function(e){var i=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0);var n,s=0;if(this._xhr)try{s=this._xhr.status,n=this._xhr.statusText||e}catch(e){}else n=e||"Browser Error - Possible CORS or Connectivity Issue";var a,c,d={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||"").split(/\r?\n/).forEach((function(e){if(0!==e.length){var t=e.indexOf(":");-1===t?d[e]="":d[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!d["content-type"]){var u=this._xhr.getResponseHeader("content-type");u&&(d["content-type"]=u)}if(a=this._xhr.response,d["content-type"]&&o(d["content-type"])&&(!a||!cN.isObject(a))&&("text"===this._xhr.responseType||""===this._xhr.responseType)&&this._xhr.responseText)try{a=JSON.parse(this._xhr.responseText)}catch(e){c=e,console.warn("Failed to parse XHR JSON response")}}if(this._xhr&&4===this._xhr.readyState&&(s>=200&&s<300||304===s)){var h={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:s,statusText:n,headers:d,body:a,responseParsingException:c};this._deferred.resolve(h)}else{var g={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:s,statusText:n,headers:d,body:a,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:c};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(g);var p=this._options.customErrorHandler?this._options.customErrorHandler(this,g):l(0,g);p!==r.DoNotRetry&&(this._options.retries&&this._options.retries>0||p===r.PauseUntilResumed||p===r.RetryUncountedImmediately||p===r.RetryUncountedWithBackoff)?(p===r.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&(t.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),p===r.PauseUntilResumed?this._paused=!0:p===r.RetryUncountedImmediately?this._enqueue():this._retryTimer=t.SimpleWebRequestOptions.setTimeout((function(){i._retryTimer=void 0,i._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(g)}m.checkQueueProcessing()}},i}(m);t.SimpleWebRequest=f})),hN=G((function(e,t){var i=j&&j.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return e.prototype._performApiCall=function(e,t,n,r){var s=this;void 0===r&&(r={});var a=i(i({},this._defaultOptions),r);n&&(a.sendData=n),a.eTag&&(a.augmentHeaders||(a.augmentHeaders={}),a.augmentHeaders["If-None-Match"]=a.eTag),a.contentType||(a.contentType=cN.isString(a.sendData)?"form":"json");var o=a.excludeEndpointUrl?e:this._endpointUrl+e;return new uN.SimpleWebRequest(t,o,a,(function(){return s._getHeaders(a)}),(function(){return s._blockRequestUntil(a)})).start().then((function(e){return s._processSuccessResponse(e),e}))},e.prototype._getHeaders=function(e){return{}},e.prototype._blockRequestUntil=function(e){},e.prototype._processSuccessResponse=function(e){},e.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},e.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,"GET",void 0,t)},e.prototype.performApiPost=function(e,t,i){return this.performApiPostDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPostDetailed=function(e,t,i){return this._performApiCall(e,"POST",t,i)},e.prototype.performApiPatch=function(e,t,i){return this.performApiPatchDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPatchDetailed=function(e,t,i){return this._performApiCall(e,"PATCH",t,i)},e.prototype.performApiPut=function(e,t,i){return this.performApiPutDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPutDetailed=function(e,t,i){return this._performApiCall(e,"PUT",t,i)},e.prototype.performApiDelete=function(e,t,i){return this.performApiDeleteDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiDeleteDetailed=function(e,t,i){return this._performApiCall(e,"DELETE",t,i)},e}();t.GenericRestClient=n})),gN=G((function(e,t){function i(e){for(var i in e)t.hasOwnProperty(i)||(t[i]=e[i])}Object.defineProperty(t,"__esModule",{value:!0}),i(dN),i(hN),i(uN)})),pN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:"ecs_client"}},e}();t.TelemetryEventBase=i})),mN=G((function(e,t){var i,n=j&&j.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r=function(e){function t(t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v){var S=e.call(this)||this;return S._responseTime=t,S._responseCode=i,S._fetchAttempts=n,S._hasValidToken=r,S._serverEndpoint=s,S._fetchDurationValid=a,S._cacheAvailable=o,S._responseSize=l,S._configAge=c,S._configExpired=d,S._fetchStart=u,S._fetchEnd=h,S._isUserConfig=g,S._etag=p,S._timedOut=m,S._responseParsingException=f,S._errorMessage=v,S}return n(t,e),t.prototype.getEventName=function(){return"ecs_tsclient_fetch_config"},t.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t.is_user_config=this._isUserConfig,this._etag&&(t.fetched_etag=this._etag),void 0!==this._timedOut&&(t.fetch_timed_out=this._timedOut),this._responseParsingException&&(t.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(t.fetch_error_message=this._errorMessage),t},t}(pN.TelemetryEventBase);t.EcsConfigFetchResponse=r})),fN=G((function(e,t){var i,n=j&&j.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),r=j&&j.__assign||function(){return r=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},r.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var s,a,o=function(e){function t(t,i,n,r,s,a,o,l){var c=e.call(this,t)||this;c._config=i,c._skypeTokenData=n,c._appActiveData=r,c._allowBackgroundFetchData=s,c._etag=a,c._getUserConfig=o;var d=c._config.getConfig();if(c._apiPath=d.clientTeam?"/config/v1/"+d.clientName+"/"+d.clientVersion+"/"+d.clientTeam:"/config/v1/"+d.clientName+"/"+d.clientVersion,l){var u=Object.keys(l).map((function(e){return encodeURIComponent(e)+"="+encodeURIComponent(l[e].toString())}));u&&(c._apiPath+="?"+u.join("&"))}return c}return n(t,e),t.prototype._blockRequestUntil=function(e){var t=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 i=this._getUserConfig?"User config":"config";console.log("ECS - Delaying "+i+" fetch until the app is active (or background fetch is allowed)")}return W.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){a=Date.now()}))},t.prototype._getHeaders=function(){var e={};return this._etag&&(e["If-None-Match"]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},t.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return void 0!==t&&(t<0?t=0:t>0&&t<3e4&&(t=3e4)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},t}(gN.GenericRestClient),l=function(){function e(e,t,i,n,r){this._config=e,this._skypeTokenData=t,this._appActiveData=i,this._allowBackgroundFetchData=n,this._telemetryManager=r,this._ecsFailureBackoffTimer=new gN.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,i){var n=this,s=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>s.length-1)&&(this._serverIndex=Math.floor(Math.random()*s.length)),!s||!s.length)return W.Rejected(new Error("no configuration service endpoint"));var l=W.Defer(),c=0,d=function(){var u=e&&e.eTag?e.eTag:void 0,h=new o(s[n._serverIndex],n._config,n._skypeTokenData,n._appActiveData,n._allowBackgroundFetchData,u,t,i);c++,h.getConfig().then((function(i){var o=i.headers.etag,d=i.headers.expires;i.body&&i.body.Headers&&(o||(o=i.body.Headers.ETag),d||(d=i.body.Headers.Expires));var h=n._calculateResponseTimeInfo(e);if(!o||!d)return console.warn("ECS - Service returned an empty ETag or Expiration header: "+JSON.stringify(i)),W.Rejected({timedOut:!1,responseParsingException:new Error("ECS Service returned empty ETag or Expiration header"),responseCode:i.statusCode});var g,p=new Date(n._calculateExpirationDate(i.headers)).getTime();if(304===i.statusCode&&e)(g=r({},e)).configType=t?sN.EcsConfigType.User:sN.EcsConfigType.Default,g.eTag=o,g.expiration=p,g.cacheUpdateTime=h.lastResponseTime,g.lastFetchTokenHash=n._skypeTokenData.getSkypeTokenHash(i.requestHeaders.Authorization);else{if("object"!=typeof i.body)return console.warn("ECS - Service returned invalid response "+JSON.stringify(i)),W.Rejected({timedOut:!1,responseParsingException:new Error("ECS Service returned invalid response body"),responseCode:i.statusCode});g={config:i.body,configType:t?sN.EcsConfigType.User:sN.EcsConfigType.Default,eTag:o,expiration:p,cacheUpdateTime:a,lastFetchTokenHash:n._skypeTokenData.getSkypeTokenHash(i.requestHeaders.Authorization),appVersion:n._config.getConfig().clientVersion}}n._telemetryManager.sendTelemetryEvent(new mN.EcsConfigFetchResponse(h.fetchDelayMs,i.statusCode,c,n._skypeTokenData.isSkypeTokenValid(),s[n._serverIndex],h.fetchDurationValid,!!u,JSON.stringify(i).length,h.cacheAge,!(e&&e.expiration-Date.now()>0),a,h.lastResponseTime,t,o)),n._ecsFailureBackoffTimer.reset(),l.resolve(g)})).catch((function(i){var r={timedOut:i&&i.timedOut||!1,responseParseError:i&&i.responseParsingException,responseCode:i&&i.statusCode||0,message:n._getErrorMessage(i)};console.error("ECS - Service request failed to return a response (timedOut: "+r.timedOut+", responseParseError: "+r.responseParseError+")");var o=n._calculateResponseTimeInfo(e);n._telemetryManager.sendTelemetryEvent(new mN.EcsConfigFetchResponse(o.fetchDelayMs,r.responseCode,c,n._skypeTokenData.isSkypeTokenValid(),s[n._serverIndex],o.fetchDurationValid,!!u,0,o.cacheAge,!(e&&e.expiration-Date.now()>0),a,o.lastResponseTime,t,void 0,r.timedOut,r.responseParseError,r.message));var l=n._config.getConfig().fetchAttemptMax;l&&c>l||setTimeout((function(){d()}),n._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return d(),l.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+1728e5;if(e.date&&e.expires){var i=new Date(e.date).getTime(),n=Date.now()-i,r=new Date(e.expires).getTime();return isNaN(r)?t:Math.min(t,r+n)}var s=this._cacheMaxAgeRegex.exec(e["cache-control"]);return this._cacheMaxAgeRegex.lastIndex=0,s&&2===s.length?Math.min(t,Date.now()+1e3*Number(s[1])):Date.now()+18e5},e.prototype._calculateResponseTimeInfo=function(e){var t=(s=Date.now())-a;return{lastResponseTime:s,fetchDelayMs:t,fetchDurationValid:!(t<0||t>31536e6),cacheAge:e?s-e.cacheUpdateTime:0}},e.prototype._getErrorMessage=function(e){if(e)return"string"==typeof e?e:"object"==typeof e&&(e.statusText||e.message)?e.statusText||e.message:void 0},e}();t.default=l})),vN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t,i,n,r,s){var a=this;this._config=e,this._skypeTokenData=t,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(e){var t,i=a._config.getConfig(),n=a._cache.getEcsConfigByType(e);if(-1!==i.configsToFetch.indexOf(e)&&!a._isFetchingSettings[e])if(n||!a._pendingFetch[e]){var r=n?n.expiration-Date.now():-1;r<=0||n&&e===sN.EcsConfigType.User&&a._skypeTokenData.isSkypeTokenValid()&&n.lastFetchTokenHash!==a._skypeTokenData.getSkypeTokenHash(a._skypeTokenData.getSkypeToken())?a._fetchSkypeEcsSettings(e):(null===(t=i.Killswitches)||void 0===t?void 0:t.isSkypeTokenDataLeakFixEnabled)?(a._pendingTimers[e]>0&&clearTimeout(a._pendingTimers[e]),a._pendingTimers[e]=window.setTimeout((function(){return a._fetchEcsSettingsIfNeeded(e)}),r)):window.setTimeout((function(){return a._fetchEcsSettingsIfNeeded(e)}),r)}else a._fetchSkypeEcsSettings(e)},this._fetchSkypeEcsSettings=function(e,t){void 0===t&&(t=!1),a._isFetchingSettings[e]||a._paused&&!t?a._pendingFetch[e]=!0:(a._pendingFetch[e]=!1,a._isFetchingSettings[e]=!0,a._config.getConfig().getEcsParameters().catch((function(){return console.warn("ECS - Failed to fetch ECS fetching parameters"),{}})).then((function(t){return a._ecsClient.getConfig(a._cache.getEcsConfig(),e===sN.EcsConfigType.User,t)})).then((function(t){console.log("ECS - Config fetch complete"),a._isFetchingSettings[e]=!1,a._cache.putConfig(t),a._fetchEcsSettingsIfNeeded(e)})))},this._ecsClient=new fN.default(this._config,this._skypeTokenData,n,r,s)}return e.prototype.initialize=function(){var e=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return e._fetchEcsSettingsIfNeeded(sN.EcsConfigType.User)}))},e.prototype.dispose=function(){var e,t,i=this._config.getConfig();if(null===(e=i.Killswitches)||void 0===e?void 0:e.isSkypeTokenDataLeakFixEnabled){for(var n=0,r=i.configsToFetch;n<r.length;n++){var s=r[n];clearTimeout(this._pendingTimers[s]),this._pendingTimers[s]=0}null===(t=this._subscriptionToken)||void 0===t||t.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},e.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,i=e.configsToFetch;t<i.length;t++)(s=i[t])in this._isFetchingSettings||(this._isFetchingSettings[s]=!1),s in this._isFetchingSettings||(this._pendingFetch[s]=!1);for(var n=0,r=e.configsToFetch;n<r.length;n++){var s=r[n],a=this._cache.getEcsConfigByType(s);!a||a.appVersion&&a.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(s,!0):this._fetchEcsSettingsIfNeeded(s)}},e.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var i=t[e];this._fetchSkypeEcsSettings(i)}},e.prototype.pause=function(){this._paused=!0},e.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var i=t[e];this._fetchEcsSettingsIfNeeded(i)}},e}();t.default=i})),SN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this.skypeTokenChanged=new aN.default}return e.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},e.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},e.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw new Error("No Skype Token provided");return e.skypeToken},e.prototype.getSkypeTokenHash=function(e){return void 0===e?0:e.split("").reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},e.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?W.Resolved():(this._validSkypeTokenDeferral||(this._validSkypeTokenDeferral=W.Defer()),this._validSkypeTokenDeferral.promise())},e}();t.default=i})),yN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._cache=e,this.telemetryEventAdded=new aN.default}return e.prototype.sendTelemetryEvent=function(t){var i=t.getEventName(),n=t.getAttributes(),r=!1,s=this._cache.getEcsConfig();if(s){if(e._containsEcsClientTelemetryConfig(s.config)){var a=s.config.ECSCONFIG;a&&a.ecsClientTelemetry&&(r=!!a.ecsClientTelemetry[i])}}else console.warn("No previously cached ECS telemetry config exists - fallback to sending event"),r=!0;r&&this.telemetryEventAdded.fire(i,n)},e._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},e}();t.default=i})),CN=G((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Models=sN;var i=function(){function e(){this._allowBackgroundFetchData=new eN.default,this._appActiveData=new tN.default,this._config=new lN.default,this._cache=new oN.default(this._config),this._skypeTokenData=new SN.default,this._telemetryManager=new yN.default(this._cache),this._scheduler=new vN.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return e.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},e.prototype.dispose=function(){var e;(null===(e=this._config.getConfig().Killswitches)||void 0===e?void 0:e.isSkypeTokenDataLeakFixEnabled)&&this._scheduler.dispose()},e.prototype.getConfig=function(){return this._cache.getEcsConfig()},e.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},e.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},e.prototype.pause=function(){this._scheduler.pause()},e.prototype.resume=function(){this._scheduler.resume()},e.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},e.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},e.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},e.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},e.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},e}();t.default=i})),TN=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(CN);function EN(e,t){const i={[Of.Public]:Cv,[Of.Dod]:Ev,[Of.GccHigh]:Tv,[Of.AirGap08]:bv,[Of.AirGap09]:_v};let n=Cv;return t&&(n=t.identityType===wv.Enterprise?Iv:i[t.cloudType]??Cv),e?.proxyfyUrl(n)??n}!function(e){e.Default="Default",e.User="User"}(XO||(XO={}));class bN{constructor(e,t,i){this._acsProxy=t,this._sourceTag=i,this._throttlingTimeoutHandle=0,this._eventEmitter=new OE.EventEmitter,this._logger=e.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(e){this._resetEcsClient(),this._resetThrottlingTimeout();const t=new TN,i=jT();try{await t.initialize(e);let n=[],r=!1,s=0;t.configUpdated.subscribe((()=>{if(i.isPending())i.resolve();else{n.push(Date.now());const e=t.getConfig();if(e?.config){const t=e?.configType===CN.Models.EcsConfigType.User?XO.User:XO.Default;this._cachedConfig=e,this._eventEmitter.emit("configUpdated",{config:e?.config,fetchType:t,sourceTag:this._sourceTag})}const i=vy().ecsClient.throttling;n.length>i.triggerCount&&(n=n.slice(n.length-i.triggerCount));const a=n[n.length-1]-n[0];r?(n.length<i.triggerCount||a>=i.coolDownDuration)&&(r=!1,s=0,n=[],this._resetThrottlingTimeout()):n.length===i.triggerCount&&a<i.triggerDuration&&(r=!0),r&&(s=0===s?i.startingDelay:Math.min(Math.ceil(s*i.delayFactor),i.maxDelay),t.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,t.resume()}),s))}})),this._ecsClient=t,await WT((()=>i.promise),7e3);const a=t.getConfig();if(!a?.config)throw new le({defaultError:ee.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=a,a.config}catch(e){throw i.reject(e),this._logger.error(`${e}`),e}}async fetchDefaultConfig(e,t){const i=`3617_${FS()}`,n={hosts:[EN(this._acsProxy,t)],clientName:Df,clientVersion:i,configsToFetch:[CN.Models.EcsConfigType.Default],getEcsParameters:()=>W.Resolved(e),initialAppActiveState:!0};return this._fetchConfig(n)}async fetchUserConfig(e,t,i){const n=`3617_${FS()}`,r=await i(),s=1e3*Py(r).exp,a={hosts:[EN(this._acsProxy,t)],clientName:Df,clientVersion:n,configsToFetch:[CN.Models.EcsConfigType.User],getEcsParameters:()=>W.Resolved(e),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:r,skypeTokenExpiration:s}};return this._fetchConfig(a)}get eTag(){return this._cachedConfig?.eTag??""}get sourceTag(){return this._sourceTag}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}getConfigIds(e){const t=this._cachedConfig?.config;return t?.ConfigIDs?.[e]}}class _N{constructor(e){this._telemetryLogManager=e,this._seq=0}sendAttemptEvent(e,t,i){this._seq++,this._telemetryLogManager.sendEvent({name:aE.acs_calling_config_fetched_attempt,tenant:xv,properties:{attemptTimestamp:e,ecsFetchType:t,correlationId:i,eventSeq:this._seq}})}sendSuccessEvent(e,t,i,n){const r=Date.now();this._seq++;const s=void 0!==e?r-e:0;this._telemetryLogManager.sendEvent({name:aE.acs_calling_config_fetched_success,tenant:xv,properties:{...void 0!==e?{attemptTimestamp:e}:void 0,successTimestamp:r,deltaTimeInMs:s,ecsFetchType:t,correlationId:i,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:n?.AcsCallingSDKWeb||"",ecsConfigIds_SkypeWebMedia:n?.SkypeWebMedia||""}})}sendFailureEvent(e,t,i,n){const r=Date.now();this._seq++;const s=void 0!==e?r-e:0,a=n.message,o=_b(n);this._telemetryLogManager.sendEvent({name:aE.acs_calling_config_fetched_failure,tenant:xv,properties:{...void 0!==e?{attemptTimestamp:e}:void 0,failureTimestamp:r,deltaTimeInMs:s,ecsFetchType:t,correlationId:i,eventSeq:this._seq,failureReason:a,additionalDetails:{...o}}})}}function IN(e,...t){Z.merge(e,...t)}var wN=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},AN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class PN{constructor(e,t,i,n,r,s,a){if(this._disposed=!1,this._trouterStateChangedListenersRegistered=new Map,this.clientId=t,this.sdkDiagnosticInformation=n,this.logger=e.createChild("CallStack"),this._telemetryLogManager=i,this._acsProxy=r,this._acsCustomRelayManager=s,this._webcvProvider=new LO,this._wasmvqeProvider=new VO,"https:"!==location.protocol&&"file:"!==location.protocol&&"localhost"!==location.hostname)throw new le({defaultError:ee.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new NO(this._telemetryLogManager),this._ecsTelemetryLogger=new _N(i),this._ecsProvider=new PO(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new bN(this.logger,this._acsProxy,"EcsClient"),this._ecsClient.on("configUpdated",(async e=>{try{await this.updateConfig(e.config,this.caConfigBag),this._ecsTelemetryLogger.sendSuccessEvent(void 0,e.fetchType,"",this.getEcsConfigIds());try{this._ecsProvider.assertConfigs(e.config)}catch(t){this._ecsTelemetryLogger.sendFailureEvent(void 0,e.fetchType,"",t)}}catch(t){const i=new le({defaultError:ee.CALL_STACK.PARSE_CONFIG,originalError:t});this._ecsTelemetryLogger.sendFailureEvent(void 0,e.fetchType,"",i)}})),this._videoEffectsStatusManager=new UO,this._audioEffectsStatusManager=new BO,void 0!==a&&(this._encodedStreamsWorkerProvider=new xO(a))}getClientId(){return this.clientId}getTrouterState(){const e=this._trouterService?.state()??this._shellTrouter?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return{AcsCallingSDKWeb:this._ecsClient?.getConfigIds("AcsCallingSDKWeb")??"",SkypeWebMedia:this._ecsClient?.getConfigIds("SkypeWebMedia")??""}}isRegistered(){return this._trouterService?.isRegistered()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e)}onTrouterStateChanged(e){const t=(t,i)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._shellTrouter?.on("stateChanged",t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){const t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._shellTrouter?.off("stateChanged",t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t="Uninitialized";if(void 0!==e)switch(e){case 0:t="Unknown";break;case 2:t="Connected";break;case 3:t="Disconnected";break;case 9:t="Switching"}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;const t=new Promise((async(t,i)=>{try{const i=this._getBaseStackConfig();if(navigator.mediaDevices?.tsCallingChannel){this._shellTrouter=new ZO;const e=function(e){const t=vy().vdi3;let i=t.cdnUrl;if(!i){const e=t.customTsVersion||X.getVersion();if(e.includes("_"))throw new le({defaultError:ee.FEATURES.VDI3.INVALID_CDN_URL});i=`${t.cdnBaseUrl}${e}/`}const n=new URL(t.loaderHtmlPath,i).toString(),r=new URL(t.pluginlessJsPath,i).toString();return{vdi3Config:{transport:AO.tsCallingChannel({transportConnectionTimeout:t.transportConnectionTimeoutInMs,remoteExecutionTimeout:t.remoteExecutionTimeoutInMs,messageConfig:{chunkSize:t.chunkSize},tsCallingChannel:{connectionUrl:n}},e),trouterSettings:{},pluginlessUrl:r,cdnUrl:i}}}(this.logger);e.vdi3Config&&(e.vdi3Config.shellTrouter=this._shellTrouter.instance),this._proxyReferenceManager=QO.create(this.logger);const t=await AO.stackFactory.buildBaseStack({stackType:1,...i,...e});this._tsStack=this._proxyReferenceManager.create(t)}else this._tsStack=await AO.stackFactory.buildBaseStack({stackType:0,...i});await this.initializeEcsBase(e),t(this._tsStack)}catch(e){i(e)}}));try{this._createStackBaseWaitPromise=WT((()=>t),5e4);const e=await this._createStackBaseWaitPromise;return this.logger.log("Base stack init success"),e}catch(e){throw await this.dispose(),408===e.code?new le({defaultError:ee.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new le({defaultError:ee.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this.caConfigBag=t,this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._tsStack=await this.createStackBase(t),this._disposed=!1;const i=new Promise((async(i,a)=>{try{this._tsStack?(this._ecsProvider=new PO(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsBase(t),await this.initializeEcsForUser(t,e),_I.overrideDefaultLogDump(),MI(this._tsStack)||(vy().calling.doNotWaitForTrouter?this._initTrouter(e).catch((()=>{this.logger.warn(ee.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):await this._initTrouter(e)),this.logger.log("Signaling initialized successfully."),await n(e,this._tsStack),await r(e,this._tsStack),await s(this._tsStack),i(this._tsStack)):(this.logger.error("Base stack failed to create"),a(new le({defaultError:ee.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){a(e)}})),n=async(e,t)=>{try{if(await t.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{const e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),vy().calling.platformSupportValidation&&0===await t.getPlatformSupportLevelAsync()){const e=new le({defaultError:ee.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(e.message),e}}catch(e){throw this.logger.error("Failed to initialize media stack",e),new le({defaultError:ee.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:e})}},r=async(e,t)=>{try{const i=MI(t),n={signalingAgentConfig:this._getSignalingConfig(e),...i?{trouterSettings:kO(this._ecsProvider),trouterService:{}}:{trouterService:this._trouterService}};await t.initializeSignalingAgentProvider(n),i&&await(this._shellTrouter?.initialize())}catch(e){throw this.logger.error("Failed to initialize signaling agent",e),new le({defaultError:ee.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:e})}},s=async e=>{try{await e.init()}catch(e){throw this.logger.error("Failed to initialize calling stack",e),new le({defaultError:ee.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeStackForUserWaitPromise=WT((()=>i),3e4);const e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log("User stack init success"),e}catch(e){if(await this.dispose(),408===e.code)throw this.sendStackInitEvent(!1,"User stack init timeout",e),new le({defaultError:ee.CALL_STACK.USER_STACK_INIT_TIMEOUT});if(!(e instanceof le)&&"Uninitialized"===this.getTrouterState())throw new le({defaultError:ee.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:e});throw this.sendStackInitEvent(!1,"User stack init failed",e),new le({defaultError:ee.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e})}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info("Using custom proxy for network requests (non media)"),new FO(this.logger,this._acsProxy)):vy().telemetry.sendNetworkInfo?new FO(this.logger):new X.HttpRequestDispatcherImplementation}async updateTsConfig(e,t){if(this._ecsProvider.setConfig(t,e),function(e){fy=e}(this._ecsProvider.getJamaSettings()),this._tsStack){const t=await(this._tsStack.getEcsProviderAsync?.());await(t?.setEcsConfig({ecsBlob:JSON.stringify(e),userIdentity:"",etag:this._ecsClient.eTag}))}}async updateConfig(e,t){e.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);try{if(MI(this._tsStack)){IN(e,HO);const t=e?.AcsCallingSDKWeb?.vdi3?.customEcsConfig;if(t)try{IN(e,JSON.parse(t))}catch(e){this.logger.error(`Failed to parse customEcsConfig: ${e}`)}}(function(e){if(!e)throw new le({defaultError:ee.INTERNAL.ECS_CONFIG_EMPTY});if(!e.AcsCallingSDKWeb)throw new le({defaultError:ee.INTERNAL.ECS_CONFIG_MISSING_ACS});try{const t=my.telemetry.deviceChangedEvents.piiSafeWords.slice();Z.mergeWith(my,e.AcsCallingSDKWeb,BS);const i=my.telemetry.deviceChangedEvents;"merge"===i.piiSafeWordsMode&&(i.piiSafeWords=Z.union(t,i.piiSafeWords))}catch(e){throw new le({defaultError:ee.INTERNAL.ECS_CONFIG_MERGING_ERROR})}})(e),await this.updateTsConfig(e,t)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new le({defaultError:ee.CALL_STACK.PARSE_CONFIG,originalError:e})}}async initializeEcsBase(e){const t=Date.now(),i=Mf();this._ecsTelemetryLogger.sendAttemptEvent(t,XO.Default,i);let n=ee.CALL_STACK.FETCH_CONFIG;try{const r=await this._ecsClient.fetchDefaultConfig(this.getEcsQueryParameters(e),e);n=ee.CALL_STACK.PARSE_CONFIG,await this.updateConfig(r,e),this._ecsTelemetryLogger.sendSuccessEvent(t,XO.Default,i,this.getEcsConfigIds());try{this._ecsProvider.assertConfigs(r)}catch(e){this._ecsTelemetryLogger.sendFailureEvent(t,XO.Default,i,e)}}catch(r){this.logger.warn("Failed to fetch base settings. Stack will initialize with default settings",r),this._ecsProvider.setConfig(e,void 0);const s=new le({defaultError:n,originalError:r});this._ecsTelemetryLogger.sendFailureEvent(t,XO.Default,i,s)}}async initializeEcsForUser(e,t){const i=Date.now(),n=Mf();this._ecsTelemetryLogger.sendAttemptEvent(i,XO.User,n);let r=ee.CALL_STACK.FETCH_CONFIG;try{const s=await this._ecsClient.fetchUserConfig(this.getEcsQueryParameters(e),e,t);r=ee.CALL_STACK.PARSE_CONFIG,await this.updateConfig(s,e),this._ecsTelemetryLogger.sendSuccessEvent(i,XO.User,n,this.getEcsConfigIds());try{this._ecsProvider.assertConfigs(s)}catch(e){this._ecsTelemetryLogger.sendFailureEvent(i,XO.User,n,e)}}catch(e){this.logger.warn("Failed to fetch user settings.",e);const t=new le({defaultError:r,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(i,XO.User,n,t)}}async getDeviceManager(){if(!this._createStackBaseWaitPromise)throw new le({defaultError:ee.CALL_STACK.GET_DM});return(await this._createStackBaseWaitPromise).getDeviceManagerAsync()}async dispose(e){if(!this._disposed){if(this._disposed=!0,this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch(e){this.logger.error("Failed to dispose signaling")}if(this._shellTrouter)try{await this._shellTrouter.dispose(),this._shellTrouter=void 0}catch(e){this.logger.error("Failed to dispose shellTrouter")}if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch(e){this.logger.error("Failed to dispose calling stack")}this._proxyReferenceManager?.dispose(),this._ecsClient.dispose(),this._createStackBaseWaitPromise=void 0,this._initializeStackForUserWaitPromise=void 0,this._tsStack=void 0,this.logger.info("Calling stack disposed")}}getEcsQueryParameters(e){const t={};try{t.CLRelease=X.getVersion();const i=bD();t.BrowserName=i.name,t.BrowserEngine=i.engine,t.BrowserVersion=i.version,t.FormFactor=i.formFactor,t.IdentityType=wv.Consumer,t.Cloud=Of.Public,t.OSVer=`${_D()}-${ID()}`,e&&(t.Cloud=e.cloudType,t.IdentityType=e.identityType);const n="_TS_BUILC_VERSION_".replace("C","D");t.CLRelease===n?t.CLRelease="9999.99":t.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete t.CLRelease}catch(e){throw this.logger.error(e),new le({defaultError:ee.CALL_STACK.SET_STACK_PARAMS,originalError:e})}return t}updateEmergencyCallCountry(e){this.caConfigBag&&!this.caConfigBag.emergencyCountryCode&&!this.caConfigBag.IsUserEmergencyCountryCode&&e&&(this.caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new OO(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let i=await this._trouterService.start();const n=this._trouterService.getTrouterSettings();return void this.sendSignalingInitEvent(!0,+new Date-t,n.registrationId??"",n.sessionId,i.trouterRequestCompletionTimeDeltaMs,i.registrarRequestCompletionTimeDeltaMs)}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,"","",void 0,void 0,e),e}}_getBaseStackConfig(){const e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:CD(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:"mediaAgent",signaling:"signalingAgent",tlePlayer:"tlePlayer"},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return void 0!==this._encodedStreamsWorkerProvider&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getSignalingConfig(e){const t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:()=>e(),trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.eTag};return this.caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this.caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings(),useOneDsLogger:!0,collectorUrl:kf,telemetryTenants:{signaling:Fv,gtcAudit:Fv,media:Uv,realtimeMedia:"5aea257f81424f5d8574e57a50974ead-d3a768ce-590c-4595-ab85-3dd046114290-6701",tlePlayer:Bv}}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,i){try{let n,r;i&&(n=i.message,r=_b(i)),this._telemetryLogManager.sendEvent({name:aE.acs_calling_stack_init,tenant:xv,properties:{success:e,reason:t,failureReason:n||"unknown",additionalDetails:{...r}}})}catch(e){}}sendSignalingInitEvent(e,t,i,n,r,s,a){try{let o,l;a&&(o=a.message,l=_b(a)),this._telemetryLogManager.sendEvent({name:aE.acs_calling_signaling_init,tenant:xv,properties:{success:e,failureReason:o||"unknown",timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:r,deltaTimeInMsRegistrarRequest:s},additionalDetails:{...l,registrationId:i,sessionId:n}}})}catch(e){}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&vy().calling.enableCustomTurnUsage)return this.logger.info("Using custom relays for media traffic"),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}}wN([SI,AN("design:type",Object)],PN.prototype,"logger",void 0),wN([pe(ZS.CreateStackBase),AN("design:type",Function),AN("design:paramtypes",[Object]),AN("design:returntype",Promise)],PN.prototype,"createStackBase",null),wN([pe(ZS.InitializeStackForUser),AN("design:type",Function),AN("design:paramtypes",[Function,Object]),AN("design:returntype",Promise)],PN.prototype,"initializeStackForUser",null),wN([pe(ZS.GetDeviceManager),AN("design:type",Function),AN("design:paramtypes",[]),AN("design:returntype",Promise)],PN.prototype,"getDeviceManager",null),wN([pe(ZS.Dispose),AN("design:type",Function),AN("design:paramtypes",[Boolean]),AN("design:returntype",Promise)],PN.prototype,"dispose",null);class RN{constructor(){this._eventEmitter=new OE.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((i,n)=>{let r=0;const s=()=>{i(),clearTimeout(r)};this._eventEmitter.once(e,s),r=window.setTimeout((()=>{this._eventEmitter.off(e,s),n(new Error("timeout"))}),t)}))}}class MN{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=vy().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return void 0!==t||(++this._deviceId,t=`${e.split(":")[0]??""}:${this._deviceId}`,this._deviceIdMapping.set(e,t)),t}scrubDeviceLabel(e){return function(e,t){if(!e)return"";if(e.length<3)return e;const i=[],n=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);n&&i.push(n[1]);try{if(!t?.length)return"no_keywords";{const n=new RegExp(`(${t.join("|")})`,"gi");let r=n.exec(e);for(;r;)i.push(r[1]),r=n.exec(e)}}catch(e){const t=e=>Z.isString(e)?e:e?.message??"";i.push(`Error: ${t(e)}`)}return 0===i.length?"unknown":i.join(" ")}(e,this._keywords)}}var DN=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},kN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class ON{constructor(e,t,i){this._callStack=t,this._videoDevices=[],this._audioDevices=[],this._tsDeviceTypeToAudioDeviceType={2:"Microphone",3:"Speaker",4:"CompositeAudioDevice"},this.logger=e.createChild("DeviceManager"),this._telemetryLogManager=i,this._eventEmitter=new T_(this.logger),this._browserInfo=bD(),this._safariVideoPermissionState="unknown",this._combinedDevicePermission=new Map,this._deviceInfoMapper=new MN,this._deviceSelectionNotifications=new RN,this._permissionChangedTasks=Promise.resolve()}get telemetryLogManager(){return this._telemetryLogManager}getRawDeviceMediaStream(e){const t=Mf(),i=+new Date;if(this.sendRawMediaEvent({eventName:aE.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"attempt",mediaType:e,timestampInfo:"",additionalDetails:""}),!this._tsDeviceManager?.getRawDeviceMediaStream){const n=new le({defaultError:ee.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error("Failed to get raw device stream track");const r=+new Date;throw this.sendRawMediaEvent({eventName:aE.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"failure",mediaType:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:n.message||"",code:n.code,subCode:n.subCode,..._b(n)}}),n}let n;try{n=this._tsDeviceManager?.getRawDeviceMediaStream(e);const r=+new Date;return this.sendRawMediaEvent({eventName:aE.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"success",mediaType:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:""}),n}catch(n){const r=new le({defaultError:ee.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:n});this.logger.error("Failed to get raw device stream track");const s=+new Date;throw this.sendRawMediaEvent({eventName:aE.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"failure",mediaType:e,timestampInfo:{deltaTimeInMs:s-i},additionalDetails:{failureReason:r.message||"",code:r.code,subCode:r.subCode,..._b(r)}}),r}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;const e=+new Date;try{this.sendGetDeviceManagerEvent({eventName:aE.acs_calling_get_device_manager,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),await this._callStack.createStackBase(),this._tsDeviceManager=await this._callStack.getDeviceManager();const t=await this.enumerateDevicesAsync();this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(1===e.kind){const t=e;this._videoDevices.push(new vI(t.label,t.id,"UsbCamera",this))}else if(2===e.kind||3===e.kind){const t=e,i=new BI(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(i)}}));const i=await(this._tsDeviceManager.getSelectedDevicesAsync?.());if(i&&(this._selectedMicrophone=this._audioDevices.find((e=>e.id===i.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===i.speaker))),this._dmDevicesChangedSub=this._tsDeviceManager.on("devicesChanged",(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);const i=+new Date;this.sendGetDeviceManagerEvent({eventName:aE.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:t?.message,code:t?.code,..._b(t),context:"devicesChanged"}})}})),vy().calling.devicePermissions.getCurrentState){const e=await(this._tsDeviceManager?.getPermissionStateAsync?.("microphone","")),t=await(this._tsDeviceManager?.getPermissionStateAsync?.("camera",""));this._audioDevicePermission=Ly(e,this.logger),this._videoDevicePermission=Ly(t,this.logger)}this.logger.info("Initial permission state audio:",this._audioDevicePermission,"video:",this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on("onPermissionStateChanged",(()=>{this._permissionChangedTasks=this._permissionChangedTasks.then((()=>this.permissionsChanged().catch(My)))}));const n=+new Date;this.sendGetDeviceManagerEvent({eventName:aE.acs_calling_get_device_manager,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:n-e},additionalDetails:""})}catch(t){const i=new le({defaultError:ee.DEVICE_MANAGER.GET_DM,originalError:t});this.logger.error(i.message);const n=+new Date;this.sendGetDeviceManagerEvent({eventName:aE.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:i.message,code:i.code,..._b(i)}})}return this._tsDeviceManager}on(e,t){if("videoDevicesUpdated"!==e&&"audioDevicesUpdated"!==e&&"selectedMicrophoneChanged"!==e&&"selectedSpeakerChanged"!==e)throw new le({defaultError:ee.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("videoDevicesUpdated"!==e&&"audioDevicesUpdated"!==e&&"selectedMicrophoneChanged"!==e&&"selectedSpeakerChanged"!==e)throw new le({defaultError:ee.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}getTsDeviceManager(){if(!this._tsDeviceManager)throw new le({defaultError:ee.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=PD()),this._environmentInfo}getOSNameInternal(){return _D()}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send raw media telemetry")}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send get_device_manager telemetry")}}async permissionsChanged(e,t){const i=this._audioDevicePermission,n=this._videoDevicePermission;let r,s;if(vy().calling.devicePermissions.getCurrentState){const e=await(this._tsDeviceManager?.getPermissionStateAsync?.("microphone","")),t=await(this._tsDeviceManager?.getPermissionStateAsync?.("camera",""));r=Ly(e,this.logger),s=Ly(t,this.logger)}else r=i,s=n;this._audioDevicePermission=r||!!e?.audio,this._videoDevicePermission=s||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),i===this._audioDevicePermission&&n===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${i}, video: ${n}\n to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:aE.acs_calling_device_permission_changed,tenant:xv,properties:{previousAudioDevicePermission:this.nullHandler(i),previousVideoDevicePermission:this.nullHandler(n),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info("checkForSelectedDevicesChanges"),this._tsDeviceManager){const e=await(this._tsDeviceManager.getSelectedDevicesAsync?.());e&&(e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit("selectedMicrophoneChanged"),void 0!==e.microphone&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit("selectedSpeakerChanged"),void 0!==e.speaker&&this._deviceSelectionNotifications.notifyAll(e.speaker)))}else this.logger.warn("DeviceManager is undefined, Unable to check selected devices")}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new le({defaultError:ee.DEVICE_MANAGER.ACCESS_DM});this.logger.info("syncDeviceList"),void 0===e&&(e=await this.enumerateDevicesAsync());const t=[];let i=[];const n=[];let r=[];e.map((e=>{if(1===e.kind){const i=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(i)i.setName(e.label),i.setId(e.id),i.setDeviceType("UsbCamera");else{const i=new vI(e.label,e.id,"UsbCamera",this);t.push(i),this._videoDevices.push(i)}}else if(2===e.kind||3===e.kind){const t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){const i=e;t.setName(i.label),t.setId(i.id),t.setIsSystemDefault(i.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[i.kind])}else{const t=new BI(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);n.push(t),this._audioDevices.push(t)}}}));const s=t=>{const i=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return i.map((e=>{t.splice(t.indexOf(e),1)})),i};i=s(this._videoDevices),r=s(this._audioDevices),(t.length>0||i.length>0)&&this._eventEmitter.emit("videoDevicesUpdated",{added:t,removed:i}),(n.length>0||r.length>0)&&this._eventEmitter.emit("audioDevicesUpdated",{added:n,removed:r})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new le({defaultError:ee.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch(e){throw new le({defaultError:ee.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new le({defaultError:ee.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((e=>"Microphone"===e.deviceType))}async getSpeakers(){if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>"Speaker"===e.deviceType));throw new le({defaultError:ee.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(!this._tsDeviceManager)throw new le({defaultError:ee.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new le({defaultError:ee.DEVICE_MANAGER.INVALID_DEVICE});if("microphone:"===e.id)throw new le({defaultError:ee.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info("selectMicrophone called"),this._selectedMicrophone?.id!==e.id){const t=vy().calling.deviceSelectionTimeoutInMs,i=this._deviceSelectionNotifications.waitFor(e.id,t),n="Microphone",r=this._deviceInfoMapper.getDeviceId(e.id),s=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=Mf(),o=(e,t,i)=>{this.sendDeviceSelectionEvent({eventName:aE.acs_calling_client_operations,operation:fO.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:void 0!==t?{deltaTimeInMs:t}:{},additionalDetails:void 0!==i?{failureReason:i.message,code:i.code,..._b(i)}:"",deviceSelection:{deviceId:r,deviceName:s,deviceType:n}})};o("attempt");const l=Date.now();try{await(this._tsDeviceManager.selectDevicesAsync?.({microphone:e.id})),await i.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o("success",Date.now()-l)}catch(e){let t;throw t=new le("timeout"===e?.message?{defaultError:ee.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:ee.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o("failure",Date.now()-l,t),t}}else this.logger.warn("microphoneDevice is already active")}async selectSpeaker(e){const t=this.logger.createFnLogger(XS.SelectSpeaker);if(!this._tsDeviceManager)throw new le({defaultError:ee.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new le({defaultError:ee.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new le({defaultError:ee.DEVICE_MANAGER.INVALID_DEVICE});if("speaker:"===e.id)throw new le({defaultError:ee.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info("selectSpeaker called"),this._selectedSpeaker?.id!==e.id){const t=vy().calling.deviceSelectionTimeoutInMs,i=this._deviceSelectionNotifications.waitFor(e.id,t),n="Speaker",r=this._deviceInfoMapper.getDeviceId(e.id),s=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=Mf(),o=(e,t,i)=>{this.sendDeviceSelectionEvent({eventName:aE.acs_calling_client_operations,operation:fO.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:void 0!==t?{deltaTimeInMs:t}:{},additionalDetails:void 0!==i?{failureReason:i.message,code:i.code,..._b(i)}:"",deviceSelection:{deviceId:r,deviceName:s,deviceType:n}})};o("attempt");const l=Date.now();try{await(this._tsDeviceManager.selectDevicesAsync?.({speaker:e.id})),await i.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o("success",Date.now()-l)}catch(e){let t;throw t=new le("timeout"===e?.message?{defaultError:ee.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:ee.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o("failure",Date.now()-l,t),t}}else t.warn("device is already selected")}async askDevicePermission(e){const t={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new le({defaultError:ee.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});const i=this.getKeyForConstrains(t);let n=this._combinedDevicePermission.get(i);return n?this.logger.info(`askDevicePermission attempt: audio:${t.audio}, video:${t.video} on pending existing request ${Ny(n)}`):(n=this.askDevicePermissionInternal(t),this._combinedDevicePermission.set(i,n),n.finally((()=>{this._combinedDevicePermission.delete(i)}))),n}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);const t=Mf(),i=+new Date;this.sendAudioVideoPermissionEvent({eventName:aE.acs_calling_adp_attempt,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video});try{if(!this._tsDeviceManager)throw new le({defaultError:ee.DEVICE_MANAGER.ACCESS_DM});const n=[];if(vy().calling.devicePermissions.splitAskAudioVideo){this.logger.info("askDevicePermission, split permission check");const t=[];if(e.audio&&(this.logger.info("askDevicePermission, split permission audio"),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video){const i=async t=>new Promise(((i,n)=>{const r=async()=>{if(this.logger.info("askDevicePermission, split permission video"),!this._tsDeviceManager){const e="askDevicePermission, split permission video failed device manager not found";return this.logger.error(e),void n(e)}try{const t=await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video});i(t)}catch(e){n(e)}};t?window.setTimeout(r,t):r()}));t.push(i(vy().calling.devicePermissions.timeoutInBetween))}const i=await Promise.allSettled(t);let r={audio:!1,video:!1};i.forEach((e=>{"fulfilled"===e.status&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),"rejected"===e.status&&e?.reason&&n.push(e.reason)}));const s=this._permissionChangedTasks.then((()=>this.permissionsChanged(r,e)));this._permissionChangedTasks=s,this._permissionChangedTasks.catch(My),await s,this._safariVideoPermissionState=this._videoDevicePermission?"granted":"denied"}else{const t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video}),i=this._permissionChangedTasks.then((()=>this.permissionsChanged(t,e)));this._permissionChangedTasks=i,this._permissionChangedTasks.catch(My),await i}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAudioVideoPermissionEvent({eventName:aE.acs_calling_adp_failure,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission},new le({defaultError:ee.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[Ny(n)]}));else{const n=+new Date;this.sendAudioVideoPermissionEvent({eventName:aE.acs_calling_adp_success,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:n-i})}}catch(n){const r=new le({defaultError:ee.DEVICE_MANAGER.ADP_FAIL,originalError:n}),s=+new Date;this.sendAudioVideoPermissionEvent({eventName:aE.acs_calling_adp_failure,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:s-i},r)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAudioVideoPermissionEvent(e,t){try{let i,n,r;t&&(i="string"==typeof t?.message?t?.message:void 0,n=_b(t)),e.deltaTimeInMs&&(r=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||"",failureReason:i||"",deltaTimeInMs:e.deltaTimeInMs||"",deltaTimeGreaterThanJAMATimeout:this.nullHandler(r),additionalDetails:{...n}}})}catch(e){this.logger.debug("Unable to send audio video permission failure success telemtery")}}sendDeviceSelectionEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send device selection telemetry")}}nullHandler(e){return void 0===e?"":e}dispose(){this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0}}DN([SI,kN("design:type",Object)],ON.prototype,"logger",void 0),DN([pe(XS.GetDeviceManager),kN("design:type",Function),kN("design:paramtypes",[]),kN("design:returntype",Promise)],ON.prototype,"getDeviceManager",null),DN([pe(XS.GetCameras),kN("design:type",Function),kN("design:paramtypes",[]),kN("design:returntype",Promise)],ON.prototype,"getCameras",null),DN([pe(XS.GetMicrophones),kN("design:type",Function),kN("design:paramtypes",[]),kN("design:returntype",Promise)],ON.prototype,"getMicrophones",null),DN([ge(XS.GetSpeakers),kN("design:type",Function),kN("design:paramtypes",[]),kN("design:returntype",Promise)],ON.prototype,"getSpeakers",null),DN([pe(XS.SelectMicrophone),kN("design:type",Function),kN("design:paramtypes",[Object]),kN("design:returntype",Promise)],ON.prototype,"selectMicrophone",null),DN([pe(XS.SelectSpeaker),kN("design:type",Function),kN("design:paramtypes",[Object]),kN("design:returntype",Promise)],ON.prototype,"selectSpeaker",null),DN([pe(XS.AskDevicePermission),kN("design:type",Function),kN("design:paramtypes",[Object]),kN("design:returntype",Promise)],ON.prototype,"askDevicePermission",null);var NN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class LN extends cO{get info(){return this._teamsCall.info}constructor(e){super(e,he.TeamsIncomingCall),this._teamsCall=e}async accept(e){if(!Vy(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}}!function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);s>3&&a&&Object.defineProperty(t,i,a)}([pe(JS.Accept),NN("design:type",Function),NN("design:paramtypes",[Object]),NN("design:returntype",Promise)],LN.prototype,"accept",null);var xN=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},FN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class UN extends rO{get info(){return this._info}constructor(e,t,i,n){super(e,t,i,n,ue.TeamsCall),this._isEmergencyCall=!1,this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._mtPolicyService=t.mtPolicyService}async startCallInternal(e,t,i,n,r,s,a){if(this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,a)){this._mtPolicyService.userDialedNumber(Array.isArray(a)?a[0].phoneNumber:a.phoneNumber);let t="",i=!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(e){i=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n Proceeding as normal pstn call`)}if(i){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){return void this.handlePolicyAndLicenseRestrictionsFailure(e)}try{this.logger.info("Deriving emergency content from fetched policies and settings"),t=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}n&&(n.emergencyContent=t||"",n.isEmergency=t?.trim().length>0||!1,this._isEmergencyCall=n.isEmergency)}}if(a){let t=[];Array.isArray(a)?t=a:t.push(a),this._isEmergencyCall&&1==t.length&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&await this.setupThreadIdWhenStartingGroupCall(t,e,n),t.forEach((e=>{this.tsCall.addParticipant(DS(e)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),this.logger.info("Paticipant added during startCall")}return this._allowBreakoutRoomJoin=vy().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!i,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(e,t,i,n,r,s)}isEmergencyCallInProgress(){return this._isEmergencyCall}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){const i=+new Date,n=Mf();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.attempt,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{attemptTimestamp:i},additionalDetails:{customContext:{userToUserPresent:!!t?.customContext?.userToUser,xHeadersPresent:!!t?.customContext?.xHeaders&&t?.customContext.xHeaders.length>0}}});try{dD(JS.AddParticipant,this.state),NS(e)}catch(e){const t=new le({defaultError:ee.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,..._b(t)}}),t}if(!Vy(this.acsProxy,this.acsCustomRelayManager,!0)){const e=new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,..._b(e)}}),e}if(this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)))){const t=new le({defaultError:ee.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[B(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:t.code,failureReason:t.message,..._b(t)}}),t}if(this.tsCall.threadId&&function(e){return e.startsWith(re)}(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(e))throw new le({defaultError:ee.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,..._b(e)}}),this.logger.error(e),e}const r=this.getOrCreateRemoteParticipant(kS(DS(e)));let s="";return this.GetOrCreateGroupChatThread(!!t?.threadId,e,t).then((a=>{a&&((t=t??{}).threadId=a,s=a,this._info.setThreadId(a)),this.addParticipantToTsCall(e,s,t,r,n,i)})).catch((e=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:n,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,..._b(e)}}),e})),r}async removeParticipant(e){const t=+new Date,i=Mf();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.attempt,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{attemptTimestamp:t}});try{dD(JS.RemoveParticipant,this.state),NS(e)}catch(e){const n=new le({defaultError:ee.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date},additionalDetails:{code:e.code,failureReason:e.message,..._b(n)}}),n}const n=this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)));if(!n){const n=new le({defaultError:ee.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[B(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:n.code,subCode:n.subCode,failureReason:n.message,..._b(n)}}),n}try{await this.tsCall.removeParticipant(DS(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.success,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date}})}catch(e){const{callEndReason:r}=Tb(this,n.tsRemoteParticipant,e);n.callEndReason||n.setCallEndReason(r);const s=Ib(r);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date},additionalDetails:{code:s?.callEndReason.code,subCode:s?.callEndReason.subCode,failureReason:s?.callEndReason.message,...s}}),new le({defaultError:{message:r.message,code:r.code,subCode:r.subCode||0,resultCategories:r.resultCategories},originalError:e})}}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(!vy().calling.musicOnHoldEnabled)return this.logger.warn("Music on Hold is not enabled"),super.hold();const e=+new Date,t=Mf();if(this._causeId=X.generateCauseId(),this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:gy.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:vy().MiddleTier.policyUrlSuffixV2,userPolicies:["TeamsCallingPolicy"]}),this._hasFetchedPolicies=!0,this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled()}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?(vy().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 i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:gy.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info("Successful park() as part of hold, Music on Hold completed successfully")}))})).catch((()=>{const i=+new Date,n=new le({defaultError:ee.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n Error message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Hold,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,holdType:gy.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,..._b(n)}}),n}))):(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 e=+new Date,t=Mf();return this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:gy.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 i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:gy.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info("Successful unhold() as part of resume, resume completed successfully")}))})).catch((()=>{const i=+new Date,n=new le({defaultError:ee.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n Error message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:aE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:JS.Resume,kindOfEvent:oE.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,holdType:gy.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,..._b(n)}}),n}))}return this.logger.info("Music on Hold Disabled, proceeding with standard resume"),super.resume()}validateAndSetThreadId(e,t){if(!t?.threadId){const e=new le({defaultError:ee.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}return this.validateThreadIdFormat(t?.threadId),t?.threadId}validateThreadIdFormat(e){if(!e.startsWith("19")){const e=new le({defaultError:ee.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){const e=+new Date;if(!this._mtPolicyService.isEvEnabled()){const t=+new Date,i=new le({defaultError:ee.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${i.message}, code = ${i.code}, subcode = ${i.subCode}`);const n=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:aE.acs_calling_call_failed,correlationId:Mf(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{..._b(i)}}},i,{code:i.code,subCode:i.subCode,phrase:i.message}),i}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:"Unknown",code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state="Disconnected",this._eventEmitter.emit("stateChanged"),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,i){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info("ThreadId is already provided in the options parameter: "+JSON.stringify(t))),void 0===t||!t.threadId){const n=[];e.forEach((e=>{n.push({id:DS(e)})}));try{const e=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:vy().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:n});t||(t={}),t.threadId=e,e&&this._info.setThreadId(e),i&&e&&(i.threadId=e)}catch(e){const t="Failed to create thread Id for Teams group call ";if(!vy().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(t+e)}}}async GetOrCreateGroupChatThread(e,t,i){let n="";if(e)return this.logger.info("Customer provided threadId in options: "+JSON.stringify(i)),n=this.validateAndSetThreadId(t,i),Promise.resolve(n);if(!vy().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new le({defaultError:ee.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(null!==this._info.threadId&&void 0!==this._info.threadId){n=this._info.threadId;const e=[];return e.push({id:DS(t)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:n,addParticipantsSuffix:vy().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:e}).catch((t=>{this.logger.warn("Error when adding participants "+JSON.stringify(e)+" to thread. "+t)})),Promise.resolve(n)}{const e=[];return this._remoteParticipants.forEach((t=>{e.push({id:DS(t.identifier)})})),e.push({id:DS(t)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:vy().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:e}).then((e=>{n=e,this.logger.info("Add participant into 1on1 call to convert it into Teams group call. Create thread id: "+n)})).catch((e=>{const i="Error when adding participants "+DS(t)+" to thread to create a Teams group call. ";if(!vy().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new le({defaultError:ee.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(i+e)})),Promise.resolve(n)}}addParticipantToTsCall(e,t,i,n,r,s){this.tsCall.addParticipant(DS(e),{threadId:t,customHeaderContext:$y(i)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.success,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:s-+new Date}})})).catch((t=>{const{callEndReason:i}=Tb(this,n.tsRemoteParticipant,t);n.callEndReason||n.setCallEndReason(i);const a=Ib(i);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:oE.failure,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:s-+new Date},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),this._remoteParticipants.find((t=>DS(t.identifier)===DS(e)))&&(this.deleteRemoteParticipant(n),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[n]}))}))}IsTargetUserAllowed(e){return"string"==typeof e.id||x(e)||L(e)}}xN([me(JS.AddParticipant),ge(JS.AddParticipant),FN("design:type",Function),FN("design:paramtypes",[Object,Object]),FN("design:returntype",Object)],UN.prototype,"addParticipant",null),xN([me(JS.RemoveParticipant),pe(JS.RemoveParticipant),FN("design:type",Function),FN("design:paramtypes",[Object]),FN("design:returntype",Promise)],UN.prototype,"removeParticipant",null),xN([me(JS.Mute),FN("design:type",Function),FN("design:paramtypes",[]),FN("design:returntype",Promise)],UN.prototype,"mute",null),xN([me(JS.Unmute),FN("design:type",Function),FN("design:paramtypes",[]),FN("design:returntype",Promise)],UN.prototype,"unmute",null),xN([me(JS.Hold),pe(JS.Hold),FN("design:type",Function),FN("design:paramtypes",[]),FN("design:returntype",Promise)],UN.prototype,"hold",null),xN([me(JS.Resume),pe(JS.Resume),FN("design:type",Function),FN("design:paramtypes",[]),FN("design:returntype",Promise)],UN.prototype,"resume",null);var BN=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},VN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class HN extends TO{get calls(){return this._calls}constructor(e,t,i,n,r,s){super(e,t,n,r,i,de.TeamsCallAgent,s),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){const t=e.on("callStateChanged",(async()=>{if(1===e.state){const i=MI(e),n=e.callId;t.dispose();let r=new UN({callId:n,isIncoming:!0},this,e,this._telemetryLogManager);i&&(r=bO(r));const s=new LN(r);this.handleCallState(r),i?await Promise.all(r.bindTsCall()):r.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:s})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);const t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){const e=vy().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit("callsUpdated",{added:[],removed:[t]}),this.logger.info("call removed")}},this.handleCallState=e=>{e.on("stateChanged",(async()=>{try{"Disconnected"===e.state?this.tsStack?(await(this._tsCallRegistry.deleteCallAsync?.(e.tsCall))||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry"):"Connecting"===e.state&&"Incoming"==e.direction&&(this.addToCallArray(e),this._eventEmitter.emit("callsUpdated",{added:[e],removed:[]}))}catch(e){this.logger.error("Failed to handle call state changed event")}}))},this.logger=t}createNewCall(e,t){const i=new UN({callId:e},this,t,this._telemetryLogManager);return MI(t)?bO(i):i}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(e){HN.teamsCallAgents.get(e?.identityMri)&&Ry(ee.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),HN.teamsCallAgents.set(e?.identityMri,this)}removeFromCallAgentsMap(e){e?.identityMri&&HN.teamsCallAgents.get(e?.identityMri)===this&&HN.teamsCallAgents.delete(e?.identityMri)}disposeCall(e){const t=this._calls.indexOf(e);-1!==t&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isCteUser()){const e=Mf();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:vy().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(e){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}startCall(e,t){const i=Mf(),n=+new Date,r={correlationId:i,timestampInfo:{attemptTimestamp:n}};this._telemetryLogManager.sendEvent({name:aE.acs_calling_call_attempt,tenant:xv,properties:r},void 0,"attempt");try{let r;if(this.assertParticipants(e),Array.isArray(e)){if(r=t,e.length>1&&!vy().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!r?.threadId)throw new le({defaultError:ee.CALL_AGENT.GROUPCALL_THREADID});if(1==e.length&&r?.threadId)throw new le({defaultError:ee.CALL_AGENT.ONE_TO_ONE_THREADID})}else r=t;if(vy().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e))throw new le({defaultError:ee.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let s=r?.audioOptions?.muted;return void 0===s&&(s=!1),this.logger.info(`startCall with video=${!!r?.videoOptions},muted=${s}`),this.createCall({participants:e,startCallOptions:r},{correlationId:i,attemptTimestamp:n})}catch(e){let t,r;throw e instanceof le&&(t="string"==typeof e?.message?e?.message:void 0,r={..._b(e)}),this._telemetryLogManager.sendEvent({name:aE.acs_calling_call_failed,tenant:xv,properties:{correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-n},failureReason:t||"",additionalDetails:r||{}}},void 0,"failure"),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(i)}}join(e,t){this.assertCallContext(e);const i=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${i}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){if(this._disposed)throw new le({defaultError:ee.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&HN.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);try{const e=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(e))}catch(e){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(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new le({defaultError:ee.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new le({defaultError:ee.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(!this.tsStack)throw new le({defaultError:ee.CALL_AGENT.STACK_NOT_INIT});let i,n,r,s=e?.teamsCallContext?.threadId,a=!1;const o=e?.teamsCallContext?.meetingLink,l=e?.teamsCallContext?.meetingId,c=e?.teamsCallContext?.passcode||"",d=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isCteUser()&&d&&(s=(e?.startCallOptions).threadId),!Vy(this.acsProxy,this.acsCustomRelayManager,!0))throw new le({defaultError:ee.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(o)if(QM(o))n=eD(o);else{if(!ZM(o,this.logger))throw new le({defaultError:ee.CALL_AGENT.INVALID_MEETING_LINK});if(XM(o.trim().toLocaleLowerCase(),vy().calling.tfl.hosts))throw new le({defaultError:ee.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});a=!0}e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(n={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():"0",organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),n&&(r={meetingType:"0"===n.messageId?1:2,tenantId:n.tenantId,organizerId:n.organizerId,replyChainMessageId:n.messageId}||void 0,s=n.threadId,i=n.messageId);const u=e?.startCallOptions?.onBehalfOfOptions,h=u?.userId;let g;if(h){if((e?.startCallOptions).customContext)throw new le({defaultError:ee.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(U(h))g=V(h);else{if(!F(h))throw new le({defaultError:ee.IDENTIFIER.INVALID_COMM_USER});if(!vy().calling.sharedLineAppearance.enabled)throw new le({defaultError:ee.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw new le({defaultError:ee.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY});g=V(h)}}const p={threadId:s||"",messageId:i||"",meetingInfo:r,mediaPeerType:2,onBehalfOf:g},m=MI(this._tsCallRegistry),f=X.generateCauseId(),v=Mf(),S=Mf();if(m){const n=bO();return(async()=>{let r;r=l?await this._tsCallRegistry.createCallAsync({callId:v,localParticipantId:S,causeId:f,type:"MeetingData",meetingData:{meetingCode:l,passcode:c,threadId:s}}):a?await this._tsCallRegistry.createCallAsync({callId:v,localParticipantId:S,causeId:f,type:"MeetingData",meetingData:{meetingUrl:o}}):await this._tsCallRegistry.createCallAsync({callId:v,localParticipantId:S,causeId:f,type:"ThreadId",threadId:s||"",messageId:i});const d=new UN({callId:v},this,r,this._telemetryLogManager);n.setTarget(d),this.addToCallArray(n),this.handleCallState(n);const u=jT();d.startCallInternal(e?.startCallOptions,!!l,e?.teamsCallContext,p,t,u,e?.participants).catch(My),await Promise.all(d.bindTsCall()),await u.promise,this._eventEmitter.emit("callsUpdated",{added:[n],removed:[]})})().catch((e=>{})),n}{let n;n=l?this._tsCallRegistry.createCallWithMeetingData({meetingCode:l,passcode:c,threadId:s},v,S,f):a?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:o},v,S,f):this._tsCallRegistry.createCall(s||"",v,S,i,f);const r=new UN({callId:v},this,n,this._telemetryLogManager);return this.addToCallArray(r),this.handleCallState(r),r.startCallInternal(e?.startCallOptions,!!l,e?.teamsCallContext,p,t,void 0,e?.participants).catch(My),r.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[r],removed:[]}),r}}assertParticipants(e){Ay(e,ee.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),wy(e,ee.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new le({defaultError:ee.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isCteUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>L(e)))&&(t=!0):L(e)&&(t=!0)),t}}HN.teamsCallAgents=new Map,BN([ge(KS.StartCall),VN("design:type",Function),VN("design:paramtypes",[Object,Object]),VN("design:returntype",Object)],HN.prototype,"startCall",null),BN([ge(KS.Join),VN("design:type",Function),VN("design:paramtypes",[Object,Object]),VN("design:returntype",Object)],HN.prototype,"join",null),BN([pe(KS.Dispose),VN("design:type",Function),VN("design:paramtypes",[]),VN("design:returntype",Promise)],HN.prototype,"dispose",null);class $N{constructor(){this._proxyInUse=!1;const e=R("ACS-calling");this.logger=new _I(e,[()=>"AcsProxy"])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||""}set proxyUrl(e){if(e.length<4)throw new le({defaultError:ee.CALL_CLIENT.PROXY_SHORT_URL});"/"!==e.slice(-1)&&(e=e.concat("","/"));try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new le({defaultError:ee.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){const i=new le({defaultError:ee.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(i.message),i}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${VS(t)}`),t;try{const e=new URL(t);t=`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${VS(e)} to ${VS(t)}`)}catch(e){const t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}}class jN{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;const e=R("ACS-calling");this._logger=new _I(e,[()=>"AcsCustomRelayManager"])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info("Custom relay config provided"),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}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 e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((i=>{const n=this._getIndividualRelay(i,t?.username,t?.credential);e.push(n)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,i){const n=[],r=[],s=[IE.turn,IE.turns,IE.stun],a=[wE.tcp,wE.tls,wE.udp];let o;try{o=new URL(e)}catch(t){throw new le({defaultError:ee.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}const l=o.protocol.replace(":","");if(!s.includes(l))throw new le({defaultError:ee.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let c,d="";try{d=o.href.replace(/((turn)s?|stun):/,"https:"),c=new URL(d)}catch(e){throw new le({defaultError:ee.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let u=c.searchParams.get("transport")??"";a.includes(u)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${wE.udp}`),u=wE.udp);let h=""===c.port?this._extractPortFromUrl(o):Number(c.port);h||(this._logger.warn("Could not read port from relay url, defaulting to 3478"),h=3478);let g=c.hostname;return function(e){return new RegExp(IS).test(e)}(g)?n.push(g):r.push(g),{addresses:n,udpPort:u===wE.udp?h:void 0,tcpPort:u===wE.tcp?h:void 0,tlsPort:u===wE.tls?h:void 0,username:t??"",password:i??"",type:"turn",fqdns:r}}_extractPortFromUrl(e){const t=e.href.match(wS)?.[0];return Number(t?.replace(":",""))}}var GN,qN=function(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a},zN=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let WN=1;class KN{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(vy().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(const e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug("Error logging telemetry",e)}},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 e=this.getOrientationBasedOnWindowSize();this._previousOrientation!==e&&(this._previousOrientation=e,this.sendOrientationChangeEvent(e))};const t=+new Date;this.clientId=Mf();const i=e?.logger||R("ACS-calling"),n=WN++;if(this._acsProxy=new $N,this._acsCustomRelayManager=new jN,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));const t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new _I(i,[()=>`CallClient${n}[${this.clientId}]`]),this._eventEmitter=new T_(this.logger),this._sdkDiagnosticInformation=function(e,t,i){const n=`azsdk-js-communication-calling/${e}`;let r="";if(i?.diagnostics?.appName){let e=i?.diagnostics?.appName.trim().replace(/\s/g,"_");e.length>64&&(t.warn("appName is too long, max allowed length is 64 chars, appName was truncated to max length"),e=e.substr(0,64)),r+=e?`${e}/`:"default/"}else r+="default/";if(i?.diagnostics?.appVersion){let e=i?.diagnostics?.appVersion.trim().replace(/\s/g,"_");e.length>64&&(t.warn("appVersion is too long, max allowed length is 64 chars, appVersion was truncated to max length"),e=e.substr(0,64)),r+=e||"0.0.0"}else r+="0.0.0";if(r+=` ${n}`,i?.diagnostics?.tags&&Array.isArray(i?.diagnostics?.tags)&&i?.diagnostics?.tags.length>0){let e=i?.diagnostics?.tags.map((e=>e.trim().replace(/\s/g,"_"))).filter((e=>!!e)).join(";");e.length>128&&(t.warn("tags are too long, max allowed length is 128 chars, tags were truncated to max length"),e=e.substr(0,128)),e.length>0&&(r+=" ("+e+").")}return r}(US(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new mE(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:aE.acs_calling_call_client_init,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),Object.defineProperty(globalThis,Xv,{value:n,writable:!0,enumerable:!1}),1===n&&Object.defineProperty(globalThis,Zv,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info("created"),this._callStack=new PN(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath),this._deviceManager=new ON(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 nb(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});const e=lD(YE.CallClientFeature);for(const t of e)"OnExtendedObjectConstructor"===t.activationOptions.activationEvent&&this.feature(t);this.sendCallClientInitEvent({eventName:aE.acs_calling_call_client_init,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:""})}catch(e){const i=new le({defaultError:ee.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:aE.acs_calling_call_client_init,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,..._b(i)}}),i}}createInstance(e){return new KN(e)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return US()}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){const{identityMri:i}=await Oy(e);if(this._callAgent?._caConfigBag?.identityMri===i)return this._callAgent;if((this._callAgent||this._teamsCallAgent)&&Ry(ee.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger),this._callAgent=wO.callAgents.get(i),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit("callAgentCreated"),this._callAgent;this.validateEmergencyCountryCode(t);try{return this._callAgent=new wO(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,t),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit("callAgentCreated"),this._callAgent}catch(e){throw this._callAgent=void 0,new le({defaultError:ee.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e})}}async createTeamsCallAgent(e,t){const{identityMri:i}=await Oy(e);if(this._teamsCallAgent?._caConfigBag?.identityMri===i)return this._teamsCallAgent;if((this._callAgent||this._teamsCallAgent)&&Ry(ee.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger),this._teamsCallAgent=HN.teamsCallAgents.get(i),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit("teamsCallAgentCreated"),this._teamsCallAgent;try{return this._teamsCallAgent=new HN(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,t),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit("teamsCallAgentCreated"),this._teamsCallAgent}catch(e){throw this._teamsCallAgent=void 0,new le({defaultError:ee.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e})}}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._deviceManager}async getEnvironmentInfoInternal(){return this._environmentInfos||(await this._callStack.createStackBase(),this._environmentInfos=PD()),this._environmentInfos}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>10&&Ry(ee.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendOrientationChangeEvent(e,t=!1){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:aE.acs_calling_orientation_changed,tenant:xv,properties:{orientation:e,isInitial:t}})}catch(e){this.logger.debug("Unable to send orientation change telemetry")}}sendInitialOrientation(){let e=screen.orientation&&screen.orientation.type;e||(e=this.getOrientationBasedOnWindowSize()),this.sendOrientationChangeEvent(e,!0)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:xv,properties:e})}catch(e){this.logger.debug("Unable to send CallClient initialized telemetry event")}}hangupCalls(){try{"Mobile"===bD().formFactor&&vy().calling.hangUpCallOnPageHide&&this._callAgent?.calls.forEach((e=>e.hangUp()))}catch(e){try{this.logger.error(`Unable to hangup call on page hide due to ${JSON.stringify(e)}`)}catch(e){this.logger.error("Unable to hangup call on page hide due to unknown error")}}}sendPageVisibilityInfoEvent(e,t){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:aE.acs_calling_page_hidden,tenant:xv,properties:{eventName:e,pageHidden:t}})}catch(e){this.logger.debug("Unable to send page hide telemetry")}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?TS.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?TS.onlyUsedProxy:this._customProxyAndTurnInformation.turn?TS.onlyUsedNonMsftTurn:""}}qN([SI,zN("design:type",Object)],KN.prototype,"logger",void 0),qN([ge(WS.GetSDKVersion),zN("design:type",Function),zN("design:paramtypes",[]),zN("design:returntype",String)],KN.prototype,"getSDKVersion",null),qN([ge(WS.Feature),zN("design:type",Function),zN("design:paramtypes",[Object]),zN("design:returntype","function"==typeof(GN="undefined"!=typeof TFeature&&TFeature)?GN:Object)],KN.prototype,"feature",null),qN([pe(WS.CreateCallAgent),zN("design:type",Function),zN("design:paramtypes",[Object,Object]),zN("design:returntype",Promise)],KN.prototype,"createCallAgent",null),qN([pe(WS.CreateTeamsCallAgent),zN("design:type",Function),zN("design:paramtypes",[Object,Object]),zN("design:returntype",Promise)],KN.prototype,"createTeamsCallAgent",null),qN([pe(WS.GetDeviceManager),zN("design:type",Function),zN("design:paramtypes",[]),zN("design:returntype",Promise)],KN.prototype,"getDeviceManager",null),qN([pe(WS.GetEnvironmentInfo),zN("design:type",Function),zN("design:paramtypes",[]),zN("design:returntype",Promise)],KN.prototype,"getEnvironmentInfoInternal",null);const JN=e=>"string"==typeof e.communicationUserId,YN=e=>"string"==typeof e.phoneNumber,QN=e=>"string"==typeof e.microsoftTeamsUserId,ZN=e=>"string"==typeof e.teamsAppId,XN=e=>JN(e)?Object.assign(Object.assign({},e),{kind:"communicationUser"}):YN(e)?Object.assign(Object.assign({},e),{kind:"phoneNumber"}):QN(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsUser"}):ZN(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsApp"}):Object.assign(Object.assign({},e),{kind:"unknown"}),eL=(e,t)=>({kind:"microsoftTeamsApp",teamsAppId:e,cloud:t}),tL=(e,t,i)=>({kind:"microsoftTeamsUser",microsoftTeamsUserId:e,isAnonymous:i,cloud:t}),iL=e=>(e=>{const t=XN(e);switch(t.kind){case"communicationUser":return t.communicationUserId;case"microsoftTeamsUser":{const{microsoftTeamsUserId:e,rawId:i,cloud:n,isAnonymous:r}=t;if(i)return i;if(r)return`8:teamsvisitor:${e}`;switch(n){case"dod":return`8:dod:${e}`;case"gcch":return`8:gcch:${e}`;case"public":return`8:orgid:${e}`}return`8:orgid:${e}`}case"microsoftTeamsApp":{const{teamsAppId:e,rawId:i,cloud:n}=t;if(i)return i;switch(n){case"dod":return`28:dod:${e}`;case"gcch":return`28:gcch:${e}`}return`28:orgid:${e}`}case"phoneNumber":{const{phoneNumber:e,rawId:i}=t;return i||`4:${e}`}case"unknown":return t.id}})(e),nL=e=>(e=>{if(e.startsWith("4:"))return{kind:"phoneNumber",phoneNumber:`${e.substring(2)}`};const t=e.split(":");if(3!==t.length)return{kind:"unknown",id:e};const i=`${t[0]}:${t[1]}:`,n=t[2];switch(i){case"8:teamsvisitor:":return{kind:"microsoftTeamsUser",microsoftTeamsUserId:n,isAnonymous:!0};case"8:orgid:":return tL(n,"public",!1);case"8:dod:":return tL(n,"dod",!1);case"8:gcch:":return tL(n,"gcch",!1);case"8:acs:":case"8:spool:":case"8:dod-acs:":case"8:gcch-acs:":return{kind:"communicationUser",communicationUserId:e};case"28:orgid:":return eL(n,"public");case"28:gcch:":return eL(n,"gcch");case"28:dod:":return eL(n,"dod")}return{kind:"unknown",id:e}})(0===e.indexOf("+")?"4:"+e:e),rL=e=>"string"==typeof e?nL(e):e,sL=(e,t=Object.is)=>{let i=new Map,n=new Map;return r=>{const s=r(((r,...s)=>{const a=i.get(r);if(a){const[e,i]=a;if(l=s,c=t,(o=e).length===l.length&&o.every(((e,t)=>c(l[t],e))))return n.set(r,[s,i]),i}var o,l,c;const d=e(r,...s);return n.set(r,[s,d]),d}));return i=n,n=new Map,s}};var aL=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const oL=e=>!!e&&!["None","Disconnected","Connecting","Ringing","EarlyMedia","Disconnecting"].includes(e),lL=e=>!!e&&["Connecting","Ringing","InLobby","EarlyMedia"].includes(e),cL=e=>{var t;return void 0!==(null===(t=e.unparentedViews[0])||void 0===t?void 0:t.view)},dL=e=>aL(void 0,void 0,void 0,(function*(){const t=e.getState().deviceManager.unparentedViews;for(const i of t)yield e.disposeView(void 0,void 0,i)})),uL=e=>e?hL((t=>Object.values(e).map((e=>{const i=iL(e.identifier);return t(i,e)})))):[],hL=sL(((e,t)=>YN(t.identifier)?Object.assign(Object.assign({},t),{displayName:t.identifier.phoneNumber}):t)),gL=e=>YN(e.identifier)&&"Connecting"===e.state?"Ringing":e.state,pL=(e,t,i,n)=>{let r=e;return n&&i&&"Attendee"===i&&(t&&"Attendee"===t&&(r="{AttendeeRole}"),!t||"Presenter"!==t&&"Co-organizer"!==t&&"Organizer"!==t||(r=`{AttendeeRole}(${e})`)),r},mL=e=>aL(void 0,void 0,void 0,(function*(){const t=yield null==e?void 0:e.getState().deviceManager.selectedCamera;if(t)return new UI(t)})),fL=(e,t)=>{if(!e.calls[t]){if(e.callsEnded[t])return;throw new Error(`Call Not Found: ${t}`)}return e.calls[t]};var vL=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class SL{constructor(e,t){this.setDeviceManager=()=>{this._context.setDeviceManagerIsSpeakerSelectionAvailable(this._deviceManager.isSpeakerSelectionAvailable),this._context.setDeviceManagerSelectedMicrophone(this._deviceManager.selectedMicrophone),this._context.setDeviceManagerSelectedSpeaker(this._deviceManager.selectedSpeaker)},this.subscribe=()=>{if(this._deviceManager.on("videoDevicesUpdated",this.videoDevicesUpdated),this._deviceManager.on("audioDevicesUpdated",this.audioDevicesUpdated),this._deviceManager.on("selectedMicrophoneChanged",this.selectedMicrophoneChanged),this._deviceManager.on("selectedSpeakerChanged",this.selectedSpeakerChanged),navigator.permissions){try{navigator.permissions.query({name:"camera"}).then((e=>{e.addEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not subscribe to Permissions API Camera changed events, API is not supported by browser",e)}try{navigator.permissions.query({name:"microphone"}).then((e=>{e.addEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not subscribe to Permissions API Microphone changed events, API is not supported by browser",e)}}},this.unsubscribe=()=>{if(this._deviceManager.off("videoDevicesUpdated",this.videoDevicesUpdated),this._deviceManager.off("audioDevicesUpdated",this.audioDevicesUpdated),this._deviceManager.off("selectedMicrophoneChanged",this.selectedMicrophoneChanged),this._deviceManager.off("selectedSpeakerChanged",this.selectedSpeakerChanged),navigator.permissions){try{navigator.permissions.query({name:"camera"}).then((e=>{e.removeEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not Unsubscribe to Permissions API Camera changed events, API is not supported by browser",e)}try{navigator.permissions.query({name:"microphone"}).then((e=>{e.removeEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not Unsubscribe to Permissions API Camera changed events, API is not supported by browser",e)}}},this.permissionsApiStateChangeHandler=()=>vL(this,void 0,void 0,(function*(){yield this.updateDevicePermissionState()})),this.selectCamera=e=>{this._context.setDeviceManagerSelectedCamera(e)},this.videoDevicesUpdated=()=>vL(this,void 0,void 0,(function*(){const e=(yield this._deviceManager.getCameras()).filter((e=>!!e.name));this._context.setDeviceManagerCameras(yL(e))})),this.audioDevicesUpdated=()=>vL(this,void 0,void 0,(function*(){this._context.setDeviceManagerMicrophones(yL(yield this._deviceManager.getMicrophones())),this._deviceManager.isSpeakerSelectionAvailable&&this._context.setDeviceManagerSpeakers(yL(yield this._deviceManager.getSpeakers()))})),this.selectedMicrophoneChanged=()=>{this._context.setDeviceManagerSelectedMicrophone(this._deviceManager.selectedMicrophone)},this.selectedSpeakerChanged=()=>{this._context.setDeviceManagerSelectedSpeaker(this._deviceManager.selectedSpeaker)},this.updateDevicePermissionState=e=>vL(this,void 0,void 0,(function*(){let t=!!(null==e?void 0:e.video),i=!!(null==e?void 0:e.audio);if(navigator.permissions)try{const[e,n]=yield Promise.all([navigator.permissions.query({name:"camera"}),navigator.permissions.query({name:"microphone"})]);t="granted"===e.state,i="granted"===n.state}catch(e){console.info("Permissions API is not supported by browser",e)}this._context.setDeviceManagerDeviceAccess({video:t,audio:i}),this.setDeviceManager()})),this._deviceManager=e,this._context=t,this.setDeviceManager(),this.subscribe()}get(e,t){switch(t){case"getCameras":return this._context.withAsyncErrorTeedToState((()=>e.getCameras().then((e=>{const t=e.filter((e=>!!e.name));return this._context.setDeviceManagerCameras(yL(t)),t}))),"DeviceManager.getCameras");case"getMicrophones":return this._context.withAsyncErrorTeedToState((()=>e.getMicrophones().then((e=>(this._context.setDeviceManagerMicrophones(yL(e)),e)))),"DeviceManager.getMicrophones");case"getSpeakers":return this._context.withAsyncErrorTeedToState((()=>e.getSpeakers().then((e=>(this._context.setDeviceManagerSpeakers(yL(e)),e)))),"DeviceManager.getSpeakers");case"selectMicrophone":return this._context.withAsyncErrorTeedToState(((...t)=>e.selectMicrophone(...t).then((()=>{this._context.setDeviceManagerSelectedMicrophone(e.selectedMicrophone)}))),"DeviceManager.selectMicrophone");case"selectSpeaker":return this._context.withAsyncErrorTeedToState(((...t)=>e.selectSpeaker(...t).then((()=>{this._context.setDeviceManagerSelectedSpeaker(e.selectedSpeaker)}))),"DeviceManager.selectSpeaker");case"askDevicePermission":return this._context.withAsyncErrorTeedToState(((...t)=>e.askDevicePermission(...t).then((e=>vL(this,void 0,void 0,(function*(){return yield this.updateDevicePermissionState(e),e}))))),"DeviceManager.askDevicePermission");default:return Reflect.get(e,t)}}}const yL=e=>{const t=new Set,i=[];return e.forEach((e=>{t.has(e.id)||(i.push(e),t.add(e.id))})),i},CL=e=>!e.kind||"Call"===e.kind,TL=e=>!e.kind||"CallAgent"===e.kind,EL=e=>"TeamsCall"===e.kind,bL=e=>"TeamsCallAgent"===e.kind,_L=e=>"TeamsIncomingCall"===e.kind;function IL(e){const t=e.feature(oD.VideoEffects);return{source:e.source,mediaStreamType:e.mediaStreamType,view:void 0,videoEffects:ML(t.activeEffects)}}function wL(e){return{id:e.id,mediaStreamType:e.mediaStreamType,isAvailable:e.isAvailable,isReceiving:e.isReceiving,view:void 0,streamSize:e.size}}function AL(e,t){return{feature:t,id:e.id,mediaStreamType:e.mediaStreamType,isAvailable:e.isAvailable,isReceiving:e.isReceiving,view:void 0,streamSize:e.size}}function PL(e){const t={};for(const i of e.videoStreams)t[i.id]=wL(i);return{identifier:e.identifier,displayName:e.displayName,state:e.state,callEndReason:e.callEndReason,videoStreams:t,isMuted:e.isMuted,isSpeaking:e.isSpeaking,raisedHand:void 0,role:e.role,spotlight:void 0,mediaAccess:void 0}}function RL(e){return{scalingMode:e.scalingMode,isMirrored:e.isMirrored,target:e.target}}function ML(e){return{activeEffects:e}}function DL(e){return{raisedHandOrderPosition:e.order}}var kL=r(8156),OL=Symbol.for("immer-nothing"),NL=Symbol.for("immer-draftable"),LL=Symbol.for("immer-state");function xL(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var FL=Object.getPrototypeOf;function UL(e){return!!e&&!!e[LL]}function BL(e){return!!e&&(HL(e)||Array.isArray(e)||!!e[NL]||!!e.constructor?.[NL]||WL(e)||KL(e))}var VL=Object.prototype.constructor.toString();function HL(e){if(!e||"object"!=typeof e)return!1;const t=FL(e);if(null===t)return!0;const i=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return i===Object||"function"==typeof i&&Function.toString.call(i)===VL}function $L(e,t){0===jL(e)?Reflect.ownKeys(e).forEach((i=>{t(i,e[i],e)})):e.forEach(((i,n)=>t(n,i,e)))}function jL(e){const t=e[LL];return t?t.type_:Array.isArray(e)?1:WL(e)?2:KL(e)?3:0}function GL(e,t){return 2===jL(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function qL(e,t){return 2===jL(e)?e.get(t):e[t]}function zL(e,t,i){const n=jL(e);2===n?e.set(t,i):3===n?e.add(i):e[t]=i}function WL(e){return e instanceof Map}function KL(e){return e instanceof Set}function JL(e){return e.copy_||e.base_}function YL(e,t){if(WL(e))return new Map(e);if(KL(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const i=HL(e);if(!0===t||"class_only"===t&&!i){const t=Object.getOwnPropertyDescriptors(e);delete t[LL];let i=Reflect.ownKeys(t);for(let n=0;n<i.length;n++){const r=i[n],s=t[r];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[r]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[r]})}return Object.create(FL(e),t)}{const t=FL(e);if(null!==t&&i)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function QL(e,t=!1){return XL(e)||UL(e)||!BL(e)||(jL(e)>1&&(e.set=e.add=e.clear=e.delete=ZL),Object.freeze(e),t&&Object.entries(e).forEach((([e,t])=>QL(t,!0)))),e}function ZL(){xL(2)}function XL(e){return Object.isFrozen(e)}var ex,tx={};function ix(e){const t=tx[e];return t||xL(0),t}function nx(e,t){tx[e]||(tx[e]=t)}function rx(){return ex}function sx(e,t){t&&(ix("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ax(e){ox(e),e.drafts_.forEach(cx),e.drafts_=null}function ox(e){e===ex&&(ex=e.parent_)}function lx(e){return ex={drafts_:[],parent_:ex,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function cx(e){const t=e[LL];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function dx(e,t){t.unfinalizedDrafts_=t.drafts_.length;const i=t.drafts_[0];return void 0!==e&&e!==i?(i[LL].modified_&&(ax(t),xL(4)),BL(e)&&(e=ux(t,e),t.parent_||gx(t,e)),t.patches_&&ix("Patches").generateReplacementPatches_(i[LL].base_,e,t.patches_,t.inversePatches_)):e=ux(t,i,[]),ax(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==OL?e:void 0}function ux(e,t,i){if(XL(t))return t;const n=t[LL];if(!n)return $L(t,((r,s)=>hx(e,n,t,r,s,i))),t;if(n.scope_!==e)return t;if(!n.modified_)return gx(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let r=t,s=!1;3===n.type_&&(r=new Set(t),t.clear(),s=!0),$L(r,((r,a)=>hx(e,n,t,r,a,i,s))),gx(e,t,!1),i&&e.patches_&&ix("Patches").generatePatches_(n,i,e.patches_,e.inversePatches_)}return n.copy_}function hx(e,t,i,n,r,s,a){if(UL(r)){const a=ux(e,r,s&&t&&3!==t.type_&&!GL(t.assigned_,n)?s.concat(n):void 0);if(zL(i,n,a),!UL(a))return;e.canAutoFreeze_=!1}else a&&i.add(r);if(BL(r)&&!XL(r)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ux(e,r),t&&t.scope_.parent_||"symbol"==typeof n||!Object.prototype.propertyIsEnumerable.call(i,n)||gx(e,r)}}function gx(e,t,i=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&QL(t,i)}var px={get(e,t){if(t===LL)return e;const i=JL(e);if(!GL(i,t))return function(e,t,i){const n=vx(t,i);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,i,t);const n=i[t];return e.finalized_||!BL(n)?n:n===fx(e.base_,t)?(yx(e),e.copy_[t]=Cx(n,e)):n},has:(e,t)=>t in JL(e),ownKeys:e=>Reflect.ownKeys(JL(e)),set(e,t,i){const n=vx(JL(e),t);if(n?.set)return n.set.call(e.draft_,i),!0;if(!e.modified_){const n=fx(JL(e),t),r=n?.[LL];if(r&&r.base_===i)return e.copy_[t]=i,e.assigned_[t]=!1,!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(i,n)&&(void 0!==i||GL(e.base_,t)))return!0;yx(e),Sx(e)}return e.copy_[t]===i&&(void 0!==i||t in e.copy_)||Number.isNaN(i)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=i,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==fx(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,yx(e),Sx(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const i=JL(e),n=Reflect.getOwnPropertyDescriptor(i,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:i[t]}:n},defineProperty(){xL(11)},getPrototypeOf:e=>FL(e.base_),setPrototypeOf(){xL(12)}},mx={};function fx(e,t){const i=e[LL];return(i?JL(i):e)[t]}function vx(e,t){if(!(t in e))return;let i=FL(e);for(;i;){const e=Object.getOwnPropertyDescriptor(i,t);if(e)return e;i=FL(i)}}function Sx(e){e.modified_||(e.modified_=!0,e.parent_&&Sx(e.parent_))}function yx(e){e.copy_||(e.copy_=YL(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Cx(e,t){const i=WL(e)?ix("MapSet").proxyMap_(e,t):KL(e)?ix("MapSet").proxySet_(e,t):function(e,t){const i=Array.isArray(e),n={type_:i?1:0,scope_:t?t.scope_:rx(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let r=n,s=px;i&&(r=[n],s=mx);const{revoke:a,proxy:o}=Proxy.revocable(r,s);return n.draft_=o,n.revoke_=a,o}(e,t);return(t?t.scope_:rx()).drafts_.push(i),i}function Tx(e){if(!BL(e)||XL(e))return e;const t=e[LL];let i;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,i=YL(e,t.scope_.immer_.useStrictShallowCopy_)}else i=YL(e,!0);return $L(i,((e,t)=>{zL(i,e,Tx(t))})),t&&(t.finalized_=!1),i}$L(px,((e,t)=>{mx[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),mx.deleteProperty=function(e,t){return mx.set.call(this,e,t,void 0)},mx.set=function(e,t,i){return px.set.call(this,e[0],t,i,e[0])};var Ex=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,i)=>{if("function"==typeof e&&"function"!=typeof t){const i=t;t=e;const n=this;return function(e=i,...r){return n.produce(e,(e=>t.call(this,e,...r)))}}let n;if("function"!=typeof t&&xL(6),void 0!==i&&"function"!=typeof i&&xL(7),BL(e)){const r=lx(this),s=Cx(e,void 0);let a=!0;try{n=t(s),a=!1}finally{a?ax(r):ox(r)}return sx(r,i),dx(n,r)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===OL&&(n=void 0),this.autoFreeze_&&QL(n,!0),i){const t=[],r=[];ix("Patches").generateReplacementPatches_(e,n,t,r),i(t,r)}return n}xL(1)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...i)=>this.produceWithPatches(t,(t=>e(t,...i)));let i,n;const r=this.produce(e,t,((e,t)=>{i=e,n=t}));return[r,i,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){var t;BL(e)||xL(8),UL(e)&&(UL(t=e)||xL(10),e=Tx(t));const i=lx(this),n=Cx(e,void 0);return n[LL].isManual_=!0,ox(i),n}finishDraft(e,t){const i=e&&e[LL];i&&i.isManual_||xL(9);const{scope_:n}=i;return sx(n,t),dx(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let i;for(i=t.length-1;i>=0;i--){const n=t[i];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}i>-1&&(t=t.slice(i+1));const n=ix("Patches").applyPatches_;return UL(e)?n(e,t):this.produce(e,(e=>n(e,t)))}},bx=Ex.produce;Ex.produceWithPatches.bind(Ex),Ex.setAutoFreeze.bind(Ex),Ex.setUseStrictShallowCopy.bind(Ex),Ex.applyPatches.bind(Ex),Ex.createDraft.bind(Ex),Ex.finishDraft.bind(Ex);const _x=(e,t=Ix(),i)=>{try{return JSON.stringify(e,t,i)}catch(e){return void console.error(e)}},Ix=()=>{const e=new Set;return function(t,i){return"object"!=typeof i?i:e.has(i)?"Visited-Ref":(e.add(i),i)}};class wx extends Error{constructor(e,t,i){super(),this.target=e,this.innerError=t,"code"in t&&(this.code=t.code),"subCode"in t&&(this.subCode=t.subCode),this.timestamp=null!=i?i:new Date(Date.now()),this.name="CallError",this.message=`${this.target}: ${this.innerError.message} code=${this.code} subCode=${this.subCode}`}}const Ax=R("communication-react:calling-stateful");var Px;!function(e){e.VIEW_RENDER_SUCCEED="VIEW_RENDER_SUCCEED",e.START_DISPOSE_STREAM="START_DISPOSE_STREAM",e.START_STREAM_RENDERING="START_STREAM_RENDERING",e.DISPOSING_RENDERER="DISPOSING_RENDERER",e.CREATING_VIEW="CREATING_VIEW",e.CREATE_STREAM_INVALID_PARAMS="CREATE_STREAM_INVALID_PARAMS",e.DISPOSE_STREAM_INVALID_PARAMS="DISPOSE_STREAM_INVALID_PARAMS",e.STREAM_ALREADY_RENDERED="STREAM_ALREADY_RENDERED",e.STREAM_ALREADY_DISPOSED="STREAM_ALREADY_DISPOSED",e.STREAM_STOPPING="STREAM_STOPPING",e.CREATED_STREAM_STOPPING="CREATED_STREAM_STOPPING",e.STREAM_RENDERING="STREAM_RENDERING",e.STREAM_NOT_FOUND="STREAM_NOT_FOUND",e.RENDER_INFO_NOT_FOUND="RENDER_INFO_NOT_FOUND",e.DISPOSE_INFO_NOT_FOUND="DISPOSE_INFO_NOT_FOUND",e.RENDERER_NOT_FOUND="RENDERER_NOT_FOUND",e.CREATE_STREAM_FAIL="CREATE_STREAM_FAIL"}(Px||(Px={}));class Rx{constructor(){this._callIdHistory=new Map}updateCallIdHistory(e,t){const i=this._callIdHistory.get(e);void 0!==i&&this.latestCallId(e)!==t&&console.trace(`${e} alredy exists and maps to ${i}, which is not the same as ${t}`),this._callIdHistory.delete(e),this._callIdHistory.set(t,e)}latestCallId(e){let t=e;for(;;){const e=this._callIdHistory.get(t);if(void 0===e)break;t=e}return t}}!function(){class e extends Map{constructor(e,t){super(),this[LL]={type_:2,parent_:t,scope_:t?t.scope_:rx(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:e,draft_:this,isManual_:!1,revoked_:!1}}get size(){return JL(this[LL]).size}has(e){return JL(this[LL]).has(e)}set(e,i){const n=this[LL];return r(n),JL(n).has(e)&&JL(n).get(e)===i||(t(n),Sx(n),n.assigned_.set(e,!0),n.copy_.set(e,i),n.assigned_.set(e,!0)),this}delete(e){if(!this.has(e))return!1;const i=this[LL];return r(i),t(i),Sx(i),i.base_.has(e)?i.assigned_.set(e,!1):i.assigned_.delete(e),i.copy_.delete(e),!0}clear(){const e=this[LL];r(e),JL(e).size&&(t(e),Sx(e),e.assigned_=new Map,$L(e.base_,(t=>{e.assigned_.set(t,!1)})),e.copy_.clear())}forEach(e,t){JL(this[LL]).forEach(((i,n,r)=>{e.call(t,this.get(n),n,this)}))}get(e){const i=this[LL];r(i);const n=JL(i).get(e);if(i.finalized_||!BL(n))return n;if(n!==i.base_.get(e))return n;const s=Cx(n,i);return t(i),i.copy_.set(e,s),s}keys(){return JL(this[LL]).keys()}values(){const e=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}}entries(){const e=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const i=this.get(t.value);return{done:!1,value:[t.value,i]}}}}[Symbol.iterator](){return this.entries()}}function t(e){e.copy_||(e.assigned_=new Map,e.copy_=new Map(e.base_))}class i extends Set{constructor(e,t){super(),this[LL]={type_:3,parent_:t,scope_:t?t.scope_:rx(),modified_:!1,finalized_:!1,copy_:void 0,base_:e,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return JL(this[LL]).size}has(e){const t=this[LL];return r(t),t.copy_?!!t.copy_.has(e)||!(!t.drafts_.has(e)||!t.copy_.has(t.drafts_.get(e))):t.base_.has(e)}add(e){const t=this[LL];return r(t),this.has(e)||(n(t),Sx(t),t.copy_.add(e)),this}delete(e){if(!this.has(e))return!1;const t=this[LL];return r(t),n(t),Sx(t),t.copy_.delete(e)||!!t.drafts_.has(e)&&t.copy_.delete(t.drafts_.get(e))}clear(){const e=this[LL];r(e),JL(e).size&&(n(e),Sx(e),e.copy_.clear())}values(){const e=this[LL];return r(e),n(e),e.copy_.values()}entries(){const e=this[LL];return r(e),n(e),e.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(e,t){const i=this.values();let n=i.next();for(;!n.done;)e.call(t,n.value,n.value,this),n=i.next()}}function n(e){e.copy_||(e.copy_=new Set,e.base_.forEach((t=>{if(BL(t)){const i=Cx(t,e);e.drafts_.set(t,i),e.copy_.add(i)}else e.copy_.add(t)})))}function r(e){e.revoked_&&xL(3,JSON.stringify(JL(e)))}nx("MapSet",{proxyMap_:function(t,i){return new e(t,i)},proxySet_:function(e,t){return new i(e,t)}})}(),function(){const e="replace",t="add",i="remove";function n(e){if(!BL(e))return e;if(Array.isArray(e))return e.map(n);if(WL(e))return new Map(Array.from(e.entries()).map((([e,t])=>[e,n(t)])));if(KL(e))return new Set(Array.from(e).map(n));const t=Object.create(FL(e));for(const i in e)t[i]=n(e[i]);return GL(e,NL)&&(t[NL]=e[NL]),t}function r(e){return UL(e)?n(e):e}nx("Patches",{applyPatches_:function(r,s){return s.forEach((s=>{const{path:a,op:o}=s;let l=r;for(let e=0;e<a.length-1;e++){const t=jL(l);let i=a[e];"string"!=typeof i&&"number"!=typeof i&&(i=""+i),0!==t&&1!==t||"__proto__"!==i&&"constructor"!==i||xL(19),"function"==typeof l&&"prototype"===i&&xL(19),l=qL(l,i),"object"!=typeof l&&xL(18,a.join("/"))}const c=jL(l),d=n(s.value),u=a[a.length-1];switch(o){case e:switch(c){case 2:return l.set(u,d);case 3:xL(16);default:return l[u]=d}case t:switch(c){case 1:return"-"===u?l.push(d):l.splice(u,0,d);case 2:return l.set(u,d);case 3:return l.add(d);default:return l[u]=d}case i:switch(c){case 1:return l.splice(u,1);case 2:return l.delete(u);case 3:return l.delete(s.value);default:return delete l[u]}default:xL(17)}})),r},generatePatches_:function(n,s,a,o){switch(n.type_){case 0:case 2:return function(n,s,a,o){const{base_:l,copy_:c}=n;$L(n.assigned_,((n,d)=>{const u=qL(l,n),h=qL(c,n),g=d?GL(l,n)?e:t:i;if(u===h&&g===e)return;const p=s.concat(n);a.push(g===i?{op:g,path:p}:{op:g,path:p,value:h}),o.push(g===t?{op:i,path:p}:g===i?{op:t,path:p,value:r(u)}:{op:e,path:p,value:r(u)})}))}(n,s,a,o);case 1:return function(n,s,a,o){let{base_:l,assigned_:c}=n,d=n.copy_;d.length<l.length&&([l,d]=[d,l],[a,o]=[o,a]);for(let t=0;t<l.length;t++)if(c[t]&&d[t]!==l[t]){const i=s.concat([t]);a.push({op:e,path:i,value:r(d[t])}),o.push({op:e,path:i,value:r(l[t])})}for(let e=l.length;e<d.length;e++){const i=s.concat([e]);a.push({op:t,path:i,value:r(d[e])})}for(let e=d.length-1;l.length<=e;--e){const t=s.concat([e]);o.push({op:i,path:t})}}(n,s,a,o);case 3:return function(e,n,r,s){let{base_:a,copy_:o}=e,l=0;a.forEach((e=>{if(!o.has(e)){const a=n.concat([l]);r.push({op:i,path:a,value:e}),s.unshift({op:t,path:a,value:e})}l++})),l=0,o.forEach((e=>{if(!a.has(e)){const a=n.concat([l]);r.push({op:t,path:a,value:e}),s.unshift({op:i,path:a,value:e})}l++}))}(n,s,a,o)}},generateReplacementPatches_:function(t,i,n,r){n.push({op:e,path:[],value:i===OL?void 0:i}),r.push({op:e,path:[],value:t})}})}();class Mx{constructor(e,t=50){this._callIdHistory=new Rx,this._timeOutId={},this._latestCallIdOfNotification={},this.teeErrorToState=(e,t)=>{const i=Dx(t,e);this.setLatestError(t,i)},this._logger=R("communication-react:calling-context"),this._state={calls:{},callsEnded:{},incomingCalls:{},incomingCallsEnded:{},deviceManager:{isSpeakerSelectionAvailable:!1,cameras:[],microphones:[],speakers:[],unparentedViews:[]},callAgent:void 0,userId:e,environmentInfo:void 0,latestErrors:{},latestNotifications:{}},this._emitter=new kL.EventEmitter,this._emitter.setMaxListeners(t),this._atomicId=0}getState(){return this._state}modifyState(e){const t=this._state;this._state=bx(this._state,e,(e=>{"verbose"===I&&this._logger.info(`State change: ${_x(e)}`)})),this._state!==t&&this._emitter.emit("stateChanged",this._state)}onStateChange(e){this._emitter.on("stateChanged",e)}offStateChange(e){this._emitter.off("stateChanged",e)}clearCallRelatedState(){this.modifyState((e=>{e.calls={},e.incomingCalls={},e.callsEnded={},e.incomingCallsEnded={}}))}setCallAgent(e){this.modifyState((t=>{t.callAgent=e}))}setCall(e){this.modifyState((t=>{const i=this._callIdHistory.latestCallId(e.id),n=t.calls[i];n?(n.callerInfo=e.callerInfo,n.state=e.state,n.callEndReason=e.callEndReason,n.direction=e.direction,n.isMuted=e.isMuted,n.isScreenSharingOn=e.isScreenSharingOn,n.localVideoStreams=e.localVideoStreams,n.remoteParticipants=e.remoteParticipants,n.transcription.isTranscriptionActive=e.transcription.isTranscriptionActive,n.optimalVideoCount.maxRemoteVideoStreams=e.optimalVideoCount.maxRemoteVideoStreams,n.recording.isRecordingActive=e.recording.isRecordingActive,n.raiseHand.raisedHands=e.raiseHand.raisedHands,n.pptLive.isActive=e.pptLive.isActive,n.raiseHand.localParticipantRaisedHand=e.raiseHand.localParticipantRaisedHand,n.role=e.role,n.totalParticipantCount=e.totalParticipantCount,n.captionsFeature.currentSpokenLanguage=e.captionsFeature.currentSpokenLanguage,n.captionsFeature.currentCaptionLanguage=e.captionsFeature.currentCaptionLanguage,n.info=e.info,n.meetingConference=e.meetingConference):t.calls[i]=e})),this._state.incomingCalls[e.id]&&this.removeIncomingCall(e.id)}removeCall(e){this.modifyState((t=>{delete t.calls[this._callIdHistory.latestCallId(e)]}))}setCallEnded(e,t){const i=this._callIdHistory.latestCallId(e);this.modifyState((e=>{const n=e.calls[i];if(n){for(n.endTime=new Date,n.callEndReason=t,delete e.calls[i];Object.keys(e.callsEnded).length>=10;){const t=kx(e.callsEnded);t&&delete e.callsEnded[t]}e.callsEnded[i]=n}}))}setCallState(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.state=t)}))}setCallId(e,t){this._callIdHistory.updateCallIdHistory(e,t),this.modifyState((i=>{const n=i.calls[t];n&&(n.id=e,delete i.calls[t],i.calls[e]=n),Object.keys(this._latestCallIdOfNotification).forEach((i=>{this._latestCallIdOfNotification[i]===t&&(this._latestCallIdOfNotification[i]=e)})),this._openBreakoutRoom===t&&(this._openBreakoutRoom=e)}))}setEnvironmentInfo(e){this.modifyState((t=>{t.environmentInfo=e}))}setCallIsScreenSharingOn(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.isScreenSharingOn=t)}))}setCallRemoteParticipants(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(i.forEach((e=>{delete r.remoteParticipants[e]})),t.forEach((e=>{r.remoteParticipants[iL(e.identifier)]=e})))}))}setCallRemoteParticipantsEnded(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(i.forEach((e=>{delete r.remoteParticipantsEnded[e]})),t.forEach((e=>{r.remoteParticipantsEnded[iL(e.identifier)]=e})))}))}setCallLocalVideoStream(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){for(const e of i){const t=r.localVideoStreams.findIndex((t=>t.mediaStreamType===e.mediaStreamType));t>-1&&r.localVideoStreams.splice(t,1)}for(const e of t){const t=r.localVideoStreams.findIndex((t=>t.mediaStreamType===e.mediaStreamType));t>-1?r.localVideoStreams[t]=e:r.localVideoStreams.push(e)}}}))}setCallLocalVideoStreamVideoEffects(e,t){this.modifyState((i=>{var n;const r=i.calls[this._callIdHistory.latestCallId(e)];if(r){const e=null===(n=r.localVideoStreams)||void 0===n?void 0:n.find((e=>"Video"===e.mediaStreamType));e&&(e.videoEffects=t)}}))}setCallIsMicrophoneMuted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.isMuted=t)}))}setRole(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.role=t)}))}setTotalParticipantCount(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.totalParticipantCount=t)}))}setCallDominantSpeakers(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.dominantSpeakers=t)}))}setCallRecordingActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.recording.isRecordingActive=t)}))}setCallRecordingInfos(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.recording.activeRecordings=t,r.recording.lastStoppedRecording=i)}))}setCallLocalRecordingActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.localRecording.isLocalRecordingActive=t)}))}setCallLocalRecordingInfos(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.localRecording.activeLocalRecordings=t,r.localRecording.lastStoppedLocalRecording=i)}))}setCallPPTLiveActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.pptLive.isActive=t)}))}setCallParticipantPPTLive(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r&&t){const e=r.remoteParticipants[t];e&&(e.contentSharingStream=i,r.contentSharingRemoteParticipant=t)}}))}setTogetherModeVideoStreams(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){for(const e of i)"Video"===e.mediaStreamType&&(r.togetherMode.streams.mainVideoStream=void 0,r.togetherMode.isActive=!1,r.togetherMode.seatingPositions={});for(const e of t){const t=r.togetherMode.streams.mainVideoStream;t&&t.id===e.id?(t.mediaStreamType=e.mediaStreamType,t.isAvailable=e.isAvailable,t.isReceiving=e.isReceiving):r.togetherMode.streams.mainVideoStream=e,r.togetherMode.isActive=!0}}}))}setTogetherModeVideoStreamIsAvailable(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.togetherMode.streams.mainVideoStream;e&&(null==e?void 0:e.id)===t&&(e.isAvailable=i)}}))}setTogetherModeVideoStreamIsReceiving(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.togetherMode.streams.mainVideoStream;e&&(null==e?void 0:e.id)===t&&(e.isReceiving=i)}}))}setTogetherModeVideoStreamSize(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.togetherMode.streams.mainVideoStream;e&&(null==e?void 0:e.id)===t&&(e.streamSize=i)}}))}removeTogetherModeVideoStream(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n)for(const e of t)"Video"===e.mediaStreamType&&(n.togetherMode.streams.mainVideoStream=void 0,n.togetherMode.isActive=!1)}))}setTogetherModeSeatingCoordinates(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e={};for(const[i,n]of t.entries())e[i]=n;n.togetherMode.seatingPositions=e}}))}setCallRaisedHands(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){n.raiseHand.raisedHands=t.map((e=>DL(e)));const e=t.find((e=>iL(e.identifier)===iL(this._state.userId)));n.raiseHand.localParticipantRaisedHand=e?DL(e):void 0}}))}setParticipantIsRaisedHand(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.raisedHand=i?DL(i):i)}}))}setReceivedReactionFromParticipant(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(!r)return;clearTimeout(this._timeOutId[t]);const s=r.remoteParticipants[t],a=i?{reactionMessage:i,receivedOn:new Date}:void 0;t===iL(this._state.userId)?r.localParticipantReaction=a:s?s.reactionState=a:null!==i&&console.warn(`Participant ${t} not found in call ${e}. Cannot set reaction state.`),i&&(this._timeOutId[t]=setTimeout((()=>{!function(e,t,i){e.setReceivedReactionFromParticipant(t,i,null)}(this,e,t)}),4133))}))}setCallTranscriptionActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.transcription.isTranscriptionActive=t)}))}setCapabilities(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.capabilitiesFeature={capabilities:t,latestCapabilitiesChangeInfo:i})}))}setHideAttendeeNames(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(t.oldValue.viewAttendeeNames!==t.newValue.viewAttendeeNames){const e=t.newValue.viewAttendeeNames;n&&e&&!e.isPresent&&"MeetingRestricted"===e.reason?n.hideAttendeeNames=!0:n&&(n.hideAttendeeNames=!1)}}))}setSpotlight(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.spotlight=Object.assign(Object.assign({},r.spotlight),{spotlightedParticipants:t,maxParticipantsToSpotlight:i}))}))}setTeamsMeetingConference(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];var r;n&&(n.meetingConference={conferencePhones:(r=t,r?r.phoneNumbers.flatMap((e=>{var t,i,n,s;const a={conferenceId:r.phoneConferenceId,country:e.countryName,city:e.cityName,phoneNumber:"",isTollFree:!1},o=Object.assign({},a);o.phoneNumber=null!==(i=null===(t=e.tollPhoneNumber)||void 0===t?void 0:t.phoneNumber)&&void 0!==i?i:"",o.isTollFree=!1;const l=Object.assign({},a);return l.phoneNumber=null!==(s=null===(n=e.tollFreePhoneNumber)||void 0===n?void 0:n.phoneNumber)&&void 0!==s?s:"",l.isTollFree=!0,[o,l].filter((e=>e.phoneNumber))})):[])})}))}setParticipantSpotlighted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e=n.remoteParticipants[iL(t.identifier)];e?e.spotlight={spotlightedOrderPosition:t.order}:n.spotlight&&iL(i.userId)===iL(t.identifier)&&(n.spotlight.localParticipantSpotlight={spotlightedOrderPosition:t.order})}}))}setParticipantNotSpotlighted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e=n.remoteParticipants[iL(t.identifier)];e?e.spotlight=void 0:n.spotlight&&iL(i.userId)===iL(t.identifier)&&(n.spotlight.localParticipantSpotlight=void 0)}}))}setAssignedBreakoutRoom(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.breakoutRooms=Object.assign(Object.assign({},n.breakoutRooms),{assignedBreakoutRoom:t}))}))}setBreakoutRoomSettings(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.breakoutRooms=Object.assign(Object.assign({},n.breakoutRooms),{breakoutRoomSettings:t}))}))}setBreakoutRoomDisplayName(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.breakoutRooms=Object.assign(Object.assign({},n.breakoutRooms),{breakoutRoomDisplayName:t}))}))}setOpenBreakoutRoom(e){this._openBreakoutRoom=e}deleteOpenBreakoutRoom(){this._openBreakoutRoom=void 0}getOpenBreakoutRoom(){return this._openBreakoutRoom}setCallScreenShareParticipant(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.screenShareRemoteParticipant=t)}))}setLocalVideoStreamRendererView(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.localVideoStreams.find((e=>e.mediaStreamType===t));e&&(e.view=i)}}))}setTogetherModeVideoStreamRendererView(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r&&"Video"===t){const e=r.togetherMode.streams.mainVideoStream;e&&(e.view=i)}}))}setParticipantState(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.state=i)}}))}setParticipantIsMuted(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.isMuted=i)}}))}setOptimalVideoCount(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.optimalVideoCount.maxRemoteVideoStreams=t)}))}setParticipantRole(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.role=i)}}))}setParticipantDisplayName(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.displayName=i)}}))}setParticipantIsSpeaking(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.isSpeaking=i)}}))}setParticipantVideoStream(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];if(e){const t=e.videoStreams[i.id];t?(t.isAvailable=i.isAvailable,t.isReceiving=i.isReceiving,t.mediaStreamType=i.mediaStreamType):e.videoStreams[i.id]=i}}}))}setRemoteVideoStreamIsAvailable(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.isAvailable=n)}}}))}setRemoteVideoStreamIsReceiving(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.isReceiving=n)}}}))}setRemoteVideoStreamSize(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.streamSize=n)}}}))}setRemoteVideoStreams(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){for(const t of n)delete e.videoStreams[t];for(const t of i){const i=e.videoStreams[t.id];i?(i.mediaStreamType=t.mediaStreamType,i.isAvailable=t.isAvailable,i.isReceiving=t.isReceiving):e.videoStreams[t.id]=t}}}}))}setRemoteVideoStreamRendererView(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.view=n)}}}))}setRemoteVideoStreamViewScalingMode(e,t,i,n){this.modifyState((r=>{const s=r.calls[this._callIdHistory.latestCallId(e)];if(s){const e=s.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&t.view&&(t.view.scalingMode=n)}}}))}setIncomingCall(e){this.modifyState((t=>{const i=t.incomingCalls[e.id];i?i.callerInfo=e.callerInfo:t.incomingCalls[e.id]=e}))}removeIncomingCall(e){this.modifyState((t=>{delete t.incomingCalls[e]}))}setIncomingCallEnded(e,t){this.modifyState((i=>{const n=i.incomingCalls[e];if(n){for(n.endTime=new Date,n.callEndReason=t,delete i.incomingCalls[e];Object.keys(i.incomingCallsEnded).length>=10;){const e=kx(i.incomingCallsEnded);e&&delete i.incomingCallsEnded[e]}i.incomingCallsEnded[e]=n}}))}setDeviceManagerIsSpeakerSelectionAvailable(e){this.modifyState((t=>{t.deviceManager.isSpeakerSelectionAvailable=e}))}setDeviceManagerSelectedMicrophone(e){this.modifyState((t=>{t.deviceManager.selectedMicrophone=e}))}setDeviceManagerSelectedSpeaker(e){this.modifyState((t=>{t.deviceManager.selectedSpeaker=e}))}setDeviceManagerSelectedCamera(e){this.modifyState((t=>{t.deviceManager.selectedCamera=e}))}setDeviceManagerCameras(e){this.modifyState((t=>{e.length>0&&!e.some((e=>{var i;return e.id===(null===(i=t.deviceManager.selectedCamera)||void 0===i?void 0:i.id)}))&&(t.deviceManager.selectedCamera=e[0]),t.deviceManager.cameras=e}))}setDeviceManagerMicrophones(e){this.modifyState((t=>{t.deviceManager.microphones=e}))}setDeviceManagerSpeakers(e){this.modifyState((t=>{t.deviceManager.speakers=e}))}setDeviceManagerDeviceAccess(e){this.modifyState((t=>{t.deviceManager.deviceAccess=e}))}setDeviceManagerUnparentedView(e,t){this.modifyState((i=>{i.deviceManager.unparentedViews.push({source:e.source,mediaStreamType:e.mediaStreamType,view:t})}))}deleteDeviceManagerUnparentedView(e){this.modifyState((t=>{const i=t.deviceManager.unparentedViews.findIndex((t=>t.mediaStreamType===e.mediaStreamType));-1!==i&&t.deviceManager.unparentedViews.splice(i,1)}))}setDeviceManagerUnparentedViewVideoEffects(e,t){this.modifyState((i=>{const n=i.deviceManager.unparentedViews.find((t=>t.mediaStreamType===e.mediaStreamType));n&&(n.videoEffects=t)}))}getAndIncrementAtomicId(){const e=this._atomicId;return this._atomicId++,e}processNewRealTimeText(e,t){var i,n,r,s,a;if("Final"===t.resultType)e.completedMessages||(e.completedMessages=[]),null===(i=e.completedMessages)||void 0===i||i.push(t),t.isMe?e.myInProgress=void 0:e.currentInProgress=null===(n=e.currentInProgress)||void 0===n?void 0:n.filter((e=>e.sequenceId!==t.sequenceId));else if(t.isMe)e.myInProgress=t;else{if(!e.currentInProgress)return e.currentInProgress=[],void e.currentInProgress.push(t);const i=null===(r=e.currentInProgress)||void 0===r?void 0:r.findIndex((e=>e.sequenceId===t.sequenceId));-1===i?null===(s=e.currentInProgress)||void 0===s||s.push(t):e.currentInProgress[i]=t}e.completedMessages||(e.completedMessages=[]),this.findTimeoutRealTimeText(e.currentInProgress,e.completedMessages),this.findTimeoutRealTimeText(e.myInProgress,e.completedMessages),e.completedMessages&&(null===(a=e.completedMessages)||void 0===a?void 0:a.length)>50&&e.completedMessages.shift()}findTimeoutRealTimeText(e,t){e&&Array.isArray(e)?e.forEach(((i,n)=>{i.updatedTimestamp&&Date.now()-i.updatedTimestamp.getTime()>5e3&&(i.resultType="Final",t.push(i),e&&e.splice(n,1))})):e&&e.updatedTimestamp&&Date.now()-e.updatedTimestamp.getTime()>5e3&&(e.resultType="Final",t.push(e),e=void 0)}processNewCaption(e,t){var i;if(t.lastUpdatedTimestamp=new Date,0===e.length)e.push(t);else if("Final"===(null===(i=e[e.length-1])||void 0===i?void 0:i.resultType))e.push(t);else{const i=e[e.length-1];i&&i.speaker.identifier&&t.speaker.identifier&&iL(i.speaker.identifier)===iL(t.speaker.identifier)?e[e.length-1]=t:(null==i?void 0:i.lastUpdatedTimestamp)&&Date.now()-i.lastUpdatedTimestamp.getTime()>5e3&&(i.resultType="Final",e.push(t))}e.length>50&&e.shift()}addTeamsCaption(e,t){this.modifyState((i=>{var n;const r=i.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.captionsFeature.currentCaptionLanguage;t.captionLanguage.toUpperCase()!==e.toUpperCase()&&""!==e&&void 0!==e||this.processNewCaption(null!==(n=null==r?void 0:r.captionsFeature.captions)&&void 0!==n?n:[],function(e){return Object.assign({},e)}(t))}}))}addCaption(e,t){this.modifyState((i=>{var n;const r=i.calls[this._callIdHistory.latestCallId(e)];r&&this.processNewCaption(null!==(n=null==r?void 0:r.captionsFeature.captions)&&void 0!==n?n:[],function(e){return Object.assign({captionText:e.spokenText},e)}(t))}))}addRealTimeText(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&this.processNewRealTimeText(n.realTimeTextFeature.realTimeTexts,function(e){return Object.assign({message:e.text,isMe:e.isLocal},e)}(t))}))}setCaptionsKind(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.captionsKind=t)}))}clearCaptions(e){this.modifyState((t=>{const i=t.calls[this._callIdHistory.latestCallId(e)];i&&(i.captionsFeature.captions=i.captionsFeature.captions.filter((e=>"message"in e)))}))}setIsCaptionActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.isCaptionsFeatureActive=t)}))}setIsRealTimeTextActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.realTimeTextFeature.isRealTimeTextFeatureActive=t)}))}setStartCaptionsInProgress(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.startCaptionsInProgress=t)}))}setSelectedSpokenLanguage(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.currentSpokenLanguage=t)}))}setSelectedCaptionLanguage(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.currentCaptionLanguage=t)}))}setAvailableCaptionLanguages(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.supportedCaptionLanguages=t)}))}setAvailableSpokenLanguages(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.supportedSpokenLanguages=t)}))}setAcceptedTransfer(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.transfer.acceptedTransfers[t.callId]=t)}))}withAsyncErrorTeedToState(e,t){return(...i)=>{return n=this,r=void 0,a=function*(){try{return yield e(...i)}catch(e){const i=Dx(t,e);throw this.setLatestError(t,i),i}},new((s=void 0)||(s=Promise))((function(e,t){function i(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s((function(e){e(n)}))).then(i,o)}l((a=a.apply(n,r||[])).next())}));var n,r,s,a}}withErrorTeedToState(e,t){return(...i)=>{try{return Ax.info(`Calling stateful client target function called: ${t}`),e(...i)}catch(e){const i=Dx(t,e);throw this.setLatestError(t,i),i}}}setLatestError(e,t){this.modifyState((i=>{i.latestErrors[e]=t}))}setLatestNotification(e,t){this._latestCallIdOfNotification[t.target]=e,this.modifyState((e=>{e.latestNotifications[t.target]=t}))}deleteLatestNotification(e,t){const i=this._latestCallIdOfNotification[e];t&&i!==t||this.modifyState((t=>{delete t.latestNotifications[e]}))}setMediaAccesses(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&t.forEach((e=>{const t=n.remoteParticipants[iL(e.participant)];t&&(t.mediaAccess={isAudioPermitted:e.isAudioPermitted,isVideoPermitted:e.isVideoPermitted})}))}))}setMeetingMediaAccess(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&t&&(n.meetingMediaAccess={isAudioPermitted:t.isAudioPermitted,isVideoPermitted:t.isVideoPermitted})}))}}const Dx=(e,t)=>t instanceof Error?new wx(e,t):new wx(e,new Error(t)),kx=e=>{var t,i,n,r;const s=Object.entries(e),a=s[0];if(!a)return;let[o,l]=a;if(void 0===l.endTime)return o;for(const[e,a]of s.slice(1)){if(void 0===a.endTime)return e;(null!==(i=null===(t=a.endTime)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)<(null!==(r=null===(n=l.endTime)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&([o,l]=[e,a])}return o};class Ox{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.on("CaptionsReceived",this.onCaptionsReceived),this._captions.on("CaptionLanguageChanged",this.isCaptionLanguageChanged),this._captions.on("SpokenLanguageChanged",this.isSpokenLanguageChanged)},this.unsubscribe=()=>{this._captions.off("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.off("CaptionsReceived",this.onCaptionsReceived),this._captions.off("CaptionLanguageChanged",this.isCaptionLanguageChanged),this._captions.off("SpokenLanguageChanged",this.isSpokenLanguageChanged)},this.onCaptionsReceived=e=>{this._context.addTeamsCaption(this._callIdRef.callId,e)},this.isCaptionsActiveChanged=()=>{this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive)},this.isCaptionLanguageChanged=()=>{this._context.setSelectedCaptionLanguage(this._callIdRef.callId,this._captions.activeCaptionLanguage)},this.isSpokenLanguageChanged=()=>{this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage)},this._callIdRef=e,this._context=t,this._captions=i,this._captions.isCaptionsFeatureActive&&this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive),this._context.setAvailableSpokenLanguages(this._callIdRef.callId,this._captions.supportedSpokenLanguages),"supportedCaptionLanguages"in this._captions&&this._context.setAvailableCaptionLanguages(this._callIdRef.callId,this._captions.supportedCaptionLanguages),this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage),this._context.setSelectedCaptionLanguage(this._callIdRef.callId,this._captions.activeCaptionLanguage),this.subscribe()}}class Nx{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.on("SpokenLanguageChanged",this.isSpokenLanguageChanged),this._captions.on("CaptionsReceived",this.onCaptionsReceived)},this.unsubscribe=()=>{this._captions.off("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.off("SpokenLanguageChanged",this.isSpokenLanguageChanged),this._captions.off("CaptionsReceived",this.onCaptionsReceived)},this.onCaptionsReceived=e=>{this._context.addCaption(this._callIdRef.callId,e)},this.isCaptionsActiveChanged=()=>{this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive)},this.isSpokenLanguageChanged=()=>{this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage)},this._callIdRef=e,this._context=t,this._captions=i,this._captions.isCaptionsFeatureActive&&this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive),this._context.setAvailableSpokenLanguages(this._callIdRef.callId,this._captions.supportedSpokenLanguages),this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage),this.subscribe()}}class Lx{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsKindChanged",this.isCaptionsKindChanged)},this.unsubscribe=()=>{var e,t;this._captions.off("CaptionsKindChanged",this.isCaptionsKindChanged),null===(e=this._TeamsCaptionsSubscriber)||void 0===e||e.unsubscribe(),null===(t=this._CaptionsSubscriber)||void 0===t||t.unsubscribe()},this.isCaptionsKindChanged=()=>{var e;this._context.setCaptionsKind(this._callIdRef.callId,this._captions.captions.kind),"TeamsCaptions"===this._captions.captions.kind&&(null===(e=this._CaptionsSubscriber)||void 0===e||e.unsubscribe(),this._TeamsCaptionsSubscriber=new Ox(this._callIdRef,this._context,this._captions.captions))},this._callIdRef=e,this._context=t,this._captions=i,this._context.setCaptionsKind(this._callIdRef.callId,this._captions.captions.kind),"TeamsCaptions"===this._captions.captions.kind?this._TeamsCaptionsSubscriber=new Ox(this._callIdRef,this._context,this._captions.captions):this._CaptionsSubscriber=new Nx(this._callIdRef,this._context,this._captions.captions),this.subscribe()}}class xx{constructor(e){this.subscribe=()=>{this._localVideoStreamEffectsAPI.on("effectsStarted",this.effectsStarted),this._localVideoStreamEffectsAPI.on("effectsStopped",this.effectsStopped),this._localVideoStreamEffectsAPI.on("effectsError",this.effectsError)},this.unsubscribe=()=>{this._localVideoStreamEffectsAPI.off("effectsStarted",this.effectsStarted),this._localVideoStreamEffectsAPI.off("effectsStopped",this.effectsStopped),this._localVideoStreamEffectsAPI.off("effectsError",this.effectsError)},this.effectsStarted=()=>{this.updateStatefulVideoEffects()},this.effectsStopped=()=>{this.updateStatefulVideoEffects()},this.effectsError=e=>{this.updateStatefulVideoEffects(),this._context.teeErrorToState(new Error(e.message),"VideoEffectsFeature.startEffects")},this.updateStatefulVideoEffects=()=>{const e=ML(this._localVideoStreamEffectsAPI.activeEffects);"unparented"===this._parent?this._context.setDeviceManagerUnparentedViewVideoEffects(this._localVideoStream,e):this._context.setCallLocalVideoStreamVideoEffects(this._parent.callId,e)},this._parent=e.parent,this._context=e.context,this._localVideoStream=e.localVideoStream,this._localVideoStreamEffectsAPI=e.localVideoStreamEffectsAPI,this.subscribe()}}class Fx{constructor(e,t,i,n){this.subscribe=()=>{this._remoteVideoStream.on("isAvailableChanged",this.isAvailableChanged),this._remoteVideoStream.on("isReceivingChanged",this.isReceivingChanged),this._remoteVideoStream.on("sizeChanged",this.isSizeChanged),this.checkAndUpdateScreenShareState()},this.unsubscribe=()=>{this._remoteVideoStream.off("isAvailableChanged",this.isAvailableChanged),this._remoteVideoStream.off("isReceivingChanged",this.isReceivingChanged),this._remoteVideoStream.off("sizeChanged",this.isSizeChanged)},this.includesActiveScreenShareStream=e=>{for(const t of Object.values(e))if("ScreenSharing"===t.mediaStreamType&&t.isAvailable)return!0;return!1},this.checkAndUpdateScreenShareState=()=>{var e,t,i;if("ScreenSharing"!==this._remoteVideoStream.mediaStreamType)return;if(this._remoteVideoStream.isAvailable)return void this._context.setCallScreenShareParticipant(this._callIdRef.callId,this._participantKey);const n=null===(e=this._context.getState().calls[this._callIdRef.callId])||void 0===e?void 0:e.screenShareRemoteParticipant;if(!n||n===this._participantKey)return void this._context.setCallScreenShareParticipant(this._callIdRef.callId,void 0);const r=null===(i=null===(t=this._context.getState().calls[this._callIdRef.callId])||void 0===t?void 0:t.remoteParticipants[n])||void 0===i?void 0:i.videoStreams;r&&this.includesActiveScreenShareStream(r)||this._context.setCallScreenShareParticipant(this._callIdRef.callId,void 0)},this.isAvailableChanged=()=>{this._context.setRemoteVideoStreamIsAvailable(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.isAvailable),this.checkAndUpdateScreenShareState()},this.isReceivingChanged=()=>{this._context.setRemoteVideoStreamIsReceiving(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.isReceiving)},this.isSizeChanged=()=>{var e,t,i,n,r,s,a;if(0===(null===(e=this._remoteVideoStream)||void 0===e?void 0:e.size.width)&&0===(null===(t=this._remoteVideoStream)||void 0===t?void 0:t.size.height))return;const o=null===(r=null===(n=null===(i=this._context.getState().calls[this._callIdRef.callId])||void 0===i?void 0:i.remoteParticipants[this._participantKey])||void 0===n?void 0:n.videoStreams[this._remoteVideoStream.id])||void 0===r?void 0:r.streamSize,l=o?o.width/o.height:void 0,c=(null===(s=this._remoteVideoStream)||void 0===s?void 0:s.size.width)/(null===(a=this._remoteVideoStream)||void 0===a?void 0:a.size.height);o&&l===c||this._context.setRemoteVideoStreamSize(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.size)},this._callIdRef=e,this._participantKey=t,this._remoteVideoStream=i,this._context=n,this.subscribe()}}const Ux=(e,t)=>{e[t.level](_x(t))};function Bx(e,t,i){"disposeViewLocal"===t.streamEventType||"disposeViewRemote"===t.streamEventType||"disposeViewUnparented"===t.streamEventType?function(e,t){switch(e){case Px.DISPOSE_STREAM_INVALID_PARAMS:return void Ux(Ax,{name:Px.DISPOSE_STREAM_INVALID_PARAMS,level:"warning",message:"Dispose View invalid combination of parameters.",data:{streamType:t.streamType}});case Px.START_DISPOSE_STREAM:return void Ux(Ax,{name:Px.START_DISPOSE_STREAM,level:"info",message:"Start disposing stream.",data:t});case Px.DISPOSE_INFO_NOT_FOUND:return void Ux(Ax,{name:Px.DISPOSE_INFO_NOT_FOUND,level:"error",message:"Cannot find render info when disposing stream.",data:t});case Px.STREAM_STOPPING:return void Ux(Ax,{name:Px.STREAM_STOPPING,level:"info",message:"Stream is currently marked as stopping, will continue if is local preview",data:t});case Px.DISPOSING_RENDERER:return void Ux(Ax,{name:Px.DISPOSING_RENDERER,level:"info",message:"Disposing view renderer.",data:t});case Px.RENDERER_NOT_FOUND:return void Ux(Ax,{name:Px.RENDERER_NOT_FOUND,level:"error",message:"Cannot find renderer when disposing stream.",data:t});case Px.STREAM_ALREADY_DISPOSED:Ux(Ax,{name:Px.STREAM_ALREADY_DISPOSED,level:"info",message:"Stream is already disposed.",data:t})}}(e,t):"createViewLocal"!==t.streamEventType&&"createViewRemote"!==t.streamEventType||function(e,t,i){switch(e){case Px.CREATE_STREAM_INVALID_PARAMS:return void Ux(Ax,{name:Px.CREATE_STREAM_INVALID_PARAMS,level:"warning",message:"Create View invalid combination of parameters.",data:{streamType:t.streamType}});case Px.START_STREAM_RENDERING:return void Ux(Ax,{name:Px.START_STREAM_RENDERING,level:"info",message:"Start creating view for local video.",data:t});case Px.STREAM_NOT_FOUND:return void Ux(Ax,{name:Px.STREAM_NOT_FOUND,level:"error",message:"Stream not found in state.",data:{callId:t.callId}});case Px.STREAM_ALREADY_RENDERED:return void Ux(Ax,{name:Px.STREAM_ALREADY_RENDERED,level:"warning",message:"Stream is already rendered.",data:t});case Px.STREAM_RENDERING:return void Ux(Ax,{name:Px.STREAM_RENDERING,level:"warning",message:"Stream is rendering.",data:t});case Px.STREAM_STOPPING:return void Ux(Ax,{name:Px.STREAM_STOPPING,level:"warning",message:'Stream was marked as stopping by dispose view. Resetting state to "Rendering".',data:t});case Px.CREATE_STREAM_FAIL:return void Ux(Ax,{name:Px.CREATE_STREAM_FAIL,level:"error",message:"Failed to create view.",data:{error:i,streamType:t.streamType,callId:t.callId}});case Px.RENDER_INFO_NOT_FOUND:return void Ux(Ax,{name:Px.RENDER_INFO_NOT_FOUND,level:"error",message:"Cannot find render info after create the view. ",data:t});case Px.CREATED_STREAM_STOPPING:return void Ux(Ax,{name:Px.CREATED_STREAM_STOPPING,level:"warning",message:"Render info status is stopping, dispose renderer.",data:t});case Px.VIEW_RENDER_SUCCEED:return void Ux(Ax,{name:Px.VIEW_RENDER_SUCCEED,level:"info",message:"Successfully render the view.",data:t});case Px.CREATING_VIEW:Ux(Ax,{name:Px.CREATING_VIEW,level:"info",message:"Start creating view for remote video.",data:t})}}(e,t,i)}var Vx=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};function Hx(e,t,i,n,r){const s=r.mediaStreamType;if(i)!function(e,t,i,n,r){let s;s=r?"disposeViewRemote":i?"disposeViewLocal":"disposeViewUnparented";const a=n.mediaStreamType,o=n.mediaStreamType,l=n.id,c="disposeViewRemote"===s&&r?"string"==typeof r?r:iL(r):void 0,d={callId:i,participantKey:c,streamId:null!=l?l:o,streamType:a};Bx(Px.START_DISPOSE_STREAM,d),"disposeViewRemote"===s&&c&&e.setRemoteVideoStreamRendererView(i,c,l,void 0);const u="disposeViewRemote"===s&&c?t.getRemoteRenderInfoForParticipant(i,c,l):t.getLocalRenderInfo(i,o);if(u)if("NotRendered"!==u.status){if("Stopping"!==u.status)return"Rendering"===u.status?(Bx(Px.STREAM_STOPPING,d),void("disposeViewRemote"===s&&c?t.setRemoteRenderInfo(i,c,l,u.stream,"Stopping",void 0):t.setLocalRenderInfo(i,o,u.stream,"Stopping",u.renderer))):void(u.renderer?(Bx(Px.DISPOSING_RENDERER,d),u.renderer.dispose(),"disposeViewRemote"===s&&c?t.setRemoteRenderInfo(i,c,l,u.stream,"NotRendered",void 0):"disposeViewLocal"===s&&(t.setLocalRenderInfo(i,o,u.stream,"NotRendered",void 0),e.setLocalVideoStreamRendererView(i,o,void 0))):Bx(Px.RENDERER_NOT_FOUND,d));Bx(Px.STREAM_STOPPING,d)}else Bx(Px.STREAM_ALREADY_DISPOSED,d);else Bx(Px.DISPOSE_INFO_NOT_FOUND,d)}(e,t,i,r,n);else{if("id"in r||i)return void Bx(Px.DISPOSE_STREAM_INVALID_PARAMS,{streamType:s});e.withErrorTeedToState((()=>function(e,t,i){const n={streamType:i.mediaStreamType,streamEventType:"disposeViewUnparented"};Bx(Px.START_DISPOSE_STREAM,n),e.deleteDeviceManagerUnparentedView(i);const r=t.getUnparentedRenderInfo(i);r?("Rendering"===r.status?(Bx(Px.STREAM_STOPPING,n),t.setUnparentedRenderInfo(i,r.stream,"Stopping",void 0)):t.deleteUnparentedRenderInfo(i),r.renderer?(Bx(Px.DISPOSING_RENDERER,n),r.renderer.dispose()):Bx(Px.RENDERER_NOT_FOUND,n)):Bx(Px.DISPOSE_INFO_NOT_FOUND,n)}(e,t,r)),"Call.stopVideo")()}}function $x(e,t,i){const n=t.getRemoteRenderInfoForCall(i);if(n)for(const[r,s]of n.entries())for(const[n,a]of s.entries())Hx(e,t,i,r,wL(a.stream));const r=t.getLocalRenderInfosForCall(i);if(r)for(const n of r.values())n&&n.renderer&&Hx(e,t,i,void 0,IL(n.stream));const s=t.getCallFeatureRenderInfosForCall(i);if(s)for(const n of s.values())for(const r of n.values())Hx(e,t,i,void 0,wL(r.stream))}class jx{constructor(e,t,i,n){this.subscribe=()=>{if(this._participant.on("stateChanged",this.stateChanged),this._participant.on("isMutedChanged",this.isMutedChanged),this._participant.on("displayNameChanged",this.displayNameChanged),this._participant.on("isSpeakingChanged",this.isSpeakingChanged),this._participant.on("videoStreamsUpdated",this.videoStreamsUpdated),this._participant.on("roleChanged",this.roleChanged),this._participant.videoStreams.length>0){for(const e of this._participant.videoStreams)this._internalContext.setRemoteRenderInfo(this._callIdRef.callId,this._participantKey,e.id,e,"NotRendered",void 0),this.addRemoteVideoStreamSubscriber(e);this._context.setRemoteVideoStreams(this._callIdRef.callId,this._participantKey,this._participant.videoStreams.map(wL),[])}},this.unsubscribe=()=>{if(this._participant.off("stateChanged",this.stateChanged),this._participant.off("isMutedChanged",this.isMutedChanged),this._participant.off("displayNameChanged",this.displayNameChanged),this._participant.off("isSpeakingChanged",this.isSpeakingChanged),this._participant.off("videoStreamsUpdated",this.videoStreamsUpdated),this._participant.off("roleChanged",this.roleChanged),this._participant.videoStreams.length>0)for(const e of this._participant.videoStreams)Hx(this._context,this._internalContext,this._callIdRef.callId,this._participantKey,wL(e)),this._internalContext.deleteRemoteRenderInfo(this._callIdRef.callId,this._participantKey,e.id)},this.addRemoteVideoStreamSubscriber=e=>{var t;null===(t=this._remoteVideoStreamSubscribers.get(e.id))||void 0===t||t.unsubscribe(),this._remoteVideoStreamSubscribers.set(e.id,new Fx(this._callIdRef,this._participantKey,e,this._context))},this.stateChanged=()=>{this._context.setParticipantState(this._callIdRef.callId,this._participantKey,this._participant.state)},this.isMutedChanged=()=>{this._context.setParticipantIsMuted(this._callIdRef.callId,this._participantKey,this._participant.isMuted)},this.roleChanged=()=>{this._context.setParticipantRole(this._callIdRef.callId,this._participantKey,this._participant.role)},this.displayNameChanged=()=>{this._context.setParticipantDisplayName(this._callIdRef.callId,this._participantKey,this._participant.displayName||"")},this.isSpeakingChanged=()=>{this._context.setParticipantIsSpeaking(this._callIdRef.callId,this._participantKey,this._participant.isSpeaking)},this.videoStreamsUpdated=e=>{var t;for(const i of e.removed)null===(t=this._remoteVideoStreamSubscribers.get(i.id))||void 0===t||t.unsubscribe(),Hx(this._context,this._internalContext,this._callIdRef.callId,this._participantKey,wL(i)),this._internalContext.deleteRemoteRenderInfo(this._callIdRef.callId,this._participantKey,i.id);for(const t of e.added)this._internalContext.setRemoteRenderInfo(this._callIdRef.callId,this._participantKey,t.id,t,"NotRendered",void 0),this.addRemoteVideoStreamSubscriber(t);this._context.setRemoteVideoStreams(this._callIdRef.callId,this._participantKey,e.added.map(wL),e.removed.map((e=>e.id)))},this._callIdRef=e,this._participant=t,this._context=i,this._internalContext=n,this._participantKey=iL(this._participant.identifier),this._remoteVideoStreamSubscribers=new Map,this.subscribe()}}class Gx{constructor(e,t,i){this.subscribe=()=>{this._recording.on("isRecordingActiveChanged",this.isAvailableChanged),this._recording.on("recordingsUpdated",this.isRecordingsUpdated)},this.unsubscribe=()=>{this._recording.off("isRecordingActiveChanged",this.isAvailableChanged),this._recording.off("recordingsUpdated",this.isRecordingsUpdated)},this.isAvailableChanged=()=>{this._context.setCallRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive)},this.isRecordingsUpdated=e=>{this._context.setCallRecordingInfos(this._callIdRef.callId,this._recording.recordings,e.removed)},this._callIdRef=e,this._context=t,this._recording=i,this._recording.isRecordingActive&&(this._context.setCallRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive),this._context.setCallRecordingInfos(this._callIdRef.callId,this._recording.recordings,[])),this.subscribe()}}class qx{constructor(e,t,i){this.subscribe=()=>{this._pptLive.on("isActiveChanged",this.isAvailableChanged)},this.unsubscribe=()=>{this._pptLive.off("isActiveChanged",this.isAvailableChanged)},this.isAvailableChanged=()=>{this._context.setCallPPTLiveActive(this._callIdRef.callId,this._pptLive.isActive),this.checkAndUpdatePPTLiveParticipant()},this.checkAndUpdatePPTLiveParticipant=()=>{return e=this,t=void 0,n=function*(){this._pptLive.activePresenterId&&(this._pptLive.isActive?(this._call.isScreenSharingOn&&(yield this._call.stopScreenSharing()),this._context.setCallParticipantPPTLive(this._callIdRef.callId,iL(this._pptLive.activePresenterId),this._pptLive.target)):this._context.setCallParticipantPPTLive(this._callIdRef.callId,iL(this._pptLive.activePresenterId),void 0))},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n},this._callIdRef=e,this._context=t,this._pptLive=i.feature(oD.PPTLive),this._call=i,this.subscribe()}}class zx{constructor(e,t,i){this.subscribe=()=>{this._transcription.on("isTranscriptionActiveChanged",this.isTranscriptionActiveChanged)},this.unsubscribe=()=>{this._transcription.off("isTranscriptionActiveChanged",this.isTranscriptionActiveChanged)},this.isTranscriptionActiveChanged=()=>{this._context.setCallTranscriptionActive(this._callIdRef.callId,this._transcription.isTranscriptionActive)},this._callIdRef=e,this._context=t,this._transcription=i,this._transcription.isTranscriptionActive&&this._context.setCallTranscriptionActive(this._callIdRef.callId,this._transcription.isTranscriptionActive),this.subscribe()}}class Wx{constructor(e,t,i){this.unsubscribe=()=>{this._diagnostics.network.off("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.off("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))},this._callIdRef=e,this._context=t,this._diagnostics=i,this.setInitialDiagnostics(),this.subscribe()}setInitialDiagnostics(){const e=this._diagnostics.network.getLatest(),t=this._diagnostics.media.getLatest();0===Object.entries(e).length&&0===Object.entries(t).length||this._context.modifyState((i=>{const n=i.calls[this._callIdRef.callId];void 0!==n&&(n.diagnostics={network:{latest:e},media:{latest:t}})}))}subscribe(){this._diagnostics.network.on("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.on("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))}networkDiagnosticsChanged(e){this._context.modifyState((t=>{var i;const n=t.calls[this._callIdRef.callId];if(void 0===n)return;const r=null===(i=n.diagnostics)||void 0===i?void 0:i.network.latest;r&&(r[e.diagnostic]=Kx(e))}))}mediaDiagnosticsChanged(e){this._context.modifyState((t=>{var i;const n=t.calls[this._callIdRef.callId];if(void 0===n)return;const r=null===(i=n.diagnostics)||void 0===i?void 0:i.media.latest;r&&(r[e.diagnostic]=Kx(e))}))}}const Kx=e=>({value:e.value,valueType:e.valueType});class Jx{constructor(e,t,i){this.subscribe=()=>{this._raiseHand.on("raisedHandEvent",this.raisedHand),this._raiseHand.on("loweredHandEvent",this.loweredHand)},this.unsubscribe=()=>{this._raiseHand.off("raisedHandEvent",this.raisedHand),this._raiseHand.off("loweredHandEvent",this.loweredHand)},this.raisedHand=()=>{this._context.setCallRaisedHands(this._callIdRef.callId,this._raiseHand.getRaisedHands());for(const e of this._raiseHand.getRaisedHands())this._context.setParticipantIsRaisedHand(this._callIdRef.callId,iL(e.identifier),e)},this.loweredHand=e=>{this.raisedHand(),this._context.setParticipantIsRaisedHand(this._callIdRef.callId,iL(e.identifier),void 0)},this._callIdRef=e,this._context=t,this._raiseHand=i,this.subscribe()}}class Yx{constructor(e){this.subscribe=()=>{this._localOptimalVideoCountFeature.on("optimalVideoCountChanged",this.optimalVideoCountChanged)},this.unsubscribe=()=>{this._localOptimalVideoCountFeature.off("optimalVideoCountChanged",this.optimalVideoCountChanged)},this.optimalVideoCountChanged=()=>{this.updateOptimalVideoCountState({maxRemoteVideoStreams:this._localOptimalVideoCountFeature.optimalVideoCount})},this.updateOptimalVideoCountState=e=>{this._context.setOptimalVideoCount(this._callIdRef.callId,e.maxRemoteVideoStreams)},this._callIdRef=e.callIdRef,this._context=e.context,this._localOptimalVideoCountFeature=e.localOptimalVideoCountFeature,this.subscribe()}}class Qx{constructor(e,t,i){this._capabilitiesInitialized=!1,this.subscribe=()=>{this._capabilitiesFeature.on("capabilitiesChanged",this.capabilitiesChanged)},this.unsubscribe=()=>{this._capabilitiesFeature.off("capabilitiesChanged",this.capabilitiesChanged)},this.capabilitiesChanged=e=>{this._context.setCapabilities(this._callIdRef.callId,this._capabilitiesFeature.capabilities,e),e.oldValue.viewAttendeeNames!==e.newValue.viewAttendeeNames&&this._context.setHideAttendeeNames(this._callIdRef.callId,e),this.setUnmuteMicAndTurnVideoOnNotification(e),this._capabilitiesInitialized=!0},this.setUnmuteMicAndTurnVideoOnNotification=e=>{var t,i,n,r,s,a,o,l,c,d;(null===(t=e.oldValue.turnVideoOn)||void 0===t?void 0:t.isPresent)!==(null===(i=e.newValue.turnVideoOn)||void 0===i?void 0:i.isPresent)&&(!1===(null===(n=e.oldValue.turnVideoOn)||void 0===n?void 0:n.isPresent)&&(null===(r=e.newValue.turnVideoOn)||void 0===r?void 0:r.isPresent)&&this._capabilitiesInitialized&&(this._context.getState().latestNotifications.capabilityTurnVideoOnAbsent&&this._context.deleteLatestNotification("capabilityTurnVideoOnAbsent",this._callIdRef.callId),this._context.getState().latestNotifications.capabilityTurnVideoOnPresent||this._context.setLatestNotification(this._callIdRef.callId,{target:"capabilityTurnVideoOnPresent",timestamp:new Date(Date.now())})),!1===(null===(s=e.newValue.turnVideoOn)||void 0===s?void 0:s.isPresent)&&(this._context.getState().latestNotifications.capabilityTurnVideoOnPresent&&this._context.deleteLatestNotification("capabilityTurnVideoOnPresent",this._callIdRef.callId),this._context.getState().latestNotifications.capabilityTurnVideoOnAbsent||this._context.setLatestNotification(this._callIdRef.callId,{target:"capabilityTurnVideoOnAbsent",timestamp:new Date(Date.now())}))),(null===(a=e.oldValue.unmuteMic)||void 0===a?void 0:a.isPresent)!==(null===(o=e.newValue.unmuteMic)||void 0===o?void 0:o.isPresent)&&(!1===(null===(l=e.oldValue.unmuteMic)||void 0===l?void 0:l.isPresent)&&(null===(c=e.newValue.unmuteMic)||void 0===c?void 0:c.isPresent)&&this._capabilitiesInitialized&&(this._context.getState().latestNotifications.capabilityUnmuteMicAbsent&&this._context.deleteLatestNotification("capabilityUnmuteMicAbsent",this._callIdRef.callId),this._context.getState().latestNotifications.capabilityUnmuteMicPresent||this._context.setLatestNotification(this._callIdRef.callId,{target:"capabilityUnmuteMicPresent",timestamp:new Date(Date.now())})),!1===(null===(d=e.newValue.unmuteMic)||void 0===d?void 0:d.isPresent)&&(this._context.getState().latestNotifications.capabilityUnmuteMicPresent&&this._context.deleteLatestNotification("capabilityUnmuteMicPresent",this._callIdRef.callId),this._context.getState().latestNotifications.capabilityUnmuteMicAbsent||this._context.setLatestNotification(this._callIdRef.callId,{target:"capabilityUnmuteMicAbsent",timestamp:new Date(Date.now())})))},this._callIdRef=e,this._context=t,this._capabilitiesFeature=i,this.subscribe()}}class Zx{constructor(e,t,i){this.subscribe=()=>{this._reaction.on("reaction",this.onReactionEvent)},this.unsubscribe=()=>{this._reaction.off("reaction",this.onReactionEvent)},this.onReactionEvent=e=>{this._context.setReceivedReactionFromParticipant(this._callIdRef.callId,e.identifier,e.reactionMessage)},this._callIdRef=e,this._context=t,this._reaction=i,this.subscribe()}}class Xx{constructor(e,t,i){this.subscribe=()=>{this._spotlightFeature.on("spotlightChanged",this.spotlightChanged)},this.unsubscribe=()=>{this._spotlightFeature.off("spotlightChanged",this.spotlightChanged)},this.spotlightChanged=e=>{this._context.setSpotlight(this._callIdRef.callId,this._spotlightFeature.getSpotlightedParticipants(),this._spotlightFeature.maxParticipantsToSpotlight);for(const t of e.added)this._context.setParticipantSpotlighted(this._callIdRef.callId,t);for(const t of e.removed)this._context.setParticipantNotSpotlighted(this._callIdRef.callId,t)},this._callIdRef=e,this._context=t,this._spotlightFeature=i,this.subscribe()}}class eF{constructor(e,t,i){this.subscribe=()=>{this._recording.on("isLocalRecordingActiveChanged",this.isAvailableChanged),this._recording.on("localRecordingsUpdated",this.isRecordingsUpdated)},this.unsubscribe=()=>{this._recording.off("isLocalRecordingActiveChanged",this.isAvailableChanged),this._recording.off("localRecordingsUpdated",this.isRecordingsUpdated)},this.isAvailableChanged=()=>{this._context.setCallLocalRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive)},this.isRecordingsUpdated=e=>{this._context.setCallLocalRecordingInfos(this._callIdRef.callId,this._recording.recordings,e.removed)},this._callIdRef=e,this._context=t,this._recording=i,this._recording.isRecordingActive&&(this._context.setCallLocalRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive),this._context.setCallLocalRecordingInfos(this._callIdRef.callId,this._recording.recordings,[])),this.subscribe()}}class tF{constructor(e,t,i){this.unsubscribe=()=>{this._breakoutRoomsFeature.off("breakoutRoomsUpdated",this.onBreakoutRoomsUpdated),this._context.deleteLatestNotification("breakoutRoomJoined",this._callIdRef.callId),this._context.deleteLatestNotification("breakoutRoomClosingSoon",this._callIdRef.callId),clearTimeout(this._breakoutRoomClosingSoonTimeoutId)},this.onBreakoutRoomsUpdated=e=>{"assignedBreakoutRooms"===e.type?this.onAssignedBreakoutRoomUpdated(e.data):"join"===e.type?this.onBreakoutRoomsJoined(e.data):"breakoutRoomsSettings"===e.type&&e.data&&this.onBreakoutRoomSettingsUpdated(e.data)},this.onAssignedBreakoutRoomUpdated=e=>{var t,i,n,r;const s=this._context.getState().calls[this._callIdRef.callId],a=null===(t=null==s?void 0:s.breakoutRooms)||void 0===t?void 0:t.assignedBreakoutRoom;if(void 0!==s){if(!e)return(null===(i=null==a?void 0:a.call)||void 0===i?void 0:i.id)&&(this._context.deleteLatestNotification("breakoutRoomJoined",a.call.id),this._context.deleteLatestNotification("breakoutRoomClosingSoon",a.call.id),clearTimeout(this._breakoutRoomClosingSoonTimeoutId)),void this._context.setAssignedBreakoutRoom(this._callIdRef.callId,e);if("open"===e.state&&(null===(n=s.breakoutRooms)||void 0===n?void 0:n.breakoutRoomDisplayName)&&s.breakoutRooms.breakoutRoomDisplayName!==e.displayName)this._context.setLatestNotification(this._callIdRef.callId,{target:"assignedBreakoutRoomChanged",timestamp:new Date(Date.now())});else if("open"!==e.state||(null===(r=null==s?void 0:s.breakoutRooms)||void 0===r?void 0:r.breakoutRoomSettings)||void 0!==this._context.getOpenBreakoutRoom()){if("closed"===e.state&&"open"===(null==a?void 0:a.state))this._context.deleteLatestNotification("assignedBreakoutRoomOpened",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomOpenedPromptJoin",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomChanged",this._callIdRef.callId),this._context.deleteLatestNotification("breakoutRoomJoined",this._callIdRef.callId);else if("closed"===e.state){this._context.deleteLatestNotification("assignedBreakoutRoomOpened",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomOpenedPromptJoin",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomChanged",this._callIdRef.callId),this._context.deleteLatestNotification("breakoutRoomJoined",this._callIdRef.callId),this._context.deleteLatestNotification("breakoutRoomClosingSoon",this._callIdRef.callId),clearTimeout(this._breakoutRoomClosingSoonTimeoutId);const e=this._context.getOpenBreakoutRoom();e&&this._context.getState().calls[e]&&this._context.setLatestNotification(this._callIdRef.callId,{target:"assignedBreakoutRoomClosed",timestamp:new Date(Date.now())}),this._context.deleteOpenBreakoutRoom()}}else{const t=!1===e.autoMoveParticipantToBreakoutRoom?"assignedBreakoutRoomOpenedPromptJoin":"assignedBreakoutRoomOpened";this._context.setLatestNotification(this._callIdRef.callId,{target:t,timestamp:new Date(Date.now())})}this._context.setAssignedBreakoutRoom(this._callIdRef.callId,e)}},this.onBreakoutRoomsJoined=e=>{var t,i,n;this._context.deleteLatestNotification("assignedBreakoutRoomOpened",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomOpenedPromptJoin",this._callIdRef.callId),this._context.deleteLatestNotification("assignedBreakoutRoomChanged",this._callIdRef.callId),this._context.setLatestNotification(e.id,{target:"breakoutRoomJoined",timestamp:new Date(Date.now())}),this._context.setOpenBreakoutRoom(e.id);const r=null===(n=null===(i=null===(t=this._context.getState().calls[this._callIdRef.callId])||void 0===t?void 0:t.breakoutRooms)||void 0===i?void 0:i.assignedBreakoutRoom)||void 0===n?void 0:n.displayName;r&&this._context.setBreakoutRoomDisplayName(e.id,r)},this.onBreakoutRoomSettingsUpdated=e=>{if("string"==typeof e.roomEndTime&&!Number.isNaN(Date.parse(e.roomEndTime))){const t=new Date(Date.now()),i=new Date(e.roomEndTime).getTime()-t.getTime(),n=Math.max(i-3e4,0);this._breakoutRoomClosingSoonTimeoutId||(this._breakoutRoomClosingSoonTimeoutId=setTimeout((()=>this._context.setLatestNotification(this._callIdRef.callId,{target:"breakoutRoomClosingSoon",timestamp:t})),n))}this._context.setBreakoutRoomSettings(this._callIdRef.callId,e)},this._callIdRef=e,this._context=t,this._breakoutRoomsFeature=i,this.subscribe()}subscribe(){this._breakoutRoomsFeature.on("breakoutRoomsUpdated",this.onBreakoutRoomsUpdated)}}class iF{constructor(e,t,i){this.subscribe=()=>{this._togetherModeStream.on("isAvailableChanged",this.isAvailableChanged),this._togetherModeStream.on("isReceivingChanged",this.isReceivingChanged),this._togetherModeStream.on("sizeChanged",this.isSizeChanged)},this.unsubscribe=()=>{this._togetherModeStream.off("isAvailableChanged",this.isAvailableChanged),this._togetherModeStream.off("isReceivingChanged",this.isReceivingChanged),this._togetherModeStream.off("sizeChanged",this.isSizeChanged)},this.isAvailableChanged=()=>{this._context.setTogetherModeVideoStreamIsAvailable(this._callIdRef.callId,this._togetherModeStream.id,this._togetherModeStream.isAvailable)},this.isReceivingChanged=()=>{this._context.setTogetherModeVideoStreamIsReceiving(this._callIdRef.callId,this._togetherModeStream.id,this._togetherModeStream.isReceiving)},this.isSizeChanged=()=>{this._context.setTogetherModeVideoStreamSize(this._callIdRef.callId,this._togetherModeStream.id,this._togetherModeStream.size)},this._callIdRef=e,this._togetherModeStream=t,this._context=i,this.subscribe()}}class nF{constructor(e,t,i,n){this._featureName="togetherMode",this.subscribe=()=>{this._togetherMode.on("togetherModeStreamsUpdated",this.onTogetherModeStreamUpdated),this._togetherMode.on("togetherModeSceneUpdated",this.onSceneUpdated),this._togetherMode.on("togetherModeSeatingUpdated",this.onSeatUpdated)},this.unsubscribe=()=>{this._togetherMode.off("togetherModeStreamsUpdated",this.onTogetherModeStreamUpdated),this._togetherMode.off("togetherModeSceneUpdated",this.onSceneUpdated),this._togetherMode.off("togetherModeSeatingUpdated",this.onSeatUpdated)},this.onSceneUpdated=e=>{this._context.setTogetherModeSeatingCoordinates(this._callIdRef.callId,e)},this.onSeatUpdated=e=>{this._context.setTogetherModeSeatingCoordinates(this._callIdRef.callId,e)},this.addRemoteVideoStreamSubscriber=e=>{this._togetherModeVideoStreamSubscribers.has(e.id)||this._togetherModeVideoStreamSubscribers.set(e.id,new iF(this._callIdRef,e,this._context))},this.updateTogetherModeStreams=(e,t)=>{t.forEach((e=>{var t;null===(t=this._togetherModeVideoStreamSubscribers.get(e.id))||void 0===t||t.unsubscribe(),this._togetherModeVideoStreamSubscribers.delete(e.id),this._internalContext.deleteCallFeatureRenderInfo(this._callIdRef.callId,this._featureName,e.mediaStreamType)})),e.filter((e=>e.isAvailable)).forEach((e=>{this._internalContext.setCallFeatureRenderInfo(this._callIdRef.callId,this._featureName,e.mediaStreamType,e,"NotRendered",void 0),this.addRemoteVideoStreamSubscriber(e)})),this._context.setTogetherModeVideoStreams(this._callIdRef.callId,e.filter((e=>e.isAvailable)).map((e=>AL(e,this._featureName))),t.map((e=>AL(e,this._featureName))));const i=this._togetherMode.togetherModeStream.length?"togetherModeStarted":"togetherModeEnded";this._context.setLatestNotification(this._callIdRef.callId,{target:i,timestamp:new Date})},this.onTogetherModeStreamUpdated=e=>{this.updateTogetherModeStreams(e.added,e.removed)},this._callIdRef=e,this._context=t,this._internalContext=i,this._togetherMode=n,this._togetherModeVideoStreamSubscribers=new Map,this.subscribe()}}class rF{constructor(e,t,i){this.subscribe=()=>{this._mediaAccessCallFeature.on("mediaAccessChanged",this.mediaAccessChanged),this._mediaAccessCallFeature.on("meetingMediaAccessChanged",this.meetingMediaAccessChanged)},this.unsubscribe=()=>{this._mediaAccessCallFeature.off("mediaAccessChanged",this.mediaAccessChanged),this._mediaAccessCallFeature.off("meetingMediaAccessChanged",this.meetingMediaAccessChanged)},this.mediaAccessChanged=e=>this._context.setMediaAccesses(this._callIdRef.callId,e.mediaAccesses),this.meetingMediaAccessChanged=e=>this._context.setMeetingMediaAccess(this._callIdRef.callId,e.meetingMediaAccess),this._callIdRef=e,this._context=t,this._mediaAccessCallFeature=i;const n=this._mediaAccessCallFeature.getAllOthersMediaAccess(),r=this._mediaAccessCallFeature.getMeetingMediaAccess();this._context.setMediaAccesses(this._callIdRef.callId,n),this._context.setMeetingMediaAccess(this._callIdRef.callId,r),this.subscribe()}}class sF{constructor(e,t,i){this.subscribe=()=>{this._realTimeTextFeature.on("realTimeTextReceived",this.realTimeTextReceived)},this.unsubscribe=()=>{this._realTimeTextFeature.off("realTimeTextReceived",this.realTimeTextReceived)},this.realTimeTextReceived=e=>{this._context.setIsRealTimeTextActive(this._callIdRef.callId,!0),this._context.addRealTimeText(this._callIdRef.callId,e)},this._callIdRef=e,this._context=t,this._realTimeTextFeature=i,this.subscribe()}}class aF{constructor(e,t,i){this._safeSubscribeInitCaptionSubscriber=()=>{this._safeSubscribe(this.initCaptionSubscriber)},this._safeSubscribeInitTeamsMeetingConference=()=>{this._safeSubscribe(this.initTeamsMeetingConference)},this._safeSubscribeInitLocalRecordingNotificationSubscriber=()=>{this._safeSubscribe(this.initLocalRecordingNotificationSubscriber)},this.subscribe=()=>{this._call.on("stateChanged",this.stateChanged),this._call.on("stateChanged",this._safeSubscribeInitCaptionSubscriber),this._call.on("stateChanged",this._safeSubscribeInitTeamsMeetingConference),this._call.on("stateChanged",this._safeSubscribeInitLocalRecordingNotificationSubscriber),this._call.on("idChanged",this.idChanged),this._call.on("isScreenSharingOnChanged",this.isScreenSharingOnChanged),this._call.on("remoteParticipantsUpdated",this.remoteParticipantsUpdated),this._call.on("localVideoStreamsUpdated",this.localVideoStreamsUpdated),this._call.on("isMutedChanged",this.isMuteChanged),this._call.on("roleChanged",this.callRoleChangedHandler),this._call.feature(oD.DominantSpeakers).on("dominantSpeakersChanged",this.dominantSpeakersChanged),this._call.on("totalParticipantCountChanged",this.totalParticipantCountChangedHandler),this._call.on("mutedByOthers",this.mutedByOthersHandler);for(const e of this._call.localVideoStreams)this._internalContext.setLocalRenderInfo(this._callIdRef.callId,e.mediaStreamType,e,"NotRendered",void 0);this._call.remoteParticipants.length>0&&(this._call.remoteParticipants.forEach((e=>{this.addParticipantListener(e)})),this._context.setCallRemoteParticipants(this._callIdRef.callId,this._call.remoteParticipants.map(PL),[]))},this.unsubscribe=()=>{var e,t,i,n,r;this._call.off("stateChanged",this.stateChanged),this._call.off("stateChanged",this._safeSubscribeInitCaptionSubscriber),this._call.off("stateChanged",this._safeSubscribeInitTeamsMeetingConference),this._call.off("stateChanged",this._safeSubscribeInitLocalRecordingNotificationSubscriber),this._call.off("idChanged",this.idChanged),this._call.off("isScreenSharingOnChanged",this.isScreenSharingOnChanged),this._call.off("remoteParticipantsUpdated",this.remoteParticipantsUpdated),this._call.off("localVideoStreamsUpdated",this.localVideoStreamsUpdated),this._call.off("isMutedChanged",this.isMuteChanged),this._call.off("roleChanged",this.callRoleChangedHandler),this._call.off("totalParticipantCountChanged",this.totalParticipantCountChangedHandler),this._call.off("mutedByOthers",this.mutedByOthersHandler),this._participantSubscribers.forEach((e=>{e.unsubscribe()})),this._participantSubscribers.clear();for(const e of this._call.localVideoStreams){const t=e.mediaStreamType;Hx(this._context,this._internalContext,this._callIdRef.callId,void 0,IL(e)),this._internalContext.deleteLocalRenderInfo(this._callIdRef.callId,t)}this._diagnosticsSubscriber.unsubscribe(),this._recordingSubscriber.unsubscribe(),this._transcriptionSubscriber.unsubscribe(),null===(e=this._localRecordingSubscriber)||void 0===e||e.unsubscribe(),this._optimalVideoCountSubscriber.unsubscribe(),this._pptLiveSubscriber.unsubscribe(),null===(t=this._CaptionsFeatureSubscriber)||void 0===t||t.unsubscribe(),null===(i=this._realTimeTextSubscriber)||void 0===i||i.unsubscribe(),null===(n=this._raiseHandSubscriber)||void 0===n||n.unsubscribe(),this._capabilitiesSubscriber.unsubscribe(),null===(r=this._reactionSubscriber)||void 0===r||r.unsubscribe(),this._spotlightSubscriber.unsubscribe(),this._breakoutRoomsSubscriber.unsubscribe(),this._togetherModeSubscriber.unsubscribe(),this._mediaAccessSubscriber.unsubscribe()},this.stateChanged=()=>{this._context.setCallState(this._callIdRef.callId,this._call.state)},this.initCaptionSubscriber=()=>{"Connected"!==this._call.state||this._CaptionsFeatureSubscriber||(this._CaptionsFeatureSubscriber=new Lx(this._callIdRef,this._context,this._call.feature(oD.Captions)),this._call.off("stateChanged",this._safeSubscribeInitCaptionSubscriber))},this.initTeamsMeetingConference=()=>{"Connected"===this._call.state&&(e=>"info"in e&&!!e.info.threadId)(this._call)&&(this._call.feature(oD.TeamsMeetingAudioConferencing).getTeamsMeetingAudioConferencingDetails().then((e=>{this._context.setTeamsMeetingConference(this._callIdRef.callId,e)})),this._call.off("stateChanged",this._safeSubscribeInitTeamsMeetingConference))},this.initLocalRecordingNotificationSubscriber=()=>{"Connected"!==this._call.state||"TeamsCall"!==this._call.kind||this._localRecordingSubscriber||(this._localRecordingSubscriber=new eF(this._callIdRef,this._context,this._call.feature(oD.LocalRecording)),this._call.off("stateChanged",this._safeSubscribeInitLocalRecordingNotificationSubscriber))},this.idChanged=()=>{this._internalContext.setCallId(this._call.id,this._callIdRef.callId),this._context.setCallId(this._call.id,this._callIdRef.callId),this._callIdRef.callId=this._call.id},this.isScreenSharingOnChanged=()=>{this._context.setCallIsScreenSharingOn(this._callIdRef.callId,this._call.isScreenSharingOn)},this.isMuteChanged=()=>{this._context.setCallIsMicrophoneMuted(this._callIdRef.callId,this._call.isMuted)},this.callRoleChangedHandler=()=>{this._context.setRole(this._callIdRef.callId,this._call.role)},this.totalParticipantCountChangedHandler=()=>{this._context.setTotalParticipantCount(this._callIdRef.callId,this._call.totalParticipantCount)},this.mutedByOthersHandler=()=>{this._context.teeErrorToState({name:"mutedByOthers",message:"Muted by another participant"},"Call.mutedByOthers")},this.remoteParticipantsUpdated=e=>{e.added.forEach((e=>{this.addParticipantListener(e)})),e.removed.forEach((e=>{this.removeParticipantListener(e)})),this._context.setCallRemoteParticipantsEnded(this._callIdRef.callId,e.removed.map(PL),e.added.map((e=>iL(e.identifier)))),this._context.setCallRemoteParticipants(this._callIdRef.callId,e.added.map(PL),e.removed.map((e=>iL(e.identifier))))},this.localVideoStreamsUpdated=e=>{var t,i;for(const i of e.added){const e=i.mediaStreamType;this._internalContext.setLocalRenderInfo(this._callIdRef.callId,e,i,"NotRendered",void 0),null===(t=this._localVideoStreamVideoEffectsSubscribers.get(e))||void 0===t||t.unsubscribe(),this._localVideoStreamVideoEffectsSubscribers.set(e,new xx({parent:this._callIdRef,context:this._context,localVideoStream:i,localVideoStreamEffectsAPI:i.feature(oD.VideoEffects)}))}for(const t of e.removed){const e=t.mediaStreamType;null===(i=this._localVideoStreamVideoEffectsSubscribers.get(e))||void 0===i||i.unsubscribe(),Hx(this._context,this._internalContext,this._callIdRef.callId,void 0,IL(t)),this._internalContext.deleteLocalRenderInfo(this._callIdRef.callId,e)}this._context.setCallLocalVideoStream(this._callIdRef.callId,e.added.map(IL),e.removed.map(IL))},this.dominantSpeakersChanged=()=>{const e=this._call.feature(oD.DominantSpeakers).dominantSpeakers;this._context.setCallDominantSpeakers(this._callIdRef.callId,e)},this._call=e,this._callIdRef={callId:e.id},this._context=t,this._internalContext=i,this._diagnosticsSubscriber=new Wx(this._callIdRef,this._context,this._call.feature(oD.UserFacingDiagnostics)),this._participantSubscribers=new Map,this._recordingSubscriber=new Gx(this._callIdRef,this._context,this._call.feature(oD.Recording)),this._pptLiveSubscriber=new qx(this._callIdRef,this._context,this._call),this._transcriptionSubscriber=new zx(this._callIdRef,this._context,this._call.feature(oD.Transcription)),this._raiseHandSubscriber=new Jx(this._callIdRef,this._context,this._call.feature(oD.RaiseHand)),this._reactionSubscriber=new Zx(this._callIdRef,this._context,this._call.feature(oD.Reaction)),this._optimalVideoCountSubscriber=new Yx({callIdRef:this._callIdRef,context:this._context,localOptimalVideoCountFeature:this._call.feature(oD.OptimalVideoCount)}),this._localVideoStreamVideoEffectsSubscribers=new Map,this._capabilitiesSubscriber=new Qx(this._callIdRef,this._context,this._call.feature(oD.Capabilities)),this._spotlightSubscriber=new Xx(this._callIdRef,this._context,this._call.feature(oD.Spotlight)),this._context.deleteLatestNotification("assignedBreakoutRoomClosed"),this._breakoutRoomsSubscriber=new tF(this._callIdRef,this._context,this._call.feature(oD.BreakoutRooms)),this._togetherModeSubscriber=new nF(this._callIdRef,this._context,this._internalContext,this._call.feature(oD.TogetherMode)),this._mediaAccessSubscriber=new rF(this._callIdRef,this._context,this._call.feature(oD.MediaAccess)),this._realTimeTextSubscriber=new sF(this._callIdRef,this._context,this._call.feature(oD.RealTimeText)),this.subscribe()}_safeSubscribe(e){try{e()}catch(e){this._context.teeErrorToState(e,"Call.on")}}addParticipantListener(e){var t;const i=iL(e.identifier);null===(t=this._participantSubscribers.get(i))||void 0===t||t.unsubscribe(),this._participantSubscribers.set(i,new jx(this._callIdRef,e,this._context,this._internalContext))}removeParticipantListener(e){const t=iL(e.identifier),i=this._participantSubscribers.get(t);i&&(i.unsubscribe(),this._participantSubscribers.delete(t))}}class oF{constructor(e,t){this.subscribe=()=>{this._incomingCall.on("callEnded",this.callEnded)},this.unsubscribe=()=>{this._incomingCall.off("callEnded",this.callEnded)},this.callEnded=e=>{this._setIncomingCallEnded(this._incomingCall.id,e.callEndReason)},this._incomingCall=e,this._setIncomingCallEnded=t,this.subscribe()}}var lF=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class cF{constructor(e){this._context=e}get(e,t){switch(t){case"accept":return this._context.withAsyncErrorTeedToState((function(...t){return lF(this,void 0,void 0,(function*(){return yield e.accept(...t)}))}),"IncomingCall.accept");case"reject":return this._context.withAsyncErrorTeedToState((function(...t){return lF(this,void 0,void 0,(function*(){return yield e.reject(...t)}))}),"IncomingCall.reject");default:return Reflect.get(e,t)}}}var dF=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class uF{constructor(e){this._context=e}get(e,t){switch(t){case"accept":return this._context.withAsyncErrorTeedToState((function(...t){return dF(this,void 0,void 0,(function*(){return yield e.accept(...t)}))}),"IncomingCall.accept");case"reject":return this._context.withAsyncErrorTeedToState((function(...t){return dF(this,void 0,void 0,(function*(){return yield e.reject(...t)}))}),"IncomingCall.reject");default:return Reflect.get(e,t)}}}class hF{constructor(e,t){this.unregisterSubscriber=()=>{for(const[e,t]of this._callSubscribers.entries())t.unsubscribe();this._callSubscribers.clear();for(const[e,t]of this._incomingCallSubscribers.entries())t.unsubscribe();this._incomingCallSubscribers.clear(),this._incomingCalls.clear();for(const[e,t]of this._declarativeCalls.entries())t.unsubscribe();this._declarativeCalls.clear()},this.callsUpdated=e=>{const t=[];for(const i of e.added){const e=this.addCall(i);t.push(e)}const i=[];for(const t of e.removed){$x(this._context,this._internalContext,t.id);const e=this._callSubscribers.get(t);e&&(e.unsubscribe(),this._callSubscribers.delete(t)),this._context.setCallEnded(t.id,t.callEndReason);const n=this._declarativeCalls.get(t);n?(n.unsubscribe(),i.push(n),this._declarativeCalls.delete(t)):i.push(this.callDeclaratify(t,this._context))}for(const e of this._externalCallsUpdatedListeners)e({added:t,removed:i})},this.setIncomingCallEnded=(e,t)=>{const i=this._incomingCallSubscribers.get(e);i&&(i.unsubscribe(),this._incomingCallSubscribers.delete(e)),this._incomingCalls.delete(e),this._context.setIncomingCallEnded(e,t)},this.incomingCall=({incomingCall:e})=>{this._incomingCallSubscribers.has(e.id)||this._incomingCallSubscribers.set(e.id,new oF(e,this.setIncomingCallEnded)),_L(e)?this._incomingCalls.set(e.id,((e,t)=>{const i=new uF(t);return new Proxy(e,i)})(e,this._context)):this._incomingCalls.set(e.id,((e,t)=>{const i=new cF(t);return new Proxy(e,i)})(e,this._context)),this._context.setIncomingCall(function(e){if(_L(e)){const t=Object.assign(Object.assign({},e.info),{kind:e.kind});return{id:e.id,info:t,callerInfo:e.callerInfo,startTime:new Date,endTime:void 0}}{const t=Object.assign(Object.assign({},e.info),{kind:e.kind});return{id:e.id,info:t,callerInfo:e.callerInfo,startTime:new Date,endTime:void 0}}}(e))},this.addCall=e=>{var t;return null===(t=this._callSubscribers.get(e))||void 0===t||t.unsubscribe(),this._context.setCall(function(e){const t={};e.remoteParticipants.forEach((e=>{t[iL(e.identifier)]=PL(e)}));let i,n=!1;if(e.feature(oD.Capabilities).capabilities&&e.feature(oD.Capabilities).capabilities.viewAttendeeNames){const t=e.feature(oD.Capabilities).capabilities.viewAttendeeNames;t.isPresent||"MeetingRestricted"!==t.reason||(n=!0)}return"info"in e&&(i=e.info),{id:e.id,kind:CL(e)?"Call":"TeamsCall",callerInfo:e.callerInfo,state:e.state,callEndReason:e.callEndReason,diagnostics:{network:{latest:{}},media:{latest:{}}},direction:e.direction,isMuted:e.isMuted,isScreenSharingOn:e.isScreenSharingOn,localVideoStreams:e.localVideoStreams.map(IL),remoteParticipants:t,remoteParticipantsEnded:{},recording:{isRecordingActive:!1},localRecording:{isLocalRecordingActive:!1},pptLive:{isActive:!1},raiseHand:{raisedHands:[]},togetherMode:{isActive:!1,streams:{},seatingPositions:{}},localParticipantReaction:void 0,transcription:{isTranscriptionActive:!1},screenShareRemoteParticipant:void 0,startTime:new Date,endTime:void 0,role:e.role,captionsFeature:{captions:[],supportedSpokenLanguages:[],supportedCaptionLanguages:[],currentCaptionLanguage:"",currentSpokenLanguage:"",isCaptionsFeatureActive:!1,startCaptionsInProgress:!1,captionsKind:EL(e)?"TeamsCaptions":"Captions"},realTimeTextFeature:{realTimeTexts:{},isRealTimeTextFeatureActive:!1},transfer:{acceptedTransfers:{}},optimalVideoCount:{maxRemoteVideoStreams:e.feature(oD.OptimalVideoCount).optimalVideoCount},hideAttendeeNames:n,info:i,meetingConference:{conferencePhones:[]}}}(e)),this._callSubscribers.set(e,new aF(e,this._context,this._internalContext)),this.getOrCreateDeclarativeCall(e)},this.getOrCreateDeclarativeCall=e=>{const t=this._declarativeCalls.get(e);if(t)return t;const i=this.callDeclaratify(e,this._context);return this._declarativeCalls.set(e,i),i},this._context=e,this._internalContext=t,this._callSubscribers=new Map,this._incomingCallSubscribers=new Map,this._incomingCalls=new Map,this._declarativeCalls=new Map,this._externalCallsUpdatedListeners=new Set}getCommon(e,t){switch(t){case"startCall":return this._context.withErrorTeedToState(((...t)=>{const i=this.startCall(e,t);return this.addCall(i),this.getOrCreateDeclarativeCall(i)}),"CallAgent.startCall");case"join":return this._context.withErrorTeedToState(((...t)=>{const i=this.joinCall(e,t);return this.addCall(i),this.getOrCreateDeclarativeCall(i)}),"CallAgent.join");case"calls":return Array.from(this._declarativeCalls.values());case"on":return(...t)=>{if("callsUpdated"===t[0]){const e=t[1];this._externalCallsUpdatedListeners.add(e)}else this.agentSubscribe(e,t)};case"off":return(...t)=>{if("callsUpdated"===t[0]){const e=t[1];this._externalCallsUpdatedListeners.delete(e)}else this.agentUnsubscribe(e,t)};case"dispose":return()=>{e.dispose(),this.unsubscribe()};case"incomingCalls":return Array.from(this._incomingCalls.values());default:return Reflect.get(e,t)}}}const gF=(e,t)=>{!function(e,t){const i=t.getCallIds();for(const n of i)$x(e,t,n)}(e,t),e.clearCallRelatedState(),t.clearCallRelatedState()};var pF=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class mF{constructor(e){this._context=e}unsubscribe(){}getContext(){return this._context}get(e,t){switch(t){case"mute":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.mute(...t)}))}),"Call.mute");case"unmute":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.unmute(...t)}))}),"Call.unmute");case"startVideo":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.startVideo(...t)}))}),"Call.startVideo");case"stopVideo":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.stopVideo(...t)}))}),"Call.stopVideo");case"startScreenSharing":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.startScreenSharing(...t)}))}),"Call.startScreenSharing");case"stopScreenSharing":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.stopScreenSharing(...t)}))}),"Call.stopScreenSharing");case"hold":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.hold(...t)}))}),"Call.hold");case"resume":return this._context.withAsyncErrorTeedToState((function(...t){return pF(this,void 0,void 0,(function*(){return yield e.resume(...t)}))}),"Call.resume");case"feature":return this._context.withErrorTeedToState(((...t)=>{if(t[0]===oD.Captions){const t=e.feature(oD.Captions);let i;return"Captions"===t.captions.kind?(i=new vF(this._context,e),{captions:new Proxy(t.captions,i),on:(...e)=>{if("CaptionsKindChanged"===e[0]){const i=e[1],n=()=>{i()};return t.on("CaptionsKindChanged",n)}},off:(...e)=>{if("CaptionsKindChanged"===e[0])return t.off("CaptionsKindChanged",e[1])}}):(i=new fF(this._context,e),{captions:new Proxy(t.captions,i)})}if(t[0]===oD.Transfer){const t=e.feature(oD.Transfer),i=new yF(this._context,e);return new Proxy(t,i)}if(t[0]===oD.Spotlight){const t=e.feature(oD.Spotlight),i=new SF(this._context);return new Proxy(t,i)}return e.feature(...t)}),"Call.feature");default:return Reflect.get(e,t)}}}class fF{constructor(e,t){this._context=e,this._call=t}get(e,t){switch(t){case"startCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){var i,n;this._context.setStartCaptionsInProgress(this._call.id,!0);try{const r=yield e.startCaptions(...t);return this._context.setSelectedSpokenLanguage(this._call.id,null!==(n=null===(i=t[0])||void 0===i?void 0:i.spokenLanguage)&&void 0!==n?n:"en-us"),r}catch(e){throw this._context.setStartCaptionsInProgress(this._call.id,!1),e}}))),"Call.feature");case"stopCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){const i=yield e.stopCaptions(...t);return this._context.setIsCaptionActive(this._call.id,!1),this._context.setStartCaptionsInProgress(this._call.id,!1),this._context.clearCaptions(this._call.id),i}))),"Call.feature");case"setSpokenLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){const i=yield e.setSpokenLanguage(...t);return this._context.setSelectedSpokenLanguage(this._call.id,t[0]),i}))),"Call.feature");case"setCaptionLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){const i=yield e.setCaptionLanguage(...t);return this._context.setSelectedCaptionLanguage(this._call.id,t[0]),i}))),"Call.feature");default:return Reflect.get(e,t)}}}class vF{constructor(e,t){this._context=e,this._call=t}get(e,t){switch(t){case"startCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){var i,n;this._context.setStartCaptionsInProgress(this._call.id,!0);try{const r=yield e.startCaptions(...t);return this._context.setSelectedSpokenLanguage(this._call.id,null!==(n=null===(i=t[0])||void 0===i?void 0:i.spokenLanguage)&&void 0!==n?n:"en-us"),r}catch(e){throw this._context.setStartCaptionsInProgress(this._call.id,!1),e}}))),"Call.feature");case"stopCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){const i=yield e.stopCaptions(...t);return this._context.setIsCaptionActive(this._call.id,!1),this._context.setStartCaptionsInProgress(this._call.id,!1),this._context.clearCaptions(this._call.id),i}))),"Call.feature");case"setSpokenLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){const i=yield e.setSpokenLanguage(...t);return this._context.setSelectedSpokenLanguage(this._call.id,t[0]),i}))),"Call.feature");default:return Reflect.get(e,t)}}}class SF{constructor(e){this._context=e}get(e,t){switch(t){case"startSpotlight":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){return yield e.startSpotlight(...t)}))),"Call.feature");case"stopSpotlight":return this._context.withAsyncErrorTeedToState(((...t)=>pF(this,void 0,void 0,(function*(){return yield e.stopSpotlight(...t)}))),"Call.feature");default:return Reflect.get(e,t)}}}class yF{constructor(e,t){this._context=e,this._call=t}get(e,t){return"on"===t?(...t)=>{if("transferAccepted"===t[0]){const i=t[1],n=e=>{this._context.setAcceptedTransfer(this._call.id,{callId:e.targetCall.id,timestamp:new Date}),i(e)};return e.on("transferAccepted",n)}}:Reflect.get(e,t)}}class CF extends mF{get(e,t){return"addParticipant"===t?this.getContext().withAsyncErrorTeedToState((function(...t){return i=this,n=void 0,s=function*(){return yield e.addParticipant(...t)},new((r=void 0)||(r=Promise))((function(e,t){function a(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(a,o)}l((s=s.apply(i,n||[])).next())}));var i,n,r,s}),"Call.addParticipant"):super.get(e,t)}}class TF extends hF{constructor(e,t,i){super(t,i),this.subscribe=()=>{this._callAgent.on("callsUpdated",this.callsUpdated),this._callAgent.on("incomingCall",this.incomingCall);for(const e of this._callAgent.calls)this.addCall(e)},this.unsubscribe=()=>{this._callAgent.off("callsUpdated",this.callsUpdated),this._callAgent.off("incomingCall",this.incomingCall),this.unregisterSubscriber()},this._callAgent=e,this.subscribe()}callDeclaratify(e,t){if(CL(e))return((e,t)=>{const i=new CF(t);return Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>i.unsubscribe()}),new Proxy(e,i)})(e,t);throw new Error("Not reachable code, DeclarativeCallAgent.callDeclaratify must be called with an ACS call.")}startCall(e,t){if(TL(e))return e.startCall(...t);throw Error("Unreachable code, DeclarativeCallAgent.startCall must be called with an ACS callAgent.")}joinCall(e,t){if(TL(e))return e.join(...t);throw Error("Unreachable code, DeclarativeCallAgent.joinCall must be called with an ACS callAgent.")}agentSubscribe(e,t){if(TL(e))return e.on(...t);throw Error("Unreachable code, DeclarativeCallAgent.agentSubscribe must be called with an ACS callAgent.")}agentUnsubscribe(e,t){if(TL(e))return e.off(...t);throw Error("Unreachable code, DeclarativeCallAgent.agentUnsubscribe must be called with an ACS callAgent.")}get(e,t){return super.getCommon(e,t)}}class EF{constructor(){this._remoteRenderInfos=new Map,this._localRenderInfos=new Map,this._callFeatureRenderInfos=new Map,this._unparentedRenderInfos=new Map,this._callIdHistory=new Rx,this._unparentedViewVideoEffectsSubscriber=new Map}setCallId(e,t){this._callIdHistory.updateCallIdHistory(e,t);const i=this._remoteRenderInfos.get(t);i&&(this._remoteRenderInfos.delete(t),this._remoteRenderInfos.set(e,i));const n=this._localRenderInfos.get(t);n&&(this._localRenderInfos.delete(t),this._localRenderInfos.set(e,n));const r=this._callFeatureRenderInfos.get(t);r&&(this._callFeatureRenderInfos.delete(t),this._callFeatureRenderInfos.set(e,r))}getCallIds(){return this._remoteRenderInfos.keys()}getRemoteRenderInfoForCall(e){return this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e))}getRemoteRenderInfoForParticipant(e,t,i){const n=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));if(!n)return;const r=n.get(t);return r?r.get(i):void 0}setRemoteRenderInfo(e,t,i,n,r,s){let a=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));a||(a=new Map,this._remoteRenderInfos.set(this._callIdHistory.latestCallId(e),a));let o=a.get(t);o||(o=new Map,a.set(t,o)),o.set(i,{stream:n,status:r,renderer:s})}deleteRemoteRenderInfo(e,t,i){const n=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));if(!n)return;const r=n.get(t);r&&r.delete(i)}setLocalRenderInfo(e,t,i,n,r){let s=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));s||(s=new Map,this._localRenderInfos.set(this._callIdHistory.latestCallId(e),s)),s.set(t,{stream:i,status:n,renderer:r})}getLocalRenderInfosForCall(e){return this._localRenderInfos.get(this._callIdHistory.latestCallId(e))}getLocalRenderInfo(e,t){const i=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));if(i)return i.get(t)}deleteLocalRenderInfo(e,t){const i=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));i&&i.delete(t)}getUnparentedRenderInfo(e){return this._unparentedRenderInfos.get(e.mediaStreamType)}getUnparentedRenderInfos(){return[...this._unparentedRenderInfos].map((([,e])=>e.stream))}setUnparentedRenderInfo(e,t,i,n){this._unparentedRenderInfos.set(e.mediaStreamType,{stream:t,status:i,renderer:n})}deleteUnparentedRenderInfo(e){var t;null===(t=this._unparentedViewVideoEffectsSubscriber.get(e.mediaStreamType))||void 0===t||t.unsubscribe(),this._unparentedRenderInfos.delete(e.mediaStreamType)}subscribeToUnparentedViewVideoEffects(e,t){var i;null===(i=this._unparentedViewVideoEffectsSubscriber.get(e.mediaStreamType))||void 0===i||i.unsubscribe(),this._unparentedViewVideoEffectsSubscriber.set(e.mediaStreamType,new xx({parent:"unparented",context:t,localVideoStream:e,localVideoStreamEffectsAPI:e.feature(oD.VideoEffects)}))}clearCallRelatedState(){this._remoteRenderInfos.clear(),this._localRenderInfos.clear(),this._callFeatureRenderInfos.clear()}getCallFeatureRenderInfosForCall(e){return this._callFeatureRenderInfos.get(this._callIdHistory.latestCallId(e))}getCallFeatureRenderInfo(e,t,i){var n,r;const s=null===(r=null===(n=this._callFeatureRenderInfos.get(this._callIdHistory.latestCallId(e)))||void 0===n?void 0:n.get(t))||void 0===r?void 0:r.get(i);if(s)return s}setCallFeatureRenderInfo(e,t,i,n,r,s){let a=this._callFeatureRenderInfos.get(this._callIdHistory.latestCallId(e));a||(a=new Map,this._callFeatureRenderInfos.set(this._callIdHistory.latestCallId(e),a));let o=a.get(t);o||(o=new Map,a.set(t,o)),o.set(i,{stream:n,status:r,renderer:s})}deleteCallFeatureRenderInfo(e,t,i){var n;const r=this._callFeatureRenderInfos.get(this._callIdHistory.latestCallId(e));r&&r.get(t)&&(null===(n=r.get(t))||void 0===n||n.delete(i))}}var bF=r(1408),_F=r.n(bF);const IF=e=>{const t=(e=>{switch(e){case"Call":return 1;case"Chat":return 2;case"CallWithChat":return 3;case"StatefulComponents":return 4;default:return 0}})(e);return(e=>{const t=e.search(/alpha/);return t>=0?e.substring(0,t+5):e})(`acr1${t}0/${_F()}`)};class wF extends mF{get(e,t){return"addParticipant"===t?this.getContext().withAsyncErrorTeedToState((function(...t){return i=this,n=void 0,s=function*(){return yield e.addParticipant(...t)},new((r=void 0)||(r=Promise))((function(e,t){function a(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(a,o)}l((s=s.apply(i,n||[])).next())}));var i,n,r,s}),"TeamsCall.addParticipant"):super.get(e,t)}}class AF extends hF{constructor(e,t,i){super(t,i),this.subscribe=()=>{this._callAgent.on("callsUpdated",this.callsUpdated),this._callAgent.on("incomingCall",this.incomingCall);for(const e of this._callAgent.calls)this.addCall(e)},this.unsubscribe=()=>{this._callAgent.off("callsUpdated",this.callsUpdated),this._callAgent.off("incomingCall",this.incomingCall),this.unregisterSubscriber()},this._callAgent=e,this.subscribe()}callDeclaratify(e,t){if(EL(e))return((e,t)=>{const i=new wF(t);return i.unsubscribe(),Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>i.unsubscribe()}),new Proxy(e,i)})(e,t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.callDeclaratify must be called with an TeamsCall.")}startCall(e,t){if(bL(e))return e.startCall(...t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.startCall must be called with an TeamsCallAgent.")}joinCall(e,t){if(bL(e))return e.join(...t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.joinCall must be called with an TeamsCallAgent.")}agentSubscribe(e,t){if(!bL(e))throw new Error("Not reachable code, DeclarativeTeamsCallAgent.agentSubscribe must be called with an TeamsCallAgent.");e.on(...t)}agentUnsubscribe(e,t){if(!bL(e))throw new Error("Not reachable code, DeclarativeTeamsCallAgent.agentUnsubscribe must be called with an TeamsCallAgent.");e.off(...t)}get(e,t){return super.getCommon(e,t)}}class PF{constructor(e,t,i,n){this._context=e,this._callId=t,this._participantId=i,this._streamId=n}get(e,t){return"updateScalingMode"===t?(...t)=>{return i=this,n=void 0,s=function*(){yield e.updateScalingMode(...t),this._context.setRemoteVideoStreamViewScalingMode(this._callId,this._participantId,this._streamId,t[0])},new((r=void 0)||(r=Promise))((function(e,t){function a(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(a,o)}l((s=s.apply(i,n||[])).next())}));var i,n,r,s}:Reflect.get(e,t)}}function RF(e,t,i,n,r){const s=n.mediaStreamType;return i&&kF(n)?function(e,t,i,n,r){return s=this,a=void 0,l=function*(){const s=null==n?void 0:n.mediaStreamType,a=n&&n.id,o={callId:i,undefined:void 0,streamId:a,streamType:s,streamEventType:"createViewCallFeature"};Bx(Px.CREATING_VIEW,o);const l=DF(n),c=t.getCallFeatureRenderInfo(i,l,n.mediaStreamType);if(!c)return void Bx(Px.STREAM_NOT_FOUND,o);if("Rendered"===c.status)return void Bx(Px.STREAM_ALREADY_RENDERED,o);if("Rendering"===c.status)return void Bx(Px.STREAM_RENDERING,o);if("Stopping"===c.status)return Bx(Px.STREAM_STOPPING,o),void t.setCallFeatureRenderInfo(i,l,n.mediaStreamType,c.stream,"Rendering",c.renderer);const d=new Gk(c.stream);let u;t.setCallFeatureRenderInfo(i,l,n.mediaStreamType,c.stream,"Rendering",void 0);try{u=yield d.createView(r)}catch(e){throw Bx(Px.CREATE_STREAM_FAIL,o,e),t.setCallFeatureRenderInfo(i,l,n.mediaStreamType,c.stream,"NotRendered",void 0),e}const h=t.getCallFeatureRenderInfo(i,l,n.mediaStreamType);return h?"Stopping"===h.status?(Bx(Px.CREATED_STREAM_STOPPING,o),d.dispose(),t.setCallFeatureRenderInfo(i,l,n.mediaStreamType,h.stream,"NotRendered",void 0),void MF(i,l,e,n.mediaStreamType,void 0)):(t.setCallFeatureRenderInfo(i,l,n.mediaStreamType,h.stream,"Rendered",d),MF(i,l,e,n.mediaStreamType,RL(u)),Bx(Px.VIEW_RENDER_SUCCEED,o),{renderer:d,view:u}):(Bx(Px.RENDER_INFO_NOT_FOUND,o),d.dispose(),void MF(i,l,e,n.mediaStreamType,void 0))},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{r(l.next(e))}catch(e){t(e)}}function n(e){try{r(l.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(i,n)}r((l=l.apply(s,a||[])).next())}));var s,a,o,l}(e,t,i,n,r):(Bx(Px.CREATE_STREAM_INVALID_PARAMS,{streamType:s}),Promise.resolve(void 0))}const MF=(e,t,i,n,r)=>{"togetherMode"===t&&i.setTogetherModeVideoStreamRendererView(e,n,r)},DF=e=>{if(e.feature)return e.feature;throw new Error("Feature name not found")};function kF(e){return"feature"in e||!1}var OF=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class NF{constructor(e,t){this._context=e,this._internalContext=t}get(e,t){switch(t){case"createCallAgent":return this._context.withAsyncErrorTeedToState(((...t)=>OF(this,void 0,void 0,(function*(){const i=yield e.createCallAgent(...t);return this._callAgent=((e,t,i)=>(gF(t,i),new Proxy(e,new TF(e,t,i))))(i,this._context,this._internalContext),this._context.setCallAgent({displayName:this._callAgent.displayName}),this._callAgent}))),"CallClient.createCallAgent");case"createTeamsCallAgent":return this._context.withAsyncErrorTeedToState(((...t)=>OF(this,void 0,void 0,(function*(){const i=yield e.createTeamsCallAgent(...t);return this._callAgent=((e,t,i)=>(gF(t,i),new Proxy(e,new AF(e,t,i))))(i,this._context,this._internalContext),this._context.setCallAgent({displayName:void 0}),this._callAgent}))),"CallClient.createTeamsCallAgent");case"getDeviceManager":return this._context.withAsyncErrorTeedToState((()=>OF(this,void 0,void 0,(function*(){const t=yield e.getDeviceManager();if(this._sdkDeviceManager){if(this._sdkDeviceManager===t)return this._deviceManager;throw new Error("Multiple DeviceManager not supported. This means a incompatible version of communication-calling is used OR calling declarative was not properly updated to communication-calling version.")}return this._sdkDeviceManager=t,this._deviceManager=((e,t,i)=>{const n=new SL(e,t);return Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>n.unsubscribe()}),Object.defineProperty(e,"selectCamera",{configurable:!1,value:e=>n.selectCamera(e)}),Object.defineProperty(e,"getUnparentedVideoStreams",{configurable:!1,value:()=>i.getUnparentedRenderInfos()}),new Proxy(e,n)})(t,this._context,this._internalContext),this._deviceManager}))),"CallClient.getDeviceManager");case"feature":return this._context.withErrorTeedToState(((...i)=>{if(i[0]===oD.DebugInfo){const t=e.feature(oD.DebugInfo);return Object.assign(Object.assign({},t),{getEnvironmentInfo:()=>OF(this,void 0,void 0,(function*(){const e=yield t.getEnvironmentInfo();return this._context.setEnvironmentInfo(e),e}))})}return Reflect.get(e,t)}),"CallClient.feature");default:return Reflect.get(e,t)}}}const LF=(e,t,i)=>{Object.defineProperty(e,"getState",{configurable:!1,value:()=>t.getState()}),Object.defineProperty(e,"onStateChange",{configurable:!1,value:e=>t.onStateChange(e)}),Object.defineProperty(e,"offStateChange",{configurable:!1,value:e=>t.offStateChange(e)}),Object.defineProperty(e,"createView",{configurable:!1,value:(e,n,r,s)=>OF(void 0,void 0,void 0,(function*(){if("feature"in r)return yield RF(t,i,e,r,s);const a=n?XN(n):void 0,o=yield function(e,t,i,n,r,s){const a=r.mediaStreamType;return i?function(e,t,i,n,r,s){return Vx(this,void 0,void 0,(function*(){let a;if(r)a="createViewRemote";else{if(!i)throw new Error("unparented createView not implemented yet here");a="createViewLocal"}const o=null==n?void 0:n.mediaStreamType,l=n.mediaStreamType,c=n.id,d="createViewRemote"===a&&r?"string"==typeof r?r:iL(r):void 0,u={callId:i,participantKey:d,streamId:null!=c?c:l,streamType:o,streamEventType:a};Bx(Px.CREATING_VIEW,u);const h="createViewRemote"===a&&d?t.getRemoteRenderInfoForParticipant(i,d,c):t.getLocalRenderInfo(i,l);if(!h)return void Bx(Px.STREAM_NOT_FOUND,u);if("Rendered"===h.status)return void Bx(Px.STREAM_ALREADY_RENDERED,u);if("Rendering"===h.status)return void Bx(Px.STREAM_RENDERING,u);if("Stopping"===h.status)return void("createViewRemote"===a&&d?(Bx(Px.STREAM_STOPPING,u),t.setRemoteRenderInfo(i,d,c,h.stream,"Rendering",h.renderer)):"createViewLocal"===a&&(Bx(Px.STREAM_STOPPING,u),t.setLocalRenderInfo(i,l,h.stream,"Rendering",h.renderer)));const g=new Gk(h.stream);let p;"createViewRemote"===a&&d?t.setRemoteRenderInfo(i,d,c,h.stream,"Rendering",void 0):t.setLocalRenderInfo(i,l,h.stream,"Rendering",g);try{p=yield g.createView(s)}catch(e){throw"createViewRemote"===a&&d?(Bx(Px.CREATE_STREAM_FAIL,u),t.setRemoteRenderInfo(i,d,c,h.stream,"NotRendered",void 0)):"createViewLocal"===a&&(Bx(Px.CREATE_STREAM_FAIL,u,e),t.setLocalRenderInfo(i,l,h.stream,"NotRendered",void 0)),e}const m="createViewRemote"===a&&d?t.getRemoteRenderInfoForParticipant(i,d,c):t.getLocalRenderInfo(i,l);return m?"Stopping"===m.status?(Bx(Px.CREATED_STREAM_STOPPING,u),g.dispose(),void("createViewRemote"===a&&d?(t.setRemoteRenderInfo(i,d,c,m.stream,"NotRendered",void 0),e.setRemoteVideoStreamRendererView(i,d,c,void 0)):"createViewLocal"===a&&(t.setLocalRenderInfo(i,l,m.stream,"NotRendered",void 0),e.setLocalVideoStreamRendererView(i,l,void 0)))):("createViewRemote"===a&&d?(t.setRemoteRenderInfo(i,d,c,m.stream,"Rendered",g),e.setRemoteVideoStreamRendererView(i,d,c,RL(p)),Bx(Px.VIEW_RENDER_SUCCEED,u)):"createViewLocal"===a&&(t.setLocalRenderInfo(i,l,m.stream,"Rendered",g),e.setLocalVideoStreamRendererView(i,l,RL(p)),Bx(Px.VIEW_RENDER_SUCCEED,u)),{renderer:g,view:p}):(Bx(Px.RENDER_INFO_NOT_FOUND,u),g.dispose(),void("createViewRemote"===a&&d?e.setRemoteVideoStreamRendererView(i,d,c,void 0):e.setLocalVideoStreamRendererView(i,l,void 0)))}))}(e,t,i,r,n,s):"id"in r||i?(Bx(Px.CREATE_STREAM_INVALID_PARAMS,{streamType:a}),Promise.resolve(void 0)):e.withAsyncErrorTeedToState((()=>Vx(this,void 0,void 0,(function*(){return yield function(e,t,i,n){return Vx(this,void 0,void 0,(function*(){const r=t.getUnparentedRenderInfo(i);if(r&&"Rendered"===r.status)return void console.warn("Unparented LocalVideoStream is already rendered");if(r&&"Rendering"===r.status)return;if(r&&"Stopping"===r.status)return void console.warn("Unparented LocalVideoStream is in the middle of stopping");const s=new UI(i.source),a=new Gk(s);let o;t.setUnparentedRenderInfo(i,s,"Rendering",void 0);try{o=yield a.createView(n)}catch(e){throw t.deleteUnparentedRenderInfo(i),e}const l=t.getUnparentedRenderInfo(i);return l?"Stopping"===l.status?(t.deleteUnparentedRenderInfo(i),void e.deleteDeviceManagerUnparentedView(i)):(t.setUnparentedRenderInfo(i,s,"Rendered",a),t.subscribeToUnparentedViewVideoEffects(s,e),e.setDeviceManagerUnparentedView(i,RL(o)),{renderer:a,view:o}):(a.dispose(),void e.deleteDeviceManagerUnparentedView(i))}))}(e,t,r,s)}))),"Call.startVideo")()}(t,i,e,a,r,s);if("id"in r&&e&&n&&o){const i=iL(n);o.view=((e,t,i,n,r)=>{const s=new PF(t,i,n,r);return new Proxy(e,s)})(o.view,t,e,i,r.id)}return o}))}),Object.defineProperty(e,"disposeView",{configurable:!1,value:(e,n,r)=>{"feature"in r&&function(e,t,i,n){const r=n.mediaStreamType;i&&kF(n)?function(e,t,i,n){const r=n.mediaStreamType,s={callId:i,undefined:void 0,streamId:n&&n.id,streamType:r};Bx(Px.START_DISPOSE_STREAM,s);const a=DF(n);MF(i,a,e,r,void 0);const o=t.getCallFeatureRenderInfo(i,a,n.mediaStreamType);if(o)if("NotRendered"!==o.status){if("Stopping"!==o.status)return"Rendering"===o.status?(Bx(Px.STREAM_STOPPING,s),void t.setCallFeatureRenderInfo(i,a,r,o.stream,"Stopping",o.renderer)):void(o.renderer?(Bx(Px.DISPOSING_RENDERER,s),o.renderer.dispose(),t.setCallFeatureRenderInfo(i,a,r,o.stream,"NotRendered",void 0),MF(i,a,e,r,void 0)):Bx(Px.RENDERER_NOT_FOUND,s));Bx(Px.STREAM_STOPPING,s)}else Bx(Px.STREAM_ALREADY_DISPOSED,s);else Bx(Px.DISPOSE_INFO_NOT_FOUND,s)}(e,t,i,n):Bx(Px.DISPOSE_STREAM_INVALID_PARAMS,{streamType:r})}(t,i,e,r);const s=n?XN(n):void 0;Hx(t,i,e,s,r)}});const n=new Proxy(e,new NF(t,i));return n.feature(oD.DebugInfo).getEnvironmentInfo(),n},xF=(e,t)=>{var i,n;const r=null!==(n=null===(i=null==t?void 0:t.diagnostics)||void 0===i?void 0:i.tags)&&void 0!==n?n:[];return r.push(IF(e)),Object.assign(Object.assign({},t),{diagnostics:Object.assign(Object.assign({},null==t?void 0:t.diagnostics),{tags:r})})},FF=["accessDeniedTeamsMeeting","joinCallFailedDueToNoNetwork","leftCall","removedFromCall","unsupportedEnvironment"];var UF=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const BF=56e4,VF=[5e3,5300,BF],HF=e=>e.call?!!e.call.localVideoStreams.find((e=>"Video"===e.mediaStreamType)):!!e.devices.selectedCamera&&cL(e.devices),$F=e=>{if(!1===e)return!1;const t=!0===e?{}:e||{};return t.displayType="compact",!0!==t.screenShareButton&&(t.screenShareButton=!1),t};var jF;!function(e){e[e.LEFT_CALL=0]="LEFT_CALL",e[e.ACCESS_DENIED=1]="ACCESS_DENIED",e[e.REMOVED_FROM_CALL=2]="REMOVED_FROM_CALL",e[e.BAD_REQUEST=3]="BAD_REQUEST"}(jF||(jF={}));const GF=(e,t)=>{var i,n,r,s,a,o,l;let c=e.strings.call.leftCallTitle,d=e.strings.call.leftCallMoreDetails,u=!1,h="NoticePageLeftCall";switch(null===(i=null==t?void 0:t.callEndReason)||void 0===i?void 0:i.subCode){case 5732:e.strings.call.roomNotFoundTitle&&(c=e.strings.call.roomNotFoundTitle,d=e.strings.call.roomNotFoundDetails,u=!0,h="NoticePageRoomNotFound");break;case 5829:e.strings.call.roomNotValidTitle&&(c=e.strings.call.roomNotValidTitle,d=e.strings.call.roomNotValidDetails,u=!0,h="NoticePageRoomNotValid");break;case 5828:e.strings.call.notInvitedToRoomTitle&&(c=e.strings.call.notInvitedToRoomTitle,d=e.strings.call.notInvitedToRoomDetails,u=!0,h="NoticePageNotInvitedToRoom");break;case 5317:e.strings.call.inviteToRoomRemovedTitle&&(c=e.strings.call.inviteToRoomRemovedTitle,d=e.strings.call.inviteToRoomRemovedDetails,u=!0,h="NoticePageInviteToRoomRemoved");break;case 10004:487===(null===(n=null==t?void 0:t.callEndReason)||void 0===n?void 0:n.code)&&e.strings.call.callTimeoutTitle&&(c=e.strings.call.callTimeoutTitle,d=e.strings.call.callTimeoutDetails,u=!0,h="NoticePageCallTimeout");break;case 10321:486===(null===(r=null==t?void 0:t.callEndReason)||void 0===r?void 0:r.code)&&e.strings.call.callTimeoutBotTitle&&(c=e.strings.call.callTimeoutBotTitle,d=e.strings.call.callTimeoutBotDetails,u=!0,h="NoticePageCallTimeout")}switch(603===(null===(s=null==t?void 0:t.callEndReason)||void 0===s?void 0:s.code)&&e.strings.call.callRejectedTitle&&(c=e.strings.call.callRejectedTitle,d=e.strings.call.callRejectedMoreDetails,u=!0,h="NoticePageCallRejected"),null===(a=null==t?void 0:t.callEndReason)||void 0===a?void 0:a.subCode){case 10037:e.strings.call.participantCouldNotBeReachedTitle&&(c=e.strings.call.participantCouldNotBeReachedTitle,d=e.strings.call.participantCouldNotBeReachedMoreDetails,u=!0);break;case 10124:e.strings.call.permissionToReachTargetParticipantNotAllowedTitle&&(c=e.strings.call.permissionToReachTargetParticipantNotAllowedTitle,d=e.strings.call.permissionToReachTargetParticipantNotAllowedMoreDetails,u=!0);break;case 10119:e.strings.call.unableToResolveTenantTitle&&(c=e.strings.call.unableToResolveTenantTitle,d=e.strings.call.unableToResolveTenantMoreDetails,u=!0);break;case 10044:e.strings.call.participantIdIsMalformedTitle&&(c=e.strings.call.participantIdIsMalformedTitle,d=e.strings.call.participantIdIsMalformedMoreDetails,u=!0)}return 5751===(null===(o=null==t?void 0:t.callEndReason)||void 0===o?void 0:o.subCode)&&e.strings.call.callRejectedTitle&&(c=e.strings.call.callRejectedTitle,d=e.strings.call.invalidMeetingIdentifier,u=!0),400===(null===(l=null==t?void 0:t.callEndReason)||void 0===l?void 0:l.code)&&e.strings.call.callRejectedTitle&&(c=e.strings.call.callRejectedTitle,u=!0),{title:c,moreDetails:d,disableStartCallButton:u,iconName:h}},qF=e=>FF.includes(e),zF=(e,t)=>{var i;if(!1===e)return!1;let n=null!==(i=e instanceof Object?Object.assign({},e):e)&&void 0!==i?i:{};return!0===n||void 0===n?n=t.reduce(((e,t)=>(e[t]={disabled:!0},e)),{}):t.forEach((e=>{!1!==n[e]&&(n[e]={disabled:!0})})),n},WF=e=>void 0!==e&&"boolean"!=typeof e&&e.disabled,KF=(e,t)=>!(!1!==(null==e?void 0:e.isSupportedBrowser)&&(!1!==(null==e?void 0:e.isSupportedBrowserVersion)||t)&&!1!==(null==e?void 0:e.isSupportedPlatform)),JF=e=>"safari"===(null==e?void 0:e.environment.browser.toLowerCase()),YF=e=>e.devices.selectedCamera||e.devices.cameras[0],QF=e=>!!Array.isArray(e);function ZF(e,t){return t?"on":"on"===e?"stopped":e}class XF{constructor(e,t){this.isMutedChangedHandler=()=>{this.emitter.emit("isMutedChanged",{participantId:this.participant.identifier,isMuted:this.participant.isMuted})},this.displayNameChangedHandler=()=>{this.emitter.emit("displayNameChanged",{participantId:this.participant.identifier,displayName:this.participant.displayName})},this.isSpeakingChangedHandler=()=>{this.emitter.emit("isSpeakingChanged",{participantId:this.participant.identifier,isSpeaking:this.participant.isSpeaking})},this.videoStreamsUpdatedHandler=e=>{this.emitter.emit("videoStreamsUpdated",e)},this.participant=e,this.emitter=t,this.subscribeParticipantEvents()}subscribeParticipantEvents(){this.participant.on("isMutedChanged",this.isMutedChangedHandler),this.participant.on("displayNameChanged",this.displayNameChangedHandler),this.participant.on("isSpeakingChanged",this.isSpeakingChangedHandler),this.participant.on("videoStreamsUpdated",this.videoStreamsUpdatedHandler)}unsubscribeAll(){this.participant.off("isMutedChanged",this.isMutedChangedHandler),this.participant.off("displayNameChanged",this.displayNameChangedHandler),this.participant.off("isSpeakingChanged",this.isSpeakingChangedHandler),this.participant.off("videoStreamsUpdated",this.videoStreamsUpdatedHandler)}}class eU{constructor(e,t){this.unsubscribe=()=>{this._diagnostics.network.off("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.off("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))},this._diagnostics=t.feature(oD.UserFacingDiagnostics),this._emitter=e,this.subscribe()}subscribe(){this._diagnostics.network.on("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.on("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))}networkDiagnosticsChanged(e){const t=Object.assign({type:"network"},e);this._emitter.emit("diagnosticChanged",t)}mediaDiagnosticsChanged(e){const t=Object.assign({type:"media"},e);this._emitter.emit("diagnosticChanged",t)}}var tU=Number.isNaN||function(e){return"number"==typeof e&&e!=e};function iU(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!((n=e[i])===(r=t[i])||tU(n)&&tU(r)))return!1;var n,r;return!0}const nU=function(e,t){var i;void 0===t&&(t=iU);var n,r=[],s=!1;return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];return s&&i===this&&t(a,r)||(n=e.apply(this,a),s=!0,i=this,r=a),n}};var rU=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const sU=(e,t)=>!!e&&!!t&&e.source.id===t.source.id,aU=nU(((e,t,i,n)=>{const r=()=>rU(void 0,void 0,void 0,(function*(){yield dL(e);const n=null==i?void 0:i.id;let r=e.getState().deviceManager.selectedCamera;if(!r){const e=yield null==t?void 0:t.getCameras();r=e&&e.length>0?e[0]:void 0,r&&(null==t||t.selectCamera(r))}if(!n||!r)return;const s=new UI(r);i&&!i.localVideoStreams.find((e=>sU(e,s)))&&(yield i.startVideo(s))})),s=()=>rU(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.startScreenSharing()})),a=()=>rU(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.stopScreenSharing()})),o=()=>rU(void 0,void 0,void 0,(function*(){const t=i&&e.getState().calls[i.id],n=null==t?void 0:t.localVideoStreams.find((e=>"Video"===e.mediaStreamType));i&&t&&n&&e.disposeView(i.id,void 0,n),yield dL(e)})),l=()=>{throw new Error("Not implemented, cannot call a method from an abstract object")},c=null==i?void 0:i.feature(oD.Capabilities).capabilities.spotlightParticipant.isPresent,d=null==i?void 0:i.feature(oD.Capabilities).capabilities.removeParticipantsSpotlight.isPresent;return{onHangUp:e=>rU(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.hangUp({forEveryone:!0===e})})),onToggleHold:()=>rU(void 0,void 0,void 0,(function*(){return"LocalHold"===(null==i?void 0:i.state)?yield null==i?void 0:i.resume():yield null==i?void 0:i.hold()})),onSelectCamera:(n,r)=>rU(void 0,void 0,void 0,(function*(){if(t)if(i&&oL(i.state)){t.selectCamera(n);const e=i.localVideoStreams.find((e=>"Video"===e.mediaStreamType));yield null==e?void 0:e.switchSource(n),yield Promise.all([null==e?void 0:e.getMediaStream(),new Promise((e=>setTimeout(e,1e3)))])}else{if(!cL(e.getState().deviceManager))return void t.selectCamera(n);yield o(),t.selectCamera(n),yield e.createView(void 0,void 0,{source:n,mediaStreamType:"Video"},r)}})),onSelectMicrophone:e=>rU(void 0,void 0,void 0,(function*(){if(t)return t.selectMicrophone(e)})),onSelectSpeaker:e=>rU(void 0,void 0,void 0,(function*(){if(t)return t.selectSpeaker(e)})),onStartScreenShare:s,onStopScreenShare:a,onToggleCamera:t=>rU(void 0,void 0,void 0,(function*(){const n=cL(e.getState().deviceManager);if(i&&(oL(i.state)||lL(i.state))){const t=i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)),n=e.getState().deviceManager.unparentedViews;t||n.length>0?(n&&(yield n.forEach((t=>"Video"===t.mediaStreamType&&e.disposeView(void 0,void 0,t)))),t&&(yield(e=>rU(void 0,void 0,void 0,(function*(){(null==i?void 0:i.id)&&i&&i.localVideoStreams.find((t=>sU(t,e)))&&(yield i.stopVideo(e))})))(t))):yield r()}else{const i=e.getState().deviceManager.selectedCamera;i&&(n?yield o():yield e.createView(void 0,void 0,{source:i,mediaStreamType:"Video"},t))}})),onToggleMicrophone:()=>rU(void 0,void 0,void 0,(function*(){if(!i||!oL(i.state)&&!lL(i.state))throw new Error("Please invoke onToggleMicrophone after call is started");return i.isMuted?yield i.unmute():yield i.mute()})),onToggleScreenShare:()=>rU(void 0,void 0,void 0,(function*(){return(null==i?void 0:i.isScreenSharingOn)?yield a():yield s()})),onCreateLocalStreamView:(...t)=>rU(void 0,[...t],void 0,(function*(t={scalingMode:"Crop",isMirrored:!0}){if(!i||0===i.localVideoStreams.length)return;const n=e.getState().calls[i.id];if(!n)return;const r=n.localVideoStreams.find((e=>"Video"===e.mediaStreamType)),s=n.localVideoStreams.find((e=>"ScreenSharing"===e.mediaStreamType));let a;return r&&!r.view&&(a=yield e.createView(i.id,void 0,r,t)),s&&!s.view&&i.isScreenSharingOn&&(a=yield e.createView(i.id,void 0,s,{scalingMode:"Fit"})),(null==a?void 0:a.view)?{view:null==a?void 0:a.view}:void 0})),onCreateRemoteStreamView:(t,...n)=>rU(void 0,[t,...n],void 0,(function*(t,n={scalingMode:"Crop"}){if(!i)return;const r=fL(e.getState(),i.id);if(!r)return;const s=Object.values(r.remoteParticipants).find((e=>iL(e.identifier)===t));if(!s||!s.videoStreams)return;const a=Object.values(s.videoStreams).findLast((e=>"Video"===e.mediaStreamType&&e.isAvailable))||Object.values(s.videoStreams).findLast((e=>"Video"===e.mediaStreamType)),o=Object.values(s.videoStreams).findLast((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable))||Object.values(s.videoStreams).findLast((e=>"ScreenSharing"===e.mediaStreamType));let l;return a&&a.isAvailable&&!a.view&&(l=yield e.createView(i.id,s.identifier,a,n)),o&&o.isAvailable&&!o.view&&(l=yield e.createView(i.id,s.identifier,o,{scalingMode:"Fit"})),(null==l?void 0:l.view)?{view:null==l?void 0:l.view}:void 0})),onStartLocalVideo:r,onDisposeRemoteStreamView:t=>rU(void 0,void 0,void 0,(function*(){if(!i)return;const n=fL(e.getState(),i.id);if(!n)return;const r=Object.values(n.remoteParticipants).find((e=>iL(e.identifier)===t));if(!r||!r.videoStreams)return;const s=Object.values(r.videoStreams).find((e=>"Video"===e.mediaStreamType)),a=Object.values(r.videoStreams).find((e=>"ScreenSharing"===e.mediaStreamType));s&&s.view&&e.disposeView(i.id,r.identifier,s),a&&a.view&&e.disposeView(i.id,r.identifier,a)})),onDisposeLocalStreamView:o,onDisposeRemoteScreenShareStreamView:t=>rU(void 0,void 0,void 0,(function*(){if(!i)return;const n=fL(e.getState(),i.id);if(!n)return;const r=Object.values(n.remoteParticipants).find((e=>iL(e.identifier)===t));if(!r||!r.videoStreams)return;const s=Object.values(r.videoStreams).filter((e=>"ScreenSharing"===e.mediaStreamType));for(const t of s)t.view&&e.disposeView(i.id,r.identifier,t)})),onDisposeLocalScreenShareStreamView:()=>rU(void 0,void 0,void 0,(function*(){if(!i)return;const t=fL(e.getState(),i.id);if(!t)return;const n=null==t?void 0:t.localVideoStreams.find((e=>"ScreenSharing"===e.mediaStreamType));n&&n.view&&e.disposeView(i.id,void 0,n)})),onDisposeRemoteVideoStreamView:t=>rU(void 0,void 0,void 0,(function*(){if(!i)return;const n=fL(e.getState(),i.id);if(!n)return;const r=Object.values(n.remoteParticipants).find((e=>iL(e.identifier)===t));if(!r||!r.videoStreams)return;const s=Object.values(r.videoStreams).filter((e=>"Video"===e.mediaStreamType));for(const t of s)t.view&&e.disposeView(i.id,r.identifier,t)})),onRaiseHand:()=>rU(void 0,void 0,void 0,(function*(){var e;return yield null===(e=null==i?void 0:i.feature(oD.RaiseHand))||void 0===e?void 0:e.raiseHand()})),onLowerHand:()=>rU(void 0,void 0,void 0,(function*(){var e;return yield null===(e=null==i?void 0:i.feature(oD.RaiseHand))||void 0===e?void 0:e.lowerHand()})),onToggleRaiseHand:()=>rU(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(oD.RaiseHand),n=e.getState().userId;(null==t?void 0:t.getRaisedHands().find((e=>iL(e.identifier)===iL(n))))?yield null==t?void 0:t.lowerHand():yield null==t?void 0:t.raiseHand()})),onReactionClick:e=>rU(void 0,void 0,void 0,(function*(){var t;"like"===e||"applause"===e||"heart"===e||"laugh"===e||"surprised"===e?yield null===(t=null==i?void 0:i.feature(oD.Reaction))||void 0===t?void 0:t.sendReaction({reactionType:e}):console.warn(`Can not recognize ${e} as meeting reaction`)})),onAddParticipant:l,onRemoveParticipant:l,onStartCall:l,onSendDtmfTone:e=>rU(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.sendDtmf(e)})),askDevicePermission:e=>rU(void 0,void 0,void 0,(function*(){t&&(yield null==t?void 0:t.askDevicePermission(e))})),onRemoveVideoBackgroundEffects:()=>rU(void 0,void 0,void 0,(function*(){const e=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(e){if(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)return e.feature(oD.VideoEffects).stopEffects();throw new Error("Video background effects dependency not resolved")}})),onBlurVideoBackground:e=>rU(void 0,void 0,void 0,(function*(){var r;const s=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(s){if(!(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency))throw new Error("Video background effects dependency not resolved");const t=(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)&&(null===(r=yield n.onResolveVideoBackgroundEffectsDependency())||void 0===r?void 0:r.createBackgroundBlurEffect);return t&&s.feature(oD.VideoEffects).startEffects(t(e))}})),onReplaceVideoBackground:e=>rU(void 0,void 0,void 0,(function*(){var r;const s=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(s){if(!(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency))throw new Error("Video background effects dependency not resolved");const t=(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)&&(null===(r=yield n.onResolveVideoBackgroundEffectsDependency())||void 0===r?void 0:r.createBackgroundReplacementEffect);return t&&s.feature(oD.VideoEffects).startEffects(t(e))}})),onStartNoiseSuppressionEffect:()=>rU(void 0,void 0,void 0,(function*(){var e;const t=(null==n?void 0:n.onResolveDeepNoiseSuppressionDependency)&&(null===(e=yield n.onResolveDeepNoiseSuppressionDependency())||void 0===e?void 0:e.deepNoiseSuppressionEffect),r=null==i?void 0:i.localAudioStreams.find((e=>"Audio"===e.mediaStreamType));if(r&&t&&t.noiseSuppression){const e=r.feature(oD.AudioEffects);if(yield e.isSupported(t.noiseSuppression))return yield e.startEffects(t);console.warn("Deep Noise Suppression is not supported on this platform.")}})),onStopNoiseSuppressionEffect:()=>rU(void 0,void 0,void 0,(function*(){const e=null==i?void 0:i.localAudioStreams.find((e=>"Audio"===e.mediaStreamType));if(e&&(null==n?void 0:n.onResolveDeepNoiseSuppressionDependency)){const t={noiseSuppression:!0};return yield e.feature(oD.AudioEffects).stopEffects(t)}})),onStartCaptions:e=>rU(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(oD.Captions).captions;yield null==t?void 0:t.startCaptions(e)})),onStopCaptions:()=>rU(void 0,void 0,void 0,(function*(){const e=null==i?void 0:i.feature(oD.Captions).captions;yield null==e?void 0:e.stopCaptions()})),onSetCaptionLanguage:e=>rU(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(oD.Captions).captions;yield t.setCaptionLanguage(e)})),onSetSpokenLanguage:e=>rU(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(oD.Captions).captions;yield null==t?void 0:t.setSpokenLanguage(e)})),onSubmitSurvey:e=>rU(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.feature(oD.CallSurvey).submitSurvey(e)})),onStartSpotlight:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.Spotlight).startSpotlight(t)})),onStopSpotlight:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.Spotlight).stopSpotlight(t)})),onStopAllSpotlight:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.Spotlight).stopAllSpotlight()})),onStartLocalSpotlight:c?()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.Spotlight).startSpotlight()})):void 0,onStopLocalSpotlight:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.Spotlight).stopSpotlight()})),onStartRemoteSpotlight:c?e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.Spotlight).startSpotlight(t)})):void 0,onStopRemoteSpotlight:d?e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.Spotlight).stopSpotlight(t)})):void 0,onMuteParticipant:e=>rU(void 0,void 0,void 0,(function*(){(null==i?void 0:i.remoteParticipants)&&(null==i||i.remoteParticipants.forEach((t=>rU(void 0,void 0,void 0,(function*(){iL(t.identifier)===e&&(yield t.mute())})))))})),onMuteAllRemoteParticipants:()=>rU(void 0,void 0,void 0,(function*(){null==i||i.muteAllRemoteParticipants()})),onAcceptCall:l,onRejectCall:l,onCreateTogetherModeStreamView:(...t)=>rU(void 0,[...t],void 0,(function*(t={scalingMode:"Fit",isMirrored:!1,viewKind:"main"}){if(!i)return;const n=e.getState().calls[i.id];if(!n)return;const r={},s=n.togetherMode.streams.mainVideoStream;if(s&&s.isAvailable&&!s.view){const n=yield e.createView(i.id,void 0,s,t);r.mainVideoView=(null==n?void 0:n.view)?{view:null==n?void 0:n.view}:void 0}return r})),onStartTogetherMode:l,onSetTogetherModeSceneSize:(e,t)=>{const n=null==i?void 0:i.feature(oD.TogetherMode);n&&(n.sceneSize={width:e,height:t})},onDisposeTogetherModeStreamView:()=>rU(void 0,void 0,void 0,(function*(){if(!i)return;const t=e.getState().calls[i.id];if(!t)throw new Error(`Call Not Found: ${i.id}`);const n=t.togetherMode.streams;n.mainVideoStream&&n.mainVideoStream.view&&e.disposeView(i.id,void 0,n.mainVideoStream)})),onForbidAudio:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.MediaAccess).forbidAudio(t)})),onPermitAudio:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.MediaAccess).permitAudio(t)})),onForbidOthersAudio:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.MediaAccess).forbidOthersAudio()})),onPermitOthersAudio:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.MediaAccess).permitOthersAudio()})),onForbidVideo:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.MediaAccess).forbidVideo(t)})),onPermitVideo:e=>rU(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>rL(e)));yield null==i?void 0:i.feature(oD.MediaAccess).permitVideo(t)})),onForbidOthersVideo:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.MediaAccess).forbidOthersVideo()})),onPermitOthersVideo:()=>rU(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(oD.MediaAccess).permitOthersVideo()})),onSendRealTimeText:(e,t)=>rU(void 0,void 0,void 0,(function*(){const n=null==i?void 0:i.feature(oD.RealTimeText);yield null==n?void 0:n.sendRealTimeText(e,t)}))}}));var oU=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const lU=nU(((...e)=>{const[t,i,n,r,s]=e,a=aU(t,n,r,s);return Object.assign(Object.assign({},a),{onStartCall:(e,t)=>null==i?void 0:i.startCall(e,t),onAddParticipant:(e,t)=>oU(void 0,void 0,void 0,(function*(){const i=rL(e);YN(i)?null==r||r.addParticipant(i,t):(JN(i)||QN(i))&&(null==r||r.addParticipant(i))})),onRemoveParticipant:e=>oU(void 0,void 0,void 0,(function*(){const t=rL(e);yield null==r?void 0:r.removeParticipant(t)})),onAcceptCall:(e,n)=>oU(void 0,void 0,void 0,(function*(){const r=n?yield mL(t):void 0,s=null==i?void 0:i.incomingCalls.find((t=>t.id===e));s&&(yield s.accept(r?{videoOptions:{localVideoStreams:[r]}}:void 0))})),onRejectCall:e=>oU(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.incomingCalls.find((t=>t.id===e));t&&(yield t.reject())}))})}));var cU=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const dU=nU(((e,t,i,n,r)=>Object.assign(Object.assign({},aU(e,i,n,r)),{onStartCall:(e,i)=>{const n=null==i?void 0:i.threadId;if(!(e=>e.every((e=>!JN(e))))(e))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(t)return t.startCall(e,n?Object.assign({threadId:n},i):void 0)},onAddParticipant:(e,t)=>cU(void 0,void 0,void 0,(function*(){const i=rL(e),r=null==t?void 0:t.threadId;if(JN(i))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(ZN(i))throw new Error("Adding Microsoft Teams app identifier is not supported!");YN(i)&&(null==n||n.addParticipant(i,r?{threadId:r}:void 0)),null==n||n.addParticipant(i)})),onRemoveParticipant:e=>cU(void 0,void 0,void 0,(function*(){const t=rL(e);if(JN(t))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(ZN(t))throw new Error("Removing Microsoft Teams app identifier is not supported!");yield null==n?void 0:n.removeParticipant(t)})),onAcceptCall:(i,n)=>cU(void 0,void 0,void 0,(function*(){const r=n?yield mL(e):void 0,s=null==t?void 0:t.incomingCalls.find((e=>e.id===i));s&&(yield s.accept(r?{videoOptions:{localVideoStreams:[r]}}:void 0))})),onRejectCall:e=>cU(void 0,void 0,void 0,(function*(){const i=null==t?void 0:t.incomingCalls.find((t=>t.id===e));i&&(yield i.reject())})),onStartTogetherMode:()=>cU(void 0,void 0,void 0,(function*(){if(!n)return;if(!e.getState().calls[n.id])return;const t=null==n?void 0:n.feature(oD.TogetherMode);yield null==t?void 0:t.start()}))})));function uU(e,t,i,n,r){if(TL(t)&&(!n||n&&CL(n)))return lU(e,t,i,n,r);if(bL(t)&&(!n||n&&EL(n)))return dU(e,t,i,n,r);throw new Error("Unhandled agent type")}const hU=(e,t)=>{const i={};return n=>{var r;const s=null===(r=n.call)||void 0===r?void 0:r.remoteParticipants;var a,o,l,c;a=void 0,o=void 0,c=function*(){let n=!1;if(s){for(const[t,r]of Object.entries(s)){if(i[t])continue;const s=yield e(t,{displayName:r.displayName});(null==s?void 0:s.displayName)&&r.displayName!==(null==s?void 0:s.displayName)&&(i[t]=null==s?void 0:s.displayName,n=!0)}n&&t()}},new((l=void 0)||(l=Promise))((function(e,t){function i(e){try{r(c.next(e))}catch(e){t(e)}}function n(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof l?r:new l((function(e){e(r)}))).then(i,n)}r((c=c.apply(a,o||[])).next())}));const d=(e=>{let t,i={};const n={};return r=>{var s,a,o,l;if((null===(s=r.call)||void 0===s?void 0:s.remoteParticipants)!==t){i={};const s=Object.entries((null===(a=r.call)||void 0===a?void 0:a.remoteParticipants)||{});for(const[t,r]of s){const s=e(t,r);if(void 0===s){i[t]=r;continue}(null===(o=n[t])||void 0===o?void 0:o.originalRef)!==r&&(n[t]={newParticipant:s,originalRef:r});const a=n[t];if(!a)throw new Error("Participant modifier encountered an unhandled exception.");i[t]=a.newParticipant}t=null===(l=r.call)||void 0===l?void 0:l.remoteParticipants}return Object.assign(Object.assign({},r),{call:r.call?Object.assign(Object.assign({},r.call),{remoteParticipants:i}):void 0})}})(((e,t)=>{if(i[e])return Object.assign(Object.assign({},t),{displayName:i[e]})}));return d(n)}};class gU{constructor(e,t,i){this.playingSounds=!1,this.onCallStateChanged=()=>{this.call.on("stateChanged",(()=>{var e,t,i,n,r,s,a;pU(this.call,this.callees)&&(null===(e=this.soundsLoaded)||void 0===e?void 0:e.callRingingSound)&&(this.soundsLoaded.callRingingSound.loop=!0,this.playSound(this.soundsLoaded.callRingingSound),this.playingSounds=!0),!pU(this.call,this.callees)&&(null===(t=this.soundsLoaded)||void 0===t?void 0:t.callRingingSound)&&(this.soundsLoaded.callRingingSound.loop=!1,this.soundsLoaded.callRingingSound.pause(),this.playingSounds=!1),"Disconnected"===this.call.state&&((null===(i=this.soundsLoaded)||void 0===i?void 0:i.callBusySound)&&603===(null===(n=this.call.callEndReason)||void 0===n?void 0:n.code)?(this.playSound(this.soundsLoaded.callBusySound),this.playingSounds=!0):(null===(r=this.soundsLoaded)||void 0===r?void 0:r.callEndedSound)&&0===(null===(s=this.call.callEndReason)||void 0===s?void 0:s.code)&&7015!==(null===(a=this.call.callEndReason)||void 0===a?void 0:a.subCode)&&(this.playSound(this.soundsLoaded.callEndedSound),this.playingSounds=!0))}))},this.call=e,this.callees=t,i&&(this.soundsLoaded=this.loadSounds(i),this.subscribeCallSoundEvents())}subscribeCallSoundEvents(){this.onCallStateChanged()}unsubscribeAll(){var e,t;null===(e=this.call)||void 0===e||e.off("stateChanged",this.onCallStateChanged),(null===(t=this.soundsLoaded)||void 0===t?void 0:t.callRingingSound)&&this.soundsLoaded.callRingingSound.pause()}pauseSounds(){var e,t,i;(null===(e=this.soundsLoaded)||void 0===e?void 0:e.callRingingSound)&&(this.soundsLoaded.callRingingSound.pause(),this.playingSounds=!1),(null===(t=this.soundsLoaded)||void 0===t?void 0:t.callEndedSound)&&(this.soundsLoaded.callEndedSound.pause(),this.playingSounds=!1),(null===(i=this.soundsLoaded)||void 0===i?void 0:i.callBusySound)&&(this.soundsLoaded.callBusySound.pause(),this.playingSounds=!1)}loadSounds(e){var t,i,n;let r,s,a;return(null==e?void 0:e.callEnded)&&(r=new Audio(null===(t=null==e?void 0:e.callEnded)||void 0===t?void 0:t.url),r.preload="auto"),(null==e?void 0:e.callRinging)&&(s=new Audio(null===(i=null==e?void 0:e.callRinging)||void 0===i?void 0:i.url),s.preload="auto"),(null==e?void 0:e.callBusy)&&(a=new Audio(null===(n=null==e?void 0:e.callBusy)||void 0===n?void 0:n.url),a.preload="auto"),{callEndedSound:r,callRingingSound:s,callBusySound:a}}playSound(e){e.play().catch((e=>{console.error(e,"Failed to play sound, check loader config to make sure it is correct")}))}}const pU=(e,t)=>!(!t||!t[0]||YN(t[0])||"Ringing"!==e.state&&"Connecting"!==e.state);var mU=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class fU{constructor(e,t,i,n,r,s){var a,o,l,c,d,u,h,g,p;this.emitter=new kL.EventEmitter,this.isReturningFromBreakoutRoom=!1,this.state={isLocalPreviewMicrophoneEnabled:!1,userId:e.userId,displayName:null===(a=e.callAgent)||void 0===a?void 0:a.displayName,devices:e.deviceManager,call:void 0,targetCallees:s,page:"configuration",latestErrors:e.latestErrors,latestNotifications:e.latestNotifications,isTeamsCall:t,isTeamsMeeting:i,isRoomsCall:n,alternateCallerId:null==r?void 0:r.alternateCallerId,environmentInfo:e.environmentInfo,unsupportedBrowserVersionsAllowed:!1,videoBackgroundImages:null===(o=null==r?void 0:r.videoBackgroundOptions)||void 0===o?void 0:o.videoBackgroundImages,onResolveVideoEffectDependency:null===(l=null==r?void 0:r.videoBackgroundOptions)||void 0===l?void 0:l.onResolveDependency,onResolveDeepNoiseSuppressionDependency:null===(c=null==r?void 0:r.deepNoiseSuppressionOptions)||void 0===c?void 0:c.onResolveDependency,deepNoiseSuppressionOnByDefault:null===(u=null===(d=null==r?void 0:r.deepNoiseSuppressionOptions)||void 0===d?void 0:d.deepNoiseSuppressionOnByDefault)||void 0===u||u,hideDeepNoiseSuppressionButton:null!==(g=null===(h=null==r?void 0:r.deepNoiseSuppressionOptions)||void 0===h?void 0:h.hideDeepNoiseSuppressionButton)&&void 0!==g&&g,selectedVideoBackgroundEffect:void 0,cameraStatus:void 0,sounds:null==r?void 0:r.callingSounds,reactions:null==r?void 0:r.reactionResources},this.emitter.setMaxListeners(null!==(p=null==r?void 0:r.maxListeners)&&void 0!==p?p:125),this.bindPublicMethods(),this.displayNameModifier=(null==r?void 0:r.onFetchProfile)?hU(r.onFetchProfile,(()=>{this.setState(this.getState())})):void 0}bindPublicMethods(){this.setAllowedUnsupportedBrowser.bind(this)}onStateChange(e){this.emitter.on("stateChanged",e)}offStateChange(e){this.emitter.off("stateChanged",e)}setState(e){this.state=this.displayNameModifier?this.displayNameModifier(e):e,this.state=TU(this.state),this.emitter.emit("stateChanged",this.state)}updateCaptionsStartedInBackground(e){var t;const i=null!==(t=this.state.captionsTriggers)&&void 0!==t?t:{};i.captionsStartedInBackground=e,this.setState(Object.assign(Object.assign({},this.state),{captionsTriggers:i}))}updateCaptionsStartedWithUI(e){var t;const i=null!==(t=this.state.captionsTriggers)&&void 0!==t?t:{};i.captionsStartedWithUI=e,this.setState(Object.assign(Object.assign({},this.state),{captionsTriggers:i}))}getState(){return this.state}setIsLocalMicrophoneEnabled(e){this.setState(Object.assign(Object.assign({},this.state),{isLocalPreviewMicrophoneEnabled:e}))}setCurrentCallId(e){this.callId=e}setTargetCallee(e){this.setState(Object.assign(Object.assign({},this.state),{targetCallees:e}))}setIsReturningFromBreakoutRoom(e){this.isReturningFromBreakoutRoom=e}onCallEnded(e){this.emitter.on("callEnded",e)}offCallEnded(e){this.emitter.off("callEnded",e)}updateClientState(e){var t,i,n;let r=this.callId?e.calls[this.callId]:void 0;const s=e.callsEnded?vU(e.callsEnded):void 0,a=this.state.page,o={environmentInfo:this.state.environmentInfo,unsupportedBrowserVersionOptedIn:this.state.unsupportedBrowserVersionsAllowed},l=(null==r?void 0:r.transfer.acceptedTransfers)?SU(r.transfer.acceptedTransfers):void 0,c=l?e.calls[l.callId]:void 0;"Connected"!==(null==r?void 0:r.state)&&"Connecting"!==(null==r?void 0:r.state)||this.setIsReturningFromBreakoutRoom(!1);let d=!1;d=this.isReturningFromBreakoutRoom;const u=((e,t,i,n,r)=>{if(KF(null==r?void 0:r.environmentInfo,null==r?void 0:r.unsupportedBrowserVersionOptedIn))return"unsupportedEnvironment";if(void 0!==i)return"transferring";if(n)return"returningFromBreakoutRoom";if(e)return lL(null==e?void 0:e.state)?"lobby":"LocalHold"===(null==e?void 0:e.state)?"hold":"Disconnecting"===(null==e?void 0:e.state)?"leaving":oL(null==e?void 0:e.state)?"call":"configuration";if(t){const e=(e=>{var t,i,n,r;const s=Array.from(Object.values(e.remoteParticipantsEnded));if(s[0]&&YN(s[0].identifier)&&(null===(t=e.callEndReason)||void 0===t?void 0:t.subCode)!==BF)return jF.LEFT_CALL;if((null===(i=e.callEndReason)||void 0===i?void 0:i.subCode)&&5854===e.callEndReason.subCode)return jF.ACCESS_DENIED;if((null===(n=e.callEndReason)||void 0===n?void 0:n.subCode)&&VF.includes(e.callEndReason.subCode))return jF.REMOVED_FROM_CALL;if(400===(null===(r=e.callEndReason)||void 0===r?void 0:r.code))return jF.BAD_REQUEST;if(e.callEndReason)return jF.LEFT_CALL;throw new Error("No matching call end reason")})(t);switch(e){case jF.ACCESS_DENIED:return"accessDeniedTeamsMeeting";case jF.REMOVED_FROM_CALL:return"removedFromCall";case jF.BAD_REQUEST:return"badRequest";case jF.LEFT_CALL:return t.diagnostics.network.latest.noNetwork?"joinCallFailedDueToNoNetwork":"leftCall"}}return"configuration"})(r,s,c,d,o);!qF(a)&&qF(u)&&(this.callId===(null==s?void 0:s.id)&&this.emitter.emit("callEnded",{callId:null==s?void 0:s.id,code:null===(t=null==s?void 0:s.callEndReason)||void 0===t?void 0:t.code,subCode:null===(i=null==s?void 0:s.callEndReason)||void 0===i?void 0:i.subCode}),this.setCurrentCallId(void 0),r=void 0),this.state.page&&this.setState(Object.assign(Object.assign({},this.state),{userId:e.userId,displayName:null===(n=e.callAgent)||void 0===n?void 0:n.displayName,call:r,page:u,endedCall:s,devices:e.deviceManager,latestErrors:e.latestErrors,latestNotifications:e.latestNotifications,cameraStatus:(null==r?void 0:r.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||e.deviceManager.unparentedViews.find((e=>"Video"===e.mediaStreamType))?"On":"Off",acceptedTransferCallState:c}))}setAllowedUnsupportedBrowser(){this.setState(Object.assign(Object.assign({},this.state),{unsupportedBrowserVersionsAllowed:!0}))}setBackroundPickerImages(e){this.setState(Object.assign(Object.assign({},this.state),{videoBackgroundImages:e}))}setSelectedVideoBackgroundEffect(e){this.setState(Object.assign(Object.assign({},this.state),{selectedVideoBackgroundEffect:e}))}setAcceptedTransferCall(e){this.setState(Object.assign(Object.assign({},this.state),{acceptedTransferCallState:e}))}}const vU=e=>{var t,i,n,r;const s=Object.values(e);if(0===s.length)return;let a=s[0];for(const e of s.slice(1))(null!==(i=null===(t=e.endTime)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)>(null!==(r=null===(n=null==a?void 0:a.endTime)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&(a=e);return a},SU=e=>{var t,i,n,r;const s=Object.values(e);if(0===s.length)return;let a=s[0];for(const e of s.slice(1))(null!==(i=null===(t=e.timestamp)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)>(null!==(r=null===(n=null==a?void 0:a.timestamp)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&(a=e);return a};class yU{get call(){return this._call}set call(e){this.resetDiagnosticsForwarder(e),this._call=e}constructor(e,t,i,n,r){var s,a,o;this.participantSubscribers=new Map,this.emitter=new kL.EventEmitter,this.isMyMutedChanged=()=>{var e;this.emitter.emit("isMutedChanged",{participantId:this.getState().userId,isMuted:null===(e=this.call)||void 0===e?void 0:e.isMuted})},this.bindPublicMethods(),this.callClient=e,this.callAgent=i,this.targetCallees=!0===QF(t)?t:void 0,this.locator=!1===QF(t)?t:void 0,this.deviceManager=n;const l=!!this.locator&&("meetingLink"in this.locator||"meetingId"in this.locator);let c;null===(s=this.targetCallees)||void 0===s||s.forEach((e=>{(QN(e)||ZN(e))&&(c=!0)}));const d=!!this.locator&&"roomId"in this.locator;this.onResolveVideoBackgroundEffectsDependency=null===(a=null==r?void 0:r.videoBackgroundOptions)||void 0===a?void 0:a.onResolveDependency,this.onResolveDeepNoiseSuppressionDependency=null===(o=null==r?void 0:r.deepNoiseSuppressionOptions)||void 0===o?void 0:o.onResolveDependency,this.context=new fU(e.getState(),!!c,l,d,r,this.targetCallees),this.context.onCallEnded((e=>this.emitter.emit("callEnded",e)));const u=t=>{var i,n,r,s,a;this?((null===(i=this.call)||void 0===i?void 0:i.id)&&this.context.setCurrentCallId(this.call.id),"Connected"===(null===(n=this.call)||void 0===n?void 0:n.state)&&(null===(r=this.callingSoundSubscriber)||void 0===r?void 0:r.playingSounds)&&this.callingSoundSubscriber.pauseSounds(),("InLobby"===(null===(s=this.call)||void 0===s?void 0:s.state)||"Connected"===(null===(a=this.call)||void 0===a?void 0:a.state))&&this.callClient.getState().deviceManager.unparentedViews.length>0&&this.callClient.getState().deviceManager.unparentedViews.forEach((e=>{this.callClient.disposeView(void 0,void 0,e)})),this.context.updateClientState(t)):e.offStateChange(u)};if(this.handlers=uU(e,i,n,void 0,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency,onResolveDeepNoiseSuppressionDependency:this.onResolveDeepNoiseSuppressionDependency}),this.onClientStateChange=u,this.subscribeDeviceManagerEvents(),this.callClient.onStateChange(u),"CallAgent"===this.callAgent.kind){const e=e=>{var t;if(!(null===(t=this.call)||void 0===t?void 0:t.id))return;const n=e.removed.find((e=>{var t;return e.id===(null===(t=this.call)||void 0===t?void 0:t.id)}));if(!n)return;const r=this.callClient.getState().callsEnded[n.id];if(!r)return;const s=SU(r.transfer.acceptedTransfers),a=i.calls.find((e=>e.id===(null==s?void 0:s.callId)));a&&this.processNewCall(a)};this.callAgent.on("callsUpdated",e)}if("TeamsCallAgent"===this.callAgent.kind){const e=e=>{var t;if(!(null===(t=this.call)||void 0===t?void 0:t.id))return;const n=e.removed.find((e=>{var t;return e.id===(null===(t=this.call)||void 0===t?void 0:t.id)}));if(!n)return;const r=this.callClient.getState().callsEnded[n.id];if(!r)return;const s=SU(r.transfer.acceptedTransfers),a=i.calls.find((e=>e.id===(null==s?void 0:s.callId)));a&&this.processNewCall(a)};this.callAgent.on("callsUpdated",e)}}subscribeDeviceManagerEvents(){this.deviceManager.on("selectedMicrophoneChanged",(()=>{this.emitter.emit("selectedMicrophoneChanged")})),this.deviceManager.on("selectedSpeakerChanged",(()=>{this.emitter.emit("selectedSpeakerChanged")}))}bindPublicMethods(){this.onStateChange.bind(this),this.offStateChange.bind(this),this.getState.bind(this),this.dispose.bind(this),this.joinCall.bind(this),this.leaveCall.bind(this),this.setCamera.bind(this),this.setMicrophone.bind(this),this.setSpeaker.bind(this),this.askDevicePermission.bind(this),this.queryCameras.bind(this),this.queryMicrophones.bind(this),this.querySpeakers.bind(this),this.startCamera.bind(this),this.stopCamera.bind(this),this.mute.bind(this),this.unmute.bind(this),this.startCall.bind(this),this.startScreenShare.bind(this),this.stopScreenShare.bind(this),this.raiseHand.bind(this),this.onReactionClick.bind(this),this.lowerHand.bind(this),this.removeParticipant.bind(this),this.createStreamView.bind(this),this.disposeStreamView.bind(this),this.createTogetherModeStreamView.bind(this),this.startTogetherMode.bind(this),this.setTogetherModeSceneSize.bind(this),this.disposeTogetherModeStreamView.bind(this),this.disposeScreenShareStreamView.bind(this),this.disposeRemoteVideoStreamView.bind(this),this.disposeLocalVideoStreamView.bind(this),this.on.bind(this),this.off.bind(this),this.processNewCall.bind(this),this.addParticipant.bind(this),this.holdCall.bind(this),this.resumeCall.bind(this),this.sendDtmfTone.bind(this),this.allowUnsupportedBrowserVersion.bind(this),this.startCaptions.bind(this),this.stopCaptions.bind(this),this.setSpokenLanguage.bind(this),this.setCaptionLanguage.bind(this),this.sendRealTimeText.bind(this),this.startVideoBackgroundEffect.bind(this),this.stopVideoBackgroundEffects.bind(this),this.updateBackgroundPickerImages.bind(this),this.startNoiseSuppressionEffect.bind(this),this.stopNoiseSuppressionEffect.bind(this),this.submitSurvey.bind(this),this.startSpotlight.bind(this),this.stopSpotlight.bind(this),this.stopAllSpotlight.bind(this),this.muteParticipant.bind(this),this.muteAllRemoteParticipants.bind(this),this.forbidOthersAudio.bind(this),this.permitOthersAudio.bind(this),this.forbidOthersAudio.bind(this),this.permitOthersAudio.bind(this)}dispose(){this.resetDiagnosticsForwarder(),this.callClient.offStateChange(this.onClientStateChange),this.callAgent.dispose()}queryCameras(){return mU(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){const t=yield this.deviceManager.getCameras(),i=(new Date).getTime();return N.info("time to query cameras",i-e,"ms"),t}))))}))}queryMicrophones(){return mU(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){const t=yield this.deviceManager.getMicrophones(),i=(new Date).getTime();return N.info("time to query microphones",i-e,"ms"),t}))))}))}querySpeakers(){return mU(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){const t=(yield this.deviceManager.isSpeakerSelectionAvailable)?this.deviceManager.getSpeakers():[],i=(new Date).getTime();return N.info("time to query speakers",i-e,"ms"),t}))))}))}askDevicePermission(e){return mU(this,void 0,void 0,(function*(){const t=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){const i=yield this.deviceManager.askDevicePermission(e),n=(new Date).getTime();return N.info("time to query askDevicePermissions",n-t,"ms"),i}))))}))}joinCall(e){var t,i;if(oL(null!==(i=null===(t=this.getState().call)||void 0===t?void 0:t.state)&&void 0!==i?i:"None"))throw new Error("You are already in the call!");if(void 0===this.locator)throw new Error("Locator is not defined!");return this.teeErrorToEventEmitter((()=>{let t="On"===this.getState().cameraStatus,i=this.getState().isLocalPreviewMicrophoneEnabled;"boolean"==typeof e?i=e:"object"==typeof e&&(e.microphoneOn&&"keep"!==e.microphoneOn&&(i=e.microphoneOn),e.cameraOn&&"keep"!==e.cameraOn&&(t=e.cameraOn));const n={muted:!i},r=YF(this.getState()),s=r&&t?{localVideoStreams:[new UI(r)]}:{},a=this._joinCall(n,s);return this.originCall=a,this.processNewCall(a),a}))}_joinCall(e,t){const i=!!this.locator&&"meetingLink"in this.locator,n=!!this.locator&&"meetingId"in this.locator;if(this.locator&&this.locator,bL(this.callAgent)){if(i)return this.callAgent.join(this.locator,{audioOptions:e,videoOptions:t});if(n)return this.callAgent.join(this.locator,{audioOptions:e,videoOptions:t});throw new Error("Locator not supported by TeamsCallAgent")}return this.callAgent.join(this.locator,{audioOptions:e,videoOptions:t})}createStreamView(e,t){return mU(this,void 0,void 0,(function*(){return void 0===e?yield this.handlers.onCreateLocalStreamView(t):yield this.handlers.onCreateRemoteStreamView(e,t)}))}disposeStreamView(e){return mU(this,void 0,void 0,(function*(){void 0===e?yield this.handlers.onDisposeLocalStreamView():yield this.handlers.onDisposeRemoteStreamView(e)}))}disposeScreenShareStreamView(e){return mU(this,void 0,void 0,(function*(){""!==e?yield this.handlers.onDisposeRemoteScreenShareStreamView(e):yield this.handlers.onDisposeLocalScreenShareStreamView()}))}disposeRemoteVideoStreamView(e){return mU(this,void 0,void 0,(function*(){yield this.handlers.onDisposeRemoteVideoStreamView(e)}))}disposeLocalVideoStreamView(){return mU(this,void 0,void 0,(function*(){yield this.handlers.onDisposeLocalStreamView()}))}createTogetherModeStreamView(e){return mU(this,void 0,void 0,(function*(){return yield this.handlers.onCreateTogetherModeStreamView(e)}))}startTogetherMode(){return mU(this,void 0,void 0,(function*(){return yield this.handlers.onStartTogetherMode()}))}setTogetherModeSceneSize(e,t){return this.handlers.onSetTogetherModeSceneSize(e,t)}disposeTogetherModeStreamView(){return mU(this,void 0,void 0,(function*(){return yield this.handlers.onDisposeTogetherModeStreamView()}))}leaveCall(e){return mU(this,void 0,void 0,(function*(){if("transferring"===this.getState().page){const e=this.callAgent.calls.filter((e=>{var t;return e.id===(null===(t=this.getState().acceptedTransferCallState)||void 0===t?void 0:t.id)}))[0];null==e||e.hangUp()}yield this.handlers.onHangUp(e),this.unsubscribeCallEvents(),this.handlers=uU(this.callClient,this.callAgent,this.deviceManager,this.call,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency,onResolveDeepNoiseSuppressionDependency:this.onResolveDeepNoiseSuppressionDependency}),this.call=void 0,this.stopCamera(),this.mute()}))}setCamera(e,t){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onSelectCamera(e,t)}))))}))}setMicrophone(e){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onSelectMicrophone(e)}))))}))}setSpeaker(e){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onSelectSpeaker(e)}))))}))}startCamera(e){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){if(!HF(this.getState())){{const e=this.getState().selectedVideoBackgroundEffect,t=YF(this.getState());if(e&&t&&this.onResolveVideoBackgroundEffectsDependency){const i=new UI(t),n=((e,t)=>"blur"===(null==e?void 0:e.effectName)?t.createBackgroundBlurEffect():"replacement"===(null==e?void 0:e.effectName)?t.createBackgroundReplacementEffect({backgroundImageUrl:e.backgroundImageUrl}):void 0)(e,yield this.onResolveVideoBackgroundEffectsDependency());n?yield i.feature(oD.VideoEffects).startEffects(n):yield i.feature(oD.VideoEffects).stopEffects()}}yield this.handlers.onToggleCamera(e)}}))))}))}stopCamera(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){HF(this.getState())&&(yield this.handlers.onToggleCamera())}))))}))}mute(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){var e,t;this.context.setIsLocalMicrophoneEnabled(!1),oL(null===(e=this.call)||void 0===e?void 0:e.state)&&!(null===(t=this.call)||void 0===t?void 0:t.isMuted)&&(yield this.handlers.onToggleMicrophone())}))))}))}unmute(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){var e,t,i;this.context.setIsLocalMicrophoneEnabled(!0),(oL(null===(e=this.call)||void 0===e?void 0:e.state)||lL(null===(t=this.call)||void 0===t?void 0:t.state))&&(null===(i=this.call)||void 0===i?void 0:i.isMuted)&&(yield this.handlers.onToggleMicrophone())}))))}))}startScreenShare(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){var e;(null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn)||(yield this.handlers.onToggleScreenShare())}))))}))}stopScreenShare(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){var e;(null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn)&&(yield this.handlers.onToggleScreenShare())}))))}))}raiseHand(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onToggleRaiseHand()}))))}))}lowerHand(){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onToggleRaiseHand()}))))}))}onReactionClick(e){return mU(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>mU(this,void 0,void 0,(function*(){yield this.handlers.onReactionClick(e)}))))}))}allowUnsupportedBrowserVersion(){this.context.setAllowedUnsupportedBrowser(),this.context.updateClientState(this.callClient.getState())}startVideoBackgroundEffect(e){return mU(this,void 0,void 0,(function*(){if(this.isBlurEffect(e)){const t=e;yield this.handlers.onBlurVideoBackground(t)}else if(this.isReplacementEffect(e)){const t=e;yield this.handlers.onReplaceVideoBackground(t)}}))}stopVideoBackgroundEffects(){return mU(this,void 0,void 0,(function*(){yield this.handlers.onRemoveVideoBackgroundEffects()}))}updateBackgroundPickerImages(e){this.context.setBackroundPickerImages(e)}updateSelectedVideoBackgroundEffect(e){this.context.setSelectedVideoBackgroundEffect(e)}startNoiseSuppressionEffect(){return mU(this,void 0,void 0,(function*(){yield this.handlers.onStartNoiseSuppressionEffect()}))}stopNoiseSuppressionEffect(){return mU(this,void 0,void 0,(function*(){yield this.handlers.onStopNoiseSuppressionEffect()}))}startCall(e,t){var i,n;if(oL(null!==(n=null===(i=this.getState().call)||void 0===i?void 0:i.state)&&void 0!==n?n:"None"))throw new Error("You are already in the call.");const r="On"===this.getState().cameraStatus,s=YF(this.getState()),a=s?{videoOptions:r?{localVideoStreams:[new UI(s)]}:void 0}:{},o=Object.assign(Object.assign({},a),t),l=e.map((e=>{const i=rL(e);if("phoneNumber"in i&&void 0===(null==t?void 0:t.alternateCallerId))throw new Error("Unable to start call, PSTN user present with no alternateCallerId.");return i}));this.context.setTargetCallee(l);const c=this.handlers.onStartCall(l,o);if(!c)throw new Error("Unable to start call.");return this.processNewCall(c),c}processNewCall(e){this.call=e,this.context.setCurrentCallId(e.id),this.context.updateClientState(this.callClient.getState()),this.handlers=uU(this.callClient,this.callAgent,this.deviceManager,this.call,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency,onResolveDeepNoiseSuppressionDependency:this.onResolveDeepNoiseSuppressionDependency}),this.subscribeCallEvents()}isBlurEffect(e){return"blur"===e.effectName}isReplacementEffect(e){return"replacement"===e.effectName}removeParticipant(e){return mU(this,void 0,void 0,(function*(){let t=e;t=rL(e),this.handlers.onRemoveParticipant(t)}))}addParticipant(e,t){return mU(this,void 0,void 0,(function*(){YN(e)&&t?this.handlers.onAddParticipant(e,t):JN(e)&&this.handlers.onAddParticipant(e)}))}holdCall(){return mU(this,void 0,void 0,(function*(){var e,t;"LocalHold"!==(null===(e=this.call)||void 0===e?void 0:e.state)&&((null===(t=this.call)||void 0===t?void 0:t.isLocalVideoStarted)?this.stopCamera().then((()=>{this.handlers.onToggleHold()})):this.handlers.onToggleHold())}))}resumeCall(){return mU(this,void 0,void 0,(function*(){var e;"LocalHold"===(null===(e=this.call)||void 0===e?void 0:e.state)&&this.handlers.onToggleHold().then((()=>{var e;!1===(null===(e=this.call)||void 0===e?void 0:e.feature(oD.Capabilities).capabilities.turnVideoOn.isPresent)&&this.stopCamera()}))}))}sendDtmfTone(e){return mU(this,void 0,void 0,(function*(){this.handlers.onSendDtmfTone(e)}))}startCaptions(e){return mU(this,void 0,void 0,(function*(){(null==e?void 0:e.startInBackground)?this.context.updateCaptionsStartedInBackground(!0):this.context.updateCaptionsStartedWithUI(!0),this.handlers.onStartCaptions(e)}))}stopCaptions(e){return mU(this,void 0,void 0,(function*(){var t;(null==e?void 0:e.stopInBackground)&&this.context.updateCaptionsStartedInBackground(!1),this.context.updateCaptionsStartedWithUI(!1),(null===(t=this.context.getState().captionsTriggers)||void 0===t?void 0:t.captionsStartedInBackground)||this.handlers.onStopCaptions()}))}setCaptionLanguage(e){return mU(this,void 0,void 0,(function*(){this.handlers.onSetCaptionLanguage(e)}))}setSpokenLanguage(e){return mU(this,void 0,void 0,(function*(){this.handlers.onSetSpokenLanguage(e)}))}sendRealTimeText(e,t){return mU(this,void 0,void 0,(function*(){this.handlers.onSendRealTimeText(e,t)}))}submitSurvey(e){return mU(this,void 0,void 0,(function*(){return this.handlers.onSubmitSurvey(e)}))}muteParticipant(e){return mU(this,void 0,void 0,(function*(){this.handlers.onMuteParticipant(e)}))}muteAllRemoteParticipants(){return mU(this,void 0,void 0,(function*(){this.handlers.onMuteAllRemoteParticipants()}))}startSpotlight(e){return mU(this,void 0,void 0,(function*(){this.handlers.onStartSpotlight(e)}))}stopSpotlight(e){return mU(this,void 0,void 0,(function*(){this.handlers.onStopSpotlight(e)}))}stopAllSpotlight(){return mU(this,void 0,void 0,(function*(){this.handlers.onStopAllSpotlight()}))}forbidAudio(e){return mU(this,void 0,void 0,(function*(){var t,i;null===(i=(t=this.handlers).onForbidAudio)||void 0===i||i.call(t,e)}))}permitAudio(e){return mU(this,void 0,void 0,(function*(){var t,i;null===(i=(t=this.handlers).onPermitAudio)||void 0===i||i.call(t,e)}))}forbidOthersAudio(){return mU(this,void 0,void 0,(function*(){var e,t;null===(t=(e=this.handlers).onForbidOthersAudio)||void 0===t||t.call(e)}))}permitOthersAudio(){return mU(this,void 0,void 0,(function*(){var e,t;null===(t=(e=this.handlers).onPermitOthersAudio)||void 0===t||t.call(e)}))}forbidVideo(e){return mU(this,void 0,void 0,(function*(){var t,i;null===(i=(t=this.handlers).onForbidVideo)||void 0===i||i.call(t,e)}))}permitVideo(e){return mU(this,void 0,void 0,(function*(){var t,i;null===(i=(t=this.handlers).onPermitVideo)||void 0===i||i.call(t,e)}))}forbidOthersVideo(){return mU(this,void 0,void 0,(function*(){var e,t;null===(t=(e=this.handlers).onForbidOthersVideo)||void 0===t||t.call(e)}))}permitOthersVideo(){return mU(this,void 0,void 0,(function*(){var e,t;null===(t=(e=this.handlers).onPermitOthersVideo)||void 0===t||t.call(e)}))}returnFromBreakoutRoom(){return mU(this,void 0,void 0,(function*(){var e,t;const i=(null===(e=this.call)||void 0===e?void 0:e.id)?this.callClient.getState().calls[this.call.id]:void 0,n=null===(t=null==i?void 0:i.breakoutRooms)||void 0===t?void 0:t.assignedBreakoutRoom;if(!n)throw new Error("Could not return from breakout room because assigned breakout room state could not be retrieved.");this.context.setIsReturningFromBreakoutRoom(!0);const r=yield n.returnToMainMeeting();this.originCall=r,this.processNewCall(r)}))}getState(){return this.context.getState()}onStateChange(e){this.context.onStateChange(e)}offStateChange(e){this.context.offStateChange(e)}on(e,t){this.emitter.on(e,t)}subscribeToCaptionEvents(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions);if("TeamsCaptions"===(null==t?void 0:t.captions.kind)&&(this.context.getState().isTeamsCall||this.context.getState().isTeamsMeeting)){const e=t.captions;e.on("CaptionsReceived",this.teamsCaptionsReceived.bind(this)),e.on("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.on("CaptionLanguageChanged",this.isCaptionLanguageChanged.bind(this)),e.on("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}else{const e=null==t?void 0:t.captions;e.on("CaptionsReceived",this.captionsReceived.bind(this)),e.on("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.on("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this)),null==t||t.on("CaptionsKindChanged",this.captionsKindChanged.bind(this))}}unsubscribeFromCaptionEvents(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions);if("TeamsCaptions"===(null==t?void 0:t.captions.kind)&&(this.context.getState().isTeamsCall||this.context.getState().isTeamsMeeting)){const e=t.captions;e.off("CaptionsReceived",this.teamsCaptionsReceived.bind(this)),e.off("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.off("CaptionLanguageChanged",this.isCaptionLanguageChanged.bind(this)),e.off("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}else{const e=null==t?void 0:t.captions;e.off("CaptionsReceived",this.captionsReceived.bind(this)),e.off("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.off("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this)),null==t||t.off("CaptionsKindChanged",this.captionsKindChanged.bind(this))}}subscribeCallEvents(){var e,t,i,n,r,s,a,o,l,c;this.call&&(this.callingSoundSubscriber=new gU(this.call,this.getState().targetCallees,this.getState().sounds)),null===(e=this.call)||void 0===e||e.on("remoteParticipantsUpdated",this.onRemoteParticipantsUpdated.bind(this)),null===(t=this.call)||void 0===t||t.on("isMutedChanged",this.isMyMutedChanged.bind(this)),null===(i=this.call)||void 0===i||i.on("isScreenSharingOnChanged",this.isScreenSharingOnChanged.bind(this)),null===(n=this.call)||void 0===n||n.on("idChanged",this.callIdChanged.bind(this)),null===(r=this.call)||void 0===r||r.on("roleChanged",this.roleChanged.bind(this)),this.subscribeToCaptionEvents(),null===(s=this.call)||void 0===s||s.feature(oD.Transfer).on("transferAccepted",this.transferAccepted.bind(this)),null===(a=this.call)||void 0===a||a.feature(oD.Capabilities).on("capabilitiesChanged",this.capabilitiesChanged.bind(this)),null===(o=this.call)||void 0===o||o.feature(oD.Spotlight).on("spotlightChanged",this.spotlightChanged.bind(this)),null===(l=this.call)||void 0===l||l.feature(oD.RealTimeText).on("realTimeTextReceived",this.realTimeTextReceived.bind(this));const d=null===(c=this.call)||void 0===c?void 0:c.feature(oD.BreakoutRooms);d&&d.on("breakoutRoomsUpdated",this.breakoutRoomsUpdated.bind(this))}unsubscribeCallEvents(){var e,t,i,n,r,s,a;for(const e of this.participantSubscribers.values())e.unsubscribeAll();this.participantSubscribers.clear(),null===(e=this.call)||void 0===e||e.off("remoteParticipantsUpdated",this.onRemoteParticipantsUpdated.bind(this)),null===(t=this.call)||void 0===t||t.off("isMutedChanged",this.isMyMutedChanged.bind(this)),null===(i=this.call)||void 0===i||i.off("isScreenSharingOnChanged",this.isScreenSharingOnChanged.bind(this)),null===(n=this.call)||void 0===n||n.off("idChanged",this.callIdChanged.bind(this)),null===(r=this.call)||void 0===r||r.off("roleChanged",this.roleChanged.bind(this)),this.unsubscribeFromCaptionEvents(),null===(s=this.call)||void 0===s||s.feature(oD.RealTimeText).off("realTimeTextReceived",this.realTimeTextReceived.bind(this)),this.callingSoundSubscriber&&this.callingSoundSubscriber.unsubscribeAll();const o=null===(a=this.call)||void 0===a?void 0:a.feature(oD.BreakoutRooms);o&&o.off("breakoutRoomsUpdated",this.breakoutRoomsUpdated.bind(this))}captionsKindChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions),i=null==t?void 0:t.captions;i.on("CaptionsReceived",this.teamsCaptionsReceived.bind(this)),i.on("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),i.on("CaptionLanguageChanged",this.isCaptionLanguageChanged.bind(this)),i.on("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}onRemoteParticipantsUpdated({added:e,removed:t}){e&&e.length>0&&this.emitter.emit("participantsJoined",{joined:e}),t&&t.length>0&&this.emitter.emit("participantsLeft",{removed:t}),e.forEach((e=>{this.participantSubscribers.set(iL(e.identifier),new XF(e,this.emitter))})),t.forEach((e=>{const t=this.participantSubscribers.get(iL(e.identifier));t&&t.unsubscribeAll(),this.participantSubscribers.delete(iL(e.identifier))}))}isScreenSharingOnChanged(){var e;this.emitter.emit("isLocalScreenSharingActiveChanged",{isScreenSharingOn:null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn})}teamsCaptionsReceived(e){this.emitter.emit("captionsReceived",{captionsInfo:e})}captionsReceived(e){this.emitter.emit("captionsReceived",{captionsInfo:e})}realTimeTextReceived(e){this.emitter.emit("realTimeTextReceived",{realTimeText:e})}isCaptionsActiveChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions).captions;this.emitter.emit("isCaptionsActiveChanged",{isActive:t.isCaptionsFeatureActive})}isSpokenLanguageChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions).captions;this.emitter.emit("isSpokenLanguageChanged",{activeSpokenLanguage:t.activeSpokenLanguage})}isCaptionLanguageChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(oD.Captions).captions;this.emitter.emit("isCaptionLanguageChanged",{activeCaptionLanguage:t.activeCaptionLanguage})}transferAccepted(e){this.emitter.emit("transferAccepted",e)}capabilitiesChanged(e){var t,i;!1===(null===(t=e.newValue.turnVideoOn)||void 0===t?void 0:t.isPresent)&&this.disposeLocalVideoStreamView(),!1===(null===(i=e.newValue.shareScreen)||void 0===i?void 0:i.isPresent)&&this.stopScreenShare(),this.emitter.emit("capabilitiesChanged",e)}roleChanged(){var e,t;"Consumer"===(null===(e=this.call)||void 0===e?void 0:e.role)&&(null===(t=this.call)||void 0===t||t.feature(oD.RaiseHand).lowerHand()),this.emitter.emit("roleChanged")}spotlightChanged(e){this.emitter.emit("spotlightChanged",e)}breakoutRoomsUpdated(e){"assignedBreakoutRooms"===e.type?this.assignedBreakoutRoomUpdated(e.data):"join"===e.type&&this.breakoutRoomJoined(e.data),this.emitter.emit("breakoutRoomsUpdated",e)}assignedBreakoutRoomUpdated(e){var t,i,n;(null===(t=this.call)||void 0===t?void 0:t.id)&&((null===(i=this.originCall)||void 0===i?void 0:i.id)===(null===(n=this.call)||void 0===n?void 0:n.id)||e&&"closed"!==e.state||this.returnFromBreakoutRoom())}breakoutRoomJoined(e){var t;(null===(t=this.call)||void 0===t?void 0:t.id)!==e.id&&this.processNewCall(e),this.hangupOtherBreakoutRoomCalls(e.id)}hangupOtherBreakoutRoomCalls(e){const t=Object.values(this.callClient.getState().calls).filter((t=>{var i;return(null===(i=t.breakoutRooms)||void 0===i?void 0:i.breakoutRoomSettings)&&t.id!==e}));for(const e of t){const t=this.callAgent.calls.find((t=>t.id===e.id));null==t||t.hangUp()}}callIdChanged(){var e;(null===(e=this.call)||void 0===e?void 0:e.id)&&this.emitter.emit("callIdChanged",{callId:this.call.id})}resetDiagnosticsForwarder(e){this.diagnosticsForwarder&&this.diagnosticsForwarder.unsubscribe(),e&&(this.diagnosticsForwarder=new eU(this.emitter,e))}off(e,t){this.emitter.off(e,t)}asyncTeeErrorToEventEmitter(e){return mU(this,void 0,void 0,(function*(){try{return yield e()}catch(e){throw EU(e)&&this.emitter.emit("error",e),e}}))}teeErrorToEventEmitter(e){try{return e()}catch(e){throw EU(e)&&this.emitter.emit("error",e),e}}}const CU=e=>mU(void 0,[e],void 0,(function*({userId:e,displayName:t,credential:i,locator:n,targetCallees:r,options:s,telemetryImplementationHint:a="Call"}){if(!(JN(o=e)||YN(o)||QN(o)||(e=>"string"==typeof e.id)(o)))throw new Error("Invalid identifier. Please provide valid identifier object.");var o;const l=((e,t,i="StatefulComponents")=>(Ax.info(`Creating calling stateful client using library version: ${IF(i)}`),LF(new KN(xF(i,null==t?void 0:t.callClientOptions)),new Mx(XN(e.userId),null==t?void 0:t.maxStateChangeListeners),new EF)))({userId:e},void 0,a),c=yield l.createCallAgent(i,{displayName:t});let d;return d=function(e,t,i,n){return mU(this,void 0,void 0,(function*(){const r=yield e.getDeviceManager();return yield Promise.all([r.getCameras(),r.getMicrophones()]),r.isSpeakerSelectionAvailable&&(yield r.getSpeakers()),QF(i),new yU(e,i,t,r,n)}))}(l,c,n||r,s),d}));const TU=e=>{var t,i,n;return(null===(t=e.call)||void 0===t?void 0:t.captionsFeature)&&(null===(i=e.captionsTriggers)||void 0===i?void 0:i.captionsStartedInBackground)&&!(null===(n=e.captionsTriggers)||void 0===n?void 0:n.captionsStartedWithUI)?Object.assign(Object.assign({},e),{call:Object.assign(Object.assign({},e.call),{captionsFeature:Object.assign(Object.assign({},e.call.captionsFeature),{isCaptionsFeatureActive:!1,startCaptionsInProgress:!1})})}):e},EU=e=>"target"in e&&"innerError"in e;var bU=function(e,t){return bU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},bU(e,t)};function _U(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}bU(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var IU=function(){return IU=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},IU.apply(this,arguments)};function wU(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}function AU(e,t,i,n){var r,s=arguments.length,a=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a}function PU(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var RU,MU="__global__",DU="__shadow_dom_stylesheet__",kU={stylesheetKey:MU,inShadow:!1,window:void 0,__isShadowConfig__:!0},OU=function(e){return!(!e||!function(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}(e))&&!0===e.__isShadowConfig__};function NU(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=[],r=[],s=e;return function e(t){for(var i=0,a=t;i<a.length;i++){var o=a[i];if(o&&!OU(o))if("string"==typeof o)if(o.indexOf(" ")>=0)e(o.split(" "));else{var l=s.argsFromClassName(o);l?e(l):-1===n.indexOf(o)&&n.push(o)}else Array.isArray(o)?e(o):"object"==typeof o&&r.push(o)}}(t),{classes:n,objects:r}}function LU(e){RU!==e&&(RU=e)}function xU(){return void 0===RU&&(RU="undefined"!=typeof document&&!!document.documentElement&&"rtl"===document.documentElement.getAttribute("dir")),RU}function FU(){return{rtl:xU(),shadowConfig:kU}}RU=xU();var UU,BU="__stylesheet__",VU="undefined"!=typeof navigator&&/rv:11.0/.test(navigator.userAgent),HU={};try{HU=window||{}}catch(uc){}var $U,jU=function(){function e(e,t){var i,n,r,s,a,o;this._rules=[],this._preservedRules=[],this._counter=0,this._keyToClassName={},this._onInsertRuleCallbacks=[],this._onResetCallbacks=[],this._classNameToArgs={},this._config=IU({injectionMode:"undefined"==typeof document?0:1,defaultPrefix:"css",namespace:void 0,cspSettings:void 0},e),this._classNameToArgs=null!==(i=null==t?void 0:t.classNameToArgs)&&void 0!==i?i:this._classNameToArgs,this._counter=null!==(n=null==t?void 0:t.counter)&&void 0!==n?n:this._counter,this._keyToClassName=null!==(s=null!==(r=this._config.classNameCache)&&void 0!==r?r:null==t?void 0:t.keyToClassName)&&void 0!==s?s:this._keyToClassName,this._preservedRules=null!==(a=null==t?void 0:t.preservedRules)&&void 0!==a?a:this._preservedRules,this._rules=null!==(o=null==t?void 0:t.rules)&&void 0!==o?o:this._rules}return e.getInstance=function(t){if(UU=HU[BU],HU[DU])return HU[DU].getInstance(t);if(!UU||UU._lastStyleElement&&UU._lastStyleElement.ownerDocument!==document){var i=(null==HU?void 0:HU.FabricConfig)||{},n=new e(i.mergeStyles,i.serializedStylesheet);UU=n,HU[BU]=n}return UU},e.prototype.serialize=function(){return JSON.stringify({classNameToArgs:this._classNameToArgs,counter:this._counter,keyToClassName:this._keyToClassName,preservedRules:this._preservedRules,rules:this._rules})},e.prototype.setConfig=function(e){this._config=IU(IU({},this._config),e)},e.prototype.onReset=function(e){var t=this;return this._onResetCallbacks.push(e),function(){t._onResetCallbacks=t._onResetCallbacks.filter((function(t){return t!==e}))}},e.prototype.onInsertRule=function(e){var t=this;return this._onInsertRuleCallbacks.push(e),function(){t._onInsertRuleCallbacks=t._onInsertRuleCallbacks.filter((function(t){return t!==e}))}},e.prototype.getClassName=function(e){var t=this._config.namespace,i=e||this._config.defaultPrefix;return"".concat(t?t+"-":"").concat(i,"-").concat(this._counter++)},e.prototype.cacheClassName=function(e,t,i,n){this._keyToClassName[this._getCacheKey(t)]=e,this._classNameToArgs[e]={args:i,rules:n}},e.prototype.classNameFromKey=function(e){return this._keyToClassName[this._getCacheKey(e)]},e.prototype.getClassNameCache=function(){return this._keyToClassName},e.prototype.argsFromClassName=function(e){var t=this._classNameToArgs[e];return t&&t.args},e.prototype.insertedRulesFromClassName=function(e){var t=this._classNameToArgs[e];return t&&t.rules},e.prototype.insertRule=function(e,t,i){void 0===i&&(i=MU);var n=this._config.injectionMode,r=0!==n?this._getStyleElement():void 0;if(t&&this._preservedRules.push(e),r)switch(n){case 1:this._insertRuleIntoSheet(r.sheet,e);break;case 2:r.appendChild(document.createTextNode(e))}else this._rules.push(e);this._config.onInsertRule&&this._config.onInsertRule(e),this._onInsertRuleCallbacks.forEach((function(t){return t({key:i,sheet:r?r.sheet:void 0,rule:e})}))},e.prototype.getRules=function(e){return(e?this._preservedRules.join(""):"")+this._rules.join("")},e.prototype.reset=function(){this._rules=[],this._counter=0,this._classNameToArgs={},this._keyToClassName={},this._onResetCallbacks.forEach((function(e){return e()}))},e.prototype.resetKeys=function(){this._keyToClassName={}},e.prototype._createStyleElement=function(){var e,t=(null===(e=this._config.window)||void 0===e?void 0:e.document)||document,i=t.head,n=t.createElement("style"),r=null;n.setAttribute("data-merge-styles","true");var s=this._config.cspSettings;if(s&&s.nonce&&n.setAttribute("nonce",s.nonce),this._lastStyleElement)r=this._lastStyleElement.nextElementSibling;else{var a=this._findPlaceholderStyleTag();r=a?a.nextElementSibling:i.childNodes[0]}return i.insertBefore(n,i.contains(r)?r:null),this._lastStyleElement=n,n},e.prototype._insertRuleIntoSheet=function(e,t){if(!e)return!1;try{return e.insertRule(t,e.cssRules.length),!0}catch(e){}return!1},e.prototype._getCacheKey=function(e){return e},e.prototype._getStyleElement=function(){var e=this;return this._styleElement||(this._styleElement=this._createStyleElement(),VU||(this._config.window||window).requestAnimationFrame((function(){e._styleElement=void 0}))),this._styleElement},e.prototype._findPlaceholderStyleTag=function(){var e=document.head;return e?e.querySelector("style[data-merge-styles]"):null},e}(),GU={},qU={"user-select":1};function zU(e,t){var i=function(){var e;if(!$U){var t="undefined"!=typeof document?document:void 0,i="undefined"!=typeof navigator?navigator:void 0,n=null===(e=null==i?void 0:i.userAgent)||void 0===e?void 0:e.toLowerCase();$U=t?{isWebkit:!(!t||!("WebkitAppearance"in t.documentElement.style)),isMoz:!!(n&&n.indexOf("firefox")>-1),isOpera:!!(n&&n.indexOf("opera")>-1),isMs:!(!i||!/rv:11.0/i.test(i.userAgent)&&!/Edge\/\d./i.test(navigator.userAgent))}:{isWebkit:!0,isMoz:!0,isOpera:!0,isMs:!0}}return $U}(),n=e[t];if(qU[n]){var r=e[t+1];qU[n]&&(i.isWebkit&&e.push("-webkit-"+n,r),i.isMoz&&e.push("-moz-"+n,r),i.isMs&&e.push("-ms-"+n,r),i.isOpera&&e.push("-o-"+n,r))}}var WU,KU=["column-count","font-weight","flex","flex-grow","flex-shrink","fill-opacity","opacity","order","z-index","zoom"];function JU(e,t){var i=e[t],n=e[t+1];if("number"==typeof n){var r=KU.indexOf(i)>-1,s=i.indexOf("--")>-1,a=r||s?"":"px";e[t+1]="".concat(n).concat(a)}}var YU="left",QU="right",ZU=((WU={})[YU]=QU,WU[QU]=YU,WU),XU={"w-resize":"e-resize","sw-resize":"se-resize","nw-resize":"ne-resize"};function eB(e,t,i){if(e.rtl){var n=t[i];if(!n)return;var r=t[i+1];if("string"==typeof r&&r.indexOf("@noflip")>=0)t[i+1]=r.replace(/\s*(?:\/\*\s*)?\@noflip\b(?:\s*\*\/)?\s*?/g,"");else if(n.indexOf(YU)>=0)t[i]=n.replace(YU,QU);else if(n.indexOf(QU)>=0)t[i]=n.replace(QU,YU);else if(String(r).indexOf(YU)>=0)t[i+1]=r.replace(YU,QU);else if(String(r).indexOf(QU)>=0)t[i+1]=r.replace(QU,YU);else if(ZU[n])t[i]=ZU[n];else if(XU[r])t[i+1]=XU[r];else switch(n){case"margin":case"padding":t[i+1]=function(e){if("string"==typeof e){var t=e.split(" ");if(4===t.length)return"".concat(t[0]," ").concat(t[3]," ").concat(t[2]," ").concat(t[1])}return e}(r);break;case"box-shadow":t[i+1]=function(e){var t=e.split(" "),i=parseInt(t[0],10);return t[0]=t[0].replace(String(i),String(-1*i)),t.join(" ")}(r)}}}var tB=/\:global\((.+?)\)/g;function iB(e,t){return e.indexOf(":global(")>=0?e.replace(tB,"$1"):0===e.indexOf(":host(")?e:0===e.indexOf(":")?t+e:e.indexOf("&")<0?t+" "+e:e}function nB(e,t,i,n,r){void 0===t&&(t={__order:[]}),0===i.indexOf("@")?rB([n],t,i=i+"{"+e,r):i.indexOf(",")>-1?function(e){if(!tB.test(e))return e;for(var t=[],i=/\:global\((.+?)\)/g,n=null;n=i.exec(e);)n[1].indexOf(",")>-1&&t.push([n.index,n.index+n[0].length,n[1].split(",").map((function(e){return":global(".concat(e.trim(),")")})).join(", ")]);return t.reverse().reduce((function(e,t){var i=t[0],n=t[1],r=t[2];return e.slice(0,i)+r+e.slice(n)}),e)}(i).split(",").map((function(e){return e.trim()})).forEach((function(i){return rB([n],t,iB(i,e),r)})):rB([n],t,iB(i,e),r)}function rB(e,t,i,n){void 0===t&&(t={__order:[]}),void 0===i&&(i="&");var r,s=t[i];s||(s={},t[i]=s,t.__order.push(i));for(var a=0,o=e;a<o.length;a++){var l=o[a];if("string"==typeof l){var c=n.argsFromClassName(l);c&&rB(c,t,i,n)}else if(Array.isArray(l))rB(l,t,i,n);else for(var d in l)if(l.hasOwnProperty(d)){var u=l[d];if("selectors"===d){var h=l.selectors;for(var g in h)h.hasOwnProperty(g)&&nB(i,t,g,h[g],n)}else"object"==typeof u||(r=d).indexOf(":global(")>=0||0===r.indexOf(":")?null!=u&&nB(i,t,d,u,n):void 0!==u&&("margin"===d||"padding"===d?sB(s,d,u):s[d]=u)}}return t}function sB(e,t,i){var n="string"==typeof i?function(e){for(var t=[],i=0,n=0,r=0;r<e.length;r++)switch(e[r]){case"(":n++;break;case")":n&&n--;break;case"\t":case" ":n||(r>i&&t.push(e.substring(i,r)),i=r+1)}return i<e.length&&t.push(e.substring(i)),t}(i):[i];0===n.length&&n.push(i),"!important"===n[n.length-1]&&(n=n.slice(0,-1).map((function(e){return e+" !important"}))),e[t+"Top"]=n[0],e[t+"Right"]=n[1]||n[0],e[t+"Bottom"]=n[2]||n[0],e[t+"Left"]=n[3]||n[1]||n[0]}function aB(e,t){return t<=0?"":1===t?e:e+aB(e,t-1)}function oB(e,t){if(!t)return"";var i,n,r,s=[];for(var a in t)t.hasOwnProperty(a)&&"displayName"!==a&&void 0!==t[a]&&s.push(a,t[a]);for(var o=0;o<s.length;o+=2)r=void 0,"-"!==(r=(i=s)[n=o]).charAt(0)&&(i[n]=GU[r]=GU[r]||r.replace(/([A-Z])/g,"-$1").toLowerCase()),JU(s,o),eB(e,s,o),zU(s,o);for(o=1;o<s.length;o+=4)s.splice(o,1,":",s[o],";");return s.join("")}function lB(e){for(var t,i=[],n=1;n<arguments.length;n++)i[n-1]=arguments[n];var r=null!==(t=e.stylesheet)&&void 0!==t?t:jU.getInstance(e.shadowConfig),s=rB(i,void 0,void 0,r),a=function(e,t){for(var i=[e.rtl?"rtl":"ltr"],n=!1,r=0,s=t.__order;r<s.length;r++){var a=s[r];i.push(a);var o=t[a];for(var l in o)o.hasOwnProperty(l)&&void 0!==o[l]&&(n=!0,i.push(l,o[l]))}return n?i.join(""):void 0}(e,s);if(a){var o={className:r.classNameFromKey(a),key:a,args:i};if(!o.className){o.className=r.getClassName(function(e){var t=e&&e["&"];return t?t.displayName:void 0}(s));for(var l=[],c=0,d=s.__order;c<d.length;c++){var u=d[c];l.push(u,oB(e,s[u]))}o.rulesToInsert=l}return o}}function cB(e,t,i,n){void 0===t&&(t=1);var r=null!=n?n:jU.getInstance(i),s=e.className,a=e.key,o=e.args,l=e.rulesToInsert;if(l){for(var c=0;c<l.length;c+=2){var d=l[c+1];if(d){var u=l[c];u=u.replace(/&/g,aB(".".concat(e.className),t));var h="".concat(u,"{").concat(d,"}").concat(0===u.indexOf("@")?"}":"");r.insertRule(h)}}r.cacheClassName(s,a,o,l)}}function dB(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return uB(e,FU())}function uB(e,t){var i=e instanceof Array?e:[e],n=t||{};OU(i[0])&&(n.shadowConfig=i[0]),n.stylesheet=jU.getInstance(n.shadowConfig);var r=NU(n.stylesheet,i),s=r.classes,a=r.objects;return a.length&&s.push(function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=lB.apply(void 0,PU([e],t,!1));return n?(cB(n,e.specificityMultiplier,e.shadowConfig,e.stylesheet),n.className):""}(n,a)),s.join(" ")}var hB=!1,gB=0,pB={empty:!0},mB={},fB="undefined"==typeof WeakMap?null:WeakMap;function vB(){gB++}function SB(e,t,i){if(void 0===t&&(t=100),void 0===i&&(i=!1),!fB)return e;if(!hB){var n=jU.getInstance();n&&n.onReset&&jU.getInstance().onReset(vB),hB=!0}var r,s=0,a=gB;return function(){for(var n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var l,c=r;(void 0===r||a!==gB||t>0&&s>t)&&(r=CB(),s=0,a=gB),c=r;for(var d=0;d<n.length;d++){var u=(l=n[d])?"object"==typeof l||"function"==typeof l?l:(mB[l]||(mB[l]={val:l}),mB[l]):pB;c.map.has(u)||c.map.set(u,CB()),c=c.map.get(u)}return c.hasOwnProperty("value")||(c.value=e.apply(void 0,n),s++),!i||null!==c.value&&void 0!==c.value||(c.value=e.apply(void 0,n)),c.value}}function yB(e){if(!fB)return e;var t=new fB;return function(i){if(!i||"function"!=typeof i&&"object"!=typeof i)return e(i);if(t.has(i))return t.get(i);var n=e(i);return t.set(i,n),n}}function CB(){return{map:fB?new fB:null}}function TB(){return"undefined"!=typeof window&&!(!window.document||!window.document.createElement)}function EB(e){if(TB()&&"undefined"!=typeof document){var t=e;return t&&t.ownerDocument?t.ownerDocument:document}}var bB=void 0;try{bB=window}catch(e){}function _B(e){if(TB()&&void 0!==bB){var t=e;return t&&t.ownerDocument&&t.ownerDocument.defaultView?t.ownerDocument.defaultView:bB}}function IB(e){var t=null;try{var i=_B();t=i?i.sessionStorage.getItem(e):null}catch(e){}return t}var wB,AB="isRTL";function PB(e){if(void 0===e&&(e={}),void 0!==e.rtl)return e.rtl;if(void 0===wB){var t=IB(AB);null!==t&&function(e,t){void 0===t&&(t=!1);var i=EB();i&&i.documentElement.setAttribute("dir",e?"rtl":"ltr"),t&&function(e,t){var i;try{null===(i=_B())||void 0===i||i.sessionStorage.setItem(e,t)}catch(e){}}(AB,e?"1":"0"),LU(wB=e)}(wB="1"===t);var i=EB();void 0===wB&&i&&LU(wB="rtl"===(i.body&&i.body.getAttribute("dir")||i.documentElement.getAttribute("dir")))}return!!wB}var RB=IU;function MB(i,n){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];var a=i;return a.isSlot?0===(r=e.Children.toArray(r)).length?a(n):a(IU(IU({},n),{children:r})):e.createElement.apply(t,PU([i,n],r,!1))}function DB(t,i){void 0===i&&(i={});var n=i.defaultProp,r=void 0===n?"children":n;return function(i,n,s,a,o){if(e.isValidElement(n))return n;var l=function(e,t){var i,n;return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?((i={})[e]=t,n=i):n=t,n}(r,n),c=function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];for(var r={},s=[],a=0,o=i;a<o.length;a++){var l=o[a];s.push(l&&l.className),RB(r,l)}return r.className=uB([e,s],{rtl:PB(t)}),r}(a,o,i,l);if(s){if(s.component){var d=s.component;return e.createElement(d,IU({},c))}if(s.render)return s.render(c,t)}return e.createElement(t,IU({},c))}}var kB=SB((function(e){return DB(e)}));function OB(e,t){var i={},n=e,r=function(e){if(t.hasOwnProperty(e)){var r=function(i){for(var r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];if(r.length>0)throw new Error("Any module using getSlots must use withSlots. Please see withSlots javadoc for more info.");return function(e,t,i,n,r,s){return void 0!==e.create?e.create(t,i,n,r):kB(e)(t,i,n,r,s)}(t[e],i,n[e],n.slots&&n.slots[e],n._defaultStyles&&n._defaultStyles[e],n.theme)};r.isSlot=!0,i[e]=r}};for(var s in t)r(s);return i}function NB(e){var t=jU.getInstance(),i=[];for(var n in e)e.hasOwnProperty(n)&&i.push(n,"{",oB(FU(),e[n]),"}");var r=i.join(""),s=t.classNameFromKey(r);if(s)return s;var a=t.getClassName();return t.insertRule("@keyframes ".concat(a,"{").concat(r,"}"),!0),t.cacheClassName(a,r,[],["keyframes",r]),a}var LB="cubic-bezier(.1,.9,.2,1)",xB="cubic-bezier(.1,.25,.75,.9)",FB="0.167s",UB="0.267s",BB="0.367s",VB="0.467s",HB=NB({from:{opacity:0},to:{opacity:1}}),$B=NB({from:{opacity:1},to:{opacity:0,visibility:"hidden"}}),jB=_V(-10),GB=_V(-20),qB=_V(-40),zB=_V(-400),WB=_V(10),KB=_V(20),JB=_V(40),YB=_V(400),QB=IV(10),ZB=IV(20),XB=IV(-10),eV=IV(-20),tV=wV(10),iV=wV(20),nV=wV(40),rV=wV(400),sV=wV(-10),aV=wV(-20),oV=wV(-40),lV=wV(-400),cV=AV(-10),dV=AV(-20),uV=AV(10),hV=AV(20),gV=NB({from:{transform:"scale3d(.98,.98,1)"},to:{transform:"scale3d(1,1,1)"}}),pV=NB({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(.98,.98,1)"}}),mV=NB({from:{transform:"scale3d(1.03,1.03,1)"},to:{transform:"scale3d(1,1,1)"}}),fV=NB({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(1.03,1.03,1)"}}),vV=NB({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(90deg)"}}),SV=NB({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(-90deg)"}}),yV=xB,CV=UB,TV=BB,EV={slideRightIn10:bV("".concat(HB,",").concat(jB),BB,LB),slideRightIn20:bV("".concat(HB,",").concat(GB),BB,LB),slideRightIn40:bV("".concat(HB,",").concat(qB),BB,LB),slideRightIn400:bV("".concat(HB,",").concat(zB),BB,LB),slideLeftIn10:bV("".concat(HB,",").concat(WB),BB,LB),slideLeftIn20:bV("".concat(HB,",").concat(KB),BB,LB),slideLeftIn40:bV("".concat(HB,",").concat(JB),BB,LB),slideLeftIn400:bV("".concat(HB,",").concat(YB),BB,LB),slideUpIn10:bV("".concat(HB,",").concat(QB),BB,LB),slideUpIn20:bV("".concat(HB,",").concat(ZB),BB,LB),slideDownIn10:bV("".concat(HB,",").concat(XB),BB,LB),slideDownIn20:bV("".concat(HB,",").concat(eV),BB,LB),slideRightOut10:bV("".concat($B,",").concat(tV),BB,LB),slideRightOut20:bV("".concat($B,",").concat(iV),BB,LB),slideRightOut40:bV("".concat($B,",").concat(nV),BB,LB),slideRightOut400:bV("".concat($B,",").concat(rV),BB,LB),slideLeftOut10:bV("".concat($B,",").concat(sV),BB,LB),slideLeftOut20:bV("".concat($B,",").concat(aV),BB,LB),slideLeftOut40:bV("".concat($B,",").concat(oV),BB,LB),slideLeftOut400:bV("".concat($B,",").concat(lV),BB,LB),slideUpOut10:bV("".concat($B,",").concat(cV),BB,LB),slideUpOut20:bV("".concat($B,",").concat(dV),BB,LB),slideDownOut10:bV("".concat($B,",").concat(uV),BB,LB),slideDownOut20:bV("".concat($B,",").concat(hV),BB,LB),scaleUpIn100:bV("".concat(HB,",").concat(gV),BB,LB),scaleDownIn100:bV("".concat(HB,",").concat(mV),BB,LB),scaleUpOut103:bV("".concat($B,",").concat(fV),FB,xB),scaleDownOut98:bV("".concat($B,",").concat(pV),FB,xB),fadeIn100:bV(HB,FB,xB),fadeIn200:bV(HB,UB,xB),fadeIn400:bV(HB,BB,xB),fadeIn500:bV(HB,VB,xB),fadeOut100:bV($B,FB,xB),fadeOut200:bV($B,UB,xB),fadeOut400:bV($B,BB,xB),fadeOut500:bV($B,VB,xB),rotate90deg:bV(vV,"0.1s",xB),rotateN90deg:bV(SV,"0.1s",xB)};function bV(e,t,i){return{animationName:e,animationDuration:t,animationTimingFunction:i,animationFillMode:"both"}}function _V(e){return NB({from:{transform:"translate3d(".concat(e,"px,0,0)"),pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function IV(e){return NB({from:{transform:"translate3d(0,".concat(e,"px,0)"),pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function wV(e){return NB({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d(".concat(e,"px,0,0)")}})}function AV(e){return NB({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d(0,".concat(e,"px,0)")}})}var PV,RV,MV,DV,kV,OV=function(e){var t={},i=function(i){var n;e.hasOwnProperty(i)&&Object.defineProperty(t,i,{get:function(){return void 0===n&&(n=dB(e[i]).toString()),n},enumerable:!0,configurable:!0})};for(var n in e)i(n);return t}(EV),NV={themeDarker:"#004578",themeDark:"#005a9e",themeDarkAlt:"#106ebe",themePrimary:"#0078d4",themeSecondary:"#2b88d8",themeTertiary:"#71afe5",themeLight:"#c7e0f4",themeLighter:"#deecf9",themeLighterAlt:"#eff6fc",black:"#000000",blackTranslucent40:"rgba(0,0,0,.4)",neutralDark:"#201f1e",neutralPrimary:"#323130",neutralPrimaryAlt:"#3b3a39",neutralSecondary:"#605e5c",neutralSecondaryAlt:"#8a8886",neutralTertiary:"#a19f9d",neutralTertiaryAlt:"#c8c6c4",neutralQuaternary:"#d2d0ce",neutralQuaternaryAlt:"#e1dfdd",neutralLight:"#edebe9",neutralLighter:"#f3f2f1",neutralLighterAlt:"#faf9f8",accent:"#0078d4",white:"#ffffff",whiteTranslucent40:"rgba(255,255,255,.4)",yellowDark:"#d29200",yellow:"#ffb900",yellowLight:"#fff100",orange:"#d83b01",orangeLight:"#ea4300",orangeLighter:"#ff8c00",redDark:"#a4262c",red:"#e81123",magentaDark:"#5c005c",magenta:"#b4009e",magentaLight:"#e3008c",purpleDark:"#32145a",purple:"#5c2d91",purpleLight:"#b4a0ff",blueDark:"#002050",blueMid:"#00188f",blue:"#0078d4",blueLight:"#00bcf2",tealDark:"#004b50",teal:"#008272",tealLight:"#00b294",greenDark:"#004b1c",green:"#107c10",greenLight:"#bad80a"};!function(e){e.Arabic="Segoe UI Web (Arabic)",e.Cyrillic="Segoe UI Web (Cyrillic)",e.EastEuropean="Segoe UI Web (East European)",e.Greek="Segoe UI Web (Greek)",e.Hebrew="Segoe UI Web (Hebrew)",e.Thai="Leelawadee UI Web",e.Vietnamese="Segoe UI Web (Vietnamese)",e.WestEuropean="Segoe UI Web (West European)",e.Selawik="Selawik Web",e.Armenian="Segoe UI Web (Armenian)",e.Georgian="Segoe UI Web (Georgian)"}(PV||(PV={})),function(e){e.Arabic="'".concat(PV.Arabic,"'"),e.ChineseSimplified="'Microsoft Yahei UI', Verdana, Simsun",e.ChineseTraditional="'Microsoft Jhenghei UI', Pmingliu",e.Cyrillic="'".concat(PV.Cyrillic,"'"),e.EastEuropean="'".concat(PV.EastEuropean,"'"),e.Greek="'".concat(PV.Greek,"'"),e.Hebrew="'".concat(PV.Hebrew,"'"),e.Hindi="'Nirmala UI'",e.Japanese="'Yu Gothic UI', 'Meiryo UI', Meiryo, 'MS Pgothic', Osaka",e.Korean="'Malgun Gothic', Gulim",e.Selawik="'".concat(PV.Selawik,"'"),e.Thai="'Leelawadee UI Web', 'Kmer UI'",e.Vietnamese="'".concat(PV.Vietnamese,"'"),e.WestEuropean="'".concat(PV.WestEuropean,"'"),e.Armenian="'".concat(PV.Armenian,"'"),e.Georgian="'".concat(PV.Georgian,"'")}(RV||(RV={})),function(e){e.size10="10px",e.size12="12px",e.size14="14px",e.size16="16px",e.size18="18px",e.size20="20px",e.size24="24px",e.size28="28px",e.size32="32px",e.size42="42px",e.size68="68px",e.mini="10px",e.xSmall="10px",e.small="12px",e.smallPlus="12px",e.medium="14px",e.mediumPlus="16px",e.icon="16px",e.large="18px",e.xLarge="20px",e.xLargePlus="24px",e.xxLarge="28px",e.xxLargePlus="32px",e.superLarge="42px",e.mega="68px"}(MV||(MV={})),function(e){e.light=100,e.semilight=300,e.regular=400,e.semibold=600,e.bold=700}(DV||(DV={})),function(e){e.xSmall="10px",e.small="12px",e.medium="16px",e.large="20px"}(kV||(kV={}));var LV={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",whiteSpace:"nowrap"},xV=SB((function(e,t){var i=jU.getInstance();return t?Object.keys(e).reduce((function(t,n){return t[n]=i.getClassName(e[n]),t}),{}):e}));function FV(e,t,i){return xV(e,void 0!==i?i:t.disableGlobalClassNames)}var UV="@media screen and (-ms-high-contrast: active), screen and (forced-colors: active)",BV="@media screen and (-ms-high-contrast: black-on-white), screen and (forced-colors: active) and (prefers-color-scheme: light)",VV=480,HV=1366;function $V(e,t){var i="number"==typeof e?" and (min-width: ".concat(e,"px)"):"",n="number"==typeof t?" and (max-width: ".concat(t,"px)"):"";return"@media only screen".concat(i).concat(n)}var jV,GV="ms-Fabric--isFocusVisible",qV="ms-Fabric--isFocusHidden";function zV(e,t){e&&(e.classList.add(t?GV:qV),e.classList.remove(t?qV:GV))}function WV(e,t,i){var n;i?i.forEach((function(t){return zV(t.current,e)})):zV(null===(n=_B(t))||void 0===n?void 0:n.document.body,e)}function KV(e,t,i,n,r,s,a,o){return function(e,t){var i,n;void 0===t&&(t={});var r=t.borderRadius,s=t.inset,a=void 0===s?0:s,o=t.width,l=void 0===o?1:o,c=t.position,d=void 0===c?"relative":c,u=t.highContrastStyle,h=t.borderColor,g=void 0===h?e.palette.white:h,p=t.outlineColor,m=void 0===p?e.palette.neutralSecondary:p,f=t.isFocusedOnly,v=void 0===f||f,S=t.pointerEvents;return{outline:"transparent",position:d,selectors:(i={"::-moz-focus-inner":{border:"0"}},i[".".concat(GV," &").concat(v?":focus":"",":after, :host(.").concat(GV,") &").concat(v?":focus":"",":after")]={content:'""',position:"absolute",pointerEvents:S,left:a+1,top:a+1,bottom:a+1,right:a+1,border:"".concat(l,"px solid ").concat(g),outline:"".concat(l,"px solid ").concat(m),zIndex:jV.FocusStyle,borderRadius:r,selectors:(n={},n[UV]=u,n)},i)}}(e,"number"!=typeof t&&t?t:{inset:t,position:i,highContrastStyle:n,borderColor:r,outlineColor:s,isFocusedOnly:a,borderRadius:o})}!function(e){e.Nav=1,e.ScrollablePane=1,e.FocusStyle=1,e.Coachmark=1e3,e.Layer=1e6,e.KeytipLayer=1000001}(jV||(jV={}));var JV=function(e,t,i,n){var r,s,a;void 0===i&&(i="border"),void 0===n&&(n=-1);var o="borderBottom"===i;return{borderColor:e,selectors:{":after":(r={pointerEvents:"none",content:"''",position:"absolute",left:o?0:n,top:n,bottom:n,right:o?0:n},r[i]="2px solid ".concat(e),r.borderRadius=t,r.width="borderBottom"===i?"100%":void 0,r.selectors=(s={},s[UV]=(a={},a["border"===i?"borderColor":"borderBottomColor"]="Highlight",a),s),r)}}},YV="__globalSettings__",QV="__callbacks__",ZV=0,XV=function(){function e(){}return e.getValue=function(e,t){var i=eH();return void 0===i[e]&&(i[e]="function"==typeof t?t():t),i[e]},e.setValue=function(e,t){var i=eH(),n=i[QV],r=i[e];if(t!==r){i[e]=t;var s={oldValue:r,value:t,key:e};for(var a in n)n.hasOwnProperty(a)&&n[a](s)}return t},e.addChangeListener=function(e){var t=e.__id__,i=tH();t||(t=e.__id__=String(ZV++)),i[t]=e},e.removeChangeListener=function(e){delete tH()[e.__id__]},e}();function eH(){var e,t=_B()||{};return t[YV]||(t[YV]=((e={})[QV]={},e)),t[YV]}function tH(){return eH()[QV]}var iH,nH,rH={settings:{},scopedSettings:{},inCustomizerContext:!1},sH=XV.getValue("customizations",{settings:{},scopedSettings:{},inCustomizerContext:!1}),aH=[],oH=function(){function e(){}return e.reset=function(){sH.settings={},sH.scopedSettings={}},e.applySettings=function(t){sH.settings=IU(IU({},sH.settings),t),e._raiseChange()},e.applyScopedSettings=function(t,i){sH.scopedSettings[t]=IU(IU({},sH.scopedSettings[t]),i),e._raiseChange()},e.getSettings=function(e,t,i){void 0===i&&(i=rH);for(var n={},r=t&&i.scopedSettings[t]||{},s=t&&sH.scopedSettings[t]||{},a=0,o=e;a<o.length;a++){var l=o[a];n[l]=r[l]||i.settings[l]||s[l]||sH.settings[l]}return n},e.applyBatchedUpdates=function(t,i){e._suppressUpdates=!0;try{t()}catch(e){}e._suppressUpdates=!1,i||e._raiseChange()},e.observe=function(e){aH.push(e)},e.unobserve=function(e){aH=aH.filter((function(t){return t!==e}))},e._raiseChange=function(){e._suppressUpdates||aH.forEach((function(e){return e()}))},e}(),lH=function(){return lH=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},lH.apply(this,arguments)},cH="undefined"==typeof window?r.g:window,dH=cH&&cH.CSPSettings&&cH.CSPSettings.nonce,uH=((nH=cH.__themeState__||{theme:void 0,lastStyleElement:void 0,registeredStyles:[]}).runState||(nH=lH(lH({},nH),{perf:{count:0,duration:0},runState:{flushTimer:0,mode:0,buffer:[]}})),nH.registeredThemableStyles||(nH=lH(lH({},nH),{registeredThemableStyles:[]})),cH.__themeState__=nH,nH);function hH(e){uH.theme=e,function(){if(uH.theme){for(var e=[],t=0,i=uH.registeredThemableStyles;t<i.length;t++){var n=i[t];e.push(n.themableStyle)}e.length>0&&(void 0===(s=1)&&(s=3),3!==s&&2!==s||(gH(uH.registeredStyles),uH.registeredStyles=[]),3!==s&&1!==s||(gH(uH.registeredThemableStyles),uH.registeredThemableStyles=[]),r=[].concat.apply([],e),uH.loadStyles?uH.loadStyles(pH(r).styleString,r):function(e){if("undefined"!=typeof document){var t=document.getElementsByTagName("head")[0],i=document.createElement("style"),n=pH(e),r=n.styleString,s=n.themable;i.setAttribute("data-load-themed-styles","true"),dH&&i.setAttribute("nonce",dH),i.appendChild(document.createTextNode(r)),uH.perf.count++,t.appendChild(i);var a=document.createEvent("HTMLEvents");a.initEvent("styleinsert",!0,!1),a.args={newStyle:i},document.dispatchEvent(a);var o={styleElement:i,themableStyle:e};s?uH.registeredThemableStyles.push(o):uH.registeredStyles.push(o)}}(r))}var r,s}()}function gH(e){e.forEach((function(e){var t=e&&e.styleElement;t&&t.parentElement&&t.parentElement.removeChild(t)}))}function pH(e){var t=uH.theme,i=!1;return{styleString:(e||[]).map((function(e){var n=e.theme;if(n){i=!0;var r=t?t[n]:void 0,s=e.defaultValue||"inherit";return t&&!r&&console&&!(n in t)&&"undefined"!=typeof DEBUG&&DEBUG&&console.warn('Theming value not provided for "'.concat(n,'". Falling back to "').concat(s,'".')),r||s}return e.rawString})).join(""),themable:i}}!function(e){e.depth0="0 0 0 0 transparent",e.depth4="0 1.6px 3.6px 0 rgba(0, 0, 0, 0.132), 0 0.3px 0.9px 0 rgba(0, 0, 0, 0.108)",e.depth8="0 3.2px 7.2px 0 rgba(0, 0, 0, 0.132), 0 0.6px 1.8px 0 rgba(0, 0, 0, 0.108)",e.depth16="0 6.4px 14.4px 0 rgba(0, 0, 0, 0.132), 0 1.2px 3.6px 0 rgba(0, 0, 0, 0.108)",e.depth64="0 25.6px 57.6px 0 rgba(0, 0, 0, 0.22), 0 4.8px 14.4px 0 rgba(0, 0, 0, 0.18)"}(iH||(iH={}));var mH={elevation4:iH.depth4,elevation8:iH.depth8,elevation16:iH.depth16,elevation64:iH.depth64,roundedCorner2:"2px",roundedCorner4:"4px",roundedCorner6:"6px"};function fH(e){var t=jU.getInstance(),i=oB(FU(),e);if(!t.classNameFromKey(i)){var n=t.getClassName();t.insertRule("@font-face{".concat(i,"}"),!0),t.cacheClassName(n,i,[],["font-face",i])}}var vH,SH="'Segoe UI', '".concat(PV.WestEuropean,"'"),yH={ar:RV.Arabic,bg:RV.Cyrillic,cs:RV.EastEuropean,el:RV.Greek,et:RV.EastEuropean,he:RV.Hebrew,hi:RV.Hindi,hr:RV.EastEuropean,hu:RV.EastEuropean,ja:RV.Japanese,kk:RV.EastEuropean,ko:RV.Korean,lt:RV.EastEuropean,lv:RV.EastEuropean,pl:RV.EastEuropean,ru:RV.Cyrillic,sk:RV.EastEuropean,"sr-latn":RV.EastEuropean,th:RV.Thai,tr:RV.EastEuropean,uk:RV.Cyrillic,vi:RV.Vietnamese,"zh-hans":RV.ChineseSimplified,"zh-hant":RV.ChineseTraditional,hy:RV.Armenian,ka:RV.Georgian};function CH(e,t,i){return{fontFamily:i,MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontSize:e,fontWeight:t}}var TH,EH,bH,_H="language",IH=(TH=function(e){if(void 0===e&&(e="sessionStorage"),void 0===vH){var t=EB(),i="localStorage"===e?function(e){var t=null;try{var i=_B();t=i?i.localStorage.getItem(e):null}catch(e){}return t}(_H):"sessionStorage"===e?IB(_H):void 0;i&&(vH=i),void 0===vH&&t&&(vH=t.documentElement.getAttribute("lang")),void 0===vH&&(vH="en")}return vH}(),EH=function(e){for(var t in yH)if(yH.hasOwnProperty(t)&&e&&0===t.indexOf(e))return yH[t];return SH}(TH),bH="".concat(EH,", ").concat("'Segoe UI', -apple-system, BlinkMacSystemFont, 'Roboto', 'Helvetica Neue', sans-serif"),{tiny:CH(MV.mini,DV.regular,bH),xSmall:CH(MV.xSmall,DV.regular,bH),small:CH(MV.small,DV.regular,bH),smallPlus:CH(MV.smallPlus,DV.regular,bH),medium:CH(MV.medium,DV.regular,bH),mediumPlus:CH(MV.mediumPlus,DV.regular,bH),large:CH(MV.large,DV.regular,bH),xLarge:CH(MV.xLarge,DV.semibold,bH),xLargePlus:CH(MV.xLargePlus,DV.semibold,bH),xxLarge:CH(MV.xxLarge,DV.semibold,bH),xxLargePlus:CH(MV.xxLargePlus,DV.semibold,bH),superLarge:CH(MV.superLarge,DV.semibold,bH),mega:CH(MV.mega,DV.semibold,bH)});function wH(e,t,i,n){fH({fontFamily:e="'".concat(e,"'"),src:(void 0!==n?"local('".concat(n,"'),"):"")+"url('".concat(t,".woff2') format('woff2'),")+"url('".concat(t,".woff') format('woff')"),fontWeight:i,fontStyle:"normal",fontDisplay:"swap"})}function AH(e,t,i,n,r){void 0===n&&(n="segoeui");var s="".concat(e,"/").concat(i,"/").concat(n);wH(t,s+"-light",DV.light,r&&r+" Light"),wH(t,s+"-semilight",DV.semilight,r&&r+" SemiLight"),wH(t,s+"-regular",DV.regular,r),wH(t,s+"-semibold",DV.semibold,r&&r+" SemiBold"),wH(t,s+"-bold",DV.bold,r&&r+" Bold")}function PH(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=0,r=t;n<r.length;n++)RH(e||{},r[n]);return e}function RH(e,t,i){for(var n in void 0===i&&(i=[]),i.push(t),t)if(t.hasOwnProperty(n)&&"__proto__"!==n&&"constructor"!==n&&"prototype"!==n){var r=t[n];if("object"!=typeof r||null===r||Array.isArray(r))e[n]=r;else{var s=i.indexOf(r)>-1;e[n]=s?r:RH(e[n]||{},r,i)}}return i.pop(),e}function MH(e,t,i,n,r){return void 0===r&&(r=!1),function(e,t){var i="";return!0===t&&(i=" /* @deprecated */"),e.listTextColor=e.listText+i,e.menuItemBackgroundChecked+=i,e.warningHighlight+=i,e.warningText=e.messageText+i,e.successText+=i,e}(DH(e,t,IU({primaryButtonBorder:"transparent",errorText:n?"#F1707B":"#a4262c",messageText:n?"#F3F2F1":"#323130",messageLink:n?"#6CB8F6":"#005A9E",messageLinkHovered:n?"#82C7FF":"#004578",infoIcon:n?"#C8C6C4":"#605e5c",errorIcon:n?"#F1707B":"#A80000",blockingIcon:n?"#442726":"#FDE7E9",warningIcon:n?"#C8C6C4":"#797775",severeWarningIcon:n?"#FCE100":"#D83B01",successIcon:n?"#92C353":"#107C10",infoBackground:n?"#323130":"#f3f2f1",errorBackground:n?"#442726":"#FDE7E9",blockingBackground:n?"#442726":"#FDE7E9",warningBackground:n?"#433519":"#FFF4CE",severeWarningBackground:n?"#4F2A0F":"#FED9CC",successBackground:n?"#393D1B":"#DFF6DD",warningHighlight:n?"#fff100":"#ffb900",successText:n?"#92c353":"#107C10"},i),n),r)}function DH(e,t,i,n,r){void 0===r&&(r=!1);var s={},a=e||{},o=a.white,l=a.black,c=a.themePrimary,d=a.themeDark,u=a.themeDarker,h=a.themeDarkAlt,g=a.themeLighter,p=a.neutralLight,m=a.neutralLighter,f=a.neutralDark,v=a.neutralQuaternary,S=a.neutralQuaternaryAlt,y=a.neutralPrimary,C=a.neutralSecondary,T=a.neutralSecondaryAlt,E=a.neutralTertiary,b=a.neutralTertiaryAlt,_=a.neutralLighterAlt,I=a.accent;return o&&(s.bodyBackground=o,s.bodyFrameBackground=o,s.accentButtonText=o,s.buttonBackground=o,s.primaryButtonText=o,s.primaryButtonTextHovered=o,s.primaryButtonTextPressed=o,s.inputBackground=o,s.inputForegroundChecked=o,s.listBackground=o,s.menuBackground=o,s.cardStandoutBackground=o),l&&(s.bodyTextChecked=l,s.buttonTextCheckedHovered=l),c&&(s.link=c,s.primaryButtonBackground=c,s.inputBackgroundChecked=c,s.inputIcon=c,s.inputFocusBorderAlt=c,s.menuIcon=c,s.menuHeader=c,s.accentButtonBackground=c),d&&(s.primaryButtonBackgroundPressed=d,s.inputBackgroundCheckedHovered=d,s.inputIconHovered=d),u&&(s.linkHovered=u),h&&(s.primaryButtonBackgroundHovered=h),g&&(s.inputPlaceholderBackgroundChecked=g),p&&(s.bodyBackgroundChecked=p,s.bodyFrameDivider=p,s.bodyDivider=p,s.variantBorder=p,s.buttonBackgroundCheckedHovered=p,s.buttonBackgroundPressed=p,s.listItemBackgroundChecked=p,s.listHeaderBackgroundPressed=p,s.menuItemBackgroundPressed=p,s.menuItemBackgroundChecked=p),m&&(s.bodyBackgroundHovered=m,s.buttonBackgroundHovered=m,s.buttonBackgroundDisabled=m,s.buttonBorderDisabled=m,s.primaryButtonBackgroundDisabled=m,s.disabledBackground=m,s.listItemBackgroundHovered=m,s.listHeaderBackgroundHovered=m,s.menuItemBackgroundHovered=m),v&&(s.primaryButtonTextDisabled=v,s.disabledSubtext=v),S&&(s.listItemBackgroundCheckedHovered=S),E&&(s.disabledBodyText=E,s.variantBorderHovered=(null==i?void 0:i.variantBorderHovered)||E,s.buttonTextDisabled=E,s.inputIconDisabled=E,s.disabledText=E),y&&(s.bodyText=y,s.actionLink=y,s.buttonText=y,s.inputBorderHovered=y,s.inputText=y,s.listText=y,s.menuItemText=y),_&&(s.bodyStandoutBackground=_,s.defaultStateBackground=_),f&&(s.actionLinkHovered=f,s.buttonTextHovered=f,s.buttonTextChecked=f,s.buttonTextPressed=f,s.inputTextHovered=f,s.menuItemTextHovered=f),C&&(s.bodySubtext=C,s.focusBorder=C,s.inputBorder=C,s.smallInputBorder=C,s.inputPlaceholderText=C),T&&(s.buttonBorder=T),b&&(s.disabledBodySubtext=b,s.disabledBorder=b,s.buttonBackgroundChecked=b,s.menuDivider=b),I&&(s.accentButtonBackground=I),(null==t?void 0:t.elevation4)&&(s.cardShadow=t.elevation4),!n&&(null==t?void 0:t.elevation8)?s.cardShadowHovered=t.elevation8:s.variantBorderHovered&&(s.cardShadowHovered="0 0 1px "+s.variantBorderHovered),IU(IU({},s),i)}function kH(e,t){var i,n,r;void 0===t&&(t={});var s=PH({},e,t,{semanticColors:DH(t.palette,t.effects,t.semanticColors,void 0===t.isInverted?e.isInverted:t.isInverted)});if((null===(i=t.palette)||void 0===i?void 0:i.themePrimary)&&!(null===(n=t.palette)||void 0===n?void 0:n.accent)&&(s.palette.accent=t.palette.themePrimary),t.defaultFontStyle)for(var a=0,o=Object.keys(s.fonts);a<o.length;a++){var l=o[a];s.fonts[l]=PH(s.fonts[l],t.defaultFontStyle,null===(r=null==t?void 0:t.fonts)||void 0===r?void 0:r[l])}return s}!function(e){if(e){var t="".concat(e,"/fonts");AH(t,PV.Thai,"leelawadeeui-thai","leelawadeeui"),AH(t,PV.Arabic,"segoeui-arabic"),AH(t,PV.Cyrillic,"segoeui-cyrillic"),AH(t,PV.EastEuropean,"segoeui-easteuropean"),AH(t,PV.Greek,"segoeui-greek"),AH(t,PV.Hebrew,"segoeui-hebrew"),AH(t,PV.Vietnamese,"segoeui-vietnamese"),AH(t,PV.WestEuropean,"segoeui-westeuropean","segoeui","Segoe UI"),AH(t,RV.Selawik,"selawik","selawik"),AH(t,PV.Armenian,"segoeui-armenian"),AH(t,PV.Georgian,"segoeui-georgian"),wH("Leelawadee UI Web","".concat(t,"/leelawadeeui-thai/leelawadeeui-semilight"),DV.light),wH("Leelawadee UI Web","".concat(t,"/leelawadeeui-thai/leelawadeeui-bold"),DV.semibold)}}(function(){var e,t,i=null===(e=_B())||void 0===e?void 0:e.FabricConfig;return null!==(t=null==i?void 0:i.fontBaseUrl)&&void 0!==t?t:"https://res-1.cdn.office.net/files/fabric-cdn-prod_20230815.002/assets"}());var OH={s2:"4px",s1:"8px",m:"16px",l1:"20px",l2:"32px"};function NH(e,t){void 0===e&&(e={}),void 0===t&&(t=!1);var i=!!e.isInverted;return kH({palette:NV,effects:mH,fonts:IH,spacing:OH,isInverted:i,disableGlobalClassNames:!1,semanticColors:MH(NV,mH,void 0,i,t),rtl:void 0},e)}var LH=NH({}),xH=[],FH="theme";function UH(){var e,t,i,n=_B();(null===(t=null==n?void 0:n.FabricConfig)||void 0===t?void 0:t.legacyTheme)?function(e,t){var i;void 0===t&&(t=!1),LH=NH(e,t),hH(IU(IU(IU(IU({},LH.palette),LH.semanticColors),LH.effects),function(e){for(var t={},i=0,n=Object.keys(e.fonts);i<n.length;i++)for(var r=n[i],s=e.fonts[r],a=0,o=Object.keys(s);a<o.length;a++){var l=o[a],c=r+l.charAt(0).toUpperCase()+l.slice(1),d=s[l];"fontSize"===l&&"number"==typeof d&&(d+="px"),t[c]=d}return t}(LH))),oH.applySettings(((i={})[FH]=LH,i)),xH.forEach((function(e){try{e(LH)}catch(e){}}))}(n.FabricConfig.legacyTheme):oH.getSettings([FH]).theme||((null===(i=null==n?void 0:n.FabricConfig)||void 0===i?void 0:i.theme)&&(LH=NH(n.FabricConfig.theme)),oH.applySettings(((e={})[FH]=LH,e)))}function BH(e){return void 0===e&&(e=!1),!0===e&&(LH=NH({},e)),LH}UH();var VH={boxShadow:"none",margin:0,padding:0,boxSizing:"border-box"},HH={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function $H(e){return{selectors:{"::placeholder":e,":-ms-input-placeholder":e,"::-ms-input-placeholder":e}}}function jH(e){console&&console.warn&&console.warn(e)}var GH=XV.getValue("icons",{__options:{disableWarnings:!1,warnOnMissingIcons:!0},__remapped:{}}),qH=jU.getInstance();qH&&qH.onReset&&qH.onReset((function(){for(var e in GH)GH.hasOwnProperty(e)&&GH[e].subset&&(GH[e].subset.className=void 0)}));var zH=function(e){return e.toLowerCase()};function WH(e,t){var i=IU(IU({},e),{isRegistered:!1,className:void 0}),n=e.icons;for(var r in t=t?IU(IU({},GH.__options),t):GH.__options,n)if(n.hasOwnProperty(r)){var s=n[r],a=zH(r);GH[a]?QH(r):GH[a]={code:s,subset:i}}}function KH(e,t){GH.__remapped[zH(e)]=zH(t)}var JH=[],YH=void 0;function QH(e){GH.__options.disableWarnings||(JH.push(e),void 0===YH&&(YH=setTimeout((function(){jH("Some icons were re-registered. Applications should only call registerIcons for any given icon once. Redefining what an icon is may have unintended consequences. Duplicates include: \n"+JH.slice(0,10).join(", ")+(JH.length>10?" (+ ".concat(JH.length-10," more)"):"")),YH=void 0,JH=[]}),2e3)))}function ZH(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(e&&1===e.length&&e[0]&&!e[0].subComponentStyles&&!OU(e[0]))return e[0];for(var i={},n={},r=0,s=e;r<s.length;r++){var a=s[r];if(a&&!OU(a))for(var o in a)if(a.hasOwnProperty(o)){if("subComponentStyles"===o&&void 0!==a.subComponentStyles){var l=a.subComponentStyles;for(var c in l)l.hasOwnProperty(c)&&(n.hasOwnProperty(c)?n[c].push(l[c]):n[c]=[l[c]]);continue}var d=i[o],u=a[o];i[o]=void 0===d?u:PU(PU([],Array.isArray(d)?d:[d],!0),Array.isArray(u)?u:[u],!0)}}if(Object.keys(n).length>0){i.subComponentStyles={};var h=i.subComponentStyles,g=function(e){if(n.hasOwnProperty(e)){var t=n[e];h[e]=function(e){return ZH.apply(void 0,t.map((function(t){return"function"==typeof t?t(e):t})))}}};for(var c in n)g(c)}return i}function XH(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=[],r=0,s=t;r<s.length;r++){var a=s[r];a&&n.push("function"==typeof a?a(e):a)}return 1===n.length?n[0]:n.length?ZH.apply(void 0,n):{}}function e$(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return t$(e,FU())}function t$(e,t){var i,n={subComponentStyles:{}},r=void 0;OU(e[0])?(r=e[0],i=e[1]):i=e[0],null!=r||(r=null==t?void 0:t.shadowConfig);var s=IU(IU({},t),{shadowConfig:r});if(!i&&e.length<=1)return{subComponentStyles:{}};var a=jU.getInstance(r);s.stylesheet=a;var o=ZH.apply(void 0,e),l=[];for(var c in o)if(o.hasOwnProperty(c)){if("subComponentStyles"===c){n.subComponentStyles=o.subComponentStyles||{};continue}if("__shadowConfig__"===c)continue;var d=NU(a,o[c]),u=d.classes,h=d.objects;(null==h?void 0:h.length)?(m=lB(s||{},{displayName:c},h))&&(l.push(m),n[c]=u.concat([m.className]).join(" ")):n[c]=u.join(" ")}for(var g=0,p=l;g<p.length;g++){var m;(m=p[g])&&cB(m,null==t?void 0:t.specificityMultiplier,r)}return n}var i$={},n$=void 0;try{n$=window}catch(e){}function r$(e,t){if(void 0!==n$){var i=n$.__packages__=n$.__packages__||{};i[e]&&i$[e]||(i$[e]=t,(i[e]=i[e]||[]).push(t))}}r$("@fluentui/set-version","6.0.0"),r$("@fluentui/style-utilities","8.11.7"),UH();var s$=e.createContext({customizations:{inCustomizerContext:!1,settings:{},scopedSettings:{}}});function a$(t,i){void 0===i&&(i={});var n=i.factoryOptions,r=(void 0===n?{}:n).defaultProp,s=function(n){var r,s,a,o=(r=i.displayName,s=e.useContext(s$),a=i.fields,oH.getSettings(a||["theme","styles","tokens"],r,s.customizations)),l=i.state;l&&(n=IU(IU({},n),l(n)));var c=n.theme||o.theme,d=o$(n,c,i.tokens,o.tokens,n.tokens),u=function(e,t,i){for(var n=[],r=3;r<arguments.length;r++)n[r-3]=arguments[r];return ZH.apply(void 0,n.map((function(n){return"function"==typeof n?n(e,t,i):n})))}(n,c,d,i.styles,o.styles,n.styles),h=IU(IU({},n),{styles:u,tokens:d,_defaultStyles:u,theme:c});return t(h)};return s.displayName=i.displayName||t.name,r&&(s.create=DB(s,{defaultProp:r})),RB(s,i.statics),s}function o$(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];for(var r={},s=0,a=i;s<a.length;s++){var o=a[s];o&&(o="function"==typeof o?o(e,t):o,Array.isArray(o)&&(o=o$.apply(void 0,PU([e,t],o,!1))),RB(r,o))}return r}var l$="__currentId__",c$=_B()||{};void 0===c$[l$]&&(c$[l$]=0);var d$=!1;function u$(e){if(!d$){var t=jU.getInstance();t&&t.onReset&&t.onReset(h$),d$=!0}return(void 0===e?"id__":e)+c$[l$]++}function h$(e){void 0===e&&(e=0),c$[l$]=e}function g$(t,i){var n=e.useRef(i);return n.current||(n.current=u$(t)),n.current}var p$=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i={},n=0,r=e;n<r.length;n++)for(var s=r[n],a=0,o=Array.isArray(s)?s:Object.keys(s);a<o.length;a++)i[o[a]]=1;return i},m$=p$(["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onInput","onSubmit","onLoad","onError","onKeyDown","onKeyDownCapture","onKeyPress","onKeyUp","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onClick","onClickCapture","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onMouseUpCapture","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onScroll","onWheel","onPointerCancel","onPointerDown","onPointerEnter","onPointerLeave","onPointerMove","onPointerOut","onPointerOver","onPointerUp","onGotPointerCapture","onLostPointerCapture"]),f$=p$(["accessKey","children","className","contentEditable","dir","draggable","hidden","htmlFor","id","lang","ref","role","style","tabIndex","title","translate","spellCheck","name"]),v$=p$(f$,m$),S$=p$(v$,["form"]),y$=p$(v$,["height","loop","muted","preload","src","width"]),C$=p$(y$,["poster"]),T$=p$(v$,["start"]),E$=p$(v$,["value"]),b$=p$(v$,["download","href","hrefLang","media","rel","target","type"]),_$=p$(v$,["autoFocus","disabled","form","formAction","formEncType","formMethod","formNoValidate","formTarget","type","value"]),I$=p$(_$,["accept","alt","autoCapitalize","autoComplete","checked","dirname","form","height","inputMode","list","max","maxLength","min","minLength","multiple","pattern","placeholder","readOnly","required","src","step","size","type","value","width"]),w$=p$(_$,["autoCapitalize","cols","dirname","form","maxLength","minLength","placeholder","readOnly","required","rows","wrap"]),A$=p$(_$,["form","multiple","required"]),P$=p$(v$,["selected","value"]),R$=p$(v$,["cellPadding","cellSpacing"]),M$=v$,D$=p$(v$,["rowSpan","scope"]),k$=p$(v$,["colSpan","headers","rowSpan","scope"]),O$=p$(v$,["span"]),N$=p$(v$,["span"]),L$=p$(v$,["acceptCharset","action","encType","encType","method","noValidate","target"]),x$=p$(v$,["allow","allowFullScreen","allowPaymentRequest","allowTransparency","csp","height","importance","referrerPolicy","sandbox","src","srcDoc","width"]),F$=p$(v$,["alt","crossOrigin","height","src","srcSet","useMap","width"]),U$=v$;function B$(e,t,i){for(var n=Array.isArray(t),r={},s=0,a=Object.keys(e);s<a.length;s++){var o=a[s];!(!n&&t[o]||n&&t.indexOf(o)>=0||0===o.indexOf("data-")||0===o.indexOf("aria-"))||i&&-1!==(null==i?void 0:i.indexOf(o))||(r[o]=e[o])}return r}function V$(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=[],n=0,r=e;n<r.length;n++){var s=r[n];if(s)if("string"==typeof s)i.push(s);else if(s.hasOwnProperty("toString")&&"function"==typeof s.toString)i.push(s.toString());else for(var a in s)s[a]&&i.push(a)}return i.join(" ")}var H$={root:"ms-StackItem"},$$={start:"flex-start",end:"flex-end"},j$=function(e,t){return t.spacing.hasOwnProperty(e)?t.spacing[e]:e},G$=function(e){var t=parseFloat(e),i=isNaN(t)?0:t,n=isNaN(t)?"":t.toString();return{value:i,unit:e.substring(n.toString().length)||"px"}},q$=function(e,t){if(void 0===e||"number"==typeof e||""===e)return e;var i=e.split(" ");return i.length<2?j$(e,t):i.reduce((function(e,i){return j$(e,t)+" "+j$(i,t)}))},z$={start:"flex-start",end:"flex-end"},W$={root:"ms-Stack",inner:"ms-Stack-inner",child:"ms-Stack-child"},K$=a$((function(e){var t=e.children,i=B$(e,v$);return null==t?null:MB(OB(e,{root:"div"}).root,IU({},i),t)}),{displayName:"StackItem",styles:function(e,t,i){var n=e.grow,r=e.shrink,s=e.disableShrink,a=e.align,o=e.verticalFill,l=e.order,c=e.className,d=e.basis,u=void 0===d?"auto":d,h=FV(H$,t);return{root:[t.fonts.medium,h.root,{flexBasis:u,margin:i.margin,padding:i.padding,height:o?"100%":"auto",width:"auto"},n&&{flexGrow:!0===n?1:n},(s||!n&&!r)&&{flexShrink:0},r&&!s&&{flexShrink:1},a&&{alignSelf:$$[a]||a},l&&{order:l},c]}}});function J$(t,i){var n=i.disableShrink,r=i.enableScopedSelectors,s=i.doNotRenderFalsyValues,a=e.Children.toArray(t);return e.Children.map(a,(function(t){if(!t)return s?null:t;if(!e.isValidElement(t))return t;if(t.type===e.Fragment)return t.props.children?J$(t.props.children,{disableShrink:n,enableScopedSelectors:r,doNotRenderFalsyValues:s}):null;var i,a=t,o={};(i=t)&&"object"==typeof i&&i.type&&i.type.displayName===K$.displayName&&(o={shrink:!n});var l=a.props.className;return e.cloneElement(a,IU(IU(IU(IU({},o),a.props),l&&{className:l}),r&&{className:V$(W$.child,l)}))}))}var Y$=a$((function(e){var t=e.as,i=void 0===t?"div":t,n=e.disableShrink,r=void 0!==n&&n,s=e.doNotRenderFalsyValues,a=void 0!==s&&s,o=e.enableScopedSelectors,l=void 0!==o&&o,c=e.wrap,d=wU(e,["as","disableShrink","doNotRenderFalsyValues","enableScopedSelectors","wrap"]),u=g$("stack-inner"),h=J$(e.children,{disableShrink:r,enableScopedSelectors:l,doNotRenderFalsyValues:a}),g=B$(d,v$),p=OB(e,{root:i,inner:"div"});return MB(p.root,IU({},g),c?MB(p.inner,{key:u},h):h)}),{displayName:"Stack",styles:function(e,t,i){var n,r,s,a,o,l,c,d,u,h,g,p,m,f=e.className,v=e.disableShrink,S=e.enableScopedSelectors,y=e.grow,C=e.horizontal,T=e.horizontalAlign,E=e.reversed,b=e.verticalAlign,_=e.verticalFill,I=e.wrap,w=FV(W$,t),A=i&&i.childrenGap?i.childrenGap:e.gap,P=i&&i.maxHeight?i.maxHeight:e.maxHeight,R=i&&i.maxWidth?i.maxWidth:e.maxWidth,M=i&&i.padding?i.padding:e.padding,D=function(e,t){if(void 0===e||""===e)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if("number"==typeof e)return{rowGap:{value:e,unit:"px"},columnGap:{value:e,unit:"px"}};var i=e.split(" ");if(i.length>2)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if(2===i.length)return{rowGap:G$(j$(i[0],t)),columnGap:G$(j$(i[1],t))};var n=G$(j$(e,t));return{rowGap:n,columnGap:n}}(A,t),k=D.rowGap,O=D.columnGap,N="".concat(-.5*O.value).concat(O.unit),L="".concat(-.5*k.value).concat(k.unit),x={textOverflow:"ellipsis"},F="> "+(S?"."+W$.child:"*"),U=((n={})["".concat(F,":not(.").concat(H$.root,")")]={flexShrink:0},n);return I?{root:[w.root,{flexWrap:"wrap",maxWidth:R,maxHeight:P,width:"auto",overflow:"visible",height:"100%"},T&&(r={},r[C?"justifyContent":"alignItems"]=z$[T]||T,r),b&&(s={},s[C?"alignItems":"justifyContent"]=z$[b]||b,s),f,{display:"flex"},C&&{height:_?"100%":"auto"}],inner:[w.inner,(a={display:"flex",flexWrap:"wrap",marginLeft:N,marginRight:N,marginTop:L,marginBottom:L,overflow:"visible",boxSizing:"border-box",padding:q$(M,t),width:0===O.value?"100%":"calc(100% + ".concat(O.value).concat(O.unit,")"),maxWidth:"100vw"},a[F]=IU({margin:"".concat(.5*k.value).concat(k.unit," ").concat(.5*O.value).concat(O.unit)},x),a),v&&U,T&&(o={},o[C?"justifyContent":"alignItems"]=z$[T]||T,o),b&&(l={},l[C?"alignItems":"justifyContent"]=z$[b]||b,l),C&&(c={flexDirection:E?"row-reverse":"row",height:0===k.value?"100%":"calc(100% + ".concat(k.value).concat(k.unit,")")},c[F]={maxWidth:0===O.value?"100%":"calc(100% - ".concat(O.value).concat(O.unit,")")},c),!C&&(d={flexDirection:E?"column-reverse":"column",height:"calc(100% + ".concat(k.value).concat(k.unit,")")},d[F]={maxHeight:0===k.value?"100%":"calc(100% - ".concat(k.value).concat(k.unit,")")},d)]}:{root:[w.root,(u={display:"flex",flexDirection:C?E?"row-reverse":"row":E?"column-reverse":"column",flexWrap:"nowrap",width:"auto",height:_?"100%":"auto",maxWidth:R,maxHeight:P,padding:q$(M,t),boxSizing:"border-box"},u[F]=x,u),v&&U,y&&{flexGrow:!0===y?1:y},T&&(h={},h[C?"justifyContent":"alignItems"]=z$[T]||T,h),b&&(g={},g[C?"alignItems":"justifyContent"]=z$[b]||b,g),C&&O.value>0&&(p={},p["".concat(F,E?":not(:last-child)":":not(:first-child)")]={marginLeft:"".concat(O.value).concat(O.unit)},p),!C&&k.value>0&&(m={},m["".concat(F,E?":not(:last-child)":":not(:first-child)")]={marginTop:"".concat(k.value).concat(k.unit)},m),f]}},statics:{Item:K$}}),Q$=function(){return!1},Z$=function(){},X$=e.createContext({stylesheets:new Map,useAdoptedStylesheetEx:Q$,useAdoptedStylesheet:Q$,useShadowConfig:function(){return kU},useMergeStylesShadowRootContext:Z$,useHasMergeStylesShadowRootContext:Q$,useMergeStylesRootStylesheets:function(){return new Map},useWindow:Z$,useStyled:Z$}),ej=function(){var t=e.useContext(X$);return{useAdoptedStylesheet:t.useAdoptedStylesheet,useAdoptedStylesheetEx:t.useAdoptedStylesheetEx,useShadowConfig:t.useShadowConfig,useMergeStylesShadowRootContext:t.useMergeStylesShadowRootContext,useHasMergeStylesShadowRootContext:t.useHasMergeStylesShadowRootContext,useMergeStylesRootStylesheets:t.useMergeStylesRootStylesheets,useWindow:t.useWindow,useStyled:t.useStyled}};function tj(t,i){var n=function(){var t=e.useState(0)[1];return function(){return t((function(e){return++e}))}}(),r=e.useContext(s$).customizations,s=r.inCustomizerContext;return e.useEffect((function(){return s||oH.observe(n),function(){s||oH.unobserve(n)}}),[s]),oH.getSettings(t,i,r)}var ij=["theme","styles"];function nj(t,i,n,r,s){var a=(r=r||{scope:"",fields:void 0}).scope,o=r.fields,l=void 0===o?ij:o,c=e.forwardRef((function(r,s){var o=e.useRef(),c=tj(l,a),d=c.styles,u=(c.dir,wU(c,["styles","dir"])),h=n?n(r):void 0,g=ej().useStyled,p=o.current&&o.current.__cachedInputs__||[],m=r.styles;if(!o.current||d!==p[1]||m!==p[2]){var f=function(e){return XH(e,i,d,m)};f.__cachedInputs__=[i,d,m],f.__noStyleOverride__=!d&&!m,o.current=f}return o.current.__shadowConfig__=g(a),e.createElement(t,IU({ref:s},u,h,r,{styles:o.current}))}));c.displayName="Styled".concat(t.displayName||t.name);var d=s?e.memo(c):c;return c.displayName&&(d.displayName=c.displayName),d}var rj=0,sj=jU.getInstance();sj&&sj.onReset&&sj.onReset((function(){return rj++}));var aj="__retval__";function oj(e){void 0===e&&(e={});var t=new Map,i=0,n=0,r=rj;return function(s,a){var o;if(void 0===a&&(a={}),e.useStaticStyles&&"function"==typeof s&&s.__noStyleOverride__)return s(a);n++;var l=s?s.__shadowConfig__:void 0,c=l&&l.window?l.window:"__default__";t.has(c)||t.set(c,new Map);var d=t.get(c),u=a.theme,h=u&&void 0!==u.rtl?u.rtl:PB(),g=e.disableCaching;if(r!==rj&&(r=rj,t.set(c,new Map),d=t.get(c),i=0),e.disableCaching||(d=cj(t.get(c),s),d=cj(d,a)),!g&&d[aj]||(d[aj]=void 0===s?{}:t$(["function"==typeof s?s(a):s],{shadowConfig:s.__shadowConfig__,rtl:!!h,specificityMultiplier:e.useStaticStyles?5:void 0}),g||i++),i>(e.cacheSize||50)){var p=_B();(null===(o=null==p?void 0:p.FabricConfig)||void 0===o?void 0:o.enableClassNameCacheFullWarning)&&(console.warn("Styles are being recalculated too frequently. Cache miss rate is ".concat(i,"/").concat(n,".")),console.trace()),t.get(c).clear(),i=0,e.disableCaching=!0}return d[aj]}}function lj(e,t){return t=function(e){switch(e){case void 0:return"__undefined__";case null:return"__null__";default:return e}}(t),e.has(t)||e.set(t,new Map),e.get(t)}function cj(e,t){if("function"==typeof t)if(t.__cachedInputs__)for(var i=0,n=t.__cachedInputs__;i<n.length;i++)e=lj(e,n[i]);else e=lj(e,t);else if("object"==typeof t)for(var r in t)t.hasOwnProperty(r)&&(e=lj(e,t[r]));return e}var dj=function(t){function i(e){var i=t.call(this,e)||this;return i.state={isRendered:void 0===_B()},i}return _U(i,t),i.prototype.componentDidMount=function(){var e=this,t=this.props.delay;this._timeoutId=window.setTimeout((function(){e.setState({isRendered:!0})}),t)},i.prototype.componentWillUnmount=function(){this._timeoutId&&clearTimeout(this._timeoutId)},i.prototype.render=function(){return this.state.isRendered?e.Children.only(this.props.children):null},i.defaultProps={delay:0},i}(e.Component);var uj=function(e){var t={refs:[]};return function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return t.resolver&&function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}(t.refs,e)||(t.resolver=function(e){return function(t){for(var i=0,n=e.refs;i<n.length;i++){var r=n[i];"function"==typeof r?r(t):r&&(r.current=t)}}}(t)),t.refs=e,t.resolver}};function hj(e,t){var i,n;if(void 0===t&&(t=!0),!e)return null;var r=t&&function(e){var t,i;return e&&(i=e)&&i._virtual&&(t=e._virtual.parent),t}(e);return r||("function"!=typeof e.assignedElements&&(null===(i=e.assignedSlot)||void 0===i?void 0:i.parentNode)?e.assignedSlot:11===(null===(n=e.parentNode)||void 0===n?void 0:n.nodeType)?e.parentNode.host:e.parentNode)}function gj(e,t,i){return null!=i||(i=document),!e||e===i.body||e instanceof Document?null:t(e)?e:gj(hj(e),t)}var pj="data-portal-element";function mj(e,t,i){var n,r=gj(e,(function(e){var i;return t===e||!!(null===(i=e.hasAttribute)||void 0===i?void 0:i.call(e,pj))}),i);return null!==r&&!!(null===(n=r.hasAttribute)||void 0===n?void 0:n.call(r,pj))}var fj=13,vj=27,Sj=32,yj=37,Cj=38,Tj=39,Ej=40;function bj(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return t.length<2?t[0]:function(){for(var i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.forEach((function(t){return t&&t.apply(e,i)}))}}function _j(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=bj(e,e[i],t[i]))}function Ij(e){_j(e,{componentDidMount:wj,componentDidUpdate:Aj,componentWillUnmount:Pj})}function wj(){Rj(this.props.componentRef,this)}function Aj(e){e.componentRef!==this.props.componentRef&&(Rj(e.componentRef,null),Rj(this.props.componentRef,this))}function Pj(){Rj(this.props.componentRef,null)}function Rj(e,t){e&&("object"==typeof e?e.current=t:"function"==typeof e&&e(t))}var Mj=function(){function e(e,t){this._timeoutIds=null,this._immediateIds=null,this._intervalIds=null,this._animationFrameIds=null,this._isDisposed=!1,this._parent=e||null,this._onErrorHandler=t,this._noop=function(){}}return e.prototype.dispose=function(){var e;if(this._isDisposed=!0,this._parent=null,this._timeoutIds){for(e in this._timeoutIds)this._timeoutIds.hasOwnProperty(e)&&this.clearTimeout(parseInt(e,10));this._timeoutIds=null}if(this._immediateIds){for(e in this._immediateIds)this._immediateIds.hasOwnProperty(e)&&this.clearImmediate(parseInt(e,10));this._immediateIds=null}if(this._intervalIds){for(e in this._intervalIds)this._intervalIds.hasOwnProperty(e)&&this.clearInterval(parseInt(e,10));this._intervalIds=null}if(this._animationFrameIds){for(e in this._animationFrameIds)this._animationFrameIds.hasOwnProperty(e)&&this.cancelAnimationFrame(parseInt(e,10));this._animationFrameIds=null}},e.prototype.setTimeout=function(e,t){var i=this,n=0;return this._isDisposed||(this._timeoutIds||(this._timeoutIds={}),n=setTimeout((function(){try{i._timeoutIds&&delete i._timeoutIds[n],e.apply(i._parent)}catch(e){i._logError(e)}}),t),this._timeoutIds[n]=!0),n},e.prototype.clearTimeout=function(e){this._timeoutIds&&this._timeoutIds[e]&&(clearTimeout(e),delete this._timeoutIds[e])},e.prototype.setImmediate=function(e,t){var i=this,n=0,r=_B(t);return this._isDisposed||(this._immediateIds||(this._immediateIds={}),n=r.setTimeout((function(){try{i._immediateIds&&delete i._immediateIds[n],e.apply(i._parent)}catch(e){i._logError(e)}}),0),this._immediateIds[n]=!0),n},e.prototype.clearImmediate=function(e,t){var i=_B(t);this._immediateIds&&this._immediateIds[e]&&(i.clearTimeout(e),delete this._immediateIds[e])},e.prototype.setInterval=function(e,t){var i=this,n=0;return this._isDisposed||(this._intervalIds||(this._intervalIds={}),n=setInterval((function(){try{e.apply(i._parent)}catch(e){i._logError(e)}}),t),this._intervalIds[n]=!0),n},e.prototype.clearInterval=function(e){this._intervalIds&&this._intervalIds[e]&&(clearInterval(e),delete this._intervalIds[e])},e.prototype.throttle=function(e,t,i){var n=this;if(this._isDisposed)return this._noop;var r,s,a=t||0,o=!0,l=!0,c=0,d=null;i&&"boolean"==typeof i.leading&&(o=i.leading),i&&"boolean"==typeof i.trailing&&(l=i.trailing);var u=function(t){var i=Date.now(),h=i-c,g=o?a-h:a;return h>=a&&(!t||o)?(c=i,d&&(n.clearTimeout(d),d=null),r=e.apply(n._parent,s)):null===d&&l&&(d=n.setTimeout(u,g)),r};return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s=e,u(!0)}},e.prototype.debounce=function(e,t,i){var n=this;if(this._isDisposed){var r=function(){};return r.cancel=function(){},r.flush=function(){return null},r.pending=function(){return!1},r}var s,a,o=t||0,l=!1,c=!0,d=null,u=0,h=Date.now(),g=null;i&&"boolean"==typeof i.leading&&(l=i.leading),i&&"boolean"==typeof i.trailing&&(c=i.trailing),i&&"number"==typeof i.maxWait&&!isNaN(i.maxWait)&&(d=i.maxWait);var p=function(e){g&&(n.clearTimeout(g),g=null),h=e},m=function(t){p(t),s=e.apply(n._parent,a)},f=function(e){var t=Date.now(),i=!1;e&&(l&&t-u>=o&&(i=!0),u=t);var r=t-u,a=o-r,p=t-h,v=!1;return null!==d&&(p>=d&&g?v=!0:a=Math.min(a,d-p)),r>=o||v||i?m(t):null!==g&&e||!c||(g=n.setTimeout(f,a)),s},v=function(){return!!g},S=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return a=e,f(!0)};return S.cancel=function(){v()&&p(Date.now())},S.flush=function(){return v()&&m(Date.now()),s},S.pending=v,S},e.prototype.requestAnimationFrame=function(e,t){var i=this,n=0,r=_B(t);if(!this._isDisposed){this._animationFrameIds||(this._animationFrameIds={});var s=function(){try{i._animationFrameIds&&delete i._animationFrameIds[n],e.apply(i._parent)}catch(e){i._logError(e)}};n=r.requestAnimationFrame?r.requestAnimationFrame(s):r.setTimeout(s,0),this._animationFrameIds[n]=!0}return n},e.prototype.cancelAnimationFrame=function(e,t){var i=_B(t);this._animationFrameIds&&this._animationFrameIds[e]&&(i.cancelAnimationFrame?i.cancelAnimationFrame(e):i.clearTimeout(e),delete this._animationFrameIds[e])},e.prototype._logError=function(e){this._onErrorHandler&&this._onErrorHandler(e)},e}();function Dj(e,t){if(!e||!t)return!e&&!t;for(var i in e)if(e.hasOwnProperty(i)&&(!t.hasOwnProperty(i)||t[i]!==e[i]))return!1;for(var i in t)if(t.hasOwnProperty(i)&&!e.hasOwnProperty(i))return!1;return!0}function kj(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return Oj.apply(this,[null,e].concat(t))}function Oj(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t=t||{};for(var r=0,s=i;r<s.length;r++){var a=s[r];if(a)for(var o in a)!a.hasOwnProperty(o)||e&&!e(o)||(t[o]=a[o])}return t}var Nj,Lj=function(){function e(t){this._id=e._uniqueId++,this._parent=t,this._eventRecords=[]}return e.raise=function(t,i,n,r,s){var a,o=null!=s?s:EB();if(e._isElement(t)){if(void 0!==o&&o.createEvent){var l=o.createEvent("HTMLEvents");l.initEvent(i,r||!1,!0),kj(l,n),a=t.dispatchEvent(l)}else if(void 0!==o&&o.createEventObject){var c=o.createEventObject(n);t.fireEvent("on"+i,c)}}else for(;t&&!1!==a;){var d=t.__events__,u=d?d[i]:null;if(u)for(var h in u)if(u.hasOwnProperty(h))for(var g=u[h],p=0;!1!==a&&p<g.length;p++){var m=g[p];m.objectCallback&&(a=m.objectCallback.call(m.parent,n))}t=r?t.parent:null}return a},e.isObserved=function(e,t){var i=e&&e.__events__;return!!i&&!!i[t]},e.isDeclared=function(e,t){var i=e&&e.__declaredEvents;return!!i&&!!i[t]},e.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},e._isElement=function(e){return!!e&&(!!e.addEventListener||"undefined"!=typeof HTMLElement&&e instanceof HTMLElement)},e.prototype.dispose=function(){this._isDisposed||(this._isDisposed=!0,this.off(),this._parent=null)},e.prototype.onAll=function(e,t,i){for(var n in t)t.hasOwnProperty(n)&&this.on(e,n,t[n],i)},e.prototype.on=function(t,i,n,r){var s=this;if(i.indexOf(",")>-1)for(var a=i.split(/[ ,]+/),o=0;o<a.length;o++)this.on(t,a[o],n,r);else{var l=this._parent,c={target:t,eventName:i,parent:l,callback:n,options:r};if((a=t.__events__=t.__events__||{})[i]=a[i]||{count:0},a[i][this._id]=a[i][this._id]||[],a[i][this._id].push(c),a[i].count++,e._isElement(t)){var d=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!s._isDisposed){var i;try{if(!1===(i=n.apply(l,e))&&e[0]){var r=e[0];r.preventDefault&&r.preventDefault(),r.stopPropagation&&r.stopPropagation(),r.cancelBubble=!0}}catch(r){}return i}};c.elementCallback=d,t.addEventListener?t.addEventListener(i,d,r):t.attachEvent&&t.attachEvent("on"+i,d)}else c.objectCallback=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!s._isDisposed)return n.apply(l,e)};this._eventRecords.push(c)}},e.prototype.off=function(e,t,i,n){for(var r=0;r<this._eventRecords.length;r++){var s=this._eventRecords[r];if(!(e&&e!==s.target||t&&t!==s.eventName||i&&i!==s.callback||"boolean"==typeof n&&n!==s.options)){var a=s.target.__events__,o=a[s.eventName],l=o?o[this._id]:null;l&&(1!==l.length&&i?(o.count--,l.splice(l.indexOf(s),1)):(o.count-=l.length,delete a[s.eventName][this._id]),o.count||delete a[s.eventName]),s.elementCallback&&(s.target.removeEventListener?s.target.removeEventListener(s.eventName,s.elementCallback,s.options):s.target.detachEvent&&s.target.detachEvent("on"+s.eventName,s.elementCallback)),this._eventRecords.splice(r--,1)}}},e.prototype.raise=function(t,i,n){return e.raise(this._parent,t,i,n)},e.prototype.declare=function(e){var t=this._parent.__declaredEvents=this._parent.__declaredEvents||{};if("string"==typeof e)t[e]=!0;else for(var i=0;i<e.length;i++)t[e[i]]=!0},e._uniqueId=0,e}();function xj(e,t,i){var n=e[i],r=t[i];(n||r)&&(e[i]=function(){for(var e,t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return r&&(e=r.apply(this,t)),n!==r&&(e=n.apply(this,t)),e})}function Fj(){return null}!function(e){function t(i,n){var r=e.call(this,i,n)||this;return function(e,t,i){for(var n=0,r=i.length;n<r;n++)xj(e,t,i[n])}(r,t.prototype,["componentDidMount","shouldComponentUpdate","getSnapshotBeforeUpdate","render","componentDidUpdate","componentWillUnmount"]),r}_U(t,e),t.prototype.componentDidUpdate=function(e,t){this._updateComponentRef(e,this.props)},t.prototype.componentDidMount=function(){this._setComponentRef(this.props.componentRef,this)},t.prototype.componentWillUnmount=function(){if(this._setComponentRef(this.props.componentRef,null),this.__disposables){for(var e=0,t=this._disposables.length;e<t;e++){var i=this.__disposables[e];i.dispose&&i.dispose()}this.__disposables=null}},Object.defineProperty(t.prototype,"className",{get:function(){if(!this.__className){var e=/function (.{1,})\(/.exec(this.constructor.toString());this.__className=e&&e.length>1?e[1]:""}return this.__className},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_disposables",{get:function(){return this.__disposables||(this.__disposables=[]),this.__disposables},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_async",{get:function(){return this.__async||(this.__async=new Mj(this),this._disposables.push(this.__async)),this.__async},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_events",{get:function(){return this.__events||(this.__events=new Lj(this),this._disposables.push(this.__events)),this.__events},enumerable:!1,configurable:!0}),t.prototype._resolveRef=function(e){var t=this;return this.__resolves||(this.__resolves={}),this.__resolves[e]||(this.__resolves[e]=function(i){return t[e]=i}),this.__resolves[e]},t.prototype._updateComponentRef=function(e,t){void 0===t&&(t={}),e&&t&&e.componentRef!==t.componentRef&&(this._setComponentRef(e.componentRef,null),this._setComponentRef(t.componentRef,this))},t.prototype._warnDeprecations=function(e){this.className,this.props},t.prototype._warnMutuallyExclusive=function(e){this.className,this.props},t.prototype._warnConditionallyRequiredProps=function(e,t,i){this.className,this.props},t.prototype._setComponentRef=function(e,t){!this._skipComponentRefResolution&&e&&("function"==typeof e&&e(t),"object"==typeof e&&(e.current=t))}}(e.Component);var Uj=((Nj={})[38]=1,Nj[40]=1,Nj[37]=1,Nj[39]=1,Nj[36]=1,Nj[35]=1,Nj[9]=1,Nj[33]=1,Nj[34]=1,Nj);function Bj(e){return!!Uj[e]}var Vj=new WeakMap,Hj=new WeakMap;function $j(e,t){var i,n=Vj.get(e);return i=n?n+t:1,Vj.set(e,i),i}function jj(e){var t=Hj.get(e);return t||(t={onMouseDown:function(t){return Qj(t,e.registeredProviders)},onPointerDown:function(t){return Zj(t,e.registeredProviders)},onKeyDown:function(t){return Xj(t,e.registeredProviders)},onKeyUp:function(t){return eG(t,e.registeredProviders)}},Hj.set(e,t),t)}var Gj=e.createContext(void 0);function qj(t){var i=e.useContext(Gj);e.useEffect((function(){var e,n,r,s,a=_B(null==t?void 0:t.current);if(a&&!0!==(null===(e=a.FabricConfig)||void 0===e?void 0:e.disableFocusRects)){var o,l,c,d,u=a;if((null===(n=null==i?void 0:i.providerRef)||void 0===n?void 0:n.current)&&(null===(s=null===(r=null==i?void 0:i.providerRef)||void 0===r?void 0:r.current)||void 0===s?void 0:s.addEventListener)){u=i.providerRef.current;var h=jj(i);o=h.onMouseDown,l=h.onPointerDown,c=h.onKeyDown,d=h.onKeyUp}else o=Qj,l=Zj,c=Xj,d=eG;var g=$j(u,1);return g<=1&&(u.addEventListener("mousedown",o,!0),u.addEventListener("pointerdown",l,!0),u.addEventListener("keydown",c,!0),u.addEventListener("keyup",d,!0)),function(){var e;a&&!0!==(null===(e=a.FabricConfig)||void 0===e?void 0:e.disableFocusRects)&&0===(g=$j(u,-1))&&(u.removeEventListener("mousedown",o,!0),u.removeEventListener("pointerdown",l,!0),u.removeEventListener("keydown",c,!0),u.removeEventListener("keyup",d,!0))}}}),[i,t])}var zj,Wj,Kj,Jj,Yj=function(e){return qj(e.rootRef),null};function Qj(e,t){WV(!1,e.target,t)}function Zj(e,t){"mouse"!==e.pointerType&&WV(!1,e.target,t)}function Xj(e,t){Bj(e.which)&&WV(!0,e.target,t)}function eG(e,t){Bj(e.which)&&WV(!0,e.target,t)}function tG(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e.filter((function(e){return e})).join(" ").trim();return""===i?void 0:i}!function(e){e[e.default=0]="default",e[e.image=1]="image",e[e.Default=1e5]="Default",e[e.Image=100001]="Image"}(zj||(zj={})),function(e){e[e.center=0]="center",e[e.contain=1]="contain",e[e.cover=2]="cover",e[e.none=3]="none",e[e.centerCover=4]="centerCover",e[e.centerContain=5]="centerContain"}(Wj||(Wj={})),function(e){e[e.landscape=0]="landscape",e[e.portrait=1]="portrait"}(Kj||(Kj={})),function(e){e[e.notLoaded=0]="notLoaded",e[e.loaded=1]="loaded",e[e.error=2]="error",e[e.errorLoaded=3]="errorLoaded"}(Jj||(Jj={}));var iG=TB()?e.useLayoutEffect:e.useEffect;function nG(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];var n=e.useCallback((function(e){n.current=e;for(var i=0,r=t;i<r.length;i++){var s=r[i];"function"==typeof s?s(e):s&&(s.current=e)}}),PU([],t,!0));return n}var rG=oj(),sG=/\.svg$/i,aG=e.forwardRef((function(t,i){var n=e.useRef(),r=e.useRef(),s=function(t,i){var n=t.onLoadingStateChange,r=t.onLoad,s=t.onError,a=t.src,o=e.useState(Jj.notLoaded),l=o[0],c=o[1];iG((function(){c(Jj.notLoaded)}),[a]),e.useEffect((function(){l===Jj.notLoaded&&i.current&&(a&&i.current.naturalWidth>0&&i.current.naturalHeight>0||i.current.complete&&sG.test(a))&&c(Jj.loaded)})),e.useEffect((function(){null==n||n(l)}),[l]);var d=e.useCallback((function(e){null==r||r(e),a&&c(Jj.loaded)}),[a,r]),u=e.useCallback((function(e){null==s||s(e),c(Jj.error)}),[s]);return[l,d,u]}(t,r),a=s[0],o=s[1],l=s[2],c=B$(t,F$,["width","height"]),d=t.src,u=t.alt,h=t.width,g=t.height,p=t.shouldFadeIn,m=void 0===p||p,f=t.shouldStartVisible,v=t.className,S=t.imageFit,y=t.role,C=t.maximizeFrame,T=t.styles,E=t.theme,b=t.loading,_=function(t,i,n,r){var s=e.useRef(i),a=e.useRef();return(void 0===a||s.current===Jj.notLoaded&&i===Jj.loaded)&&(a.current=function(e,t,i,n){var r=e.imageFit,s=e.width,a=e.height;if(void 0!==e.coverStyle)return e.coverStyle;if(t===Jj.loaded&&(r===Wj.cover||r===Wj.contain||r===Wj.centerContain||r===Wj.centerCover)&&i.current&&n.current){var o;if(o="number"==typeof s&&"number"==typeof a&&r!==Wj.centerContain&&r!==Wj.centerCover?s/a:n.current.clientWidth/n.current.clientHeight,i.current.naturalWidth/i.current.naturalHeight>o)return Kj.landscape}return Kj.portrait}(t,i,n,r)),s.current=i,a.current}(t,a,r,n),I=rG(T,{theme:E,className:v,width:h,height:g,maximizeFrame:C,shouldFadeIn:m,shouldStartVisible:f,isLoaded:a===Jj.loaded||a===Jj.notLoaded&&t.shouldStartVisible,isLandscape:_===Kj.landscape,isCenter:S===Wj.center,isCenterContain:S===Wj.centerContain,isCenterCover:S===Wj.centerCover,isContain:S===Wj.contain,isCover:S===Wj.cover,isNone:S===Wj.none,isError:a===Jj.error,isNotImageFit:void 0===S});return e.createElement("div",{className:I.root,style:{width:h,height:g},ref:n},e.createElement("img",IU({},c,{onLoad:o,onError:l,key:"fabricImage"+t.src||"",className:I.image,ref:nG(r,i),src:d,alt:u,role:y,loading:b})))}));aG.displayName="ImageBase";var oG={root:"ms-Image",rootMaximizeFrame:"ms-Image--maximizeFrame",image:"ms-Image-image",imageCenter:"ms-Image-image--center",imageContain:"ms-Image-image--contain",imageCover:"ms-Image-image--cover",imageCenterContain:"ms-Image-image--centerContain",imageCenterCover:"ms-Image-image--centerCover",imageNone:"ms-Image-image--none",imageLandscape:"ms-Image-image--landscape",imagePortrait:"ms-Image-image--portrait"},lG=nj(aG,(function(e){var t=e.className,i=e.width,n=e.height,r=e.maximizeFrame,s=e.isLoaded,a=e.shouldFadeIn,o=e.shouldStartVisible,l=e.isLandscape,c=e.isCenter,d=e.isContain,u=e.isCover,h=e.isCenterContain,g=e.isCenterCover,p=e.isNone,m=e.isError,f=e.isNotImageFit,v=e.theme,S=FV(oG,v),y={position:"absolute",left:"50% /* @noflip */",top:"50%",transform:"translate(-50%,-50%)"},C=_B(),T=void 0!==C&&void 0===C.navigator.msMaxTouchPoints,E=d&&l||u&&!l?{width:"100%",height:"auto"}:{width:"auto",height:"100%"};return{root:[S.root,v.fonts.medium,{overflow:"hidden"},r&&[S.rootMaximizeFrame,{height:"100%",width:"100%"}],s&&a&&!o&&OV.fadeIn400,(c||d||u||h||g)&&{position:"relative"},t],image:[S.image,{display:"block",opacity:0},s&&["is-loaded",{opacity:1}],c&&[S.imageCenter,y],d&&[S.imageContain,T&&{width:"100%",height:"100%",objectFit:"contain"},!T&&E,!T&&y],u&&[S.imageCover,T&&{width:"100%",height:"100%",objectFit:"cover"},!T&&E,!T&&y],h&&[S.imageCenterContain,l&&{maxWidth:"100%"},!l&&{maxHeight:"100%"},y],g&&[S.imageCenterCover,l&&{maxHeight:"100%"},!l&&{maxWidth:"100%"},y],p&&[S.imageNone,{width:"auto",height:"auto"}],f&&[!!i&&!n&&{height:"auto",width:"100%"},!i&&!!n&&{height:"100%",width:"auto"},!!i&&!!n&&{height:"100%",width:"100%"}],l&&S.imageLandscape,!l&&S.imagePortrait,!s&&"is-notLoaded",a&&"is-fadeIn",m&&"is-error"]}}),void 0,{scope:"Image"},!0);lG.displayName="Image";var cG=e$({root:{display:"inline-block",textDecoration:"inherit"},placeholder:["ms-Icon-placeHolder",{width:"1em"}],image:["ms-Icon-imageContainer",{overflow:"hidden"}]}),dG="ms-Icon",uG=SB((function(e){var t=function(e){var t=void 0,i=GH.__options;if(e=e?zH(e):"",e=GH.__remapped[e]||e)if(t=GH[e]){var n=t.subset;n&&n.fontFace&&(n.isRegistered||(fH(n.fontFace),n.isRegistered=!0),n.className||(n.className=dB(n.style,{fontFamily:n.fontFace.fontFamily,fontWeight:n.fontFace.fontWeight||"normal",fontStyle:n.fontFace.fontStyle||"normal"})))}else!i.disableWarnings&&i.warnOnMissingIcons&&jH('The icon "'.concat(e,'" was used but not registered. See https://github.com/microsoft/fluentui/wiki/Using-icons for more information.'));return t}(e)||{subset:{},code:void 0},i=t.code,n=t.subset;return i?{children:i,iconClassName:n.className,fontFamily:n.fontFace&&n.fontFace.fontFamily,mergeImageProps:n.mergeImageProps}:null}),void 0,!0),hG=function(t){var i=t.iconName,n=t.className,r=t.style,s=void 0===r?{}:r,a=uG(i)||{},o=a.iconClassName,l=a.children,c=a.fontFamily,d=a.mergeImageProps,u=B$(t,v$),h=t["aria-label"]||t.title,g=t["aria-label"]||t["aria-labelledby"]||t.title?{role:d?void 0:"img"}:{"aria-hidden":!0},p=l;return d&&"object"==typeof l&&"object"==typeof l.props&&h&&(p=e.cloneElement(l,{alt:h})),e.createElement("i",IU({"data-icon-name":i},g,u,d?{title:void 0,"aria-label":void 0}:{},{className:V$(dG,cG.root,o,!i&&cG.placeholder,n),style:IU({fontFamily:c},s)}),p)},gG=(SB((function(e,t,i){return hG({iconName:e,className:t,"aria-label":i})})),oj({cacheSize:100})),pG=function(t){function i(e){var i=t.call(this,e)||this;return i._onImageLoadingStateChange=function(e){i.props.imageProps&&i.props.imageProps.onLoadingStateChange&&i.props.imageProps.onLoadingStateChange(e),e===Jj.error&&i.setState({imageLoadError:!0})},i.state={imageLoadError:!1},i}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.children,n=t.className,r=t.styles,s=t.iconName,a=t.imageErrorAs,o=t.theme,l="string"==typeof s&&0===s.length,c=!!this.props.imageProps||this.props.iconType===zj.image||this.props.iconType===zj.Image,d=uG(s)||{},u=d.iconClassName,h=d.children,g=d.mergeImageProps,p=gG(r,{theme:o,className:n,iconClassName:u,isImage:c,isPlaceholder:l}),m=c?"span":"i",f=B$(this.props,v$,["aria-label"]),v=this.state.imageLoadError,S=IU(IU({},this.props.imageProps),{onLoadingStateChange:this._onImageLoadingStateChange}),y=v&&a||lG,C=this.props["aria-label"]||this.props.ariaLabel,T=S.alt||C||this.props.title,E=T||this.props["aria-labelledby"]||S["aria-label"]||S["aria-labelledby"]?{role:c||g?void 0:"img","aria-label":c||g?void 0:T}:{"aria-hidden":!0},b=h;return g&&h&&"object"==typeof h&&T&&(b=e.cloneElement(h,{alt:T})),e.createElement(m,IU({"data-icon-name":s},E,f,g?{title:void 0,"aria-label":void 0}:{},{className:p.root}),c?e.createElement(y,IU({},S)):i||b)},i}(e.Component),mG=nj(pG,(function(e){var t=e.className,i=e.iconClassName,n=e.isPlaceholder,r=e.isImage,s=e.styles;return{root:[n&&cG.placeholder,cG.root,r&&cG.image,i,t,s&&s.root,s&&s.imageContainer]}}),void 0,{scope:"Icon"},!0);mG.displayName="Icon";var fG,vG=function(t){var i=t.className,n=t.imageProps,r=B$(t,v$,["aria-label","aria-labelledby","title","aria-describedby"]),s=n.alt||t["aria-label"],a=s||t["aria-labelledby"]||t.title||n["aria-label"]||n["aria-labelledby"]||n.title,o={"aria-labelledby":t["aria-labelledby"],"aria-describedby":t["aria-describedby"],title:t.title},l=a?{}:{"aria-hidden":!0};return e.createElement("div",IU({},l,r,{className:V$(dG,cG.root,cG.image,i)}),e.createElement(lG,IU({},o,n,{alt:a?s:""})))},SG=yB((function(e){return yB((function(t){var i=yB((function(e){return function(i){return t(i,e)}}));return function(n,r){return e(n,r?i(r):t)}}))}));!function(e){e[e.Normal=0]="Normal",e[e.Divider=1]="Divider",e[e.Header=2]="Header",e[e.Section=3]="Section"}(fG||(fG={}));var yG;function CG(e,t,i){void 0===i&&(i=!0);var n=!1;if(e&&t)if(i)if(e===t)n=!0;else for(n=!1;t;){var r=hj(t);if(r===e){n=!0;break}t=r}else e.contains&&(n=e.contains(t));return n}function TG(e,t,i,n){return _G(e,t,!0,!1,!1,i,void 0,void 0,void 0,n)}function EG(e,t,i,n){return bG(e,t,!0,!1,!0,i,void 0,void 0,n)}function bG(e,t,i,n,r,s,a,o,l){var c;if(!t||!a&&t===e)return null;var d=IG(t);if(r&&d&&(s||!PG(t)&&!RG(t))){var u=bG(e,t.lastElementChild||l&&(null===(c=t.shadowRoot)||void 0===c?void 0:c.lastElementChild),!0,!0,!0,s,a,o,l);if(u){if(o&&AG(u,!0,l)||!o)return u;var h=bG(e,u.previousElementSibling,!0,!0,!0,s,a,o,l);if(h)return h;for(var g=u.parentElement;g&&g!==t;){var p=bG(e,g.previousElementSibling,!0,!0,!0,s,a,o,l);if(p)return p;g=g.parentElement}}}return i&&d&&AG(t,o,l)?t:bG(e,t.previousElementSibling,!0,!0,!0,s,a,o,l)||(n?null:bG(e,t.parentElement,!0,!1,!1,s,a,o,l))}function _G(e,t,i,n,r,s,a,o,l,c){var d;if(!t||t===e&&r&&!a)return null;var u=(l?wG:IG)(t);if(i&&u&&AG(t,o,c))return t;if(!r&&u&&(s||!PG(t)&&!RG(t))){var h=_G(e,t.firstElementChild||c&&(null===(d=t.shadowRoot)||void 0===d?void 0:d.firstElementChild),!0,!0,!1,s,a,o,l,c);if(h)return h}return t===e?null:_G(e,t.nextElementSibling,!0,!0,!1,s,a,o,l,c)||(n?null:_G(e,t.parentElement,!1,!1,!0,s,a,o,l,c))}function IG(e){if(!e||!e.getAttribute)return!1;var t=e.getAttribute("data-is-visible");return null!=t?"true"===t:0!==e.offsetHeight||null!==e.offsetParent||!0===e.isVisible}function wG(e,t){var i=null!=t?t:_B();return!!e&&IG(e)&&!e.hidden&&"hidden"!==i.getComputedStyle(e).visibility}function AG(e,t,i){if(void 0===i&&(i=!0),!e||e.disabled)return!1;var n=0,r=null;e&&e.getAttribute&&(r=e.getAttribute("tabIndex"))&&(n=parseInt(r,10));var s=e.getAttribute?e.getAttribute("data-is-focusable"):null,a=null!==r&&n>=0,o=!(!i||!e.shadowRoot||!e.shadowRoot.delegatesFocus),l=!!e&&"false"!==s&&("A"===e.tagName||"BUTTON"===e.tagName||"INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||"true"===s||a||o);return t?-1!==n&&l:l}function PG(e){return!!(e&&e.getAttribute&&e.getAttribute("data-focuszone-id"))}function RG(e){return!(!e||!e.getAttribute||"true"!==e.getAttribute("data-is-sub-focuszone"))}function MG(e,t,i){return"true"!==function(e,t,i){var n=gj(e,(function(e){return e.hasAttribute(t)}),i);return n&&n.getAttribute(t)}(e,t,null!=i?i:EB())}!function(e){e[e.vertical=0]="vertical",e[e.horizontal=1]="horizontal",e[e.bidirectional=2]="bidirectional",e[e.domOrder=3]="domOrder"}(yG||(yG={}));var DG,kG=void 0;function OG(e){if(e){var t=_B(e);t&&(void 0!==kG&&t.cancelAnimationFrame(kG),kG=t.requestAnimationFrame((function(){e&&e.focus(),kG=void 0})))}}var NG=0,LG=dB({overflow:"hidden !important"}),xG="data-is-scrollable",FG=function(e,t){var i=_B(e);if(e&&i){var n=0,r=null,s=i.getComputedStyle(e);t.on(e,"touchstart",(function(e){1===e.targetTouches.length&&(n=e.targetTouches[0].clientY)}),{passive:!1}),t.on(e,"touchmove",(function(e){if(1===e.targetTouches.length&&(e.stopPropagation(),r)){var t=e.targetTouches[0].clientY-n,a=VG(e.target);a&&r!==a&&(r=a,s=i.getComputedStyle(r));var o=r.scrollTop,l="column-reverse"===(null==s?void 0:s.flexDirection);0===o&&(l?t<0:t>0)&&e.preventDefault(),r.scrollHeight-Math.abs(Math.ceil(o))<=r.clientHeight&&(l?t>0:t<0)&&e.preventDefault()}}),{passive:!1}),r=e}},UG=function(e,t){e&&t.on(e,"touchmove",(function(e){e.stopPropagation()}),{passive:!1})},BG=function(e){e.preventDefault()};function VG(e){for(var t=e,i=EB(e);t&&t!==i.body;){if("true"===t.getAttribute(xG))return t;t=t.parentElement}for(t=e;t&&t!==i.body;){if("false"!==t.getAttribute(xG)){var n=getComputedStyle(t),r=n?n.getPropertyValue("overflow-y"):"";if(r&&("scroll"===r||"auto"===r))return t}t=t.parentElement}return t&&t!==i.body||(t=_B(e)),t}var HG,$G=e.createContext(void 0),jG="data-is-focusable",GG="data-focuszone-id",qG="tabindex",zG="data-no-vertical-wrap",WG="data-no-horizontal-wrap",KG=999999999,JG=-999999999;function YG(e,t){var i;"function"==typeof MouseEvent?i=new MouseEvent("click",{ctrlKey:null==t?void 0:t.ctrlKey,metaKey:null==t?void 0:t.metaKey,shiftKey:null==t?void 0:t.shiftKey,altKey:null==t?void 0:t.altKey,bubbles:null==t?void 0:t.bubbles,cancelable:null==t?void 0:t.cancelable}):(i=document.createEvent("MouseEvents")).initMouseEvent("click",!!t&&t.bubbles,!!t&&t.cancelable,window,0,0,0,0,0,!!t&&t.ctrlKey,!!t&&t.altKey,!!t&&t.shiftKey,!!t&&t.metaKey,0,null),e.dispatchEvent(i)}var QG,ZG={},XG=new Set,eq=["text","number","password","email","tel","url","search","textarea"],tq=!1,iq=function(t){function i(n){var r,s,a,o,l=t.call(this,n)||this;l._root=e.createRef(),l._mergedRef=uj(),l._onFocus=function(e){if(!l._portalContainsElement(e.target)){var t,i=l.props,n=i.onActiveElementChanged,r=i.doNotAllowFocusEventToPropagate,s=i.stopFocusPropagation,a=i.onFocusNotification,o=i.onFocus,c=i.shouldFocusInnerElementWhenReceivedFocus,d=i.defaultTabbableElement,u=l._isImmediateDescendantOfZone(e.target);if(u)t=e.target;else for(var h=e.target;h&&h!==l._root.current;){if(AG(h,void 0,l._inShadowRoot)&&l._isImmediateDescendantOfZone(h)){t=h;break}h=hj(h,tq)}if(c&&e.target===l._root.current){var g=d&&"function"==typeof d&&l._root.current&&d(l._root.current);g&&AG(g,void 0,l._inShadowRoot)?(t=g,g.focus()):(l.focus(!0),l._activeElement&&(t=null))}var p=!l._activeElement;t&&t!==l._activeElement&&((u||p)&&l._setFocusAlignment(t,!0,!0),l._activeElement=t,p&&l._updateTabIndexes()),n&&n(l._activeElement,e),(s||r)&&e.stopPropagation(),o?o(e):a&&a()}},l._onBlur=function(){l._setParkedFocus(!1)},l._onMouseDown=function(e){if(!l._portalContainsElement(e.target)&&!l.props.disabled){for(var t=e.target,i=[];t&&t!==l._root.current;)i.push(t),t=hj(t,tq);for(;i.length&&((t=i.pop())&&AG(t,void 0,l._inShadowRoot)&&l._setActiveElement(t,!0),!PG(t)););}},l._onKeyDown=function(e,t){if(!l._portalContainsElement(e.target)){var i=l.props,n=i.direction,r=i.disabled,s=i.isInnerZoneKeystroke,a=i.pagingSupportDisabled,o=i.shouldEnterInnerZone;if(!(r||(l.props.onKeyDown&&l.props.onKeyDown(e),e.isDefaultPrevented()||l._getDocument().activeElement===l._root.current&&l._isInnerZone))){if((o&&o(e)||s&&s(e))&&l._isImmediateDescendantOfZone(e.target)){var c=l._getFirstInnerZone();if(c){if(!c.focus(!0))return}else{if(!RG(e.target))return;if(!l.focusElement(_G(e.target,e.target.firstChild,!0)))return}}else{if(e.altKey)return;switch(e.which){case Sj:if(l._shouldRaiseClicksOnSpace&&l._tryInvokeClickForFocusable(e.target,e))break;return;case yj:if(n!==yG.vertical&&(l._preventDefaultWhenHandled(e),l._moveFocusLeft(t)))break;return;case Tj:if(n!==yG.vertical&&(l._preventDefaultWhenHandled(e),l._moveFocusRight(t)))break;return;case Cj:if(n!==yG.horizontal&&(l._preventDefaultWhenHandled(e),l._moveFocusUp()))break;return;case Ej:if(n!==yG.horizontal&&(l._preventDefaultWhenHandled(e),l._moveFocusDown()))break;return;case 34:if(!a&&l._moveFocusPaging(!0))break;return;case 33:if(!a&&l._moveFocusPaging(!1))break;return;case 9:if(l.props.allowTabKey||1===l.props.handleTabKey||2===l.props.handleTabKey&&l._isElementInput(e.target)){var d=!1;if(l._processingTabKey=!0,d=n!==yG.vertical&&l._shouldWrapFocus(l._activeElement,WG)?(PB(t)?!e.shiftKey:e.shiftKey)?l._moveFocusLeft(t):l._moveFocusRight(t):e.shiftKey?l._moveFocusUp():l._moveFocusDown(),l._processingTabKey=!1,d)break;l.props.shouldResetActiveElementWhenTabFromZone&&(l._activeElement=null)}return;case 36:if(l._isContentEditableElement(e.target)||l._isElementInput(e.target)&&!l._shouldInputLoseFocus(e.target,!1))return!1;var u=l._root.current&&l._root.current.firstChild;if(l._root.current&&u&&l.focusElement(_G(l._root.current,u,!0)))break;return;case 35:if(l._isContentEditableElement(e.target)||l._isElementInput(e.target)&&!l._shouldInputLoseFocus(e.target,!0))return!1;var h=l._root.current&&l._root.current.lastChild;if(l._root.current&&l.focusElement(bG(l._root.current,h,!0,!0,!0)))break;return;case fj:if(l._shouldRaiseClicksOnEnter&&l._tryInvokeClickForFocusable(e.target,e))break;return;default:return}}e.preventDefault(),e.stopPropagation()}}},l._getHorizontalDistanceFromCenter=function(e,t,i){var n=l._focusAlignment.left||l._focusAlignment.x||0,r=Math.floor(i.top),s=Math.floor(t.bottom),a=Math.floor(i.bottom),o=Math.floor(t.top);return e&&r>s||!e&&a<o?n>=i.left&&n<=i.left+i.width?0:Math.abs(i.left+i.width/2-n):l._shouldWrapFocus(l._activeElement,zG)?KG:JG},Ij(l),l._id=u$("FocusZone"),l._focusAlignment={left:0,top:0},l._processingTabKey=!1;var c=null===(s=null!==(r=n.shouldRaiseClicks)&&void 0!==r?r:i.defaultProps.shouldRaiseClicks)||void 0===s||s;return l._shouldRaiseClicksOnEnter=null!==(a=n.shouldRaiseClicksOnEnter)&&void 0!==a?a:c,l._shouldRaiseClicksOnSpace=null!==(o=n.shouldRaiseClicksOnSpace)&&void 0!==o?o:c,l}return _U(i,t),i.getOuterZones=function(){return XG.size},i._onKeyDownCapture=function(e){9===e.which&&XG.forEach((function(e){return e._updateTabIndexes()}))},i.prototype.componentDidMount=function(){var e,t=this._root.current;if(this._inShadowRoot=!!(null===(e=this.context)||void 0===e?void 0:e.shadowRoot),ZG[this._id]=this,t){for(var n=hj(t,tq);n&&n!==this._getDocument().body&&1===n.nodeType;){if(PG(n)){this._isInnerZone=!0;break}n=hj(n,tq)}this._isInnerZone||(XG.add(this),this._root.current&&this._root.current.addEventListener("keydown",i._onKeyDownCapture,!0)),this._root.current&&this._root.current.addEventListener("blur",this._onBlur,!0),this._updateTabIndexes(),this.props.defaultTabbableElement&&"string"==typeof this.props.defaultTabbableElement?this._activeElement=this._getDocument().querySelector(this.props.defaultTabbableElement):this.props.defaultActiveElement&&(this._activeElement=this._getDocument().querySelector(this.props.defaultActiveElement)),this.props.shouldFocusOnMount&&this.focus()}},i.prototype.componentDidUpdate=function(){var e,t=this._root.current,i=this._getDocument();if(this._inShadowRoot=!!(null===(e=this.context)||void 0===e?void 0:e.shadowRoot),(this._activeElement&&!CG(this._root.current,this._activeElement,tq)||this._defaultFocusElement&&!CG(this._root.current,this._defaultFocusElement,tq))&&(this._activeElement=null,this._defaultFocusElement=null,this._updateTabIndexes()),!this.props.preventFocusRestoration&&i&&this._lastIndexPath&&(i.activeElement===i.body||null===i.activeElement||i.activeElement===t)){var n=function(e,t){for(var i=e,n=0,r=t;n<r.length;n++){var s=r[n],a=i.children[Math.min(s,i.children.length-1)];if(!a)break;i=a}return AG(i)&&IG(i)?i:_G(e,i,!0)||bG(e,i)}(t,this._lastIndexPath);n?(this._setActiveElement(n,!0),n.focus(),this._setParkedFocus(!1)):this._setParkedFocus(!0)}},i.prototype.componentWillUnmount=function(){delete ZG[this._id],this._isInnerZone||(XG.delete(this),this._root.current&&this._root.current.removeEventListener("keydown",i._onKeyDownCapture,!0)),this._root.current&&this._root.current.removeEventListener("blur",this._onBlur,!0),this._activeElement=null,this._defaultFocusElement=null},i.prototype.render=function(){var t=this,i=this.props,n=i.as,r=i.elementType,s=i.rootProps,a=i.ariaDescribedBy,o=i.ariaLabelledBy,l=i.className,c=B$(this.props,v$),d=n||r||"div";this._evaluateFocusBeforeRender();var u=BH();return e.createElement(d,IU({"aria-labelledby":o,"aria-describedby":a},c,s,{className:V$((HG||(HG=dB({selectors:{":focus":{outline:"none"}}},"ms-FocusZone")),HG),l),ref:this._mergedRef(this.props.elementRef,this._root),"data-focuszone-id":this._id,onKeyDown:function(e){return t._onKeyDown(e,u)},onFocus:this._onFocus,onMouseDownCapture:this._onMouseDown}),this.props.children)},i.prototype.focus=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),this._root.current){if(!e&&"true"===this._root.current.getAttribute(jG)&&this._isInnerZone){var i=this._getOwnerZone(this._root.current);if(i!==this._root.current){var n=ZG[i.getAttribute(GG)];return!!n&&n.focusElement(this._root.current)}return!1}if(!e&&this._activeElement&&CG(this._root.current,this._activeElement)&&AG(this._activeElement,void 0,this._inShadowRoot)&&(!t||wG(this._activeElement)))return this._activeElement.focus(),!0;var r=this._root.current.firstChild;return this.focusElement(_G(this._root.current,r,!0,void 0,void 0,void 0,void 0,void 0,t))}return!1},i.prototype.focusLast=function(){if(this._root.current){var e=this._root.current&&this._root.current.lastChild;return this.focusElement(bG(this._root.current,e,!0,!0,!0))}return!1},i.prototype.focusElement=function(e,t){var i=this.props,n=i.onBeforeFocus,r=i.shouldReceiveFocus;return!(r&&!r(e)||n&&!n(e)||!e||(this._setActiveElement(e,t),this._activeElement&&this._activeElement.focus(),0))},i.prototype.setFocusAlignment=function(e){this._focusAlignment=e},Object.defineProperty(i.prototype,"defaultFocusElement",{get:function(){return this._defaultFocusElement},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"activeElement",{get:function(){return this._activeElement},enumerable:!1,configurable:!0}),i.prototype._evaluateFocusBeforeRender=function(){var e=this._root.current,t=this._getDocument();if(t){var i=t.activeElement;if(i!==e){var n=CG(e,i,!1);this._lastIndexPath=n?function(e,t){for(var i=[];t&&e&&t!==e;){var n=hj(t,!0);if(null===n)return[];i.unshift(Array.prototype.indexOf.call(n.children,t)),t=n}return i}(e,i):void 0}}},i.prototype._setParkedFocus=function(e){var t=this._root.current;t&&this._isParked!==e&&(this._isParked=e,e?(this.props.allowFocusRoot||(this._parkedTabIndex=t.getAttribute("tabindex"),t.setAttribute("tabindex","-1")),t.focus()):this.props.allowFocusRoot||(this._parkedTabIndex?(t.setAttribute("tabindex",this._parkedTabIndex),this._parkedTabIndex=void 0):t.removeAttribute("tabindex")))},i.prototype._setActiveElement=function(e,t){var i=this._activeElement;this._activeElement=e,i&&(PG(i)&&this._updateTabIndexes(i),i.tabIndex=-1),this._activeElement&&(this._focusAlignment&&!t||this._setFocusAlignment(e,!0,!0),this._activeElement.tabIndex=0)},i.prototype._preventDefaultWhenHandled=function(e){this.props.preventDefaultWhenHandled&&e.preventDefault()},i.prototype._tryInvokeClickForFocusable=function(e,t){var i=e;if(i===this._root.current)return!1;do{if("BUTTON"===i.tagName||"A"===i.tagName||"INPUT"===i.tagName||"TEXTAREA"===i.tagName||"SUMMARY"===i.tagName)return!1;if(this._isImmediateDescendantOfZone(i)&&"true"===i.getAttribute(jG)&&"true"!==i.getAttribute("data-disable-click-on-enter"))return YG(i,t),!0;i=hj(i,tq)}while(i!==this._root.current);return!1},i.prototype._getFirstInnerZone=function(e){if(!(e=e||this._activeElement||this._root.current))return null;if(PG(e))return ZG[e.getAttribute(GG)];for(var t=e.firstElementChild;t;){if(PG(t))return ZG[t.getAttribute(GG)];var i=this._getFirstInnerZone(t);if(i)return i;t=t.nextElementSibling}return null},i.prototype._moveFocus=function(e,t,i,n){void 0===n&&(n=!0);var r=this._activeElement,s=-1,a=void 0,o=!1,l=this.props.direction===yG.bidirectional;if(!r||!this._root.current)return!1;if(this._isElementInput(r)&&!this._shouldInputLoseFocus(r,e))return!1;var c=l?r.getBoundingClientRect():null;do{if(r=e?_G(this._root.current,r):bG(this._root.current,r),!l){a=r;break}if(r){var d=t(c,r.getBoundingClientRect());if(-1===d&&-1===s){a=r;break}if(d>-1&&(-1===s||d<s)&&(s=d,a=r),s>=0&&d<0)break}}while(r);if(a&&a!==this._activeElement)o=!0,this.focusElement(a);else if(this.props.isCircularNavigation&&n)return e?this.focusElement(_G(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(bG(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return o},i.prototype._moveFocusDown=function(){var e=this,t=-1,i=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!0,(function(n,r){var s=-1,a=Math.floor(r.top),o=Math.floor(n.bottom);return a<o?e._shouldWrapFocus(e._activeElement,zG)?KG:JG:((-1===t&&a>=o||a===t)&&(t=a,s=i>=r.left&&i<=r.left+r.width?0:Math.abs(r.left+r.width/2-i)),s)}))&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},i.prototype._moveFocusUp=function(){var e=this,t=-1,i=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!1,(function(n,r){var s=-1,a=Math.floor(r.bottom),o=Math.floor(r.top),l=Math.floor(n.top);return a>l?e._shouldWrapFocus(e._activeElement,zG)?KG:JG:((-1===t&&a<=l||o===t)&&(t=o,s=i>=r.left&&i<=r.left+r.width?0:Math.abs(r.left+r.width/2-i)),s)}))&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},i.prototype._moveFocusLeft=function(e){var t=this,i=this._shouldWrapFocus(this._activeElement,WG);return!!this._moveFocus(PB(e),(function(n,r){var s=-1;return(PB(e)?parseFloat(r.top.toFixed(3))<parseFloat(n.bottom.toFixed(3)):parseFloat(r.bottom.toFixed(3))>parseFloat(n.top.toFixed(3)))&&r.right<=n.right&&t.props.direction!==yG.vertical?s=n.right-r.right:i||(s=JG),s}),void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},i.prototype._moveFocusRight=function(e){var t=this,i=this._shouldWrapFocus(this._activeElement,WG);return!!this._moveFocus(!PB(e),(function(n,r){var s=-1;return(PB(e)?parseFloat(r.bottom.toFixed(3))>parseFloat(n.top.toFixed(3)):parseFloat(r.top.toFixed(3))<parseFloat(n.bottom.toFixed(3)))&&r.left>=n.left&&t.props.direction!==yG.vertical?s=r.left-n.left:i||(s=JG),s}),void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},i.prototype._moveFocusPaging=function(e,t){void 0===t&&(t=!0);var i=this._activeElement;if(!i||!this._root.current)return!1;if(this._isElementInput(i)&&!this._shouldInputLoseFocus(i,e))return!1;var n=VG(i);if(!n)return!1;var r=-1,s=void 0,a=-1,o=-1,l=n.clientHeight,c=i.getBoundingClientRect();do{if(i=e?_G(this._root.current,i):bG(this._root.current,i)){var d=i.getBoundingClientRect(),u=Math.floor(d.top),h=Math.floor(c.bottom),g=Math.floor(d.bottom),p=Math.floor(c.top),m=this._getHorizontalDistanceFromCenter(e,c,d);if(e&&u>h+l||!e&&g<p-l)break;m>-1&&(e&&u>a?(a=u,r=m,s=i):!e&&g<o?(o=g,r=m,s=i):(-1===r||m<=r)&&(r=m,s=i))}}while(i);var f=!1;if(s&&s!==this._activeElement)f=!0,this.focusElement(s),this._setFocusAlignment(s,!1,!0);else if(this.props.isCircularNavigation&&t)return e?this.focusElement(_G(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(bG(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return f},i.prototype._setFocusAlignment=function(e,t,i){if(this.props.direction===yG.bidirectional&&(!this._focusAlignment||t||i)){var n=e.getBoundingClientRect(),r=n.left+n.width/2,s=n.top+n.height/2;this._focusAlignment||(this._focusAlignment={left:r,top:s}),t&&(this._focusAlignment.left=r),i&&(this._focusAlignment.top=s)}},i.prototype._isImmediateDescendantOfZone=function(e){return this._getOwnerZone(e)===this._root.current},i.prototype._getOwnerZone=function(e){for(var t=hj(e,tq);t&&t!==this._root.current&&t!==this._getDocument().body;){if(PG(t))return t;t=hj(t,tq)}return t},i.prototype._updateTabIndexes=function(e){!this._activeElement&&this.props.defaultTabbableElement&&"function"==typeof this.props.defaultTabbableElement&&(this._activeElement=this.props.defaultTabbableElement(this._root.current)),!e&&this._root.current&&(this._defaultFocusElement=null,e=this._root.current,this._activeElement&&!CG(e,this._activeElement)&&(this._activeElement=null)),this._activeElement&&!AG(this._activeElement,void 0,this._inShadowRoot)&&(this._activeElement=null);for(var t=e&&e.children,i=0;t&&i<t.length;i++){var n=t[i];PG(n)?"true"===n.getAttribute(jG)&&(this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(qG)&&n.setAttribute(qG,"-1"):(this._defaultFocusElement=n,"0"!==n.getAttribute(qG)&&n.setAttribute(qG,"0"))):(n.getAttribute&&"false"===n.getAttribute(jG)&&n.setAttribute(qG,"-1"),AG(n,void 0,this._inShadowRoot)?this.props.disabled?n.setAttribute(qG,"-1"):this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(qG)&&n.setAttribute(qG,"-1"):(this._defaultFocusElement=n,"0"!==n.getAttribute(qG)&&n.setAttribute(qG,"0")):"svg"===n.tagName&&"false"!==n.getAttribute("focusable")&&n.setAttribute("focusable","false")),this._updateTabIndexes(n)}},i.prototype._isContentEditableElement=function(e){return e&&"true"===e.getAttribute("contenteditable")},i.prototype._isElementInput=function(e){return!(!e||!e.tagName||"input"!==e.tagName.toLowerCase()&&"textarea"!==e.tagName.toLowerCase())},i.prototype._shouldInputLoseFocus=function(e,t){if(!this._processingTabKey&&e&&e.type&&eq.indexOf(e.type.toLowerCase())>-1){var i=e.selectionStart,n=i!==e.selectionEnd,r=e.value,s=e.readOnly;if(n||i>0&&!t&&!s||i!==r.length&&t&&!s||this.props.handleTabKey&&(!this.props.shouldInputLoseFocusOnArrowKey||!this.props.shouldInputLoseFocusOnArrowKey(e)))return!1}return!0},i.prototype._shouldWrapFocus=function(e,t){return!this.props.checkForNoWrap||MG(e,t)},i.prototype._portalContainsElement=function(e){return e&&!!this._root.current&&mj(e,this._root.current)},i.prototype._getDocument=function(){return EB(this._root.current)},i.contextType=$G,i.defaultProps={isCircularNavigation:!1,direction:yG.bidirectional,shouldRaiseClicks:!0,"data-tabster":'{"uncontrolled": {}}'},i}(e.Component);function nq(e){var t;if(void 0===QG||e){var i=_B(),n=null===(t=null==i?void 0:i.navigator)||void 0===t?void 0:t.userAgent;QG=!!n&&-1!==n.indexOf("Macintosh")}return!!QG}var rq=function(){return!!(window&&window.navigator&&window.navigator.userAgent)&&/iPad|iPhone|iPod/i.test(window.navigator.userAgent)};function sq(e,t){for(var i=IU({},t),n=0,r=Object.keys(e);n<r.length;n++){var s=r[n];void 0===i[s]&&(i[s]=e[s])}return i}var aq,oq,lq=yB((function(t){var i=t;return yB((function(n){if(t===n)throw new Error("Attempted to compose a component with itself.");var r=n,s=yB((function(t){return function(i){return e.createElement(r,IU({},i,{defaultRender:t}))}}));return function(t){var n=t.defaultRender;return e.createElement(i,IU({},t,{defaultRender:n?s(n):r}))}}))}));function cq(e,t){return lq(e)(t)}function dq(e){return e.canCheck?!(!e.isChecked&&!e.checked):"boolean"==typeof e.isChecked?e.isChecked:"boolean"==typeof e.checked?e.checked:null}function uq(e){return!(!e.subMenuProps&&!e.items)}function hq(e){return!(!e.isDisabled&&!e.disabled)}function gq(e){return null!==dq(e)?"menuitemcheckbox":"menuitem"}function pq(e,t,i,n){return e.addEventListener(t,i,n),function(){return e.removeEventListener(t,i,n)}}!function(e){e[e.top=1]="top",e[e.bottom=-1]="bottom",e[e.left=2]="left",e[e.right=-2]="right"}(aq||(aq={})),function(e){e[e.top=0]="top",e[e.bottom=1]="bottom",e[e.start=2]="start",e[e.end=3]="end"}(oq||(oq={}));var mq,fq=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.top=i,this.bottom=n,this.left=e,this.right=t}return Object.defineProperty(e.prototype,"width",{get:function(){return this.right-this.left},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.bottom-this.top},enumerable:!1,configurable:!0}),e.prototype.equals=function(e){return parseFloat(this.top.toFixed(4))===parseFloat(e.top.toFixed(4))&&parseFloat(this.bottom.toFixed(4))===parseFloat(e.bottom.toFixed(4))&&parseFloat(this.left.toFixed(4))===parseFloat(e.left.toFixed(4))&&parseFloat(this.right.toFixed(4))===parseFloat(e.right.toFixed(4))},e}();function vq(e,t,i){return{targetEdge:e,alignmentEdge:t,isAuto:i}}var Sq=((mq={})[0]=vq(aq.top,aq.left),mq[1]=vq(aq.top),mq[2]=vq(aq.top,aq.right),mq[3]=vq(aq.top,void 0,!0),mq[4]=vq(aq.bottom,aq.left),mq[5]=vq(aq.bottom),mq[6]=vq(aq.bottom,aq.right),mq[7]=vq(aq.bottom,void 0,!0),mq[8]=vq(aq.left,aq.top),mq[9]=vq(aq.left),mq[10]=vq(aq.left,aq.bottom),mq[11]=vq(aq.right,aq.top),mq[12]=vq(aq.right),mq[13]=vq(aq.right,aq.bottom),mq);function yq(e,t){return!(e.top<t.top||e.bottom>t.bottom||e.left<t.left||e.right>t.right)}function Cq(e,t){var i=[];return e.top<t.top&&i.push(aq.top),e.bottom>t.bottom&&i.push(aq.bottom),e.left<t.left&&i.push(aq.left),e.right>t.right&&i.push(aq.right),i}function Tq(e,t){return e[aq[t]]}function Eq(e,t,i){return e[aq[t]]=i,e}function bq(e,t){var i=Lq(t);return(Tq(e,i.positiveEdge)+Tq(e,i.negativeEdge))/2}function _q(e,t){return e>0?t:-1*t}function Iq(e,t){return _q(e,Tq(t,e))}function wq(e,t,i){return _q(i,Tq(e,i)-Tq(t,i))}function Aq(e,t,i,n){void 0===n&&(n=!0);var r=Tq(e,t)-i,s=Eq(e,t,i);return n&&(s=Eq(e,-1*t,Tq(e,-1*t)-r)),s}function Pq(e,t,i,n){return void 0===n&&(n=0),Aq(e,i,Tq(t,i)+_q(i,n))}function Rq(e,t,i){return Iq(i,e)>Iq(i,t)}function Mq(e,t){for(var i=0,n=0,r=Cq(e,t);n<r.length;n++){var s=r[n];i+=Math.pow(wq(e,t,s),2)}return i}function Dq(e,t,i,n){return void 0===n&&(n=200),(i===aq.bottom||i===aq.top)&&wq(e,t,i)>=n}function kq(e,t,i,n){for(var r=0,s=e;r<s.length;r++){var a=s[r],o=void 0;n&&n===-1*a?(o=Aq(t.elementRectangle,a,Tq(i,a),!1),t.forcedInBounds=!0):Rq(o=Pq(t.elementRectangle,i,a),i,-1*a)||(o=Aq(o,-1*a,Tq(i,-1*a),!1),t.forcedInBounds=!0),t.elementRectangle=o}return t}function Oq(e,t,i){var n=Lq(t).positiveEdge;return Aq(e,n,i-(bq(e,t)-Tq(e,n)))}function Nq(e,t,i,n,r){void 0===n&&(n=0);var s=new fq(e.left,e.right,e.top,e.bottom),a=i.alignmentEdge,o=i.targetEdge,l=r?o:-1*o;return s=r?Pq(s,t,o,n):function(e,t,i,n){void 0===n&&(n=0);var r=_q(-1*i,n);return Aq(e,-1*i,Tq(t,i)+r)}(s,t,o,n),s=a?Pq(s,t,a):Oq(s,l,bq(t,o))}function Lq(e){return e===aq.top||e===aq.bottom?{positiveEdge:aq.left,negativeEdge:aq.right}:{positiveEdge:aq.top,negativeEdge:aq.bottom}}function xq(e,t,i){return i&&Math.abs(wq(e,i,t))>Math.abs(wq(e,i,-1*t))?-1*t:t}function Fq(e,t,i,n,r,s,a,o){var l,c={},d=Vq(t),u=s?i:-1*i,h=r||Lq(i).positiveEdge;return a&&!function(e,t,i){return void 0!==i&&Tq(e,t)===Tq(i,t)}(e,(l=h,-1*l),n)||(h=xq(e,h,n)),c[aq[u]]=wq(e,d,u),c[aq[h]]=wq(e,d,h),o&&(c[aq[-1*u]]=wq(e,d,-1*u),c[aq[-1*h]]=wq(e,d,-1*h)),c}function Uq(e,t,i){var n=bq(t,e),r=bq(i,e),s=Lq(e),a=s.positiveEdge,o=s.negativeEdge;return n<=r?a:o}function Bq(e,t,i,n,r,s,a,o,l){void 0===s&&(s=!1);var c=Nq(e,t,n,r,l);return yq(c,i)?{elementRectangle:c,targetEdge:n.targetEdge,alignmentEdge:n.alignmentEdge}:function(e,t,i,n,r,s,a,o,l){void 0===r&&(r=!1),void 0===a&&(a=0);var c=n.alignmentEdge,d=n.alignTargetEdge,u={elementRectangle:e,targetEdge:n.targetEdge,alignmentEdge:c};o||l||(u=function(e,t,i,n,r,s,a){void 0===r&&(r=!1),void 0===a&&(a=0);var o=[aq.left,aq.right,aq.bottom,aq.top];PB()&&(o[0]*=-1,o[1]*=-1);for(var l,c=e,d=n.targetEdge,u=n.alignmentEdge,h=d,g=u,p=0;p<4;p++){if(Rq(c,i,d))return{elementRectangle:c,targetEdge:d,alignmentEdge:u};if(r&&Dq(t,i,d,s)){switch(d){case aq.bottom:c.bottom=i.bottom;break;case aq.top:c.top=i.top}return{elementRectangle:c,targetEdge:d,alignmentEdge:u,forcedInBounds:!0}}var m=Mq(c,i);(!l||m<l)&&(l=m,h=d,g=u),o.splice(o.indexOf(d),1),o.length>0&&(o.indexOf(-1*d)>-1?d*=-1:(u=d,d=o.slice(-1)[0]),c=Nq(e,t,{targetEdge:d,alignmentEdge:u},a))}return{elementRectangle:c=Nq(e,t,{targetEdge:h,alignmentEdge:g},a),targetEdge:h,alignmentEdge:g}}(e,t,i,n,r,s,a));var h=Cq(u.elementRectangle,i),g=o?-u.targetEdge:void 0;if(h.length>0)if(d)if(u.alignmentEdge&&h.indexOf(-1*u.alignmentEdge)>-1){var p=function(e,t,i,n){var r=e.alignmentEdge,s=e.targetEdge,a=-1*r;return{elementRectangle:Nq(e.elementRectangle,t,{targetEdge:s,alignmentEdge:a},i,n),targetEdge:s,alignmentEdge:a}}(u,t,a,l);if(yq(p.elementRectangle,i))return p;u=kq(Cq(p.elementRectangle,i),u,i,g)}else u=kq(h,u,i,g);else u=kq(h,u,i,g);return u}(c,t,i,n,s,a,r,o,l)}function Vq(e){var t=e.getBoundingClientRect();return new fq(t.left,t.right,t.top,t.bottom)}function Hq(e,t,i,n,r,s){void 0===r&&(r=!1);var a=e.gapSpace?e.gapSpace:0,o=function(e,t){var i;if(t){if(t.preventDefault){var n=t;i=new fq(n.clientX,n.clientX,n.clientY,n.clientY)}else if(t.getBoundingClientRect)i=Vq(t);else{var r=t,s=r.left||r.x,a=r.top||r.y,o=r.right||s,l=r.bottom||a;i=new fq(s,o,a,l)}if(!yq(i,e))for(var c=0,d=Cq(i,e);c<d.length;c++){var u=d[c];i[aq[u]]=e[aq[u]]}}else i=new fq(0,0,0,0);return i}(i,e.target),l=function(e,t,i,n,r){return e.isAuto&&(e.alignmentEdge=Uq(e.targetEdge,t,i)),e.alignTargetEdge=r,e}(function(e,t,i){if(void 0===e&&(e=7),i)return{alignmentEdge:i.alignmentEdge,isAuto:i.isAuto,targetEdge:i.targetEdge};var n=IU({},Sq[e]);return PB()?(n.alignmentEdge&&n.alignmentEdge%2==0&&(n.alignmentEdge=-1*n.alignmentEdge),void 0!==t?Sq[t]:n):n}(e.directionalHint,e.directionalHintForRTL,n),o,i,e.coverTarget,e.alignTargetEdge),c=Bq(Vq(t),o,i,l,a,r,s,e.directionalHintFixed,e.coverTarget);return IU(IU({},c),{targetRectangle:o})}function $q(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=0),function(e){return Math.sqrt(e*e*2)}(e?t:0)/2+i}function jq(e,t,i,n,r,s,a,o){void 0===r&&(r=!1);var l=null!=o?o:_B(),c=e.isBeakVisible&&e.beakWidth||0,d=$q(e.isBeakVisible,e.beakWidth,e.gapSpace),u=e;u.gapSpace=d;var h,g,p,m,f,v,S,y,C,T=e.bounds?(C=e.bounds,new fq(C.left,C.right,C.top,C.bottom)):new fq(0,l.innerWidth-function(){if(void 0===DG){var e=EB(),t=e.createElement("div");t.style.setProperty("width","100px"),t.style.setProperty("height","100px"),t.style.setProperty("overflow","scroll"),t.style.setProperty("position","absolute"),t.style.setProperty("top","-9999px"),e.body.appendChild(t),DG=t.offsetWidth-t.clientWidth,e.body.removeChild(t)}return DG}(),0,l.innerHeight),E=Hq(u,i,T,n,r,s),b=(h=E,g=function(e,t){var i=t.targetRectangle,n=Lq(t.targetEdge),r=n.positiveEdge,s=n.negativeEdge,a=bq(i,t.targetEdge),o=new fq(e/2,t.elementRectangle.width-e/2,e/2,t.elementRectangle.height-e/2),l=new fq(0,e,0,e);return Rq(l=Oq(l=Aq(l,-1*t.targetEdge,-e/2),-1*t.targetEdge,a-Iq(r,t.elementRectangle)),o,r)?Rq(l,o,s)||(l=Pq(l,o,s)):l=Pq(l,o,r),l}(c,E),p=T,m=-1*h.targetEdge,f=new fq(0,h.elementRectangle.width,0,h.elementRectangle.height),v={},S=xq(h.elementRectangle,h.alignmentEdge?h.alignmentEdge:Lq(m).positiveEdge,p),y=wq(h.elementRectangle,h.targetRectangle,m)>Math.abs(Tq(g,m)),v[aq[m]]=Tq(g,m),v[aq[S]]=wq(g,f,S),{elementPosition:IU({},v),closestEdge:Uq(h.targetEdge,g,f),targetEdge:m,hideBeak:!y});return IU(IU({},function(e,t,i,n,r){return{elementPosition:Fq(e.elementRectangle,t,e.targetEdge,i,e.alignmentEdge,n,r,e.forcedInBounds),targetEdge:e.targetEdge,alignmentEdge:e.alignmentEdge}}(E,t,T,e.coverTarget,a)),{beakPosition:b})}var Gq=["TEMPLATE","STYLE","SCRIPT"];function qq(e){var t=EB(e);if(!t)return function(){};for(var i=[];e!==t.body&&e.parentElement;){for(var n=0,r=e.parentElement.children;n<r.length;n++){var s=r[n],a=s.getAttribute("aria-hidden");s!==e&&"true"!==(null==a?void 0:a.toLowerCase())&&-1===Gq.indexOf(s.tagName)&&i.push([s,a])}e=e.parentElement}return i.forEach((function(e){e[0].setAttribute("aria-hidden","true")})),function(){!function(e){e.forEach((function(e){var t=e[0],i=e[1];i?t.setAttribute("aria-hidden",i):t.removeAttribute("aria-hidden")}))}(i),i=[]}}function zq(){var t=e.useRef();return t.current||(t.current=new Mj),e.useEffect((function(){return function(){var e;null===(e=t.current)||void 0===e||e.dispose(),t.current=void 0}}),[]),t.current}function Wq(t,i,n,r){var s=e.useRef(n);s.current=n,e.useEffect((function(){var e=t&&"current"in t?t.current:t;if(e&&e.addEventListener)return pq(e,i,(function(e){return s.current(e)}),r)}),[t,i,r])}var Kq=e.createContext({window:"object"==typeof window?window:void 0}),Jq=function(){return e.useContext(Kq).window},Yq=function(){var t;return null===(t=e.useContext(Kq).window)||void 0===t?void 0:t.document};function Qq(e){var t=e.originalElement,i=e.containsFocus;t&&i&&t!==_B()&&setTimeout((function(){var e;null===(e=t.focus)||void 0===e||e.call(t)}),0)}var Zq=e.forwardRef((function(t,i){var n=sq({shouldRestoreFocus:!0,enableAriaHiddenSiblings:!0},t),r=e.useRef(),s=nG(r,i);!function(t,i){var n="true"===String(t["aria-modal"]).toLowerCase()&&t.enableAriaHiddenSiblings;e.useEffect((function(){if(n&&i.current)return qq(i.current)}),[i,n])}(n,r),function(t,i){var n=t.onRestoreFocus,r=void 0===n?Qq:n,s=e.useRef(),a=e.useRef(!1);e.useEffect((function(){var e,t,n;return s.current=EB().activeElement,(n=(t=EB(e=i.current))&&t.activeElement)&&CG(e,n)&&(a.current=!0),function(){var e;null==r||r({originalElement:s.current,containsFocus:a.current,documentContainsFocus:(null===(e=EB())||void 0===e?void 0:e.hasFocus())||!1}),s.current=void 0}}),[]),Wq(i,"focus",e.useCallback((function(){a.current=!0}),[]),!0),Wq(i,"blur",e.useCallback((function(e){i.current&&e.relatedTarget&&!i.current.contains(e.relatedTarget)&&(a.current=!1)}),[]),!0)}(n,r);var a=n.role,o=n.className,l=n.ariaLabel,c=n.ariaLabelledBy,d=n.ariaDescribedBy,u=n.style,h=n.children,g=n.onDismiss,p=function(t,i){var n=zq(),r=e.useState(!1),s=r[0],a=r[1];return e.useEffect((function(){return n.requestAnimationFrame((function(){var e;if(!t.style||!t.style.overflowY){var n=!1;if(i&&i.current&&(null===(e=i.current)||void 0===e?void 0:e.firstElementChild)){var r=i.current.clientHeight,o=i.current.firstElementChild.clientHeight;r>0&&o>r&&(n=o-r>1)}s!==n&&a(n)}})),function(){return n.dispose()}})),s}(n,r),m=e.useCallback((function(e){e.which===vj&&g&&(g(e),e.preventDefault(),e.stopPropagation())}),[g]);return Wq(Jq(),"keydown",m),e.createElement("div",IU({ref:s},B$(n,U$),{className:o,role:a,"aria-label":l,"aria-labelledby":c,"aria-describedby":d,onKeyDown:m,style:IU({overflowY:p?"scroll":void 0,outline:"none"},u)}),h)}));function Xq(t){var i=e.useRef();return void 0===i.current&&(i.current={value:"function"==typeof t?t():t}),i.current.value}function ez(t,i){var n,r,s,a=e.useRef(),o=e.useRef(null),l=Jq();if(!t||t!==a.current||"string"==typeof t){var c=null==i?void 0:i.current;if(t)if("string"==typeof t)if(null===(n=null==c?void 0:c.getRootNode())||void 0===n?void 0:n.host)o.current=null!==(s=null===(r=null==c?void 0:c.getRootNode())||void 0===r?void 0:r.querySelector(t))&&void 0!==s?s:null;else{var d=EB(c);o.current=d?d.querySelector(t):null}else o.current="stopPropagation"in t||"getBoundingClientRect"in t?t:"current"in t?t.current:t;a.current=t}return[o,l]}Zq.displayName="Popup";var tz,iz=function(){var e;return null!==(e=Jq())&&void 0!==e?e:"undefined"!=typeof window?window:void 0},nz=function(e){var t,i;return null!==(i=null===(t=null==e?void 0:e.window)||void 0===t?void 0:t.document)&&void 0!==i?i:"undefined"!=typeof document?document:void 0},rz=function(e){var t;return null!==(t=null==e?void 0:e.window)&&void 0!==t?t:"undefined"!=typeof window?window:void 0},sz=((tz={})[aq.top]=OV.slideUpIn10,tz[aq.bottom]=OV.slideDownIn10,tz[aq.left]=OV.slideLeftIn10,tz[aq.right]=OV.slideRightIn10,tz),az={opacity:0,filter:"opacity(0)",pointerEvents:"none"},oz=["role","aria-roledescription"],lz={preventDismissOnLostFocus:!1,preventDismissOnScroll:!1,preventDismissOnResize:!1,isBeakVisible:!0,beakWidth:16,gapSpace:0,minPagePadding:8,directionalHint:7},cz=oj({disableCaching:!0});function dz(t,i,n,r){var s,a=t.calloutMaxHeight,o=t.finalHeight,l=t.directionalHint,c=t.directionalHintFixed,d=t.hidden,u=t.gapSpace,h=t.beakWidth,g=t.isBeakVisible,p=t.coverTarget,m=e.useState(),f=m[0],v=m[1],S=null!==(s=null==r?void 0:r.elementPosition)&&void 0!==s?s:{},y=S.top,C=S.bottom,T=(null==n?void 0:n.current)?function(e){var t,i,n,r,s=e,a=e,o=e,l=null!==(t=o.left)&&void 0!==t?t:o.x,c=null!==(i=o.top)&&void 0!==i?i:o.y,d=null!==(n=o.right)&&void 0!==n?n:l,u=null!==(r=o.bottom)&&void 0!==r?r:c;return s.stopPropagation?new fq(s.clientX,s.clientX,s.clientY,s.clientY):void 0!==l&&void 0!==c?new fq(l,d,c,u):Vq(a)}(n.current):void 0;return e.useEffect((function(){var e,t,n=null!==(e=i())&&void 0!==e?e:{},s=n.top,o=n.bottom;(null==r?void 0:r.targetEdge)===aq.top&&(null==T?void 0:T.top)&&!p&&(o=T.top-function(e,t,i){return $q(e,t,i)}(g,h,u)),"number"==typeof y&&o?t=o-y:"number"==typeof C&&"number"==typeof s&&o&&(t=o-s-C),v(!a&&!d||a&&t&&a>t?t:a||void 0)}),[C,a,o,l,c,i,d,r,y,u,h,g,T,p]),f}function uz(t,i,n,r,s,a){var o,l=e.useState(),c=l[0],d=l[1],u=e.useRef(0),h=e.useRef(),g=zq(),p=t.hidden,m=t.target,f=t.finalHeight,v=t.calloutMaxHeight,S=t.onPositioned,y=t.directionalHint,C=t.hideOverflow,T=t.preferScrollResizePositioning,E=iz(),b=e.useRef();b.current!==a.current&&(b.current=a.current,o=a.current?null==E?void 0:E.getComputedStyle(a.current):void 0);var _=null==o?void 0:o.overflowY;return e.useEffect((function(){if(!p){var e=g.requestAnimationFrame((function(){var e,a,o,l;if(i.current&&n){var g=IU(IU({},t),{target:r.current,bounds:s()}),p=n.cloneNode(!0);p.style.maxHeight=v?"".concat(v):"",p.style.visibility="hidden",null===(e=n.parentElement)||void 0===e||e.appendChild(p);var y=h.current===m?c:void 0,b=T&&!(C||"clip"===_||"hidden"===_),I=f?function(e,t,i,n,r){return function(e,t,i,n,r){return jq(e,t,i,n,!1,void 0,!0,null!=r?r:_B())}(e,t,i,n,r)}(g,i.current,p,y,E):function(e,t,i,n,r,s,a){return jq(e,t,i,n,r,void 0,void 0,a)}(g,i.current,p,y,b,0,E);null===(a=n.parentElement)||void 0===a||a.removeChild(p),!c&&I||c&&I&&(l=I,!pz((o=c).elementPosition,l.elementPosition)||!pz(o.beakPosition.elementPosition,l.beakPosition.elementPosition))&&u.current<5?(u.current++,d(I)):u.current>0&&(u.current=0,null==S||S(c))}}),n);return h.current=m,function(){g.cancelAnimationFrame(e),h.current=void 0}}d(void 0),u.current=0}),[p,y,g,n,v,i,r,f,s,S,c,t,m,C,T,_,E]),c}var hz=e.memo(e.forwardRef((function(t,i){var n=sq(lz,t),r=n.styles,s=n.style,a=n.ariaLabel,o=n.ariaDescribedBy,l=n.ariaLabelledBy,c=n.className,d=n.isBeakVisible,u=n.children,h=n.beakWidth,g=n.calloutWidth,p=n.calloutMaxWidth,m=n.calloutMinWidth,f=n.doNotLayer,v=n.finalHeight,S=n.hideOverflow,y=void 0===S?!!v:S,C=n.backgroundColor,T=n.calloutMaxHeight,E=n.onScroll,b=n.shouldRestoreFocus,_=void 0===b||b,I=n.target,w=n.hidden,A=n.onLayerMounted,P=n.popupProps,R=e.useRef(null),M=nG(e.useRef(null),null==P?void 0:P.ref),D=e.useState(null),k=D[0],O=D[1],N=e.useCallback((function(e){O(e)}),[]),L=nG(R,i),x=ez(n.target,{current:k}),F=x[0],U=x[1],B=function(t,i,n){var r=t.bounds,s=t.minPagePadding,a=void 0===s?lz.minPagePadding:s,o=t.target,l=e.useState(!1),c=l[0],d=l[1],u=e.useRef(),h=e.useCallback((function(){if(!u.current||c){var e="function"==typeof r?n?r(o,n):void 0:r;!e&&n&&(e=function(e,t){return function(e,t){var i=void 0;if(t.getWindowSegments&&(i=t.getWindowSegments()),void 0===i||i.length<=1)return{top:0,left:0,right:t.innerWidth,bottom:t.innerHeight,width:t.innerWidth,height:t.innerHeight};var n=0,r=0;if(null!==e&&e.getBoundingClientRect){var s=e.getBoundingClientRect();n=(s.left+s.right)/2,r=(s.top+s.bottom)/2}else null!==e&&(n=e.left||e.x,r=e.top||e.y);for(var a={top:0,left:0,right:0,bottom:0,width:0,height:0},o=0,l=i;o<l.length;o++){var c=l[o];n&&c.left<=n&&c.right>=n&&r&&c.top<=r&&c.bottom>=r&&(a={top:c.top,left:c.left,right:c.right,bottom:c.bottom,width:c.width,height:c.height})}return a}(e,t)}(i.current,n),e={top:e.top+a,left:e.left+a,right:e.right-a,bottom:e.bottom-a,width:e.width-2*a,height:e.height-2*a}),u.current=e,c&&d(!1)}return u.current}),[r,a,o,i,n,c]),g=zq();return Wq(n,"resize",g.debounce((function(){d(!0)}),500,{leading:!0})),h}(n,F,U),V=uz(n,R,k,F,B,M),H=dz(n,B,F,V),$=function(t,i,n,r,s){var a=t.hidden,o=t.onDismiss,l=t.preventDismissOnScroll,c=t.preventDismissOnResize,d=t.preventDismissOnLostFocus,u=t.dismissOnTargetClick,h=t.shouldDismissOnWindowFocus,g=t.preventDismissOnEvent,p=e.useRef(!1),m=zq(),f=Xq([function(){p.current=!0},function(){p.current=!1}]),v=!!i;return e.useEffect((function(){var e=function(e){v&&!l&&f(e)},t=function(e){c||g&&g(e)||null==o||o(e)},i=function(e){d||f(e)},f=function(e){var t=e.composedPath?e.composedPath():[],i=t.length>0?t[0]:e.target,a=n.current&&!CG(n.current,i);if(a&&p.current)p.current=!1;else if(!r.current&&a||e.target!==s&&a&&(!r.current||"stopPropagation"in r.current||u||i!==r.current&&!CG(r.current,i))){if(g&&g(e))return;null==o||o(e)}},S=function(e){h&&((!g||g(e))&&(g||d)||(null==s?void 0:s.document.hasFocus())||null!==e.relatedTarget||null==o||o(e))},y=new Promise((function(n){m.setTimeout((function(){if(!a&&s){var r=[pq(s,"scroll",e,!0),pq(s,"resize",t,!0),pq(s.document.documentElement,"focus",i,!0),pq(s.document.documentElement,"click",i,!0),pq(s,"blur",S,!0)];n((function(){r.forEach((function(e){return e()}))}))}}),0)}));return function(){y.then((function(e){return e()}))}}),[a,m,n,r,s,o,h,u,d,c,l,v,g]),f}(n,V,R,F,U),j=$[0],G=$[1],q=(null==V?void 0:V.elementPosition.top)&&(null==V?void 0:V.elementPosition.bottom),z=IU(IU({},null==V?void 0:V.elementPosition),{maxHeight:H});if(q&&(z.bottom=void 0),function(t,i,n){var r=t.hidden,s=t.setInitialFocus,a=zq(),o=!!i;e.useEffect((function(){if(!r&&s&&o&&n){var e=a.requestAnimationFrame((function(){return!!(t=_G(e=n,e,!0,!1,!1,!0,void 0,void 0,void 0,void 0))&&(OG(t),!0);var e,t}),n);return function(){return a.cancelAnimationFrame(e)}}}),[r,o,a,n,s])}(n,V,k),e.useEffect((function(){w||null==A||A()}),[w]),!U)return null;var W=y,K=d&&!!I,J=cz(r,{theme:n.theme,className:c,overflowYHidden:W,calloutWidth:g,positions:V,beakWidth:h,backgroundColor:C,calloutMaxWidth:p,calloutMinWidth:m,doNotLayer:f}),Y=IU(IU({maxHeight:T||"100%"},s),W&&{overflowY:"hidden"}),Q=n.hidden?{visibility:"hidden"}:void 0;return e.createElement("div",{ref:L,className:J.container,style:Q},e.createElement("div",IU({},B$(n,U$,oz),{className:V$(J.root,V&&V.targetEdge&&sz[V.targetEdge]),style:V?IU({},z):az,tabIndex:-1,ref:N}),K&&e.createElement("div",{className:J.beak,style:gz(V)}),K&&e.createElement("div",{className:J.beakCurtain}),e.createElement(Zq,IU({role:n.role,"aria-roledescription":n["aria-roledescription"],ariaDescribedBy:o,ariaLabel:a,ariaLabelledBy:l,className:J.calloutMain,onDismiss:n.onDismiss,onMouseDown:j,onMouseUp:G,onRestoreFocus:n.onRestoreFocus,onScroll:E,shouldRestoreFocus:_,style:Y},P,{ref:M}),u)))})),(function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||Dj(e,t)}));function gz(e){var t,i,n=IU(IU({},null===(t=null==e?void 0:e.beakPosition)||void 0===t?void 0:t.elementPosition),{display:(null===(i=null==e?void 0:e.beakPosition)||void 0===i?void 0:i.hideBeak)?"none":void 0});return n.top||n.bottom||n.left||n.right||(n.left=0,n.top=0),n}function pz(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=e[i],r=t[i];if(void 0===n||void 0===r)return!1;if(n.toFixed(2)!==r.toFixed(2))return!1}return!0}function mz(e){return{height:e,width:e}}hz.displayName="CalloutContentBase";var fz={container:"ms-Callout-container",root:"ms-Callout",beak:"ms-Callout-beak",beakCurtain:"ms-Callout-beakCurtain",calloutMain:"ms-Callout-main"},vz=nj(hz,(function(e){var t,i=e.theme,n=e.className,r=e.overflowYHidden,s=e.calloutWidth,a=e.beakWidth,o=e.backgroundColor,l=e.calloutMaxWidth,c=e.calloutMinWidth,d=e.doNotLayer,u=FV(fz,i),h=i.semanticColors,g=i.effects;return{container:[u.container,{position:"relative"}],root:[u.root,i.fonts.medium,{position:"absolute",display:"flex",zIndex:d?jV.Layer:void 0,boxSizing:"border-box",borderRadius:g.roundedCorner2,boxShadow:g.elevation16,selectors:(t={},t[UV]={borderWidth:1,borderStyle:"solid",borderColor:"WindowText"},t)},{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}},n,!!s&&{width:s},!!l&&{maxWidth:l},!!c&&{minWidth:c}],beak:[u.beak,{position:"absolute",backgroundColor:h.menuBackground,boxShadow:"inherit",border:"inherit",boxSizing:"border-box",transform:"rotate(45deg)"},mz(a),o&&{backgroundColor:o}],beakCurtain:[u.beakCurtain,{position:"absolute",top:0,right:0,bottom:0,left:0,backgroundColor:h.menuBackground,borderRadius:g.roundedCorner2}],calloutMain:[u.calloutMain,{backgroundColor:h.menuBackground,overflowX:"hidden",overflowY:"auto",position:"relative",width:"100%",borderRadius:g.roundedCorner2},r&&{overflowY:"hidden"},o&&{backgroundColor:o}]}}),void 0,{scope:"CalloutContent"}),Sz=e.createContext(void 0),yz=function(){return function(){}};Sz.Provider;var Cz=r(5491),Tz=function(t){var i=t.providerRef,n=t.layerRoot,r=e.useState([])[0],s=e.useContext(Gj),a=void 0!==s&&!n,o=e.useMemo((function(){return a?void 0:{providerRef:i,registeredProviders:r,registerProvider:function(e){r.push(e),null==s||s.registerProvider(e)},unregisterProvider:function(e){null==s||s.unregisterProvider(e);var t=r.indexOf(e);t>=0&&r.splice(t,1)}}}),[i,r,s,a]);return e.useEffect((function(){if(o)return o.registerProvider(o.providerRef),function(){return o.unregisterProvider(o.providerRef)}}),[o]),o?e.createElement(Gj.Provider,{value:o},t.children):e.createElement(e.Fragment,null,t.children)};function Ez(e,t){void 0===e&&(e={});var i=bz(t)?t:function(e){return function(t){return e?IU(IU({},t),e):t}}(t);return i(e)}function bz(e){return"function"==typeof e}var _z=function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._onCustomizationChange=function(){return e.forceUpdate()},e}return _U(i,t),i.prototype.componentDidMount=function(){oH.observe(this._onCustomizationChange)},i.prototype.componentWillUnmount=function(){oH.unobserve(this._onCustomizationChange)},i.prototype.render=function(){var t=this,i=this.props.contextTransform;return e.createElement(s$.Consumer,null,(function(n){var r=function(e,t){var i,n,r,s=(t||{}).customizations,a=void 0===s?{settings:{},scopedSettings:{}}:s;return{customizations:{settings:Ez(a.settings,e.settings),scopedSettings:(i=a.scopedSettings,n=e.scopedSettings,void 0===i&&(i={}),(bz(n)?n:(void 0===(r=n)&&(r={}),function(e){var t=IU({},e);for(var i in r)r.hasOwnProperty(i)&&(t[i]=IU(IU({},e[i]),r[i]));return t}))(i)),inCustomizerContext:!0}}}(t.props,n);return i&&(r=i(r)),e.createElement(s$.Provider,{value:r},t.props.children)}))},i}(e.Component),Iz=oj(),wz=SB((function(e,t){return NH(IU(IU({},e),{rtl:t}))})),Az=e.forwardRef((function(t,i){var n=t.className,r=t.theme,s=t.applyTheme,a=t.applyThemeToBody,o=t.styles,l=Iz(o,{theme:r,applyTheme:s,className:n}),c=e.useRef(null);return function(t,i,n){var r=i.bodyThemed;e.useEffect((function(){if(t){var e=EB(n.current);if(e)return e.body.classList.add(r),function(){e.body.classList.remove(r)}}}),[r,t,n])}(a,l,c),e.createElement(e.Fragment,null,function(t,i,n,r){var s=i.root,a=t.as,o=void 0===a?"div":a,l=t.dir,c=t.theme,d=B$(t,U$,["dir"]),u=function(e){var t=e.theme,i=e.dir,n=PB(t)?"rtl":"ltr",r=PB()?"rtl":"ltr",s=i||n;return{rootDir:s!==n||s!==r?s:i,needsTheme:s!==n}}(t),h=u.rootDir,g=u.needsTheme,p=e.createElement(Tz,{providerRef:n},e.createElement(o,IU({dir:h},d,{className:s,ref:nG(n,r)})));return g&&(p=e.createElement(_z,{settings:{theme:wz(c,"rtl"===l)}},p)),p}(t,l,c,i))}));Az.displayName="FabricBase";var Pz={fontFamily:"inherit"},Rz={root:"ms-Fabric",bodyThemed:"ms-Fabric-bodyThemed"},Mz=nj(Az,(function(e){var t=e.applyTheme,i=e.className,n=e.preventBlanketFontInheritance,r=e.theme;return{root:[FV(Rz,r).root,r.fonts.medium,{color:r.palette.neutralPrimary},!n&&{"& button":Pz,"& input":Pz,"& textarea":Pz},t&&{color:r.semanticColors.bodyText,backgroundColor:r.semanticColors.bodyBackground},i],bodyThemed:[{backgroundColor:r.semanticColors.bodyBackground}]}}),void 0,{scope:"Fabric"}),Dz={},kz={},Oz="fluent-default-layer-host",Nz="#".concat(Oz);function Lz(e){Dz[e]&&Dz[e].forEach((function(e){return e()}))}var xz,Fz=oj(),Uz=e.forwardRef((function(t,i){var n,r=null!==(n=e.useContext(Sz))&&void 0!==n?n:yz,s=e.useRef(null),a=nG(s,i),o=e.useRef(),l=e.useRef(null),c=e.useContext(Gj),d=e.useState(!1),u=d[0],h=d[1],g=e.useCallback((function(e){var t,i=!!(null==(t=null==c?void 0:c.providerRef)?void 0:t.current)&&t.current.classList.contains(GV);e&&i&&e.classList.add(GV)}),[c]),p=t.children,m=t.className,f=t.eventBubblingEnabled,v=t.fabricProps,S=t.hostId,y=t.insertFirst,C=t.onLayerDidMount,T=void 0===C?function(){}:C,E=t.onLayerMounted,b=void 0===E?function(){}:E,_=t.onLayerWillUnmount,I=t.styles,w=t.theme,A=nG(l,null==v?void 0:v.ref,g),P=Fz(I,{theme:w,className:m,isNotHost:!S}),R=function(){null==_||_();var e=o.current;o.current=void 0,e&&e.parentNode&&e.parentNode.removeChild(e)},M=function(){var e,t,i,n,r=EB(s.current),a=(null===(t=null===(e=s.current)||void 0===e?void 0:e.getRootNode())||void 0===t?void 0:t.host)?null===(i=null==s?void 0:s.current)||void 0===i?void 0:i.getRootNode():void 0;if(r&&(r||a)){var l=function(e,t){var i,n;void 0===t&&(t=null);var r=null!=t?t:e;if(S){var s=function(e){var t=kz[e];return t&&t[0]||void 0}(S);return s?null!==(i=s.rootRef.current)&&void 0!==i?i:null:null!==(n=r.getElementById(S))&&void 0!==n?n:null}var a=Nz,o=a?r.querySelector(a):null;return o||(o=function(e,t){void 0===t&&(t=null);var i=e.createElement("div");return i.setAttribute("id",Oz),i.style.cssText="position:fixed;z-index:1000000",t?t.appendChild(i):null==e||e.body.appendChild(i),i}(e,t)),o}(r,a);if(l){l.__tabsterElementFlags||(l.__tabsterElementFlags={}),l.__tabsterElementFlags.noDirectAriaHidden=!0,R();var c=(null!==(n=l.ownerDocument)&&void 0!==n?n:r).createElement("div");c.className=P.root,c.setAttribute(pj,"true"),function(e,t){var i=e,n=t;i._virtual||(i._virtual={children:[]});var r=i._virtual.parent;if(r&&r!==t){var s=r._virtual.children.indexOf(i);s>-1&&r._virtual.children.splice(s,1)}i._virtual.parent=n||void 0,n&&(n._virtual||(n._virtual={children:[]}),n._virtual.children.push(i))}(c,s.current),y?l.insertBefore(c,l.firstChild):l.appendChild(c),o.current=c,h(!0)}}};return iG((function(){M(),S&&function(e,t){Dz[e]||(Dz[e]=[]),Dz[e].push(t);var i=kz[e];if(i)for(var n=0,r=i;n<r.length;n++)r[n].notifyLayersChanged()}(S,M);var e=o.current?r(o.current):void 0;return function(){e&&e(),R(),S&&function(e,t){var i=Dz[e];if(i){var n=i.indexOf(t);n>=0&&(i.splice(n,1),0===i.length&&delete Dz[e])}var r=kz[e];if(r)for(var s=0,a=r;s<a.length;s++)a[s].notifyLayersChanged()}(S,M)}}),[S]),e.useEffect((function(){o.current&&u&&(null==b||b(),null==T||T(),h(!1))}),[u,b,T]),e.createElement("span",{className:"ms-layer",ref:a},o.current&&Cz.createPortal(e.createElement(Tz,{layerRoot:!0,providerRef:A},e.createElement(Mz,IU({},!f&&(xz||(xz={},["onClick","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOver","onMouseOut","onMouseUp","onTouchMove","onTouchStart","onTouchCancel","onTouchEnd","onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onInvalid","onSubmit"].forEach((function(e){return xz[e]=Bz}))),xz),v,{className:V$(P.content,null==v?void 0:v.className),ref:A}),p)),o.current))}));Uz.displayName="LayerBase";var Bz=function(e){e.eventPhase===Event.BUBBLING_PHASE&&"mouseenter"!==e.type&&"mouseleave"!==e.type&&"touchstart"!==e.type&&"touchend"!==e.type&&e.stopPropagation()},Vz={root:"ms-Layer",rootNoHost:"ms-Layer--fixed",content:"ms-Layer-content"},Hz=nj(Uz,(function(e){var t=e.className,i=e.isNotHost,n=e.theme,r=FV(Vz,n);return{root:[r.root,n.fonts.medium,i&&[r.rootNoHost,{position:"fixed",zIndex:jV.Layer,top:0,left:0,bottom:0,right:0,visibility:"hidden"}],t],content:[r.content,{visibility:"visible"}]}}),void 0,{scope:"Layer",fields:["hostId","theme","styles"]}),$z=e.forwardRef((function(t,i){var n=t.layerProps,r=t.doNotLayer,s=wU(t,["layerProps","doNotLayer"]),a=e.createElement(vz,IU({},s,{doNotLayer:r,ref:i}));return r?a:e.createElement(Hz,IU({},n),a)}));$z.displayName="Callout";var jz,Gz=function(t){var i=t.item,n=t.classNames,r=i.iconProps;return e.createElement(mG,IU({},r,{className:n.icon}))},qz=function(e){var t=e.item;return e.hasIcons?t.onRenderIcon?t.onRenderIcon(e,Gz):Gz(e):null},zz=function(t){var i=t.onCheckmarkClick,n=t.item,r=t.classNames,s=dq(n);return i?e.createElement(mG,{iconName:!1!==n.canCheck&&s?"CheckMark":"",className:r.checkmarkIcon,onClick:function(e){return i(n,e)}}):null},Wz=function(t){var i=t.item,n=t.classNames;return i.text||i.name?e.createElement("span",{className:n.label},i.text||i.name):null},Kz=function(t){var i=t.item,n=t.classNames;return i.secondaryText?e.createElement("span",{className:n.secondaryText},i.secondaryText):null},Jz=function(t){var i=t.item,n=t.classNames,r=t.theme;return uq(i)?e.createElement(mG,IU({iconName:PB(r)?"ChevronLeft":"ChevronRight"},i.submenuIconProps,{className:n.subMenuIcon})):null},Yz=function(t){function i(e){var i=t.call(this,e)||this;return i.openSubMenu=function(){var e=i.props,t=e.item,n=e.openSubMenu,r=e.getSubmenuTarget;if(r){var s=r();uq(t)&&n&&s&&n(t,s)}},i.dismissSubMenu=function(){var e=i.props,t=e.item,n=e.dismissSubMenu;uq(t)&&n&&n()},i.dismissMenu=function(e){var t=i.props.dismissMenu;t&&t(void 0,e)},Ij(i),i}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.item,n=t.classNames,r=i.onRenderContent||this._renderLayout;return e.createElement("div",{className:i.split?n.linkContentMenu:n.linkContent},r(this.props,{renderCheckMarkIcon:zz,renderItemIcon:qz,renderItemName:Wz,renderSecondaryText:Kz,renderSubMenuIcon:Jz}))},i.prototype._renderLayout=function(t,i){return e.createElement(e.Fragment,null,i.renderCheckMarkIcon(t),i.renderItemIcon(t),i.renderItemName(t),i.renderSecondaryText(t),i.renderSubMenuIcon(t))},i}(e.Component),Qz=SB((function(e){return e$({wrapper:{display:"inline-flex",height:"100%",alignItems:"center"},divider:{width:1,height:"100%",backgroundColor:e.palette.neutralTertiaryAlt}})})),Zz=36,Xz=$V(0,639),eW=SB((function(e){var t,i,n,r,s,a=e.semanticColors,o=e.fonts,l=e.palette,c=a.menuItemBackgroundHovered,d=a.menuItemTextHovered,u=a.menuItemBackgroundPressed,h=a.bodyDivider;return ZH({item:[o.medium,{color:a.bodyText,position:"relative",boxSizing:"border-box"}],divider:{display:"block",height:"1px",backgroundColor:h,position:"relative"},root:[KV(e),o.medium,{color:a.bodyText,backgroundColor:"transparent",border:"none",width:"100%",height:Zz,lineHeight:Zz,display:"block",cursor:"pointer",padding:"0px 8px 0 4px",textAlign:"left"}],rootDisabled:{color:a.disabledBodyText,cursor:"default",pointerEvents:"none",selectors:(t={},t[UV]={color:"GrayText",opacity:1},t)},rootHovered:{backgroundColor:c,color:d,selectors:{".ms-ContextualMenu-icon":{color:l.themeDarkAlt},".ms-ContextualMenu-submenuIcon":{color:l.neutralPrimary}}},rootFocused:{backgroundColor:l.white},rootChecked:{selectors:{".ms-ContextualMenu-checkmarkIcon":{color:l.neutralPrimary}}},rootPressed:{backgroundColor:u,selectors:{".ms-ContextualMenu-icon":{color:l.themeDark},".ms-ContextualMenu-submenuIcon":{color:l.neutralPrimary}}},rootExpanded:{backgroundColor:u,color:a.bodyTextChecked,selectors:(i={".ms-ContextualMenu-submenuIcon":(n={},n[UV]={color:"inherit"},n)},i[UV]=IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)},linkContent:{whiteSpace:"nowrap",height:"inherit",display:"flex",alignItems:"center",maxWidth:"100%"},anchorLink:{padding:"0px 8px 0 4px",textRendering:"auto",color:"inherit",letterSpacing:"normal",wordSpacing:"normal",textTransform:"none",textIndent:"0px",textShadow:"none",textDecoration:"none",boxSizing:"border-box"},label:{margin:"0 4px",verticalAlign:"middle",display:"inline-block",flexGrow:"1",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"},secondaryText:{color:e.palette.neutralSecondary,paddingLeft:"20px",textAlign:"right"},icon:{display:"inline-block",minHeight:"1px",maxHeight:Zz,fontSize:kV.medium,width:kV.medium,margin:"0 4px",verticalAlign:"middle",flexShrink:"0",selectors:(r={},r[Xz]={fontSize:kV.large,width:kV.large},r)},iconColor:{color:a.menuIcon},iconDisabled:{color:a.disabledBodyText},checkmarkIcon:{color:a.bodySubtext},subMenuIcon:{height:Zz,lineHeight:Zz,color:l.neutralSecondary,textAlign:"center",display:"inline-block",verticalAlign:"middle",flexShrink:"0",fontSize:kV.small,selectors:(s={":hover":{color:l.neutralPrimary},":active":{color:l.neutralPrimary}},s[Xz]={fontSize:kV.medium},s)},splitButtonFlexContainer:[KV(e),{display:"flex",height:Zz,flexWrap:"nowrap",justifyContent:"center",alignItems:"flex-start"}]})})),tW="28px",iW=$V(0,639),nW=SB((function(e){var t;return e$(Qz(e),{wrapper:{position:"absolute",right:28,selectors:(t={},t[iW]={right:32},t)},divider:{height:16,width:1}})})),rW={item:"ms-ContextualMenu-item",divider:"ms-ContextualMenu-divider",root:"ms-ContextualMenu-link",isChecked:"is-checked",isExpanded:"is-expanded",isDisabled:"is-disabled",linkContent:"ms-ContextualMenu-linkContent",linkContentMenu:"ms-ContextualMenu-linkContent",icon:"ms-ContextualMenu-icon",iconColor:"ms-ContextualMenu-iconColor",checkmarkIcon:"ms-ContextualMenu-checkmarkIcon",subMenuIcon:"ms-ContextualMenu-submenuIcon",label:"ms-ContextualMenu-itemText",secondaryText:"ms-ContextualMenu-secondaryText",splitMenu:"ms-ContextualMenu-splitMenu",screenReaderText:"ms-ContextualMenu-screenReaderText"},sW=SB((function(e,t,i,n,r,s,a,o,l,c,d,u){var h,g,p,m,f=eW(e),v=FV(rW,e);return e$({item:[v.item,f.item,a],divider:[v.divider,f.divider,o],root:[v.root,f.root,n&&[v.isChecked,f.rootChecked],r&&f.anchorLink,i&&[v.isExpanded,f.rootExpanded],t&&[v.isDisabled,f.rootDisabled],!t&&!i&&[{selectors:(h={":hover":f.rootHovered,":active":f.rootPressed},h[".".concat(GV," &:focus, .").concat(GV," &:focus:hover, :host(.").concat(GV,") &:focus, :host(.").concat(GV,") &:focus:hover")]=f.rootFocused,h[".".concat(GV," &:hover, :host(.").concat(GV,") &:hover")]={background:"inherit;"},h)}],u],splitPrimary:[f.root,{width:"calc(100% - ".concat(tW,")")},n&&["is-checked",f.rootChecked],(t||d)&&["is-disabled",f.rootDisabled],!(t||d)&&!n&&[{selectors:(g={":hover":f.rootHovered},g[":hover ~ .".concat(v.splitMenu)]=f.rootHovered,g[":active"]=f.rootPressed,g[".".concat(GV," &:focus, .").concat(GV," &:focus:hover, :host(.").concat(GV,") &:focus, :host(.").concat(GV,") &:focus:hover")]=f.rootFocused,g[".".concat(GV," &:hover, :host(.").concat(GV,") &:hover")]={background:"inherit;"},g)}]],splitMenu:[v.splitMenu,f.root,{flexBasis:"0",padding:"0 8px",minWidth:tW},i&&["is-expanded",f.rootExpanded],t&&["is-disabled",f.rootDisabled],!t&&!i&&[{selectors:(p={":hover":f.rootHovered,":active":f.rootPressed},p[".".concat(GV," &:focus, .").concat(GV," &:focus:hover, :host(.").concat(GV,") &:focus, :host(.").concat(GV,") &:focus:hover")]=f.rootFocused,p[".".concat(GV," &:hover, :host(.").concat(GV,") &:hover")]={background:"inherit;"},p)}]],anchorLink:f.anchorLink,linkContent:[v.linkContent,f.linkContent],linkContentMenu:[v.linkContentMenu,f.linkContent,{justifyContent:"center"}],icon:[v.icon,s&&f.iconColor,f.icon,l,t&&[v.isDisabled,f.iconDisabled]],iconColor:f.iconColor,checkmarkIcon:[v.checkmarkIcon,s&&f.checkmarkIcon,f.icon,l],subMenuIcon:[v.subMenuIcon,f.subMenuIcon,c,i&&{color:e.palette.neutralPrimary},t&&[f.iconDisabled]],label:[v.label,f.label],secondaryText:[v.secondaryText,f.secondaryText],splitContainer:[f.splitButtonFlexContainer,!t&&!n&&[{selectors:(m={},m[".".concat(GV," &:focus, .").concat(GV," &:focus:hover, :host(.").concat(GV,") &:focus, :host(.").concat(GV,") &:focus:hover")]=f.rootFocused,m)}]],screenReaderText:[v.screenReaderText,f.screenReaderText,LV,{visibility:"hidden"}]})})),aW=function(e){var t=e.theme,i=e.disabled,n=e.expanded,r=e.checked,s=e.isAnchorLink,a=e.knownIcon,o=e.itemClassName,l=e.dividerClassName,c=e.iconClassName,d=e.subMenuClassName,u=e.primaryDisabled,h=e.className;return sW(t,i,n,r,s,a,o,l,c,d,u,h)},oW=nj(Yz,aW,void 0,{scope:"ContextualMenuItem"}),lW=function(e){function t(t){var i=e.call(this,t)||this;return i._onItemMouseEnter=function(e){var t=i.props,n=t.item,r=t.onItemMouseEnter;r&&r(n,e,e.currentTarget)},i._onItemClick=function(e){var t=i.props,n=t.item,r=t.onItemClickBase;r&&r(n,e,e.currentTarget)},i._onItemMouseLeave=function(e){var t=i.props,n=t.item,r=t.onItemMouseLeave;r&&r(n,e)},i._onItemKeyDown=function(e){var t=i.props,n=t.item,r=t.onItemKeyDown;r&&r(n,e)},i._onItemMouseMove=function(e){var t=i.props,n=t.item,r=t.onItemMouseMove;r&&r(n,e,e.currentTarget)},i._getSubmenuTarget=function(){},Ij(i),i}return _U(t,e),t.prototype.shouldComponentUpdate=function(e){return!Dj(e,this.props)},t}(e.Component);function cW(t){var i=e.useRef();return e.useEffect((function(){i.current=t})),i.current}!function(e){e.KEYTIP_ADDED="keytipAdded",e.KEYTIP_REMOVED="keytipRemoved",e.KEYTIP_UPDATED="keytipUpdated",e.PERSISTED_KEYTIP_ADDED="persistedKeytipAdded",e.PERSISTED_KEYTIP_REMOVED="persistedKeytipRemoved",e.PERSISTED_KEYTIP_EXECUTE="persistedKeytipExecute",e.ENTER_KEYTIP_MODE="enterKeytipMode",e.EXIT_KEYTIP_MODE="exitKeytipMode"}(jz||(jz={}));var dW=function(){function e(){this.keytips={},this.persistedKeytips={},this.sequenceMapping={},this.inKeytipMode=!1,this.shouldEnterKeytipMode=!0,this.delayUpdatingKeytipChange=!1}return e.getInstance=function(){return this._instance},e.prototype.init=function(e){this.delayUpdatingKeytipChange=e},e.prototype.register=function(e,t){void 0===t&&(t=!1);var i=e;t||(i=this.addParentOverflow(e),this.sequenceMapping[i.keySequences.toString()]=i);var n=this._getUniqueKtp(i);if(t?this.persistedKeytips[n.uniqueID]=n:this.keytips[n.uniqueID]=n,this.inKeytipMode||!this.delayUpdatingKeytipChange){var r=t?jz.PERSISTED_KEYTIP_ADDED:jz.KEYTIP_ADDED;Lj.raise(this,r,{keytip:i,uniqueID:n.uniqueID})}return n.uniqueID},e.prototype.update=function(e,t){var i=this.addParentOverflow(e),n=this._getUniqueKtp(i,t),r=this.keytips[t];r&&(n.keytip.visible=r.keytip.visible,this.keytips[t]=n,delete this.sequenceMapping[r.keytip.keySequences.toString()],this.sequenceMapping[n.keytip.keySequences.toString()]=n.keytip,!this.inKeytipMode&&this.delayUpdatingKeytipChange||Lj.raise(this,jz.KEYTIP_UPDATED,{keytip:n.keytip,uniqueID:n.uniqueID}))},e.prototype.unregister=function(e,t,i){void 0===i&&(i=!1),i?delete this.persistedKeytips[t]:delete this.keytips[t],!i&&delete this.sequenceMapping[e.keySequences.toString()];var n=i?jz.PERSISTED_KEYTIP_REMOVED:jz.KEYTIP_REMOVED;!this.inKeytipMode&&this.delayUpdatingKeytipChange||Lj.raise(this,n,{keytip:e,uniqueID:t})},e.prototype.enterKeytipMode=function(){Lj.raise(this,jz.ENTER_KEYTIP_MODE)},e.prototype.exitKeytipMode=function(){Lj.raise(this,jz.EXIT_KEYTIP_MODE)},e.prototype.getKeytips=function(){var e=this;return Object.keys(this.keytips).map((function(t){return e.keytips[t].keytip}))},e.prototype.addParentOverflow=function(e){var t=PU([],e.keySequences,!0);if(t.pop(),0!==t.length){var i=this.sequenceMapping[t.toString()];if(i&&i.overflowSetSequence)return IU(IU({},e),{overflowSetSequence:i.overflowSetSequence})}return e},e.prototype.menuExecute=function(e,t){Lj.raise(this,jz.PERSISTED_KEYTIP_EXECUTE,{overflowButtonSequences:e,keytipSequences:t})},e.prototype._getUniqueKtp=function(e,t){return void 0===t&&(t=u$()),{keytip:IU({},e),uniqueID:t}},e._instance=new e,e}();function uW(e){return e.reduce((function(e,t){return e+"-"+t.split("").join("-")}),"ktp")}var hW=function(t){var i,n=t.children,r=function(t){var i=e.useRef(),n=t.keytipProps?IU({disabled:t.disabled},t.keytipProps):void 0,r=Xq(dW.getInstance()),s=cW(t);iG((function(){i.current&&n&&((null==s?void 0:s.keytipProps)!==t.keytipProps||(null==s?void 0:s.disabled)!==t.disabled)&&r.update(n,i.current)})),iG((function(){return n&&(i.current=r.register(n)),function(){n&&r.unregister(n,i.current)}}),[]);var a={ariaDescribedBy:t.ariaDescribedBy,keytipId:void 0};return n&&(a=function(e,t,i){var n=e.addParentOverflow(t),r=tG(i,function(e){var t=" ktp-layer-id";return e.length?t+" "+uW(e):t}(n.keySequences)),s=PU([],n.keySequences,!0);return n.overflowSetSequence&&(s=function(e,t){var i,n,r;return i=t.length-1,n=PU([],t,!0).pop(),(r=PU([],e,!0).slice()).splice(i,0,n),r}(s,n.overflowSetSequence)),{ariaDescribedBy:r,keytipId:uW(s)}}(r,n,t.ariaDescribedBy)),a}(wU(t,["children"])),s=r.keytipId,a=r.ariaDescribedBy;return n(((i={})["data-ktp-target"]=s,i["data-ktp-execute-target"]=s,i["aria-describedby"]=a,i))},gW=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._anchor=e.createRef(),i._getMemoizedMenuButtonKeytipProps=SB((function(e){return IU(IU({},e),{hasMenu:!0})})),i._getSubmenuTarget=function(){return i._anchor.current?i._anchor.current:void 0},i._onItemClick=function(e){var t=i.props,n=t.item,r=t.onItemClick;r&&r(n,e)},i._renderAriaDescription=function(t,n){return t?e.createElement("span",{id:i._ariaDescriptionId,className:n},t):null},i}return _U(i,t),i.prototype.render=function(){var t=this,i=this.props,n=i.item,r=i.classNames,s=i.index,a=i.focusableElementIndex,o=i.totalItemCount,l=i.hasCheckmarks,c=i.hasIcons,d=i.expandedMenuItemKey,u=i.onItemClick,h=i.openSubMenu,g=i.dismissSubMenu,p=i.dismissMenu,m=oW;this.props.item.contextualMenuItemAs&&(m=cq(this.props.item.contextualMenuItemAs,m)),this.props.contextualMenuItemAs&&(m=cq(this.props.contextualMenuItemAs,m));var f=n.rel;n.target&&"_blank"===n.target.toLowerCase()&&(f=f||"nofollow noopener noreferrer");var v=uq(n),S=B$(n,b$),y=hq(n),C=n.itemProps,T=n.ariaDescription,E=n.keytipProps;E&&v&&(E=this._getMemoizedMenuButtonKeytipProps(E)),T&&(this._ariaDescriptionId=u$());var b=tG(n.ariaDescribedBy,T?this._ariaDescriptionId:void 0,S["aria-describedby"]),_={"aria-describedby":b};return e.createElement("div",null,e.createElement(hW,{keytipProps:n.keytipProps,ariaDescribedBy:b,disabled:y},(function(i){return e.createElement("a",IU({},_,S,i,{ref:t._anchor,href:n.href,target:n.target,rel:f,className:r.root,role:"menuitem","aria-haspopup":v||void 0,"aria-expanded":v?n.key===d:void 0,"aria-posinset":a+1,"aria-setsize":o,"aria-disabled":hq(n),style:n.style,onClick:t._onItemClick,onMouseEnter:t._onItemMouseEnter,onMouseLeave:t._onItemMouseLeave,onMouseMove:t._onItemMouseMove,onKeyDown:v?t._onItemKeyDown:void 0}),e.createElement(m,IU({componentRef:n.componentRef,item:n,classNames:r,index:s,onCheckmarkClick:l&&u?u:void 0,hasIcons:c,openSubMenu:h,dismissSubMenu:g,dismissMenu:p,getSubmenuTarget:t._getSubmenuTarget},C)),t._renderAriaDescription(T,r.screenReaderText))})))},i}(lW),pW=oj(),mW=e.forwardRef((function(t,i){var n=t.styles,r=t.theme,s=t.getClassNames,a=t.className,o=pW(n,{theme:r,getClassNames:s,className:a});return e.createElement("span",{className:o.wrapper,ref:i},e.createElement("span",{className:o.divider}))}));mW.displayName="VerticalDividerBase";var fW,vW=nj(mW,(function(e){var t=e.theme,i=e.getClassNames,n=e.className;if(!t)throw new Error("Theme is undefined or null.");if(i){var r=i(t);return{wrapper:[r.wrapper],divider:[r.divider]}}return{wrapper:[{display:"inline-flex",height:"100%",alignItems:"center"},n],divider:[{width:1,height:"100%",backgroundColor:t.palette.neutralTertiaryAlt}]}}),void 0,{scope:"VerticalDivider"}),SW=function(t){function i(i){var n=t.call(this,i)||this;return n._getMemoizedMenuButtonKeytipProps=SB((function(e){return IU(IU({},e),{hasMenu:!0})})),n._onItemKeyDown=function(e){var t=n.props,i=t.item,r=t.onItemKeyDown;e.which===fj?(n._executeItemClick(e),e.preventDefault(),e.stopPropagation()):r&&r(i,e)},n._getSubmenuTarget=function(){return n._splitButton},n._renderAriaDescription=function(t,i){return t?e.createElement("span",{id:n._ariaDescriptionId,className:i},t):null},n._onItemMouseEnterPrimary=function(e){var t=n.props,i=t.item,r=t.onItemMouseEnter;r&&r(IU(IU({},i),{subMenuProps:void 0,items:void 0}),e,n._splitButton)},n._onItemMouseEnterIcon=function(e){var t=n.props,i=t.item,r=t.onItemMouseEnter;r&&r(i,e,n._splitButton)},n._onItemMouseMovePrimary=function(e){var t=n.props,i=t.item,r=t.onItemMouseMove;r&&r(IU(IU({},i),{subMenuProps:void 0,items:void 0}),e,n._splitButton)},n._onItemMouseMoveIcon=function(e){var t=n.props,i=t.item,r=t.onItemMouseMove;r&&r(i,e,n._splitButton)},n._onIconItemClick=function(e){var t=n.props,i=t.item,r=t.onItemClickBase;r&&r(i,e,n._splitButton?n._splitButton:e.currentTarget)},n._executeItemClick=function(e){var t=n.props,i=t.item,r=t.executeItemClick,s=t.onItemClick;if(!i.disabled&&!i.isDisabled)return n._processingTouch&&!i.canCheck&&s?s(i,e):void(r&&r(i,e))},n._onTouchStart=function(e){n._splitButton&&!("onpointerdown"in n._splitButton)&&n._handleTouchAndPointerEvent(e)},n._onPointerDown=function(e){"touch"===e.pointerType&&(n._handleTouchAndPointerEvent(e),e.preventDefault(),e.stopImmediatePropagation())},n._async=new Mj(n),n._events=new Lj(n),n._dismissLabelId=u$(),n}return _U(i,t),i.prototype.componentDidMount=function(){this._splitButton&&"onpointerdown"in this._splitButton&&this._events.on(this._splitButton,"pointerdown",this._onPointerDown,!0)},i.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},i.prototype.render=function(){var t,i=this,n=this.props,r=n.item,s=n.classNames,a=n.index,o=n.focusableElementIndex,l=n.totalItemCount,c=n.hasCheckmarks,d=n.hasIcons,u=n.onItemMouseLeave,h=n.expandedMenuItemKey,g=uq(r),p=r.keytipProps;p&&(p=this._getMemoizedMenuButtonKeytipProps(p));var m=r.ariaDescription;m&&(this._ariaDescriptionId=u$());var f=null!==(t=dq(r))&&void 0!==t?t:void 0;return e.createElement(hW,{keytipProps:p,disabled:hq(r)},(function(t){return e.createElement("div",{"data-ktp-target":t["data-ktp-target"],ref:function(e){return i._splitButton=e},role:gq(r),"aria-label":r.ariaLabel,className:s.splitContainer,"aria-disabled":hq(r),"aria-expanded":g?r.key===h:void 0,"aria-haspopup":!0,"aria-describedby":tG(r.ariaDescribedBy,m?i._ariaDescriptionId:void 0,t["aria-describedby"]),"aria-checked":f,"aria-posinset":o+1,"aria-setsize":l,onMouseEnter:i._onItemMouseEnterPrimary,onMouseLeave:u?u.bind(i,IU(IU({},r),{subMenuProps:null,items:null})):void 0,onMouseMove:i._onItemMouseMovePrimary,onKeyDown:i._onItemKeyDown,onClick:i._executeItemClick,onTouchStart:i._onTouchStart,tabIndex:0,"data-is-focusable":!0,"aria-roledescription":r["aria-roledescription"]},i._renderSplitPrimaryButton(r,s,a,c,d),i._renderSplitDivider(r),i._renderSplitIconButton(r,s,a,t),i._renderAriaDescription(m,s.screenReaderText))}))},i.prototype._renderSplitPrimaryButton=function(t,i,n,r,s){var a=this.props,o=a.contextualMenuItemAs,l=void 0===o?oW:o,c=a.onItemClick,d={key:t.key,disabled:hq(t)||t.primaryDisabled,name:t.name,text:t.text||t.name,secondaryText:t.secondaryText,className:i.splitPrimary,canCheck:t.canCheck,isChecked:t.isChecked,checked:t.checked,iconProps:t.iconProps,id:this._dismissLabelId,onClick:t.onClick,onRenderIcon:t.onRenderIcon,data:t.data,"data-is-focusable":!1},u=t.itemProps;return e.createElement("button",IU({},B$(d,_$)),e.createElement(l,IU({"data-is-focusable":!1,item:d,classNames:i,index:n,onCheckmarkClick:r&&c?c:void 0,hasIcons:s},u)))},i.prototype._renderSplitDivider=function(t){var i=t.getSplitButtonVerticalDividerClassNames||nW;return e.createElement(vW,{getClassNames:i})},i.prototype._renderSplitIconButton=function(t,i,n,r){var s=this.props,a=s.onItemMouseLeave,o=s.onItemMouseDown,l=s.openSubMenu,c=s.dismissSubMenu,d=s.dismissMenu,u=oW;this.props.item.contextualMenuItemAs&&(u=cq(this.props.item.contextualMenuItemAs,u)),this.props.contextualMenuItemAs&&(u=cq(this.props.contextualMenuItemAs,u));var h={onClick:this._onIconItemClick,disabled:hq(t),className:i.splitMenu,subMenuProps:t.subMenuProps,submenuIconProps:t.submenuIconProps,split:!0,key:t.key,"aria-labelledby":this._dismissLabelId},g=IU(IU({},B$(h,_$)),{onMouseEnter:this._onItemMouseEnterIcon,onMouseLeave:a?a.bind(this,t):void 0,onMouseDown:function(e){return o?o(t,e):void 0},onMouseMove:this._onItemMouseMoveIcon,"data-is-focusable":!1,"data-ktp-execute-target":r["data-ktp-execute-target"],"aria-haspopup":!0}),p=t.itemProps;return e.createElement("button",IU({},g),e.createElement(u,IU({componentRef:t.componentRef,item:h,classNames:i,index:n,hasIcons:!1,openSubMenu:l,dismissSubMenu:c,dismissMenu:d,getSubmenuTarget:this._getSubmenuTarget},p)))},i.prototype._handleTouchAndPointerEvent=function(e){var t=this,i=this.props.onTap;i&&i(e),this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout((function(){t._processingTouch=!1,t._lastTouchTimeoutId=void 0}),500)},i}(lW),yW=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._btn=e.createRef(),i._getMemoizedMenuButtonKeytipProps=SB((function(e){return IU(IU({},e),{hasMenu:!0})})),i._renderAriaDescription=function(t,n){return t?e.createElement("span",{id:i._ariaDescriptionId,className:n},t):null},i._getSubmenuTarget=function(){return i._btn.current?i._btn.current:void 0},i}return _U(i,t),i.prototype.render=function(){var t=this,i=this.props,n=i.item,r=i.classNames,s=i.index,a=i.focusableElementIndex,o=i.totalItemCount,l=i.hasCheckmarks,c=i.hasIcons,d=i.contextualMenuItemAs,u=i.expandedMenuItemKey,h=i.onItemMouseDown,g=i.onItemClick,p=i.openSubMenu,m=i.dismissSubMenu,f=i.dismissMenu,v=oW;n.contextualMenuItemAs&&(v=cq(n.contextualMenuItemAs,v)),d&&(v=cq(d,v));var S=dq(n),y=null!==S,C=gq(n),T=uq(n),E=n.itemProps,b=n.ariaLabel,_=n.ariaDescription,I=B$(n,_$);delete I.disabled;var w=n.role||C;_&&(this._ariaDescriptionId=u$());var A=tG(n.ariaDescribedBy,_?this._ariaDescriptionId:void 0,I["aria-describedby"]),P={className:r.root,onClick:this._onItemClick,onKeyDown:T?this._onItemKeyDown:void 0,onMouseEnter:this._onItemMouseEnter,onMouseLeave:this._onItemMouseLeave,onMouseDown:function(e){return h?h(n,e):void 0},onMouseMove:this._onItemMouseMove,href:n.href,title:n.title,"aria-label":b,"aria-describedby":A,"aria-haspopup":T||void 0,"aria-expanded":T?n.key===u:void 0,"aria-posinset":a+1,"aria-setsize":o,"aria-disabled":hq(n),"aria-checked":"menuitemcheckbox"!==w&&"menuitemradio"!==w||!y?void 0:!!S,"aria-selected":"menuitem"===w&&y?!!S:void 0,role:w,style:n.style},R=n.keytipProps;return R&&T&&(R=this._getMemoizedMenuButtonKeytipProps(R)),e.createElement(hW,{keytipProps:R,ariaDescribedBy:A,disabled:hq(n)},(function(i){return e.createElement("button",IU({ref:t._btn},I,P,i),e.createElement(v,IU({componentRef:n.componentRef,item:n,classNames:r,index:s,onCheckmarkClick:l&&g?g:void 0,hasIcons:c,openSubMenu:p,dismissSubMenu:m,dismissMenu:f,getSubmenuTarget:t._getSubmenuTarget},E)),t._renderAriaDescription(_,r.screenReaderText))}))},i}(lW);!function(e){e[e.small=0]="small",e[e.medium=1]="medium",e[e.large=2]="large",e[e.xLarge=3]="xLarge",e[e.xxLarge=4]="xxLarge",e[e.xxxLarge=5]="xxxLarge",e[e.unknown=999]="unknown"}(fW||(fW={}));var CW,TW=[479,639,1023,1365,1919,99999999];function EW(){var e;return null!==(e=CW)&&void 0!==e?e:fW.large}function bW(e){try{return e.document.documentElement.clientWidth}catch(t){return e.innerWidth}}var _W=function(t,i){var n=e.useState(EW()),r=n[0],s=n[1],a=e.useCallback((function(){var e=function(e){var t=fW.small;if(!e)throw new Error("Content was rendered in a server environment without providing a default responsive mode. Call setResponsiveMode to define what the responsive mode is.");try{for(;bW(e)>TW[t];)t++}catch(e){t=EW()}return CW=t,t}(_B(t.current));r!==e&&s(e)}),[t,r]);return Wq(Jq(),"resize",a),e.useEffect((function(){void 0===i&&a()}),[i]),null!=i?i:r},IW=e.createContext({}),wW=oj(),AW=oj(),PW={items:[],shouldFocusOnMount:!0,gapSpace:0,directionalHint:7,beakWidth:16};function RW(e){for(var t=0,i=0,n=e;i<n.length;i++){var r=n[i];r.itemType!==fG.Divider&&r.itemType!==fG.Header&&(t+=r.customOnRenderListLength?r.customOnRenderListLength:1)}return t}function MW(e,t){var i=null==t?void 0:t.target,n=e.subMenuProps?e.subMenuProps.items:e.items;if(n){for(var r=[],s=0,a=n;s<a.length;s++){var o=a[s];if(o.preferMenuTargetAsEventTarget){var l=o.onClick,c=wU(o,["onClick"]);r.push(IU(IU({},c),{onClick:BW(l,i)}))}else r.push(o)}return r}}var DW="ContextualMenu",kW=SB((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){return XH.apply(void 0,PU([t,aW],e,!1))}}));function OW(t,i){var n=t.hidden,r=t.items,s=t.theme,a=t.className,o=t.id,l=t.target,c=e.useState(),d=c[0],u=c[1],h=e.useState(),g=h[0],p=h[1],m=e.useState(),f=m[0],v=m[1],S=g$(DW,o),y=e.useCallback((function(){v(void 0),u(void 0),p(void 0)}),[]),C=e.useCallback((function(e,t,i){var n=e.key;d!==n&&(t.focus(),v(i),u(n),p(t))}),[d]);e.useEffect((function(){n&&y()}),[n,y]);var T=function(t,i){var n=e.useRef(!1);e.useEffect((function(){return n.current=!0,function(){n.current=!1}}),[]);return function(e,r){r?t(e,r):n.current&&i()}}(i,y);return[d,C,function(){var e=UW(d,r),t=null;if(e&&(t={items:MW(e,{target:l}),target:g,onDismiss:T,isSubMenu:!0,id:S,shouldFocusOnMount:!0,shouldFocusOnContainer:f,directionalHint:PB(s)?8:11,className:a,gapSpace:0,isBeakVisible:!1},e.subMenuProps&&kj(t,e.subMenuProps),e.preferMenuTargetAsEventTarget)){var i=e.onItemClick;t.onItemClick=BW(i,l)}return t},T]}var NW=e.memo(e.forwardRef((function(t,i){var n,r=sq(PW,t),s=(r.ref,wU(r,["ref"])),a=e.useRef(null),o=zq(),l=g$(DW,s.id),c=function(e,t){var i;return null===(i=s.onDismiss)||void 0===i?void 0:i.call(s,e,t)},d=ez(s.target,a),u=d[0],h=d[1],g=function(t,i,n){var r=t.hidden,s=t.onRestoreFocus,a=e.useRef(),o=e.useCallback((function(e){var t,i;s?s(e):(null==e?void 0:e.documentContainsFocus)&&(null===(i=null===(t=a.current)||void 0===t?void 0:t.focus)||void 0===i||i.call(t))}),[s]);return iG((function(){var e,t;if(r)a.current&&(o({originalElement:a.current,containsFocus:!0,documentContainsFocus:(null===(t=EB())||void 0===t?void 0:t.hasFocus())||!1}),a.current=void 0);else{var s=null==i?void 0:i.document.activeElement;(null===(e=n.current)||void 0===e?void 0:e.contains(s))||"BODY"===s.tagName||(a.current=s)}}),[r,null==i?void 0:i.document.activeElement,o,n]),[o]}(s,h,a)[0],p=OW(s,c),m=p[0],f=p[1],v=p[2],S=p[3],y=function(t){var i=t.delayUpdateFocusOnHover,n=t.hidden,r=e.useRef(!i),s=e.useRef(!1);e.useEffect((function(){r.current=!i,s.current=!n&&!i&&s.current}),[i,n]);var a=e.useCallback((function(){i&&(r.current=!1)}),[i]);return[r,s,a]}(s),C=y[0],T=y[1],E=y[2],b=function(t){var i=e.useRef(!0),n=e.useRef();return[function(){i.current||void 0===n.current?i.current=!1:(t.clearTimeout(n.current),n.current=void 0),n.current=t.setTimeout((function(){i.current=!0}),250)},i]}(o),_=b[0],I=b[1],w=function(t,i){var n=t.subMenuHoverDelay,r=void 0===n?250:n,s=e.useRef(void 0),a=function(){void 0!==s.current&&(i.clearTimeout(s.current),s.current=void 0)};return[a,function(e){s.current=i.setTimeout((function(){e(),a()}),r)},s]}(s,o),A=w[0],P=w[1],R=w[2],M=_W(a,s.responsiveMode);!function(t){var i=t.hidden,n=void 0!==i&&i,r=t.onMenuDismissed,s=t.onMenuOpened,a=cW(n),o=e.useRef(s),l=e.useRef(r),c=e.useRef(t);o.current=s,l.current=r,c.current=t,e.useEffect((function(){var e,t;n&&!1===a?null===(e=l.current)||void 0===e||e.call(l,c.current):n||!1===a||null===(t=o.current)||void 0===t||t.call(o,c.current)}),[n,a]),e.useEffect((function(){return function(){var e;return null===(e=l.current)||void 0===e?void 0:e.call(l,c.current)}}),[])}(s);var D,k=function(t,i,n,r){var s=t.theme,a=t.isSubMenu,o=t.focusZoneProps,l=void 0===o?{}:o,c=l.checkForNoWrap,d=l.direction,u=void 0===d?yG.vertical:d,h=e.useRef(),g=function(e,t,n){var r=!1;return t(e)&&(i(e,n),e.preventDefault(),e.stopPropagation(),r=!0),r},p=function(e){return e.which===vj||function(e){var t=PB(s)?Tj:yj;return!(e.which!==t||!a||u!==yG.vertical&&(!c||MG(e.target,"data-no-horizontal-wrap")))}(e)||e.which===Cj&&(e.altKey||e.metaKey)},m=function(e){h.current=LW(e);var t=e.which===vj&&(nq()||rq());return g(e,p,t)},f=function(e){var t=h.current&&LW(e);return h.current=!1,!!t&&!(rq()||nq())};return[m,function(e){return g(e,f,!0)},function(e){if(!m(e)&&n.current){var t=!(!e.altKey&&!e.metaKey),i=e.which===Cj,r=e.which===Ej;if(!t&&(i||r)){var s=i?EG(n.current,n.current.lastChild,!0):TG(n.current,n.current.firstChild,!0);s&&(s.focus(),e.preventDefault(),e.stopPropagation())}}},function(e,t){var i=PB(s)?yj:Tj;e.disabled||t.which!==i&&t.which!==fj&&(t.which!==Ej||!t.altKey&&!t.metaKey)||(r(e,t.currentTarget),t.preventDefault())}]}(s,c,a,f),O=k[0],N=k[1],L=k[2],x=k[3],F=function(e,t,i,n,r,s,a,o,l,c,d,u,h){var g=e.target,p=function(){return!t.current||!s.current},m=function(e,t,i){var n=i||t.currentTarget;e.key!==a&&(c(),void 0===a&&n.focus(),uq(e)?(t.stopPropagation(),l((function(){n.focus(),d(e,n,!0)}))):l((function(){u(t),n.focus()})))},f=function(t,i,n){var r=MW(t,{target:g});if(c(),uq(t)||r&&r.length){if(t.key!==a){var s="boolean"==typeof e.shouldFocusOnContainer?e.shouldFocusOnContainer:"mouse"===i.nativeEvent.pointerType;d(t,n,s)}}else v(t,i);i.stopPropagation(),i.preventDefault()},v=function(t,i){if(!t.disabled&&!t.isDisabled){t.preferMenuTargetAsEventTarget&&VW(i,g);var n=!1;t.onClick?n=!!t.onClick(i,t):e.onItemClick&&(n=!!e.onItemClick(i,t)),!n&&i.defaultPrevented||h(i,!0)}};return[function(e,t,i){r.current&&(s.current=!0),p()||m(e,t,i)},function(e,a,o){var l=a.currentTarget;r.current&&(s.current=!0,t.current&&void 0===i.current&&l!==(null==n?void 0:n.document.activeElement)&&m(e,a,o))},function(e,t){var i;if(!p()&&(c(),void 0===a))if(o.current.setActive)try{o.current.setActive()}catch(e){}else null===(i=o.current)||void 0===i||i.focus()},function(e,t){f(e,t,t.currentTarget)},function(e,t){v(e,t),t.stopPropagation()},v,f]}(s,I,R,h,C,T,m,a,P,A,f,S,c),U=F[0],B=F[1],V=F[2],H=F[3],$=F[4],j=F[5],G=F[6],q=function(t,i,n){var r=0,s=t.items,a=t.totalItemCount,o=t.hasCheckmarks,l=t.hasIcons;return e.createElement("ul",{className:i.list,onKeyDown:O,onKeyUp:N,role:"presentation"},s.map((function(e,t){var n=z(e,t,r,a,o,l,i);if(e.itemType!==fG.Divider&&e.itemType!==fG.Header){var s=e.customOnRenderListLength?e.customOnRenderListLength:1;r+=s}return n})))},z=function(t,i,n,r,a,o,l){var c,d,u=[],h=t.iconProps||{iconName:"None"},g=t.getItemClassNames,p=t.itemProps,f=p?p.styles:void 0,v=t.itemType===fG.Divider?t.className:void 0,S=t.submenuIconProps?t.submenuIconProps.className:"";if(g)d=g(s.theme,hq(t),m===t.key,!!dq(t),!!t.href,"None"!==h.iconName,t.className,v,h.className,S,t.primaryDisabled);else{var y={theme:s.theme,disabled:hq(t),expanded:m===t.key,checked:!!dq(t),isAnchorLink:!!t.href,knownIcon:"None"!==h.iconName,itemClassName:t.className,dividerClassName:v,iconClassName:h.className,subMenuClassName:S,primaryDisabled:t.primaryDisabled};d=AW(kW(null===(c=l.subComponentStyles)||void 0===c?void 0:c.menuItem,f),y)}switch("-"!==t.text&&"-"!==t.name||(t.itemType=fG.Divider),t.itemType){case fG.Divider:u.push(J(i,d));break;case fG.Header:u.push(J(i,d));var C=Q(t,d,l,i,a,o);u.push(K(C,t.key||i,d,t.title));break;case fG.Section:u.push(W(t,d,l,i,a,o));break;default:var T=function(){return Y(t,d,i,n,r,a,o)},E=s.onRenderContextualMenuItem?s.onRenderContextualMenuItem(t,T):T();u.push(K(E,t.key||i,d,t.title))}return e.createElement(e.Fragment,{key:t.key},u)},W=function(t,i,n,r,s,a){var o=t.sectionProps;if(o){var c,d;if(o.title){var u=void 0,h="";if("string"==typeof o.title){var g=l+o.title.replace(/\s/g,"");u={key:"section-".concat(o.title,"-title"),itemType:fG.Header,text:o.title,id:g},h=g}else{var p=o.title.id||l+o.title.key.replace(/\s/g,"");u=IU(IU({},o.title),{id:p}),h=p}u&&(d={role:"group","aria-labelledby":h},c=Q(u,i,n,r,s,a))}if(o.items&&o.items.length>0){var m=0;return e.createElement("li",{role:"presentation",key:o.key||t.key||"section-".concat(r)},e.createElement("div",IU({},d),e.createElement("ul",{className:n.list,role:"presentation"},o.topDivider&&J(r,i,!0,!0),c&&K(c,t.key||r,i,t.title),o.items.map((function(e,t){var i=z(e,t,m,RW(o.items),s,a,n);if(e.itemType!==fG.Divider&&e.itemType!==fG.Header){var r=e.customOnRenderListLength?e.customOnRenderListLength:1;m+=r}return i})),o.bottomDivider&&J(r,i,!1,!0))))}}},K=function(t,i,n,r){return e.createElement("li",{role:"presentation",title:r,key:i,className:n.item},t)},J=function(t,i,n,r){return r||t>0?e.createElement("li",{role:"separator",key:"separator-"+t+(void 0===n?"":n?"-top":"-bottom"),className:i.divider,"aria-hidden":"true"}):null},Y=function(t,i,n,r,a,o,l){if(t.onRender)return t.onRender(IU({"aria-posinset":r+1,"aria-setsize":a},t),c);var d={item:t,classNames:i,index:n,focusableElementIndex:r,totalItemCount:a,hasCheckmarks:o,hasIcons:l,contextualMenuItemAs:s.contextualMenuItemAs,onItemMouseEnter:U,onItemMouseLeave:V,onItemMouseMove:B,onItemMouseDown:xW,executeItemClick:j,onItemKeyDown:x,expandedMenuItemKey:m,openSubMenu:f,dismissSubMenu:S,dismissMenu:c};if(t.href){var u=gW;return t.contextualMenuItemWrapperAs&&(u=cq(t.contextualMenuItemWrapperAs,u)),e.createElement(u,IU({},d,{onItemClick:$}))}if(t.split&&uq(t)){var h=SW;return t.contextualMenuItemWrapperAs&&(h=cq(t.contextualMenuItemWrapperAs,h)),e.createElement(h,IU({},d,{onItemClick:H,onItemClickBase:G,onTap:A}))}var g=yW;return t.contextualMenuItemWrapperAs&&(g=cq(t.contextualMenuItemWrapperAs,g)),e.createElement(g,IU({},d,{onItemClick:H,onItemClickBase:G}))},Q=function(t,i,n,r,a,o){var l=oW;t.contextualMenuItemAs&&(l=cq(t.contextualMenuItemAs,l)),s.contextualMenuItemAs&&(l=cq(s.contextualMenuItemAs,l));var c=t.itemProps,d=t.id,u=c&&B$(c,U$);return e.createElement("div",IU({id:d,className:n.header},u,{style:t.style}),e.createElement(l,IU({item:t,classNames:i,index:r,onCheckmarkClick:a?H:void 0,hasIcons:o},c)))},Z=s.isBeakVisible,X=s.items,ee=s.labelElementId,te=s.id,ie=s.className,ne=s.beakWidth,re=s.directionalHint,se=s.directionalHintForRTL,ae=s.alignTargetEdge,oe=s.gapSpace,le=s.coverTarget,ce=s.ariaLabel,de=s.doNotLayer,ue=s.target,he=s.bounds,ge=s.useTargetWidth,pe=s.useTargetAsMinWidth,me=s.directionalHintFixed,fe=s.shouldFocusOnMount,ve=s.shouldFocusOnContainer,Se=s.title,ye=s.styles,Ce=s.theme,Te=s.calloutProps,Ee=s.onRenderSubMenu,be=void 0===Ee?FW:Ee,_e=s.onRenderMenuList,Ie=void 0===_e?function(e,t){return q(e,Pe)}:_e,we=s.focusZoneProps,Ae=s.getMenuClassNames,Pe=Ae?Ae(Ce,ie):wW(ye,{theme:Ce,className:ie}),Re=function e(t){for(var i=0,n=t;i<n.length;i++){var r=n[i];if(r.iconProps)return!0;if(r.itemType===fG.Section&&r.sectionProps&&e(r.sectionProps.items))return!0}return!1}(X),Me=IU(IU({direction:yG.vertical,handleTabKey:1,isCircularNavigation:!0,"data-tabster":'{"uncontrolled": {}, "focusable": { "excludeFromMover": true }}'},we),{className:V$(Pe.root,null===(n=s.focusZoneProps)||void 0===n?void 0:n.className)}),De=function(e){return e.some((function(e){return!!e.canCheck||!(!e.sectionProps||!e.sectionProps.items.some((function(e){return!0===e.canCheck})))}))}(X),ke=m&&!0!==s.hidden?v():null;Z=void 0===Z?M<=fW.medium:Z;var Oe=u.current;if((ge||pe)&&Oe&&Oe.offsetWidth){var Ne=Oe.getBoundingClientRect().width-2;ge?D={width:Ne}:pe&&(D={minWidth:Ne})}if(X&&X.length>0){var Le=RW(X),xe=Pe.subComponentStyles?Pe.subComponentStyles.callout:void 0;return e.createElement(IW.Consumer,null,(function(t){return e.createElement($z,IU({styles:xe,onRestoreFocus:g},Te,{target:ue||t.target,isBeakVisible:Z,beakWidth:ne,directionalHint:re,directionalHintForRTL:se,gapSpace:oe,coverTarget:le,doNotLayer:de,className:V$("ms-ContextualMenu-Callout",Te&&Te.className),setInitialFocus:fe,onDismiss:s.onDismiss||t.onDismiss,onScroll:_,bounds:he,directionalHintFixed:me,alignTargetEdge:ae,hidden:s.hidden||t.hidden,ref:i}),e.createElement("div",{style:D,ref:a,id:te,className:Pe.container,tabIndex:ve?0:-1,onKeyDown:L,onKeyUp:N,onFocusCapture:E,"aria-label":ce,"aria-labelledby":ee,role:"menu"},Se&&e.createElement("div",{className:Pe.title}," ",Se," "),X&&X.length?function(t,i){var n=s.focusZoneAs,r=void 0===n?iq:n;return e.createElement(r,IU({},i),t)}(Ie({ariaLabel:ce,items:X,totalItemCount:Le,hasCheckmarks:De,hasIcons:Re,defaultMenuItemRenderer:function(e){return function(e,t){var i=e.index,n=e.focusableElementIndex,r=e.totalItemCount,s=e.hasCheckmarks,a=e.hasIcons;return z(e,i,n,r,s,a,t)}(e,Pe)},labelElementId:ee},(function(e,t){return q(e,Pe)})),Me):null,ke&&be(ke,FW)),e.createElement(Yj,null))}))}return null})),(function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||Dj(e,t)}));function LW(e){return 18===e.which||"Meta"===e.key}function xW(e,t){var i;null===(i=e.onMouseDown)||void 0===i||i.call(e,e,t)}function FW(e,t){throw Error("ContextualMenuBase: onRenderSubMenu callback is null or undefined. Please ensure to set `onRenderSubMenu` property either manually or with `styled` helper.")}function UW(e,t){for(var i=0,n=t;i<n.length;i++){var r=n[i];if(r.itemType===fG.Section&&r.sectionProps){var s=UW(e,r.sectionProps.items);if(s)return s}else if(r.key&&r.key===e)return r}}function BW(e,t){return e?function(i,n){return VW(i,t),e(i,n)}:e}function VW(e,t){e&&t&&(e.persist(),t instanceof Event?e.target=t.target:t instanceof Element&&(e.target=t))}NW.displayName="ContextualMenuBase";var HW={root:"ms-ContextualMenu",container:"ms-ContextualMenu-container",list:"ms-ContextualMenu-list",header:"ms-ContextualMenu-header",title:"ms-ContextualMenu-title",isopen:"is-open"};function $W(t){return e.createElement(jW,IU({},t))}var jW=nj(NW,(function(e){var t=e.className,i=e.theme,n=FV(HW,i),r=i.fonts,s=i.semanticColors,a=i.effects;return{root:[i.fonts.medium,n.root,n.isopen,{backgroundColor:s.menuBackground,minWidth:"180px"},t],container:[n.container,{selectors:{":focus":{outline:0}}}],list:[n.list,n.isopen,{listStyleType:"none",margin:"0",padding:"0"}],header:[n.header,r.small,{fontWeight:DV.semibold,color:s.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:Zz,lineHeight:Zz,cursor:"default",padding:"0px 6px",userSelect:"none",textAlign:"left"}],title:[n.title,{fontSize:r.mediumPlus.fontSize,paddingRight:"14px",paddingLeft:"14px",paddingBottom:"5px",paddingTop:"5px",backgroundColor:s.menuItemBackgroundPressed}],subComponentStyles:{callout:{root:{boxShadow:a.elevation8}},menuItem:{}}}}),(function(e){return{onRenderSubMenu:e.onRenderSubMenu?(t=e.onRenderSubMenu,i=$W,SG(t)(i)):$W};var t,i}),{scope:"ContextualMenu"}),GW=jW;GW.displayName="ContextualMenu";var qW={msButton:"ms-Button",msButtonHasMenu:"ms-Button--hasMenu",msButtonIcon:"ms-Button-icon",msButtonMenuIcon:"ms-Button-menuIcon",msButtonLabel:"ms-Button-label",msButtonDescription:"ms-Button-description",msButtonScreenReaderText:"ms-Button-screenReaderText",msButtonFlexContainer:"ms-Button-flexContainer",msButtonTextContainer:"ms-Button-textContainer"},zW=SB((function(e,t,i,n,r,s,a,o,l,c,d){var u,h,g=FV(qW,e||{}),p=c&&!d;return e$(t.__shadowConfig__,{root:[g.msButton,t.root,n,l&&["is-checked",t.rootChecked],p&&["is-expanded",t.rootExpanded,(u={},u[":hover .".concat(g.msButtonIcon)]=t.iconExpandedHovered,u[":hover .".concat(g.msButtonMenuIcon)]=t.menuIconExpandedHovered||t.rootExpandedHovered,u[":hover"]=t.rootExpandedHovered,u)],o&&[qW.msButtonHasMenu,t.rootHasMenu],a&&["is-disabled",t.rootDisabled],!a&&!p&&!l&&(h={":hover":t.rootHovered},h[":hover .".concat(g.msButtonLabel)]=t.labelHovered,h[":hover .".concat(g.msButtonIcon)]=t.iconHovered,h[":hover .".concat(g.msButtonDescription)]=t.descriptionHovered,h[":hover .".concat(g.msButtonMenuIcon)]=t.menuIconHovered,h[":focus"]=t.rootFocused,h[":active"]=t.rootPressed,h[":active .".concat(g.msButtonIcon)]=t.iconPressed,h[":active .".concat(g.msButtonDescription)]=t.descriptionPressed,h[":active .".concat(g.msButtonMenuIcon)]=t.menuIconPressed,h),a&&l&&[t.rootCheckedDisabled],!a&&l&&{":hover":t.rootCheckedHovered,":active":t.rootCheckedPressed},i],flexContainer:[g.msButtonFlexContainer,t.flexContainer],textContainer:[g.msButtonTextContainer,t.textContainer],icon:[g.msButtonIcon,r,t.icon,p&&t.iconExpanded,l&&t.iconChecked,a&&t.iconDisabled],label:[g.msButtonLabel,t.label,l&&t.labelChecked,a&&t.labelDisabled],menuIcon:[g.msButtonMenuIcon,s,t.menuIcon,l&&t.menuIconChecked,a&&!d&&t.menuIconDisabled,!a&&!p&&!l&&{":hover":t.menuIconHovered,":active":t.menuIconPressed},p&&["is-expanded",t.menuIconExpanded]],description:[g.msButtonDescription,t.description,l&&t.descriptionChecked,a&&t.descriptionDisabled],screenReaderText:[g.msButtonScreenReaderText,t.screenReaderText]})})),WW=SB((function(e,t,i,n,r){return{root:dB(e.splitButtonMenuButton,i&&[e.splitButtonMenuButtonExpanded],t&&[e.splitButtonMenuButtonDisabled],n&&!t&&[e.splitButtonMenuButtonChecked],r&&!t&&[{":focus":e.splitButtonMenuFocused}]),splitButtonContainer:dB(e.splitButtonContainer,!t&&n&&[e.splitButtonContainerChecked,{":hover":e.splitButtonContainerCheckedHovered}],!t&&!n&&[{":hover":e.splitButtonContainerHovered,":focus":e.splitButtonContainerFocused}],t&&e.splitButtonContainerDisabled),icon:dB(e.splitButtonMenuIcon,t&&e.splitButtonMenuIconDisabled,!t&&r&&e.splitButtonMenuIcon),flexContainer:dB(e.splitButtonFlexContainer),divider:dB("ms-SplitButton-divider",e.splitButtonDivider,(r||t)&&e.splitButtonDividerDisabled)}})),KW=function(t){function i(i){var n=t.call(this,i)||this;return n._buttonElement=e.createRef(),n._splitButtonContainer=e.createRef(),n._mergedRef=uj(),n._renderedVisibleMenu=!1,n._getMemoizedMenuButtonKeytipProps=SB((function(e){return IU(IU({},e),{hasMenu:!0})})),n._onRenderIcon=function(t,i){var r=n.props.iconProps;if(r&&(void 0!==r.iconName||r.imageProps)){var s=r.className,a=r.imageProps,o=wU(r,["className","imageProps"]);if(r.styles)return e.createElement(mG,IU({className:V$(n._classNames.icon,s),imageProps:a},o));if(r.iconName)return e.createElement(hG,IU({className:V$(n._classNames.icon,s)},o));if(a)return e.createElement(vG,IU({className:V$(n._classNames.icon,s),imageProps:a},o))}return null},n._onRenderTextContents=function(){var t=n.props,i=t.text,r=t.children,s=t.secondaryText,a=void 0===s?n.props.description:s,o=t.onRenderText,l=void 0===o?n._onRenderText:o,c=t.onRenderDescription,d=void 0===c?n._onRenderDescription:c;return i||"string"==typeof r||a?e.createElement("span",{className:n._classNames.textContainer},l(n.props,n._onRenderText),d(n.props,n._onRenderDescription)):[l(n.props,n._onRenderText),d(n.props,n._onRenderDescription)]},n._onRenderText=function(){var t=n.props.text,i=n.props.children;return void 0===t&&"string"==typeof i&&(t=i),n._hasText()?e.createElement("span",{key:n._labelId,className:n._classNames.label,id:n._labelId},t):null},n._onRenderChildren=function(){var e=n.props.children;return"string"==typeof e?null:e},n._onRenderDescription=function(t){var i=t.secondaryText,r=void 0===i?n.props.description:i;return r?e.createElement("span",{key:n._descriptionId,className:n._classNames.description,id:n._descriptionId},r):null},n._onRenderAriaDescription=function(){var t=n.props.ariaDescription;return t?e.createElement("span",{className:n._classNames.screenReaderText,id:n._ariaDescriptionId},t):null},n._onRenderMenuIcon=function(t){var i=n.props.menuIconProps;return e.createElement(hG,IU({iconName:"ChevronDown"},i,{className:n._classNames.menuIcon}))},n._onRenderMenu=function(t){var i=n.props.menuAs?cq(n.props.menuAs,GW):GW;return e.createElement(i,IU({},t))},n._onDismissMenu=function(e){var t=n.props.menuProps;t&&t.onDismiss&&t.onDismiss(e),e&&e.defaultPrevented||n._dismissMenu()},n._dismissMenu=function(){n._menuShouldFocusOnMount=void 0,n._menuShouldFocusOnContainer=void 0,n.setState({menuHidden:!0})},n._openMenu=function(e,t){void 0===t&&(t=!0),n.props.menuProps&&(n._menuShouldFocusOnContainer=e,n._menuShouldFocusOnMount=t,n._renderedVisibleMenu=!0,n.setState({menuHidden:!1}))},n._onToggleMenu=function(e){var t=!0;n.props.menuProps&&!1===n.props.menuProps.shouldFocusOnMount&&(t=!1),n.state.menuHidden?n._openMenu(e,t):n._dismissMenu()},n._onSplitContainerFocusCapture=function(e){var t=n._splitButtonContainer.current;!t||e.target&&mj(e.target,t)||t.focus()},n._onSplitButtonPrimaryClick=function(e){n.state.menuHidden||n._dismissMenu();var t=n._processingTouch&&!n.props.toggle;!t&&n.props.onClick?n.props.onClick(e):t&&n._onMenuClick(e)},n._onKeyDown=function(e){!n.props.disabled||e.which!==fj&&e.which!==Sj?n.props.disabled||(n.props.menuProps?n._onMenuKeyDown(e):void 0!==n.props.onKeyDown&&n.props.onKeyDown(e)):(e.preventDefault(),e.stopPropagation())},n._onKeyUp=function(e){n.props.disabled||void 0===n.props.onKeyUp||n.props.onKeyUp(e)},n._onKeyPress=function(e){n.props.disabled||void 0===n.props.onKeyPress||n.props.onKeyPress(e)},n._onMouseUp=function(e){n.props.disabled||void 0===n.props.onMouseUp||n.props.onMouseUp(e)},n._onMouseDown=function(e){n.props.disabled||void 0===n.props.onMouseDown||n.props.onMouseDown(e)},n._onClick=function(e){n.props.disabled||(n.props.menuProps?n._onMenuClick(e):void 0!==n.props.onClick&&n.props.onClick(e))},n._onSplitButtonContainerKeyDown=function(e){e.which===fj||e.which===Sj?n._buttonElement.current&&(n._buttonElement.current.click(),e.preventDefault(),e.stopPropagation()):n._onMenuKeyDown(e)},n._onMenuKeyDown=function(e){var t;if(!n.props.disabled){n.props.onKeyDown&&n.props.onKeyDown(e);var i=e.which===Cj,r=e.which===Ej;if(!e.defaultPrevented&&n._isValidMenuOpenKey(e)){var s=n.props.onMenuClick;s&&s(e,n.props),n._onToggleMenu(!1),e.preventDefault(),e.stopPropagation()}e.which!==fj&&e.which!==Sj||WV(!0,e.target,null===(t=n.context)||void 0===t?void 0:t.registeredProviders),e.altKey||e.metaKey||!i&&!r||!n.state.menuHidden&&n.props.menuProps&&((void 0!==n._menuShouldFocusOnMount?n._menuShouldFocusOnMount:n.props.menuProps.shouldFocusOnMount)||(e.preventDefault(),e.stopPropagation(),n._menuShouldFocusOnMount=!0,n.forceUpdate()))}},n._onTouchStart=function(){n._isSplitButton&&n._splitButtonContainer.current&&!("onpointerdown"in n._splitButtonContainer.current)&&n._handleTouchAndPointerEvent()},n._onMenuClick=function(e){var t=n.props,i=t.onMenuClick,r=t.menuProps;i&&i(e,n.props);var s="boolean"==typeof(null==r?void 0:r.shouldFocusOnContainer)?r.shouldFocusOnContainer:"mouse"===e.nativeEvent.pointerType;e.defaultPrevented||(n._onToggleMenu(s),e.preventDefault(),e.stopPropagation())},Ij(n),n._async=new Mj(n),n._events=new Lj(n),n.props.split,n._labelId=u$(),n._descriptionId=u$(),n._ariaDescriptionId=u$(),n.state={menuHidden:!0},n}return _U(i,t),Object.defineProperty(i.prototype,"_isSplitButton",{get:function(){return!!this.props.menuProps&&!!this.props.onClick&&!0===this.props.split},enumerable:!1,configurable:!0}),i.prototype.render=function(){var e,t=this.props,i=t.ariaDescription,n=t.ariaLabel,r=t.ariaHidden,s=t.className,a=t.disabled,o=t.allowDisabledFocus,l=t.primaryDisabled,c=t.secondaryText,d=void 0===c?this.props.description:c,u=t.href,h=t.iconProps,g=t.menuIconProps,p=t.styles,m=t.checked,f=t.variantClassName,v=t.theme,S=t.toggle,y=t.getClassNames,C=t.role,T=this.state.menuHidden,E=a||l;this._classNames=y?y(v,s,f,h&&h.className,g&&g.className,E,m,!T,!!this.props.menuProps,this.props.split,!!o):zW(v,p,s,f,h&&h.className,g&&g.className,E,!!this.props.menuProps,m,!T,this.props.split);var b=this,_=b._ariaDescriptionId,I=b._labelId,w=b._descriptionId,A=!E&&!!u,P=A?"a":"button",R=B$(kj(A?{}:{type:"button"},this.props.rootProps,this.props),A?b$:_$,["disabled"]),M=n||R["aria-label"],D=void 0;i?D=_:d&&this.props.onRenderDescription!==Fj?D=w:R["aria-describedby"]&&(D=R["aria-describedby"]);var k=void 0;R["aria-labelledby"]?k=R["aria-labelledby"]:D&&!M&&(k=this._hasText()?I:void 0);var O=!(!1===this.props["data-is-focusable"]||a&&!o||this._isSplitButton),N="menuitemcheckbox"===C||"checkbox"===C,L=N||!0===S?!!m:void 0,x=kj(R,((e={className:this._classNames.root,ref:this._mergedRef(this.props.elementRef,this._buttonElement),disabled:E&&!o,onKeyDown:this._onKeyDown,onKeyPress:this._onKeyPress,onKeyUp:this._onKeyUp,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onClick:this._onClick,"aria-label":M,"aria-labelledby":k,"aria-describedby":D,"aria-disabled":E,"data-is-focusable":O})[N?"aria-checked":"aria-pressed"]=L,e));if(r&&(x["aria-hidden"]=!0),this._isSplitButton)return this._onRenderSplitButtonContent(P,x);if(this.props.menuProps){var F=this.props.menuProps.id,U=void 0===F?"".concat(this._labelId,"-menu"):F;kj(x,{"aria-expanded":!T,"aria-controls":T?null:U,"aria-haspopup":!0})}return this._onRenderContent(P,x)},i.prototype.componentDidMount=function(){this._isSplitButton&&this._splitButtonContainer.current&&("onpointerdown"in this._splitButtonContainer.current&&this._events.on(this._splitButtonContainer.current,"pointerdown",this._onPointerDown,!0),"onpointerup"in this._splitButtonContainer.current&&this.props.onPointerUp&&this._events.on(this._splitButtonContainer.current,"pointerup",this.props.onPointerUp,!0))},i.prototype.componentDidUpdate=function(e,t){this.props.onAfterMenuDismiss&&!t.menuHidden&&this.state.menuHidden&&this.props.onAfterMenuDismiss()},i.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},i.prototype.focus=function(){var e,t;this._isSplitButton&&this._splitButtonContainer.current?(WV(!0,void 0,null===(e=this.context)||void 0===e?void 0:e.registeredProviders),this._splitButtonContainer.current.focus()):this._buttonElement.current&&(WV(!0,void 0,null===(t=this.context)||void 0===t?void 0:t.registeredProviders),this._buttonElement.current.focus())},i.prototype.dismissMenu=function(){this._dismissMenu()},i.prototype.openMenu=function(e,t){this._openMenu(e,t)},i.prototype._onRenderContent=function(t,i){var n=this,r=this.props,s=t,a=r.menuIconProps,o=r.menuProps,l=r.onRenderIcon,c=void 0===l?this._onRenderIcon:l,d=r.onRenderAriaDescription,u=void 0===d?this._onRenderAriaDescription:d,h=r.onRenderChildren,g=void 0===h?this._onRenderChildren:h,p=r.onRenderMenu,m=void 0===p?this._onRenderMenu:p,f=r.onRenderMenuIcon,v=void 0===f?this._onRenderMenuIcon:f,S=r.disabled,y=r.keytipProps;y&&o&&(y=this._getMemoizedMenuButtonKeytipProps(y));var C=function(t){return e.createElement(s,IU({},i,t),e.createElement("span",{className:n._classNames.flexContainer,"data-automationid":"splitbuttonprimary"},c(r,n._onRenderIcon),n._onRenderTextContents(),u(r,n._onRenderAriaDescription),g(r,n._onRenderChildren),!n._isSplitButton&&(o||a||n.props.onRenderMenuIcon)&&v(n.props,n._onRenderMenuIcon),o&&!o.doNotLayer&&n._shouldRenderMenu()&&m(n._getMenuProps(o),n._onRenderMenu)))},T=y?e.createElement(hW,{keytipProps:this._isSplitButton?void 0:y,ariaDescribedBy:i["aria-describedby"],disabled:S},(function(e){return C(e)})):C();return o&&o.doNotLayer?e.createElement(e.Fragment,null,T,this._shouldRenderMenu()&&m(this._getMenuProps(o),this._onRenderMenu)):e.createElement(e.Fragment,null,T,e.createElement(Yj,null))},i.prototype._shouldRenderMenu=function(){var e=this.state.menuHidden,t=this.props,i=t.persistMenu,n=t.renderPersistedMenuHiddenOnMount;return!e||!(!i||!this._renderedVisibleMenu&&!n)},i.prototype._hasText=function(){return null!==this.props.text&&(void 0!==this.props.text||"string"==typeof this.props.children)},i.prototype._getMenuProps=function(e){var t=this.props.persistMenu,i=this.state.menuHidden;return e.ariaLabel||e.labelElementId||!this._hasText()||(e=IU(IU({},e),{labelElementId:this._labelId})),IU(IU({id:this._labelId+"-menu",directionalHint:4},e),{shouldFocusOnContainer:this._menuShouldFocusOnContainer,shouldFocusOnMount:this._menuShouldFocusOnMount,hidden:t?i:void 0,className:V$("ms-BaseButton-menuhost",e.className),target:this._isSplitButton?this._splitButtonContainer.current:this._buttonElement.current,onDismiss:this._onDismissMenu})},i.prototype._onRenderSplitButtonContent=function(t,i){var n=this,r=this.props,s=r.styles,a=void 0===s?{}:s,o=r.disabled,l=r.allowDisabledFocus,c=r.checked,d=r.getSplitButtonClassNames,u=r.primaryDisabled,h=r.menuProps,g=r.toggle,p=r.role,m=r.primaryActionButtonProps,f=this.props.keytipProps,v=this.state.menuHidden,S=d?d(!!o,!v,!!c,!!l):a&&WW(a,!!o,!v,!!c,!!u);kj(i,{onClick:void 0,onPointerDown:void 0,onPointerUp:void 0,tabIndex:-1,"data-is-focusable":!1}),f&&h&&(f=this._getMemoizedMenuButtonKeytipProps(f));var y=B$(i,[],["disabled"]);m&&kj(i,m);var C=function(r){return e.createElement("div",IU({},y,{"data-ktp-target":r?r["data-ktp-target"]:void 0,role:p||"button","aria-disabled":o,"aria-haspopup":!0,"aria-expanded":!v,"aria-pressed":g?!!c:void 0,"aria-describedby":tG(i["aria-describedby"],r?r["aria-describedby"]:void 0),className:S&&S.splitButtonContainer,onKeyDown:n._onSplitButtonContainerKeyDown,onTouchStart:n._onTouchStart,ref:n._splitButtonContainer,"data-is-focusable":!0,onClick:o||u?void 0:n._onSplitButtonPrimaryClick,tabIndex:!o&&!u||l?0:void 0,"aria-roledescription":i["aria-roledescription"],onFocusCapture:n._onSplitContainerFocusCapture}),e.createElement("span",{style:{display:"flex",width:"100%"}},n._onRenderContent(t,i),n._onRenderSplitButtonMenuButton(S,r),n._onRenderSplitButtonDivider(S)))};return f?e.createElement(hW,{keytipProps:f,disabled:o},(function(e){return C(e)})):C()},i.prototype._onRenderSplitButtonDivider=function(t){return t&&t.divider?e.createElement("span",{className:t.divider,"aria-hidden":!0,onClick:function(e){e.stopPropagation()}}):null},i.prototype._onRenderSplitButtonMenuButton=function(t,n){var r=this.props,s=r.allowDisabledFocus,a=r.checked,o=r.disabled,l=r.splitButtonMenuProps,c=r.splitButtonAriaLabel,d=r.primaryDisabled,u=this.state.menuHidden,h=this.props.menuIconProps;void 0===h&&(h={iconName:"ChevronDown"});var g=IU(IU({},l),{styles:t,checked:a,disabled:o,allowDisabledFocus:s,onClick:this._onMenuClick,menuProps:void 0,iconProps:IU(IU({},h),{className:this._classNames.menuIcon}),ariaLabel:c,"aria-haspopup":!0,"aria-expanded":!u,"data-is-focusable":!1});return e.createElement(i,IU({},g,{"data-ktp-execute-target":n?n["data-ktp-execute-target"]:n,onMouseDown:this._onMouseDown,tabIndex:d&&!s?0:-1}))},i.prototype._onPointerDown=function(e){var t=this.props.onPointerDown;t&&t(e),"touch"===e.pointerType&&(this._handleTouchAndPointerEvent(),e.preventDefault(),e.stopImmediatePropagation())},i.prototype._handleTouchAndPointerEvent=function(){var e=this;void 0!==this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout((function(){e._processingTouch=!1,e._lastTouchTimeoutId=void 0,e.state.menuHidden&&e.focus()}),500)},i.prototype._isValidMenuOpenKey=function(e){return this.props.menuTriggerKeyCode?e.which===this.props.menuTriggerKeyCode:!!this.props.menuProps&&e.which===Ej&&(e.altKey||e.metaKey)},i.defaultProps={baseClassName:"ms-Button",styles:{},split:!1},i.contextType=Gj,i}(e.Component),JW=function(){return e.useContext($G)},YW=function(e){var t=e.stylesheetKey,i=e.children,n=ej(),r=n.useAdoptedStylesheetEx,s=n.useMergeStylesRootStylesheets,a=n.useWindow,o=JW(),l=s(),c=a();return r(MU,o,l,c),r(t,o,l,c),i(!!o)},QW=SB((function(e,t,i){return{stylesheetKey:e,inShadow:t,window:i,__isShadowConfig__:!0}})),ZW=SB((function(e,t,i){var n,r=null!==(n=null!=t?t:e)&&void 0!==n?n:{};return r.__shadowConfig__=i,r}));function XW(t,i,n){return function(r){var s,a=(s=function(s){function a(e){var t=s.call(this,e)||this;return t._styleCache={},t._onSettingChanged=t._onSettingChanged.bind(t),t}return _U(a,s),a.prototype.componentDidMount=function(){oH.observe(this._onSettingChanged)},a.prototype.componentWillUnmount=function(){oH.unobserve(this._onSettingChanged)},a.prototype.render=function(){var s=this;return e.createElement(YW,{stylesheetKey:t},(function(a){return e.createElement(s$.Consumer,null,(function(o){var l,c=oH.getSettings(i,t,o.customizations),d=null!==(l=s.context.window)&&void 0!==l?l:_B(),u=QW(t,a,d),h=s.props;if(c.styles&&"function"==typeof c.styles&&(c.styles=c.styles(IU(IU({},c),h))),n&&c.styles){if(s._styleCache.default!==c.styles||s._styleCache.component!==h.styles){var g=ZH(c.styles,h.styles);g.__shadowConfig__=u,s._styleCache.default=c.styles,s._styleCache.component=h.styles,s._styleCache.merged=g}return e.createElement(r,IU({},c,h,{styles:s._styleCache.merged}))}var p=ZW(c.styles,h.styles,u);return e.createElement(r,IU({},c,h,{styles:p}))}))}))},a.prototype._onSettingChanged=function(){this.forceUpdate()},a}(e.Component),s.displayName="Customized"+t,s.contextType=Kq,s);return function(e,t){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}(r,a)}}var eK,tK,iK={outline:0},nK=function(e){return{fontSize:e,margin:"0 4px",height:"16px",lineHeight:"16px",textAlign:"center",flexShrink:0}},rK=SB((function(e){var t,i,n=e.semanticColors,r=e.effects,s=e.fonts,a=n.buttonBorder,o=n.disabledBackground,l=n.disabledText,c={left:-2,top:-2,bottom:-2,right:-2,outlineColor:"ButtonText"};return{root:[KV(e,{inset:1,highContrastStyle:c,borderColor:"transparent"}),e.fonts.medium,{border:"1px solid "+a,borderRadius:r.roundedCorner2,boxSizing:"border-box",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0 16px",textDecoration:"none",textAlign:"center",userSelect:"none",":active > span":{position:"relative",left:0,top:0}}],rootDisabled:[KV(e,{inset:1,highContrastStyle:c,borderColor:"transparent"}),{backgroundColor:o,borderColor:o,color:l,cursor:"default",":hover":iK,":focus":iK}],iconDisabled:(t={color:l},t[UV]={color:"GrayText"},t),menuIconDisabled:(i={color:l},i[UV]={color:"GrayText"},i),flexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},description:{display:"block"},textContainer:{flexGrow:1,display:"block"},icon:nK(s.mediumPlus.fontSize),menuIcon:nK(s.small.fontSize),label:{margin:"0 4px",lineHeight:"100%",display:"block"},screenReaderText:LV}})),sK=SB((function(e,t){var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y=e.effects,C=e.palette,T=e.semanticColors,E={left:-2,top:-2,bottom:-2,right:-2,border:"none"},b={position:"absolute",width:1,right:31,top:8,bottom:8};return ZH({splitButtonContainer:[KV(e,{highContrastStyle:E,inset:2,pointerEvents:"none"}),{display:"inline-flex",".ms-Button--default":{borderTopRightRadius:"0",borderBottomRightRadius:"0",borderRight:"none",flexGrow:"1"},".ms-Button--primary":(i={borderTopRightRadius:"0",borderBottomRightRadius:"0",border:"none",flexGrow:"1",":hover":{border:"none"},":active":{border:"none"}},i[UV]=IU(IU({color:"WindowText",backgroundColor:"Window",border:"1px solid WindowText",borderRightWidth:"0"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{":hover":{backgroundColor:"Highlight",border:"1px solid Highlight",borderRightWidth:"0",color:"HighlightText"},":active":{border:"1px solid Highlight"}}),i),".ms-Button--default + .ms-Button":(n={},n[UV]={border:"1px solid WindowText",borderLeftWidth:"0",":hover":{backgroundColor:"HighlightText",borderColor:"Highlight",color:"Highlight",".ms-Button-menuIcon":IU({backgroundColor:"HighlightText",color:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"})}},n),'.ms-Button--default + .ms-Button[aria-expanded="true"]':(r={},r[UV]={backgroundColor:"HighlightText",borderColor:"Highlight",color:"Highlight",".ms-Button-menuIcon":IU({backgroundColor:"HighlightText",color:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"})},r),".ms-Button--primary + .ms-Button":(s={border:"none"},s[UV]={border:"1px solid WindowText",borderLeftWidth:"0",":hover":{borderLeftWidth:"0",backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText",".ms-Button-menuIcon":IU(IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"HighlightText"})}},s),'.ms-Button--primary + .ms-Button[aria-expanded="true"]':(a={},a[UV]=IU(IU({backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{".ms-Button-menuIcon":{color:"HighlightText"}}),a),".ms-Button.is-disabled":(o={},o[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},o)}],splitButtonContainerHovered:{".ms-Button--default.is-disabled":(l={backgroundColor:T.buttonBackgroundDisabled,color:T.buttonTextDisabled},l[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},l),".ms-Button--primary.is-disabled":(c={backgroundColor:T.primaryButtonBackgroundDisabled,color:T.primaryButtonTextDisabled},c[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},c)},splitButtonContainerChecked:{".ms-Button--primary":(d={},d[UV]=IU({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),d)},splitButtonContainerCheckedHovered:{".ms-Button--primary":(u={},u[UV]=IU({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u)},splitButtonContainerFocused:{outline:"none!important"},splitButtonMenuButton:(h={padding:6,height:"auto",boxSizing:"border-box",borderRadius:0,borderTopRightRadius:y.roundedCorner2,borderBottomRightRadius:y.roundedCorner2,border:"1px solid ".concat(C.neutralSecondaryAlt),borderLeft:"none",outline:"transparent",userSelect:"none",display:"inline-block",textDecoration:"none",textAlign:"center",cursor:"pointer",verticalAlign:"top",width:32,marginLeft:-1,marginTop:0,marginRight:0,marginBottom:0},h[UV]={".ms-Button-menuIcon":{color:"WindowText"}},h),splitButtonDivider:IU(IU({},b),(g={},g[UV]={backgroundColor:"WindowText"},g)),splitButtonDividerDisabled:IU(IU({},b),(p={},p[UV]={backgroundColor:"GrayText"},p)),splitButtonMenuButtonDisabled:(m={pointerEvents:"none",border:"none",":hover":{cursor:"default"},".ms-Button--primary":(f={},f[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},f),".ms-Button-menuIcon":(v={},v[UV]={color:"GrayText"},v)},m[UV]={color:"GrayText",border:"1px solid GrayText",backgroundColor:"Window"},m),splitButtonFlexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},splitButtonContainerDisabled:(S={outline:"none",border:"none"},S[UV]=IU({color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),S),splitButtonMenuFocused:IU({},KV(e,{highContrastStyle:E,inset:2}))},t)})),aK=SB((function(e,t){var i,n=rK(e),r=sK(e),s=e.palette;return ZH(n,{root:{padding:"0 4px",width:"32px",height:"32px",backgroundColor:"transparent",border:"none",color:e.semanticColors.link},rootHovered:(i={color:s.themeDarkAlt,backgroundColor:s.neutralLighter},i[UV]={borderColor:"Highlight",color:"Highlight"},i),rootHasMenu:{width:"auto"},rootPressed:{color:s.themeDark,backgroundColor:s.neutralLight},rootExpanded:{color:s.themeDark,backgroundColor:s.neutralLight},rootChecked:{color:s.themeDark,backgroundColor:s.neutralLight},rootCheckedHovered:{color:s.themeDark,backgroundColor:s.neutralQuaternaryAlt},rootDisabled:{color:s.neutralTertiaryAlt}},r,t)})),oK=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(KW,IU({},this.props,{variantClassName:"ms-Button--icon",styles:aK(n,i),onRenderText:Fj,onRenderDescription:Fj}))},AU([XW("IconButton",["theme","styles"],!0)],i)}(e.Component);function lK(t){var i=e.useState(t),n=i[0],r=i[1];return[n,{setTrue:Xq((function(){return function(){r(!0)}})),setFalse:Xq((function(){return function(){r(!1)}})),toggle:Xq((function(){return function(){r((function(e){return!e}))}}))}]}!function(e){e[e.info=0]="info",e[e.error=1]="error",e[e.blocked=2]="blocked",e[e.severeWarning=3]="severeWarning",e[e.success=4]="success",e[e.warning=5]="warning"}(eK||(eK={}));var cK,dK,uK,hK,gK=((tK={})[eK.info]="Info",tK[eK.warning]="Info",tK[eK.error]="ErrorBadge",tK[eK.blocked]="Blocked2",tK[eK.severeWarning]="Warning",tK[eK.success]="Completed",tK),pK=oj(),mK=function(e){switch(e){case eK.blocked:case eK.error:case eK.severeWarning:return"assertive"}return"polite"},fK=function(e){switch(e){case eK.blocked:case eK.error:case eK.severeWarning:return"alert"}return"status"},vK=e.forwardRef((function(t,i){var n=lK(!1),r=n[0],s=n[1].toggle,a=g$("MessageBar"),o=t.actions,l=t.className,c=t.children,d=t.overflowButtonAriaLabel,u=t.dismissIconProps,h=t.styles,g=t.theme,p=t.messageBarType,m=void 0===p?eK.info:p,f=t.onDismiss,v=void 0===f?void 0:f,S=t.isMultiline,y=void 0===S||S,C=t.truncated,T=t.dismissButtonAriaLabel,E=t.messageBarIconProps,b=t.role,_=t.delayedRender,I=void 0===_||_,w=t.expandButtonProps,A=t.onExpandButtonToggled,P=void 0===A?void 0:A,R=t.showExpandButton,M=e.useCallback((function(){s(),P&&P(!r)}),[r,P,s]),D=B$(t,v$,["className","role"]),k=pK(h,{theme:g,messageBarType:m||eK.info,onDismiss:void 0!==v,actions:void 0!==o,truncated:C,isMultiline:y,expandSingleLine:r,className:l}),O={iconName:r?"DoubleChevronUp":"DoubleChevronDown"},N=o||v?{"aria-describedby":a,role:"region"}:{},L=o?e.createElement("div",{className:k.actions},o):null,x=v?e.createElement(oK,{disabled:!1,className:k.dismissal,onClick:v,iconProps:u||{iconName:"Clear"},title:T,ariaLabel:T}):null;return e.createElement("div",IU({ref:i,className:k.root},N),e.createElement("div",{className:k.content},e.createElement("div",{className:k.iconContainer,"aria-hidden":!0},E?e.createElement(mG,IU({},E,{className:V$(k.icon,E.className)})):e.createElement(mG,{iconName:gK[m],className:k.icon})),e.createElement("div",{className:k.text,id:a,role:b||fK(m),"aria-live":mK(m)},e.createElement("span",IU({className:k.innerText},D),I?e.createElement(dj,null,e.createElement("span",null,c)):e.createElement("span",null,c))),(R||!y&&!L&&C)&&e.createElement("div",{className:k.expandSingleLine},e.createElement(oK,IU({disabled:!1,className:k.expand,onClick:M,iconProps:O,ariaLabel:d,"aria-expanded":r},w))),!y&&L,!y&&x&&e.createElement("div",{className:k.dismissSingleLine},x),y&&x),y&&L)}));vK.displayName="MessageBar";var SK={root:"ms-MessageBar",error:"ms-MessageBar--error",blocked:"ms-MessageBar--blocked",severeWarning:"ms-MessageBar--severeWarning",success:"ms-MessageBar--success",warning:"ms-MessageBar--warning",multiline:"ms-MessageBar-multiline",singleline:"ms-MessageBar-singleline",dismissalSingleLine:"ms-MessageBar-dismissalSingleLine",expandingSingleLine:"ms-MessageBar-expandingSingleLine",content:"ms-MessageBar-content",iconContainer:"ms-MessageBar-icon",text:"ms-MessageBar-text",innerText:"ms-MessageBar-innerText",dismissSingleLine:"ms-MessageBar-dismissSingleLine",expandSingleLine:"ms-MessageBar-expandSingleLine",dismissal:"ms-MessageBar-dismissal",expand:"ms-MessageBar-expand",actions:"ms-MessageBar-actions",actionsSingleline:"ms-MessageBar-actionsSingleLine"},yK=((cK={})[eK.error]="errorBackground",cK[eK.blocked]="errorBackground",cK[eK.success]="successBackground",cK[eK.warning]="warningBackground",cK[eK.severeWarning]="severeWarningBackground",cK[eK.info]="infoBackground",cK),CK=((dK={})[eK.error]="errorIcon",dK[eK.blocked]="errorIcon",dK[eK.success]="successIcon",dK[eK.warning]="warningIcon",dK[eK.severeWarning]="severeWarningIcon",dK[eK.info]="infoIcon",dK),TK=((uK={})[eK.error]="#ff0000",uK[eK.blocked]="#ff0000",uK[eK.success]="#bad80a",uK[eK.warning]="#fff100",uK[eK.severeWarning]="#ff0000",uK[eK.info]="WindowText",uK),EK=((hK={})[eK.error]="#e81123",hK[eK.blocked]="#e81123",hK[eK.success]="#107c10",hK[eK.warning]="#966400",hK[eK.severeWarning]="#d83b01",hK[eK.info]="WindowText",hK),bK=nj(vK,(function(e){var t,i,n,r,s,a,o,l,c,d,u,h=e.theme,g=e.className,p=e.onDismiss,m=e.truncated,f=e.isMultiline,v=e.expandSingleLine,S=e.messageBarType,y=void 0===S?eK.info:S,C=h.semanticColors,T=h.fonts,E=$V(0,479),b=FV(SK,h),_={fontSize:kV.xSmall,height:10,lineHeight:"10px",color:C.messageText,selectors:(t={},t[UV]=IU(IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),t)},I=[KV(h,{inset:1,highContrastStyle:{outlineOffset:"-6px",outline:"1px solid Highlight"},borderColor:"transparent"}),{flexShrink:0,width:32,height:32,padding:"8px 12px",selectors:{"& .ms-Button-icon":_,":hover":{backgroundColor:"transparent"},":active":{backgroundColor:"transparent"}}}];return{root:[b.root,T.medium,y===eK.error&&b.error,y===eK.blocked&&b.blocked,y===eK.severeWarning&&b.severeWarning,y===eK.success&&b.success,y===eK.warning&&b.warning,f?b.multiline:b.singleline,!f&&p&&b.dismissalSingleLine,!f&&m&&b.expandingSingleLine,{background:C[yK[y]],boxSizing:"border-box",color:C.messageText,minHeight:32,width:"100%",display:"flex",wordBreak:"break-word",selectors:(i={".ms-Link":{color:C.messageLink,selectors:{":hover":{color:C.messageLinkHovered}}}},i[UV]=IU(IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{background:"transparent",border:"1px solid ".concat(TK[y]),color:"WindowText"}),i[BV]={border:"1px solid ".concat(EK[y])},i)},f&&{flexDirection:"column"},g],content:[b.content,(n={display:"flex",width:"100%",lineHeight:"normal"},n[E]={display:"grid",gridTemplateColumns:"auto 1fr auto",gridTemplateRows:"1fr auto",gridTemplateAreas:'\n "icon text close"\n "action action action"\n '},n)],iconContainer:[b.iconContainer,(r={fontSize:kV.medium,minWidth:16,minHeight:16,display:"flex",flexShrink:0,margin:"8px 0 8px 12px"},r[E]={gridArea:"icon"},r)],icon:{color:C[CK[y]],selectors:(s={},s[UV]=IU(IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),s)},text:[b.text,IU(IU({minWidth:0,display:"flex",flexGrow:1,margin:8},T.small),(a={},a[E]={gridArea:"text"},a.selectors=(o={},o[UV]=IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o),a)),!p&&{marginRight:12}],innerText:[b.innerText,{lineHeight:16,selectors:{"& span a:last-child":{paddingLeft:4}}},m&&{overflow:"visible",whiteSpace:"pre-wrap"},!f&&{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},!f&&!m&&{selectors:(l={},l[E]={overflow:"visible",whiteSpace:"pre-wrap"},l)},v&&{overflow:"visible",whiteSpace:"pre-wrap"}],dismissSingleLine:[b.dismissSingleLine,(c={},c[E]={gridArea:"close"},c)],expandSingleLine:b.expandSingleLine,dismissal:[b.dismissal,I],expand:[b.expand,I],actions:[f?b.actions:b.actionsSingleline,(d={display:"flex",flexGrow:0,flexShrink:0,flexBasis:"auto",flexDirection:"row-reverse",alignItems:"center",margin:"0 12px 0 8px",forcedColorAdjust:"auto",MsHighContrastAdjust:"auto"},d[E]={gridArea:"action",marginRight:8,marginBottom:8},d.selectors={"& button:nth-child(n+2)":(u={marginLeft:8},u[E]={marginBottom:0},u)},d),f&&{marginBottom:8},p&&!f&&{marginRight:0}]}}),void 0,{scope:"MessageBar"});const _K={strings:JSON.parse('{"participantItem":{"isMeText":"(you)","menuTitle":"More Options","removeButtonLabel":"Remove","sharingIconLabel":"Sharing","mutedIconLabel":"Muted","handRaisedIconLabel":"Hand raised - Position {position}","displayNamePlaceholder":"Unnamed participant","participantStateRinging":"Calling...","participantStateHold":"On hold","participantItemAriaLabel":"{displayName}, {handRaisedState}, {mutedState}, {micDisabledState}, {cameraDisabledState}, {sharingState}, {connectionState}","participantItemWithMoreOptionsAriaLabel":"{displayName}, {handRaisedState}, {mutedState}, {micDisabledState}, {cameraDisabledState}, {sharingState}, {connectionState}, More Options","attendeeRole":"Attendee","micDisabledIconLabel":"Micophone disabled","cameraDisabledIconLabel":"Camera disabled"},"ParticipantList":{"overflowParticipantCount":"+{overflowCount} more"},"typingIndicator":{"singleUser":"{user} is typing ...","multipleUsers":"{users} are typing ...","multipleUsersAbbreviateOne":"{users} and 1 other are typing ...","multipleUsersAbbreviateMany":"{users} and {numOthers} others are typing ...","delimiter":", "},"sendBox":{"placeholderText":"Enter a message","textTooLong":"Your message length is over the maximum limit.","sendButtonAriaLabel":"Send message","attachmentUploadsPendingError":"File is uploading, please wait.","removeAttachment":"Remove file","uploading":"Uploading","uploadCompleted":"Upload completed","attachmentMoreMenu":"More Options"},"richTextSendBox":{"placeholderText":"Enter a message","textTooLong":"Your message length is over the maximum limit.","sendButtonAriaLabel":"Send message","attachmentUploadsPendingError":"File is uploading, please wait.","imageUploadsPendingError":"Image is uploading, please wait.","removeAttachment":"Remove file","uploading":"Uploading","uploadCompleted":"Upload completed","richTextBoldTooltip":"Bold","richTextItalicTooltip":"Italic","richTextUnderlineTooltip":"Underline","richTextBulletListTooltip":"Bulleted list","richTextNumberListTooltip":"Numbered list","richTextIncreaseIndentTooltip":"Increase indent","richTextDecreaseIndentTooltip":"Decrease indent","richTextInsertTableTooltip":"Insert table","richTextFormatButtonTooltip":"Format","richTextInsertRowOrColumnMenu":"Insert","richTextInsertTableMenuTitle":"Insert {column} x {row} table","richTextInsertRowAboveMenu":"Insert above","richTextInsertRowBelowMenu":"Insert below","richTextInsertColumnLeftMenu":"Insert left","richTextInsertColumnRightMenu":"Insert right","richTextDeleteRowOrColumnMenu":"Delete","richTextDeleteColumnMenu":"Delete column","richTextDeleteRowMenu":"Delete row","richTextDeleteTableMenu":"Delete table","richTextToolbarAriaLabel":"Message Formatting Toolbar","richTextToolbarMoreButtonAriaLabel":"More options","attachmentMoreMenu":"More Options","richTextNewBulletedListItemAnnouncement":"Bullet, new line","richTextNewNumberedListItemAnnouncement":"{0}, new line","richTextBulletedListAppliedAnnouncement":"Bulleted list applied","richTextNumberedListAppliedAnnouncement":"Numbered list applied"},"realTimeTextModal":{"realTimeTextModalAriaLabel":"Turn on RTT Modal","realTimeTextModalTitle":"Turn on RTT?","realTimeTextModalText":"Real-time text (RTT) will be turned on for everyone in the meeting.","realTimeTextConfirmButtonLabel":"Turn on","realTimeTextCancelButtonLabel":"Cancel","realTimeTextCloseModalButtonAriaLabel":"Close RTT Modal"},"captionsBanner":{"captionsBannerSpinnerText":"Starting captions...","realTimeTextInputBoxDefaultText":"Type message in real time","realTimeTextInputErrorMessage":"Message can not exceed 2000 characters","realTimeTextBannerTitle":"RTT","realTimeTextBannerContent":"RTT (real-time text) is enabled for all participants for the entire duration of the meeting.","realTimeTextBannerLinkLabel":"Learn more","captionsOnlyContainerTitle":"Captions","realTimeTextOnlyContainerTitle":"Real-Time Text","captionsAndRealTimeTextContainerTitle":"Captions and Real-Time Text","expandButtonAriaLabel":"Expand","minimizeButtonAriaLabel":"Collapse"},"mentionPopover":{"mentionPopoverHeader":"Suggestions"},"imageOverlay":{"downloadButtonLabel":"Download","dismissButtonAriaLabel":"Close","overlayVisibleMessage":"Image Details Overlay"},"messageStatusIndicator":{"deliveredAriaLabel":"Message sent","deliveredTooltipText":"Sent","seenAriaLabel":"Message seen by others","seenTooltipText":"Seen","readByTooltipText":"Read by {messageThreadReadCount} of {remoteParticipantsCount}","sendingAriaLabel":"Message sending","sendingTooltipText":"Sending","failedToSendAriaLabel":"Message failed to send","failedToSendTooltipText":"Failed to send"},"endCallButton":{"label":"Leave","tooltipContent":"Leave call","leaveOption":"Leave","endCallOption":"End call for everyone"},"cameraButton":{"onLabel":"Camera","offLabel":"Camera","tooltipDisabledContent":"Camera is disabled","tooltipOnContent":"Turn off camera","tooltipOffContent":"Turn on camera","tooltipVideoLoadingContent":"Video is loading","cameraMenuTitle":"Camera","cameraMenuTooltip":"Choose camera","cameraButtonSplitRoleDescription":"Split button","onSplitButtonAriaLabel":"Turn off camera","offSplitButtonAriaLabel":"Turn on camera","cameraActionTurnedOnAnnouncement":"Your camera has been turned on","cameraActionTurnedOffAnnouncement":"Your camera has been turned off","onSplitButtonPrimaryActionCamera":"Turn off camera","offSplitButtonPrimaryActionCamera":"Turn on camera","cameraPrimaryActionSplitButtonTitle":"Use camera","videoEffectsMenuItemTitle":"Effects","cameraButtonAriaDescription":"camera options"},"microphoneButton":{"onLabel":"Mic","offLabel":"Mic","tooltipDisabledContent":"Microphone is disabled","tooltipOnContent":"Mute microphone","tooltipOffContent":"Unmute microphone","microphoneMenuTitle":"Microphone","microphoneMenuTooltip":"Choose microphone","speakerMenuTitle":"Speaker","speakerMenuTooltip":"Choose speaker","microphoneButtonSplitRoleDescription":"Split button","onSplitButtonAriaLabel":"Mute mic","offSplitButtonAriaLabel":"Unmute mic","microphoneActionTurnedOnAnnouncement":"Your microphone has been turned on","microphoneActionTurnedOffAnnouncement":"Your microphone has been turned off","offSplitButtonMicrophonePrimaryAction":"Unmute mic","onSplitButtonMicrophonePrimaryAction":"Mute mic","microphonePrimaryActionSplitButtonTitle":"Use microphone","microphoneAriaDescription":"Audio options","deepNoiseSuppressionTitle":"Noise suppression","deepNoiseSuppressionOnAnnouncement":"Deep noise suppression has been turned on","deepNoiseSuppressionOffAnnouncement":"Deep noise suppression has been turned off"},"devicesButton":{"label":"Devices","tooltipContent":"Manage devices","cameraMenuTitle":"Camera","cameraMenuTooltip":"Choose camera","audioDeviceMenuTitle":"Audio Device","audioDeviceMenuTooltip":"Choose audio device","microphoneMenuTitle":"Microphone","microphoneMenuTooltip":"Choose microphone","speakerMenuTitle":"Speaker","speakerMenuTooltip":"Choose speaker"},"participantsButton":{"label":"People","ariaLabel":"People","tooltipContent":"Show participants","menuHeader":"In this call","participantsListButtonLabel":"{numParticipants} people","muteAllButtonLabel":"Mute all","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkActionedAriaLabel":"Invite link copied"},"screenShareButton":{"onLabel":"Stop presenting","offLabel":"Present","tooltipDisabledContent":"Presenting is disabled","tooltipOnContent":"Presenting your screen","tooltipOffContent":"Present your screen"},"raiseHandButton":{"offLabel":"Raise","onLabel":"Lower","tooltipDisabledContent":"Raise Hand action is disabled","tooltipOnContent":"Lower Hand","tooltipOffContent":"Raise Hand"},"reactionButton":{"label":"React","ariaLabel":"React","tooltipDisabledContent":"Reaction action is disabled","tooltipContent":"Send a reaction","likeReactionTooltipContent":"Like","heartReactionTooltipContent":"Love","laughReactionTooltipContent":"Laugh","applauseReactionTooltipContent":"Applause","surprisedReactionTooltipContent":"Surprised"},"realTimeText":{"isTypingText":"RTT typing"},"captionsSettingsModal":{"captionsSettingsModalTitle":"Captions Settings","captionsSettingsSpokenLanguageDropdownLabel":"Spoken language","captionsSettingsCaptionLanguageDropdownLabel":"Captions language","captionsSettingsSpokenLanguageDropdownInfoText":"Language that everyone on this call is speaking.","captionsSettingsCaptionLanguageDropdownInfoText":"Captions will appear in this langugage.","captionsSettingsConfirmButtonLabel":"Confirm","captionsSettingsCancelButtonLabel":"Cancel","captionsSettingsModalAriaLabel":"Captions Setting Modal","captionsSettingsCloseModalButtonAriaLabel":"Close Captions Setting"},"spokenLanguages":{"ar-ae":"Arabic - U.A.E.","ar-sa":"Arabic - Saudi Arabia","da-dk":"Danish","de-de":"German - Germany","en-au":"English - Australia","en-ca":"English - Canada","en-gb":"English - United Kingdom","en-in":"English - India","en-nz":"English - New Zealand","en-us":"English - United States","es-es":"Spanish - Spain (Modern Sort)","es-mx":"Spanish - Mexico","fi-fi":"Finnish","fr-ca":"French - Canada","fr-fr":"French - France","hi-in":"Hindi","it-it":"Italian - Italy","ja-jp":"Japanese","ko-kr":"Korean","nb-no":"Norwegian (Bokmål)","nl-be":"Dutch - Belgium","nl-nl":"Dutch - Netherlands","pl-pl":"Polish","pt-br":"Portuguese - Brazil","ru-ru":"Russian","sv-se":"Swedish","zh-cn":"Chinese - People\'s Republic of China","zh-hk":"Chinese - Hong Kong SAR","cs-cz":"Czech","pt-pt":"Portuguese - Portugal","tr-tr":"Turkish","vi-vn":"Vietnamese","th-th":"Thai","he-il":"Hebrew","cy-gb":"Welsh","uk-ua":"Ukrainian","el-gr":"Greek","hu-hu":"Hungarian","ro-ro":"Romanian","sk-sk":"Slovak","zh-tw":"Chinese - Taiwan"},"captionLanguages":{"ar":"Arabic","da":"Danish","de":"German","en":"English","es":"Spanish","fi":"Finnish","fr-ca":"French - Canada","fr":"French - France","hi":"Hindi","it":"Italian","ja":"Japanese","ko":"Korean","nb":"Norwegian (Bokmål)","nl":"Dutch","pl":"Polish","pt":"Portuguese - Brazil","ru":"Russian","sv":"Swedish","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)","cs":"Czech","pt-pt":"Portuguese - Portugal","tr":"Turkish","vi":"Vietnamese","th":"Thai","he":"Hebrew","cy":"Welsh","uk":"Ukrainian","el":"Greek","hu":"Hungarian","ro":"Romanian","sk":"Slovak"},"startCaptionsButton":{"onLabel":"Turn on captions","offLabel":"Turn off captions","tooltipOnContent":"Turn off captions","tooltipOffContent":"Turn on captions"},"startRealTimeTextButton":{"label":"Turn on RTT for this call","tooltipOffContent":"Turn on RTT for this call"},"messageThread":{"yesterday":"Yesterday","sunday":"Sunday","monday":"Monday","tuesday":"Tuesday","wednesday":"Wednesday","thursday":"Thursday","friday":"Friday","saturday":"Saturday","participantJoined":"joined the chat.","participantLeft":"left the chat.","editMessage":"Edit","removeMessage":"Delete","resendMessage":"Try sending again","failToSendTag":"Failed to send","editedTag":"Edited","liveAuthorIntro":"Message from {author}","editedMessageLiveAuthorIntro":"Edited message from {author}","editedMessageLocalUserLiveAuthorIntro":"Edited message","messageContentAriaText":"{status} {author} said {message}","messageContentMineAriaText":"{status} You said {message}","editBoxTextLimit":"Your message is over the limit of {limitNumber} characters","editBoxPlaceholderText":"Edit your message","newMessagesIndicator":"New messages","noDisplayNameSub":"No name","editBoxCancelButton":"Cancel","editBoxSubmitButton":"Done","messageReadCount":"Read by {messageReadByCount} of {remoteParticipantsCount}","actionMenuMoreOptions":"More Options","downloadAttachment":"Download file","openAttachment":"Open file","blockedWarningText":"This message was deleted due to organizational policy.","blockedWarningLinkText":"Details","attachmentCardGroupMessage":"The message has {attachmentCount} attachment","messageDeletedAnnouncementAriaLabel":"The message is deleted","richTextBoldTooltip":"Bold","richTextItalicTooltip":"Italic","richTextUnderlineTooltip":"Underline","richTextBulletListTooltip":"Bulleted list","richTextNumberListTooltip":"Numbered list","richTextIncreaseIndentTooltip":"Increase indent","richTextDecreaseIndentTooltip":"Decrease indent","richTextInsertTableTooltip":"Insert table","richTextFormatButtonTooltip":"Format","richTextInsertRowOrColumnMenu":"Insert","richTextInsertTableMenuTitle":"Insert {column} x {row} table","richTextInsertRowAboveMenu":"Insert above","richTextInsertRowBelowMenu":"Insert below","richTextInsertColumnLeftMenu":"Insert left","richTextInsertColumnRightMenu":"Insert right","richTextDeleteRowOrColumnMenu":"Delete","richTextDeleteColumnMenu":"Delete column","richTextDeleteRowMenu":"Delete row","richTextDeleteTableMenu":"Delete table","richTextToolbarMoreButtonAriaLabel":"More options","attachmentUploadsPendingError":"File is uploading, please wait.","imageUploadsPendingError":"Image is uploading, please wait.","richTextNewBulletedListItemAnnouncement":"Bullet, new line","richTextNewNumberedListItemAnnouncement":"{0}, new line","richTextBulletedListAppliedAnnouncement":"Bulleted list applied","richTextNumberedListAppliedAnnouncement":"Numbered list applied"},"errorBar":{"unableToReachChatService":"You are offline","accessDenied":"Unable to access chat services - please check the user credentials provided","userNotInChatThread":"You are no longer in this chat thread","sendMessageNotInChatThread":"Failed to send message because you are no longer in this chat thread","sendMessageGeneric":"Failed to send message","callingNetworkFailure":"Troubling connecting call - you seem to be offline","startVideoGeneric":"Failed to start video","stopVideoGeneric":"Failed to stop video","muteGeneric":"Failed to mute microphone","unmuteGeneric":"Failed to unmute microphone","speakingWhileMuted":"Your microphone is muted","startScreenShareGeneric":"There was an issue starting screen share.","stopScreenShareGeneric":"Failed to stop screen sharing","callNetworkQualityLow":"Network quality is low.","teamsMeetingCallNetworkQualityLow":"Network quality is low.","callNoSpeakerFound":"No speakers or headphones found. Connect an audio device to hear the call.","callNoMicrophoneFound":"No microphones found. Connect an audio input device.","callMicrophoneAccessDenied":"Unable to access microphone. Click the lock in the address bar to grant permission to this webpage.","callMicrophoneAccessDeniedSafari":"Unable to access microphone. Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","callMicrophoneMutedBySystem":"You are muted by your system.","callMicrophoneUnmutedBySystem":"Your microphone recovered and you were unmuted by your system.","callMacOsMicrophoneAccessDenied":"Unable to access microphone. Grant microphone permission in your macOS privacy settings.","callLocalVideoFreeze":"Network bandwidth is poor. Your video may appear paused for others on the call.","callCameraAccessDenied":"Unable to access camera. Click the lock in the address bar to grant permission to this webpage.","callCameraAccessDeniedSafari":"Unable to access camera. Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","callCameraAlreadyInUse":"Unable to access camera. It may already be in use by another application.","callVideoStoppedBySystem":"Your video has been stopped by your system.","callVideoRecoveredBySystem":"Your video has resumed.","callMacOsCameraAccessDenied":"MacOS is blocking access to your camera. Update your privacy settings to allow this browser to access your camera.","callMacOsScreenShareAccessDenied":"MacOS is blocking screen sharing. Update your privacy settings to allow this browser to record your screen.","dismissButtonAriaLabel":"Close","failedToJoinCallGeneric":"Failed to join call.","failedToJoinCallInvalidMeetingLink":"Unable to join Meeting. Invalid Link.","cameraFrozenForRemoteParticipants":"Users in the call are having issues seeing your video. Please check your devices and network.","unableToStartVideoEffect":"Unable to apply video effect.","startSpotlightWhileMaxParticipantsAreSpotlighted":"Cannot start spotlight on participant(s) because the maximum number of participants are already spotlighted.","mutedByRemoteParticipant":"You were muted by another participant."},"notificationStack":{"callingNetworkFailure":{"title":"Troubling connecting call","message":"You seem to be offline. Please check your network connection and try again.","dismissButtonAriaLabel":"Close"},"startVideoGeneric":{"title":"Failed to start video.","dismissButtonAriaLabel":"Close"},"stopVideoGeneric":{"title":"Failed to stop video.","dismissButtonAriaLabel":"Close"},"muteGeneric":{"title":"Failed to mute microphone.","dismissButtonAriaLabel":"Close"},"unmuteGeneric":{"title":"Failed to unmute microphone.","dismissButtonAriaLabel":"Close"},"speakingWhileMuted":{"title":"You\'re muted.","dismissButtonAriaLabel":"Close"},"startScreenShareGeneric":{"title":"There was an issue starting screen share.","dismissButtonAriaLabel":"Close"},"stopScreenShareGeneric":{"title":"Failed to stop screen sharing.","dismissButtonAriaLabel":"Close"},"callNetworkQualityLow":{"title":"Network quality is low.","dismissButtonAriaLabel":"Close"},"teamsMeetingCallNetworkQualityLow":{"title":"Network quality is low.","dismissButtonAriaLabel":"Close","message":"Join this call from your phone for better sound. You can continue viewing the meeting on this device.","primaryButtonLabel":"Join by Phone"},"callNoSpeakerFound":{"title":"No speakers or headphones found","message":"Connect an audio device to hear the call.","dismissButtonAriaLabel":"Close"},"callNoMicrophoneFound":{"title":"No microphones found","message":"Connect an audio input device.","dismissButtonAriaLabel":"Close"},"callMicrophoneAccessDenied":{"title":"Unable to access microphone","message":"Click the lock in the address bar to grant permission to this webpage.","dismissButtonAriaLabel":"Close"},"callMicrophoneAccessDeniedSafari":{"title":"Unable to access microphone","message":"Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","dismissButtonAriaLabel":"Close"},"callMicrophoneMutedBySystem":{"title":"You are muted by your system.","dismissButtonAriaLabel":"Close"},"callMicrophoneUnmutedBySystem":{"title":"Your microphone recovered and you were unmuted by your system.","dismissButtonAriaLabel":"Close"},"callMacOsMicrophoneAccessDenied":{"title":"Unable to access microphone","message":"Grant microphone permission in your macOS privacy settings.","dismissButtonAriaLabel":"Close"},"callLocalVideoFreeze":{"title":"Network bandwidth is poor","message":"Your video may appear paused for others on the call.","dismissButtonAriaLabel":"Close"},"callCameraAccessDenied":{"title":"Unable to access camera","message":"Click the lock in the address bar to grant permission to this webpage.","dismissButtonAriaLabel":"Close"},"callCameraAccessDeniedSafari":{"title":"Unable to access camera","message":"Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","dismissButtonAriaLabel":"Close"},"callCameraAlreadyInUse":{"title":"Unable to access camera","message":"It may already be in use by another application.","dismissButtonAriaLabel":"Close"},"callVideoStoppedBySystem":{"title":"Your video has been stopped by your system.","dismissButtonAriaLabel":"Close"},"callVideoRecoveredBySystem":{"title":"Your video has resumed.","dismissButtonAriaLabel":"Close"},"callMacOsCameraAccessDenied":{"title":"MacOS is blocking access to your camera","message":"Update your privacy settings to allow this browser to access your camera.","dismissButtonAriaLabel":"Close"},"callMacOsScreenShareAccessDenied":{"title":"MacOS is blocking screen sharing","message":"Update your privacy settings to allow this browser to record your screen.","dismissButtonAriaLabel":"Close"},"failedToJoinCallGeneric":{"title":"Failed to join call.","dismissButtonAriaLabel":"Close"},"failedToJoinCallInvalidMeetingLink":{"title":"Unable to join Meeting. Invalid Link.","dismissButtonAriaLabel":"Close"},"cameraFrozenForRemoteParticipants":{"title":"Users in the call are having issues seeing your video","message":"Please check your devices and network.","dismissButtonAriaLabel":"Close"},"unableToStartVideoEffect":{"title":"Unable to apply video effect.","dismissButtonAriaLabel":"Close"},"startSpotlightWhileMaxParticipantsAreSpotlighted":{"title":"Cannot start spotlight on participant(s)","message":"The maximum number of participants are already spotlighted.","dismissButtonAriaLabel":"Close"},"mutedByRemoteParticipant":{"title":"You were muted by another participant.","dismissButtonAriaLabel":"Close"},"recordingStarted":{"title":"Recording has started.","message":"By joining, you are giving consent for this meeting to be transcribed.","dismissButtonAriaLabel":"Close"},"transcriptionStarted":{"title":"Transcription has started.","message":"By joining, you are giving consent for this meeting to be transcribed.","dismissButtonAriaLabel":"Close"},"recordingStopped":{"title":"Recording is being saved.","message":"Recording has stopped.","dismissButtonAriaLabel":"Close"},"transcriptionStopped":{"title":"Transcription is being saved.","message":"Transcription has stopped.","dismissButtonAriaLabel":"Close"},"recordingAndTranscriptionStarted":{"title":"Recording and transcription have started.","message":"By joining, you are giving consent for this meeting to be transcribed.","dismissButtonAriaLabel":"Close"},"recordingAndTranscriptionStopped":{"title":"Recording and transcription are being saved.","message":"Recording and transcription have stopped.","dismissButtonAriaLabel":"Close"},"recordingStoppedStillTranscribing":{"title":"Recording has stopped.","message":"You are now only transcribing this meeting.","dismissButtonAriaLabel":"Close"},"transcriptionStoppedStillRecording":{"title":"Transcription has stopped.","message":"You are now only recording this meeting.","dismissButtonAriaLabel":"Close"},"assignedBreakoutRoomOpened":{"title":"We\'ll move you to your assigned room in 5 seconds.","dismissButtonAriaLabel":"Close"},"assignedBreakoutRoomChanged":{"title":"Your breakout room has changed","message":"We\'ll move you to your assigned room in 5 seconds.","dismissButtonAriaLabel":"Close"},"assignedBreakoutRoomClosed":{"title":"Your breakout room has closed","message":"We\'ll move you back to your meeting in 5 seconds.","dismissButtonAriaLabel":"Close"},"assignedBreakoutRoomOpenedPromptJoin":{"title":"Join breakout room?","message":"You\'ve been assigned to a breakout room.","dismissButtonAriaLabel":"Close","primaryButtonLabel":"Join room","secondaryButtonLabel":"Later"},"breakoutRoomJoined":{"title":"You have joined a breakout room.","dismissButtonAriaLabel":"Close"},"breakoutRoomClosingSoon":{"title":"Room time limit about to expire.","message":"This room will close in 30 seconds","dismissButtonAriaLabel":"Close"},"capabilityTurnVideoOnPresent":{"title":"Your camera has been enabled","message":"Turn it on if you\'d like to share video.","dismissButtonAriaLabel":"Close"},"capabilityTurnVideoOnAbsent":{"title":"Your camera has been disabled","message":"You can no longer share video.","dismissButtonAriaLabel":"Close"},"capabilityUnmuteMicPresent":{"title":"Your mic has been enabled","message":"Unmute if you\'d like to speak.","dismissButtonAriaLabel":"Close"},"capabilityUnmuteMicAbsent":{"title":"Your mic has been disabled","message":"You can no longer unmute.","dismissButtonAriaLabel":"Close"},"togetherModeStarted":{"title":"Togethermode has started","dismissButtonAriaLabel":"Close"},"togetherModeEnded":{"title":"Togethermode has ended","dismissButtonAriaLabel":"Close"}},"videoGallery":{"screenIsBeingSharedMessage":"You are sharing your screen","screenShareLoadingMessage":"Loading {participant}\'s screen","localScreenShareLoadingMessage":"Loading your screen","localVideoLabel":"You","localVideoCameraSwitcherLabel":"Switch camera","localVideoMovementLabel":"Movable Local Video Tile","localVideoMovementAriaLabel":"Movable Local Video Tile","localVideoSelectedDescription":"{cameraName} selected","displayNamePlaceholder":"Unnamed participant","fitRemoteParticipantToFrame":"Fit to frame","fillRemoteParticipantFrame":"Fill frame","pinParticipantForMe":"Pin for me","pinParticipantForMeLimitReached":"Pin (limit reached)","unpinParticipantForMe":"Unpin","pinParticipantMenuItemAriaLabel":"Pin {participantName}","unpinParticipantMenuItemAriaLabel":"Unpin {participantName}","pinnedParticipantAnnouncementAriaLabel":"Pinned {participantName}","unpinnedParticipantAnnouncementAriaLabel":"Unpinned {participantName}","startSpotlightVideoTileMenuLabel":"Spotlight for everyone","addSpotlightVideoTileMenuLabel":"Add spotlight","spotlightLimitReachedMenuTitle":"Spotlight limit reached","stopSpotlightVideoTileMenuLabel":"Stop spotlighting","stopSpotlightOnSelfVideoTileMenuLabel":"Exit spotlight","attendeeRole":"Attendee","muteParticipantMenuItemLabel":"Mute","waitingScreenText":"Waiting for others to join","forbidAudio":"Disable mic","permitAudio":"Allow mic","forbidAudioTileMenuLabel":"Disable mic","permitAudioTileMenuLabel":"Allow mic","forbidVideo":"Disable camera","permitVideo":"Allow camera","forbidVideoTileMenuLabel":"Disable camera","permitVideoTileMenuLabel":"Allow camera"},"dialpad":{"placeholderText":"Enter phone number","deleteButtonAriaLabel":"Delete"},"holdButton":{"onLabel":"Resume","offLabel":"Hold","tooltipOnContent":"Resume call","tooltipOffContent":"Hold call"},"videoTile":{"participantStateRinging":"Calling...","participantReconnecting":"Reconnecting...","participantStateHold":"On hold","moreOptionsButtonAriaLabel":"More Options {displayName} {isMuted} {micDisabledState} {cameraDisabledState} {isHandRaised} {state} {isSpeaking}","moreOptionsParticipantMutedStateMutedAriaLabel":"muted","moreOptionsParticipantMutedStateUnmutedAriaLabel":"unmuted","moreOptionsParticipantHandRaisedAriaLabel":"Hand raised","moreOptionsParticipantIsSpeakingAriaLabel":"Speaking","moreOptionsParticipantMicDisabledAriaLabel":"Microphone disabled","moreOptionsParticipantCameraDisabledAriaLabel":"Camera disabled"},"CameraAndMicrophoneSitePermissionsRequest":{"primaryText":"Allow {appName} to use your camera and microphone","secondaryText":"This is so participants can see and hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera and microphone","ariaLabel":"Allow camera and microphone access"},"CameraSitePermissionsRequest":{"primaryText":"Allow {appName} to use your camera","secondaryText":"This is so participants can see you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera","ariaLabel":"Allow camera access"},"MicrophoneSitePermissionsRequest":{"primaryText":"Allow {appName} to use your microphone","secondaryText":"This is so participants can hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without microphone","ariaLabel":"Allow microphone access"},"CameraAndMicrophoneSitePermissionsCheck":{"primaryText":"Checking for camera and microphone access","secondaryText":"Allow access if prompted. This is so participants can see and hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera and microphone","ariaLabel":"Checking for camera and microphone access. Allow access if prompted."},"CameraSitePermissionsCheck":{"primaryText":"Checking for camera access","secondaryText":"Allow access if prompted. This is so participants can see you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera","ariaLabel":"Checking for camera access. Allow access if prompted."},"MicrophoneSitePermissionsCheck":{"primaryText":"Checking for microphone access","secondaryText":"Allow access if prompted. This is so participants can hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without microphone","ariaLabel":"Checking for microphone access. Allow access if prompted."},"CameraAndMicrophoneSitePermissionsDenied":{"primaryText":"Unable to access camera and microphone","secondaryText":"Click the lock icon in the address bar to grant microphone permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without camera and microphone","linkText":"Need help? Get troubleshooting help"},"CameraAndMicrophoneSitePermissionsDeniedSafari":{"primaryText":"Unable to access camera and microphone","secondaryText":"Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without camera and microphone","linkText":"Need help? Get troubleshooting help"},"CameraSitePermissionsDenied":{"primaryText":"Unable to access camera","secondaryText":"Click the lock icon in the address bar to grant camera permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without camera","linkText":"Need help? Get troubleshooting help"},"MicrophoneSitePermissionsDenied":{"primaryText":"Unable to access microphone","secondaryText":"Click the lock icon in the address bar to grant microphone permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without microphone","linkText":"Need help? Get troubleshooting help"},"CameraSitePermissionsDeniedSafari":{"primaryText":"Unable to access camera","secondaryText":"Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without camera","linkText":"Need help? Get troubleshooting help"},"MicrophoneSitePermissionsDeniedSafari":{"primaryText":"Unable to access microphone","secondaryText":"Refresh the page to allow permissions, or check this browsers settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without microphone","linkText":"Need help? Get troubleshooting help"},"UnsupportedBrowser":{"primaryText":"Browser not supported","secondaryText":"Please join this call using a compatible browser.","moreHelpLinkText":"See compatibility requirements"},"UnsupportedBrowserVersion":{"primaryText":"Browser update needed","secondaryText":"To ensure the best call possible, please update your browser and then try joining the call again.","moreHelpLinkText":"See compatibility requirements","continueAnywayButtonText":"Start call without updating"},"UnsupportedOperatingSystem":{"primaryText":"Operating system not supported","secondaryText":"Please join this call using a device with a compatible operating system.","moreHelpLinkText":"See compatibility requirements"},"BrowserPermissionDenied":{"primaryText":"Can\'t use your camera or microphone","secondaryText":"Your browser might not have access to your camera or microphone. To fix this, open System Preferences.","primaryButtonText":"Try again","linkText":"Need help? Get troubleshooting help"},"BrowserPermissionDeniedIOS":{"primaryText":"Allow microphone access to continue","secondaryText":"So other participants can hear you.","primaryButtonText":"Try again","imageAltText":"Microphone and camera device permission location for iOS","linkText":"Need help? Get troubleshooting help","step1Text":"Go to the Settings app","step2Text":"Scroll down to settings for this browser","step3Text":"Turn on Microphone (Camera optional)","step4Text":"Try joining the call again","step1DigitText":"1","step2DigitText":"2","step3DigitText":"3","step4DigitText":"4"},"verticalGallery":{"leftNavButtonAriaLabel":"previous page {current} of {total}","rightNavButtonAriaLabel":"next page {current} of {total}"},"meetingConferencePhoneInfo":{"meetingConferencePhoneInfoModalTitle":"Join call from your phone","meetingConferencePhoneInfoModalDialIn":"Dial number","meetingConferencePhoneInfoModalMeetingId":"Enter meeting ID","meetingConferencePhoneInfoModalWait":"Wait to be admitted by organizer","meetingConferencePhoneInfoModalNoPhoneAvailable":"No phone available","meetingConferencePhoneInfoModalTollGeoData":"{country}, {city}","meetingConferencePhoneInfoModalTollFree":"(Toll-free)","meetingConferencePhoneInfoModalToll":"(Toll)"},"IncomingCallNotification":{"incomingCallNotificationPlaceholderId":"Unknown User","incomingCallNotificationPlaceholderAlert":"{callerName} is calling","incomingCallNoticicationAcceptWithAudioAriaLabel":"Accept with audio","incomingCallNoticicationAcceptWithVideoAriaLabel":"Accept with video","incomingCallNoticicationRejectAriaLabel":"Reject","incomingCallNotificationAcceptButtonLabel":"Accept","incomingCallNotificationRejectButtonLabel":"Decline","incomingCallNotificationAccceptWithVideoButtonLabel":"Accept with Video","incomingCallNotificationDismissButtonAriaLabel":"Dismiss"}}')},IK=(0,e.createContext)(_K),wK=t=>{const{locale:i,children:n}=t;return e.createElement(IK.Provider,{value:i},n)},AK=()=>(0,e.useContext)(IK),PK=(e,t)=>e?t?e.replace(/{(\w+)}/g,((e,i)=>{const n=t[i];return void 0===n?`{${i}}`:n})):e:"",RK=(e,t)=>{var i;const n=new Date(Date.now());for(const i of e)if(i.type===t.type)return i.dismissedAt=n,i.activeSince=t.timestamp,Array.from(e);const r=null!==(i=t.timestamp)&&void 0!==i?i:n;return[...e,{type:t.type,dismissedAt:n>r?n:r,activeSince:t.timestamp}]},MK=(e,t)=>{const i=new Map;for(const t of e)i.set(t.type,t);const n=e=>void 0===e.activeSince&&void 0===i.get(e.type);return t.some((e=>n(e)))?t.filter((e=>!n(e))):t},DK=(e,t,i)=>{const n=new Map;for(const e of t)n.set(e.type,e);return e.filter((e=>{if(i&&e.timestamp&&i>e.timestamp)return!1;const t=n.get(e.type);return!t||!!e.timestamp&&e.timestamp>t.dismissedAt}))},kK=e=>{switch(e){case"callNetworkQualityLow":case"callNoSpeakerFound":case"callNoMicrophoneFound":case"callMicrophoneAccessDenied":case"callMicrophoneAccessDeniedSafari":case"callMicrophoneMutedBySystem":case"callMicrophoneUnmutedBySystem":case"callMacOsMicrophoneAccessDenied":case"callLocalVideoFreeze":case"callCameraAccessDenied":case"callCameraAccessDeniedSafari":case"callCameraAlreadyInUse":case"callVideoStoppedBySystem":case"callVideoRecoveredBySystem":case"callMacOsCameraAccessDenied":case"callMacOsScreenShareAccessDenied":case"startScreenShareGeneric":case"cameraFrozenForRemoteParticipants":return eK.warning;default:return eK.error}},OK=e=>{const t=NK[e];return t?{iconName:t}:void 0},NK={callNetworkQualityLow:"ErrorBarCallNetworkQualityLow",callNoSpeakerFound:"ErrorBarCallNoSpeakerFound",callNoMicrophoneFound:"ErrorBarCallNoMicrophoneFound",callMicrophoneAccessDenied:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneAccessDeniedSafari:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneMutedBySystem:"ErrorBarCallMicrophoneMutedBySystem",callMicrophoneUnmutedBySystem:"ErrorBarCallMicrophoneUnmutedBySystem",callMacOsMicrophoneAccessDenied:"ErrorBarCallMacOsMicrophoneAccessDenied",callLocalVideoFreeze:"ErrorBarCallLocalVideoFreeze",callCameraAccessDenied:"ErrorBarCallCameraAccessDenied",callCameraAccessDeniedSafari:"ErrorBarCallCameraAccessDenied",callCameraAlreadyInUse:"ErrorBarCallCameraAlreadyInUse",callVideoStoppedBySystem:"ErrorBarCallVideoStoppedBySystem",callVideoRecoveredBySystem:"ErrorBarCallVideoRecoveredBySystem",callMacOsCameraAccessDenied:"ErrorBarCallMacOsCameraAccessDenied"},LK=e=>{const t=xK[e];return t?{iconName:t}:void 0},xK={callNetworkQualityLow:"ErrorBarCallNetworkQualityLow",teamsMeetingCallNetworkQualityLow:"ErrorBarCallNetworkQualityLow",callNoSpeakerFound:"ErrorBarCallNoSpeakerFound",callNoMicrophoneFound:"ErrorBarCallNoMicrophoneFound",callMicrophoneAccessDenied:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneAccessDeniedSafari:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneMutedBySystem:"ErrorBarCallMicrophoneMutedBySystem",callMicrophoneUnmutedBySystem:"ErrorBarCallMicrophoneUnmutedBySystem",callMacOsMicrophoneAccessDenied:"ErrorBarCallMacOsMicrophoneAccessDenied",callLocalVideoFreeze:"ErrorBarCallLocalVideoFreeze",callCameraAccessDenied:"ErrorBarCallCameraAccessDenied",callCameraAccessDeniedSafari:"ErrorBarCallCameraAccessDenied",callCameraAlreadyInUse:"ErrorBarCallCameraAlreadyInUse",callVideoStoppedBySystem:"ErrorBarCallVideoStoppedBySystem",callVideoRecoveredBySystem:"ErrorBarCallVideoRecoveredBySystem",callMacOsCameraAccessDenied:"ErrorBarCallMacOsCameraAccessDenied",mutedByRemoteParticipant:"ErrorBarMutedByRemoteParticipant",speakingWhileMuted:"ErrorBarCallMicrophoneMutedBySystem",recordingStarted:"NotificationBarRecording",transcriptionStarted:"NotificationBarRecording",recordingStopped:"NotificationBarRecording",transcriptionStopped:"NotificationBarRecording",recordingAndTranscriptionStarted:"NotificationBarRecording",recordingAndTranscriptionStopped:"NotificationBarRecording",recordingStoppedStillTranscribing:"NotificationBarRecording",transcriptionStoppedStillRecording:"NotificationBarRecording",assignedBreakoutRoomOpened:"NotificationBarBreakoutRoomOpened",assignedBreakoutRoomOpenedPromptJoin:"NotificationBarBreakoutRoomPromptJoin",assignedBreakoutRoomChanged:"NotificationBarBreakoutRoomChanged",assignedBreakoutRoomClosed:"NotificationBarBreakoutRoomClosed",breakoutRoomJoined:"NotificationBarBreakoutRoomJoined",breakoutRoomClosingSoon:"NotificationBarBreakoutRoomClosingSoon",capabilityTurnVideoOnPresent:"ControlButtonCameraOff",capabilityTurnVideoOnAbsent:"ControlButtonCameraProhibited",capabilityUnmuteMicPresent:"ControlButtonMicOff",capabilityUnmuteMicAbsent:"ControlButtonMicProhibited",togetherModeStarted:"NotificationBarTogetherModeIcon",togetherModeEnded:"NotificationBarTogetherModeIcon"},FK=e=>!!e&&e.length>0,UK="en-us",BK=t=>{var i;const n=AK().strings.errorBar,r=null!==(i=t.strings)&&void 0!==i?i:n,s=!t.onDismissError,a=(0,e.useRef)(new Date(Date.now())),[o,l]=(0,e.useState)([]);(0,e.useEffect)((()=>{s&&l(MK(t.activeErrorMessages,o))}),[t.activeErrorMessages,o,s]);const c=DK(t.activeErrorMessages,o,t.ignorePremountErrors?a.current:void 0);return e.createElement(Y$,{"data-ui-id":"notifications-stack"},c.map((i=>e.createElement(bK,Object.assign({},t,{styles:{innerText:{alignSelf:"center"},icon:{height:0},content:{lineHeight:"inherit"},dismissal:{height:"2rem",paddingBottom:"0.8rem"}},key:i.type,messageBarType:kK(i.type),messageBarIconProps:OK(i.type),onDismiss:()=>{var e;return s?l(RK(o,i)):null===(e=t.onDismissError)||void 0===e?void 0:e.call(t,i)},dismissButtonAriaLabel:`${r[i.type]}, ${r.dismissButtonAriaLabel}`,dismissIconProps:{iconName:"ErrorBarClear"}}),r[i.type]))))};var VK,HK,$K,jK,GK=e.createContext(void 0),qK=function(){var t=e.useContext(GK),i=tj(["theme"]).theme;return t||i||NH({})},zK=0,WK=function(){return zK},KK=function(e,t){return t$(Array.isArray(e)?e:[e],t)},JK=(VK=function(e){var t=e.semanticColors,i=e.fonts;return{body:[{color:t.bodyText,background:t.bodyBackground,fontFamily:i.medium.fontFamily,fontWeight:i.medium.fontWeight,fontSize:i.medium.fontSize,MozOsxFontSmoothing:i.medium.MozOsxFontSmoothing,WebkitFontSmoothing:i.medium.WebkitFontSmoothing}]}},HK=new Map,$K=new Set,jK=function(e){var t=e.currentTarget,i=t.__id__;HK.delete(i),t.removeEventListener("unload",jK),$K.delete(i)},function(t){void 0===t&&(t={});var i,n=t.theme,r=Jq();r&&(r.__id__=r.__id__||u$(),i=r.__id__,$K.has(i)||($K.add(i),r.addEventListener("unload",jK)));var s=qK();n=n||s;var a=WK(),o=[i,a,n],l=function(e,t){var i,n,r,s=t[0],a=t[1],o=t[2];return null===(r=null===(n=null===(i=e.get(s))||void 0===i?void 0:i.get(a))||void 0===n?void 0:n.get(o))||void 0===r?void 0:r.classMap}(HK,o);if(e.useEffect((function(){return function(e,t){var i,n,r=t[0],s=t[1],a=t[2],o=null===(n=null===(i=e.get(r))||void 0===i?void 0:i.get(s))||void 0===n?void 0:n.get(a);o&&o.refCount++}(HK,[i,a,n]),function(){return function(e,t){var i,n,r,s,a,o,l,c,d=t[0],u=t[1],h=t[2],g=null===(n=null===(i=e.get(d))||void 0===i?void 0:i.get(u))||void 0===n?void 0:n.get(h);g&&(g.refCount--,0===g.refCount&&(null===(s=null===(r=e.get(d))||void 0===r?void 0:r.get(u))||void 0===s||s.delete(h),0===(null===(o=null===(a=e.get(d))||void 0===a?void 0:a.get(u))||void 0===o?void 0:o.size)&&(null===(l=e.get(d))||void 0===l||l.delete(u),0===(null===(c=e.get(d))||void 0===c?void 0:c.size)&&e.delete(d))))}(HK,[i,a,n])}}),[i,a,n]),!l){var c=function(e){return"function"==typeof e}(VK)?VK(n):VK;l=KK(c,{targetWindow:r,rtl:!!n.rtl}),function(e,t,i){var n,r,s=t[0],a=t[1],o=t[2],l=null!==(n=e.get(s))&&void 0!==n?n:new Map;e.set(s,l);var c=null!==(r=l.get(a))&&void 0!==r?r:new Map;l.set(a,c),c.set(o,{classMap:i,refCount:0})}(HK,o,l)}return l});var YK={label:S$,audio:y$,video:C$,ol:T$,li:E$,a:b$,button:_$,input:I$,textarea:w$,select:A$,option:P$,table:R$,tr:M$,th:D$,td:k$,colGroup:O$,col:N$,form:L$,iframe:x$,img:F$},QK=function(t){var i,n=t.customizerContext,r=t.ref,s=t.theme,a=t.as||"div",o="string"==typeof t.as?B$(t,(i=t.as)&&YK[i]||v$,undefined):t.as===e.Fragment?{children:t.children}:function(e,t){var i={};for(var n in e)-1===t.indexOf(n)&&e.hasOwnProperty(n)&&(i[n]=e[n]);return i}(t,["as"]);return e.createElement(GK.Provider,{value:s},e.createElement(s$.Provider,{value:n},e.createElement(Tz,{providerRef:r},e.createElement(a,IU({},o)))))},ZK=new Map,XK=e.forwardRef((function(t,i){var n=function(t,i){var n,r,s,a,o=sq(i,t);return r=(n=o).theme,s=qK(),a=n.theme=e.useMemo((function(){var e=kH(s,r);return e.id=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=[],n=0,r=e;n<r.length;n++){var s=r[n];if(s){var a=s.id||ZK.get(s);a||(a=u$(""),ZK.set(s,a)),i.push(a)}}return i.join("-")}(s,r),e}),[s,r]),n.customizerContext=e.useMemo((function(){return{customizations:{inCustomizerContext:!0,settings:{theme:a},scopedSettings:a.components||{}}}}),[a]),n.theme.rtl!==s.rtl&&(n.dir=n.theme.rtl?"rtl":"ltr"),{state:o,render:QK}}(t,{ref:nG(i,e.useRef(null)),as:"div",applyTo:"element"}),r=n.render,s=n.state;return function(t){var i=JK(t),n=t.className,r=t.applyTo;!function(t,i){var n,r="body"===t.applyTo,s=null===(n=Yq())||void 0===n?void 0:n.body;e.useEffect((function(){if(r&&s){for(var e=0,t=i;e<t.length;e++){var n=t[e];n&&s.classList.add(n)}return function(){if(r&&s)for(var e=0,t=i;e<t.length;e++){var n=t[e];n&&s.classList.remove(n)}}}}),[r,s,i])}(t,[i.root,i.body]),t.className=V$(n,i.root,"element"===r&&i.body)}(s),r(s)}));XK.displayName="ThemeProvider";const eJ={palette:{themePrimary:"#0078d4",themeLighterAlt:"#eff6fc",themeLighter:"#deecf9",themeLight:"#c7e0f4",themeTertiary:"#71afe5",themeSecondary:"#2b88d8",themeDarkAlt:"#106ebe",themeDark:"#59b0f7",themeDarker:"#004578",neutralLighterAlt:"#faf9f8",neutralLighter:"#f3f2f1",neutralLight:"#edebe9",neutralQuaternaryAlt:"#e1dfdd",neutralQuaternary:"#d0d0d0",neutralTertiaryAlt:"#c8c6c4",neutralTertiary:"#a19f9d",neutralSecondary:"#605e5c",neutralPrimaryAlt:"#3b3a39",neutralPrimary:"#323130",neutralDark:"#201f1e",black:"#000000",white:"#ffffff",whiteTranslucent40:"rgba(255, 255, 255, 0.4)"},callingPalette:{callRed:"#a42e43",callRedDark:"#8b2c3d",callRedDarker:"#772a38",iconWhite:"#ffffff",raiseHandGold:"#eaa300",videoTileLabelBackgroundLight:"rgba(255,255,255,0.8)"},semanticColors:{errorText:"#a80000"}},tJ=Object.assign(Object.assign({},NH(Object.assign(Object.assign({},{palette:{themePrimary:"#2899f5",themeLighterAlt:"#02060a",themeLighter:"#061827",themeLight:"#0c2e49",themeTertiary:"#185b93",themeSecondary:"#2286d7",themeDarkAlt:"#3ca2f6",themeDark:"#59b0f7",themeDarker:"#84c5f9",neutralLighterAlt:"#302e2d",neutralLighter:"#383735",neutralLight:"#464443",neutralQuaternaryAlt:"#4e4d4b",neutralQuaternary:"#4d4b49",neutralTertiaryAlt:"#72706e",neutralTertiary:"#c8c8c8",neutralSecondary:"#d0d0d0",neutralPrimaryAlt:"#dadada",neutralPrimary:"#ffffff",neutralDark:"#f4f4f4",black:"#f8f8f8",white:"#252423",whiteTranslucent40:"rgba(0, 0, 0, 0.4)"},semanticColors:{errorText:"#f1707b"}}),{isInverted:!0}))),{callingPalette:{callRed:"#c4314b",callRedDark:"#a42e43",callRedDarker:"#8b2c3d",iconWhite:"#ffffff",raiseHandGold:"#eaa300",videoTileLabelBackgroundLight:"rgba(37,36,35,0.8)"}}),iJ=(tJ.palette,Object.assign(Object.assign({},tJ.semanticColors),{bodyBackground:"rgba(0, 0, 0, 0.85)"}),dB({height:"100%",width:"100%","*":{boxSizing:"border-box"},"*:before":{boxSizing:"border-box"},"*:after":{boxSizing:"border-box"},"[hidden]":{display:"none!important"}})),nJ=Object.assign({},kH(BH(),eJ)),rJ=(0,e.createContext)(nJ),sJ=t=>{const{fluentTheme:i,rtl:n,children:r,rootStyle:s}=t,a=(0,e.useMemo)((()=>{const e=kH(nJ,i);return kH(e,{rtl:n})}),[i,n]);return e.createElement(rJ.Provider,{value:a},e.createElement(XK,{theme:a,className:iJ,style:s},r))},aJ=()=>(0,e.useContext)(rJ);var oJ=a$((function(e){if(null==e.children)return null;e.block,e.className;var t=e.as,i=void 0===t?"span":t,n=(e.variant,e.nowrap,wU(e,["block","className","as","variant","nowrap"]));return MB(OB(e,{root:i}).root,IU({},B$(n,v$)))}),{displayName:"Text",styles:function(e,t){var i=e.as,n=e.className,r=e.block,s=e.nowrap,a=e.variant,o=t.fonts,l=t.semanticColors,c=o[a||"medium"];return{root:[c,{color:c.color||l.bodyText,display:r?"td"===i?"table-cell":"block":"inline",mozOsxFontSmoothing:c.MozOsxFontSmoothing,webkitFontSmoothing:c.WebkitFontSmoothing},s&&{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},n]}}}),lJ=oj(),cJ=function(e,t){t.as;var i=t.disabled,n=t.target,r=t.href,s=(t.theme,t.getStyles,t.styles,t.componentRef,t.underline,wU(t,["as","disabled","target","href","theme","getStyles","styles","componentRef","underline"]));return"string"==typeof e?"a"===e?IU({target:n,href:i?void 0:r},s):"button"===e?IU({type:"button",disabled:i},s):IU(IU({},s),{disabled:i}):IU({target:n,href:r,disabled:i},s)},dJ=e.forwardRef((function(t,i){var n=function(t,i){var n=t.as,r=t.className,s=t.disabled,a=t.href,o=t.onClick,l=t.styles,c=t.theme,d=t.underline,u=e.useRef(null),h=nG(u,i);(function(t,i){e.useImperativeHandle(t.componentRef,(function(){return{focus:function(){i.current&&i.current.focus()}}}),[i])})(t,u),qj(u);var g=lJ(l,{className:r,isButton:!a,isDisabled:s,isUnderlined:d,theme:c}),p=n||(a?"a":"button");return{state:{},slots:{root:p},slotProps:{root:IU(IU({},cJ(p,t)),{"aria-disabled":s,className:g.root,onClick:function(e){s?e.preventDefault():o&&o(e)},ref:h})}}}(t,i),r=n.slots,s=n.slotProps;return e.createElement(r.root,IU({},s.root))}));dJ.displayName="LinkBase";var uJ={root:"ms-Link"},hJ=nj(dJ,(function(e){var t,i,n,r,s,a,o,l=e.className,c=e.isButton,d=e.isDisabled,u=e.isUnderlined,h=e.theme,g=h.semanticColors,p=g.link,m=g.linkHovered,f=g.disabledText,v=g.focusBorder,S=FV(uJ,h);return{root:[S.root,h.fonts.medium,{color:p,outline:"none",fontSize:"inherit",fontWeight:"inherit",textDecoration:u?"underline":"none",selectors:(t={},t[".".concat(GV," &:focus, :host(.").concat(GV,") &:focus")]={boxShadow:"0 0 0 1px ".concat(v," inset"),outline:"1px auto ".concat(v),selectors:(i={},i[UV]={outline:"1px solid WindowText"},i)},t[UV]={borderBottom:"none"},t)},c&&{background:"none",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"inline",margin:0,overflow:"inherit",padding:0,textAlign:"left",textOverflow:"inherit",userSelect:"text",borderBottom:"1px solid transparent",selectors:(n={},n[UV]={color:"LinkText",forcedColorAdjust:"none"},n)},!c&&{selectors:(r={},r[UV]={MsHighContrastAdjust:"auto",forcedColorAdjust:"auto"},r)},d&&["is-disabled",{color:f,cursor:"default"},{selectors:(s={"&:link, &:visited":{pointerEvents:"none"}},s[UV]={color:"GrayText"},s)}],!d&&{selectors:{"&:active, &:hover, &:active:hover":{color:m,textDecoration:"underline",selectors:(a={},a[UV]={color:"LinkText"},a)},"&:focus":{color:p,selectors:(o={},o[UV]={color:"LinkText"},o)}}},S.root,l]}}),void 0,{scope:"Link"}),gJ=SB((function(e,t,i){var n=rK(e),r=sK(e);return ZH(n,{root:{minWidth:"80px",minHeight:"32px"},label:{fontWeight:DV.semibold}},i?function(e){var t,i,n,r,s,a,o,l,c,d=e.palette,u=e.semanticColors;return{root:(t={backgroundColor:u.primaryButtonBackground,border:"1px solid ".concat(u.primaryButtonBackground),color:u.primaryButtonText},t[UV]=IU({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t[".".concat(GV," &:focus, :host(.").concat(GV,") &:focus")]={":after":{border:"none",outlineColor:d.white}},t),rootHovered:(i={backgroundColor:u.primaryButtonBackgroundHovered,border:"1px solid ".concat(u.primaryButtonBackgroundHovered),color:u.primaryButtonTextHovered},i[UV]={color:"Window",backgroundColor:"Highlight",borderColor:"Highlight"},i),rootPressed:(n={backgroundColor:u.primaryButtonBackgroundPressed,border:"1px solid ".concat(u.primaryButtonBackgroundPressed),color:u.primaryButtonTextPressed},n[UV]=IU({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n),rootExpanded:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootChecked:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootCheckedHovered:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootDisabled:(r={color:u.primaryButtonTextDisabled,backgroundColor:u.primaryButtonBackgroundDisabled},r[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},r),splitButtonContainer:(s={},s[UV]={border:"none"},s),splitButtonDivider:IU(IU({},{position:"absolute",width:1,right:31,top:8,bottom:8}),(a={backgroundColor:d.white},a[UV]={backgroundColor:"Window"},a)),splitButtonMenuButton:(o={backgroundColor:u.primaryButtonBackground,color:u.primaryButtonText},o[UV]={backgroundColor:"Canvas"},o[":hover"]=(l={backgroundColor:u.primaryButtonBackgroundHovered},l[UV]={color:"Highlight"},l),o),splitButtonMenuButtonDisabled:{backgroundColor:u.primaryButtonBackgroundDisabled,":hover":{backgroundColor:u.primaryButtonBackgroundDisabled}},splitButtonMenuButtonChecked:{backgroundColor:u.primaryButtonBackgroundPressed,":hover":{backgroundColor:u.primaryButtonBackgroundPressed}},splitButtonMenuButtonExpanded:{backgroundColor:u.primaryButtonBackgroundPressed,":hover":{backgroundColor:u.primaryButtonBackgroundPressed}},splitButtonMenuIcon:{color:u.primaryButtonText},splitButtonMenuIconDisabled:(c={color:d.neutralTertiary},c[UV]={color:"GrayText"},c)}}(e):function(e){var t,i,n,r,s,a=e.semanticColors,o=e.palette,l=a.buttonBackground,c=a.buttonBackgroundPressed,d=a.buttonBackgroundHovered,u=a.buttonBackgroundDisabled,h=a.buttonText,g=a.buttonTextHovered,p=a.buttonTextDisabled,m=a.buttonTextChecked,f=a.buttonTextCheckedHovered;return{root:{backgroundColor:l,color:h},rootHovered:(t={backgroundColor:d,color:g},t[UV]={borderColor:"Highlight",color:"Highlight"},t),rootPressed:{backgroundColor:c,color:m},rootExpanded:{backgroundColor:c,color:m},rootChecked:{backgroundColor:c,color:m},rootCheckedHovered:{backgroundColor:c,color:f},rootDisabled:(i={color:p,backgroundColor:u},i[UV]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},i),splitButtonContainer:(n={},n[UV]={border:"none"},n),splitButtonMenuButton:{color:o.white,backgroundColor:"transparent",":hover":(r={backgroundColor:o.neutralLight},r[UV]={color:"Highlight"},r)},splitButtonMenuButtonDisabled:{backgroundColor:a.buttonBackgroundDisabled,":hover":{backgroundColor:a.buttonBackgroundDisabled}},splitButtonDivider:IU(IU({},{position:"absolute",width:1,right:31,top:8,bottom:8}),(s={backgroundColor:o.neutralTertiaryAlt},s[UV]={backgroundColor:"WindowText"},s)),splitButtonDividerDisabled:{backgroundColor:e.palette.neutralTertiaryAlt},splitButtonMenuButtonChecked:{backgroundColor:o.neutralQuaternaryAlt,":hover":{backgroundColor:o.neutralQuaternaryAlt}},splitButtonMenuButtonExpanded:{backgroundColor:o.neutralQuaternaryAlt,":hover":{backgroundColor:o.neutralQuaternaryAlt}},splitButtonMenuIcon:{color:a.buttonText},splitButtonMenuIconDisabled:{color:a.buttonTextDisabled}}}(e),r,t)})),pJ=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.primary,n=void 0!==i&&i,r=t.styles,s=t.theme;return e.createElement(KW,IU({},this.props,{variantClassName:n?"ms-Button--primary":"ms-Button--default",styles:gJ(s,r,n),onRenderDescription:Fj}))},AU([XW("DefaultButton",["theme","styles"],!0)],i)}(e.Component),mJ=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){return e.createElement(pJ,IU({},this.props,{primary:!0,onRenderDescription:Fj}))},AU([XW("PrimaryButton",["theme","styles"],!0)],i)}(e.Component);const fJ={iconName:"Cancel"},vJ=e=>e/16+"rem",SJ=e=>({root:{fontWeight:400,fontSize:vJ(14),lineHeight:vJ(16),color:e.palette.neutralSecondary,marginTop:"0.25rem"}}),yJ=e=>({root:{boxShadow:e.effects.elevation8,width:"20rem",padding:"0.75rem",borderRadius:"0.25rem",position:"relative",backgroundColor:e.palette.white}}),CJ=e=>dB({boxShadow:e.effects.elevation8,width:"19.5rem",borderRadius:"0.25rem",marginTop:"-0.65rem",height:"1rem"}),TJ=e=>({root:{color:e.palette.themePrimary,fontWeight:"600",paddingLeft:"0.25rem"}}),EJ=t=>{var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v;const S=t.notificationStrings,y=qK(),[C,T]=(0,e.useState)(!0),{ariaLive:E="assertive",role:b="alert"}=t;return t.autoDismiss&&(setTimeout((()=>{T(!1)}),5e3),!C)?(t.onDismiss&&t.onDismiss(),e.createElement(e.Fragment,null)):e.createElement(Y$,{horizontalAlign:"center","aria-live":E,role:b},e.createElement(Y$,{"data-ui-id":"notification-bar",styles:null!==(n=null===(i=t.styles)||void 0===i?void 0:i.root)&&void 0!==n?n:yJ(y)},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between"},e.createElement(Y$,{horizontal:!0},e.createElement(mG,Object.assign({styles:null!==(s=null===(r=t.styles)||void 0===r?void 0:r.icon)&&void 0!==s?s:{root:{fontSize:"1.25rem",alignSelf:"center",marginRight:"0.5rem",svg:{width:"1.25rem",height:"1.25rem"}}},iconName:null!==(o=null===(a=t.notificationIconProps)||void 0===a?void 0:a.iconName)&&void 0!==o?o:"ErrorBadge"},t.notificationIconProps)),e.createElement(oJ,{styles:null!==(c=null===(l=t.styles)||void 0===l?void 0:l.title)&&void 0!==c?c:{root:{fontWeight:400,fontSize:vJ(14),lineHeight:vJ(16),alignSelf:"center"}}},null==S?void 0:S.title)),t.onDismiss&&e.createElement(oK,{iconProps:fJ,ariaLabel:null==S?void 0:S.dismissButtonAriaLabel,"aria-live":"polite",onClick:t.onDismiss})),e.createElement("span",null,e.createElement(oJ,{styles:null!==(u=null===(d=t.styles)||void 0===d?void 0:d.content)&&void 0!==u?u:SJ(y)}," ",null==S?void 0:S.message),t.onClickLink&&(null==S?void 0:S.linkLabel)&&e.createElement(hJ,{styles:null!==(g=null===(h=t.styles)||void 0===h?void 0:h.link)&&void 0!==g?g:TJ(y),onClick:t.onClickLink},null==S?void 0:S.linkLabel)),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-evenly"},(null==S?void 0:S.secondaryButtonLabel)&&e.createElement(pJ,{onClick:t.onClickSecondaryButton,styles:null!==(m=null===(p=t.styles)||void 0===p?void 0:p.secondaryButton)&&void 0!==m?m:{root:{marginTop:"1rem"}}},null==S?void 0:S.secondaryButtonLabel),(null==S?void 0:S.primaryButtonLabel)&&e.createElement(mJ,{onClick:t.onClickPrimaryButton,styles:null!==(v=null===(f=t.styles)||void 0===f?void 0:f.primaryButton)&&void 0!==v?v:{root:{marginTop:"1rem"}}},null==S?void 0:S.primaryButtonLabel))),t.showStackedEffect&&e.createElement(Y$,{className:CJ(y)}))},bJ=t=>{var i,n;const r=AK().strings.notificationStack,s=null!==(i=t.strings)&&void 0!==i?i:r,a=null!==(n=t.maxNotificationsToShow)&&void 0!==n?n:2,o=!t.onDismissNotification,l=(0,e.useRef)(new Date(Date.now())),[c,d]=(0,e.useState)([]);(0,e.useEffect)((()=>{o&&d(((e,t)=>{const i=new Map;for(const t of e)i.set(t.type,t);const n=e=>void 0===e.activeSince&&void 0===i.get(e.type);return t.some((e=>n(e)))?t.filter((e=>!n(e))):t})(t.activeNotifications,c))}),[t.activeNotifications,c,o]);const u=((e,t,i)=>{const n=new Map;for(const e of t)n.set(e.type,e);return e.filter((e=>{if(i&&e.timestamp&&i>e.timestamp)return!1;const t=n.get(e.type);return!t||!!e.timestamp&&e.timestamp>t.dismissedAt}))})(t.activeNotifications,c,t.ignorePremountNotifications?l.current:void 0);return e.createElement(Y$,{"data-ui-id":"notifications-stack",style:{width:"fit-content"}},u.map(((i,n)=>{if(n<a){const r=()=>{var e;o?d(((e,t)=>{var i;const n=new Date(Date.now());for(const i of e)if(i.type===t.type)return i.dismissedAt=n,i.activeSince=t.timestamp,Array.from(e);const r=null!==(i=t.timestamp)&&void 0!==i?i:n;return[...e,{type:t.type,dismissedAt:n>r?n:r,activeSince:t.timestamp}]})(c,i)):null===(e=t.onDismissNotification)||void 0===e||e.call(t,i),i.onDismiss&&i.onDismiss()};return"assignedBreakoutRoomOpenedPromptJoin"===i.type&&(i.onClickSecondaryButton=i.onClickSecondaryButton?i.onClickSecondaryButton:()=>r()),e.createElement("div",{key:n,style:{marginBottom:`${n===a-1?0:"0.25rem"}`}},e.createElement(EJ,{notificationStrings:s?s[i.type]:void 0,notificationIconProps:LK(i.type),onClickPrimaryButton:()=>{var e;return null===(e=i.onClickPrimaryButton)||void 0===e?void 0:e.call(i)},onClickSecondaryButton:()=>{var e;return null===(e=i.onClickSecondaryButton)||void 0===e?void 0:e.call(i)},onDismiss:r,showStackedEffect:n===a-1&&u.length>a,autoDismiss:i.autoDismiss,ariaLive:i.ariaLive}))}return e.createElement(e.Fragment,null)})))};var _J=function(t){var i=e.useRef(t);i.current=t,e.useEffect((function(){return function(){var e;null===(e=i.current)||void 0===e||e.call(i)}}),[])},IJ=function(t){var i=t.className,n=e.useState((function(){return u$()}))[0],r=t.id,s=void 0===r?n:r,a=e.useRef({hostId:s,rootRef:e.useRef(null),notifyLayersChanged:function(){}});return e.useImperativeHandle(t.componentRef,(function(){return a.current})),e.useEffect((function(){!function(e,t){(kz[e]||(kz[e]=[])).unshift(t)}(s,a.current),Lz(s)}),[]),_J((function(){!function(e,t){var i=kz[e];if(i){var n=i.indexOf(t);n>=0&&i.splice(n,1),0===i.length&&delete kz[e]}}(s,a.current),Lz(s)})),e.createElement("div",IU({},t,{className:V$("ms-LayerHost",i),ref:a.current.rootRef}))};const wJ={component:_K,strings:JSON.parse('{"call":{"cameraLabel":"Camera","noCamerasLabel":"No cameras found","cameraPermissionDenied":"Your browser is blocking access to your camera","cameraTurnedOff":"Your camera is turned off","chatButtonLabel":"Chat","close":"Close","complianceBannerNowOnlyRecording":"You are now only recording this meeting.","complianceBannerNowOnlyTranscription":"You are now only transcribing this meeting.","complianceBannerRecordingAndTranscriptionSaved":"Recording and transcription are being saved.","complianceBannerRecordingAndTranscriptionStarted":"Recording and transcription have started.","complianceBannerRecordingAndTranscriptionStopped":"Recording and transcription have stopped.","complianceBannerRecordingSaving":"Recording is being saved.","complianceBannerRecordingStarted":"Recording has started.","complianceBannerRecordingStopped":"Recording has stopped.","complianceBannerTranscriptionStarted":"Transcription has started.","complianceBannerTranscriptionConsent":"By joining, you are giving consent for this meeting to be transcribed.","complianceBannerTranscriptionSaving":"Transcription is being saved.","complianceBannerTranscriptionStopped":"Transcription has stopped.","configurationPageTitle":"Start a call","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkButtonActionedLabel":"Link copied","copyInviteLinkActionedAriaLabel":"Invite link copied","defaultPlaceHolder":"Select an option","dismissSidePaneButtonLabel":"Close","videoEffectsPaneTitle":"Effects","videoEffectsPaneBackgroundSelectionTitle":"Background","videoEffectsPaneAriaLabel":"Video effects pane","configurationPageCameraIsLoadingLabel":"Video is loading...","configurationPageVideoEffectsButtonLabel":"Effects","unableToStartVideoEffect":"Unable to apply video effect.","blurBackgroundEffectButtonLabel":"Blur","blurBackgroundTooltip":"Blur Background","removeBackgroundEffectButtonLabel":"None","removeBackgroundTooltip":"Remove Background","cameraOffBackgroundEffectWarningText":"Your camera is off. Turn on camera to see video effect.","failedToJoinCallDueToNoNetworkMoreDetails":"Call was disconnected due to a network issue. Check your connection and join again.","failedToJoinCallDueToNoNetworkTitle":"Call disconnected","failedToJoinTeamsMeetingReasonAccessDeniedMoreDetails":"You were not granted entry in the call. If this was a mistake, re-join the call.","failedToJoinTeamsMeetingReasonAccessDeniedTitle":"Dismissed from lobby","learnMore":"Learn more","leavingCallTitle":"Leaving...","leftCallMoreDetails":"If this was a mistake, re-join the call.","leftCallTitle":"You left the call","lobbyScreenConnectingToCallTitle":"Joining call","lobbyScreenWaitingToBeAdmittedTitle":"Waiting to be admitted","microphonePermissionDenied":"Your browser is blocking access to your microphone","microphoneToggleInLobbyNotAllowed":"Cannot mute or unmute while in lobby.","mutedMessage":"You\'re muted","networkReconnectMoreDetails":"Looks like something went wrong. We\'re trying to get back into the call.","networkReconnectTitle":"Hold on","notInvitedToRoomDetails":"You are not able to join this room because you do not have an invite.","notInvitedToRoomTitle":"Not invited to room","peopleButtonLabel":"People","selectedPeopleButtonLabel":"People Button Selected","peoplePaneTitle":"People","peoplePaneMoreButtonAriaLabel":"More","peopleButtonTooltipOpen":"Show participants","peopleButtonTooltipClose":"Hide participants","peoplePaneSubTitle":"In this call {numberOfPeople}","privacyPolicy":"Privacy policy","rejoinCallButtonLabel":"Re-join call","removedFromCallMoreDetails":"Another participant removed you from the call.","removedFromCallTitle":"You were removed","removeMenuLabel":"Remove","startSpotlightMenuLabel":"Spotlight for everyone","addSpotlightMenuLabel":"Add spotlight","stopSpotlightMenuLabel":"Stop spotlighting","stopSpotlightOnSelfMenuLabel":"Exit spotlight","spotlightLimitReachedMenuTitle":"Spotlight limit reached","stopAllSpotlightMenuLabel":"Stop all spotlights","returnToCallButtonAriaDescription":"Return to Call","returnToCallButtonAriaLabel":"Back","roomNotFoundDetails":"The room ID provided could not be found.","roomNotFoundTitle":"Room not found","roomNotValidDetails":"This room is not valid at this current time.","roomNotValidTitle":"Room not valid","inviteToRoomRemovedDetails":"Your invite to join this room was removed.","inviteToRoomRemovedTitle":"Invite to room removed","soundLabel":"Sound","noMicrophonesLabel":"No microphones found","noSpeakersLabel":"No speakers found","startCallButtonLabel":"Start call","openDialpadButtonLabel":"Dial phone number","peoplePaneAddPeopleButtonLabel":"Add People","dialpadStartCallButtonLabel":"Call","dialpadModalTitle":"Dial Phone Number","dialpadModalAriaLabel":"Dialpad","dialpadCloseModalButtonAriaLabel":"Close dialpad","moreButtonCallingLabel":"More","resumeCallButtonLabel":"Resume","resumingCallButtonLabel":"Resuming...","resumeCallButtonAriaLabel":"Resume call","resumingCallButtonAriaLabel":"Resume call","holdScreenLabel":"You\'re on hold","openDtmfDialpadLabel":"Show dialpad","dtmfDialpadPlaceholderText":"Enter number","outboundCallingNoticeString":"Calling...","participantJoinedNoticeString":"{displayName} joined","twoParticipantJoinedNoticeString":"{displayName1} and {displayName2} have joined","threeParticipantJoinedNoticeString":"{displayName1}, {displayName2} and {displayName3} have joined","participantLeftNoticeString":"{displayName} left","twoParticipantLeftNoticeString":"{displayName1} and {displayName2} have left","threeParticipantLeftNoticeString":"{displayName1}, {displayName2} and {displayName3} have left","unnamedParticipantString":"unnamed participant","manyUnnamedParticipantsJoined":"unnamed participant and {numOfParticipants} other participants joined","manyUnnamedParticipantsLeft":"unnamed participant and {numOfParticipants} other participants left","manyParticipantsJoined":"{displayName1}, {displayName2}, {displayName3} and {numOfParticipants} other participants joined","manyParticipantsLeft":"{displayName1}, {displayName2}, {displayName3} and {numOfParticipants} other participants left","liveCaptionsLabel":"Live captions","captionsSettingsLabel":"Caption settings","startCaptionsButtonOnLabel":"Turn on captions","startCaptionsButtonOffLabel":"Turn off captions","startCaptionsButtonTooltipOnContent":"Turn off captions","startCaptionsButtonTooltipOffContent":"Turn on captions","captionsSettingsModalTitle":"Captions Settings","captionsSettingsSpokenLanguageDropdownLabel":"Spoken language","captionsSettingsCaptionLanguageDropdownLabel":"Captions language","captionsSettingsSpokenLanguageDropdownInfoText":"Language that everyone on this call is speaking.","captionsSettingsCaptionLanguageDropdownInfoText":"Captions will appear in this language.","captionsSettingsConfirmButtonLabel":"Confirm","captionsSettingsCancelButtonLabel":"Cancel","captionsSettingsModalAriaLabel":"Captions Setting Modal","captionsSettingsCloseModalButtonAriaLabel":"Close Captions Setting","captionsBannerMoreButtonCallingLabel":"Captions Settings More Options","captionsBannerMoreButtonTooltip":"More options","realTimeTextLabel":"Real-time text (RTT)","startRealTimeTextLabel":"Turn on RTT for this call","disabledStartRealTimeTextLabel":"RTT is currently turned on, it cannot be turned off","dismissModalAriaLabel":"Local and remote picture and picture, press enter to return to call","callRejectedTitle":"The call could not be completed","callRejectedMoreDetails":"The person you are trying to reach is unavailable. Please try again later.","callTimeoutTitle":"The call could not be completed","callTimeoutDetails":"The person you are trying to reach is unavailable. Please try again later.","callTimeoutBotTitle":"The call could not be completed","callTimeoutBotDetails":"The service that you are trying to reach is unavailable. Please try again later.","dtmfDialerButtonLabel":"Dialpad","dtmfDialerButtonTooltipOn":"Show dialpad","dtmfDialerButtonTooltipOff":"Hide dialpad","dtmfDialerMoreButtonLabelOn":"Show dialpad","dtmfDialerMoreButtonLabelOff":"Hide dialpad","phoneCallMoreButtonLabel":"Phone Call","spokenLanguageStrings":{"ar-ae":"Arabic - U.A.E.","ar-sa":"Arabic - Saudi Arabia","da-dk":"Danish","de-de":"German - Germany","en-au":"English - Australia","en-ca":"English - Canada","en-gb":"English - United Kingdom","en-in":"English - India","en-nz":"English - New Zealand","en-us":"English - United States","es-es":"Spanish - Spain (Modern Sort)","es-mx":"Spanish - Mexico","fi-fi":"Finnish","fr-ca":"French - Canada","fr-fr":"French - France","hi-in":"Hindi","it-it":"Italian - Italy","ja-jp":"Japanese","ko-kr":"Korean","nb-no":"Norwegian (Bokmål)","nl-be":"Dutch - Belgium","nl-nl":"Dutch - Netherlands","pl-pl":"Polish","pt-br":"Portuguese - Brazil","ru-ru":"Russian","sv-se":"Swedish","zh-cn":"Chinese - People\'s Republic of China","zh-hk":"Chinese - Hong Kong SAR","cs-cz":"Czech","pt-pt":"Portuguese - Portugal","tr-tr":"Turkish","vi-vn":"Vietnamese","th-th":"Thai","he-il":"Hebrew","cy-gb":"Welsh","uk-ua":"Ukrainian","el-gr":"Greek","hu-hu":"Hungarian","ro-ro":"Romanian","sk-sk":"Slovak","zh-tw":"Chinese - Taiwan"},"captionLanguageStrings":{"ar":"Arabic","da":"Danish","de":"German","en":"English","es":"Spanish","fi":"Finnish","fr-ca":"French - Canada","fr":"French - France","hi":"Hindi","it":"Italian","ja":"Japanese","ko":"Korean","nb":"Norwegian (Bokmål)","nl":"Dutch","pl":"Polish","pt":"Portuguese - Brazil","ru":"Russian","sv":"Swedish","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)","cs":"Czech","pt-pt":"Portuguese - Portugal","tr":"Turkish","vi":"Vietnamese","th":"Thai","he":"Hebrew","cy":"Welsh","uk":"Ukrainian","el":"Greek","hu":"Hungarian","ro":"Romanian","sk":"Slovak"},"captionsBannerSpinnerText":"Starting captions...","realTimeTextInputBoxDefaultText":"Type message in real-time","realTimeTextInputErrorMessage":"Message can not exceed 2000 characters","realTimeTextBannerTitle":"RTT","realTimeTextBannerContent":"RTT (real-time text) is enabled for all participants for the entire duration of the meeting.","realTimeTextBannerLinkLabel":"Learn more","realTimeTextModalAriaLabel":"Turn on RTT Modal","realTimeTextModalTitle":"Turn on RTT?","realTimeTextModalText":"Real-time text (RTT) will be turned on for everyone in the meeting.","realTimeTextConfirmButtonLabel":"Turn on","realTimeTextCancelButtonLabel":"Cancel","realTimeTextCloseModalButtonAriaLabel":"Close RTT Modal","captionsOnlyContainerTitle":"Captions","realTimeTextOnlyContainerTitle":"Real-Time Text","captionsAndRealTimeTextContainerTitle":"Captions and Real-Time Text","expandButtonAriaLabel":"Expand","minimizeButtonAriaLabel":"Collapse","transferPageTransferorText":"Transferring...","transferPageTransferTargetText":"Connecting...","transferPageUnknownTransferorDisplayName":"Unknown","transferPageUnknownTransferTargetDisplayName":"Unknown","transferPageNoticeString":"You are being transferred","participantCouldNotBeReachedTitle":"Target participant is currently not available","participantCouldNotBeReachedMoreDetails":"Please contact participant when they are available","permissionToReachTargetParticipantNotAllowedTitle":"Permission to reach target participant is not allowed","permissionToReachTargetParticipantNotAllowedMoreDetails":"Please check that the target participant is in the same tenant","unableToResolveTenantTitle":"Unable to resolve tenant id for the target participant","unableToResolveTenantMoreDetails":"Please check the participant id is entered correctly","participantIdIsMalformedTitle":"Participant id is not in the correct format","participantIdIsMalformedMoreDetails":"Please check that the participant id is in the correct format","moreButtonGalleryControlLabel":"View","moreButtonGalleryPositionToggleLabel":"Move gallery to top","moreButtonGallerySpeakerLayoutLabel":"Speaker","moreButtonGalleryFloatingLocalLayoutLabel":"Dynamic","moreButtonGalleryDefaultLayoutLabel":"Gallery view","moreButtonGalleryFocusedContentLayoutLabel":"Focus on content","moreButtonLargeGalleryDefaultLayoutLabel":"Large Gallery","moreButtonTogetherModeLayoutLabel":"Together mode","capabilityChangedNotification":{"turnVideoOn":{"lostDueToMeetingOption":"Your camera has been disabled. You can no longer share video.","grantedDueToMeetingOption":"Your camera has been enabled. Turn it on if you\'d like to share video."},"unmuteMic":{"lostDueToMeetingOption":"Your mic has been disabled. You can no longer unmute.","grantedDueToMeetingOption":"Your mic has been enabled. Unmute if you\'d like to speak."},"shareScreen":{"lostDueToRoleChangeToAttendee":"Your role has been changed. Some actions, like sharing content, won\'t be available to you.","grantedDueToRoleChangeToPresenter":"You\'re a presenter. You can share content and facilitate the meeting."},"hideAttendeeNames":{"hideAttendeeNameAttendee":"Your name is hidden from other attendees. Organizers and presenters can see your real name.","hideAttendeeNamePresenter":"Attendee names are hidden. Only organizers and presenters can see names to protect attendee privacy."}},"surveyTitle":"Help us improve","starSurveyHelperText":"How was the quality of the call?","starSurveyOneStarText":"The quality was bad.","starSurveyTwoStarText":"The quality was poor.","starSurveyThreeStarText":"The quality was good.","starSurveyFourStarText":"The quality was great.","starSurveyFiveStarText":"The quality was excellent.","surveyConfirmButtonLabel":"Send Feedback","starRatingAriaLabel":"Select {0} of {1} stars","surveySkipButtonLabel":"Skip","tagsSurveyQuestion":"What could have been better?","tagsSurveyTextFieldDefaultText":"Other, please specify","tagsSurveyHelperText":"Check any issues you experienced","endOfSurveyText":"Thank you for your feedback!","surveyIssues":{"overallRating":{"callCannotJoin":"I could not join call","callCannotInvite":"I could not invite others into the call","hadToRejoin":"I had to rejoin the call","callEndedUnexpectedly":"Call ended for me unexpectedly","otherIssues":"I was having other issues with the call"},"audioRating":{"noLocalAudio":"The other side could not hear any sound","noRemoteAudio":"I could not hear any sound","echo":"I heard echos on the call","audioNoise":"I heard noise on the call","lowVolume":"Volume was low","audioStoppedUnexpectedly":"Audio stopped unexpectedly","distortedSpeech":"Audio was distorted","audioInterruption":"Audio was interrupted","otherIssues":"I was having other audio issues in this call"},"videoRating":{"noVideoReceived":"I could not see any video","noVideoSent":"Others could not see me","lowQuality":"Video quality was low","freezes":"Video frozen","stoppedUnexpectedly":"Video stopped unexpectedly","darkVideoReceived":"I can only see dark screens when others turn on their camera","audioVideoOutOfSync":"Audio and Video was out of sync","otherIssues":"I was having other video issues in this call"},"screenshareRating":{"noContentLocal":"Other people could not see my screenshare","noContentRemote":"I could not see other people\'s screenshare","cannotPresent":"I could not present my screen","lowQuality":"Screen share quality was low","freezes":"Screen share frozen","stoppedUnexpectedly":"Screen share stopped unexpectedly","largeDelay":"Screen share has a large delay","otherIssues":"I was having other screen share issues in this call"}},"surveyIssuesHeadingStrings":{"overallRating":"Overall","audioRating":"Audio","videoRating":"Video","screenshareRating":"Presenting"},"spotlightPrompt":{"startSpotlightHeading":"Spotlight for everyone?","startSpotlightText":"You\'ll highlight this video for everyone in the meeting.","startSpotlightOnSelfText":"You\'ll highlight your video for everyone in the meeting.","startSpotlightConfirmButtonLabel":"Spotlight for everyone","startSpotlightCancelButtonLabel":"Cancel","stopSpotlightHeading":"Stop spotlighting this video?","stopSpotlightOnSelfHeading":"Exit spotlight?","stopAllSpotlightHeading":"Stop spotlighting all videos?","stopSpotlightText":"This video will no longer be highlighted for everyone in the meeting.","stopSpotlightOnSelfText":"Your video will no longer be highlighted for everyone in the meeting.","stopAllSpotlightText":"The videos will no longer be highlighted for everyone in the meeting.","stopSpotlightConfirmButtonLabel":"Stop spotlighting","stopSpotlightOnSelfConfirmButtonLabel":"Exit spotlight","stopSpotlightCancelButtonLabel":"Cancel","closeSpotlightPromptButtonLabel":"Close"},"exitSpotlightButtonLabel":"Exit spotlight","exitSpotlightButtonTooltip":"Exit spotlight","leaveConfirmButtonLabel":"Leave","endCallConfirmButtonLabel":"End call","hangUpCancelButtonLabel":"Cancel","leaveConfirmDialogTitle":"Leave the call?","leaveConfirmDialogContent":"Are you sure you want to leave the call?","endCallConfirmDialogTitle":"End the call?","endCallConfirmDialogContent":"You\'ll end the call for everyone.","invalidMeetingIdentifier":"Invalid meeting ID or passcode","pinParticipantMenuLabel":"Pin for me","pinParticipantLimitReachedMenuLabel":"Pin (limit reached)","unpinParticipantMenuLabel":"Unpin","pinParticipantMenuItemAriaLabel":"Pin for me","unpinParticipantMenuItemAriaLabel":"Unpin","muteAllMenuLabel":"Mute all","muteAllDialogTitle":"Mute everyone?","muteAllDialogContent":"This will mute everyone in the meeting but you.","muteAllConfirmButtonLabel":"Mute all","muteAllCancelButtonLabel":"Cancel","joinBreakoutRoomButtonLabel":"Join breakout room","returnFromBreakoutRoomButtonLabel":"Leave room","leaveBreakoutRoomAndMeetingButtonLabel":"Leave meeting","breakoutRoomJoinedNotificationTitle":"You\'ve joined Breakout room \'{roomName}\'","joinBreakoutRoomBannerTitle":"Breakout room \'{roomName}\' is open","joinBreakoutRoomBannerButtonLabel":"Join","returnFromBreakoutRoomBannerTitle":"Return to main meeting","returnFromBreakoutRoomBannerButtonLabel":"Rejoin","forbidAudioMenuLabel":"Disable mic","permitAudioMenuLabel":"Allow mic","forbidOthersAudioDialogTitle":"Disable mic for attendees?","forbidOthersAudioDialogContent":"Attendees wont be able to unmute themselves. The organizer and presenters can let people unmute as needed.","forbidOthersAudioConfirmButtonLabel":"Disable mics","forbidOthersAudioCancelButtonLabel":"Cancel","permitOthersAudioDialogTitle":"Allow mic for attendees?","permitOthersAudioDialogContent":"Everyone in the meeting will be able to unmute themselves.","permitOthersAudioConfirmButtonLabel":"Allow mics","permitOthersAudioCancelButtonLabel":"Cancel","forbidOthersAudioMenuLabel":"Disable mic for attendees","permitOthersAudioMenuLabel":"Allow mic for attendees","forbidVideoMenuLabel":"Disable camera","permitVideoMenuLabel":"Allow camera","forbidOthersVideoDialogTitle":"Disable camera for attendees?","forbidOthersVideoDialogContent":"Attendees wont be able to turn on video themselves. The organizer and presenters can let people turn on camera as needed.","forbidOthersVideoConfirmButtonLabel":"Disable cameras","forbidOthersVideoCancelButtonLabel":"Cancel","permitOthersVideoDialogTitle":"Allow camera for attendees?","permitOthersVideoDialogContent":"Everyone in the meeting will be able to turn on video themselves.","permitOthersVideoConfirmButtonLabel":"Allow cameras","permitOthersVideoCancelButtonLabel":"Cancel","forbidOthersVideoMenuLabel":"Disable camera for attendees","permitOthersVideoMenuLabel":"Allow camera for attendees"},"chat":{"chatListHeader":"In this chat","uploadAttachment":"Upload Attachment","uploadImageDataNotProvided":"Image data is not provided.","uploadImageIsTooLarge":"Image is too large. Choose one that\'s less than {maxImageSize} MB.","uploadImageExtensionIsNotAllowed":"Uploading .{imageExtension} image is not allowed.","uploadImageFailed":"Unable to upload image. Please try again later."},"callWithChat":{"chatButtonLabel":"Chat","chatButtonNewMessageNotificationLabel":"New Message","chatButtonTooltipClosedWithMessageCount":"Show chat ({unreadMessagesCount} unread)","chatButtonTooltipClose":"Hide chat","chatButtonTooltipOpen":"Show chat","chatPaneTitle":"Chat","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkButtonActionedLabel":"Link copied","copyInviteLinkActionedAriaLabel":"Invite link copied","dismissSidePaneButtonLabel":"Close","moreDrawerAudioDeviceMenuTitle":"Audio Device","moreDrawerButtonLabel":"More options","moreDrawerButtonTooltip":"More options","moreDrawerMicrophoneMenuTitle":"Microphone","moreDrawerSpeakerMenuTitle":"Speaker","moreDrawerCaptionsMenuTitle":"Live captions","moreDrawerSpokenLanguageMenuTitle":"Spoken language","moreDrawerCaptionLanguageMenuTitle":"Caption language","moreDrawerGalleryOptionsMenuTitle":"Gallery options","peopleButtonLabel":"People","selectedPeopleButtonLabel":"People Button Selected","peopleButtonTooltipOpen":"Show participants","peopleButtonTooltipClose":"Hide participants","peopleButtonTooltipOpenAriaLabel":"People button, Show participants","peopleButtonTooltipCloseAriaLabel":"People button, Hide participants","peoplePaneSubTitle":"In this call","peoplePaneTitle":"People","pictureInPictureTileAriaLabel":"Video Feeds. Click to return to call screen.","removeMenuLabel":"Remove","openDialpadButtonLabel":"Dial phone number","returnToCallButtonAriaDescription":"Return to Call","returnToCallButtonAriaLabel":"Back","peoplePaneAddPeopleButtonLabel":"Add People","dialpadStartCallButtonLabel":"Call","dialpadModalTitle":"Dial Phone Number","dialpadModalAriaLabel":"Dialpad","dialpadCloseModalButtonAriaLabel":"Close dialpad","openDtmfDialpadLabel":"Show dialpad","dtmfDialpadPlaceholderText":"Enter number","breakoutRoomChatPaneTitle":"Breakout Room Chat","chatContentSpinnerLabel":"Loading chat"}}')},AJ=(0,e.createContext)(wJ),PJ=()=>(0,e.useContext)(AJ),RJ=e.createContext(void 0),MJ={},DJ=(RJ.Provider,()=>{const e={};return function(t,i){void 0===e[t.id]&&(t.insertCSSRules(i),e[t.id]=!0)}}),kJ="undefined"==typeof window?r.g:window,OJ="@griffel/";function NJ(e,t){return kJ[Symbol.for(OJ+e)]||(kJ[Symbol.for(OJ+e)]=t),kJ[Symbol.for(OJ+e)]}const LJ=NJ("DEFINITION_LOOKUP_TABLE",{}),xJ="data-make-styles-bucket";function FJ(e,t,i=[]){return"___"+function(e){const t=e.length;if(7===t)return e;for(let i=t;i<7;i++)e+="0";return e}(function(e){for(var t,i=0,n=0,r=e.length;r>=4;++n,r-=4)t=1540483477*(65535&(t=255&e.charCodeAt(n)|(255&e.charCodeAt(++n))<<8|(255&e.charCodeAt(++n))<<16|(255&e.charCodeAt(++n))<<24))+(59797*(t>>>16)<<16),i=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&i)+(59797*(i>>>16)<<16);switch(r){case 3:i^=(255&e.charCodeAt(n+2))<<16;case 2:i^=(255&e.charCodeAt(n+1))<<8;case 1:i=1540483477*(65535&(i^=255&e.charCodeAt(n)))+(59797*(i>>>16)<<16)}return(((i=1540483477*(65535&(i^=i>>>13))+(59797*(i>>>16)<<16))^i>>>15)>>>0).toString(36)}(e+t))}function UJ(e,t){let i="",n="";for(const r in e){const s=e[r];if(0===s){n+=r+" ";continue}const a=Array.isArray(s),o="rtl"===t?(a?s[1]:s)+" ":(a?s[0]:s)+" ";i+=o,n+=o}return[i.slice(0,-1),n.slice(0,-1)]}function BJ(e,t){const i={};for(const n in e){const[r,s]=UJ(e[n],t);if(""===s){i[n]="";continue}const a=FJ(s,t),o=a+(""===r?"":" "+r);LJ[a]=[e[n],t],i[n]=o}return i}const VJ=t.useInsertionEffect?t.useInsertionEffect:void 0,HJ=()=>{const e={};return function(t,i){VJ&&"undefined"!=typeof window&&window.document&&window.document.createElement?VJ((()=>{t.insertCSSRules(i)}),[t,i]):void 0===e[t.id]&&(t.insertCSSRules(i),e[t.id]=!0)}};const $J=["r","d","l","v","w","f","i","h","a","s","k","t","m","c"].reduce(((e,t,i)=>(e[t]=i,e)),{});function jJ(e,t,i,n,r={}){var s,a;const o="m"===e,l=null!==(s=r.m)&&void 0!==s?s:"0",c=null!==(a=r.p)&&void 0!==a?a:0,d=function(e,t,i){return("m"===e?e+t:e)+i}(e,l,c);if(!n.stylesheets[d]){const s=t&&t.createElement("style"),a=function(e,t,i,n){const r=[];if(n[xJ]=t,n["data-priority"]=String(i),e)for(const t in n)e.setAttribute(t,n[t]);return{elementAttributes:n,insertRule:function(t){return(null==e?void 0:e.sheet)?e.sheet.insertRule(t,e.sheet.cssRules.length):r.push(t)},element:e,bucketName:t,cssRules:()=>(null==e?void 0:e.sheet)?Array.from(e.sheet.cssRules).map((e=>e.cssText)):r}}(s,e,c,Object.assign({},n.styleElementAttributes,o&&{media:l}));n.stylesheets[d]=a,t&&s&&t.head.insertBefore(s,function(e,t,i,n,r={}){var s,a;const o=$J[i],l=null!==(s=r.m)&&void 0!==s?s:"",c=null!==(a=r.p)&&void 0!==a?a:0;let d=e=>o-$J[e.getAttribute(xJ)],u=e.head.querySelectorAll(`[${xJ}]`);if("m"===i){const t=e.head.querySelectorAll(`[${xJ}="${i}"]`);t.length&&(u=t,d=e=>n.compareMediaQueries(l,e.media))}const h=e=>function(e,t,i){var n,r;return t+(null!==(n=i.m)&&void 0!==n?n:"")===e.getAttribute(xJ)+(null!==(r=e.media)&&void 0!==r?r:"")}(e,i,r)?c-Number(e.getAttribute("data-priority")):d(e),g=u.length;let p=g-1;for(;p>=0;){const e=u.item(p);if(h(e)>0)return e.nextSibling;p--}return g>0?u.item(0):t?t.nextSibling:null}(t,i,e,n,r))}return n.stylesheets[d]}function GJ(e,t){try{e.insertRule(t)}catch(e){}}let qJ=0;const zJ=(e,t)=>e<t?-1:e>t?1:0;function WJ(e=("undefined"==typeof document?void 0:document),t={}){const{classNameHashSalt:i,unstable_filterCSSRule:n,insertionPoint:r,styleElementAttributes:s,compareMediaQueries:a=zJ}=t,o={classNameHashSalt:i,insertionCache:{},stylesheets:{},styleElementAttributes:Object.freeze(s),compareMediaQueries:a,id:"d"+qJ++,insertCSSRules(t){for(const s in t){const a=t[s];for(let t=0,l=a.length;t<l;t++){const[l,c]=(i=a[t],Array.isArray(i)?i:[i]),d=jJ(s,e,r||null,o,c);o.insertionCache[l]||(o.insertionCache[l]=s,n?n(l)&&GJ(d,l):GJ(d,l))}}var i}};return o}const KJ=e.createContext(WJ()),JJ=e.createContext("ltr"),YJ={},QJ=function(){const t=function(e,t,i=DJ){const n=i();let r=null,s=null;return function(i){const{dir:a,renderer:o}=i,l="ltr"===a;return l?null===r&&(r=BJ(e,a)):null===s&&(s=BJ(e,a)),n(o,t),l?r:s}}({root:{mc9l5x:"f1w7gpdv",Bg96gwp:"fez10in",ycbfsm:"fg4l7m0"},rtl:{Bz10aip:"f13rod7r"}},{d:[".f1w7gpdv{display:inline;}",".fez10in{line-height:0;}",".f13rod7r{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);transform:scaleX(-1);}"],t:["@media (forced-colors: active){.fg4l7m0{forced-color-adjust:auto;}}"]},HJ);return function(){const i=e.useContext(JJ),n=e.useContext(KJ);return t({dir:i,renderer:n})}}(),ZJ=(t,i)=>{const{title:n,primaryFill:r="currentColor",...s}=t,a={...s,title:void 0,fill:r},o=QJ(),l=e.useContext(RJ)?e.useContext(RJ):MJ;return a.className=function(){let e=null,t="",i="";const n=new Array(arguments.length);for(let e=0;e<arguments.length;e++){const r=arguments[e];if("string"==typeof r&&""!==r){const s=r.indexOf("___");if(-1===s)t+=r+" ";else{const a=r.substr(s,10);s>0&&(t+=r.slice(0,s)),i+=a,n[e]=a}}}if(""===i)return t.slice(0,-1);const r=YJ[i];if(void 0!==r)return t+r;const s=[];for(let t=0;t<arguments.length;t++){const i=n[t];if(i){const t=LJ[i];t&&(s.push(t[0]),e=t[1])}}const a=Object.assign.apply(Object,[{}].concat(s)),[o,l]=UJ(a,e),c=FJ(l,e,n),d=c+" "+o;return YJ[i]=d,LJ[c]=[a,e],t+d}(o.root,(null==i?void 0:i.flipInRtl)&&"rtl"===(null==l?void 0:l.textDirection)&&o.rtl,a.className),n&&(a["aria-label"]=n),a["aria-label"]||a["aria-labelledby"]?a.role="img":a["aria-hidden"]=!0,a},XJ=(t,i,n,r)=>{const s="1em"===i?"20":i,a=e.forwardRef(((t,a)=>{const o={...ZJ(t,{flipInRtl:null==r?void 0:r.flipInRtl}),ref:a,width:i,height:i,viewBox:`0 0 ${s} ${s}`,xmlns:"http://www.w3.org/2000/svg"};return e.createElement("svg",o,...n.map((t=>e.createElement("path",{d:t,fill:o.fill}))))}));return a.displayName=t,a},eY=XJ("TextIndentIncrease20Regular","20",["M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 0 1 0 1h-8a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h6a.5.5 0 0 0 0-1h-6ZM2.85 7.73a.5.5 0 1 0-.7.7L3.2 9.5l-1.06 1.06a.5.5 0 1 0 .7.7l1.42-1.4a.5.5 0 0 0 0-.71L2.85 7.73Z"],{flipInRtl:!0}),tY=XJ("TextItalic20Regular","20",["M16 3a.5.5 0 0 1 0 1h-3.16L8.23 16h3.27a.5.5 0 0 1 0 1H4a.5.5 0 0 1 0-1h3.16l4.61-12H8.5a.5.5 0 0 1 0-1H16Z"]),iY=XJ("TextNumberListLtr20Regular","20",["M5 1.5a.5.5 0 0 0-.39-.49.5.5 0 0 0-.56.27l-.07.12a2.96 2.96 0 0 1-1.2 1.15.5.5 0 1 0 .44.9c.3-.15.56-.34.78-.53V5.5a.5.5 0 0 0 1 0v-4ZM2.65 7.65a.5.5 0 0 0 .7.7l.05-.04.2-.12C3.76 8.09 4 8 4.3 8c.23 0 .41.06.53.15.1.07.16.17.16.35a.5.5 0 0 1-.21.44c-.15.12-.35.22-.62.35l-.14.08c-.32.15-.7.36-1 .7-.33.35-.53.81-.53 1.43 0 .28.22.5.5.5h2.5a.5.5 0 0 0 0-1H3.59c.04-.1.1-.2.17-.27a2.38 2.38 0 0 1 .83-.53c.27-.13.59-.29.84-.5.33-.27.57-.65.57-1.2 0-.5-.22-.9-.57-1.15A1.92 1.92 0 0 0 4.33 7h-.01a2.5 2.5 0 0 0-1.66.63v.01h-.01Zm.01-.02-.01.02s.1-.1.01-.02ZM4.25 15a.5.5 0 1 0 0 1c.34 0 .53.1.63.18.1.09.13.2.13.3-.01.2-.19.52-.76.52-.41 0-.63-.1-.72-.17a.42.42 0 0 1-.1-.07.5.5 0 0 0-.88.46v.01l.02.02a.8.8 0 0 0 .1.15c.07.08.17.17.3.27.28.18.7.33 1.28.33 1.03 0 1.73-.67 1.76-1.48.01-.37-.12-.74-.4-1.02.28-.28.41-.65.4-1.02-.03-.8-.73-1.48-1.76-1.48-.59 0-1 .15-1.28.33a1.4 1.4 0 0 0-.4.42l-.01.01v.01a.5.5 0 0 0 .87.48.42.42 0 0 1 .1-.08c.1-.07.3-.17.72-.17.57 0 .75.33.76.52 0 .1-.04.21-.13.3-.1.08-.29.18-.63.18Zm-.82-.75.01-.02v.02ZM8.5 4a.5.5 0 1 0 0 1h8a.5.5 0 0 0 0-1h-8Zm0 5a.5.5 0 1 0 0 1h8a.5.5 0 0 0 0-1h-8ZM8 14.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5Z"]),nY=XJ("TextUnderlineCharacterU20Regular","20",["M7 3.5a.5.5 0 0 0-1 0V10a4 4 0 0 0 8 0V3.5a.5.5 0 0 0-1 0V10a3 3 0 1 1-6 0V3.5ZM5.5 16a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9Z"]),rY=XJ("Translate20Regular","20",["M4.08 4.22c.7-.21 1.7-.34 2.84 0 1.01.3 1.56.9 1.83 1.56.26.63.26 1.27.26 1.67v5.05a.5.5 0 0 1-1 0v-.53c-.31.19-.67.38-1.05.55-.78.34-1.74.6-2.64.42a2.97 2.97 0 0 1-2.25-2.09c-.29-.97-.08-2.1.8-2.84a4.57 4.57 0 0 1 3.21-1c.71.03 1.38.17 1.93.32 0-.37-.03-.79-.18-1.17-.16-.4-.48-.77-1.19-.98a4.04 4.04 0 0 0-3.15.37h-.01a.5.5 0 0 1-.57-.82h.01l.02-.02a2.45 2.45 0 0 1 .3-.17c.2-.1.48-.22.84-.32ZM6.04 8a3.58 3.58 0 0 0-2.52.77 1.66 1.66 0 0 0-.5 1.79c.2.66.73 1.23 1.5 1.39.6.12 1.33-.04 2.04-.35.58-.26 1.1-.6 1.45-.85V8.37a8.27 8.27 0 0 0-1.97-.36Zm8.43-1.34a.5.5 0 0 0-.94-.34c-.18.5-.37 1.22-.47 1.65-.5.03-1 .03-1.53 0a.5.5 0 1 0-.06 1c.47.02.92.03 1.36 0-.11.58-.2 1.1-.25 1.56a4.71 4.71 0 0 0-2.3 2.3c-.44 1.02-.4 2.17.25 2.85.43.46 1.06.53 1.64.4.42-.1.86-.31 1.28-.61l.08.2a.5.5 0 0 0 .93-.36 8.18 8.18 0 0 0-.23-.53 6.7 6.7 0 0 0 1.68-3.6c.77.26 1.28.8 1.5 1.38.38 1.04-.04 2.55-2.11 3.47a.5.5 0 1 0 .4.92c2.43-1.08 3.26-3.07 2.64-4.73A3.37 3.37 0 0 0 16 10.17V10a.5.5 0 1 0-1 0v.02c-.43-.01-.88.03-1.36.13l.23-1.25a21.3 21.3 0 0 0 2.24-.41.5.5 0 0 0-.22-.98c-.62.15-1.2.27-1.77.35.1-.38.23-.85.35-1.2Zm-3.27 6.57c.23-.52.64-1.06 1.3-1.5-.01.63.04 1.16.13 1.61.1.48.24.87.38 1.2-.38.3-.75.49-1.06.56-.39.09-.6 0-.69-.1-.27-.3-.4-.97-.06-1.77Zm3.73-2.22a5.83 5.83 0 0 1-1.15 2.76l-.17-.62a7.2 7.2 0 0 1-.09-1.94l.13-.04c.46-.12.89-.17 1.28-.16Z"]),sY=XJ("Video16Filled","16",["M1 5.5A2.5 2.5 0 0 1 3.5 3h4A2.5 2.5 0 0 1 10 5.5v5A2.5 2.5 0 0 1 7.5 13h-4A2.5 2.5 0 0 1 1 10.5v-5Zm12.04 6.28L10.9 10.3l.02-.28V5.98c0-.1 0-.19-.02-.28l2.14-1.48c.82-.57 1.96.02 1.96 1.03v5.5c0 1-1.14 1.6-1.96 1.03Z"]),aY=XJ("Video20Filled","20",["M2 7a3 3 0 0 1 3-3h5a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V7Zm14.04 7.78L14 13.37V6.63l2.04-1.4c.83-.58 1.96.01 1.96 1.02v7.5c0 1-1.13 1.6-1.96 1.03Z"]),oY=XJ("Video20Regular","20",["M5 4a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3v-.32l3.04 2.1c.83.57 1.96-.03 1.96-1.03v-7.5c0-1-1.13-1.6-1.96-1.03L13 7.32V7a3 3 0 0 0-3-3H5Zm8 4.54 3.6-2.5c.17-.1.4.01.4.21v7.5c0 .2-.23.32-.4.2L13 11.46V8.54ZM3 7c0-1.1.9-2 2-2h5a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"]),lY=XJ("VideoBackgroundEffect20Filled","20",["M6.2 4 2 8.2V6.8L4.8 4h1.4Zm7 0-1.46 1.46a3.48 3.48 0 0 0-1.02-.39L11.79 4h1.42Zm-1.08 3.17a2.51 2.51 0 0 0-2.34-1.16 2.5 2.5 0 1 0 2.34 1.16Zm.72-.72c.2.29.37.6.48.94L16.69 4 16.5 4h-1.2l-2.46 2.45ZM7.5 12c-.08 0-.15 0-.22.02A1.5 1.5 0 0 0 6 13.5V16h8v-2.5a1.5 1.5 0 0 0-1.5-1.5h-5Zm5-1c.22 0 .43.03.63.08L18 6.2V5.5c0-.2-.04-.4-.12-.59l-4.5 4.5a3.5 3.5 0 0 1-.93 1.59h.05Zm1.9.88c.23.27.4.58.5.93L18 9.7V8.29l-3.6 3.6ZM15 16v-1.2l3-3v1.4L15.2 16H15Zm-10-.3v-1.4l-1.7 1.69.2.01h1.2l.3-.3Zm1.57-6.48c.08.36.21.7.4 1.02L2.11 15.1A1.5 1.5 0 0 1 2 14.5v-.7l4.57-4.58ZM9.71 4 2 11.7v-1.4L8.3 4h1.4Z"]),cY=XJ("VideoBackgroundEffect20Regular","20",["M6.2 4 2 8.2V6.8L4.8 4h1.4ZM3.5 16H5v-1.7l-1.7 1.69.2.01Zm11.7 0H15v-1.2l3-3v1.4L15.2 16ZM18 9.7l-3.1 3.1a2.5 2.5 0 0 0-.5-.92L18 8.3v1.42ZM12.5 12a1.5 1.5 0 0 1 1.5 1.5V16h-1v-2.5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0-.5.5V16H6v-2.5c0-.08 0-.15.02-.22A1.5 1.5 0 0 1 7.5 12h5Zm-2.78-1.02a2.49 2.49 0 0 1-2.21-2.7 2.5 2.5 0 1 1 2.21 2.7ZM10 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm-7.88 5.09 4.84-4.85a3.48 3.48 0 0 1-.39-1.02L2 13.79v.71c0 .2.04.4.12.59Zm9.62-9.63a3.48 3.48 0 0 0-1.02-.39L11.79 4h1.42l-1.47 1.46Zm1.58 1.93a3.49 3.49 0 0 0-.48-.94L15.29 4h1.21l.2.01-3.38 3.38ZM12.45 11c.44-.43.76-.98.93-1.59l4.5-4.5c.08.18.12.38.12.59v.7l-4.87 4.88a2.5 2.5 0 0 0-.63-.08h-.05ZM2 11.7 9.7 4H8.3L2 10.3v1.4Z"]),dY=XJ("VideoOff20Filled","20",["M2.85 2.15a.5.5 0 1 0-.7.7l1.48 1.48A3 3 0 0 0 2 7v6a3 3 0 0 0 3 3h5a3 3 0 0 0 2.93-2.36l4.22 4.21a.5.5 0 0 0 .7-.7l-15-15ZM14 11.88l3.08 3.07c.5-.14.92-.6.92-1.2v-7.5c0-1-1.13-1.6-1.96-1.03L14 6.63v5.25ZM6.12 4 13 10.88V7a3 3 0 0 0-3-3H6.12Z"]),uY=XJ("VideoPerson20Filled","20",["M12.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0ZM2 5.5C2 4.67 2.67 4 3.5 4h13c.83 0 1.5.67 1.5 1.5v9c0 .83-.67 1.5-1.5 1.5h-13A1.5 1.5 0 0 1 2 14.5v-9ZM14 15h2.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-13a.5.5 0 0 0-.5.5v9c0 .28.22.5.5.5H6v-1.5c0-.83.67-1.5 1.5-1.5h5c.83 0 1.5.67 1.5 1.5V15Z"]),hY=XJ("Mic16Filled","16",["M8 2a2.5 2.5 0 0 0-2.5 2.5V8a2.5 2.5 0 0 0 5 0V4.5A2.5 2.5 0 0 0 8 2ZM4 7.5c.28 0 .5.22.5.5a3.5 3.5 0 1 0 7 0 .5.5 0 0 1 1 0 4.5 4.5 0 0 1-4 4.47v1.03a.5.5 0 0 1-1 0v-1.03A4.5 4.5 0 0 1 3.5 8c0-.28.22-.5.5-.5Z"]),gY=XJ("Mic20Filled","20",["M5.5 10a.5.5 0 0 0-1 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0v-2.02c2.8-.26 5-2.61 5-5.48a.5.5 0 0 0-1 0 4.5 4.5 0 1 1-9 0Zm7.5 0a3 3 0 0 1-6 0V5a3 3 0 0 1 6 0v5Z"]),pY=XJ("Mic20Regular","20",["M10 13a3 3 0 0 0 3-3V5a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3Zm0-1a2 2 0 0 1-2-2V5a2 2 0 1 1 4 0v5a2 2 0 0 1-2 2ZM5 9.5c.28 0 .5.22.5.5a4.5 4.5 0 1 0 9 0 .5.5 0 0 1 1 0 5.5 5.5 0 0 1-5 5.48v2.02a.5.5 0 0 1-1 0v-2.02a5.5 5.5 0 0 1-5-5.48c0-.28.22-.5.5-.5Z"]),mY=XJ("MicOff16Filled","16",["m10.8 11.52 3.35 3.33a.5.5 0 0 0 .7-.7l-13-13a.5.5 0 1 0-.7.7L5.5 6.21V8a2.5 2.5 0 0 0 3.88 2.09l.72.71A3.5 3.5 0 0 1 4.5 8a.5.5 0 1 0-1 0 4.5 4.5 0 0 0 4 4.47v1.03a.5.5 0 1 0 1 0v-1.03c.87-.1 1.66-.44 2.3-.95Zm1.26-1.58-.76-.76c.13-.37.2-.77.2-1.18a.5.5 0 0 1 1 0c0 .7-.16 1.35-.44 1.94Zm-1.58-1.59-4.8-4.79a2.5 2.5 0 0 1 4.82.94V8c0 .12 0 .24-.02.35Z"]),fY=XJ("MicOff16Regular","16",["m10.8 11.52 3.35 3.33a.5.5 0 0 0 .7-.7l-13-13a.5.5 0 1 0-.7.7L5.5 6.21V8a2.5 2.5 0 0 0 3.88 2.09l.72.71A3.5 3.5 0 0 1 4.5 8a.5.5 0 1 0-1 0 4.5 4.5 0 0 0 4 4.47v1.03a.5.5 0 1 0 1 0v-1.03c.87-.1 1.66-.44 2.3-.95ZM8.66 9.35A1.5 1.5 0 0 1 6.5 8v-.8l2.15 2.15Zm.85-1.97V4.5a1.5 1.5 0 0 0-3-.12l-.82-.82a2.5 2.5 0 0 1 4.82.94V8c0 .12 0 .24-.02.35l-.98-.97Zm2.56 2.56-.76-.76c.13-.37.2-.77.2-1.18a.5.5 0 0 1 1 0c0 .7-.16 1.35-.44 1.94Z"]),vY=XJ("MicOff20Filled","20",["M13 10a3 3 0 0 1-.1.78L7 4.88A3 3 0 0 1 13 5v5ZM7 7.7V10a3 3 0 0 0 4.74 2.45l1.07 1.07A4.5 4.5 0 0 1 5.5 10a.5.5 0 0 0-1.01 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0v-2.02a5.48 5.48 0 0 0 3.02-1.25l3.63 3.62a.5.5 0 0 0 .7-.7l-15-15a.5.5 0 1 0-.7.7L7 7.71Zm7.8 4.98c.45-.8.7-1.7.7-2.68a.5.5 0 0 0-1 0c0 .7-.16 1.35-.44 1.94l.74.74Z"]),SY=XJ("MicOff20Regular","20",["M12 5v4.88l.9.9A3 3 0 0 0 13 10V5a3 3 0 0 0-6-.12l1 1V5a2 2 0 1 1 4 0ZM7 7.7 2.15 2.86a.5.5 0 1 1 .7-.7l15 15a.5.5 0 0 1-.7.7l-3.63-3.62a5.48 5.48 0 0 1-3.02 1.25v2.02a.5.5 0 0 1-1 0v-2.02a5.5 5.5 0 0 1-5-5.48.5.5 0 0 1 1 0 4.5 4.5 0 0 0 7.3 3.52l-1.06-1.07A3 3 0 0 1 7 10V7.7Zm4.02 4.02L8 8.71V10a2 2 0 0 0 3.02 1.72Zm3.78.96-.74-.74c.28-.59.44-1.25.44-1.94a.5.5 0 0 1 1 0c0 .97-.25 1.89-.7 2.68Z"]),yY=XJ("MicProhibited16Filled","16",["M4 4.5a2.5 2.5 0 0 1 5 0v.7a5.5 5.5 0 0 0-3.98 4.82A2.5 2.5 0 0 1 4 8V4.5Zm1.04 6.68A3.5 3.5 0 0 1 3 8a.5.5 0 0 0-1 0 4.5 4.5 0 0 0 3.32 4.34 5.47 5.47 0 0 1-.28-1.16ZM6 10.5a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm2.4 2.8 4.9-4.9a3.5 3.5 0 0 1-4.9 4.9Zm-.7-.7a3.5 3.5 0 0 1 4.9-4.9l-4.9 4.9Z"]),CY=XJ("MicProhibited20Filled","20",["M9.2 13A5.51 5.51 0 0 1 12 9.6V5a3 3 0 1 0-6 0v5a3 3 0 0 0 3.2 3Zm.3 4.5v-.7c-.32-.7-.5-1.48-.5-2.3A4.5 4.5 0 0 1 4.5 10a.5.5 0 0 0-1 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0Zm5 1.5a4.5 4.5 0 1 1 0-9 4.5 4.5 0 0 1 0 9Zm0-8a3.5 3.5 0 0 0-2.8 5.6l4.9-4.9a3.48 3.48 0 0 0-2.1-.7Zm-2.1 6.3a3.5 3.5 0 0 0 4.9-4.9l-4.9 4.9Z"]),TY=XJ("MoreHorizontal20Filled","20",["M6.75 10a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0Zm5 0a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0ZM15 11.75a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5Z"]),EY=XJ("MoreHorizontal20Regular","20",["M6.25 10a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Zm5 0a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0ZM15 11.25a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Z"]),bY=XJ("Open20Regular","20",["M6 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2v-2.5a.5.5 0 0 1 1 0V14a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h2.5a.5.5 0 0 1 0 1H6Zm5-.5c0-.28.22-.5.5-.5h5c.28 0 .5.22.5.5v5a.5.5 0 0 1-1 0V4.7l-4.15 4.15a.5.5 0 0 1-.7-.7L15.29 4H11.5a.5.5 0 0 1-.5-.5Z"]),_Y=XJ("Sparkle20Filled","20",["M7.4 12.8a1.04 1.04 0 0 0 1.59-.51l.45-1.37a2.34 2.34 0 0 1 1.47-1.48l1.4-.45A1.04 1.04 0 0 0 12.25 7l-1.37-.45A2.34 2.34 0 0 1 9.4 5.08L8.95 3.7a1.03 1.03 0 0 0-.82-.68 1.04 1.04 0 0 0-1.15.7l-.46 1.4a2.34 2.34 0 0 1-1.44 1.45L3.7 7a1.04 1.04 0 0 0 .02 1.97l1.37.45a2.33 2.33 0 0 1 1.48 1.48l.46 1.4c.07.2.2.37.38.5Zm6.14 4.05a.8.8 0 0 0 1.22-.4l.25-.76a1.09 1.09 0 0 1 .68-.68l.77-.25a.8.8 0 0 0-.02-1.52l-.77-.25a1.08 1.08 0 0 1-.68-.68l-.25-.77a.8.8 0 0 0-1.52.01l-.24.76a1.1 1.1 0 0 1-.67.68l-.77.25a.8.8 0 0 0 0 1.52l.77.25a1.09 1.09 0 0 1 .68.68l.25.77c.06.16.16.3.3.4Z"]),IY=XJ("Speaker220Filled","20",["M12 3a1 1 0 0 0-1.68-.73l-3.87 3.6A.5.5 0 0 1 6.1 6H3.5C2.67 6 2 6.67 2 7.5v5c0 .83.67 1.5 1.5 1.5h2.6a.5.5 0 0 1 .35.13l3.87 3.6a1 1 0 0 0 1.68-.74V3.01Zm3.25 1.63a.5.5 0 0 1 .71.04 8 8 0 0 1 0 10.66.5.5 0 1 1-.75-.66 7 7 0 0 0 0-9.34.5.5 0 0 1 .04-.7Zm-1.17 8.3a.5.5 0 0 1-.19-.68 4.5 4.5 0 0 0 0-4.5.5.5 0 1 1 .87-.5 5.5 5.5 0 0 1 0 5.5.5.5 0 0 1-.68.18Z"]),wY=XJ("Speaker220Regular","20",["M12 3a1 1 0 0 0-1.68-.73l-3.88 3.6A.5.5 0 0 1 6.1 6H3.5C2.67 6 2 6.67 2 7.5v5c0 .83.67 1.5 1.5 1.5h2.6a.5.5 0 0 1 .34.13l3.88 3.6a1 1 0 0 0 1.68-.74V3.01ZM7.12 6.6 11 3v14l-3.88-3.6A1.5 1.5 0 0 0 6.1 13H3.5a.5.5 0 0 1-.5-.5v-5c0-.28.22-.5.5-.5h2.6c.38 0 .75-.14 1.02-.4Zm8.14-1.97a.5.5 0 0 1 .7.04 8 8 0 0 1 0 10.66.5.5 0 0 1-.74-.66 7 7 0 0 0 0-9.34.5.5 0 0 1 .04-.7Zm-1.18 8.3a.5.5 0 0 1-.18-.68 4.5 4.5 0 0 0 0-4.5.5.5 0 1 1 .86-.5 5.5 5.5 0 0 1 0 5.5.5.5 0 0 1-.68.18Z"]),AY=XJ("SpeakerMute16Filled","16",["M9 2.5a.5.5 0 0 0-.85-.36L5.22 5H3.5C2.67 5 2 5.66 2 6.5v3c0 .82.67 1.5 1.5 1.5h1.72l2.93 2.87A.5.5 0 0 0 9 13.5v-11Zm1.15 3.65c.2-.2.5-.2.7 0L12 7.29l1.15-1.14a.5.5 0 1 1 .7.7L12.71 8l1.14 1.15a.5.5 0 1 1-.7.7L12 8.71l-1.15 1.14a.5.5 0 0 1-.7-.7L11.29 8l-1.14-1.15a.5.5 0 0 1 0-.7Z"]),PY=XJ("Star28Filled","28",["M12.7 3.9a1.45 1.45 0 0 1 2.6 0L18 9.37l6.01.87a1.45 1.45 0 0 1 .8 2.48l-4.35 4.24 1.03 6a1.45 1.45 0 0 1-2.1 1.52L14 21.64l-5.38 2.83a1.45 1.45 0 0 1-2.1-1.52l1.02-6-4.35-4.24c-.86-.84-.39-2.3.8-2.48l6.02-.87 2.7-5.45Z"]),RY=XJ("Star28Regular","28",["M12.7 3.9a1.45 1.45 0 0 1 2.6 0L18 9.37l6.01.87a1.45 1.45 0 0 1 .8 2.48l-4.35 4.24 1.03 6a1.45 1.45 0 0 1-2.1 1.52L14 21.64l-5.38 2.83a1.45 1.45 0 0 1-2.1-1.52l1.02-6-4.35-4.24c-.86-.84-.39-2.3.8-2.48l6.02-.87 2.7-5.45Zm1.3.76-2.66 5.39c-.2.43-.62.72-1.09.8l-5.94.85 4.3 4.2c.34.33.5.8.42 1.28L8 23.1l5.32-2.8c.42-.22.92-.22 1.35 0l5.31 2.8-1.01-5.92c-.08-.47.07-.95.41-1.28l4.3-4.2-5.94-.86a1.45 1.45 0 0 1-1.1-.8L14 4.67Z"]),MY=XJ("Table20Filled","20",["M13 17h1.5a2.5 2.5 0 0 0 2.5-2.5V13h-4v4Zm0-5V8h4v4h-4Zm-1 0H8V8h4v4Zm-4 1h4v4H8v-4Zm-1-1V8H3v4h4Zm-4 1h4v4H5.5A2.5 2.5 0 0 1 3 14.5V13Zm10-6h4V5.5A2.5 2.5 0 0 0 14.5 3H13v4Zm-1-4v4H8V3h4ZM7 3v4H3V5.5A2.5 2.5 0 0 1 5.5 3H7Z"]),DY=XJ("Table20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h9a2.5 2.5 0 0 0 2.5-2.5v-9Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5Zm8-1.5v3H8v-3h4Zm2.5 3H13v-3h3V14.64A1.5 1.5 0 0 1 14.5 16ZM12 8v4H8V8h4Zm1 0h3v4h-3V8Zm-1-4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Z"]),kY=XJ("TableAdd20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h4.1c-.16-.32-.3-.65-.4-1H8v-3h1.2c.1-.35.24-.68.4-1H8V8h4v1.6c.32-.16.65-.3 1-.4V8h3v1.2c.35.1.68.24 1 .4V5.5Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5ZM12 4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Zm12 6.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-4-2a.5.5 0 0 0-1 0V14h-1.5a.5.5 0 0 0 0 1H14v1.5a.5.5 0 0 0 1 0V15h1.5a.5.5 0 0 0 0-1H15v-1.5Z"]),OY=XJ("TableDismiss20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h4.1c-.16-.32-.3-.65-.4-1H8v-3h1.2c.1-.35.24-.68.4-1H8V8h4v1.6c.32-.16.65-.3 1-.4V8h3v1.2c.35.1.68.24 1 .4V5.5Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5ZM12 4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Zm12 6.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-3.8 0 1.15-1.15a.5.5 0 0 0-.7-.7l-1.15 1.14-1.15-1.14a.5.5 0 0 0-.7.7l1.14 1.15-1.14 1.15a.5.5 0 0 0 .7.7l1.15-1.14 1.15 1.14a.5.5 0 0 0 .7-.7l-1.14-1.15Z"]),NY=XJ("CallMissed20Filled","20",["m17.8 7.77.16-.83c.16-.82-.15-1.7-.8-2.28-1.57-1.38-3.84-2.16-7.17-2.16-3.32 0-5.89.79-7.31 2.17-.6.59-.83 1.46-.58 2.28l.25.83A1.74 1.74 0 0 0 4.17 9l1.63-.16c.7-.07 1-.66 1.2-1.33.3-1 .5-1.75.5-1.75a6.63 6.63 0 0 1 5 0s.2.75.5 1.75c.22.74.75 1.26 1.47 1.33l1.63.16c.83.08 1.55-.44 1.7-1.22ZM9.5 11.5c.28 0 .5.22.5.5v1.5h1a.5.5 0 1 1 0 1H9.5A.5.5 0 0 1 9 14v-2c0-.28.22-.5.5-.5Zm-4 2a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM10 10a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7Z"]),LY=XJ("CallPause20Filled","20",["M3.55 2.44a4.1 4.1 0 0 1 2.99-.32c.5.12.94.45 1.2.9l.9 1.57a2.5 2.5 0 0 1-.84 3.36l-.79.5c-.32.2-.44.52-.37.77.27.9.86 1.9 1.52 2.58.19.2.54.25.9.05l.43-.26a2.5 2.5 0 0 1 3.44.94l.8 1.44c.27.47.31 1.03.12 1.53a3.9 3.9 0 0 1-1.96 2.22c-.9.41-1.94.4-2.88-.24-1.5-1-3.3-2.68-4.94-5.48a13.27 13.27 0 0 1-2.03-7.06 2.87 2.87 0 0 1 1.51-2.5ZM13 2.5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Zm3 0a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Z"]),xY=XJ("CallPause20Regular","20",["M3.55 2.44a4.1 4.1 0 0 1 2.99-.32c.5.12.94.45 1.2.9l.97 1.7a2.5 2.5 0 0 1-.67 3.24l-.6.45c-.28.22-.4.52-.34.77.18.82.59 1.57 1.15 2.13.17.16.47.22.8.1l.66-.26a2.5 2.5 0 0 1 3.07 1.11l.95 1.7c.27.48.31 1.04.12 1.54a3.9 3.9 0 0 1-1.96 2.22c-.9.41-1.94.4-2.88-.24-1.5-1-3.3-2.68-4.94-5.48a13.27 13.27 0 0 1-2.03-7.06 2.87 2.87 0 0 1 1.51-2.5Zm.49.87c-.59.33-.98.89-1 1.66-.04 1.61.33 3.85 1.9 6.53a15.3 15.3 0 0 0 4.62 5.15 1.9 1.9 0 0 0 1.91.16 2.91 2.91 0 0 0 1.45-1.65.84.84 0 0 0-.06-.7l-.95-1.7a1.5 1.5 0 0 0-1.85-.68l-.66.26c-.58.22-1.33.2-1.85-.32A5.32 5.32 0 0 1 6.13 9.4c-.17-.72.2-1.4.71-1.78l.6-.46c.6-.45.78-1.29.4-1.94l-.97-1.7a.93.93 0 0 0-.58-.43 3.1 3.1 0 0 0-2.25.22ZM13 2.5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Zm3 0a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Z"]),FY=XJ("CameraSwitch24Regular","24",["M21.25 7.5c.38 0 .7.28.74.65l.01.1v8.5a3.25 3.25 0 0 1-3.07 3.24l-.18.01H6.06l.72.72c.27.27.3.68.07.98l-.07.08a.75.75 0 0 1-.98.07l-.08-.07-2-2-.06-.07-.01-.01.07.08a.75.75 0 0 1 0-1.06l2-2a.75.75 0 0 1 1.13.98l-.07.08-.72.72h12.69c.92 0 1.67-.7 1.74-1.6l.01-.15v-8.5c0-.41.34-.75.75-.75ZM18.2 2.15l.08.07 2 2 .07.08-.07-.08a.75.75 0 0 1 0 1.06l-2 2a.75.75 0 0 1-1.13-.98l.07-.08.72-.72H5.25c-.92 0-1.67.7-1.74 1.6l-.01.15v8.5a.75.75 0 0 1-1.5.1v-8.6a3.25 3.25 0 0 1 3.07-3.24L5.25 4h12.69l-.72-.72a.75.75 0 0 1-.07-.98l.07-.08a.75.75 0 0 1 .98-.07ZM12 8a4 4 0 1 1 0 8 4 4 0 0 1 0-8Zm0 1.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"]),UY=XJ("Chat20Filled","20",["M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm.5 9H7.41a.5.5 0 0 0 0 1H10.59a.5.5 0 0 0 0-1h-.09Zm2-3H7.41a.5.5 0 0 0 0 1h5.18a.5.5 0 0 0 0-1h-.09Z"]),BY=XJ("Chat20Regular","20",["M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"]),VY=XJ("Checkmark20Regular","20",["M3.37 10.17a.5.5 0 0 0-.74.66l4 4.5c.19.22.52.23.72.02l10.5-10.5a.5.5 0 0 0-.7-.7L7.02 14.27l-3.65-4.1Z"]),HY=XJ("CheckmarkCircle16Regular","16",["M2 8a6 6 0 1 1 12 0A6 6 0 0 1 2 8Zm6-7a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm2.85 5.85a.5.5 0 0 0-.7-.7l-2.9 2.9-1.4-1.4a.5.5 0 1 0-.7.7L6.9 10.1c.2.2.5.2.7 0l3.25-3.25Z"]),$Y=XJ("ChevronLeft20Regular","20",["M12.35 15.85a.5.5 0 0 1-.7 0L6.16 10.4a.55.55 0 0 1 0-.78l5.49-5.46a.5.5 0 1 1 .7.7L7.2 10l5.16 5.15c.2.2.2.5 0 .7Z"]),jY=XJ("ChevronRight20Regular","20",["M7.65 4.15c.2-.2.5-.2.7 0l5.49 5.46c.21.22.21.57 0 .78l-5.49 5.46a.5.5 0 0 1-.7-.7L12.8 10 7.65 4.85a.5.5 0 0 1 0-.7Z"]),GY=XJ("Circle16Regular","16",["M8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12Zm0-1A5 5 0 1 1 8 3a5 5 0 0 1 0 10Z"]),qY=XJ("Circle20Regular","20",["M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm-8 7a8 8 0 1 1 16 0 8 8 0 0 1-16 0Z"]),zY=XJ("People20Filled","20",["M6.75 10a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5Zm5.69 5.14c.53.22 1.2.36 2.06.36 4 0 4-3 4-3 0-.83-.67-1.5-1.5-1.5h-4.63c.4.48.63 1.09.63 1.75v.36a2.94 2.94 0 0 1-.02.25 4.62 4.62 0 0 1-.54 1.78ZM17 7.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0ZM1.5 13c0-1.1.9-2 2-2H10a2 2 0 0 1 2 2s0 4-5.25 4-5.25-4-5.25-4Zm11.5.1v.07Z"]),WY=XJ("People20Regular","20",["M4.5 6.75a2.25 2.25 0 1 1 4.5 0 2.25 2.25 0 0 1-4.5 0ZM6.75 3.5a3.25 3.25 0 1 0 0 6.5 3.25 3.25 0 0 0 0-6.5Zm5.69 11.65c.53.21 1.21.35 2.06.35 1.88 0 2.92-.67 3.47-1.43a2.92 2.92 0 0 0 .53-1.5v-.07c0-.83-.67-1.5-1.5-1.5h-4.63c.24.29.42.63.53 1H17c.28 0 .5.22.5.5v.1l-.04.22c-.04.18-.13.42-.3.66-.33.46-1.04 1.02-2.66 1.02-.73 0-1.28-.11-1.69-.28-.08.28-.2.6-.37.93ZM1.5 13c0-1.1.9-2 2-2H10a2 2 0 0 1 2 2V13.08a1.43 1.43 0 0 1-.01.18 3.95 3.95 0 0 1-.67 1.8C10.62 16.09 9.26 17 6.75 17c-2.51 0-3.87-.92-4.57-1.93a3.95 3.95 0 0 1-.68-1.99V13Zm1 .06v.1l.06.33c.07.27.2.64.45 1C3.49 15.2 4.5 16 6.75 16s3.26-.8 3.74-1.5a2.95 2.95 0 0 0 .5-1.42l.01-.02V13a1 1 0 0 0-1-1H3.5a1 1 0 0 0-1 1v.06ZM13 7.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM14.5 5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"]),KY=XJ("PeopleAudience20Regular","20",["M9.99 2.99a2.23 2.23 0 1 1 0 4.45 2.23 2.23 0 0 1 0-4.45Zm0 1a1.23 1.23 0 1 0 0 2.45 1.23 1.23 0 0 0 0-2.45ZM3.02 11.5a.5.5 0 1 1-1 0V9.01a1 1 0 0 1 .88-.99h2.87c-.14.24-.23.52-.26.81v.18H3v2.49Zm14.47.5a.5.5 0 0 0 .5-.5V8.9a1 1 0 0 0-1-.89h-2.78c.14.26.24.55.26.86V9H17v2.49c0 .28.22.5.5.5Zm-5.02-3.99a1 1 0 0 1 1 .89v2.6a.5.5 0 1 1-1 0V9.01H7.5v2.49a.5.5 0 1 1-1 0V9.01a1 1 0 0 1 .89-.99h5.08Zm4.42-2.48a1.91 1.91 0 1 0-3.83 0 1.91 1.91 0 0 0 3.83 0Zm-2.83 0a.91.91 0 1 1 1.83 0 .91.91 0 0 1-1.83 0ZM5.02 3.62a1.91 1.91 0 1 1 0 3.82 1.91 1.91 0 0 1 0-3.82Zm0 1a.91.91 0 1 0 0 1.82.91.91 0 0 0 0-1.82ZM2.5 13a.5.5 0 0 0-.5.5v1A2.5 2.5 0 0 0 4.5 17h11a2.5 2.5 0 0 0 2.5-2.5v-1a.5.5 0 0 0-.5-.5h-15Zm.5 1.5V14h14v.5c0 .83-.67 1.5-1.5 1.5h-11A1.5 1.5 0 0 1 3 14.5Z"]),JY=XJ("PersonAdd20Regular","20",["M9 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM6 6a3 3 0 1 1 6 0 3 3 0 0 1-6 0Zm-2 5a2 2 0 0 0-2 2c0 1.7.83 2.97 2.13 3.8A9.14 9.14 0 0 0 9 18c.41 0 .82-.02 1.21-.06A5.5 5.5 0 0 1 9.6 17 12 12 0 0 1 9 17a8.16 8.16 0 0 1-4.33-1.05A3.36 3.36 0 0 1 3 13a1 1 0 0 1 1-1h5.6c.18-.36.4-.7.66-1H4Zm10.5 8a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm0-7c.28 0 .5.22.5.5V14h1.5a.5.5 0 0 1 0 1H15v1.5a.5.5 0 0 1-1 0V15h-1.5a.5.5 0 0 1 0-1H14v-1.5c0-.28.22-.5.5-.5Z"]),YY=XJ("PersonCall20Regular","20",["M10 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM7 6a3 3 0 1 1 6 0 3 3 0 0 1-6 0Zm-2 5a2 2 0 0 0-2 2c0 1.7.83 2.97 2.13 3.8A9.14 9.14 0 0 0 10 18c.36 0 .71-.01 1.06-.04a2.2 2.2 0 0 1 0-1c-.34.02-.7.04-1.06.04a8.16 8.16 0 0 1-4.33-1.05A3.36 3.36 0 0 1 4 13a1 1 0 0 1 1-1h9.52c0-.26.03-.52.13-.77l.08-.23H5.01Zm10.58.58.29-.75a1.32 1.32 0 0 1 1.74-.73l.39.17c.47.2.86.57.94 1.06.46 2.73-1.9 6.6-4.63 7.59a1.6 1.6 0 0 1-1.44-.25l-.35-.23c-.6-.41-.7-1.24-.2-1.79l.54-.6c.26-.3.66-.42 1.04-.33l1.22.29c.97-.6 1.5-1.46 1.56-2.56l-.88-.86a.94.94 0 0 1-.22-1Z"]),QY=XJ("PersonDelete20Filled","20",["M5 6a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm-3 7a2 2 0 0 1 2-2h6.26a5.48 5.48 0 0 0-.05 6.94c-.4.04-.8.06-1.21.06a9.14 9.14 0 0 1-4.87-1.2A4.35 4.35 0 0 1 2 13Zm17 1.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-2.65-1.15a.5.5 0 0 0-.7-.7l-1.15 1.14-1.15-1.14a.5.5 0 0 0-.7.7l1.14 1.15-1.14 1.15a.5.5 0 0 0 .7.7l1.15-1.14 1.15 1.14a.5.5 0 0 0 .7-.7l-1.14-1.15 1.14-1.15Z"]),ZY=XJ("PersonDelete20Regular","20",["M5 6a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm4-3a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM2 13a2 2 0 0 1 2-2h6.26c-.26.3-.48.64-.66 1H4a1 1 0 0 0-1 1c0 1.3.62 2.28 1.67 2.95A8.16 8.16 0 0 0 9 17l.6-.01c.17.34.37.66.61.95-.4.04-.8.06-1.21.06a9.14 9.14 0 0 1-4.87-1.2A4.35 4.35 0 0 1 2 13Zm17 1.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-2.65-1.15a.5.5 0 0 0-.7-.7l-1.15 1.14-1.15-1.14a.5.5 0 0 0-.7.7l1.14 1.15-1.14 1.15a.5.5 0 0 0 .7.7l1.15-1.14 1.15 1.14a.5.5 0 0 0 .7-.7l-1.14-1.15 1.14-1.15Z"]),XY=XJ("PersonSquare20Regular","20",["M10 5a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm2.5 5h-5c-.83 0-1.5.67-1.5 1.5 0 1.12.46 2.01 1.21 2.61.74.6 1.74.89 2.79.89s2.05-.29 2.79-.89c.75-.6 1.21-1.5 1.21-2.61 0-.83-.67-1.5-1.5-1.5ZM6 3a3 3 0 0 0-3 3v8a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3H6ZM4 6c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z"]),eQ=XJ("PersonVoice20Regular","20",["M17.13 1.06a.5.5 0 0 1 .68.2 9.96 9.96 0 0 1 0 9.48.5.5 0 1 1-.88-.48 8.96 8.96 0 0 0 0-8.52.5.5 0 0 1 .2-.68Zm-2.32 1.97a.5.5 0 0 1 .65.27 6.98 6.98 0 0 1 0 5.4.5.5 0 1 1-.92-.39 5.98 5.98 0 0 0 0-4.62.5.5 0 0 1 .27-.66ZM5 6a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm4-3a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM2 13a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2c0 1.7-.83 2.97-2.13 3.8A9.14 9.14 0 0 1 9 18a9.14 9.14 0 0 1-4.87-1.2A4.35 4.35 0 0 1 2 13Zm2-1a1 1 0 0 0-1 1c0 1.3.62 2.28 1.67 2.95A8.16 8.16 0 0 0 9 17c1.74 0 3.26-.36 4.33-1.05A3.36 3.36 0 0 0 15 13a1 1 0 0 0-1-1H4Z"]),tQ=XJ("VideoPersonStar20Filled","20",["M2 5.5C2 4.67 2.67 4 3.5 4h13c.83 0 1.5.67 1.5 1.5v4.76a5.5 5.5 0 0 0-1-.66V5.5a.5.5 0 0 0-.5-.5h-13a.5.5 0 0 0-.5.5v9c0 .28.22.5.5.5H6v-1.5c0-.83.67-1.5 1.5-1.5h2.1a5.48 5.48 0 0 0-.4 4H3.5A1.5 1.5 0 0 1 2 14.5v-9Zm10.5 3c0 .34-.07.66-.19.95-.8.35-1.5.88-2.04 1.54L10 11a2.5 2.5 0 1 1 2.5-2.5Zm6.5 6a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-4.02-2.64a.5.5 0 0 0-.96 0l-.47 1.53H12c-.48 0-.69.65-.3.95l1.26.94-.48 1.53c-.15.49.38.89.77.59l1.25-.95 1.25.95c.4.3.92-.1.77-.59l-.48-1.53 1.25-.94c.4-.3.2-.95-.3-.95h-1.54l-.47-1.53Z"]),iQ=XJ("VideoPersonStarOff20Filled","20",["M2.85 2.15a.5.5 0 1 0-.7.7L3.3 4.01C2.57 4.11 2 4.74 2 5.5v9c0 .83.67 1.5 1.5 1.5h5.7a5.5 5.5 0 0 1 .4-4H7.5c-.83 0-1.5.67-1.5 1.5V15H3.5a.5.5 0 0 1-.5-.5v-9c0-.28.22-.5.5-.5h.8l3.22 3.22-.02.28a2.5 2.5 0 0 0 2.77 2.49v-.01l.71.71a4.5 4.5 0 0 0 6.37 6.29.5.5 0 0 0 .5-.83l-15-15ZM16.5 17.2c-.13.27-.47.4-.75.2l-1.25-.95-1.25.95c-.4.3-.92-.1-.77-.59l.48-1.53-1.25-.94c-.4-.3-.2-.95.3-.95h.68l3.8 3.81ZM8.57 6.45l3.25 3.25c.16-.1.32-.17.5-.25A2.5 2.5 0 0 0 10 6c-.53 0-1.02.17-1.43.45Zm3.99 3.99 1.45 1.45.01-.03a.5.5 0 0 1 .96 0l.45 1.45.08.08H17c.48 0 .68.65.3.95l-.48.36 1.74 1.74a4.5 4.5 0 0 0-6-6ZM6.12 4l1 1h9.38c.28 0 .5.22.5.5v4.1c.36.18.7.4 1 .66V5.5c0-.83-.67-1.5-1.5-1.5H6.12Z"]),nQ=XJ("VideoProhibited16Filled","16",["M1 5a2.5 2.5 0 0 1 2.5-2.5h5A2.5 2.5 0 0 1 11 5v1.02a5.5 5.5 0 0 0-4.63 7.48H3.5A2.5 2.5 0 0 1 1 11V5Zm11 1.02c1.13.1 2.17.55 3 1.24V4.5a.5.5 0 0 0-.82-.39L12 5.9v.13ZM7 11.5a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm1 0a3.5 3.5 0 0 1 5.6-2.8l-4.9 4.9a3.48 3.48 0 0 1-.7-2.1Zm3.5 3.5c-.79 0-1.51-.26-2.1-.7l4.9-4.9a3.5 3.5 0 0 1-2.8 5.6Z"]),rQ=XJ("VideoProhibited20Filled","20",["M13 6.5A2.5 2.5 0 0 0 10.5 4h-6A2.5 2.5 0 0 0 2 6.5v7A2.5 2.5 0 0 0 4.5 16h4.7A5.5 5.5 0 0 1 13 9.2V6.5Zm5-.3v4.06a5.48 5.48 0 0 0-4-1.24V7.93l2.77-2.31a.75.75 0 0 1 1.23.57Zm-8 8.3a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm1 0a3.5 3.5 0 0 1 5.6-2.8l-4.9 4.9a3.48 3.48 0 0 1-.7-2.1Zm3.5 3.5c-.79 0-1.51-.26-2.1-.7l4.9-4.9a3.5 3.5 0 0 1-2.8 5.6Z"]),sQ=XJ("Warning20Filled","20",["M8.68 2.79a1.5 1.5 0 0 1 2.64 0l6.5 12A1.5 1.5 0 0 1 16.5 17h-13a1.5 1.5 0 0 1-1.32-2.21l6.5-12ZM10.5 7.5a.5.5 0 0 0-1 0v4a.5.5 0 0 0 1 0v-4Zm.25 6.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"]),aQ=XJ("WifiWarning20Filled","20",["M16.73 7.56c.4.4.78.87 1.11 1.35a.75.75 0 0 1-1.23.85 7.97 7.97 0 0 0-13.14 0 .75.75 0 1 1-1.23-.86 9.47 9.47 0 0 1 14.5-1.34ZM5.48 9.46a6.44 6.44 0 0 1 8.65-.43c-.52.1-1 .4-1.31.9a4.94 4.94 0 0 0-7.2 1.84.75.75 0 0 1-1.33-.67c.3-.61.7-1.16 1.19-1.65Zm4.3 6.51 1.08-2.15a1.24 1.24 0 1 0-1.08 2.15Zm1.7-3.4.68-1.35a4.13 4.13 0 0 0-5.9 1.9.75.75 0 0 0 1.37.6c.13-.32.32-.6.54-.82.9-.9 2.3-1.01 3.31-.33Zm2.12-2.02-3.5 7A1 1 0 0 0 11 19h7a1 1 0 0 0 .9-1.45l-3.5-7a1 1 0 0 0-1.8 0ZM15 12.5v3a.5.5 0 1 1-1 0v-3a.5.5 0 1 1 1 0Zm-.5 5.5a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1Z"]),oQ=XJ("WindowHeaderHorizontal20Regular","20",["M5.5 3A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h9a2.5 2.5 0 0 0 2.5-2.5v-9A2.5 2.5 0 0 0 14.5 3h-9ZM4 14.5V7h12v7.5c0 .83-.67 1.5-1.5 1.5h-9A1.5 1.5 0 0 1 4 14.5Z"]),lQ=XJ("Call20Filled","20",["M6.99 2.07A2 2 0 0 1 9.3 3l.08.15.66 1.47a2.5 2.5 0 0 1-.44 2.72l-.13.13-1.05.98c-.19.17-.04.86.64 2.04.6 1.06 1.1 1.56 1.35 1.58h.1l2.05-.64a1.5 1.5 0 0 1 1.56.45l.1.11 1.35 1.88a2 2 0 0 1-.13 2.5l-.12.12-.54.52a3.5 3.5 0 0 1-3.72.7c-1.93-.78-3.69-2.56-5.29-5.33S3.52 7.2 3.82 5.14a3.5 3.5 0 0 1 2.26-2.8l.19-.06.72-.21Z"]),cQ=XJ("Call20Regular","20",["m6.99 2.07-.72.21a3.5 3.5 0 0 0-2.45 2.86c-.3 2.06.36 4.48 1.96 7.25 1.6 2.77 3.36 4.55 5.3 5.33a3.5 3.5 0 0 0 3.7-.7l.55-.52a2 2 0 0 0 .25-2.62L14.22 12a1.5 1.5 0 0 0-1.65-.56l-2.05.63-.06.01c-.22.04-.74-.45-1.4-1.58-.67-1.18-.82-1.87-.63-2.04l1.05-.98a2.5 2.5 0 0 0 .57-2.85l-.66-1.47a2 2 0 0 0-2.4-1.1Zm1.49 1.5.66 1.47a1.5 1.5 0 0 1-.35 1.71l-1.04.98c-.67.63-.45 1.71.45 3.27.85 1.47 1.62 2.19 2.45 2.06l.12-.02 2.09-.64a.5.5 0 0 1 .55.19l1.36 1.88a1 1 0 0 1-.13 1.3l-.54.52a2.5 2.5 0 0 1-2.65.5c-1.7-.68-3.3-2.3-4.8-4.9-1.5-2.59-2.1-4.8-1.84-6.61a2.5 2.5 0 0 1 1.75-2.04l.72-.22a1 1 0 0 1 1.2.55Z"]),dQ=XJ("CallEnd20Filled","20",["m17.96 10.94-.16.83c-.15.78-.87 1.3-1.7 1.22l-1.63-.16c-.72-.07-1.25-.59-1.47-1.33-.3-1-.5-1.75-.5-1.75a6.63 6.63 0 0 0-5 0s-.2.75-.5 1.75c-.2.67-.5 1.26-1.2 1.33l-1.63.16c-.81.08-1.6-.43-1.82-1.2l-.25-.84c-.25-.82-.03-1.7.58-2.28C4.1 7.3 6.67 6.51 9.99 6.5c3.33 0 5.6.78 7.16 2.16.66.58.97 1.46.8 2.28Z"]),uQ=XJ("HandRight20Regular","20",["M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z"]),hQ=XJ("HandRightOff20Regular","20",["M4 6c0-.36.13-.7.34-.95l-2.2-2.2a.5.5 0 1 1 .71-.7l15 15a.5.5 0 0 1-.7.7l-3.57-3.56-.21.22c-.7.72-1.22 1.56-1.72 2.43a2.16 2.16 0 0 1-1.87 1.08H7.23c-.3 0-.6-.07-.86-.21a2.55 2.55 0 0 1-1.18-1.3l-.58-1.41c-.4-.98-.61-2.02-.61-3.08V6Zm8.87 7.58L7 7.7V9.5a.5.5 0 0 1-1 0V6.7l-.94-.93A.5.5 0 0 0 5 6v6.02c0 .93.18 1.84.53 2.7l.59 1.42c.14.34.4.61.71.78.13.07.27.1.4.1h2.55c.42 0 .8-.22 1-.58.55-.94 1.11-1.84 1.86-2.63l.23-.23ZM10 3.5v4.38l.9.9a.5.5 0 0 0 .1-.28v-4a.5.5 0 0 1 1 0v5.38l.92.92c.2-.2.4-.38.66-.51.7-.35 2.22-.57 2.4.5l-.53.4c-.4.3-.81.61-1.18.95l.7.71c.38-.34.8-.65 1.2-.96l.6-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0 1.5 1.5 0 0 0-1.96.87l.91.9V4.5a.5.5 0 0 1 1 0v1.38l1 1V3.5a.5.5 0 0 1 1 0Z"]),gQ=XJ("Important20Filled","20",["M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"]),pQ=XJ("Info20Filled","20",["M18 10a8 8 0 1 0-16 0 8 8 0 0 0 16 0ZM9.5 8.91a.5.5 0 0 1 1 0V13.6a.5.5 0 0 1-1 0V8.9Zm-.25-2.16a.75.75 0 1 1 1.5 0 .75.75 0 0 1-1.5 0Z"]),mQ=XJ("Clock20Filled","20",["M10 2a8 8 0 1 1 0 16 8 8 0 0 1 0-16Zm-.5 3a.5.5 0 0 0-.5.5v5.09a.5.5 0 0 0 .5.41h3.09a.5.5 0 0 0-.09-1H10V5.41A.5.5 0 0 0 9.5 5Z"]),fQ=XJ("ClosedCaption20Regular","20",["M6.4 7.24c.82-.41 1.8-.24 2.45.4a.5.5 0 0 1-.7.71 1.12 1.12 0 0 0-1.3-.22C6.44 8.34 6 8.9 6 10s.44 1.66.85 1.87c.43.21.95.13 1.3-.22a.5.5 0 0 1 .7.7c-.65.65-1.63.82-2.45.41C5.56 12.34 5 11.39 5 10c0-1.39.56-2.34 1.4-2.76Zm7.95.4a2.12 2.12 0 0 0-2.45-.4c-.84.42-1.4 1.37-1.4 2.76 0 1.39.56 2.34 1.4 2.76.82.41 1.8.24 2.45-.4a.5.5 0 0 0-.7-.71c-.35.35-.87.43-1.3.22-.41-.21-.85-.76-.85-1.87s.44-1.66.85-1.87c.43-.21.95-.13 1.3.22a.5.5 0 0 0 .7-.7ZM2 7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V7Zm3-2a2 2 0 0 0-2 2v6c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H5Z"]),vQ=XJ("ClosedCaptionOff20Regular","20",["M2.85 2.15a.5.5 0 1 0-.7.7l1.48 1.48A3 3 0 0 0 2 7v6a3 3 0 0 0 3 3h10l.28-.01 1.87 1.86a.5.5 0 0 0 .7-.7l-1.48-1.48-.76-.77-2.93-2.93-1.06-1.05L10.5 9.8 8.94 8.23 7.77 7.06 4.72 4.01 2.85 2.15ZM14.3 15H5a2 2 0 0 1-2-2V7a2 2 0 0 1 1.39-1.9l2.1 2.1-.09.04C5.56 7.66 5 8.61 5 10c0 1.39.56 2.34 1.4 2.76.82.41 1.8.24 2.45-.4a.5.5 0 1 0-.7-.71c-.35.35-.87.43-1.3.22C6.44 11.66 6 11.1 6 10s.44-1.66.85-1.87c.15-.07.3-.1.46-.11L14.3 15Zm2.9.06-.72-.7A2 2 0 0 0 17 13V7a2 2 0 0 0-2-2H7.12l-1-1H15a3 3 0 0 1 3 3v6c0 .8-.31 1.52-.82 2.06Zm-5.65-5.64-.81-.81c.24-.65.65-1.11 1.17-1.37.82-.41 1.8-.24 2.45.4a.5.5 0 0 1-.7.71 1.12 1.12 0 0 0-1.3-.22c-.33.17-.68.56-.8 1.3Z"]),SQ=XJ("ConferenceRoom16Regular","16",["M10 8a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0ZM7.6 2a.5.5 0 0 0-.6.49v11a.5.5 0 0 0 .6.49l5-1a.5.5 0 0 0 .4-.5V3.5a.5.5 0 0 0-.4-.49l-5-1ZM8 12.89V3.1l4 .8v8.18l-4 .8Zm-2 .1v-1H4V4h2V3H3.5a.5.5 0 0 0-.5.5v9c0 .27.22.5.5.5H6Z"]),yQ=XJ("ContentView20Regular","20",["M5 7a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V7Zm9 0H6v2h8V7Zm-2 4a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-1a1 1 0 0 0-1-1h-2Zm0 1h2v1h-2v-1Zm-7-.5c0-.28.22-.5.5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5Zm.5 1.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4ZM3 6a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6Zm3-2a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H6Z"]),CQ=XJ("Grid20Regular","20",["M7.5 11c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4A1.5 1.5 0 0 1 2 16.5v-4c0-.83.67-1.5 1.5-1.5h4Zm9 0c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4a1.5 1.5 0 0 1-1.5-1.5v-4c0-.83.67-1.5 1.5-1.5h4Zm-9 1h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm9 0h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm-9-10C8.33 2 9 2.67 9 3.5v4C9 8.33 8.33 9 7.5 9h-4A1.5 1.5 0 0 1 2 7.5v-4C2 2.67 2.67 2 3.5 2h4Zm9 0c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4A1.5 1.5 0 0 1 11 7.5v-4c0-.83.67-1.5 1.5-1.5h4Zm-9 1h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm9 0h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Z"]),TQ=XJ("Delete20Regular","20",["M8.5 4h3a1.5 1.5 0 0 0-3 0Zm-1 0a2.5 2.5 0 0 1 5 0h5a.5.5 0 0 1 0 1h-1.05l-1.2 10.34A3 3 0 0 1 12.27 18H7.73a3 3 0 0 1-2.98-2.66L3.55 5H2.5a.5.5 0 0 1 0-1h5ZM5.74 15.23A2 2 0 0 0 7.73 17h4.54a2 2 0 0 0 1.99-1.77L15.44 5H4.56l1.18 10.23ZM8.5 7.5c.28 0 .5.22.5.5v6a.5.5 0 0 1-1 0V8c0-.28.22-.5.5-.5ZM12 8a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V8Z"]),EQ=XJ("Dialpad20Regular","20",["M6 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm3-7a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm3-11a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"]),bQ=XJ("Dismiss16Regular","16",["m2.59 2.72.06-.07a.5.5 0 0 1 .63-.06l.07.06L8 7.29l4.65-4.64a.5.5 0 0 1 .7.7L8.71 8l4.64 4.65c.18.17.2.44.06.63l-.06.07a.5.5 0 0 1-.63.06l-.07-.06L8 8.71l-4.65 4.64a.5.5 0 0 1-.7-.7L7.29 8 2.65 3.35a.5.5 0 0 1-.06-.63l.06-.07-.06.07Z"]),_Q=XJ("Dismiss20Regular","20",["m4.09 4.22.06-.07a.5.5 0 0 1 .63-.06l.07.06L10 9.29l5.15-5.14a.5.5 0 0 1 .63-.06l.07.06c.18.17.2.44.06.63l-.06.07L10.71 10l5.14 5.15c.18.17.2.44.06.63l-.06.07a.5.5 0 0 1-.63.06l-.07-.06L10 10.71l-5.15 5.14a.5.5 0 0 1-.63.06l-.07-.06a.5.5 0 0 1-.06-.63l.06-.07L9.29 10 4.15 4.85a.5.5 0 0 1-.06-.63l.06-.07-.06.07Z"]),IQ=XJ("DividerTall24Regular","24",["M11.25 2.75v18.5a.75.75 0 0 0 1.5 0V2.75a.75.75 0 0 0-1.5 0Z"]),wQ=XJ("ScaleFill20Regular","20",["M6 6.5a.5.5 0 0 1 .14-.35A.5.5 0 0 1 6.5 6h2a.5.5 0 0 1 0 1h-.8l1.15 1.15a.5.5 0 1 1-.7.7L7 7.71v.79a.5.5 0 0 1-1 0v-2Zm.04 7.2a.5.5 0 0 1-.04-.2v-2a.5.5 0 0 1 1 0v.8l1.15-1.15a.5.5 0 0 1 .7.7L7.71 13h.79a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.46-.3Zm7.65-7.66a.5.5 0 0 1 .3.46v2a.5.5 0 0 1-.99 0v-.8l-1.15 1.15a.5.5 0 0 1-.7-.7L12.29 7h-.79a.5.5 0 0 1 0-1h2a.5.5 0 0 1 .2.04Zm.16 7.82a.5.5 0 0 1-.35.14h-2a.5.5 0 0 1 0-1h.8l-1.15-1.15a.5.5 0 0 1 .7-.7L13 12.29v-.79a.5.5 0 0 1 1 0v2a.5.5 0 0 1-.14.35ZM3 5c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm2-1a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1H5Z"]),AQ=XJ("ScaleFit20Regular","20",["M6.88 7.92a.5.5 0 0 1-.05.7l-1 .88H8.5a.5.5 0 0 1 0 1H5.83l1 .87a.5.5 0 1 1-.66.76l-2-1.75a.5.5 0 0 1 0-.76l2-1.75a.5.5 0 0 1 .7.05Zm7.29 2.58-1 .87a.5.5 0 0 0 .66.76l2-1.75a.5.5 0 0 0 0-.76l-2-1.75a.5.5 0 0 0-.66.76l1 .87H11.5a.5.5 0 0 0 0 1h2.67ZM2 6c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6Zm2-1a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H4Z"]),PQ=XJ("Send20Filled","20",["M2.72 2.05a.5.5 0 0 0-.7.58l1.5 5.62c.05.19.2.33.4.36l6.85 1.14c.28.05.28.45 0 .5l-6.85 1.14a.5.5 0 0 0-.4.36l-1.5 5.62a.5.5 0 0 0 .7.58l15-7.5a.5.5 0 0 0 0-.9l-15-7.5Z"],{flipInRtl:!0}),RQ=XJ("Send20Regular","20",["M2.18 2.11a.5.5 0 0 1 .54-.06l15 7.5a.5.5 0 0 1 0 .9l-15 7.5a.5.5 0 0 1-.7-.58L3.98 10 2.02 2.63a.5.5 0 0 1 .16-.52Zm2.7 8.39-1.61 6.06L16.38 10 3.27 3.44 4.88 9.5h6.62a.5.5 0 1 1 0 1H4.88Z"],{flipInRtl:!0}),MQ=XJ("Settings20Filled","20",["M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54ZM8 10a2 2 0 1 0 4 0 2 2 0 0 0-4 0Z"]),DQ=XJ("Settings20Regular","20",["M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54Zm1.06 0 1.3 1.1a2 2 0 0 1 0 3.04l-1.3 1.1c.3.79.72 1.51 1.25 2.16l1.6-.58a2 2 0 0 1 2.63 1.53l.3 1.67a7.56 7.56 0 0 0 2.5 0l.3-1.67a2 2 0 0 1 2.64-1.53l1.6.58a7.5 7.5 0 0 0 1.24-2.16l-1.3-1.1a2 2 0 0 1 0-3.04l1.3-1.1a7.5 7.5 0 0 0-1.25-2.16l-1.6.58a2 2 0 0 1-2.63-1.53l-.3-1.67a7.55 7.55 0 0 0-2.5 0l-.3 1.67A2 2 0 0 1 5.81 5.8l-1.6-.58a7.5 7.5 0 0 0-1.24 2.16ZM7.5 10a2.5 2.5 0 1 1 5 0 2.5 2.5 0 0 1-5 0Zm1 0a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0Z"]),kQ=XJ("ShareScreenStart20Filled","20",["M4 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H4Zm6 10a.5.5 0 0 1-.5-.5V7.7L7.85 9.36a.5.5 0 1 1-.7-.7l2.5-2.5c.2-.2.5-.2.7 0l2.5 2.5a.5.5 0 0 1-.7.7L10.5 7.71v5.79a.5.5 0 0 1-.5.5Z"]),OQ=XJ("ShareScreenStop20Filled","20",["M4.5 4A2.5 2.5 0 0 0 2 6.5v7A2.5 2.5 0 0 0 4.5 16h11a2.5 2.5 0 0 0 2.5-2.5v-7A2.5 2.5 0 0 0 15.5 4h-11Zm2.65 3.15c.2-.2.5-.2.7 0L10 9.29l2.15-2.14a.5.5 0 0 1 .7.7L10.71 10l2.14 2.15a.5.5 0 0 1-.7.7L10 10.71l-2.15 2.14a.5.5 0 0 1-.7-.7L9.29 10 7.15 7.85a.5.5 0 0 1 0-.7Z"]),NQ=XJ("SlideTextCall20Regular","20",["M5.5 7a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4Zm0 2.5a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7Zm-.5 3c0-.28.22-.5.5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5ZM4.5 4A2.5 2.5 0 0 0 2 6.5v7A2.5 2.5 0 0 0 4.5 16h6.57a2.19 2.19 0 0 1-.02-1H4.5A1.5 1.5 0 0 1 3 13.5v-7C3 5.67 3.67 5 4.5 5h11c.83 0 1.5.67 1.5 1.5V7c.33-.01.68.05 1 .18V6.5A2.5 2.5 0 0 0 15.5 4h-11Zm11.08 5.58.29-.75a1.32 1.32 0 0 1 1.74-.73l.39.17c.47.2.86.57.94 1.06.46 2.73-1.9 6.6-4.63 7.59a1.6 1.6 0 0 1-1.44-.25l-.35-.23c-.6-.41-.7-1.24-.2-1.79l.54-.6c.26-.3.66-.42 1.04-.33l1.22.29c.97-.6 1.5-1.46 1.56-2.56l-.88-.86a.94.94 0 0 1-.22-1Z"]),LQ=XJ("DoorArrowLeft16Regular","16",["M4.75 1C3.78 1 3 1.78 3 2.75v10.5c0 .97.78 1.75 1.75 1.75h2.5a5.5 5.5 0 0 1-.65-1H4.75a.75.75 0 0 1-.75-.75V2.75c0-.41.34-.75.75-.75h6.5c.41 0 .75.34.75.75v3.27c.34.03.68.1 1 .19V2.75C13 1.78 12.22 1 11.25 1h-6.5ZM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm9 3.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-6.85-.35a.5.5 0 0 0-.15.35.5.5 0 0 0 .15.35l2 2a.5.5 0 0 0 .7-.7L10.71 12h2.79a.5.5 0 0 0 0-1h-2.8l1.15-1.15a.5.5 0 0 0-.7-.7l-2 2Z"]),xQ=XJ("DoorArrowRight16Regular","16",["M4.75 1C3.78 1 3 1.78 3 2.75v10.5c0 .97.78 1.75 1.75 1.75h2.5a5.5 5.5 0 0 1-.65-1H4.75a.75.75 0 0 1-.75-.75V2.75c0-.41.34-.75.75-.75h6.5c.41 0 .75.34.75.75v3.27c.34.03.68.1 1 .19V2.75C13 1.78 12.22 1 11.25 1h-6.5ZM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm4.5 8a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm.35-2.15a.5.5 0 0 1-.7-.7L12.29 12H9.5a.5.5 0 0 1 0-1h2.8l-1.15-1.15a.5.5 0 0 1 .7-.7l2 2a.5.5 0 0 1 .15.35.5.5 0 0 1-.14.35l-2 2Z"]),FQ=XJ("Edit20Regular","20",["M17.18 2.93a2.97 2.97 0 0 0-4.26-.06l-9.37 9.38c-.33.33-.56.74-.66 1.2l-.88 3.94a.5.5 0 0 0 .6.6l3.93-.87c.46-.1.9-.34 1.23-.68l9.36-9.36a2.97 2.97 0 0 0 .05-4.15Zm-3.55.65a1.97 1.97 0 1 1 2.8 2.8l-.68.66-2.8-2.79.68-.67Zm-1.38 1.38 2.8 2.8-7.99 7.97c-.2.2-.46.35-.74.41l-3.16.7.7-3.18c.07-.27.2-.51.4-.7l8-8Z"]),UQ=XJ("Emoji20Regular","20",["M18 10a8 8 0 1 0-16 0 8 8 0 0 0 16 0ZM3 10a7 7 0 1 1 14 0 7 7 0 0 1-14 0Zm10.5-1.5a1 1 0 1 0-2 0 1 1 0 0 0 2 0Zm-5 0a1 1 0 1 0-2 0 1 1 0 0 0 2 0Zm-1.61 4.01a.5.5 0 1 0-.78.63 5 5 0 0 0 7.78 0 .5.5 0 1 0-.78-.63 4 4 0 0 1-6.22 0Z"]),BQ=XJ("ErrorCircle16Regular","16",["M8 2a6 6 0 1 1 0 12A6 6 0 0 1 8 2Zm0 1a5 5 0 1 0 0 10A5 5 0 0 0 8 3Zm0 7a.75.75 0 1 1 0 1.5.75.75 0 0 1 0-1.5Zm0-5.5a.5.5 0 0 1 .5.41V8.5a.5.5 0 0 1-1 .09V5c0-.28.22-.5.5-.5Z"]),VQ=XJ("Eye16Regular","16",["M2.98 8.62a.5.5 0 0 1-.6.36c-.44-.11-.36-.6-.36-.6l.01-.07.05-.14A6.7 6.7 0 0 1 3.2 6.19C4.1 5.08 5.6 4 8 4s3.9 1.09 4.8 2.18a6.7 6.7 0 0 1 1.18 2.17v.02a.5.5 0 0 1-.96.26L13 8.6a3.05 3.05 0 0 0-.2-.52 5.7 5.7 0 0 0-.78-1.26A4.96 4.96 0 0 0 8 5c-2.04 0-3.29.91-4.03 1.82A5.7 5.7 0 0 0 3 8.6v.02ZM8 7a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5ZM6.5 9.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"]),HQ=XJ("Pin16Filled","16",["M10.06 2.45a1.5 1.5 0 0 0-2.39.35L5.65 6.59l-2.8.94a.5.5 0 0 0-.2.82l2.14 2.15-2.64 2.65L2 14l.85-.15 2.65-2.64 2.15 2.14a.5.5 0 0 0 .82-.2l.94-2.8 3.78-2.03a1.5 1.5 0 0 0 .35-2.38l-3.48-3.5Z"]),$Q=XJ("Pin20Filled","20",["M13.33 2.62a2 2 0 0 0-3.2.52L8.38 6.6a1.5 1.5 0 0 1-.78.72L4 8.75a1 1 0 0 0-.33 1.64l2.61 2.6L3 16.3v.7h.7L7 13.72l2.61 2.6a1 1 0 0 0 1.64-.33l1.43-3.59c.14-.34.4-.62.72-.78l3.46-1.73a2 2 0 0 0 .52-3.2l-4.05-4.06Z"]),jQ=XJ("Pin20Regular","20",["M10.12 3.14a2 2 0 0 1 3.2-.52l4.06 4.05a2 2 0 0 1-.52 3.2l-3.46 1.74a1.5 1.5 0 0 0-.72.78L11.25 16a1 1 0 0 1-1.64.33L7 13.7 3.7 17H3v-.7L6.3 13l-2.62-2.61a1 1 0 0 1 .34-1.64L7.6 7.32c.34-.14.62-.4.78-.72l1.73-3.46Zm2.5.18a1 1 0 0 0-1.6.26L9.29 7.04a2.5 2.5 0 0 1-1.31 1.2L4.39 9.69l5.93 5.93 1.43-3.59a2.5 2.5 0 0 1 1.2-1.3l3.46-1.74a1 1 0 0 0 .26-1.6l-4.05-4.06Z"]),GQ=XJ("PinOff20Regular","20",["M2.85 2.15a.5.5 0 1 0-.7.7L6.9 7.6 4.02 8.75a1 1 0 0 0-.34 1.64L6.3 13 3 16.3v.7h.7L7 13.7l2.61 2.62a1 1 0 0 0 1.64-.34l1.15-2.88 4.75 4.75a.5.5 0 0 0 .7-.7l-15-15Zm8.78 10.18-1.31 3.28-5.93-5.93 3.28-1.3 3.96 3.95Zm1.33-1.62-.08.04.74.75 3.24-1.62a2 2 0 0 0 .52-3.2l-4.05-4.06a2 2 0 0 0-3.2.52L8.5 6.38l.75.74.04-.08 1.73-3.45a1 1 0 0 1 1.6-.26l4.05 4.05a1 1 0 0 1-.26 1.6l-3.45 1.73Z"]),qQ=XJ("Play20Regular","20",["M17.22 8.69a1.5 1.5 0 0 1 0 2.62l-10 5.5A1.5 1.5 0 0 1 5 15.5v-11A1.5 1.5 0 0 1 7.22 3.2l10 5.5Zm-.48 1.75a.5.5 0 0 0 0-.88l-10-5.5A.5.5 0 0 0 6 4.5v11c0 .38.4.62.74.44l10-5.5Z"]),zQ=XJ("Prohibited16Regular","16",["M11.87 3.42a6 6 0 0 0-8.45 8.45l8.45-8.45Zm.71.7-8.45 8.46a6 6 0 0 0 8.45-8.45ZM3.05 3.06a7 7 0 1 1 9.9 9.9 7 7 0 0 1-9.9-9.9Z"]),WQ=XJ("Record16Regular","16",["M8 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1ZM2 8a6 6 0 1 1 12 0A6 6 0 0 1 2 8Z"]),KQ=XJ("ArrowClockwise16Regular","16",["M3 8a5 5 0 0 1 9-3h-2a.5.5 0 0 0 0 1h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-1 0v1.53A5.99 5.99 0 0 0 2 8a6 6 0 0 0 11.98.54.5.5 0 0 0-1-.08A5 5 0 0 1 3 8Z"]),JQ=XJ("ArrowDownload20Regular","20",["M15.5 17a.5.5 0 0 1 .09 1H4.5a.5.5 0 0 1-.09-1H15.5ZM10 2a.5.5 0 0 1 .5.41V14.3l3.64-3.65a.5.5 0 0 1 .64-.06l.07.06c.17.17.2.44.06.63l-.06.07-4.5 4.5a.5.5 0 0 1-.25.14L10 16a.5.5 0 0 1-.4-.2l-4.46-4.45a.5.5 0 0 1 .64-.76l.07.06 3.65 3.64V2.5c0-.27.22-.5.5-.5Z"]),YQ=XJ("ArrowMaximize20Regular","20",["M10.5 3h6.04l.09.02.06.02.08.04.05.04.06.06.03.04.04.07.03.08.02.08V9.5a.5.5 0 0 1-1 .09V4.7L4.7 16h4.8a.5.5 0 0 1 .5.41v.09a.5.5 0 0 1-.41.5H3.41l-.1-.04-.08-.04-.05-.04-.06-.06-.03-.04-.04-.07-.03-.08v-.02A.5.5 0 0 1 3 16.5v.07-6.07a.5.5 0 0 1 1-.09v4.89L15.3 4h-4.8a.5.5 0 0 1-.5-.41V3.5c0-.28.22-.5.5-.5Z"]),QQ=XJ("ArrowMinimize20Regular","20",["M3.5 11h5a.5.5 0 0 1 .5.41v5.09a.5.5 0 0 1-1 .09V12.7l-5.15 5.15a.5.5 0 0 1-.76-.63l.06-.07L7.29 12H3.5a.5.5 0 0 1-.5-.41v-.09a.5.5 0 0 1 .41-.5H8.5h-5Zm14.35-8.85c.18.17.2.44.06.63l-.06.07L12.71 8h3.79a.5.5 0 0 1 .5.41v.09a.5.5 0 0 1-.41.5h-5.18l-.1-.04-.08-.04-.05-.04-.03-.03-.04-.04-.04-.06-.03-.06-.02-.06V8.6a.5.5 0 0 1-.02-.1v.07V3.5a.5.5 0 0 1 1-.09V7.3l5.15-5.15c.2-.2.5-.2.7 0Z"]),ZQ=XJ("Attach20Regular","20",["m4.83 10.48 5.65-5.65a3 3 0 0 1 4.25 4.24L8 15.8a1.5 1.5 0 0 1-2.12-2.12l6-6.01a.5.5 0 1 0-.7-.71l-6 6.01a2.5 2.5 0 0 0 3.53 3.54l6.71-6.72a4 4 0 1 0-5.65-5.66L4.12 9.78a.5.5 0 0 0 .7.7Z"]),XQ=XJ("Backspace20Regular","20",["M9.15 7.15c.2-.2.5-.2.7 0L12 9.29l2.15-2.14a.5.5 0 0 1 .7.7L12.71 10l2.14 2.15a.5.5 0 0 1-.7.7L12 10.71l-2.15 2.14a.5.5 0 0 1-.7-.7L11.29 10 9.15 7.85a.5.5 0 0 1 0-.7ZM6.59 4.66A2.5 2.5 0 0 1 8.29 4h7.21A2.5 2.5 0 0 1 18 6.5v7a2.5 2.5 0 0 1-2.5 2.5H8.28a2.5 2.5 0 0 1-1.7-.66l-3.78-3.5a2.5 2.5 0 0 1 0-3.68l3.79-3.5Zm1.7.34c-.38 0-.75.14-1.03.4L3.48 8.9a1.5 1.5 0 0 0 0 2.2l3.78 3.5c.28.26.65.4 1.02.4h7.22c.83 0 1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5H8.28Z"]),eZ=XJ("BoardSplit20Regular","20",["M3 6a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6Zm1 4v4c0 1.1.9 2 2 2h5v-6H4Zm7-1V4H6a2 2 0 0 0-2 2v3h7Zm1 7h2a2 2 0 0 0 2-2v-1h-4v3Zm4-9V6a2 2 0 0 0-2-2h-2v3h4Zm0 1h-4v4h4V8Z"]),tZ=XJ("TableSimple20Regular","20",["M3 5.5A2.5 2.5 0 0 1 5.5 3h9A2.5 2.5 0 0 1 17 5.5v9a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 3 14.5v-9Zm1 5v4c0 .83.67 1.5 1.5 1.5h4v-5.5H4Zm5.5-1V4h-4C4.67 4 4 4.67 4 5.5v4h5.5Zm1 1V16h4c.83 0 1.5-.67 1.5-1.5v-4h-5.5Zm5.5-1v-4c0-.83-.67-1.5-1.5-1.5h-4v5.5H16Z"]),iZ=XJ("TextBold20Regular","20",["M5.5 4.25C5.5 3.56 6.06 3 6.75 3h3.5a4 4 0 0 1 3.17 6.44c.9.7 1.58 1.8 1.58 3.31A4.23 4.23 0 0 1 10.75 17h-4c-.69 0-1.25-.56-1.25-1.25V4.25ZM8 11v3.5h2.75c.81 0 1.75-.62 1.75-1.75S11.56 11 10.75 11H8Zm0-2.5h2.25a1.5 1.5 0 1 0 0-3H8v3Z"]),nZ=XJ("TextBulletList20Regular","20",["M3 5.5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm3-1c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h11a.5.5 0 0 0 0-1h-11Zm-2.5.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1-4a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"]),rZ=XJ("TextEditStyle20Filled","20",["M14.09 6.7a2.26 2.26 0 0 1 3.07-.12l.13.12.12.13c.73.85.73 2.1 0 2.96l-.12.13-6.87 6.9a1.5 1.5 0 0 1-.55.35l-.16.05-3.08.76a.5.5 0 0 1-.62-.53l.01-.08.8-3.07c.05-.21.15-.4.28-.57l.1-.12 6.89-6.9ZM6.42 2.23l.05.08 2.98 7.63-.77.78L8 9H4l-1.03 2.68a.5.5 0 0 1-.56.3l-.1-.02a.5.5 0 0 1-.3-.56l.02-.08 3.5-9a.5.5 0 0 1 .9-.1ZM6 3.87 4.4 8H7.6l-1.6-4.13Z"]),sZ=XJ("TextEditStyle20Regular","20",["M14.09 6.7a2.26 2.26 0 0 1 3.07-.12l.13.12.12.13c.73.85.73 2.1 0 2.96l-.12.13-6.87 6.9a1.5 1.5 0 0 1-.55.35l-.16.05-3.08.76a.5.5 0 0 1-.62-.53l.01-.08.8-3.07c.05-.21.15-.4.28-.57l.1-.12 6.89-6.9Zm2.5.7a1.26 1.26 0 0 0-1.7-.08l-.1.09-6.88 6.9a.5.5 0 0 0-.1.15l-.03.08-.58 2.27 2.27-.56a.5.5 0 0 0 .12-.05l.05-.03.07-.06 6.87-6.9c.5-.5.5-1.3 0-1.8ZM6.41 2.24l.05.08 2.98 7.63-.77.78L8 9H4l-1.03 2.68a.5.5 0 0 1-.56.3l-.1-.02a.5.5 0 0 1-.3-.56l.02-.08 3.5-9a.5.5 0 0 1 .9-.1ZM6 3.87 4.4 8H7.6l-1.6-4.13Z"]),aZ=XJ("TextIndentDecrease20Regular","20",["M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5ZM3.56 7.73a.5.5 0 0 1 .7.7L3.22 9.5l1.06 1.06a.5.5 0 1 1-.7.7l-1.42-1.4a.5.5 0 0 1 0-.71l1.41-1.42ZM6.5 9a.5.5 0 0 0 0 1h11a.5.5 0 1 0 0-1h-11ZM6 14.5c0-.28.22-.5.5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5Z"],{flipInRtl:!0}),oZ=e=>({transform:"scale(2)",display:"flex",justifyContent:"center",alignItems:"center",lineHeight:"0.2rem",color:e.palette.themePrimary,zIndex:1}),lZ=e=>({root:{borderRadius:"100%",background:e.palette.themeLighterAlt,padding:"2rem"}}),cZ=()=>e.createElement(aQ,{style:{height:"1rem",width:"1rem"}}),dZ=()=>aJ().rtl?e.createElement(jY,null):e.createElement($Y,null),uZ=()=>aJ().rtl?e.createElement($Y,null):e.createElement(jY,null),hZ={ChatMessageOptions:e.createElement((()=>e.createElement("div",{className:dB({transform:"scale(0.9)"})},e.createElement(EY,null))),null),ControlButtonCameraOff:e.createElement(dY,null),ControlButtonCameraOn:e.createElement(aY,null),ControlButtonEndCall:e.createElement(dQ,null),ControlButtonMicOff:e.createElement(vY,null),ControlButtonMicOn:e.createElement(gY,null),ControlButtonOptions:e.createElement(MQ,null),ControlButtonParticipants:e.createElement(zY,null),ControlButtonParticipantsContextualMenuItem:e.createElement(WY,null),ControlButtonScreenShareStart:e.createElement(kQ,null),ControlButtonScreenShareStop:e.createElement(OQ,null),ControlButtonRaiseHand:e.createElement((()=>e.createElement(uQ,null)),null),ControlButtonLowerHand:e.createElement((()=>e.createElement(hQ,null)),null),ControlButtonMicProhibited:e.createElement(CY,null),ControlButtonMicProhibitedSmall:e.createElement(yY,null),ControlButtonCameraProhibited:e.createElement(rQ,null),ControlButtonCameraProhibitedSmall:e.createElement(nQ,null),RaiseHandContextualMenuItem:e.createElement(uQ,null),LowerHandContextualMenuItem:e.createElement(hQ,null),ReactionButtonIcon:e.createElement(UQ,null),CancelAttachmentUpload:e.createElement(bQ,null),DownloadAttachment:e.createElement(JQ,null),OpenAttachment:e.createElement(bY,null),AttachmentMoreMenu:e.createElement(TY,null),DataLossPreventionProhibited:e.createElement((()=>e.createElement(zQ,null)),null),EditBoxCancel:e.createElement(_Q,null),EditBoxSubmit:e.createElement(VY,null),ErrorBarCallCameraAccessDenied:e.createElement(nQ,null),ErrorBarCallCameraAlreadyInUse:e.createElement(nQ,null),ErrorBarCallLocalVideoFreeze:e.createElement(cZ,null),ErrorBarCallMacOsCameraAccessDenied:e.createElement(nQ,null),ErrorBarCallMacOsMicrophoneAccessDenied:e.createElement(yY,null),ErrorBarCallMicrophoneAccessDenied:e.createElement(yY,null),ErrorBarCallMicrophoneMutedBySystem:e.createElement(fY,null),ErrorBarCallMicrophoneUnmutedBySystem:e.createElement(hY,null),ErrorBarCallNetworkQualityLow:e.createElement(cZ,null),ErrorBarCallNoMicrophoneFound:e.createElement(yY,null),ErrorBarCallNoSpeakerFound:e.createElement(AY,null),ErrorBarClear:e.createElement(bQ,null),ErrorBarCallVideoRecoveredBySystem:e.createElement(sY,null),ErrorBarCallVideoStoppedBySystem:e.createElement(nQ,null),ErrorBarMutedByRemoteParticipant:e.createElement(fY,null),NotificationBarRecording:e.createElement(WQ,null),NotificationBarBreakoutRoomOpened:e.createElement(xQ,null),NotificationBarBreakoutRoomPromptJoin:e.createElement(xQ,null),NotificationBarBreakoutRoomChanged:e.createElement(xQ,null),NotificationBarBreakoutRoomJoined:e.createElement(SQ,null),NotificationBarBreakoutRoomClosingSoon:e.createElement(LQ,null),NotificationBarBreakoutRoomClosed:e.createElement(LQ,null),HorizontalGalleryLeftButton:e.createElement(dZ,null),HorizontalGalleryRightButton:e.createElement(uZ,null),MessageDelivered:e.createElement(HY,null),MessageEdit:e.createElement(FQ,null),MessageFailed:e.createElement(BQ,null),MessageRemove:e.createElement(TQ,null),MessageResend:e.createElement(KQ,null),MessageSeen:e.createElement(VQ,null),MessageSending:e.createElement(GY,null),OptionsCamera:e.createElement(oY,null),OptionsMic:e.createElement(pY,null),OptionsSpeaker:e.createElement(wY,null),ParticipantItemMicOff:e.createElement(SY,null),ParticipantItemOptions:e.createElement(e.Fragment,null),ParticipantItemOptionsHovered:e.createElement(TY,null),ParticipantItemScreenShareStart:e.createElement(kQ,null),ParticipantItemSpotlighted:e.createElement(tQ,null),HoldCallContextualMenuItem:e.createElement(xY,null),HoldCallButton:e.createElement(LY,null),ResumeCall:e.createElement(qQ,null),SendBoxSend:e.createElement(RQ,null),SendBoxSendHovered:e.createElement(PQ,null),VideoTileMicOff:e.createElement(mY,null),VideoTileCameraOff:e.createElement(nQ,null),DialpadBackspace:e.createElement(XQ,null),SitePermissionsSparkle:e.createElement((()=>e.createElement("div",{className:dB({transform:"scale(2)"})},e.createElement(_Y,null))),null),SitePermissionCamera:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:lZ(t)},e.createElement("div",{className:dB(oZ(t))},e.createElement(aY,null)))}),null),SitePermissionMic:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:lZ(t)},e.createElement("div",{className:dB(oZ(t))},e.createElement(gY,null)))}),null),SitePermissionCameraDenied:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:lZ(t)},e.createElement("div",{className:dB(oZ(t))},e.createElement(rQ,null)))}),null),SitePermissionMicDenied:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:lZ(t)},e.createElement("div",{className:dB(oZ(t))},e.createElement(CY,null)))}),null),UnsupportedEnvironmentWarning:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:{root:{width:vJ(84),borderRadius:"100%",background:t.palette.themeLighterAlt,padding:"2rem",margin:"auto"}}},e.createElement("div",{className:dB(oZ(t))},e.createElement(sQ,null)))}),null),BrowserPermissionDeniedError:e.createElement((()=>{const t=aJ();return e.createElement(Y$,{horizontalAlign:"center",styles:lZ(t)},e.createElement("div",{className:dB(oZ(t))},e.createElement(gQ,null)))}),null),VideoTilePinned:e.createElement(HQ,null),ParticipantItemPinned:e.createElement($Q,null),VideoTileMoreOptions:e.createElement(TY,null),VideoTileScaleFit:e.createElement(AQ,null),VideoTileScaleFill:e.createElement(wQ,null),PinParticipant:e.createElement(jQ,null),UnpinParticipant:e.createElement(GQ,null),SplitButtonPrimaryActionCameraOn:e.createElement(aY,null),SplitButtonPrimaryActionCameraOff:e.createElement(dY,null),SplitButtonPrimaryActionMicUnmuted:e.createElement(gY,null),SplitButtonPrimaryActionMicMuted:e.createElement(vY,null),VerticalGalleryLeftButton:e.createElement(dZ,null),VerticalGalleryRightButton:e.createElement(uZ,null),ControlButtonVideoEffectsOption:e.createElement(cY,null),ConfigurationScreenVideoEffectsButton:e.createElement(lY,null),CaptionsIcon:e.createElement(fQ,null),CaptionsOffIcon:e.createElement(vQ,null),CaptionsSettingsIcon:e.createElement(DQ,null),ChangeSpokenLanguageIcon:e.createElement(eQ,null),ChangeCaptionLanguageIcon:e.createElement(rY,null),ContextMenuCameraIcon:e.createElement(oY,null),ContextMenuMicIcon:e.createElement(pY,null),ContextMenuSpeakerIcon:e.createElement(wY,null),ContextMenuRemoveParticipant:e.createElement(ZY,null),SurveyStarIcon:e.createElement(RY,null),SurveyStarIconFilled:e.createElement(PY,null),StartSpotlightContextualMenuItem:e.createElement(tQ,null),StopSpotlightContextualMenuItem:e.createElement(iQ,null),VideoTileSpotlighted:e.createElement(tQ,{style:{height:"16px",width:"16px"}}),RichTextBoldButtonIcon:e.createElement(iZ,null),RichTextItalicButtonIcon:e.createElement(tY,null),RichTextUnderlineButtonIcon:e.createElement(nY,null),RichTextBulletListButtonIcon:e.createElement(nZ,null),RichTextNumberListButtonIcon:e.createElement(iY,null),RichTextIndentDecreaseButtonIcon:e.createElement(aZ,null),RichTextIndentIncreaseButtonIcon:e.createElement(eY,null),RichTextDividerIcon:e.createElement(IQ,null),RichTextEditorButtonIcon:e.createElement(sZ,null),RichTextEditorButtonIconFilled:e.createElement(rZ,null),RichTextInsertTableRegularIcon:e.createElement(DY,null),RichTextInsertTableFilledIcon:e.createElement(MY,null),RichTextTableInsertMenuIcon:e.createElement(kY,null),RichTextTableDeleteMenuIcon:e.createElement(OY,null),ContextualMenuMicMutedIcon:e.createElement(SY,null),IncomingCallNotificationRejectIcon:e.createElement(dQ,null),IncomingCallNotificationAcceptIcon:e.createElement(lQ,null),IncomingCallNotificationAcceptWithVideoIcon:e.createElement(aY,null),NotificationBarTogetherModeIcon:e.createElement(KY,null),RealTimeTextIcon:e.createElement(NQ,null),ExpandIcon:e.createElement(YQ,null),MinimizeIcon:e.createElement(QQ,null)};var gZ,pZ;!function(e){e[e.xSmall=0]="xSmall",e[e.small=1]="small",e[e.medium=2]="medium",e[e.large=3]="large"}(gZ||(gZ={})),function(e){e[e.normal=0]="normal",e[e.large=1]="large"}(pZ||(pZ={}));var mZ=oj(),fZ=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.type,n=t.size,r=t.ariaLabel,s=t.ariaLive,a=t.styles,o=t.label,l=t.theme,c=t.className,d=t.labelPosition,u=r,h=B$(this.props,U$,["size"]),g=n;void 0===g&&void 0!==i&&(g=i===pZ.large?gZ.large:gZ.medium);var p=mZ(a,{theme:l,size:g,className:c,labelPosition:d});return e.createElement("div",IU({},h,{className:p.root}),e.createElement("div",{className:p.circle}),o&&e.createElement("div",{className:p.label},o),u&&e.createElement("div",{role:"status","aria-live":s},e.createElement(dj,null,e.createElement("div",{className:p.screenReaderText},u))))},i.defaultProps={size:gZ.medium,ariaLive:"polite",labelPosition:"bottom"},i}(e.Component),vZ={root:"ms-Spinner",circle:"ms-Spinner-circle",label:"ms-Spinner-label"},SZ=SB((function(){return NB({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}})})),yZ=nj(fZ,(function(e){var t,i=e.theme,n=e.size,r=e.className,s=e.labelPosition,a=i.palette,o=FV(vZ,i);return{root:[o.root,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},"top"===s&&{flexDirection:"column-reverse"},"right"===s&&{flexDirection:"row"},"left"===s&&{flexDirection:"row-reverse"},r],circle:[o.circle,{boxSizing:"border-box",borderRadius:"50%",borderWidth:"1.5px",borderStyle:"solid",borderTopColor:a.themePrimary,borderRightColor:a.themeLight,borderBottomColor:a.themeLight,borderLeftColor:a.themeLight,animationName:SZ(),animationDuration:"1.3s",animationIterationCount:"infinite",animationTimingFunction:"cubic-bezier(.53,.21,.29,.67)",selectors:(t={},t[UV]=IU({borderTopColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},n===gZ.xSmall&&["ms-Spinner--xSmall",{width:12,height:12}],n===gZ.small&&["ms-Spinner--small",{width:16,height:16}],n===gZ.medium&&["ms-Spinner--medium",{width:20,height:20}],n===gZ.large&&["ms-Spinner--large",{width:28,height:28}]],label:[o.label,i.fonts.small,{color:a.themePrimary,margin:"8px 0 0",textAlign:"center"},"top"===s&&{margin:"0 0 8px"},"right"===s&&{margin:"0 0 0 8px"},"left"===s&&{margin:"0 8px 0 0"}],screenReaderText:LV}}),void 0,{scope:"Spinner"});const CZ=()=>e.createElement(yZ,{size:gZ.large}),TZ={ChevronLeft:void 0,Link:void 0,LobbyScreenConnectingToCall:e.createElement(CZ,null),LobbyScreenWaitingToBeAdmitted:e.createElement(CZ,null),LocalDeviceSettingsCamera:e.createElement(aY,null),LocalDeviceSettingsMic:e.createElement(gY,null),LocalDeviceSettingsSpeaker:e.createElement(IY,null),LocalPreviewPlaceholder:e.createElement(dY,null),LocalCameraSwitch:e.createElement(FY,null),ControlBarChatButtonActive:e.createElement(UY,null),ControlBarChatButtonInactive:e.createElement(BY,null),ControlButtonCameraProhibited:e.createElement(rQ,null),ControlButtonMicProhibited:e.createElement(CY,null),ControlButtonExitSpotlight:e.createElement(iQ,null),ControlBarPeopleButton:e.createElement(WY,null),MoreDrawerMicrophones:e.createElement(pY,null),MoreDrawerPeople:e.createElement(WY,null),MoreDrawerSpeakers:e.createElement(wY,null),MoreDrawerSelectedMicrophone:e.createElement(gY,null),MoreDrawerSelectedSpeaker:e.createElement(IY,null),Muted:e.createElement(vY,null),NetworkReconnectIcon:e.createElement(NY,null),NoticePageAccessDeniedTeamsMeeting:e.createElement(QY,null),NoticePageJoinCallFailedDueToNoNetwork:e.createElement(aQ,null),NoticePageLeftCall:e.createElement(dQ,null),NoticePageRemovedFromCall:e.createElement(pQ,null),NoticePageNotInvitedToRoom:e.createElement(pQ,null),NoticePageRoomNotFound:e.createElement(pQ,null),NoticePageRoomNotValid:e.createElement(pQ,null),NoticePageCallRejected:e.createElement(pQ,null),NoticePageCallTimeout:e.createElement(pQ,null),SendBoxAttachFile:e.createElement(ZQ,null),PeoplePaneAddPerson:e.createElement(JY,null),PeoplePaneOpenDialpad:e.createElement(EQ,null),DialpadStartCall:e.createElement(cQ,null),NoticePageInviteToRoomRemoved:e.createElement(pQ,null),BlurVideoBackground:e.createElement(cY,null),RemoveVideoBackgroundEffect:e.createElement(uY,null),GalleryOptions:e.createElement(CQ,null),OverflowGalleryTop:e.createElement(oQ,null),SpeakerGalleryLayout:e.createElement(XY,null),DefaultGalleryLayout:e.createElement(tZ,null),FloatingLocalVideoGalleryLayout:e.createElement(eZ,null),FocusedContentGalleryLayout:e.createElement(yQ,null),LargeGalleryLayout:e.createElement(DY,null),DefaultCustomButton:e.createElement(qY,null),DtmfDialpadButton:e.createElement(EQ,null),PhoneNumberButton:e.createElement(YY,null),JoinByPhoneDialStepIcon:e.createElement(YY,null),JoinByPhoneConferenceIdIcon:e.createElement(EQ,null),JoinByPhoneWaitToBeAdmittedIcon:e.createElement(mQ,null),PeoplePaneMoreButton:e.createElement(TY,null),StopAllSpotlightMenuButton:e.createElement(iQ,null),TogetherModeLayout:e.createElement(KY,null)},EZ=Object.assign(Object.assign({},hZ),TZ),bZ=t=>e.createElement(hG,Object.assign({},t)),_Z=t=>e.createElement(hG,Object.assign({},t)),IZ={position:"fixed",zIndex:1e6,inset:"0px",visibility:"hidden"},wZ=t=>{const{audioContext:i,children:n}=t,[r,s]=(0,e.useState)(void 0);return(0,e.useEffect)((()=>{s(i)}),[i]),PZ()?e.createElement(e.Fragment,null,n):e.createElement(AZ.Provider,{value:r},t.children)},AZ=(0,e.createContext)(void 0),PZ=()=>(0,e.useContext)(AZ),RZ=t=>{const{fluentTheme:i,rtl:n,locale:r}=t,s=g$("composite-global-hostId");if(DZ())return e.createElement(e.Fragment,null,t.children);const a={};Object.entries(EZ).forEach((([e,t])=>{t&&(a[e]=t)})),WH({icons:Object.assign(Object.assign({},a),t.icons)});const o=new AudioContext,l=e.createElement(sJ,{fluentTheme:i,rtl:n},"mobile"===t.formFactor&&e.createElement("meta",{name:"viewport",content:"width=device-width"}),e.createElement(_z,{scopedSettings:{Layer:{hostId:s}}},e.createElement(wZ,{audioContext:o},e.createElement(kZ,null,t.children))),e.createElement(IJ,{id:s,className:dB(IZ)})),c=r?(t=>{const{locale:i,children:n}=t;return e.createElement(AJ.Provider,{value:i},e.createElement(wK,{locale:i.component},n))})({locale:r,children:l}):l;return e.createElement(MZ.Provider,{value:!0},c)},MZ=(0,e.createContext)(!1),DZ=()=>(0,e.useContext)(MZ),kZ=t=>{const{children:i}=t,n=dB({background:qK().semanticColors.bodyBackground,height:"100%",width:"100%",position:"relative"});return e.createElement(Y$,{className:n},i)},OZ=(0,e.createContext)(void 0),NZ=t=>{const{adapter:i}=t;return e.createElement(OZ.Provider,{value:i},t.children)},LZ=()=>{const t=(0,e.useContext)(OZ);if(!t)throw"Cannot find adapter please initialize before usage.";return t};var xZ;!function(e){e[e.Parent=0]="Parent",e[e.Self=1]="Self"}(xZ||(xZ={}));var FZ,UZ=oj(),BZ=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._onRenderContent=function(t){return"string"==typeof t.content?e.createElement("p",{className:i._classNames.subText},t.content):e.createElement("div",{className:i._classNames.subText},t.content)},i}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.className,n=t.calloutProps,r=t.directionalHint,s=t.directionalHintForRTL,a=t.styles,o=t.id,l=t.maxWidth,c=t.onRenderContent,d=void 0===c?this._onRenderContent:c,u=t.targetElement,h=t.theme;return this._classNames=UZ(a,{theme:h,className:i||n&&n.className,beakWidth:n&&n.isBeakVisible?n.beakWidth:0,gapSpace:n&&n.gapSpace,maxWidth:l}),e.createElement($z,IU({target:u,directionalHint:r,directionalHintForRTL:s},n,B$(this.props,U$,["id"]),{className:this._classNames.root}),e.createElement("div",{className:this._classNames.content,id:o,onFocus:this.props.onFocus,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave},d(this.props,this._onRenderContent)))},i.defaultProps={directionalHint:1,maxWidth:"364px",calloutProps:{isBeakVisible:!0,beakWidth:16,gapSpace:0,setInitialFocus:!0,doNotLayer:!1}},i}(e.Component),VZ=nj(BZ,(function(e){var t=e.className,i=e.beakWidth,n=void 0===i?16:i,r=e.gapSpace,s=void 0===r?0:r,a=e.maxWidth,o=e.theme,l=o.semanticColors,c=o.fonts,d=o.effects,u=-(Math.sqrt(n*n/2)+s)+1/window.devicePixelRatio;return{root:["ms-Tooltip",o.fonts.medium,OV.fadeIn200,{background:l.menuBackground,boxShadow:d.elevation8,padding:"8px",maxWidth:a,selectors:{":after":{content:"''",position:"absolute",bottom:u,left:u,right:u,top:u,zIndex:0}}},t],content:["ms-Tooltip-content",c.small,{position:"relative",zIndex:1,color:l.menuItemText,wordWrap:"break-word",overflowWrap:"break-word",overflow:"hidden"}],subText:["ms-Tooltip-subtext",{fontSize:"inherit",fontWeight:"inherit",color:"inherit",margin:0}]}}),void 0,{scope:"Tooltip"});!function(e){e[e.zero=0]="zero",e[e.medium=1]="medium",e[e.long=2]="long"}(FZ||(FZ={}));var HZ,$Z,jZ,GZ,qZ,zZ,WZ=oj(),KZ=function(t){function i(n){var r=t.call(this,n)||this;return r._tooltipHost=e.createRef(),r._defaultTooltipId=u$("tooltip"),r.show=function(){r._toggleTooltip(!0)},r.dismiss=function(){r._hideTooltip()},r._getTargetElement=function(){if(r._tooltipHost.current){var e=r.props.overflowMode;if(void 0!==e)switch(e){case xZ.Parent:return r._tooltipHost.current.parentElement;case xZ.Self:return r._tooltipHost.current}return r._tooltipHost.current}},r._onTooltipFocus=function(e){r._ignoreNextFocusEvent?r._ignoreNextFocusEvent=!1:r._onTooltipMouseEnter(e)},r._onTooltipContentFocus=function(e){i._currentVisibleTooltip&&i._currentVisibleTooltip!==r&&i._currentVisibleTooltip.dismiss(),i._currentVisibleTooltip=r,r._clearDismissTimer(),r._clearOpenTimer()},r._onTooltipBlur=function(e){var t;r._ignoreNextFocusEvent=(null===(t=nz(r.context))||void 0===t?void 0:t.activeElement)===e.target,r._dismissTimerId=r._async.setTimeout((function(){r._hideTooltip()}),0)},r._onTooltipMouseEnter=function(e){var t,n=r.props,s=n.overflowMode,a=n.delay,o=nz(r.context);if(i._currentVisibleTooltip&&i._currentVisibleTooltip!==r&&i._currentVisibleTooltip.dismiss(),i._currentVisibleTooltip=r,void 0!==s){var l=r._getTargetElement();if(l&&!function(e){return e.clientWidth<e.scrollWidth}(t=l)&&!function(e){return e.clientHeight<e.scrollHeight}(t))return}if(!e.target||!mj(e.target,r._getTargetElement(),o))if(r._clearDismissTimer(),r._clearOpenTimer(),a!==FZ.zero){var c=r._getDelayTime(a);r._openTimerId=r._async.setTimeout((function(){r._toggleTooltip(!0)}),c)}else r._toggleTooltip(!0)},r._onTooltipMouseLeave=function(e){var t=r.props.closeDelay;r._clearDismissTimer(),r._clearOpenTimer(),t?r._dismissTimerId=r._async.setTimeout((function(){r._toggleTooltip(!1)}),t):r._toggleTooltip(!1),i._currentVisibleTooltip===r&&(i._currentVisibleTooltip=void 0)},r._onTooltipKeyDown=function(e){(e.which===vj||e.ctrlKey)&&r.state.isTooltipVisible&&(r._hideTooltip(),e.stopPropagation())},r._clearDismissTimer=function(){r._async.clearTimeout(r._dismissTimerId)},r._clearOpenTimer=function(){r._async.clearTimeout(r._openTimerId)},r._hideTooltip=function(){r._clearOpenTimer(),r._clearDismissTimer(),r._toggleTooltip(!1)},r._toggleTooltip=function(e){r.state.isTooltipVisible!==e&&r.setState({isTooltipVisible:e},(function(){return r.props.onTooltipToggle&&r.props.onTooltipToggle(e)}))},r._getDelayTime=function(e){switch(e){case FZ.medium:return 300;case FZ.long:return 500;default:return 0}},Ij(r),r.state={isAriaPlaceholderRendered:!1,isTooltipVisible:!1},r}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.calloutProps,n=t.children,r=t.content,s=t.directionalHint,a=t.directionalHintForRTL,o=t.hostClassName,l=t.id,c=t.setAriaDescribedBy,d=void 0===c||c,u=t.tooltipProps,h=t.styles,g=t.theme;this._classNames=WZ(h,{theme:g,className:o});var p=this.state.isTooltipVisible,m=l||this._defaultTooltipId,f=IU(IU({id:"".concat(m,"--tooltip"),content:r,targetElement:this._getTargetElement(),directionalHint:s,directionalHintForRTL:a,calloutProps:kj({},i,{onDismiss:this._hideTooltip,onFocus:this._onTooltipContentFocus,onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave}),onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave},B$(this.props,U$,["id"])),u),v=(null==u?void 0:u.onRenderContent)?u.onRenderContent(f,(function(t){return(null==t?void 0:t.content)?e.createElement(e.Fragment,null,t.content):null})):r,S=p&&!!v,y=d&&p&&v?m:void 0;return e.createElement("div",{className:this._classNames.root,ref:this._tooltipHost,onFocusCapture:this._onTooltipFocus,onBlurCapture:this._onTooltipBlur,onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave,onKeyDown:this._onTooltipKeyDown,role:"none","aria-describedby":y},n,S&&e.createElement(VZ,IU({},f)),e.createElement("div",{hidden:!0,id:m,style:LV},v))},i.prototype.componentDidMount=function(){this._async=new Mj(this)},i.prototype.componentWillUnmount=function(){i._currentVisibleTooltip&&i._currentVisibleTooltip===this&&(i._currentVisibleTooltip=void 0),this._async.dispose()},i.defaultProps={delay:FZ.medium},i.contextType=Kq,i}(e.Component),JZ={root:"ms-TooltipHost",ariaPlaceholder:"ms-TooltipHost-aria-placeholder"},YZ=nj(KZ,(function(e){var t=e.className,i=e.theme;return{root:[FV(JZ,i).root,{display:"inline"},t]}}),void 0,{scope:"TooltipHost"}),QZ=/[\(\[\{\<][^\)\]\}\>]*[\)\]\}\>]/g,ZZ=/[\0-\u001F\!-/:-@\[-`\{-\u00BF\u0250-\u036F\uD800-\uFFFF]/g,XZ=/^\d+[\d\s]*(:?ext|x|)\s*\d+$/i,eX=/\s+/g,tX=/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF\u3040-\u309F\u30A0-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF]|[\uD840-\uD869][\uDC00-\uDED6]/;!function(e){e[e.tiny=0]="tiny",e[e.extraExtraSmall=1]="extraExtraSmall",e[e.extraSmall=2]="extraSmall",e[e.small=3]="small",e[e.regular=4]="regular",e[e.large=5]="large",e[e.extraLarge=6]="extraLarge",e[e.size8=17]="size8",e[e.size10=9]="size10",e[e.size16=8]="size16",e[e.size24=10]="size24",e[e.size28=7]="size28",e[e.size32=11]="size32",e[e.size40=12]="size40",e[e.size48=13]="size48",e[e.size56=16]="size56",e[e.size72=14]="size72",e[e.size100=15]="size100",e[e.size120=18]="size120"}(HZ||(HZ={})),function(e){e[e.none=0]="none",e[e.offline=1]="offline",e[e.online=2]="online",e[e.away=3]="away",e[e.dnd=4]="dnd",e[e.blocked=5]="blocked",e[e.busy=6]="busy"}($Z||($Z={})),function(e){e[e.lightBlue=0]="lightBlue",e[e.blue=1]="blue",e[e.darkBlue=2]="darkBlue",e[e.teal=3]="teal",e[e.lightGreen=4]="lightGreen",e[e.green=5]="green",e[e.darkGreen=6]="darkGreen",e[e.lightPink=7]="lightPink",e[e.pink=8]="pink",e[e.magenta=9]="magenta",e[e.purple=10]="purple",e[e.black=11]="black",e[e.orange=12]="orange",e[e.red=13]="red",e[e.darkRed=14]="darkRed",e[e.transparent=15]="transparent",e[e.violet=16]="violet",e[e.lightRed=17]="lightRed",e[e.gold=18]="gold",e[e.burgundy=19]="burgundy",e[e.warmGray=20]="warmGray",e[e.coolGray=21]="coolGray",e[e.gray=22]="gray",e[e.cyan=23]="cyan",e[e.rust=24]="rust"}(jZ||(jZ={})),function(e){e.size8="20px",e.size10="20px",e.size16="16px",e.size24="24px",e.size28="28px",e.size32="32px",e.size40="40px",e.size48="48px",e.size56="56px",e.size72="72px",e.size100="100px",e.size120="120px"}(qZ||(qZ={})),function(e){e.size6="6px",e.size8="8px",e.size12="12px",e.size16="16px",e.size20="20px",e.size28="28px",e.size32="32px",e.border="2px"}(zZ||(zZ={}));var iX=function(e){return{isSize8:e===HZ.size8,isSize10:e===HZ.size10||e===HZ.tiny,isSize16:e===HZ.size16,isSize24:e===HZ.size24||e===HZ.extraExtraSmall,isSize28:e===HZ.size28||e===HZ.extraSmall,isSize32:e===HZ.size32,isSize40:e===HZ.size40||e===HZ.small,isSize48:e===HZ.size48||e===HZ.regular,isSize56:e===HZ.size56,isSize72:e===HZ.size72||e===HZ.large,isSize100:e===HZ.size100||e===HZ.extraLarge,isSize120:e===HZ.size120}},nX=((GZ={})[HZ.tiny]=10,GZ[HZ.extraExtraSmall]=24,GZ[HZ.extraSmall]=28,GZ[HZ.small]=40,GZ[HZ.regular]=48,GZ[HZ.large]=72,GZ[HZ.extraLarge]=100,GZ[HZ.size8]=8,GZ[HZ.size10]=10,GZ[HZ.size16]=16,GZ[HZ.size24]=24,GZ[HZ.size28]=28,GZ[HZ.size32]=32,GZ[HZ.size40]=40,GZ[HZ.size48]=48,GZ[HZ.size56]=56,GZ[HZ.size72]=72,GZ[HZ.size100]=100,GZ[HZ.size120]=120,GZ),rX=function(e){return{isAvailable:e===$Z.online,isAway:e===$Z.away,isBlocked:e===$Z.blocked,isBusy:e===$Z.busy,isDoNotDisturb:e===$Z.dnd,isOffline:e===$Z.offline}},sX=oj({cacheSize:100}),aX=e.forwardRef((function(t,i){var n=t.coinSize,r=t.isOutOfOffice,s=t.styles,a=t.presence,o=t.theme,l=t.presenceTitle,c=t.presenceColors,d=nG(i,e.useRef(null)),u=iX(t.size),h=!(u.isSize8||u.isSize10||u.isSize16||u.isSize24||u.isSize28||u.isSize32)&&(!n||n>32),g=n?n/3<40?n/3+"px":"40px":"",p=n?{fontSize:n?n/6<20?n/6+"px":"20px":"",lineHeight:g}:void 0,m=n?{width:g,height:g}:void 0,f=sX(s,{theme:o,presence:a,size:t.size,isOutOfOffice:r,presenceColors:c});return a===$Z.none?null:e.createElement("div",{role:"presentation",className:f.presence,style:m,title:l,ref:d},h&&e.createElement(mG,{className:f.presenceIcon,iconName:oX(t.presence,t.isOutOfOffice),style:p}))}));function oX(e,t){if(e){var i="SkypeArrow";switch($Z[e]){case"online":return"SkypeCheck";case"away":return t?i:"SkypeClock";case"dnd":return"SkypeMinus";case"offline":return t?i:""}return""}}aX.displayName="PersonaPresenceBase";var lX={presence:"ms-Persona-presence",presenceIcon:"ms-Persona-presenceIcon"};function cX(e){return{color:e,borderColor:e}}function dX(e,t){return{selectors:{":before":{border:"".concat(e," solid ").concat(t)}}}}function uX(e){return{height:e,width:e}}function hX(e){return{backgroundColor:e}}var gX=nj(aX,(function(e){var t,i,n,r,s,a,o=e.theme,l=e.presenceColors,c=o.semanticColors,d=o.fonts,u=FV(lX,o),h=iX(e.size),g=rX(e.presence),p=l&&l.available||"#6BB700",m=l&&l.away||"#FFAA44",f=l&&l.busy||"#C43148",v=l&&l.dnd||"#C50F1F",S=l&&l.offline||"#8A8886",y=l&&l.oof||"#B4009E",C=l&&l.background||c.bodyBackground,T=g.isOffline||e.isOutOfOffice&&(g.isAvailable||g.isBusy||g.isAway||g.isDoNotDisturb),E=h.isSize72||h.isSize100?"2px":"1px";return{presence:[u.presence,IU(IU({position:"absolute",height:zZ.size12,width:zZ.size12,borderRadius:"50%",top:"auto",right:"-2px",bottom:"-2px",border:"2px solid ".concat(C),textAlign:"center",boxSizing:"content-box",backgroundClip:"border-box"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:(t={},t[UV]={borderColor:"Window",backgroundColor:"WindowText"},t)}),(h.isSize8||h.isSize10)&&{right:"auto",top:"7px",left:0,border:0,selectors:(i={},i[UV]={top:"9px",border:"1px solid WindowText"},i)},(h.isSize8||h.isSize10||h.isSize24||h.isSize28||h.isSize32)&&uX(zZ.size8),(h.isSize40||h.isSize48)&&uX(zZ.size12),h.isSize16&&{height:zZ.size6,width:zZ.size6,borderWidth:"1.5px"},h.isSize56&&uX(zZ.size16),h.isSize72&&uX(zZ.size20),h.isSize100&&uX(zZ.size28),h.isSize120&&uX(zZ.size32),g.isAvailable&&{backgroundColor:p,selectors:(n={},n[UV]=hX("Highlight"),n)},g.isAway&&hX(m),g.isBlocked&&[{selectors:(r={":after":h.isSize40||h.isSize48||h.isSize72||h.isSize100?{content:'""',width:"100%",height:E,backgroundColor:f,transform:"translateY(-50%) rotate(-45deg)",position:"absolute",top:"50%",left:0}:void 0},r[UV]={selectors:{":after":{width:"calc(100% - 4px)",left:"2px",backgroundColor:"Window"}}},r)}],g.isBusy&&hX(f),g.isDoNotDisturb&&hX(v),g.isOffline&&hX(S),(T||g.isBlocked)&&[{backgroundColor:C,selectors:(s={":before":{content:'""',width:"100%",height:"100%",position:"absolute",top:0,left:0,border:"".concat(E," solid ").concat(f),borderRadius:"50%",boxSizing:"border-box"}},s[UV]={backgroundColor:"WindowText",selectors:{":before":{width:"calc(100% - 2px)",height:"calc(100% - 2px)",top:"1px",left:"1px",borderColor:"Window"}}},s)}],T&&g.isAvailable&&dX(E,p),T&&g.isBusy&&dX(E,f),T&&g.isAway&&dX(E,y),T&&g.isDoNotDisturb&&dX(E,v),T&&g.isOffline&&dX(E,S),T&&g.isOffline&&e.isOutOfOffice&&dX(E,y)],presenceIcon:[u.presenceIcon,{color:C,fontSize:"6px",lineHeight:zZ.size12,verticalAlign:"top",selectors:(a={},a[UV]={color:"Window"},a)},h.isSize56&&{fontSize:"8px",lineHeight:zZ.size16},h.isSize72&&{fontSize:d.small.fontSize,lineHeight:zZ.size20},h.isSize100&&{fontSize:d.medium.fontSize,lineHeight:zZ.size28},h.isSize120&&{fontSize:d.medium.fontSize,lineHeight:zZ.size32},g.isAway&&{position:"relative",left:T?void 0:"1px"},T&&g.isAvailable&&cX(p),T&&g.isBusy&&cX(f),T&&g.isAway&&cX(y),T&&g.isDoNotDisturb&&cX(v),T&&g.isOffline&&cX(S),T&&g.isOffline&&e.isOutOfOffice&&cX(y)]}}),void 0,{scope:"PersonaPresence"}),pX=[jZ.lightBlue,jZ.blue,jZ.darkBlue,jZ.teal,jZ.green,jZ.darkGreen,jZ.lightPink,jZ.pink,jZ.magenta,jZ.purple,jZ.orange,jZ.lightRed,jZ.darkRed,jZ.violet,jZ.gold,jZ.burgundy,jZ.warmGray,jZ.cyan,jZ.rust,jZ.coolGray],mX=pX.length;function fX(e){var t,i=e.primaryText,n=e.text,r=e.initialsColor;return"string"==typeof r?t=r:(r=void 0!==r?r:function(e){var t=jZ.blue;if(!e)return t;for(var i=0,n=e.length-1;n>=0;n--){var r=e.charCodeAt(n),s=n%8;i^=(r<<s)+(r>>8-s)}return pX[i%mX]}(n||i),t=function(e){switch(e){case jZ.lightBlue:return"#4F6BED";case jZ.blue:return"#0078D4";case jZ.darkBlue:return"#004E8C";case jZ.teal:return"#038387";case jZ.lightGreen:case jZ.green:return"#498205";case jZ.darkGreen:return"#0B6A0B";case jZ.lightPink:return"#C239B3";case jZ.pink:return"#E3008C";case jZ.magenta:return"#881798";case jZ.purple:return"#5C2E91";case jZ.orange:return"#CA5010";case jZ.red:return"#EE1111";case jZ.lightRed:return"#D13438";case jZ.darkRed:return"#A4262C";case jZ.transparent:return"transparent";case jZ.violet:return"#8764B8";case jZ.gold:return"#986F0B";case jZ.burgundy:return"#750B1C";case jZ.warmGray:return"#7A7574";case jZ.cyan:return"#005B70";case jZ.rust:return"#8E562E";case jZ.coolGray:return"#69797E";case jZ.black:return"#1D1D1D";case jZ.gray:return"#393939"}}(r)),t}var vX=oj({cacheSize:100}),SX=SB((function(e,t,i,n,r,s){return dB(e,!s&&{backgroundColor:fX({text:n,initialsColor:t,primaryText:r}),color:i})})),yX={size:HZ.size48,presence:$Z.none,imageAlt:""},CX=e.forwardRef((function(t,i){var n=sq(yX,t),r=function(t){var i=t.onPhotoLoadingStateChange,n=t.imageUrl,r=e.useState(Jj.notLoaded),s=r[0],a=r[1];return e.useEffect((function(){a(Jj.notLoaded)}),[n]),[s,function(e){a(e),null==i||i(e)}]}(n),s=r[0],a=r[1],o=TX(a),l=n.className,c=n.coinProps,d=n.showUnknownPersonaCoin,u=n.coinSize,h=n.styles,g=n.imageUrl,p=n.initialsColor,m=n.initialsTextColor,f=n.isOutOfOffice,v=n.onRenderCoin,S=void 0===v?o:v,y=n.onRenderPersonaCoin,C=void 0===y?S:y,T=n.onRenderInitials,E=void 0===T?EX:T,b=n.presence,_=n.presenceTitle,I=n.presenceColors,w=n.primaryText,A=n.showInitialsUntilImageLoads,P=n.text,R=n.theme,M=n.size,D=B$(n,U$),k=B$(c||{},U$),O=u?{width:u,height:u}:void 0,N=d,L={coinSize:u,isOutOfOffice:f,presence:b,presenceTitle:_,presenceColors:I,size:M,theme:R},x=vX(h,{theme:R,className:c&&c.className?c.className:l,size:M,coinSize:u,showUnknownPersonaCoin:d}),F=Boolean(s!==Jj.loaded&&(A&&g||!g||s===Jj.error||N));return e.createElement("div",IU({role:"presentation"},D,{className:x.coin,ref:i}),M!==HZ.size8&&M!==HZ.size10&&M!==HZ.tiny?e.createElement("div",IU({role:"presentation"},k,{className:x.imageArea,style:O}),F&&e.createElement("div",{className:SX(x.initials,p,m,P,w,d),style:O,"aria-hidden":"true"},E(n,EX)),!N&&C(n,o),e.createElement(gX,IU({},L))):n.presence?e.createElement(gX,IU({},L)):e.createElement(mG,{iconName:"Contact",className:x.size10WithoutPresenceIcon}),n.children)}));CX.displayName="PersonaCoinBase";var TX=function(t){return function(i){var n=i.coinSize,r=i.styles,s=i.imageUrl,a=i.imageAlt,o=i.imageShouldFadeIn,l=i.imageShouldStartVisible,c=i.theme,d=i.showUnknownPersonaCoin,u=i.size,h=void 0===u?yX.size:u;if(!s)return null;var g=vX(r,{theme:c,size:h,showUnknownPersonaCoin:d}),p=n||nX[h];return e.createElement(lG,{className:g.image,imageFit:Wj.cover,src:s,width:p,height:p,alt:a,shouldFadeIn:o,shouldStartVisible:l,onLoadingStateChange:t})}},EX=function(t){var i=t.imageInitials,n=t.allowPhoneInitials,r=t.showUnknownPersonaCoin,s=t.text,a=t.primaryText,o=t.theme;if(r)return e.createElement(mG,{iconName:"Help"});var l=PB(o);return""!==(i=i||function(e,t,i){return e?(e=function(e){return(e=(e=(e=e.replace(QZ,"")).replace(ZZ,"")).replace(eX," ")).trim()}(e),tX.test(e)||!i&&XZ.test(e)?"":function(e,t){var i="",n=e.split(" ");return 2===n.length?(i+=n[0].charAt(0).toUpperCase(),i+=n[1].charAt(0).toUpperCase()):3===n.length?(i+=n[0].charAt(0).toUpperCase(),i+=n[2].charAt(0).toUpperCase()):0!==n.length&&(i+=n[0].charAt(0).toUpperCase()),t&&i.length>1?i.charAt(1)+i.charAt(0):i}(e,t)):""}(s||a||"",l,n))?e.createElement("span",null,i):e.createElement(mG,{iconName:"Contact"})},bX={coin:"ms-Persona-coin",imageArea:"ms-Persona-imageArea",image:"ms-Persona-image",initials:"ms-Persona-initials",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120"},_X=nj(CX,(function(e){var t,i=e.className,n=e.theme,r=e.coinSize,s=n.palette,a=n.fonts,o=iX(e.size),l=FV(bX,n),c=r||e.size&&nX[e.size]||48;return{coin:[l.coin,a.medium,o.isSize8&&l.size8,o.isSize10&&l.size10,o.isSize16&&l.size16,o.isSize24&&l.size24,o.isSize28&&l.size28,o.isSize32&&l.size32,o.isSize40&&l.size40,o.isSize48&&l.size48,o.isSize56&&l.size56,o.isSize72&&l.size72,o.isSize100&&l.size100,o.isSize120&&l.size120,i],size10WithoutPresenceIcon:{fontSize:a.xSmall.fontSize,position:"absolute",top:"5px",right:"auto",left:0},imageArea:[l.imageArea,{position:"relative",textAlign:"center",flex:"0 0 auto",height:c,width:c},c<=10&&{overflow:"visible",background:"transparent",height:0,width:0}],image:[l.image,{marginRight:"10px",position:"absolute",top:0,left:0,width:"100%",height:"100%",border:0,borderRadius:"50%",perspective:"1px"},c<=10&&{overflow:"visible",background:"transparent",height:0,width:0},c>10&&{height:c,width:c}],initials:[l.initials,{borderRadius:"50%",color:e.showUnknownPersonaCoin?"rgb(168, 0, 0)":s.white,fontSize:a.large.fontSize,fontWeight:DV.semibold,lineHeight:48===c?46:c,height:c,selectors:(t={},t[UV]=IU(IU({border:"1px solid WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText",boxSizing:"border-box",backgroundColor:"Window !important"}),t.i={fontWeight:DV.semibold},t)},e.showUnknownPersonaCoin&&{backgroundColor:"rgb(234, 234, 234)"},c<32&&{fontSize:a.xSmall.fontSize},c>=32&&c<40&&{fontSize:a.medium.fontSize},c>=40&&c<56&&{fontSize:a.mediumPlus.fontSize},c>=56&&c<72&&{fontSize:a.xLarge.fontSize},c>=72&&c<100&&{fontSize:a.xxLarge.fontSize},c>=100&&{fontSize:a.superLarge.fontSize}]}}),void 0,{scope:"PersonaCoin"}),IX=oj(),wX={size:HZ.size48,presence:$Z.none,imageAlt:"",showOverflowTooltip:!0},AX=e.forwardRef((function(t,i){var n=sq(wX,t),r=nG(i,e.useRef(null)),s=function(){return n.text||n.primaryText||""},a=function(t,i,r){var s=i&&i(n,r);return s?e.createElement("div",{dir:"auto",className:t},s):void 0},o=function(t,i){return void 0===i&&(i=!0),t?i?function(){return e.createElement(YZ,{content:t,overflowMode:xZ.Parent,directionalHint:0},t)}:function(){return e.createElement(e.Fragment,null,t)}:void 0},l=o(s(),n.showOverflowTooltip),c=o(n.secondaryText,n.showOverflowTooltip),d=o(n.tertiaryText,n.showOverflowTooltip),u=o(n.optionalText,n.showOverflowTooltip),h=n.hidePersonaDetails,g=n.onRenderOptionalText,p=void 0===g?u:g,m=n.onRenderPrimaryText,f=void 0===m?l:m,v=n.onRenderSecondaryText,S=void 0===v?c:v,y=n.onRenderTertiaryText,C=void 0===y?d:y,T=n.onRenderPersonaCoin,E=void 0===T?function(t){return e.createElement(_X,IU({},t))}:T,b=n.size,_=n.allowPhoneInitials,I=n.className,w=n.coinProps,A=n.showUnknownPersonaCoin,P=n.coinSize,R=n.styles,M=n.imageAlt,D=n.imageInitials,k=n.imageShouldFadeIn,O=n.imageShouldStartVisible,N=n.imageUrl,L=n.initialsColor,x=n.initialsTextColor,F=n.isOutOfOffice,U=n.onPhotoLoadingStateChange,B=n.onRenderCoin,V=n.onRenderInitials,H=n.presence,$=n.presenceTitle,j=n.presenceColors,G=n.showInitialsUntilImageLoads,q=n.showSecondaryText,z=n.theme,W=IU({allowPhoneInitials:_,showUnknownPersonaCoin:A,coinSize:P,imageAlt:M,imageInitials:D,imageShouldFadeIn:k,imageShouldStartVisible:O,imageUrl:N,initialsColor:L,initialsTextColor:x,onPhotoLoadingStateChange:U,onRenderCoin:B,onRenderInitials:V,presence:H,presenceTitle:$,showInitialsUntilImageLoads:G,size:b,text:s(),isOutOfOffice:F,presenceColors:j},w),K=IX(R,{theme:z,className:I,showSecondaryText:q,presence:H,size:b}),J=B$(n,U$),Y=e.createElement("div",{className:K.details},a(K.primaryText,f,l),a(K.secondaryText,S,c),a(K.tertiaryText,C,d),a(K.optionalText,p,u),n.children);return e.createElement("div",IU({},J,{ref:r,className:K.root,style:P?{height:P,minWidth:P}:void 0}),E(W,E),(!h||b===HZ.size8||b===HZ.size10||b===HZ.tiny)&&Y)}));AX.displayName="PersonaBase";var PX={root:"ms-Persona",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120",available:"ms-Persona--online",away:"ms-Persona--away",blocked:"ms-Persona--blocked",busy:"ms-Persona--busy",doNotDisturb:"ms-Persona--donotdisturb",offline:"ms-Persona--offline",details:"ms-Persona-details",primaryText:"ms-Persona-primaryText",secondaryText:"ms-Persona-secondaryText",tertiaryText:"ms-Persona-tertiaryText",optionalText:"ms-Persona-optionalText",textContent:"ms-Persona-textContent"},RX=nj(AX,(function(e){var t=e.className,i=e.showSecondaryText,n=e.theme,r=n.semanticColors,s=n.fonts,a=FV(PX,n),o=iX(e.size),l=rX(e.presence),c="16px",d={color:r.bodySubtext,fontWeight:DV.regular,fontSize:s.small.fontSize};return{root:[a.root,n.fonts.medium,VH,{color:r.bodyText,position:"relative",height:qZ.size48,minWidth:qZ.size48,display:"flex",alignItems:"center",selectors:{".contextualHost":{display:"none"}}},o.isSize8&&[a.size8,{height:qZ.size8,minWidth:qZ.size8}],o.isSize10&&[a.size10,{height:qZ.size10,minWidth:qZ.size10}],o.isSize16&&[a.size16,{height:qZ.size16,minWidth:qZ.size16}],o.isSize24&&[a.size24,{height:qZ.size24,minWidth:qZ.size24}],o.isSize24&&i&&{height:"36px"},o.isSize28&&[a.size28,{height:qZ.size28,minWidth:qZ.size28}],o.isSize28&&i&&{height:"32px"},o.isSize32&&[a.size32,{height:qZ.size32,minWidth:qZ.size32}],o.isSize40&&[a.size40,{height:qZ.size40,minWidth:qZ.size40}],o.isSize48&&a.size48,o.isSize56&&[a.size56,{height:qZ.size56,minWidth:qZ.size56}],o.isSize72&&[a.size72,{height:qZ.size72,minWidth:qZ.size72}],o.isSize100&&[a.size100,{height:qZ.size100,minWidth:qZ.size100}],o.isSize120&&[a.size120,{height:qZ.size120,minWidth:qZ.size120}],l.isAvailable&&a.available,l.isAway&&a.away,l.isBlocked&&a.blocked,l.isBusy&&a.busy,l.isDoNotDisturb&&a.doNotDisturb,l.isOffline&&a.offline,t],details:[a.details,{padding:"0 24px 0 16px",minWidth:0,width:"100%",textAlign:"left",display:"flex",flexDirection:"column",justifyContent:"space-around"},(o.isSize8||o.isSize10)&&{paddingLeft:17},(o.isSize24||o.isSize28||o.isSize32)&&{padding:"0 8px"},(o.isSize40||o.isSize48)&&{padding:"0 12px"}],primaryText:[a.primaryText,HH,{color:r.bodyText,fontWeight:DV.regular,fontSize:s.medium.fontSize,selectors:{":hover":{color:r.inputTextHovered}}},i&&{height:c,lineHeight:c,overflowX:"hidden"},(o.isSize8||o.isSize10)&&{fontSize:s.small.fontSize,lineHeight:qZ.size8},o.isSize16&&{lineHeight:qZ.size28},(o.isSize24||o.isSize28||o.isSize32||o.isSize40||o.isSize48)&&i&&{height:18},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&{fontSize:s.xLarge.fontSize},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&i&&{height:22}],secondaryText:[a.secondaryText,HH,d,(o.isSize8||o.isSize10||o.isSize16||o.isSize24||o.isSize28||o.isSize32)&&{display:"none"},i&&{display:"block",height:c,lineHeight:c,overflowX:"hidden"},o.isSize24&&i&&{height:18},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&{fontSize:s.medium.fontSize},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&i&&{height:18}],tertiaryText:[a.tertiaryText,HH,d,{display:"none",fontSize:s.medium.fontSize},(o.isSize72||o.isSize100||o.isSize120)&&{display:"block"}],optionalText:[a.optionalText,HH,d,{display:"none",fontSize:s.medium.fontSize},(o.isSize100||o.isSize120)&&{display:"block"}],textContent:[a.textContent,HH]}}),void 0,{scope:"Persona"});const MX=(0,e.createContext)({sendboxTextField:"sendbox-textfield",participantButtonPeopleMenuItem:"participant-button-people-menu-item",participantItemMenuButton:"participant-item-menu-button",participantList:"participant-list",participantListPeopleButton:"participant-list-people-button",participantListRemoveParticipantButton:"participant-list-remove-participant-button",messageContent:"message-content",messageTimestamp:"message-timestamp",typingIndicator:"typing-indicator",videoGallery:"video-gallery",videoTile:"video-tile",overflowGalleryLeftNavButton:"overflow-gallery-left-nav-button",overflowGalleryRightNavButton:"overflow-gallery-right-nav-button",verticalGalleryVideoTile:"vertical-gallery-video-tile",horizontalGalleryVideoTile:"horizontal-gallery-video-tile",verticalGalleryPageCounter:"vertical-gallery-page-counter",mentionSuggestionList:"mention-suggestion-list",mentionSuggestionItem:"mention-suggestion-item"}),DX=()=>(0,e.useContext)(MX),kX=()=>e.createElement("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e.createElement("defs",null,e.createElement("radialGradient",{id:"paint0_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(16.6796 10.8658) rotate(161.935) scale(13.4702 20.3408)"},e.createElement("stop",{offset:"0.817521",stopColor:"#E99329",stopOpacity:"0"}),e.createElement("stop",{offset:"0.961397",stopColor:"#E99329"})),e.createElement("radialGradient",{id:"paint1_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7464 4.86265) rotate(103.662) scale(15.5522 10.8511)"},e.createElement("stop",{offset:"0.750766",stopColor:"#F88456",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#F88456"})),e.createElement("radialGradient",{id:"paint2_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(10.8862 4.86067) rotate(98.3094) scale(14.3189 9.99881)"},e.createElement("stop",{offset:"0.937186",stopColor:"#F27A74",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#F27A74"})),e.createElement("radialGradient",{id:"paint3_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.3363 11.238) rotate(-144.906) scale(1.08553 4.6268)"},e.createElement("stop",{offset:"0.0636767",stopColor:"#EAB170"}),e.createElement("stop",{offset:"1",stopColor:"#F6B44B",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint4_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.1484 8.75) rotate(129.452) scale(4.85649 1.57945)"},e.createElement("stop",{stopColor:"#FFC748"}),e.createElement("stop",{offset:"1",stopColor:"#FFC64A",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint5_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.6953 8.75) rotate(135) scale(1.1601 1.07723)"},e.createElement("stop",{stopColor:"#FFE964"}),e.createElement("stop",{offset:"1",stopColor:"#FFE65F",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint6_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(15.7422 8.47656) rotate(128.853) scale(3.61154 0.774997)"},e.createElement("stop",{offset:"0.251132",stopColor:"#EDB019"}),e.createElement("stop",{offset:"1",stopColor:"#EEB018",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint7_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(15.6055 8.04687) rotate(125.92) scale(3.06292 0.505665)"},e.createElement("stop",{offset:"0.0171863",stopColor:"#D29E4C"}),e.createElement("stop",{offset:"1",stopColor:"#DAA23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint8_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.2578 9.47266) rotate(-56.3099) scale(1.05631 0.227513)"},e.createElement("stop",{offset:"0.297381",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint9_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.4609 9.62891) rotate(107.216) scale(1.45176 3.15212)"},e.createElement("stop",{offset:"0.251132",stopColor:"#FFCF48"}),e.createElement("stop",{offset:"1",stopColor:"#FFD04B",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint10_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.3242 9.02344) rotate(144.638) scale(0.742444 1.38192)"},e.createElement("stop",{offset:"0.420068",stopColor:"#F2AA23"}),e.createElement("stop",{offset:"1",stopColor:"#F2AA23",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint11_linear_10246_159312",x1:"5.72266",y1:"10.9399",x2:"5.07979",y2:"9.68081",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.376446",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint12_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(3.32031 8.28125) rotate(85.0032) scale(7.17571 2.51091)"},e.createElement("stop",{stopColor:"#E6943A"}),e.createElement("stop",{offset:"1",stopColor:"#E7943A",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint13_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.46875 6.17188) rotate(87.0391) scale(6.80596 1.61557)"},e.createElement("stop",{stopColor:"#FFCF50"}),e.createElement("stop",{offset:"0.741378",stopColor:"#FFB847"}),e.createElement("stop",{offset:"1",stopColor:"#FFB848",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint14_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(6.69922 6.95312) rotate(85.2393) scale(4.00062 0.583904)"},e.createElement("stop",{stopColor:"#E79F08"}),e.createElement("stop",{offset:"1",stopColor:"#E79F08",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint15_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.82031 7.76306) rotate(83.1071) scale(3.90579 0.814298)"},e.createElement("stop",{stopColor:"#FFD14D"}),e.createElement("stop",{offset:"1",stopColor:"#FFD04E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint16_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(6.69922 9.17969) rotate(136.548) scale(1.53355 0.783563)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint17_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.46875 5.48828) rotate(80.3401) scale(0.931172 0.709009)"},e.createElement("stop",{stopColor:"#FFDA62"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA60",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint18_linear_10246_159312",x1:"6.05957",y1:"7.05618",x2:"7.26562",y2:"7.03125",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#DE890D"}),e.createElement("stop",{offset:"1",stopColor:"#F9B23D"})),e.createElement("linearGradient",{id:"paint19_linear_10246_159312",x1:"11.7919",y1:"10.3872",x2:"11.5711",y2:"7.83625",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.405208",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint20_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.90363 2.31009) rotate(56.3221) scale(2.85335 11.4486)"},e.createElement("stop",{stopColor:"#E1AE3F"}),e.createElement("stop",{offset:"1",stopColor:"#E8AD3C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint21_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.35938 5.19531) rotate(86.2538) scale(6.57655 1.44733)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.621882",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint22_linear_10246_159312",x1:"8.0957",y1:"9.0918",x2:"7.91992",y2:"7.06055",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.168836",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint23_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.82031 5.97656) rotate(78.518) scale(5.10211 0.93429)"},e.createElement("stop",{offset:"0.425088",stopColor:"#BD6606"}),e.createElement("stop",{offset:"1",stopColor:"#C77122",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint24_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.24219 5.89844) rotate(83.5653) scale(5.22825 0.629818)"},e.createElement("stop",{stopColor:"#FFCB4F"}),e.createElement("stop",{offset:"1",stopColor:"#FFCD4C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint25_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.29687 8.20313) rotate(154.799) scale(1.46784 0.851345)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint26_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.33594 4.98047) rotate(88.915) scale(5.15717 0.762321)"},e.createElement("stop",{offset:"0.342657",stopColor:"#E29E07"}),e.createElement("stop",{offset:"1",stopColor:"#DF9906",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint27_linear_10246_159312",x1:"9.14062",y1:"6.25",x2:"8.80978",y2:"6.26984",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#B76001"}),e.createElement("stop",{offset:"0.647059",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint28_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.125 3.51562) rotate(86.1859) scale(1.17448 1.07205)"},e.createElement("stop",{stopColor:"#FFDA62"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA60",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint29_linear_10246_159312",x1:"9.0625",y1:"5.68143",x2:"10.5816",y2:"5.72531",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#D5850A"}),e.createElement("stop",{offset:"1",stopColor:"#F9B343",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint30_linear_10246_159312",x1:"9.0625",y1:"5.68143",x2:"9.55093",y2:"5.6712",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#B76001"}),e.createElement("stop",{offset:"1",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint31_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.3014 4.55861) rotate(90) scale(5.01272 0.983716)"},e.createElement("stop",{stopColor:"#FFCB45"}),e.createElement("stop",{offset:"1",stopColor:"#FFC44A",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint32_linear_10246_159312",x1:"10.0391",y1:"8.40332",x2:"10.0195",y2:"7.2461",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.210964",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"0.80669",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint33_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7188 8.04687) rotate(166.996) scale(1.16638 0.888873)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFCA5B"}),e.createElement("stop",{offset:"1",stopColor:"#FFCF60",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint34_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.9922 4.76563) rotate(92.1409) scale(4.18261 0.38546)"},e.createElement("stop",{offset:"0.342657",stopColor:"#E29E07"}),e.createElement("stop",{offset:"1",stopColor:"#DF9906",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint35_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(10.9766 4.51172) rotate(90) scale(9.27734 1.28906)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.621882",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint36_linear_10246_159312",x1:"12.3828",y1:"5.9375",x2:"11.6797",y2:"5.93971",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#E59714"}),e.createElement("stop",{offset:"1",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint37_linear_10246_159312",x1:"10.0195",y1:"8.82935",x2:"10.2318",y2:"8.00715",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint38_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.2847 7.66848) rotate(-113.448) scale(6.85723 7.32906)"},e.createElement("stop",{offset:"0.869582",stopColor:"#D8A13D",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#D8A13D"})),e.createElement("radialGradient",{id:"paint39_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.2891 1.91406) rotate(93.0128) scale(1.48643 1.29895)"},e.createElement("stop",{stopColor:"#FFE763"}),e.createElement("stop",{offset:"1",stopColor:"#FFE55D",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint40_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.8164 8.53516) rotate(168.022) scale(1.41758 0.903842)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint41_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(13.4766 5.89844) rotate(92.6574) scale(9.26778 2.30713)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.431711",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint42_linear_10246_159312",x1:"11.5863",y1:"6.2696",x2:"13.5726",y2:"6.42645",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0662431",stopColor:"#E08F13"}),e.createElement("stop",{offset:"0.602743",stopColor:"#E7981B",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint43_linear_10246_159312",x1:"11.5863",y1:"6.2696",x2:"13.259",y2:"6.33379",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0662431",stopColor:"#C2681D"}),e.createElement("stop",{offset:"0.602743",stopColor:"#E69717",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint44_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.9907 8.54439) rotate(-115.482) scale(6.44971 7.3339)"},e.createElement("stop",{offset:"0.869582",stopColor:"#D8A13D",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#D8A13D"})),e.createElement("radialGradient",{id:"paint45_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.0625 5.66406) rotate(91.8841) scale(5.94071 1.40501)"},e.createElement("stop",{stopColor:"#FFDC3F"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA3C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint46_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.1016 3.51563) rotate(99.1412) scale(1.27667 1.12346)"},e.createElement("stop",{stopColor:"#FFE966"}),e.createElement("stop",{offset:"1",stopColor:"#FFE966",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint47_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7139 8.84766) rotate(124.509) scale(0.853264 2.02461)"},e.createElement("stop",{offset:"0.251132",stopColor:"#F0A623"}),e.createElement("stop",{offset:"1",stopColor:"#F2AA23",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint48_linear_10246_159312",x1:"13.877",y1:"10.0293",x2:"13.5547",y2:"9.05273",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0912498",stopColor:"#FFCD47"}),e.createElement("stop",{offset:"1",stopColor:"#FFCD52",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint49_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.8059 9.14063) rotate(99.1613) scale(2.21576 0.860587)"},e.createElement("stop",{offset:"0.251132",stopColor:"#D69211"}),e.createElement("stop",{offset:"1",stopColor:"#DAA23E",stopOpacity:"0"}))),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"#FFC23E"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint0_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint1_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint2_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint3_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint4_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint5_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint6_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint7_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint8_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint9_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint10_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"#FFC23E"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint11_linear_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint12_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint13_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint14_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint15_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint16_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint17_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"#FFC23E"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint18_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint19_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint20_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint21_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint22_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint23_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint24_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint25_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint26_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint27_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint28_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"#FFC23E"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint29_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint30_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint31_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint32_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint33_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint34_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint35_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint36_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint37_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint38_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint39_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint40_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"#FFC23E"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint41_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint42_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint43_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint44_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint45_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint46_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint47_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint48_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint49_radial_10246_159312)"})),OX=44,NX=e=>e.getTime(),LX=e=>{const t=xX(e.palette.black),i=xX(e.palette.white);return!Number.isNaN(t)&&!Number.isNaN(i)&&t>i},xX=e=>/^#[0-9A-Fa-f]{6}$/i.test(e)?(parseInt(e.substring(1,3),16)+parseInt(e.substring(3,5),16)+parseInt(e.substring(5,7),16))/3:NaN,FX={position:"relative",height:"100%",width:"100%"},UX=e=>({"@media (forced-colors: active)":{border:`0.125rem solid ${e.palette.black}`}}),BX={position:"absolute",top:"0",left:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",objectPosition:"center",objectFit:"cover",zIndex:0},VX={width:"100%",height:"100%",zIndex:5},HX=dB({position:"absolute",bottom:"0",left:"0",padding:"0.5rem",width:"100%"}),$X=dB({backgroundColor:"inherit",boxShadow:"none",textAlign:"left",overflow:"hidden",whiteSpace:"nowrap",alignItems:"center",padding:"0.15rem",maxWidth:"100%"}),jX={padding:"0.1rem",fontSize:"0.75rem",fontWeight:600,color:"inherit",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},GX={padding:"0.125rem"},qX={margin:"auto 0.2rem",alignItems:"center","& svg":{display:"block",color:"inherit"}},zX=e=>({minWidth:"max-content",color:e.palette.black,fontSize:"0.75rem",lineHeight:"normal",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"0.1rem"}),WX=e=>({root:{zIndex:1,top:"-0.125rem",height:"100%",padding:"0rem"},rootHovered:{background:"none"},rootPressed:{background:"none"},icon:{color:e.palette.neutralPrimary},iconExpanded:{background:"none",color:e.palette.themePrimary}}),KX=(e,t)=>dB({alignItems:"center",padding:"0.2rem 0.3rem",backgroundColor:e.palette.white,opacity:.9,borderRadius:"1rem",margin:"0.5rem",width:"fit-content",position:"absolute",top:0,height:"fit-content"},t&&JX),JX={marginLeft:"auto",marginRight:"auto",left:0,right:0,bottom:0},YX=SB(((e,t)=>NB({from:{backgroundPosition:"0px 0px"},to:{backgroundPosition:`0px ${t*-e}px`}}))),QX=(e,t)=>({circle:{width:"2rem",height:"2rem"},label:{fontSize:"1rem",color:t?LX(e)?e.palette.black:e.palette.white:e.palette.themeDarkAlt}}),ZX={marginLeft:"0.2rem"};function XX(t){const{onClick:i,onLongPress:n,touchEventsOnly:r=!1}=t,s=(0,e.useRef)(),[a,o]=(0,e.useState)(!1),[l,c]=(0,e.useState)(!1);(0,e.useEffect)((()=>(s.current&&clearTimeout(s.current),()=>{s.current&&clearTimeout(s.current)})),[i,n,r]);const d=(0,e.useCallback)((()=>{o(!1),s.current=setTimeout((()=>{o(!0),n()}),500)}),[n]),u=(0,e.useCallback)((()=>{!r&&i&&(a||i())}),[a,i,r]),h=(0,e.useCallback)((()=>{r||l&&(c(!1),d())}),[l,d,r]),g=(0,e.useCallback)((()=>{r||(c(!0),s.current&&clearTimeout(s.current))}),[r]),p=(0,e.useCallback)((()=>{r||d()}),[d,r]),m=(0,e.useCallback)((()=>{r||s.current&&clearTimeout(s.current)}),[r]),f=(0,e.useCallback)((()=>{d()}),[d]),v=(0,e.useCallback)((()=>{!a&&i&&i(),s.current&&clearTimeout(s.current)}),[i,a]),S=(0,e.useCallback)((()=>{s.current&&clearTimeout(s.current)}),[]);return(0,e.useMemo)((()=>({onClick:u,onMouseDown:p,onMouseUp:m,onTouchStart:f,onTouchEnd:v,onKeyDown:h,onKeyUp:g,onTouchMove:S})),[u,h,g,p,m,v,f,S])}const e0=100,t0=32,i0=t=>{const{text:i,noVideoAvailableAriaLabel:n,coinSize:r,hidePersonaDetails:s}=t;return e.createElement(Y$,{className:dB({position:"absolute",height:"100%",width:"100%"})},e.createElement(Y$,{styles:n0},r&&e.createElement(RX,{coinSize:r,hidePersonaDetails:s,text:null!=i?i:"",initialsTextColor:"white","aria-label":null!=n?n:"",showOverflowTooltip:!1})))},n0={root:{margin:"auto",maxHeight:"100%"}},r0={iconName:void 0,style:{display:"none"}},s0={directionalHint:0,isBeakVisible:!1,styles:{container:{maxWidth:"8rem"}}},a0=t=>{const i=AK().strings.videoTile,n=aJ(),{contextualMenu:r,canShowContextMenuButton:s,participantDisplayName:a,participantHandRaised:o,participantIsSpeaking:l,participantState:c,participantIsMuted:d,isMicDisabled:u,isCameraDisabled:h}=t,[g,p]=(0,e.useState)("");if((0,e.useEffect)((()=>{p(((e,t,i,n,r,s,a,o)=>{const l=t?null==s?void 0:s.moreOptionsParticipantMutedStateMutedAriaLabel:null==s?void 0:s.moreOptionsParticipantMutedStateUnmutedAriaLabel,c=i?null==s?void 0:s.moreOptionsParticipantHandRaisedAriaLabel:void 0,d=r?null==s?void 0:s.moreOptionsParticipantIsSpeakingAriaLabel:void 0,u=a?null==s?void 0:s.moreOptionsParticipantMicDisabledAriaLabel:void 0,h=o?null==s?void 0:s.moreOptionsParticipantCameraDisabledAriaLabel:void 0;return(null==s?void 0:s.moreOptionsButtonAriaLabel)?PK(null==s?void 0:s.moreOptionsButtonAriaLabel,{displayName:null!=e?e:" ",isMuted:null!=l?l:" ",isHandRaised:null!=c?c:" ",state:null!=n?n:" ",isSpeaking:null!=d?d:" ",micDisabledState:null!=u?u:" ",cameraDisabledState:null!=h?h:" "}):""})(a,d,o,c,l,i,u,h))}),[a,o,d,l,c,i,u,h]),!r)return e.createElement(e.Fragment,null);const m=s?"VideoTileMoreOptions":void 0;return e.createElement(oK,{"data-ui-id":"video-tile-more-options-button",ariaLabel:g,styles:WX(n),menuIconProps:r0,menuProps:Object.assign(Object.assign({},s0),r),iconProps:{iconName:m}})},o0=t=>{const{children:i,displayName:n,initialsName:r,isMirrored:s,isMuted:a,isSpotlighted:o,isPinned:l,onRenderPlaceholder:c,renderElement:d,overlay:u,showLabel:h=!0,showMuteIndicator:g=!0,styles:p,userId:m,noVideoAvailableAriaLabel:f,isSpeaking:v,raisedHand:S,personaMinSize:y=t0,personaMaxSize:C=e0,contextualMenu:T,mediaAccess:E}=t,[b,_]=(0,e.useState)(!1),[I,w]=(0,e.useState)(!1),[A,P]=(0,e.useState)(1),R=(0,e.useRef)(null),M=AK(),D=aJ(),k=D.callingPalette,O=!!d,N=(0,e.useRef)(new ResizeObserver((e=>{if(!e[0])return;const{width:t,height:i}=e[0].contentRect,n=Math.min(t,i)/3;n!==A&&P(Math.max(Math.min(n,C),y))})));(0,e.useLayoutEffect)((()=>{R.current&&N.current.observe(R.current);const e=N.current;return()=>e.disconnect()}),[R]),(0,e.useEffect)((()=>{var e;if(null===(e=R.current)||void 0===e?void 0:e.id)return;let t;return R.current&&(t=new MutationObserver((e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector("iframe");e&&(e.getAttribute("tabIndex")||e.setAttribute("tabIndex","-1"))}})),t.observe(R.current,{childList:!0,subtree:!0})),()=>{null==t||t.disconnect()}}),[n,d]);const L=(0,e.useMemo)((()=>({onLongPress:()=>{var e;null===(e=t.onLongTouch)||void 0===e||e.call(t)},touchEventsOnly:!0})),[t.onLongTouch]),x=XX(L),F=(0,e.useMemo)((()=>({onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),onFocus:()=>w(!0),onBlur:()=>w(!1)})),[]),U={userId:m,text:null!=r?r:n,noVideoAvailableAriaLabel:f,coinSize:A,styles:n0,hidePersonaDetails:!0},B=dB($X,{borderRadius:D.effects.roundedCorner4,backgroundColor:k.videoTileLabelBackgroundLight}),V=(0,e.useMemo)((()=>dB(O||t.alwaysShowLabelBackground?B:$X,null==p?void 0:p.displayNameContainer)),[O,B,null==p?void 0:p.displayNameContainer,t.alwaysShowLabelBackground]),H=DX(),$=h&&(n||g&&a),j=c0(t,M),G=b||I;let q="";q=k.raiseHandGold;const z=(0,e.useMemo)((()=>$||j?l0(g,a,E):void 0),[$,a,E,j,g]),W=z||o||l;return e.createElement(Y$,Object.assign({"data-ui-id":H.videoTile,className:dB(FX,{background:D.palette.neutralLighter,borderRadius:D.effects.roundedCorner4},v||S?{"&::after":{content:"''",position:"absolute",border:`0.25rem solid ${v?D.palette.themePrimary:q}`,borderRadius:D.effects.roundedCorner4,width:"100%",height:"100%",pointerEvents:"none"}}:{},UX(D),null==p?void 0:p.root)},x),e.createElement("div",Object.assign({ref:R,style:{width:"100%",height:"100%"}},F,{"data-is-focusable":!0}),O?e.createElement(Y$,{className:dB(BX,s&&{transform:"scaleX(-1)"},null==p?void 0:p.videoContainer)},d):e.createElement(Y$,{className:dB(BX,{opacity:j||"Idle"===t.participantState?.4:1})},c?c(null!=m?m:"",U,i0):e.createElement(i0,Object.assign({},U))),u,($||j)&&e.createElement(Y$,{horizontal:!0,className:HX,tokens:d0},e.createElement(Y$,{horizontal:!0,className:V},$&&e.createElement(oJ,{className:dB(jX),title:n,style:{color:j?D.palette.neutralSecondary:"inherit"},"data-ui-id":"video-tile-display-name"},n),j&&e.createElement(oJ,{className:dB(zX(D))},u0(j,!!$)),W&&e.createElement(Y$,{horizontal:!0,className:dB(ZX)},z,o&&e.createElement(Y$,{className:dB(qX)},e.createElement(mG,{iconName:"VideoTileSpotlighted"})),l&&e.createElement(Y$,{className:dB(qX)},e.createElement(mG,{iconName:"VideoTilePinned",className:dB(GX)}))),e.createElement(a0,{contextualMenu:T,participantDisplayName:n,participantHandRaised:!!S,participantIsMuted:a,participantState:j,participantIsSpeaking:v,canShowContextMenuButton:G,isMicDisabled:!1===(null==E?void 0:E.isAudioPermitted),isCameraDisabled:!1===(null==E?void 0:E.isVideoPermitted)}))),i&&e.createElement(Y$,{className:dB(VX,null==p?void 0:p.overlayContainer)},i),S&&e.createElement(Y$,{horizontal:!0,tokens:{childrenGap:"0.2rem"},className:KX(D,!$)},e.createElement(Y$.Item,null,e.createElement(oJ,null,S.raisedHandOrderPosition)),e.createElement(Y$.Item,null,e.createElement(kX,null)))))},l0=(t,i,n)=>{const r=n&&!(null==n?void 0:n.isVideoPermitted)?e.createElement(Y$,{className:dB(qX)},e.createElement(mG,{iconName:"ControlButtonCameraProhibitedSmall"})):void 0,s=(!n||n.isAudioPermitted)&&t&&i?e.createElement(Y$,{className:dB(qX)},e.createElement(mG,{iconName:"VideoTileMicOff"})):void 0,a=n&&!(null==n?void 0:n.isAudioPermitted)&&t?e.createElement(Y$,{className:dB(qX)},e.createElement(mG,{iconName:"ControlButtonMicProhibitedSmall"})):void 0;if(r||s||a)return e.createElement(e.Fragment,null,r,s,a)},c0=(e,t)=>{const i=Object.assign(Object.assign({},t.strings.videoTile),e.strings);return"EarlyMedia"===e.participantState||"Ringing"===e.participantState?null==i?void 0:i.participantStateRinging:"Hold"===e.participantState?null==i?void 0:i.participantStateHold:void 0},d0={childrenGap:"none"},u0=(e,t)=>t?`(${e})`:e;const h0=t=>{var i,n,r,s,a,o,l,c;const{userId:d,dataProvider:u,text:h,imageUrl:g,imageInitials:p,initialsColor:m,initialsTextColor:f,showOverflowTooltip:v}=t,[S,y]=(0,e.useState)();(0,e.useEffect)((()=>{var e,t,i,n;e=void 0,t=void 0,n=function*(){if(u&&d){const e=yield u(d);g0(S,e)&&y(e)}},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))}),[S,u,d]);let C="";return t.allowActiveBorder&&(C=dB({border:"solid 2px",borderColor:"transparent",borderRadius:"50%",padding:"2px",boxSizing:"content-box",margin:"-4px"}),dB(C,t.styles)),e.createElement(RX,Object.assign({},t,{className:C,text:null!==(i=null==S?void 0:S.text)&&void 0!==i?i:h,imageUrl:null!==(n=null==S?void 0:S.imageUrl)&&void 0!==n?n:g,imageInitials:null!==(r=null==S?void 0:S.imageInitials)&&void 0!==r?r:p,initialsColor:null!==(s=null==S?void 0:S.initialsColor)&&void 0!==s?s:m,initialsTextColor:null!==(o=null!==(a=null==S?void 0:S.initialsTextColor)&&void 0!==a?a:f)&&void 0!==o?o:"white",showOverflowTooltip:null!=v&&v,showUnknownPersonaCoin:null!==(c=null!==(l=null==S?void 0:S.showUnknownPersonaCoin)&&void 0!==l?l:t.showUnknownPersonaCoin)&&void 0!==c&&c}))},g0=(e,t)=>(null==e?void 0:e.text)!==(null==t?void 0:t.text)||(null==e?void 0:e.imageUrl)!==(null==t?void 0:t.imageUrl)||(null==e?void 0:e.initialsColor)!==(null==t?void 0:t.initialsColor)||(null==e?void 0:e.imageInitials)!==(null==t?void 0:t.imageInitials)||(null==e?void 0:e.initialsTextColor)!==(null==t?void 0:t.initialsTextColor),p0=e=>e*f0(),m0=e=>e/f0(),f0=()=>{let e=parseFloat(getComputedStyle(document.documentElement).fontSize);return Number.isNaN(e)&&(e=16),e},v0=e=>"resize"===e.type||"scroll"===e.type;function S0(e){return Object.keys(e)}const y0=t=>{const[i,n]=(0,e.useState)(void 0),r=(0,e.useRef)(new ResizeObserver((e=>{if(!e[0])return;const{width:t}=e[0].contentRect;Number.isNaN(t)?n(0):n(t)})));return(0,e.useEffect)((()=>{t.current&&r.current.observe(t.current);const e=r.current;return()=>{e.disconnect()}}),[t,r]),i},C0=t=>{const[i,n]=(0,e.useState)(void 0),r=(0,e.useRef)(new ResizeObserver((e=>{if(!e[0])return;const{height:t}=e[0].contentRect;Number.isNaN(t)?n(0):n(t)})));return(0,e.useEffect)((()=>{t.current&&r.current.observe(t.current);const e=r.current;return()=>{e.disconnect()}}),[t,r]),i},T0=e=>e<=p0(30),E0=e=>e<=p0(23.75),b0=(e,t)=>{"Enter"!==e.key&&" "!==e.key||t(e)},_0=t=>{var i;const n=aJ(),r=e=>t.onItemClick&&t.onItemClick(e,t.itemKey),s=t.secondaryIconProps?e.createElement(I0,Object.assign({},t.secondaryIconProps)):t.subMenuProps?e.createElement(I0,{iconName:"ChevronRight"}):void 0;return e.createElement(iq,{shouldFocusOnMount:t.shouldFocusOnMount},e.createElement(Y$,{tabIndex:0,role:"menuitem",horizontal:!0,className:dB(A0(n.palette.neutralLight,n.fonts.small),t.disabled?P0(n.palette.neutralQuaternaryAlt):void 0,null===(i=t.styles)||void 0===i?void 0:i.root),onKeyPress:t.disabled?void 0:e=>r&&b0(e,r),onClick:t.disabled?void 0:r,tokens:w0,id:t.id,"aria-label":t.ariaLabel},t.iconProps&&e.createElement(Y$.Item,{role:"presentation",styles:t.disabled?{root:{color:n.palette.neutralTertiaryAlt}}:void 0},e.createElement(I0,Object.assign({},t.iconProps))),e.createElement(Y$.Item,{styles:R0,grow:!0},e.createElement(oJ,{styles:t.disabled?{root:{color:n.palette.neutralTertiaryAlt}}:void 0},t.text)),t.secondaryText&&e.createElement(Y$.Item,{styles:R0,className:dB(D0)},e.createElement(oJ,{styles:{root:{color:t.disabled?n.palette.neutralTertiaryAlt:n.palette.neutralSecondary}}},t.secondaryText)),t.secondaryComponent&&e.createElement(Y$.Item,null,t.secondaryComponent),s&&e.createElement(Y$.Item,null,s)))},I0=t=>e.createElement(hG,Object.assign({className:dB(M0)},t)),w0={childrenGap:"0.5rem"},A0=(e,t)=>Object.assign(Object.assign({},t),{height:"3rem",lineHeight:"3rem",padding:"0rem 0.75rem",cursor:"pointer",":hover, :focus":{background:e}}),P0=e=>({pointerEvents:"none",background:e,":hover, :focus":{background:e}}),R0={root:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},M0={display:"flex",alignItems:"center",height:"100%"," span":{display:"flex",alignItems:"center",height:"100%"}},D0={maxWidth:"50%"};var k0=function(e){for(var t=e.activeElement;null==t?void 0:t.shadowRoot;)t=t.shadowRoot.activeElement;return t},O0=function(e){var t=e.target;return t&&t.shadowRoot&&(t=e.composedPath()[0]),t};function N0(t){var i=e.useRef((function(){throw new Error("Cannot call an event handler while rendering")}));return iG((function(){i.current=t}),[t]),Xq((function(){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.current.apply(void 0,e)}}))}var L0={disabled:!1,disableFirstFocus:!1,forceFocusInsideTrap:!0,isClickableOutsideFocusTrap:!1,"data-tabster":'{"uncontrolled": {"completely": true}}'},x0=e.forwardRef((function(t,i){var n,r=e.useRef(null),s=e.useRef(null),a=e.useRef(null),o=nG(r,i),l=Yq(),c=iz(),d=!!JW(),u=null===(n=cW(!1))||void 0===n||n,h=sq(L0,t),g=Xq({hasFocus:!1,focusStackId:g$("ftz-",h.id)}),p=h.children,m=h.componentRef,f=h.disabled,v=h.disableFirstFocus,S=h.forceFocusInsideTrap,y=h.focusPreviouslyFocusedInnerElement,C=h.firstFocusableSelector,T=h.firstFocusableTarget,E=h.disableRestoreFocus,b=void 0===E?h.ignoreExternalFocusing:E,_=h.isClickableOutsideFocusTrap,I=h.enableAriaHiddenSiblings,w={"aria-hidden":!0,style:{pointerEvents:"none",position:"fixed"},tabIndex:f?-1:0,"data-is-visible":!0,"data-is-focus-trap-zone-bumper":!0},A=e.useCallback((function(e){e!==s.current&&e!==a.current&&OG(e)}),[]),P=N0((function(){if(r.current){var e=g.previouslyFocusedElementInTrapZone;if(y&&e&&CG(r.current,e))A(e);else{var t=null;if("string"==typeof T)t=r.current.querySelector(T);else if(T)t=T(r.current);else if(C){var i="string"==typeof C?C:C();t=r.current.querySelector("."+i)}t||(t=_G(r.current,r.current.firstChild,!1,!1,!1,!0,void 0,void 0,void 0,d)),t&&A(t)}}})),R=function(e){if(!f&&r.current){var t,i=e===g.hasFocus?(void 0===(t=!1)&&(t=!0),bG(r.current,a.current,t,!1,!0,!0,!1,!0,d)):function(e,t,i,n,r){return void 0===n&&(n=!0),_G(e,t,n,!1,!1,!0,!1,!0,void 0,r)}(r.current,s.current,0,!1,d);i&&(i===s.current||i===a.current?P():i.focus())}},M=N0((function(e){if(x0.focusStack=x0.focusStack.filter((function(e){return g.focusStackId!==e})),l){var t=l.activeElement;b||"function"!=typeof(null==e?void 0:e.focus)||!CG(r.current,t)&&t!==l.body&&!t.shadowRoot||A(e)}})),D=N0((function(e){if(!f&&g.focusStackId===x0.focusStack.slice(-1)[0]){var t=O0(e);t&&!CG(r.current,t)&&(l&&k0(l)===l.body?setTimeout((function(){l&&k0(l)===l.body&&(P(),g.hasFocus=!0)}),0):(P(),g.hasFocus=!0),e.preventDefault(),e.stopPropagation())}}));return e.useEffect((function(){var e=[];return S&&e.push(pq(c,"focus",D,!0)),_||e.push(pq(c,"click",D,!0)),function(){e.forEach((function(e){return e()}))}}),[S,_,c]),e.useEffect((function(){if(!f&&(u||S)&&r.current){x0.focusStack.push(g.focusStackId);var e=h.elementToFocusOnDismiss||k0(l);return v||CG(r.current,e)||P(),function(){return M(e)}}}),[S,f]),e.useEffect((function(){if(!f&&I)return qq(r.current)}),[f,I,r]),_J((function(){delete g.previouslyFocusedElementInTrapZone})),function(t,i,n){e.useImperativeHandle(t,(function(){return{get previouslyFocusedElement(){return i},focus:n}}),[n,i])}(m,g.previouslyFocusedElementInTrapZone,P),e.createElement("div",IU({"aria-labelledby":h.ariaLabelledBy},B$(h,U$),{ref:o,onFocusCapture:function(e){var t;null===(t=h.onFocusCapture)||void 0===t||t.call(h,e),e.target===s.current?R(!0):e.target===a.current&&R(!1),g.hasFocus=!0,e.target!==e.currentTarget&&e.target!==s.current&&e.target!==a.current&&(g.previouslyFocusedElementInTrapZone=O0(e.nativeEvent))},onBlurCapture:function(e){var t;null===(t=h.onBlurCapture)||void 0===t||t.call(h,e);var i=e.relatedTarget;null===e.relatedTarget&&(i=k0(l)),CG(r.current,i)||(g.hasFocus=!1)}}),e.createElement("div",IU({},w,{ref:s})),p,e.createElement("div",IU({},w,{ref:a})))}));x0.displayName="FocusTrapZone",x0.focusStack=[];const F0=t=>{var i;const n=qK(),r=n.palette.white,s=n.effects.roundedCorner4,a=dB(U0(r,s),null===(i=t.styles)||void 0===i?void 0:i.root);return e.createElement(Y$,{className:a},t.heading&&e.createElement(Y$,{className:dB(B0)},e.createElement(oJ,{className:dB(V0(n))},t.heading)),t.children)},U0=(e,t)=>Object.assign({background:e,borderTopRightRadius:t,borderTopLeftRadius:t},EV.slideUpIn10),B0={textAlign:"center",width:"100%",padding:"0.5rem"},V0=e=>({color:e.palette.neutralSecondary,fontSize:e.fonts.smallPlus.fontSize,lineHeight:"1rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),H0=t=>e.createElement(Y$,{className:dB($0,t.styles),grow:!0,onClick:()=>t.onDismiss()}),$0={root:{height:"100%"}},j0=t=>{var i,n,r,s;const a=t.disableMaxHeight?dB(G0,null===(i=t.styles)||void 0===i?void 0:i.root):dB(G0,q0,null===(n=t.styles)||void 0===n?void 0:n.root),o=e$(z0,null===(r=t.styles)||void 0===r?void 0:r.drawerContentContainer);return e.createElement(Y$,{className:a},e.createElement(H0,{styles:null===(s=t.styles)||void 0===s?void 0:s.lightDismissRoot,onDismiss:t.onLightDismiss}),e.createElement(x0,{onKeyDown:e=>{"Escape"!==e.key&&"Esc"!==e.key||t.onLightDismiss&&t.onLightDismiss()},isClickableOutsideFocusTrap:!0},e.createElement(F0,{styles:o,heading:t.heading},t.children)))},G0={width:"100%",height:"100%",background:"rgba(0,0,0,0.4)"},q0={"> div:nth-child(2)":{maxHeight:"75%",overflow:"auto"}},z0={root:{height:"auto"}},W0=e=>void 0===e.onRendererContent,K0=t=>{var i,n;const[r,s]=(0,e.useState)([]),a=(0,e.useMemo)((()=>{var e;let i=t.items;for(const t of r)i=null===(e=null==i?void 0:i.find((e=>W0(e)&&e.itemKey===t)))||void 0===e?void 0:e.subMenuProps;return i}),[t.items,r]),o=(0,e.useCallback)(((e,t,i)=>{var n;e.subMenuProps&&s([...r,e.itemKey]),null===(n=e.onItemClick)||void 0===n||n.call(e,t,i)}),[r]),l=aJ().effects.roundedCorner4,c=(null==a?void 0:a[0])&&(null===(i=a[0])||void 0===i?void 0:i.styles),d=(0,e.useMemo)((()=>PH(null!=c?c:{},{root:{borderTopRightRadius:l,borderTopLeftRadius:l}})),[c,l]);return e.createElement(j0,{disableMaxHeight:t.disableMaxHeight,styles:null===(n=t.styles)||void 0===n?void 0:n.drawerSurfaceStyles,onLightDismiss:t.onLightDismiss,heading:t.heading,"data-ui-id":"drawer-menu"},e.createElement(Y$,{styles:t.styles,role:"menu","data-ui-id":"drawer-menu"},null==a?void 0:a.slice(0,1).map((t=>{var i;return W0(t)?e.createElement(_0,Object.assign({},t,{key:`${t.itemKey}0`,shouldFocusOnMount:"reactions"!==t.itemKey,styles:d,onItemClick:"reactions"===t.itemKey?void 0:(e,i)=>{o(t,e,i)}})):null===(i=t.onRendererContent)||void 0===i?void 0:i.call(t)})),null==a?void 0:a.slice(1).map(((t,i)=>{var n;return W0(t)?e.createElement(_0,Object.assign({},t,{key:`${t.itemKey}${i+1}`,onItemClick:(e,i)=>{o(t,e,i)}})):null===(n=t.onRendererContent)||void 0===n?void 0:n.call(t)}))))},J0=t=>{const{announcementString:i,ariaLive:n}=t;return e.createElement(Y$,{"aria-label":i,"aria-live":n,role:"status","aria-atomic":!0,styles:Y0})},Y0={root:{position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0}},Q0={root:{height:"100%"},circle:{maxHeight:"5rem",height:"50%",width:"unset",aspectRatio:"1 / 1",borderWidth:"0.25em"}},Z0=e=>dB({position:"relative",height:"100%",width:"100%",background:"transparent",display:"flex","& video":{borderRadius:e.effects.roundedCorner4}}),X0=e=>dB(Z0(e),{transform:"rotateY(180deg)","& video:picture-in-picture":{transform:"rotateY(180deg)"}}),e1=t=>{const i=(0,e.useRef)(null),n=aJ(),{isMirrored:r,videoStreamElement:s,styles:a,loadingState:o="none"}=t,[l,c]=(0,e.useState)(!1);return(0,e.useEffect)((()=>{const e=i.current;if(e)return e.innerHTML="",c(!1),s&&(s.addEventListener("enterpictureinpicture",(()=>{c(!0)})),s.addEventListener("leavepictureinpicture",(()=>{c(!1)})),e.appendChild(s)),()=>{e.innerHTML="",c(!1)}}),[s]),e.createElement("div",{className:dB({position:"relative",display:"contents"})},e.createElement("div",{"data-ui-id":"stream-media-container",className:dB(r&&l?X0(n):Z0(n),null==a?void 0:a.root),ref:i}),"loading"===o&&e.createElement("div",{className:dB({position:"absolute",top:"50%",bottom:"0",left:"50%",right:"0",transform:"translate(-50%, -50%)"})},e.createElement(yZ,{"data-ui-id":"stream-media-loading-spinner",styles:Q0})))},t1={height:"100%",width:"100%",position:"relative"},i1={root:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:2}},n1=R("communication-react:calling-component"),r1=t=>{const{isMirrored:i,isScreenSharingOn:n,isStreamAvailable:r,onCreateStreamView:s,onDisposeStreamView:a,renderElementExists:o,scalingMode:l,streamId:c,isVideoPermitted:d}=t,[u,h]=(0,e.useState)();return(0,e.useEffect)((()=>{var e;return!1!==d&&r&&!o&&(null===(e=null==s?void 0:s({isMirrored:i,scalingMode:l}))||void 0===e||e.then((e=>{e&&h(e)}))),()=>{o?n||null==a||a():n1.warning("Stream view element does not exist when disposing stream view")}}),[i,n,r,s,a,o,l,c,d]),(0,e.useEffect)((()=>()=>{n||null==a||a()}),[n,a]),u},s1=t=>{var i;const{participant:n,view:r,strings:s,isPinned:a,onPinParticipant:o,onUnpinParticipant:l,onUpdateScalingMode:c,disablePinMenuItem:d,toggleAnnouncerString:u,spotlightedParticipantUserIds:h=[],isSpotlighted:g,onStartSpotlight:p,onStopSpotlight:m,maxParticipantsToSpotlight:f,myUserId:v,onMuteParticipant:S,onForbidAudio:y,onPermitAudio:C,onForbidVideo:T,onPermitVideo:E}=t,b=(0,e.useMemo)((()=>{var e;return null===(e=t.participant.videoStream)||void 0===e?void 0:e.scalingMode}),[null===(i=t.participant.videoStream)||void 0===i?void 0:i.scalingMode]),_=(0,e.useMemo)((()=>{var e,t;const i=[];if(S&&(null==s?void 0:s.muteParticipantMenuItemLabel)&&i.push({key:"mute",text:null==s?void 0:s.muteParticipantMenuItemLabel,iconProps:{iconName:"ContextualMenuMicMutedIcon",styles:{root:{lineHeight:0}}},onClick:()=>S(n.userId),"data-ui-id":"video-tile-mute-participant",ariaLabel:null==s?void 0:s.muteParticipantMenuItemLabel,disabled:n.isMuted}),n.canAudioBeForbidden&&n.mediaAccess&&!n.mediaAccess.isAudioPermitted&&C&&i.push({key:"permitAudio",text:null==s?void 0:s.permitAudioTileMenuLabel,iconProps:{iconName:"ControlButtonMicOn",styles:{root:{lineHeight:0}}},onClick:()=>C([n.userId]),"data-ui-id":"video-tile-permit-audio",ariaLabel:null==s?void 0:s.permitAudioTileMenuLabel}),n.canAudioBeForbidden&&(null===(e=n.mediaAccess)||void 0===e?void 0:e.isAudioPermitted)&&y&&i.push({key:"forbidAudio",text:null==s?void 0:s.forbidAudioTileMenuLabel,iconProps:{iconName:"ControlButtonMicProhibited",styles:{root:{lineHeight:0}}},onClick:()=>y([n.userId]),"data-ui-id":"video-tile-forbid-audio",ariaLabel:null==s?void 0:s.forbidAudioTileMenuLabel}),n.canVideoBeForbidden&&n.mediaAccess&&!n.mediaAccess.isVideoPermitted&&E&&i.push({key:"permitVideo",text:null==s?void 0:s.permitVideoTileMenuLabel,iconProps:{iconName:"ControlButtonCameraOn",styles:{root:{lineHeight:0}}},onClick:()=>E([n.userId]),"data-ui-id":"video-tile-permit-video",ariaLabel:null==s?void 0:s.permitVideoTileMenuLabel}),n.canVideoBeForbidden&&(null===(t=n.mediaAccess)||void 0===t?void 0:t.isVideoPermitted)&&T&&i.push({key:"forbidVideo",text:null==s?void 0:s.forbidVideoTileMenuLabel,iconProps:{iconName:"ControlButtonCameraProhibited",styles:{root:{lineHeight:0}}},onClick:()=>T([n.userId]),"data-ui-id":"video-tile-forbid-video",ariaLabel:null==s?void 0:s.forbidVideoTileMenuLabel}),void 0!==a){if(a&&l&&(null==s?void 0:s.unpinParticipantForMe)){let e;u&&s.unpinParticipantMenuItemAriaLabel&&n.displayName&&(e=PK(null==s?void 0:s.unpinParticipantMenuItemAriaLabel,{participantName:n.displayName})),i.push({key:"unpin",text:s.unpinParticipantForMe,iconProps:{iconName:"UnpinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{l(n.userId),e&&(null==u||u(e))},"data-ui-id":"video-tile-unpin-participant-button",ariaLabel:e})}if(!a&&o&&(null==s?void 0:s.pinParticipantForMe)){let e;u&&s.pinnedParticipantAnnouncementAriaLabel&&n.displayName&&(e=PK(null==s?void 0:s.pinnedParticipantAnnouncementAriaLabel,{participantName:n.displayName})),i.push({key:"pin",text:d?s.pinParticipantForMeLimitReached:s.pinParticipantForMe,iconProps:{iconName:"PinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{o(n.userId),e&&(null==u||u(e))},"data-ui-id":"video-tile-pin-participant-button",disabled:d||g,ariaLabel:s.pinParticipantForMe})}}if(g){const e=v===n.userId?null==s?void 0:s.stopSpotlightOnSelfVideoTileMenuLabel:null==s?void 0:s.stopSpotlightVideoTileMenuLabel;m&&n.userId&&(null==s?void 0:s.stopSpotlightVideoTileMenuLabel)&&i.push({key:"stopSpotlight",text:e,iconProps:{iconName:"StopSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},onClick:()=>m([n.userId]),ariaLabel:s.stopSpotlightVideoTileMenuLabel})}else{const e=h&&h.length>0?null==s?void 0:s.addSpotlightVideoTileMenuLabel:null==s?void 0:s.startSpotlightVideoTileMenuLabel,t=!!f&&h.length>=f;p&&n.userId&&e&&i.push({key:"startSpotlight",text:e,iconProps:{iconName:"StartSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},onClick:()=>p([n.userId]),ariaLabel:e,disabled:t,title:t?null==s?void 0:s.spotlightLimitReachedMenuTitle:void 0})}if(b&&("Crop"===b&&(null==s?void 0:s.fitRemoteParticipantToFrame)?i.push({key:"fitRemoteParticipantToFrame",text:s.fitRemoteParticipantToFrame,iconProps:{iconName:"VideoTileScaleFit",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{null==c||c(n.userId,"Fit"),null==r||r.updateScalingMode("Fit")},"data-ui-id":"video-tile-fit-to-frame",ariaLabel:s.fitRemoteParticipantToFrame}):"Fit"===b&&(null==s?void 0:s.fillRemoteParticipantFrame)&&i.push({key:"fillRemoteParticipantFrame",text:s.fillRemoteParticipantFrame,iconProps:{iconName:"VideoTileScaleFill",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{null==c||c(n.userId,"Crop"),null==r||r.updateScalingMode("Crop")},"data-ui-id":"video-tile-fill-frame",ariaLabel:s.fillRemoteParticipantFrame})),0!==i.length)return{items:i,styles:{},calloutProps:{preventDismissOnEvent:v0},shouldFocusOnContainer:!1}}),[S,s,n.isMuted,n.userId,n.displayName,a,g,b,l,o,u,d,v,m,h,f,p,c,r,n.canAudioBeForbidden,n.canVideoBeForbidden,n.mediaAccess,C,y,E,T]);return _},a1=e=>{const{participants:t,dominantSpeakers:i=[],currentParticipants:n=[],maxDominantSpeakers:r}=e;if(t.length<=r)return t;const s=o1(t),a=i.filter((e=>!!s[e])).slice(0,r),o=n.map((e=>e.userId)).slice(0,r),l=a.filter((e=>!o.includes(e)));for(let e=0;e<r;e++){const t=o[e];if(void 0===t||!a.includes(t)){const t=l.shift();if(!t)break;o[e]=t}}let c=o.map((e=>s[e])).filter((e=>void 0!==e));const d=new Set(o),u=t.filter((e=>!d.has(e.userId)));return c=c.concat(u),c},o1=e=>{const t={};return e.forEach((e=>t[e.userId]=e)),t},l1=6,c1=4,d1=t=>{var i,n;const r=null!==(i=t.spotlightedParticipantUserIds)&&void 0!==i?i:[],s=null!==(n=t.pinnedParticipantUserIds)&&void 0!==n?n:[],a=new Set(r.concat(s)),o=[...a].map((e=>t.remoteParticipants.find((t=>t.userId===e)))).filter((e=>void 0!==e)),l=t.remoteParticipants.filter((e=>!a.has(e.userId))),c=(0,e.useRef)([]),d=(0,e.useRef)([]),u=(e=>{const{remoteParticipants:t=[],dominantSpeakers:i=[],maxGridParticipants:n=c1,maxOverflowGalleryDominantSpeakers:r=l1,layout:s,previousGridParticipants:a=[],previousOverflowParticipants:o=[]}=e,l=t.filter((e=>"Connecting"===e.state||"Ringing"===e.state)),c=new Set(l.map((e=>e.userId))),d=t.filter((e=>!c.has(e.userId))),u=u1(d),h=t.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})),g="floatingLocalVideo"===s&&h.length>0?h:u;let p=a1({participants:g,dominantSpeakers:i,currentParticipants:a,maxDominantSpeakers:n}).slice(0,n);"speaker"===s&&(p=(null==i?void 0:i[0])?p.filter((e=>e.userId===i[0])):p.slice(1));const m=new Set(p.map((e=>e.userId)));let f=p,v=a1({participants:u.filter((e=>!m.has(e.userId))),dominantSpeakers:i,currentParticipants:o,maxDominantSpeakers:r});if(0===v.length){const e=n-f.length,t=l.slice(0,e),i=l.slice(e);f=f.concat(t),v=i}else v=v.concat(l);return{gridParticipants:f,overflowGalleryParticipants:v}})(Object.assign(Object.assign({},t),{maxGridParticipants:o.length>0||t.isScreenShareActive?0:t.maxGridParticipants,remoteParticipants:l,previousGridParticipants:c.current,previousOverflowParticipants:d.current}));return c.current=u.gridParticipants,d.current=u.overflowGalleryParticipants,o.length>0?{gridParticipants:t.isScreenShareActive?[]:o,overflowGalleryParticipants:t.isScreenShareActive?o.concat(u.overflowGalleryParticipants):u.overflowGalleryParticipants}:u},u1=e=>{const t=[],i=[];return e.forEach((e=>{var n;(null===(n=e.videoStream)||void 0===n?void 0:n.isAvailable)?t.push(e):i.push(e)})),t.concat(i)},h1=(e,t,i,n,r,s)=>{const a=null!=s?s:[];let o=i;const l=e.filter((e=>{var t;return null===(t=null==e?void 0:e.videoStream)||void 0===t?void 0:t.isAvailable})),c=a.filter((e=>l.find((t=>(null==t?void 0:t.userId)===e)))).slice(0,o);o-=c.length;const d=e.map((e=>{var i;return t(e,c.includes(e.userId)||(null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)&&o-- >0)})),u=n.map((e=>r.at(e))).filter((e=>{var t;return null===(t=null==e?void 0:e.videoStream)||void 0===t?void 0:t.isAvailable})),h=a.filter((e=>u.find((t=>(null==t?void 0:t.userId)===e)))).slice(0,o);o-=h.length;const g=r.map((e=>{var i;return t(e,h.includes(e.userId)||(null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)&&o-- >0)}));return{gridTiles:d,overflowGalleryTiles:g}},g1=(e,t)=>{var i,n,r,s,a;switch(e){case"like":return null===(i=t.likeReaction)||void 0===i?void 0:i.url;case"heart":return null===(n=t.heartReaction)||void 0===n?void 0:n.url;case"laugh":return null===(r=t.laughReaction)||void 0===r?void 0:r.url;case"applause":return null===(s=t.applauseReaction)||void 0===s?void 0:s.url;case"surprised":return null===(a=t.surprisedReaction)||void 0===a?void 0:a.url}},p1=(e,t)=>{var i,n,r,s,a,o,l,c,d,u;switch(e){case"like":return null!==(n=null===(i=t.likeReaction)||void 0===i?void 0:i.frameCount)&&void 0!==n?n:0;case"heart":return null!==(s=null===(r=t.heartReaction)||void 0===r?void 0:r.frameCount)&&void 0!==s?s:0;case"laugh":return null!==(o=null===(a=t.laughReaction)||void 0===a?void 0:a.frameCount)&&void 0!==o?o:0;case"applause":return null!==(c=null===(l=t.applauseReaction)||void 0===l?void 0:l.frameCount)&&void 0!==c?c:0;case"surprised":return null!==(u=null===(d=t.surprisedReaction)||void 0===d?void 0:d.frameCount)&&void 0!==u?u:0;default:return 0}},m1=e.memo((t=>{const{reaction:i,reactionResources:n,emojiSize:r=OX}=t,[s,a]=(0,e.useState)(!1),o=void 0!==i&&void 0!==n?g1(null==i?void 0:i.reactionType,n):void 0,l=void 0!==i&&void 0!==n?p1(null==i?void 0:i.reactionType,n):void 0,c=Date.now(),d=i?NX(i.receivedOn):void 0,u=!!d&&c-d<4133&&void 0!==o;(0,e.useEffect)((()=>{if(o&&0!==o.length)return fetch(`${o}`).then((e=>{a(e.ok)})).catch((e=>console.warn(`Sprite image for animation rendering failed with warning: ${e}`))),()=>a(!1)}),[o]);const h=null!=o?o:void 0,g=(0,e.useCallback)((()=>(e=>{var t;const i=`url(${e.spriteImageUrl})`,n=null!==(t=e.frameCount)&&void 0!==t?t:0,r=e.rawFrameSize;return dB({height:`${r}px`,width:`${r}px`,overflow:"hidden",animationName:YX(r,n),backgroundImage:i,animationDuration:"4.133s",animationTimingFunction:`steps(${n})`,animationPlayState:"running",animationIterationCount:"infinite",transform:`scale(${e.emojiSize/r})`,transformOrigin:"top left"})})({spriteImageUrl:null!=h?h:"",emojiSize:r,frameCount:null!=l?l:51,rawFrameSize:128})),[h,r,l]);return e.createElement(Y$,{className:dB(BX,{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:u?"rgba(0, 0, 0, 0.5)":"transparent",borderRadius:"0.25rem"})},e.createElement("div",{style:{height:"33.33%"}}),u&&s&&e.createElement("div",{style:{minHeight:`${r}px`,height:`${r}px`,width:`${r}px`}},e.createElement("div",{className:g()})))})),f1={bottom:"0",height:"50%",pointerEvents:"none",position:"absolute",width:"100%"},v1={sizeScale:.9,heightMaxScale:.7*.95,opacityMax:.9};function S1(){return v1}const y1=SB(((e,t)=>NB({"0%":{transform:`translateY(${e}px)`},"100%":{transform:`translateY(${t}px)`}}))),C1=(e,t)=>({animationName:y1(e,t),animationFillMode:"forwards",animationDuration:"4.133s",animationTimingFunction:"cubic-bezier(0, 0.83, 0.19, 1.09)"}),T1=SB((e=>NB({"0%":{opacity:0},"31.2%":{opacity:e},"67.2%":{opacity:e},"100%":{opacity:0,display:"none",visibility:"hidden"}}))),E1=SB(((e,t)=>NB({from:{backgroundPosition:"0px 0px"},to:{backgroundPosition:`0px -${e*t}px`}}))),b1=(e,t,i)=>({height:`${t}px`,width:`${t}px`,backgroundImage:`url(${i})`,backgroundRepeat:"no-repeat",animationName:E1(e,t),animationDuration:e/24+"s",animationFillMode:"forwards",animationIterationCount:"infinite",animationTimingFunction:`steps(${e})`,backgroundSize:`${t}px ${e*t}px`,transform:`scale(${t}/128)`}),_1=e.memo((t=>{const{reactionResources:i,localParticipant:n,remoteParticipants:r,hostDivHeight:s,hostDivWidth:a}=t,[o,l]=(0,e.useState)([]),c=(0,e.useRef)({}),d=(0,e.useRef)({like:0,heart:0,laugh:0,applause:0,surprised:0}),u=(0,e.useRef)(new Array(55).fill(!1)),h=(0,e.useMemo)((()=>{var e;return null!==(e=null==r?void 0:r.map((e=>e.reaction)).filter((e=>!!e)))&&void 0!==e?e:[]}),[r]),g=(0,e.useCallback)(((e,t)=>{var i,n;const r=((e,t,i)=>e+t+i.toISOString())(t,e.reactionType,e.receivedOn);if((null===(i=c.current[t])||void 0===i?void 0:i.id)===r)return;if((null!==(n=d.current[e.reactionType])&&void 0!==n?n:0)>=10)return void(c.current[t]={id:r,status:"ignored"});d.current[e.reactionType]+=1,c.current[t]={id:r,status:"animating"};const s=u.current.findIndex((e=>!1===e));u.current[s]=!0,l([...o,{reaction:e,id:r,reactionMovementIndex:s,styleBucket:S1()}])}),[d,o]),p=(e,t,i)=>{l(o.filter((e=>e.id!==t))),u.current[i]=!1,d.current[e]-=1,Object.entries(c.current).forEach((([e,i])=>{const n=c.current[e];i.id===t&&n&&(n.status="completedAnimating")}))};(0,e.useEffect)((()=>{(null==n?void 0:n.reaction)&&g(n.reaction,n.userId)}),[n,g]),(0,e.useEffect)((()=>{null==r||r.map((e=>{(null==e?void 0:e.reaction)&&g(e.reaction,e.userId)}))}),[h,r,g]);const m=()=>OX*S1().sizeScale,f=null!=s?s:0,v=(null!=a?a:0)-m();return e.createElement(Y$,{className:dB(BX,{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"transparent"})},o.map((t=>{var n,r,s,a;return e.createElement("div",{key:t.id,style:f1},e.createElement("div",{className:"reaction-item"},((e,t,i)=>{const n=Date.now()-NX(e.receivedOn)<4133;return n||p(null==e?void 0:e.reactionType,t,i),n})(t.reaction,t.id,t.reactionMovementIndex)&&e.createElement("div",{style:C1(f/2,f/2*(1-t.styleBucket.heightMaxScale))},e.createElement("div",{onAnimationEnd:()=>{p(t.reaction.reactionType,t.id,t.reactionMovementIndex)},style:(r=t.styleBucket.opacityMax,{animationName:T1(r),animationFillMode:"forwards",animationDuration:"4.133s"})},e.createElement("div",{style:(s=t.reactionMovementIndex,a=(e=>function(e,t,i=!0){const n=i?t:0,r=0===e?0:e%2*2-1;if(0===r)return n;const s=function(e){switch(e){case 1:case 2:return.3;case 3:case 4:return.6;case 5:case 6:return.9;case 7:case 8:return.75;case 9:case 18:return.375;case 10:case 23:return.525;case 11:case 16:return.15;case 12:case 15:return.225;case 13:case 14:return.075;case 17:case 24:return.45;case 19:case 20:return.675;case 21:case 22:return.825;default:return 0}}(e);return n+r*s*t}(e,v/2,!0))(s),{position:"absolute",left:`${a}px`})},e.createElement("div",{style:b1(51,m(),null!==(n=g1(null==t?void 0:t.reaction.reactionType,i))&&void 0!==n?n:"")}))))))})))}));function I1(e){return{width:vJ(e.width),height:vJ(e.height),left:vJ(e.left),top:vJ(e.top)}}function w1(e){return{seatPosition:I1(e)}}const A1={width:"100%",height:"100%",position:"absolute",top:"0",left:"0"},P1={root:{width:"100%",height:"100%",display:"flex",justifyContent:"center",alignItems:"center",position:"absolute",top:0,left:0}},R1=()=>({width:vJ(20),flexShrink:0}),M1=(e,t)=>({backgroundColor:e,display:"flex",justifyContent:"center",alignItems:"center",gap:vJ(2),margin:"0 auto",padding:`0 ${vJ(5)}`,borderRadius:t,width:"fit-content"}),D1=(e,t,i)=>({width:`${e}`,position:"absolute",left:(100-t/(16*parseFloat(i))*100)/2+"%"}),k1={position:"absolute",bottom:`${vJ(2)}`,width:"fit-content",textAlign:"center",transform:"translate(-50%)",transition:"width 0.3s ease, transform 0.3s ease",left:"50%"},O1=(0,e.memo)((t=>{const i=AK(),n=aJ(),r=n.callingPalette,{emojiSize:s,reactionResources:a,remoteParticipants:o,localParticipant:l,togetherModeSeatPositions:c}=t,[d,u]=(0,e.useState)({}),[h,g]=(0,e.useState)(""),p=(0,e.useMemo)((()=>{const e=[...o,l].filter((e=>{var t;return(null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable)&&c[e.userId]})),t={};for(const s of e){const{userId:e,reaction:o,raisedHand:l,spotlight:d,isMuted:u,displayName:g}=s,p=c[e];p&&(t[e]={id:e,reaction:a&&o,isHandRaised:!!l,isSpotlighted:!!d,isMuted:u,displayName:g||i.strings.videoGallery.displayNamePlaceholder,showDisplayName:!(!d&&!l&&h!==e),scaledSize:(n=p.width,r=p.height,35+35*(Math.min(n,r)-200)/400),seatPositionStyle:w1(p)})}var n,r;const s=Object.keys(d).filter((e=>!t[e])),u=Object.assign(Object.assign({},d),t);return s.forEach((e=>{delete u[e]})),Object.keys(u).some((e=>JSON.stringify(u[e])!==JSON.stringify(d[e])))||Object.keys(u).length!==Object.keys(d).length?u:d}),[o,l,d,c,a,i.strings.videoGallery.displayNamePlaceholder,h]);return(0,e.useEffect)((()=>{h&&!p[h]&&g(""),u(p)}),[h,p]),e.createElement("div",{style:{position:"absolute",width:"100%",height:"100%"}},Object.values(d).map((t=>{var i,o,l,c,d,u;return t.id&&e.createElement("div",{key:t.id,"data-ui-id":`together-mode-participant-${t.id}`,style:Object.assign({},(u=t.seatPositionStyle,Object.assign(Object.assign({},u.seatPosition),{position:"absolute"}))),onMouseEnter:()=>g(t.id),onMouseLeave:()=>g("")},e.createElement("div",null,t.showDisplayName&&e.createElement("div",{style:Object.assign({},k1)},e.createElement("div",{style:Object.assign({},M1(r.videoTileLabelBackgroundLight,n.effects.roundedCorner4))},t.isHandRaised&&e.createElement(kX,null),t.showDisplayName&&e.createElement(oJ,{style:Object.assign({},(l=h===t.id,c=parseFloat(t.seatPositionStyle.seatPosition.width),d=t.displayName?n.palette.neutralSecondary:"inherit",{textOverflow:"ellipsis",whiteSpace:"nowrap",textAlign:"center",color:d,overflow:l?"visible":"hidden",width:l||16*c>150?"fit-content":vJ(.7*c*16),display:l||16*c>150?"inline-block":"none",fontSize:`${vJ(13)}`,lineHeight:`${vJ(20)}`,maxWidth:l?"fit-content":vJ(.7*c*16)}))},t.displayName),t.isMuted&&e.createElement(Y$,{className:dB(R1)},e.createElement(mG,{iconName:"VideoTileMicOff"})),t.isSpotlighted&&e.createElement(Y$,{className:dB(R1)},e.createElement(mG,{iconName:"VideoTileSpotlighted"})))),(null===(i=t.reaction)||void 0===i?void 0:i.reactionType)&&e.createElement("div",{style:C1(8*parseFloat(t.seatPositionStyle.seatPosition.height),5.6*parseFloat(t.seatPositionStyle.seatPosition.height))},e.createElement("div",{"data-ui-id":`together-mode-participant-reaction-${t.id}`,style:Object.assign({},D1(s,t.scaledSize||1,t.seatPositionStyle.seatPosition.width))},e.createElement("div",{style:b1(51,t.scaledSize||1,null!==(o=t.reaction&&g1(null==t?void 0:t.reaction.reactionType,a))&&void 0!==o?o:"")})))))})))})),N1=t=>{const{overlayMode:i,reaction:n,reactionResources:r,localParticipant:s,remoteParticipants:a,togetherModeSeatPositions:o}=t,[l,c]=(0,e.useState)(0),[d,u]=(0,e.useState)(0),[h,g]=(0,e.useState)(0),p=(0,e.useRef)(null),m=(0,e.useRef)(new ResizeObserver((e=>{var t;const i=null===(t=e.at(0))||void 0===t?void 0:t.contentRect,n=void 0!==i?i.width:0,r=void 0!==i?i.height:0,s=Math.min(n,r)/3;s!==l&&c(Math.max(Math.min(s,70),32)),r!==d&&u(r),n!==h&&g(n)})));return(0,e.useLayoutEffect)((()=>{p.current&&m.current.observe(p.current);const e=m.current;return()=>e.disconnect()}),[p]),"grid-tiles"===i?e.createElement("div",{ref:p,style:{width:"100%",height:"100%",pointerEvents:"none"}},e.createElement(m1,{emojiSize:l,reaction:n,reactionResources:r})):"screen-share"===t.overlayMode||"content-share"===t.overlayMode?e.createElement("div",{ref:p,style:{width:"100%",height:"100%",pointerEvents:"none"}},e.createElement(_1,{hostDivHeight:d,hostDivWidth:h,reactionResources:r,localParticipant:s,remoteParticipants:a})):"together-mode"===t.overlayMode?e.createElement("div",{style:Object.assign({},A1)},e.createElement(O1,{emojiSize:l,reactionResources:r,localParticipant:null!=s?s:{},remoteParticipants:null!=a?a:[],togetherModeSeatPositions:null!=o?o:{}})):e.createElement(e.Fragment,null)},L1=e.memo((t=>{var i,n;const{isAvailable:r,isReceiving:s=!0,isScreenSharingOn:a,onCreateRemoteStreamView:o,onDisposeRemoteStreamView:l,remoteVideoViewOptions:c,renderElement:d,userId:u,onRenderAvatar:h,showMuteIndicator:g,remoteParticipant:p,participantState:m,menuKind:f,isPinned:v,onPinParticipant:S,onUnpinParticipant:y,spotlightedParticipantUserIds:C,isSpotlighted:T,onStartSpotlight:E,onStopSpotlight:b,maxParticipantsToSpotlight:_,onMuteParticipant:I,onUpdateScalingMode:w,disablePinMenuItem:A,toggleAnnouncerString:P,strings:R,reactionResources:M,streamId:D,onForbidAudio:k,onPermitAudio:O,onForbidVideo:N,onPermitVideo:L}=t,x=(t=>{const{remoteParticipantId:i,onCreateRemoteStreamView:n,onDisposeRemoteStreamView:r}=t,s=(0,e.useMemo)((()=>e=>null==n?void 0:n(i,e)),[n,i]),a=(0,e.useMemo)((()=>()=>{null==r||r(i)}),[r,i]);return r1(Object.assign(Object.assign({},t),{onCreateStreamView:s,onDisposeStreamView:a}))})((0,e.useMemo)((()=>({isMirrored:null==c?void 0:c.isMirrored,isScreenSharingOn:a,isStreamAvailable:r,isStreamReceiving:s,onCreateRemoteStreamView:o,onDisposeRemoteStreamView:l,remoteParticipantId:u,renderElementExists:!!d,scalingMode:null==c?void 0:c.scalingMode,streamId:D,isVideoPermitted:!p.mediaAccess||p.mediaAccess.isVideoPermitted})),[r,s,a,o,l,null==c?void 0:c.isMirrored,null==c?void 0:c.scalingMode,d,u,D,p.mediaAccess])),F=s1({participant:p,view:null==x?void 0:x.view,strings:Object.assign({},t.strings),isPinned:v,onPinParticipant:S,onUnpinParticipant:y,onUpdateScalingMode:w,disablePinMenuItem:A,toggleAnnouncerString:P,spotlightedParticipantUserIds:C,isSpotlighted:T,onStartSpotlight:E,onStopSpotlight:b,maxParticipantsToSpotlight:_,onMuteParticipant:I,onForbidAudio:k,onPermitAudio:O,onForbidVideo:N,onPermitVideo:L}),U=(0,e.useMemo)((()=>"contextual"===f&&F?{contextualMenu:F}:{}),[F,f]),B=r&&!1===s&&"Disconnected"!==m,V="Reconnecting"===m,[H,$]=e.useState([]),j=(0,e.useMemo)((()=>{if(d&&d.childElementCount||V)return e.createElement(e1,{videoStreamElement:null!=d?d:null,loadingState:B?"loading":V?"reconnecting":"none"})}),[V,d,B]),G=(0,e.useCallback)((e=>{"Enter"===e.key&&$(x1(F,(()=>$([]))))}),[$,F]),q=null===(i=t.strings)||void 0===i?void 0:i.attendeeRole,z=((e,t)=>e&&t?PK(e,{AttendeeRole:t}):e)(p.displayName?p.displayName:R.displayNamePlaceholder,q),W=M&&e.createElement(N1,{overlayMode:"grid-tiles",reaction:p.reaction,reactionResources:M});return e.createElement(Y$,{tabIndex:"drawer"===f?0:void 0,onKeyDown:"drawer"===f?G:void 0,style:t1},e.createElement(o0,Object.assign({key:u,userId:u,initialsName:null!==(n=p.displayName&&q?PK(p.displayName,{AttendeeRole:q}):p.displayName)&&void 0!==n?n:"",renderElement:j,displayName:z,onRenderPlaceholder:h,isMuted:p.isMuted,raisedHand:p.raisedHand,isSpeaking:p.isSpeaking,showMuteIndicator:g,personaMinSize:t.personaMinSize,showLabel:t.showLabel,alwaysShowLabelBackground:t.alwaysShowLabelBackground,participantState:m},U,{isPinned:t.isPinned,onLongTouch:t.onLongTouch?t.onLongTouch:()=>$(x1(F,(()=>$([])))),isSpotlighted:T,overlay:W,mediaAccess:p.mediaAccess})),H.length>0&&e.createElement(Hz,{hostId:t.drawerMenuHostId},e.createElement(Y$,{styles:i1},e.createElement(K0,{onLightDismiss:()=>$([]),items:H,heading:z}))))})),x1=(e,t)=>e?e.items.map((e=>({itemKey:e.key,text:e.text,iconProps:e.iconProps,disabled:e.disabled,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),null==t||t()}}))):[],F1=dB({height:"100%",width:"100%"}),U1={label:{maxWidth:"10rem",overflow:"hidden",textOverflow:"ellipsis"}},B1=e.memo((t=>{const{userId:i,displayName:n,isMuted:r,renderElement:s,onCreateRemoteStreamView:a,onDisposeRemoteStreamView:o,isReceiving:l,participantVideoScalingMode:c,reactionResources:d,localParticipant:u,remoteParticipants:h}=t,g=AK();s||a&&a(i,c),(0,e.useEffect)((()=>()=>{o&&o(i)}),[o,i]);const p=n?PK(g.strings.videoGallery.screenShareLoadingMessage,{participant:n}):"";return e.createElement(o0,{displayName:n,isMuted:r,renderElement:s?e.createElement(e1,{videoStreamElement:s,loadingState:!1===l?"loading":"none"}):void 0,onRenderPlaceholder:()=>e.createElement(V1,{loadingMessage:p}),overlay:d&&e.createElement(N1,{reactionResources:d,localParticipant:u,remoteParticipants:h,overlayMode:"screen-share"})})})),V1=t=>e.createElement(Y$,{verticalAlign:"center",className:F1},e.createElement(yZ,{styles:U1,label:t.loadingMessage,size:gZ.xSmall,"aria-live":"assertive"})),H1=dB({width:"100%",height:"100%"}),$1=e=>dB({backgroundColor:"inherit",padding:"1rem",maxWidth:"95%",borderRadius:e.effects.roundedCorner4,color:e.palette.neutralSecondary}),j1=dB({height:"2rem",lineHeight:0}),G1=e=>dB({transform:"scale(2.5)",color:e.palette.neutralTertiary}),q1=dB({fontSize:"1rem",color:"inherit"}),z1=e.memo((t=>{const{localParticipant:i,renderElement:n,isAvailable:r,onCreateLocalStreamView:s,onDisposeLocalScreenShareStreamView:a,localScreenShareView:o="stream"}=t,l=AK(),c=aJ();if(n||"stream"!==o||s&&s(),(0,e.useEffect)((()=>()=>{a&&a()}),[a]),!i||!i.isScreenSharingOn)return null;const d=e.createElement(Y$,{horizontalAlign:"center",verticalAlign:"center",className:H1},e.createElement(Y$,{horizontalAlign:"center",verticalAlign:"center",className:$1(c),tokens:{childrenGap:"1rem"}},e.createElement(Y$,{horizontal:!0,verticalAlign:"center",className:j1},e.createElement(mG,{iconName:"ControlButtonScreenShareStart",className:G1(c)})),e.createElement(oJ,{className:q1,"aria-live":"polite"},l.strings.videoGallery.screenIsBeingSharedMessage))),u=(null==i?void 0:i.displayName)?null==i?void 0:i.displayName:l.strings.videoGallery.displayNamePlaceholder,h=l.strings.videoGallery.localScreenShareLoadingMessage;return"placeholderMessage"===o?e.createElement(o0,{displayName:u,isMuted:null==i?void 0:i.isMuted,onRenderPlaceholder:()=>e.createElement(e.Fragment,null)},d):e.createElement(o0,{displayName:u,isMuted:null==i?void 0:i.isMuted,renderElement:n?e.createElement(e1,{videoStreamElement:n,loadingState:!1===r?"loading":"none"}):void 0,onRenderPlaceholder:()=>e.createElement(V1,{loadingMessage:h}),mediaAccess:i.mediaAccess})})),W1=dB({position:"relative",width:"100%",height:"100%"}),K1=(e,t)=>({root:{position:"absolute",width:vJ("large"===t?40:32),height:vJ("large"===t?40:32),right:"0rem",top:"0rem",color:"#FFFFFF",zIndex:2,background:"rgba(0,0,0,0.4)",borderRadius:e.effects.roundedCorner2},rootFocused:{color:"#FFFFFF",background:"rgba(0,0,0,0.4)"},rootDisabled:{position:"absolute"},icon:{paddingLeft:vJ(3),paddingRight:vJ(3),margin:0},flexContainer:{paddingBottom:vJ(8),height:"unset"}}),J1={root:{width:"100%",height:"100%"}};const Y1=t=>{const{cameras:i,selectedCamera:n,onSelectCamera:r,label:s,ariaDescription:a,size:o}=t,l=qK(),[c,d]=(0,e.useState)(!1),u=(0,e.useCallback)((e=>{return t=void 0,i=void 0,s=function*(){if(r){d(!0);try{yield r(e)}finally{d(!1)}}},new((n=void 0)||(n=Promise))((function(e,r){function a(e){try{l(s.next(e))}catch(e){r(e)}}function o(e){try{l(s.throw(e))}catch(e){r(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(a,o)}l((s=s.apply(t,i||[])).next())}));var t,i,n,s}),[r]),h=!!c,g=AK().strings.cameraButton.tooltipVideoLoadingContent;return e.createElement(oK,{"data-ui-id":"local-camera-switcher-button",styles:K1(l,o),disabled:h,iconProps:{iconName:"LocalCameraSwitch"},ariaLabel:s,ariaDescription:h?g:a,"aria-live":"polite",onClick:()=>{if(i&&i.length>1&&void 0!==n){const e=i.findIndex((e=>n.id===e.id)),t=i[(e+1)%i.length];if(!t)throw new Error("Camera not found");u(t)}}})},Q1=e.memo((t=>{const{isAvailable:i,isMuted:n,onCreateLocalStreamView:r,onDisposeLocalStreamView:s,localVideoViewOptions:a,renderElement:o,userId:l,showLabel:c,alwaysShowLabelBackground:d,displayName:u,initialsName:h,onRenderAvatar:g,showMuteIndicator:p,styles:m,showCameraSwitcherInLocalPreview:f,localVideoCameraCycleButtonProps:v,localVideoCameraSwitcherLabel:S,localVideoSelectedDescription:y,raisedHand:C,reaction:T,isSpotlighted:E,spotlightedParticipantUserIds:b,onStartSpotlight:_,onStopSpotlight:I,maxParticipantsToSpotlight:w,menuKind:A,strings:P,reactionResources:R,isScreenSharingOn:M,mediaAccess:D}=t,k=aJ();(t=>{const{onCreateLocalStreamView:i,onDisposeLocalStreamView:n}=t,r=(0,e.useMemo)((()=>e=>null==i?void 0:i(e)),[i]),s=(0,e.useMemo)((()=>()=>{null==n||n()}),[n]);r1(Object.assign(Object.assign({},t),{onCreateStreamView:r,onDisposeStreamView:s}))})((0,e.useMemo)((()=>({isMirrored:null==a?void 0:a.isMirrored,isStreamAvailable:i,onCreateLocalStreamView:r,onDisposeLocalStreamView:s,renderElementExists:!!o,scalingMode:null==a?void 0:a.scalingMode,isVideoPermitted:!D||D.isVideoPermitted})),[i,null==a?void 0:a.isMirrored,null==a?void 0:a.scalingMode,r,s,o,D]));const O=s1({participant:{userId:null!=l?l:""},strings:Object.assign({},P),spotlightedParticipantUserIds:b,isSpotlighted:E,onStartSpotlight:_,onStopSpotlight:I,maxParticipantsToSpotlight:w,myUserId:l}),N=(0,e.useMemo)((()=>"contextual"===A&&O?{contextualMenu:O}:{}),[O,A]),L=(0,e.useMemo)((()=>E?ZH({root:{outline:`0.25rem solid ${k.palette.neutralTertiaryAlt}`,outlineOffset:"-0.25rem"}},m):m),[E,k.palette.neutralTertiaryAlt,m]),[x,F]=e.useState([]),U=(0,e.useCallback)((e=>{"Enter"===e.key&&F(X1(O,(()=>F([]))))}),[F,O]),B=(0,e.useMemo)((()=>{if(o&&o.childElementCount)return e.createElement(e.Fragment,null,e.createElement(Z1,{showCameraSwitcherInLocalPreview:null!=f&&f,localVideoCameraCycleButtonProps:v,localVideoCameraSwitcherLabel:S,localVideoSelectedDescription:y}),e.createElement(e1,{videoStreamElement:o,isMirrored:!0}),1===t.participantsCount&&!M&&e.createElement(Y$,{className:dB(BX,{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"rgba(0, 0, 0, 0.3)"})},e.createElement(yZ,{label:null==P?void 0:P.waitingScreenText,ariaLive:"assertive",role:"alert",labelPosition:"bottom",styles:QX(k,!0)})))}),[v,S,y,o,f,t.participantsCount,null==P?void 0:P.waitingScreenText,k,M]),V=(0,e.useMemo)((()=>void 0!==R?e.createElement(N1,{overlayMode:"grid-tiles",reaction:T,reactionResources:R}):void 0),[T,R]),H=(0,e.useCallback)((()=>e.createElement(Y$,{className:dB(BX,{display:"flex",justifyContent:"center",alignItems:"center"})},e.createElement(yZ,{label:null==P?void 0:P.waitingScreenText,ariaLive:"assertive",labelPosition:"bottom",role:"alert",styles:QX(k,!1)}))),[null==P?void 0:P.waitingScreenText,k]);return e.createElement(Y$,{"data-ui-id":"local-video-tile",className:dB({width:"100%",height:"100%"}),onKeyDown:"drawer"===A?U:void 0},e.createElement(o0,Object.assign({key:null!=l?l:"local-video-tile",userId:l,renderElement:B,showLabel:c,alwaysShowLabelBackground:d,displayName:u,initialsName:h,styles:L,onRenderPlaceholder:1!==t.participantsCount||M?g:H,isMuted:n,showMuteIndicator:p,personaMinSize:t.personaMinSize,raisedHand:C,isSpotlighted:E},N,{onLongTouch:()=>F(X1(O,(()=>F([])))),overlay:V,mediaAccess:D}),x.length>0&&e.createElement(Hz,{hostId:t.drawerMenuHostId},e.createElement(Y$,{styles:i1},e.createElement(K0,{onLightDismiss:()=>F([]),items:x})))))})),Z1=t=>{const{showCameraSwitcherInLocalPreview:i,localVideoCameraCycleButtonProps:n,localVideoCameraSwitcherLabel:r,localVideoSelectedDescription:s}=t,a=(null==n?void 0:n.selectedCamera)&&s&&PK(s,{cameraName:n.selectedCamera.name});return e.createElement(Y$,{horizontalAlign:"end"},i&&void 0!==(null==n?void 0:n.cameras)&&void 0!==(null==n?void 0:n.selectedCamera)&&void 0!==(null==n?void 0:n.onSelectCamera)&&e.createElement(Y1,{cameras:n.cameras,selectedCamera:n.selectedCamera,onSelectCamera:n.onSelectCamera,label:r,ariaDescription:a}))},X1=(e,t)=>e?e.items.map((e=>({itemKey:e.key,text:e.text,iconProps:e.iconProps,disabled:e.disabled,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),null==t||t()}}))):[],e2=dB({width:"100%",height:"100%",display:"grid",gridGap:"0.5rem"}),t2=t=>{const{children:i,styles:n}=t,r=e.Children.count(i),[s,a]=(0,e.useState)(0),[o,l]=(0,e.useState)(0),c=(0,e.useRef)(null),d=(0,e.useRef)(new ResizeObserver((e=>{if(!e[0])return;const{width:t,height:i}=e[0].contentRect;a(t),l(i)})));(0,e.useEffect)((()=>{c.current&&d.current.observe(c.current);const e=d.current;return()=>e.disconnect()}),[d,c]);const u=(0,e.useMemo)((()=>r2(r,s,o)),[r,s,o]),h=(0,e.useMemo)((()=>s2(r,u)),[r,u]);return e.createElement("div",{ref:c,className:dB(e2,h,null==n?void 0:n.root),"data-ui-id":"grid-layout"},i)},i2=16/9,n2=8/9,r2=(e,t,i)=>{if(e<=0)return{fillDirection:"horizontal",rows:0,columns:0};if(t<=0||i<=0)return{fillDirection:"horizontal",rows:Math.ceil(Math.sqrt(e)),columns:Math.ceil(Math.sqrt(e))};const n=t/i;let r=Math.floor(Math.sqrt(i2/n*e))||1;r=Math.min(r,e);let s=Math.ceil(e/r),a="horizontal";for(;r<e;){if(!(r/s*n<n2)){if(e<r*s){const t=e>=r+(s-1)*(r-1),i=e>=s+(r-1)*(s-1);if(!t&&!i){r+=1,s=Math.ceil(e/r);continue}if(!t)break;if(!i){a="vertical";break}const d=(r-1)/s*n;d>=n2&&(o=d,l=r/(s-1)*n,c=i2,Math.abs(c-o)<Math.abs(c-l)&&(a="vertical"))}break}r+=1,s=Math.ceil(e/r)}var o,l,c;return{fillDirection:a,rows:r,columns:s}},s2=(e,t)=>{const i="horizontal"===t.fillDirection,n=i?t.rows:t.columns,r=Math.ceil(e/n),s=Math.floor(e/n),a=(t.rows*t.columns-e)*s,o=r*s;return dB(i?{gridTemplateColumns:`repeat(${o}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${n}, minmax(0, 1fr))`,gridAutoFlow:"row"}:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${o}, minmax(0, 1fr))`,gridAutoFlow:"column"},i?{"> *":{gridColumn:"auto / span "+o/r}}:{"> *":{gridRow:"auto / span "+o/r}},a?{[`> *:nth-last-child(-n + ${a})`]:i?{gridColumn:"auto / span "+o/s}:{gridRow:"auto / span "+o/s}}:{})},a2={root:{position:"relative",height:"100%",width:"100%",padding:"0.5rem"}},o2={childrenGap:"0.5rem"},l2=e=>({background:"none",padding:0,height:"auto",minWidth:"1.75rem",maxWidth:"1.75rem",border:`1px solid ${e.palette.neutralLight}`,borderRadius:e.effects.roundedCorner4}),c2={height:"100%",width:"100%",gap:"0.5rem"},d2={height:"100%",width:"100%",gap:"0.5rem"};function u2(e,t){const i=[];if(t<=0)return i;for(let n=0;n<e.length;n+=t)i.push(e.slice(n,n+t));return i}const h2=5,g2=t=>{var i;const{children:n,childrenPerPage:r=h2,styles:s,onFetchTilesToRender:a}=t,o=DX(),[l,c]=(0,e.useState)(0),d=e.Children.count(n),u=Math.ceil(d/r)-1,h=(0,e.useMemo)((()=>u2([...Array(d).keys()],r)),[d,r]);(0,e.useEffect)((()=>{var e;a&&h&&a(null!==(e=h[l])&&void 0!==e?e:[])}),[h,a,l]);const g=l*r<d-1?l:u,p=(0,e.useMemo)((()=>{const t=null==h?void 0:h[g];return t?t.map((t=>e.Children.toArray(n)[t])):[]}),[h,g,n]),m=d>r,f=0===l,v=l===u,S=(0,e.useMemo)((()=>({root:null==s?void 0:s.children})),[null==s?void 0:s.children]);return r<=0?e.createElement(e.Fragment,null):e.createElement(Y$,{horizontal:!0,className:dB(c2,null===(i=t.styles)||void 0===i?void 0:i.root)},m&&e.createElement(p2,{key:"previous-nav-button",icon:e.createElement(mG,{iconName:"HorizontalGalleryLeftButton"}),styles:null==s?void 0:s.previousButton,onClick:()=>c(Math.max(0,Math.min(u,l-1))),disabled:f,identifier:o.overflowGalleryLeftNavButton}),e.createElement(Y$,{horizontal:!0,className:dB(d2)},p.map(((t,i)=>e.createElement(Y$.Item,{styles:S,key:i,"data-ui-id":o.horizontalGalleryVideoTile},t)))),m&&e.createElement(p2,{key:"next-nav-button",icon:e.createElement(mG,{iconName:"HorizontalGalleryRightButton"}),styles:null==s?void 0:s.nextButton,onClick:()=>c(Math.min(u,l+1)),disabled:v,identifier:o.overflowGalleryRightNavButton}))},p2=t=>{const i=aJ();return e.createElement(pJ,{className:dB(l2(i),t.styles),onClick:t.onClick,disabled:t.disabled,"data-ui-id":t.identifier},t.icon)},m2=(dB({position:"relative",width:"100%",height:"100%"}),{width:3.625,height:6.5}),f2={width:13.75,height:7.5},v2={width:9,height:5.063},S2={width:11,height:6.25},y2=(e,t,i,n)=>({width:i?`${t.width}rem`:"",height:i?`${t.height}rem`:"",minWidth:i?"":`${t.width}rem`,minHeight:i?"":`${t.height}rem`,position:"absolute",bottom:"horizontalTop"!==n?`${T2}rem`:"unset",top:"horizontalTop"===n?`${T2}rem`:"unset",borderRadius:e.effects.roundedCorner4,overflow:"hidden",right:`${T2}rem`}),C2=(e,t)=>ZH(y2(e,t),{root:{boxShadow:e.effects.elevation8}}),T2=.5,E2={root:{position:"absolute",zIndex:2,height:"100%",width:"100%"}},b2={keyboardMoveIconContainer:{zIndex:3}},_2=6.5,I2=6.5,w2=7.5,A2=7.5,P2={minHeight:`${_2}rem`,minWidth:`${I2}rem`,maxHeight:`${_2}rem`,maxWidth:`${I2}rem`},R2={minHeight:`${w2}rem`,minWidth:`${A2}rem`,maxHeight:`${w2}rem`,maxWidth:`${13.43}rem`,width:"100%",height:"100%"},M2={minHeight:"5.625rem",minWidth:"9rem",maxHeight:"9rem",maxWidth:"9rem",width:"100%",height:"100%"},D2={minHeight:"6.75rem",minWidth:"11rem",maxHeight:"11rem",maxWidth:"11rem",width:"100%",height:"100%"},k2=t=>{const{gapWidthRem:i,buttonWidthRem:n=0,onFetchTilesToRender:r,onChildrenPerPageChange:s}=t,a=(0,e.useRef)(null),o=y0(a),l=a.current?parseFloat(getComputedStyle(a.current).paddingLeft):0,c=a.current?parseFloat(getComputedStyle(a.current).paddingRight):0;let d=Math.max((null!=o?o:0)-l-c,0);Number.isNaN(d)&&(d=0);const u=(e=>{const{numberOfChildren:t,containerWidth:i,buttonWidthRem:n,gapWidthRem:r}=e,s=p0(A2),a=p0(r),o=Math.floor((i+a)/(s+a));if(t<=o)return o;const l=i-2*p0(n)-2*a;return Math.max(Math.floor((l+a)/(s+a)),1)})({numberOfChildren:e.Children.count(t.children),containerWidth:d,gapWidthRem:i,buttonWidthRem:n});return null==s||s(u),e.createElement("div",{"data-ui-id":"responsive-horizontal-gallery",ref:a,className:dB(t.containerStyles)},e.createElement(g2,{childrenPerPage:u,styles:t.horizontalGalleryStyles,onFetchTilesToRender:r},t.children))},O2={height:"100%",width:"inherit",gap:"0.5rem",position:"relative"},N2={height:"2rem",width:"100%",position:"absolute",bottom:"0"},L2=e=>({background:"none",padding:0,height:"auto",borderRadius:e.effects.roundedCorner4,border:"none",minWidth:"2rem"}),x2={lineHeight:"2rem",width:"100%",textAlign:"center"},F2={root:{lineHeight:"0"}},U2=t=>{const{children:i,styles:n,childrenPerPage:r,onFetchTilesToRender:s}=t,[a,o]=(0,e.useState)(1),[l,c]=(0,e.useState)({previous:!0,next:!0}),d=DX(),u=e.Children.count(i),h=Math.ceil(u/r),g=(0,e.useMemo)((()=>u2([...Array(u).keys()],r)),[u,r]);(0,e.useEffect)((()=>{var e;s&&g&&s(null!==(e=g[a-1])&&void 0!==e?e:[])}),[g,s,a]);const p=(a-1)*r<u-1?a:h,m=(0,e.useMemo)((()=>{var t;if(void 0!==g[0])return null===(t=g[p-1])||void 0===t?void 0:t.map((t=>e.Children.toArray(i)[t]))}),[g,p,i]),f=u>r;a>h&&h>0&&o(h),(0,e.useEffect)((()=>{a>1&&a<h&&f?c({previous:!1,next:!1}):1===a&&f?c({previous:!0,next:!1}):a===h&&f&&c({previous:!1,next:!0})}),[a,u,h,f]);const v=(0,e.useMemo)((()=>({root:{width:"100%",height:"calc(100% - 2.5rem)",gap:"0.5rem"}})),[]),S=(0,e.useMemo)((()=>({root:null==n?void 0:n.children})),[null==n?void 0:n.children]);return r<=0?e.createElement(e.Fragment,null):e.createElement(Y$,{className:dB(O2,null==n?void 0:n.root)},e.createElement(Y$,{styles:v},null==m?void 0:m.map(((t,i)=>e.createElement(Y$.Item,{key:i,styles:S,"data-ui-id":d.verticalGalleryVideoTile},t)))),f&&e.createElement(B2,{buttonsDisabled:l,onPreviousButtonClick:()=>{o(a-1)},onNextButtonClick:()=>{o(a+1)},totalPages:h,currentPage:a}))},B2=t=>{const{onNextButtonClick:i,onPreviousButtonClick:n,buttonsDisabled:r,currentPage:s,totalPages:a,styles:o}=t,l=aJ(),c=DX(),d=AK().strings.verticalGallery,u=(0,e.useMemo)((()=>dB(N2,null==o?void 0:o.root)),[null==o?void 0:o.root]),h=(0,e.useMemo)((()=>dB(L2(l),null==o?void 0:o.previousButton)),[null==o?void 0:o.previousButton,l]),g=(0,e.useMemo)((()=>dB(x2,null==o?void 0:o.counter)),[null==o?void 0:o.counter]),p=(0,e.useMemo)((()=>dB(L2(l),null==o?void 0:o.nextButton)),[null==o?void 0:o.nextButton,l]),m=d.leftNavButtonAriaLabel?PK(d.leftNavButtonAriaLabel,{current:`${s}`,total:`${a}`}):void 0,f=d.rightNavButtonAriaLabel?PK(d.rightNavButtonAriaLabel,{current:`${s}`,total:`${a}`}):void 0;return e.createElement(Y$,{horizontalAlign:"center",tokens:{childrenGap:"0.5rem"},horizontal:!0,className:u},e.createElement(pJ,{className:h,onClick:n,disabled:null==r?void 0:r.previous,ariaLabel:m,"data-ui-id":c.overflowGalleryLeftNavButton},e.createElement(mG,{iconName:"VerticalGalleryLeftButton",styles:F2})),e.createElement(oJ,{"data-ui-id":c.verticalGalleryPageCounter,className:g},`${s} / ${a}`),e.createElement(pJ,{className:p,onClick:i,disabled:null==r?void 0:r.next,ariaLabel:f,"data-ui-id":c.overflowGalleryRightNavButton},e.createElement(mG,{iconName:"VerticalGalleryRightButton",styles:F2})))},V2=t=>{var i;const{children:n,containerStyles:r,verticalGalleryStyles:s,gapHeightRem:a,controlBarHeightRem:o,isShort:l,onFetchTilesToRender:c,onChildrenPerPageChange:d}=t,u=(0,e.useRef)(null),h=C0(u),g=u.current?parseFloat(getComputedStyle(u.current).paddingTop):0,p=u.current?parseFloat(getComputedStyle(u.current).paddingBottom):0;let m=Math.max((null!=h?h:0)-g-p,0);Number.isNaN(m)&&(m=0);const f=(e=>{const{numberOfChildren:t,containerHeight:i,gapHeightRem:n,controlBarHeight:r,isShort:s}=e,a=p0(s?5.625:6.75),o=p0(n),l=p0(r),c=Math.floor((i+o)/(a+o));if(t<=c)return c;const d=i-l-2*o;return Math.max(Math.floor((d+o)/(a+o)),1)})({numberOfChildren:null!==(i=e.Children.count(n))&&void 0!==i?i:0,containerHeight:m,gapHeightRem:a,controlBarHeight:null!=o?o:2,isShort:null!=l&&l});return null==d||d(f),e.createElement("div",{"data-ui-id":"responsive-vertical-gallery",ref:u,className:dB(r)},e.createElement(U2,{childrenPerPage:f,styles:s,onFetchTilesToRender:c},n))};var H2="undefined"!=typeof window?e.useLayoutEffect:e.useEffect;const $2={root:{width:"100%",minHeight:`${_2}rem`,paddingRight:"0.5rem","> *":P2}},j2={display:"flex",minHeight:`${_2}rem`,overflow:"scroll","-ms-overflow-style":"none","scrollbar-width":"none","::-webkit-scrollbar":{display:"none"}},G2=t=>{const{horizontalGalleryElements:i,onFetchTilesToRender:n,containerStyles:r}=t;(0,e.useEffect)((()=>{const e=[...Array(null==i?void 0:i.length).keys()];n&&e&&n(null!=e?e:[])}),[n,null==i?void 0:i.length]);const s=(0,e.useRef)(),{events:a}=function(t,i){var n,r,s,a,o=void 0===i?{}:i,l=o.decayRate,c=void 0===l?.95:l,d=o.safeDisplacement,u=void 0===d?10:d,h=o.applyRubberBandEffect,g=void 0!==h&&h,p=o.activeMouseButton,m=void 0===p?"Left":p,f=o.isMounted,v=void 0===f||f,S=(0,e.useRef)({isMouseDown:!1,isDraggingX:!1,isDraggingY:!1,initialMouseX:0,initialMouseY:0,lastMouseX:0,lastMouseY:0,scrollSpeedX:0,scrollSpeedY:0,lastScrollX:0,lastScrollY:0}),y=!1,C=!1,T=0,E=0,b=1/60*1e3;H2((function(){v&&(y="scroll"===window.getComputedStyle(t.current).overflowX,C="scroll"===window.getComputedStyle(t.current).overflowY,T=t.current.scrollWidth-t.current.clientWidth,E=t.current.scrollHeight-t.current.clientHeight,n=window.getComputedStyle(t.current).cursor,r=[],s=[],a=[],t.current.childNodes.forEach((function(e){r.push(window.getComputedStyle(e).cursor),s.push("none"===window.getComputedStyle(e).transform?"":window.getComputedStyle(e).transform),a.push("none"===window.getComputedStyle(e).transition?"":window.getComputedStyle(e).transition)})))}),[v]);var _,I,w,A=function(){var e=S.current.scrollSpeedX*b,i=S.current.scrollSpeedY*b,n=t.current.scrollLeft+e,r=t.current.scrollTop+i;t.current.scrollLeft=n,t.current.scrollTop=r,S.current.lastScrollX=n,S.current.lastScrollY=r},P=function(){t.current.childNodes.forEach((function(e,t){e.style.transform=s[t],e.style.transition=a[t]}))},R=function(e){e.preventDefault(),e.stopImmediatePropagation()},M=function(e){var i=S.current.isDraggingX||S.current.isDraggingY,s=S.current.initialMouseX-e.clientX,a=S.current.initialMouseY-e.clientY,o=Math.abs(s)>u||Math.abs(a)>u,l=i&&o;l?t.current.childNodes.forEach((function(e){e.addEventListener("click",R)})):t.current.childNodes.forEach((function(e){e.removeEventListener("click",R)})),S.current.isMouseDown=!1,S.current.lastMouseX=0,S.current.lastMouseY=0,t.current.style.cursor=n,t.current.childNodes.forEach((function(e,t){e.style.cursor=r[t]})),l&&(I=setInterval((function(){var e=S.current.scrollSpeedX*c;S.current.scrollSpeedX=e;var i=t.current.scrollLeft<=0,n=t.current.scrollLeft>=T,r=i||n;A(),(Math.abs(e)<.05||S.current.isMouseDown||r)&&(S.current.scrollSpeedX=0,clearInterval(I))}),b),w=setInterval((function(){var e=S.current.scrollSpeedY*c;S.current.scrollSpeedY=e;var i=t.current.scrollTop<=0,n=t.current.scrollTop>=E,r=i||n;A(),(Math.abs(e)<.05||S.current.isMouseDown||r)&&(S.current.scrollSpeedY=0,clearInterval(w))}),b),S.current.isDraggingX=!1,S.current.isDraggingY=!1,g&&(t.current.childNodes.forEach((function(e){e.style.transform="translate3d(0px, 0px, 0px)",e.style.transition="transform 250ms"})),_=setTimeout(P,250)))},D=function(e){if(S.current.isMouseDown){e.preventDefault();var i=S.current.lastMouseX-e.clientX;S.current.lastMouseX=e.clientX,S.current.scrollSpeedX=i/b,S.current.isDraggingX=!0;var n=S.current.lastMouseY-e.clientY;S.current.lastMouseY=e.clientY,S.current.scrollSpeedY=n/b,S.current.isDraggingY=!0,t.current.style.cursor="grabbing",t.current.childNodes.forEach((function(e){e.style.cursor="grabbing"}));var r=t.current.scrollLeft<=0&&y,s=t.current.scrollLeft>=T&&y,a=t.current.scrollTop<=0&&C,o=t.current.scrollTop>=E&&C;(r||s||a||o)&&g&&function(e){var i=e.clientX-S.current.initialMouseX,n=e.clientY-S.current.initialMouseY,r=t.current,s=r.clientWidth,a=r.clientHeight,o=0,l=0;y&&C?(o=.3*s*Math.sign(i)*Math.log10(1+.5*Math.abs(i)/s),l=.3*a*Math.sign(n)*Math.log10(1+.5*Math.abs(n)/a)):y?o=.3*s*Math.sign(i)*Math.log10(1+.5*Math.abs(i)/s):C&&(l=.3*a*Math.sign(n)*Math.log10(1+.5*Math.abs(n)/a)),t.current.childNodes.forEach((function(e){e.style.transform="translate3d("+o+"px, "+l+"px, 0px)",e.style.transition="transform 0ms"}))}(e),A()}},k=function(){T=t.current.scrollWidth-t.current.clientWidth,E=t.current.scrollHeight-t.current.clientHeight};return(0,e.useEffect)((function(){return v&&(window.addEventListener("mouseup",M),window.addEventListener("mousemove",D),window.addEventListener("resize",k)),function(){window.removeEventListener("mouseup",M),window.removeEventListener("mousemove",D),window.removeEventListener("resize",k),clearInterval(I),clearInterval(w),clearTimeout(_)}}),[v]),{events:{onMouseDown:function(e){var t;t=e.buttons,("Left"===m&&1===t||"Middle"===m&&4===t||"Right"===m&&2===t)&&(S.current.isMouseDown=!0,S.current.lastMouseX=e.clientX,S.current.lastMouseY=e.clientY,S.current.initialMouseX=e.clientX,S.current.initialMouseY=e.clientY)}}}}(s);return e.createElement("div",Object.assign({ref:s},a,{className:dB(j2,r)}),e.createElement(Y$,{"data-ui-id":"scrollable-horizontal-gallery",horizontal:!0,styles:$2,tokens:{childrenGap:"0.5rem"}},i))},q2=t=>{const{shouldFloatLocalVideo:i=!1,onFetchTilesToRender:n,isNarrow:r=!1,isShort:s=!1,overflowGalleryElements:a,horizontalGalleryStyles:o,overflowGalleryPosition:l="horizontalBottom",verticalGalleryStyles:c,onChildrenPerPageChange:d,parentWidth:u}=t,h=(0,e.useMemo)((()=>"verticalRight"===l?((e,t,i)=>t&&i?{width:"9rem",height:e?`calc(100% - ${m2.height}rem)`:"100%",paddingBottom:"0.5rem"}:!t&&i?{width:"9rem",height:e?`calc(100% - ${v2.height}rem)`:"100%",paddingBottom:"0.5rem"}:{width:"11rem",height:e?`calc(100% - ${S2.height}rem)`:"100%",paddingBottom:"0.5rem"})(i,r,s):((e,t)=>({minHeight:t?`${_2}rem`:`${w2}rem`,width:e?t?`calc(100% - ${m2.width}rem)`:`calc(100% - ${f2.width}rem)`:"100%",paddingRight:"0.5rem"}))(i,r)),[i,s,r,l]),g=(0,e.useMemo)((()=>"verticalRight"===l?ZH((e=>e?{children:M2}:{children:D2})(s),c):ZH((e=>({children:e?P2:R2}))(r),o)),[r,s,o,l,c]),p=(0,e.useMemo)((()=>{if(r&&u)return{width:i?m0(u)-m2.width-1+"rem":m0(u)-1+"rem"}}),[r,u,i]);return"verticalRight"===l?e.createElement(V2,{key:"responsive-vertical-gallery",containerStyles:h,verticalGalleryStyles:g,controlBarHeightRem:1.75,gapHeightRem:.5,isShort:s,onFetchTilesToRender:n,onChildrenPerPageChange:d},a||[e.createElement(e.Fragment,null)]):r?(null==d||d(3),e.createElement(G2,{horizontalGalleryElements:a||[e.createElement(e.Fragment,null)],onFetchTilesToRender:n,key:"scrollable-horizontal-gallery",containerStyles:p})):e.createElement(k2,{key:"responsive-horizontal-gallery",containerStyles:h,onFetchTilesToRender:n,horizontalGalleryStyles:g,buttonWidthRem:1.75,gapWidthRem:.5,onChildrenPerPageChange:d},a||[e.createElement(e.Fragment,null)])},z2=t=>{const{remoteParticipants:i=[],localParticipant:n,dominantSpeakers:r,localVideoComponent:s,screenShareComponent:a,onRenderRemoteParticipant:o,styles:l,maxRemoteVideoStreams:c,parentWidth:d,parentHeight:u,pinnedParticipantUserIds:h=[],overflowGalleryPosition:g="horizontalBottom",spotlightedParticipantUserIds:p=[]}=t,m=!!d&&T0(d),f=!!u&&E0(u),v=(0,e.useRef)(4),S=i.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})).length>0,{gridParticipants:y,overflowGalleryParticipants:C}=d1({remoteParticipants:i,localParticipant:n,dominantSpeakers:r,maxGridParticipants:S?c:9,isScreenShareActive:!!a,maxOverflowGalleryDominantSpeakers:a?v.current-(h.length+1)%v.current:v.current,pinnedParticipantUserIds:h,layout:"default",spotlightedParticipantUserIds:p}),[T,E]=(0,e.useState)([]);let{gridTiles:b,overflowGalleryTiles:_}=h1(y,o,c,T,C,r);s&&(a||p.length>0?_=[s].concat(_):b=[s].concat(b));const I=(0,e.useMemo)((()=>0===_.length?null:e.createElement(q2,{isNarrow:m,isShort:f,shouldFloatLocalVideo:!1,overflowGalleryElements:_,horizontalGalleryStyles:null==l?void 0:l.horizontalGallery,verticalGalleryStyles:null==l?void 0:l.verticalGallery,overflowGalleryPosition:g,onFetchTilesToRender:E,onChildrenPerPageChange:e=>{v.current=e},parentWidth:d})),[m,f,_,null==l?void 0:l.horizontalGallery,g,E,null==l?void 0:l.verticalGallery,d]);return e.createElement(Y$,{horizontal:"verticalRight"===g,styles:a2,tokens:o2},"horizontalTop"===t.overflowGalleryPosition?I:e.createElement(e.Fragment,null),a||e.createElement(t2,{key:"grid-layout",styles:null==l?void 0:l.gridLayout},b),W2(I,t.overflowGalleryPosition))},W2=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null);var K2=function(){var t=Xq({});return e.useEffect((function(){return function(){for(var e=0,i=Object.keys(t);e<i.length;e++){var n=i[e];clearTimeout(n)}}}),[t]),Xq({setTimeout:function(e,i){var n=setTimeout(e,i);return t[n]=1,n},clearTimeout:function(e){delete t[e],clearTimeout(e)}})},J2=oj(),Y2=function(t){function i(e){var i=t.call(this,e)||this;Ij(i);var n=i.props.allowTouchBodyScroll,r=void 0!==n&&n;return i._allowTouchBodyScroll=r,i}return _U(i,t),i.prototype.componentDidMount=function(){var e;!this._allowTouchBodyScroll&&((e=EB())&&e.body&&!NG&&(e.body.classList.add(LG),e.body.addEventListener("touchmove",BG,{passive:!1,capture:!1})),NG++)},i.prototype.componentWillUnmount=function(){!this._allowTouchBodyScroll&&function(){if(NG>0){var e=EB();e&&e.body&&1===NG&&(e.body.classList.remove(LG),e.body.removeEventListener("touchmove",BG)),NG--}}()},i.prototype.render=function(){var t=this.props,i=t.isDarkThemed,n=t.className,r=t.theme,s=t.styles,a=B$(this.props,U$),o=J2(s,{theme:r,className:n,isDark:i});return e.createElement("div",IU({},a,{className:o.root}))},i}(e.Component),Q2={root:"ms-Overlay",rootDark:"ms-Overlay--dark"},Z2=nj(Y2,(function(e){var t,i=e.className,n=e.theme,r=e.isNone,s=e.isDark,a=n.palette,o=FV(Q2,n);return{root:[o.root,n.fonts.medium,{backgroundColor:a.whiteTranslucent40,top:0,right:0,bottom:0,left:0,position:"absolute",selectors:(t={},t[UV]={border:"1px solid WindowText",opacity:0},t)},r&&{visibility:"hidden"},s&&[o.rootDark,{backgroundColor:a.blackTranslucent40}],i]}}),void 0,{scope:"Overlay"});const X2=CV,e5={x:0,y:0},t5={isOpen:!1,isDarkOverlay:!0,className:"",containerClassName:"",enableAriaHiddenSiblings:!0},i5=oj(),n5=e.forwardRef(((t,i)=>{var n;const r=sq(t5,t),{allowTouchBodyScroll:s,className:a,children:o,containerClassName:l,scrollableContentClassName:c,elementToFocusOnDismiss:d,firstFocusableSelector:u,forceFocusInsideTrap:h,ignoreExternalFocusing:g,isBlocking:p,isAlert:m,isClickableOutsideFocusTrap:f,isDarkOverlay:v,onDismiss:S,layerProps:y,overlay:C,isOpen:T,titleAriaId:E,styles:b,subtitleAriaId:_,theme:I,topOffsetFixed:w,responsiveMode:A,onLayerDidMount:P,isModeless:R,dragOptions:M,onDismissed:D,minDragPosition:k,maxDragPosition:O,dataUiId:N,keyEventElement:L=window}=r,x=e.useRef(null),F=e.useRef(null),U=e.useRef(null),B=nG(x,i),V=_W(B),H=g$("ModalFocusTrapZone"),{setTimeout:$,clearTimeout:j}=K2(),[G,q]=e.useState(T),[z,W]=e.useState(T),[K,J]=e.useState(e5),[Y,Q]=e.useState(),[Z,{setTrue:X,setFalse:ee}]=lK(!1),[te,ie]=e.useState(0),ne=e.useCallback((()=>ie((e=>e+1))),[]),re=Xq((()=>({onModalCloseTimer:0,allowTouchBodyScroll:s,scrollableContent:null,lastSetCoordinates:e5,events:new Lj({})}))),{keepInBounds:se}=M||{},ae=null!=m?m:p&&!R,oe=void 0===y?"":y.className,le=i5(b,{theme:I,className:a,containerClassName:l,scrollableContentClassName:c,isOpen:T,isVisible:z,hasBeenOpened:re.hasBeenOpened,modalRectangleTop:Y,topOffsetFixed:w,isModeless:R,layerClassName:oe,windowInnerHeight:null===window||void 0===window?void 0:window.innerHeight,isDefaultDragHandle:M&&!M.dragHandleSelector}),ce=Object.assign(Object.assign({eventBubblingEnabled:!1},y),{onLayerDidMount:y&&y.onLayerDidMount?y.onLayerDidMount:P,insertFirst:R,className:le.layer}),de=e.useCallback((e=>{e?re.allowTouchBodyScroll?UG(e,re.events):FG(e,re.events):re.events.off(re.scrollableContent),re.scrollableContent=e}),[re]),ue=()=>{const e=U.current,t=null==e?void 0:e.getBoundingClientRect();t&&(w&&Q(t.top),se&&(re.minPosition=null!=k?k:{x:-t.left,y:-t.top},re.maxPosition=null!=O?O:{x:t.left,y:t.top},J({x:he("x",K.x),y:he("y",K.y)})))},he=e.useCallback(((e,t)=>{const{minPosition:i,maxPosition:n}=re;return se&&i&&n&&(t=Math.max(i[e],t),t=Math.min(n[e],t)),t}),[se,re]),ge=()=>{var e;re.lastSetCoordinates=e5,ee(),re.isInKeyboardMoveMode=!1,q(!1),J(e5),null===(e=re.disposeOnKeyUp)||void 0===e||e.call(re),null==D||D()},pe=e.useCallback((()=>{ee(),re.isInKeyboardMoveMode=!1}),[re,ee]),me=e.useCallback(((e,t)=>{J((e=>({x:he("x",e.x+t.delta.x),y:he("y",e.y+t.delta.y)})))}),[he]),fe=e.useCallback((()=>{F.current&&F.current.focus()}),[]);e.useEffect((()=>{j(re.onModalCloseTimer),T&&(requestAnimationFrame((()=>$(ue,0))),q(!0),M&&(()=>{const e=e=>{const t=e;t.altKey&&t.ctrlKey&&t.keyCode===Sj&&CG(re.scrollableContent,t.target)&&(X(),t.preventDefault(),t.stopPropagation())};re.disposeOnKeyUp||(L.addEventListener("keyup",e,!0),re.disposeOnKeyUp=()=>{L.removeEventListener("keyup",e,!0),re.disposeOnKeyUp=void 0})})(),re.hasBeenOpened=!0,W(!0)),!T&&G&&(re.onModalCloseTimer=$(ge,1e3*parseFloat(X2)),W(!1))}),[G,T,k,O]),_J((()=>{re.events.dispose()})),((t,i)=>{e.useImperativeHandle(t.componentRef,(()=>({focus(){i.current&&i.current.focus()}})),[i])})(r,F);const ve=e.createElement(x0,Object.assign({disabled:!0,id:H,ref:U,componentRef:F,className:le.main,elementToFocusOnDismiss:d,isClickableOutsideFocusTrap:R||f||!p,ignoreExternalFocusing:g,forceFocusInsideTrap:h&&!R,firstFocusableSelector:u,focusPreviouslyFocusedInnerElement:!0,onBlur:re.isInKeyboardMoveMode?()=>{var e;re.lastSetCoordinates=e5,re.isInKeyboardMoveMode=!1,null===(e=re.disposeOnKeyDown)||void 0===e||e.call(re)}:void 0,"data-ui-id":N},null!==(n=r.focusTrapZoneProps)&&void 0!==n?n:{}),M&&re.isInKeyboardMoveMode&&e.createElement("div",{className:le.keyboardMoveIconContainer},M.keyboardMoveIconProps?e.createElement(mG,Object.assign({},M.keyboardMoveIconProps)):e.createElement(mG,{iconName:"move",className:le.keyboardMoveIcon})),e.createElement("div",{ref:de,className:le.scrollableContent,"data-is-scrollable":!0},M&&Z&&e.createElement(M.menu,{items:[{key:"move",text:M.moveMenuItemText,onClick:()=>{const e=e=>{const t=e;if(t.altKey&&t.ctrlKey&&t.keyCode===Sj)return t.preventDefault(),void t.stopPropagation();const i=t.altKey||t.keyCode===vj;if(Z&&i&&ee(),!re.isInKeyboardMoveMode||t.keyCode!==vj&&t.keyCode!==fj||(re.isInKeyboardMoveMode=!1,ne(),t.preventDefault(),t.stopPropagation()),re.isInKeyboardMoveMode){let e=!0;const i=(e=>{let t=10;return e.shiftKey?e.ctrlKey||(t=50):e.ctrlKey&&(t=1),t})(t);switch(t.keyCode){case vj:J(re.lastSetCoordinates);case fj:re.lastSetCoordinates=e5;break;case Cj:J((e=>({x:e.x,y:he("y",e.y-i)})));break;case Ej:J((e=>({x:e.x,y:he("y",e.y+i)})));break;case yj:J((e=>({x:he("x",e.x-i),y:e.y})));break;case Tj:J((e=>({x:he("x",e.x+i),y:e.y})));break;default:e=!1}e&&(t.preventDefault(),t.stopPropagation())}};re.lastSetCoordinates=K,ee(),re.isInKeyboardMoveMode=!0,L.addEventListener("keydown",e,!0),re.disposeOnKeyDown=()=>{L.removeEventListener("keydown",e,!0),re.disposeOnKeyDown=void 0}}},{key:"close",text:M.closeMenuItemText,onClick:ge}],onDismiss:ee,alignTargetEdge:!0,coverTarget:!0,directionalHint:0,directionalHintFixed:!0,shouldFocusOnMount:!0,target:re.scrollableContent}),o));return G&&V>=(A||fW.small)&&e.createElement(Hz,Object.assign({ref:B},ce),e.createElement(Zq,{role:ae?"alertdialog":"dialog",ariaLabelledBy:E,ariaDescribedBy:_,shouldRestoreFocus:!g,"aria-modal":!R},e.createElement("div",{className:le.root,role:R?void 0:"document"},!R&&e.createElement(Z2,Object.assign({"aria-hidden":!0,isDarkThemed:v,onClick:p?void 0:S,allowTouchBodyScroll:s},C)),M?e.createElement(o5,{handleSelector:M.dragHandleSelector||`#${H}`,preventDragSelector:"button",onStart:pe,onDragChange:me,onStop:fe,position:K},ve):ve)))||null}));n5.displayName="ModalBase";const r5=SB(((e,t)=>({root:dB(e,t&&{touchAction:"none",selectors:{"& *":{userSelect:"none"}}})}))),s5={start:"touchstart",move:"touchmove",stop:"touchend"},a5={start:"mousedown",move:"mousemove",stop:"mouseup"};class o5 extends e.Component{constructor(t){super(t),this._currentEventType=a5,this._events=[],this._onMouseDown=t=>{const i=e.Children.only(this.props.children).props.onMouseDown;return i&&i(t),this._currentEventType=a5,this._onDragStart(t)},this._onMouseUp=t=>{const i=e.Children.only(this.props.children).props.onMouseUp;return i&&i(t),this._currentEventType=a5,this._onDragStop(t)},this._onTouchStart=t=>{const i=e.Children.only(this.props.children).props.onTouchStart;return i&&i(t),this._currentEventType=s5,this._onDragStart(t)},this._onTouchEnd=t=>{const i=e.Children.only(this.props.children).props.onTouchEnd;i&&i(t),this._currentEventType=s5,this._onDragStop(t)},this._onDragStart=e=>{if("number"==typeof e.button&&0!==e.button)return!1;if(this.props.handleSelector&&!this._matchesSelector(e.target,this.props.handleSelector)||this.props.preventDragSelector&&this._matchesSelector(e.target,this.props.preventDragSelector))return;this._touchId=this._getTouchId(e);const t=this._getControlPosition(e);if(void 0===t)return;const i=this._createDragDataFromPosition(t);this.props.onStart&&this.props.onStart(e,i),this.setState({isDragging:!0,lastPosition:t}),this._events=[pq(document.body,this._currentEventType.move,this._onDrag,!0),pq(document.body,this._currentEventType.stop,this._onDragStop,!0)]},this._onDrag=e=>{"touchmove"===e.type&&e.preventDefault();const t=this._getControlPosition(e);if(!t)return;const i=this._createUpdatedDragData(this._createDragDataFromPosition(t)),n=i.position;this.props.onDragChange&&this.props.onDragChange(e,i),this.setState({position:n,lastPosition:t})},this._onDragStop=e=>{if(!this.state.isDragging)return;const t=this._getControlPosition(e);if(!t)return;const i=this._createDragDataFromPosition(t);this.setState({isDragging:!1,lastPosition:void 0}),this.props.onStop&&this.props.onStop(e,i),this.props.position&&this.setState({position:this.props.position}),this._events.forEach((e=>e()))},this.state={isDragging:!1,position:this.props.position||{x:0,y:0},lastPosition:void 0}}componentDidUpdate(e){!this.props.position||e.position&&this.props.position===e.position||this.setState({position:this.props.position})}componentWillUnmount(){this._events.forEach((e=>e()))}render(){const t=e.Children.only(this.props.children),{props:i}=t,{position:n}=this.props,{position:r,isDragging:s}=this.state;let a=r.x,o=r.y;return n&&!s&&(a=n.x,o=n.y),e.cloneElement(t,{style:Object.assign(Object.assign({},i.style),{transform:`translate(${a}px, ${o}px)`}),className:r5(i.className,this.state.isDragging).root,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onTouchStart:this._onTouchStart,onTouchEnd:this._onTouchEnd})}_getControlPosition(e){const t=this._getActiveTouch(e);if(void 0!==this._touchId&&!t)return;const i=t||e;return{x:i.clientX,y:i.clientY}}_getActiveTouch(e){return e.targetTouches&&this._findTouchInTouchList(e.targetTouches)||e.changedTouches&&this._findTouchInTouchList(e.changedTouches)}_getTouchId(e){const t=e.targetTouches&&e.targetTouches[0]||e.changedTouches&&e.changedTouches[0];if(t)return t.identifier}_matchesSelector(e,t){if(!e||e===document.body)return!1;const i=e.matches||e.webkitMatchesSelector||e.msMatchesSelector;return!!i&&(i.call(e,t)||this._matchesSelector(e.parentElement,t))}_findTouchInTouchList(e){var t;if(void 0!==this._touchId)for(let i=0;i<e.length;i++)if((null===(t=e[i])||void 0===t?void 0:t.identifier)===this._touchId)return e[i]}_createDragDataFromPosition(e){const{lastPosition:t}=this.state;return void 0===t?{delta:{x:0,y:0},lastPosition:e,position:e}:{delta:{x:e.x-t.x,y:e.y-t.y},lastPosition:t,position:e}}_createUpdatedDragData(e){const{position:t}=this.state;return{position:{x:t.x+e.delta.x,y:t.y+e.delta.y},delta:e.delta,lastPosition:t}}}const l5={root:"ms-Modal",main:"ms-Dialog-main",scrollableContent:"ms-Modal-scrollableContent",isOpen:"is-open",layer:"ms-Modal-Layer"},c5=nj(n5,(e=>{const{className:t,containerClassName:i,scrollableContentClassName:n,isOpen:r,isVisible:s,hasBeenOpened:a,modalRectangleTop:o,theme:l,topOffsetFixed:c,isModeless:d,layerClassName:u,isDefaultDragHandle:h,windowInnerHeight:g}=e,{palette:p,effects:m,fonts:f}=l,v=FV(l5,l);return{root:[v.root,f.medium,{backgroundColor:"transparent",position:d?"absolute":"fixed",height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",opacity:0,pointerEvents:"none",transition:`opacity ${X2}`},c&&"number"==typeof o&&a&&{alignItems:"flex-start"},r&&v.isOpen,s&&{opacity:1,pointerEvents:"auto"},t],main:[v.main,{boxShadow:m.elevation64,borderRadius:m.roundedCorner2,backgroundColor:p.white,boxSizing:"border-box",position:"relative",textAlign:"left",outline:"3px solid transparent",maxHeight:"calc(100% - 32px)",maxWidth:"calc(100% - 32px)",minHeight:"176px",minWidth:"288px",overflowY:"auto",zIndex:d?jV.Layer:void 0},c&&"number"==typeof o&&a&&{top:o},h&&{cursor:"move"},i],scrollableContent:[v.scrollableContent,{overflowY:"auto",flexGrow:1,maxHeight:"100vh",selectors:{"@supports (-webkit-overflow-scrolling: touch)":{maxHeight:g}}},n],layer:d&&[u,v.layer,{position:"static",width:"unset",height:"unset"}],keyboardMoveIconContainer:{position:"absolute",display:"flex",justifyContent:"center",width:"100%",padding:"3px 0px"},keyboardMoveIcon:{fontSize:f.xLargePlus.fontSize,width:"24px"}}}),void 0,{scope:"Modal",fields:["theme","styles","enableAriaHiddenSiblings"]});c5.displayName="Modal";const d5={moveMenuItemText:"Move",closeMenuItemText:"Close",menu:GW,keepInBounds:!0},u5={x:p0(1),y:p0(1)},h5=t=>{var i;const{localVideoComponent:n,layerHostId:r,localVideoSizeRem:s,parentWidth:a,parentHeight:o}=t,l=aJ(),c=AK().strings.videoGallery,d=(0,e.useMemo)((()=>a&&o?{x:-a+p0(s.width)+p0(1),y:-o+p0(s.height)+p0(1)}:void 0),[o,a,s.width,s.height]),u=(0,e.useMemo)((()=>((e,t)=>ZH({main:dB(y2(e,t),{bottom:"1rem",right:"1rem"})},{main:{boxShadow:e.effects.elevation8,":focus-within":{boxShadow:e.effects.elevation16,border:`${vJ(2)} solid ${e.palette.neutralPrimary}`}}},{root:{pointerEvents:"none"}},b2))(l,s)),[l,s]),h=(0,e.useMemo)((()=>({hostId:r})),[r]);return e.createElement(c5,{isOpen:!0,isModeless:!0,dragOptions:d5,styles:u,layerProps:h,maxDragPosition:u5,minDragPosition:d,dataUiId:"floating-local-video-host"},e.createElement(Y$,{"aria-label":null!==(i=c.localVideoMovementAriaLabel)&&void 0!==i?i:c.localVideoMovementLabel,tabIndex:0,role:"dialog",style:{pointerEvents:"auto"}},n))},g5={root:{position:"relative",height:"100%",width:"100%"}},p5={root:{position:"relative",height:"100%",width:"100%",padding:"0.5rem"}},m5={position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden",pointerEvents:"none"},f5=t=>{const{remoteParticipants:i=[],dominantSpeakers:n,localVideoComponent:r,screenShareComponent:s,onRenderRemoteParticipant:a,styles:o,maxRemoteVideoStreams:l,showCameraSwitcherInLocalPreview:c,parentWidth:d,parentHeight:u,overflowGalleryPosition:h="horizontalBottom",pinnedParticipantUserIds:g=[],localVideoTileSize:p,spotlightedParticipantUserIds:m}=t,f=aJ(),v=!!d&&T0(d),S=!!u&&E0(u),y=(0,e.useRef)(4),C=i.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})).length>0,{gridParticipants:T,overflowGalleryParticipants:E}=d1({remoteParticipants:i,dominantSpeakers:n,maxGridParticipants:C?l:9,isScreenShareActive:!!s,maxOverflowGalleryDominantSpeakers:s?y.current-g.length%y.current:y.current,pinnedParticipantUserIds:g,layout:"floatingLocalVideo",spotlightedParticipantUserIds:m}),[b,_]=(0,e.useState)([]),{gridTiles:I,overflowGalleryTiles:w}=h1(T,a,l,b,E,n),A=i.length>0;!A&&r&&I.push(r);const P=g$("layerhost"),R=(0,e.useMemo)((()=>v||"9:16"===p?m2:(w.length>0||s)&&"verticalRight"===h?v?m2:S?v2:S2:(w.length>0||s)&&"horizontalBottom"===h&&"16:9"!==p&&v?m2:f2),[w.length,v,s,S,h,p]),M=r&&A||s&&r?c?e.createElement(Y$,{className:dB(C2(f,R),{boxShadow:f.effects.elevation8,zIndex:2})},r):w.length>0||s?e.createElement(Y$,{className:dB(y2(f,R,!!s,h))},r):e.createElement(h5,{localVideoComponent:r,layerHostId:P,localVideoSizeRem:R,parentWidth:d,parentHeight:u}):void 0,D=(0,e.useMemo)((()=>0!==w.length||s?e.createElement(q2,{isShort:S,onFetchTilesToRender:_,isNarrow:v,shouldFloatLocalVideo:!!r,overflowGalleryElements:w,horizontalGalleryStyles:null==o?void 0:o.horizontalGallery,verticalGalleryStyles:null==o?void 0:o.verticalGallery,overflowGalleryPosition:h,onChildrenPerPageChange:e=>{y.current=e},parentWidth:d}):null),[v,S,s,w,null==o?void 0:o.horizontalGallery,h,_,null==o?void 0:o.verticalGallery,d,r]);return e.createElement(Y$,{styles:g5},e.createElement(Y$,{horizontal:"verticalRight"===h,styles:p5,tokens:o2},"horizontalTop"===t.overflowGalleryPosition?D:e.createElement(e.Fragment,null),s||e.createElement(t2,{key:"grid-layout",styles:null==o?void 0:o.gridLayout},I),v5(D,t.overflowGalleryPosition)),e.createElement(IJ,{id:P,className:dB(m5)}),M)},v5=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null),S5=t=>{const{remoteParticipants:i=[],dominantSpeakers:n,localVideoComponent:r,screenShareComponent:s,onRenderRemoteParticipant:a,styles:o,maxRemoteVideoStreams:l,parentWidth:c,parentHeight:d,overflowGalleryPosition:u="horizontalBottom",pinnedParticipantUserIds:h=[],localVideoTileSize:g}=t,p=qK(),m=!!c&&T0(c),f=!!d&&E0(d),v=(0,e.useRef)(4),{gridParticipants:S,overflowGalleryParticipants:y}=d1({remoteParticipants:i,dominantSpeakers:n,maxGridParticipants:l,isScreenShareActive:!!s,maxOverflowGalleryDominantSpeakers:s?v.current-h.length%v.current:v.current,pinnedParticipantUserIds:h,layout:"speaker"}),[C,T]=(0,e.useState)([]),{gridTiles:E,overflowGalleryTiles:b}=h1(S,a,l,C,y,n);!(i.length>0)&&r&&E.push(r);const _=g$("layerhost"),I=(0,e.useMemo)((()=>m||"9:16"===g?m2:(b.length>0||s)&&"verticalRight"===u?m?m2:f?v2:S2:(b.length>0||s)&&"horizontalBottom"===u&&"16:9"!==g&&m?m2:f2),[b.length,m,s,f,u,g]),w=r||s&&r?e.createElement(Y$,{className:dB(y2(p,I,!!s,u))},r):void 0,A=(0,e.useMemo)((()=>0!==b.length||s?e.createElement(q2,{isShort:f,onFetchTilesToRender:T,isNarrow:m,shouldFloatLocalVideo:!!r,overflowGalleryElements:b,horizontalGalleryStyles:null==o?void 0:o.horizontalGallery,verticalGalleryStyles:null==o?void 0:o.verticalGallery,overflowGalleryPosition:u,onChildrenPerPageChange:e=>{v.current=e},parentWidth:c}):null),[m,f,s,b,null==o?void 0:o.horizontalGallery,u,T,null==o?void 0:o.verticalGallery,c,r]);return e.createElement(Y$,{styles:g5},e.createElement(Y$,{horizontal:"verticalRight"===u,styles:p5,tokens:o2},"horizontalTop"===t.overflowGalleryPosition?A:e.createElement(e.Fragment,null),s||e.createElement(t2,{key:"grid-layout",styles:null==o?void 0:o.gridLayout},E),y5(A,t.overflowGalleryPosition)),e.createElement(IJ,{id:_,className:dB(m5)}),w)},y5=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null),C5=t=>{const{screenShareComponent:i}=t,n=g$("layerhost");return e.createElement(Y$,{styles:g5},e.createElement(IJ,{id:n,className:dB(m5)}),e.createElement(Y$,{styles:p5,tokens:o2},i||e.createElement(e.Fragment,null)))},T5=t=>{const{togetherModeStreamComponent:i}=t;return e.createElement(Y$,null,i)},E5=(0,e.memo)((t=>{var i,n,r;const{startTogetherModeEnabled:s,isTogetherModeActive:a,onCreateTogetherModeStreamView:o,onStartTogetherMode:l,onSetTogetherModeSceneSize:c,onDisposeTogetherModeStreamView:d,togetherModeStreams:u,containerWidth:h,containerHeight:g}=t;(0,e.useEffect)((()=>()=>{d&&d()}),[d]),(0,e.useEffect)((()=>{s&&!a&&(null==l||l())}),[s,a,l]),(0,e.useEffect)((()=>{var e,t;(null===(e=null==u?void 0:u.mainVideoStream)||void 0===e?void 0:e.isAvailable)&&!(null===(t=null==u?void 0:u.mainVideoStream)||void 0===t?void 0:t.renderElement)&&(null==o||o())}),[null===(i=null==u?void 0:u.mainVideoStream)||void 0===i?void 0:i.renderElement,null===(n=null==u?void 0:u.mainVideoStream)||void 0===n?void 0:n.isAvailable,o]),(0,e.useMemo)((()=>{c&&h&&g&&c(h,g)}),[c,h,g]);const p=null===(r=t.togetherModeStreams)||void 0===r?void 0:r.mainVideoStream,m=!(p&&p.isAvailable&&p.isReceiving);return h&&g?e.createElement(Y$,{styles:P1,horizontalAlign:"center",verticalAlign:"center","data-ui-id":"together-mode-layout"},e.createElement(e1,{videoStreamElement:(null==p?void 0:p.renderElement)||null,isMirrored:!0,loadingState:m?"loading":"none"}),e.createElement(N1,{reactionResources:t.reactionResources||{},localParticipant:t.localParticipant,remoteParticipants:t.remoteParticipants,togetherModeSeatPositions:t.seatingCoordinates,overlayMode:"together-mode"})):e.createElement(e.Fragment,null)})),b5=4,_5={"-webkit-user-select":"none","-webkit-touch-callout":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"},I5={kind:"contextual"},w5=t=>{var i,n,r,s;const{localParticipant:a,remoteParticipants:o=[],localVideoViewOptions:l,remoteVideoViewOptions:c,dominantSpeakers:d,onRenderLocalVideoTile:u,onRenderRemoteVideoTile:h,onCreateLocalStreamView:g,onDisposeLocalStreamView:p,onCreateRemoteStreamView:m,onDisposeRemoteScreenShareStreamView:f,onDisposeLocalScreenShareStreamView:v,onDisposeRemoteVideoStreamView:S,styles:y,layout:C,onRenderAvatar:T,showMuteIndicator:E,maxRemoteVideoStreams:b=b5,showCameraSwitcherInLocalPreview:_,localVideoCameraCycleButtonProps:I,onPinParticipant:w,onUnpinParticipant:A,remoteVideoTileMenu:P=I5,overflowGalleryPosition:R="horizontalBottom",localVideoTileSize:M="followDeviceOrientation",spotlightedParticipants:D,onStartLocalSpotlight:k,onStartRemoteSpotlight:O,onStopLocalSpotlight:N,onStopRemoteSpotlight:L,maxParticipantsToSpotlight:x,reactionResources:F,videoTilesOptions:U,onMuteParticipant:B,startTogetherModeEnabled:V,isTogetherModeActive:H,onCreateTogetherModeStreamView:$,onStartTogetherMode:j,onSetTogetherModeSceneSize:G,togetherModeStreams:q,togetherModeSeatingCoordinates:z,onDisposeTogetherModeStreamView:W,onForbidAudio:K,onPermitAudio:J,onForbidVideo:Y,onPermitVideo:Q,localScreenShareView:Z}=t,X=DX(),ee=aJ(),te=AK().strings.videoGallery,ie=(0,e.useMemo)((()=>Object.assign(Object.assign({},te),t.strings)),[te,t.strings]),ne=P&&"drawer"===P.kind?P.hostId:void 0,re=g$("drawerMenuHost",ne),se=("floatingLocalVideo"===C||"speaker"===C)&&o.length>0,ae=(0,e.useRef)(null),oe=y0(ae),le=C0(ae),ce=!!oe&&T0(oe),[de,ue]=e.useState([]),[he,ge]=e.useState({}),pe=(0,e.useCallback)(((e,t)=>{ge((i=>Object.assign(Object.assign({},i),{[e]:{scalingMode:t,isMirrored:null==c?void 0:c.isMirrored}})))}),[null==c?void 0:c.isMirrored]);(0,e.useEffect)((()=>{var e;null===(e=t.pinnedParticipants)||void 0===e||e.forEach((e=>{var i;(null===(i=t.remoteParticipants)||void 0===i?void 0:i.find((t=>t.userId===e)))||console.warn("Invalid pinned participant UserId :"+e)}))}),[t.pinnedParticipants,t.remoteParticipants]);const me=(0,e.useMemo)((()=>{var e;return null!==(e=t.pinnedParticipants)&&void 0!==e?e:de.filter((e=>o.find((t=>t.userId===e))))}),[t.pinnedParticipants,de,o]),fe=!(se&&ce||"9:16"===M)||"default"===C,ve=(0,e.useMemo)((()=>{var t,i;if("hidden"===M)return;if(u)return u(a);const n=!!a.spotlight,r=ZH(se?E2:{},{root:{borderRadius:ee.effects.roundedCorner4}},null==y?void 0:y.localVideo),s=a.displayName?a.displayName:"";return e.createElement(Y$,{styles:J1,key:"local-video-tile-key"},e.createElement(Q1,{alwaysShowLabelBackground:null==U?void 0:U.alwaysShowLabelBackground,userId:a.userId,onCreateLocalStreamView:g,onDisposeLocalStreamView:p,isAvailable:null===(t=null==a?void 0:a.videoStream)||void 0===t?void 0:t.isAvailable,isMuted:a.isMuted,renderElement:null===(i=null==a?void 0:a.videoStream)||void 0===i?void 0:i.renderElement,displayName:"default"===C?ie.localVideoLabel:ce?"":ie.localVideoLabel,initialsName:s,localVideoViewOptions:l,onRenderAvatar:T,showLabel:fe,showMuteIndicator:E,showCameraSwitcherInLocalPreview:_,localVideoCameraCycleButtonProps:I,localVideoCameraSwitcherLabel:ie.localVideoCameraSwitcherLabel,localVideoSelectedDescription:ie.localVideoSelectedDescription,styles:r,raisedHand:a.raisedHand,reaction:a.reaction,spotlightedParticipantUserIds:D,isSpotlighted:n,onStartSpotlight:k,onStopSpotlight:N,maxParticipantsToSpotlight:x,menuKind:P?"drawer"===P.kind?"drawer":"contextual":void 0,drawerMenuHostId:re,strings:ie,reactionResources:F,participantsCount:o.length+1,isScreenSharingOn:a.isScreenSharingOn,mediaAccess:a.mediaAccess}))}),[ce,a,I,l,g,p,T,u,se,_,E,null==y?void 0:y.localVideo,ee.effects.roundedCorner4,M,C,fe,D,k,N,x,P,ie,re,F,U,o.length]),Se=(0,e.useCallback)((e=>{me.length>=4||(me.includes(e)||ue(me.concat(e)),null==w||w(e))}),[me,ue,w]),ye=(0,e.useCallback)((e=>{ue(de.filter((t=>t!==e))),null==A||A(e)}),[de,ue,A]),[Ce,Te]=e.useState(""),Ee=(0,e.useCallback)((e=>{Te(e),setTimeout((()=>{Te("")}),3e3)}),[Te]),be=(0,e.useCallback)(((t,i)=>{const n=t.videoStream,r=n?he[t.userId]:void 0;let s=null==me?void 0:me.includes(t.userId);const o=!!t.spotlight;return s=!o&&s,e.createElement(L1,{alwaysShowLabelBackground:null==U?void 0:U.alwaysShowLabelBackground,streamId:null==n?void 0:n.id,key:t.userId,userId:t.userId,remoteParticipant:t,onCreateRemoteStreamView:i?m:void 0,onDisposeRemoteStreamView:i?S:void 0,isAvailable:!!i&&(null==n?void 0:n.isAvailable),isReceiving:!!i&&(null==n?void 0:n.isReceiving),renderElement:i?null==n?void 0:n.renderElement:void 0,remoteVideoViewOptions:(()=>{var e,t;return r||((null==n?void 0:n.streamSize)&&(null===(e=n.streamSize)||void 0===e?void 0:e.height)>(null===(t=n.streamSize)||void 0===t?void 0:t.width)?{scalingMode:"Fit",isMirrored:null==c?void 0:c.isMirrored}:c)})(),onRenderAvatar:T,showMuteIndicator:E,strings:ie,participantState:t.state,menuKind:t.userId===a.userId?void 0:P?"drawer"===P.kind?"drawer":"contextual":void 0,drawerMenuHostId:re,onPinParticipant:Se,onUnpinParticipant:ye,onUpdateScalingMode:pe,isPinned:s,disablePinMenuItem:me.length>=4,toggleAnnouncerString:Ee,spotlightedParticipantUserIds:D,isSpotlighted:o,onStartSpotlight:O,onStopSpotlight:L,maxParticipantsToSpotlight:x,reactionResources:F,onMuteParticipant:B,onForbidAudio:K,onPermitAudio:J,onForbidVideo:Y,onPermitVideo:Q})}),[he,me,null==U?void 0:U.alwaysShowLabelBackground,m,S,T,E,ie,a.userId,P,re,Se,ye,pe,Ee,D,O,L,x,F,B,K,J,Y,Q,c]),_e=o.find((e=>{var t;return null===(t=e.screenShareStream)||void 0===t?void 0:t.isAvailable})),Ie=e.createElement(z1,{localParticipant:a,renderElement:null===(i=a.screenShareStream)||void 0===i?void 0:i.renderElement,isAvailable:null===(n=a.screenShareStream)||void 0===n?void 0:n.isAvailable,onCreateLocalStreamView:g,onDisposeLocalScreenShareStreamView:v,localScreenShareView:Z}),we=_e&&e.createElement(B1,Object.assign({},_e,{renderElement:null===(r=_e.screenShareStream)||void 0===r?void 0:r.renderElement,onCreateRemoteStreamView:m,onDisposeRemoteStreamView:f,isReceiving:null===(s=_e.screenShareStream)||void 0===s?void 0:s.isReceiving,participantVideoScalingMode:he[_e.userId],localParticipant:a,remoteParticipants:o,reactionResources:F}))||(a.isScreenSharingOn?Ie:void 0),Ae=H||(e=>{if(!e)return!1;const t=rL(e);return QN(t)})(a.userId)&&V,Pe=(0,e.useMemo)((()=>!we&&Ae&&"togetherMode"===C?e.createElement(E5,{startTogetherModeEnabled:V,isTogetherModeActive:H,onCreateTogetherModeStreamView:$,onStartTogetherMode:j,onDisposeTogetherModeStreamView:W,onSetTogetherModeSceneSize:G,togetherModeStreams:q,seatingCoordinates:z,localParticipant:a,remoteParticipants:o,reactionResources:F,containerWidth:oe,containerHeight:le}):void 0),[C,we,Ae,V,H,$,j,W,G,q,z,a,o,F,oe,le]),Re=(0,e.useMemo)((()=>({remoteParticipants:o,localParticipant:a,screenShareComponent:we,showCameraSwitcherInLocalPreview:_,maxRemoteVideoStreams:b,dominantSpeakers:d,styles:y,onRenderRemoteParticipant:null!=h?h:be,localVideoComponent:ve,parentWidth:oe,parentHeight:le,pinnedParticipantUserIds:me,overflowGalleryPosition:R,localVideoTileSize:M,spotlightedParticipantUserIds:D})),[o,a,we,_,b,d,y,ve,oe,le,h,be,me,R,M,D]),Me=(0,e.useMemo)((()=>_e&&"focusedContent"===C?e.createElement(C5,Object.assign({},Re)):"floatingLocalVideo"===C?e.createElement(f5,Object.assign({},Re)):"speaker"===C?e.createElement(S5,Object.assign({},Re)):Pe&&"togetherMode"===C?e.createElement(T5,{togetherModeStreamComponent:Pe}):e.createElement(z2,Object.assign({},Re))),[C,Re,_e,Pe]);return e.createElement("div",{id:ne?void 0:re,"data-ui-id":X.videoGallery,ref:ae,className:dB(W1,null==y?void 0:y.root,_5)},Me,e.createElement(J0,{announcementString:Ce,ariaLive:"polite"}))};var A5,P5=oj({cacheSize:100}),R5=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.as,n=void 0===i?"label":i,r=t.children,s=t.className,a=t.disabled,o=t.styles,l=t.required,c=t.theme,d=P5(o,{className:s,disabled:a,required:l,theme:c});return e.createElement(n,IU({},B$(this.props,U$),{className:d.root}),r)},i}(e.Component),M5=nj(R5,(function(e){var t,i=e.theme,n=e.className,r=e.disabled,s=e.required,a=i.semanticColors,o=DV.semibold,l=a.bodyText,c=a.disabledBodyText,d=a.errorText;return{root:["ms-Label",i.fonts.medium,{fontWeight:o,color:l,boxSizing:"border-box",boxShadow:"none",margin:0,display:"block",padding:"5px 0",wordWrap:"break-word",overflowWrap:"break-word"},r&&{color:c,selectors:(t={},t[UV]=IU({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},s&&{selectors:{"::after":{content:"' *'",color:d,paddingRight:12}}},n]}}),void 0,{scope:"Label"}),D5=oj(),k5="TextField",O5=function(t){function i(i){var n=t.call(this,i)||this;n._textElement=e.createRef(),n._onFocus=function(e){n.props.onFocus&&n.props.onFocus(e),n.setState({isFocused:!0},(function(){n.props.validateOnFocusIn&&n._validate(n.value)}))},n._onBlur=function(e){n.props.onBlur&&n.props.onBlur(e),n.setState({isFocused:!1},(function(){n.props.validateOnFocusOut&&n._validate(n.value)}))},n._onRenderLabel=function(t){var i=t.label,r=t.required,s=n._classNames.subComponentStyles?n._classNames.subComponentStyles.label:void 0;return i?e.createElement(M5,{required:r,htmlFor:n._id,styles:s,disabled:t.disabled,id:n._labelId},t.label):null},n._onRenderDescription=function(t){return t.description?e.createElement("span",{className:n._classNames.description},t.description):null},n._onRevealButtonClick=function(e){n.setState((function(e){return{isRevealingPassword:!e.isRevealingPassword}}))},n._onInputChange=function(e){var t,i,r=e.target.value,s=N5(n.props,n.state)||"";void 0!==r&&r!==n._lastChangeValue&&r!==s?(n._lastChangeValue=r,null===(i=(t=n.props).onChange)||void 0===i||i.call(t,e,r),n._isControlled||n.setState({uncontrolledValue:r})):n._lastChangeValue=void 0},Ij(n),n._async=new Mj(n),n._fallbackId=u$(k5),n._descriptionId=u$(k5+"Description"),n._labelId=u$(k5+"Label"),n._prefixId=u$(k5+"Prefix"),n._suffixId=u$(k5+"Suffix"),n._warnControlledUsage();var r=i.defaultValue,s=void 0===r?"":r;return"number"==typeof s&&(s=String(s)),n.state={uncontrolledValue:n._isControlled?void 0:s,isFocused:!1,errorMessage:""},n._delayedValidate=n._async.debounce(n._validate,n.props.deferredValidationTime),n._lastValidation=0,n}return _U(i,t),Object.defineProperty(i.prototype,"value",{get:function(){return N5(this.props,this.state)},enumerable:!1,configurable:!0}),i.prototype.componentDidMount=function(){this._adjustInputHeight(),this.props.validateOnLoad&&this._validate(this.value)},i.prototype.componentWillUnmount=function(){this._async.dispose()},i.prototype.getSnapshotBeforeUpdate=function(e,t){return{selection:[this.selectionStart,this.selectionEnd]}},i.prototype.componentDidUpdate=function(e,t,i){var n=this.props,r=(i||{}).selection,s=void 0===r?[null,null]:r,a=s[0],o=s[1];!!e.multiline!=!!n.multiline&&t.isFocused&&(this.focus(),null!==a&&null!==o&&a>=0&&o>=0&&this.setSelectionRange(a,o)),e.value!==n.value&&(this._lastChangeValue=void 0);var l=N5(e,t),c=this.value;l!==c&&(this._warnControlledUsage(e),this.state.errorMessage&&!n.errorMessage&&this.setState({errorMessage:""}),this._adjustInputHeight(),L5(n)&&this._delayedValidate(c))},i.prototype.render=function(){var t=this.props,i=t.borderless,n=t.className,r=t.disabled,s=t.invalid,a=t.iconProps,o=t.inputClassName,l=t.label,c=t.multiline,d=t.required,u=t.underlined,h=t.prefix,g=t.resizable,p=t.suffix,m=t.theme,f=t.styles,v=t.autoAdjustHeight,S=t.canRevealPassword,y=t.revealPasswordAriaLabel,C=t.type,T=t.onRenderPrefix,E=void 0===T?this._onRenderPrefix:T,b=t.onRenderSuffix,_=void 0===b?this._onRenderSuffix:b,I=t.onRenderLabel,w=void 0===I?this._onRenderLabel:I,A=t.onRenderDescription,P=void 0===A?this._onRenderDescription:A,R=this.state,M=R.isFocused,D=R.isRevealingPassword,k=this._errorMessage,O="boolean"==typeof s?s:!!k,N=!!S&&"password"===C&&function(){if("boolean"!=typeof A5){var e=_B();if(null==e?void 0:e.navigator){var t=/Edg/.test(e.navigator.userAgent||"");A5=!(function(){var e,t=_B();return!!(null===(e=null==t?void 0:t.navigator)||void 0===e?void 0:e.userAgent)&&t.navigator.userAgent.indexOf("rv:11.0")>-1}()||t)}else A5=!0}return A5}(),L=this._classNames=D5(f,{theme:m,className:n,disabled:r,focused:M,required:d,multiline:c,hasLabel:!!l,hasErrorMessage:O,borderless:i,resizable:g,hasIcon:!!a,underlined:u,inputClassName:o,autoAdjustHeight:v,hasRevealButton:N});return e.createElement("div",{ref:this.props.elementRef,className:L.root},e.createElement("div",{className:L.wrapper},w(this.props,this._onRenderLabel),e.createElement("div",{className:L.fieldGroup},(void 0!==h||this.props.onRenderPrefix)&&e.createElement("div",{className:L.prefix,id:this._prefixId},E(this.props,this._onRenderPrefix)),c?this._renderTextArea():this._renderInput(),a&&e.createElement(mG,IU({className:L.icon},a)),N&&e.createElement("button",{"aria-label":y,className:L.revealButton,onClick:this._onRevealButtonClick,"aria-pressed":!!D,type:"button"},e.createElement("span",{className:L.revealSpan},e.createElement(mG,{className:L.revealIcon,iconName:D?"Hide":"RedEye"}))),(void 0!==p||this.props.onRenderSuffix)&&e.createElement("div",{className:L.suffix,id:this._suffixId},_(this.props,this._onRenderSuffix)))),this._isDescriptionAvailable&&e.createElement("span",{id:this._descriptionId},P(this.props,this._onRenderDescription),k&&e.createElement("div",{role:"alert"},e.createElement(dj,null,this._renderErrorMessage()))))},i.prototype.focus=function(){this._textElement.current&&this._textElement.current.focus()},i.prototype.blur=function(){this._textElement.current&&this._textElement.current.blur()},i.prototype.select=function(){this._textElement.current&&this._textElement.current.select()},i.prototype.setSelectionStart=function(e){this._textElement.current&&(this._textElement.current.selectionStart=e)},i.prototype.setSelectionEnd=function(e){this._textElement.current&&(this._textElement.current.selectionEnd=e)},Object.defineProperty(i.prototype,"selectionStart",{get:function(){return this._textElement.current?this._textElement.current.selectionStart:-1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"selectionEnd",{get:function(){return this._textElement.current?this._textElement.current.selectionEnd:-1},enumerable:!1,configurable:!0}),i.prototype.setSelectionRange=function(e,t){this._textElement.current&&this._textElement.current.setSelectionRange(e,t)},i.prototype._warnControlledUsage=function(e){this._id,this.props,null!==this.props.value||this._hasWarnedNullValue||(this._hasWarnedNullValue=!0,jH("Warning: 'value' prop on '".concat(k5,"' should not be null. Consider using an ")+"empty string to clear the component or undefined to indicate an uncontrolled component."))},Object.defineProperty(i.prototype,"_id",{get:function(){return this.props.id||this._fallbackId},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_isControlled",{get:function(){return void 0!==(e=this.props)["value"]&&null!==e.value;var e},enumerable:!1,configurable:!0}),i.prototype._onRenderPrefix=function(t){var i=t.prefix;return e.createElement("span",{style:{paddingBottom:"1px"}},i)},i.prototype._onRenderSuffix=function(t){var i=t.suffix;return e.createElement("span",{style:{paddingBottom:"1px"}},i)},Object.defineProperty(i.prototype,"_errorMessage",{get:function(){var e=this.props.errorMessage;return(void 0===e?this.state.errorMessage:e)||""},enumerable:!1,configurable:!0}),i.prototype._renderErrorMessage=function(){var t=this._errorMessage;return t?"string"==typeof t?e.createElement("p",{className:this._classNames.errorMessage},e.createElement("span",{"data-automation-id":"error-message"},t)):e.createElement("div",{className:this._classNames.errorMessage,"data-automation-id":"error-message"},t):null},Object.defineProperty(i.prototype,"_isDescriptionAvailable",{get:function(){var e=this.props;return!!(e.onRenderDescription||e.description||this._errorMessage)},enumerable:!1,configurable:!0}),i.prototype._renderTextArea=function(){var t=this.props.invalid,i=void 0===t?!!this._errorMessage:t,n=B$(this.props,w$,["defaultValue"]),r=this.props["aria-labelledby"]||(this.props.label?this._labelId:void 0);return e.createElement("textarea",IU({id:this._id},n,{ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-labelledby":r,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":i,"aria-label":this.props.ariaLabel,readOnly:this.props.readOnly,onFocus:this._onFocus,onBlur:this._onBlur}))},i.prototype._renderInput=function(){var t=this.props,i=t.ariaLabel,n=t.invalid,r=void 0===n?!!this._errorMessage:n,s=t.onRenderPrefix,a=t.onRenderSuffix,o=t.prefix,l=t.suffix,c=t.type,d=void 0===c?"text":c,u=[];t.label&&u.push(this._labelId),(void 0!==o||s)&&u.push(this._prefixId),(void 0!==l||a)&&u.push(this._suffixId);var h=IU(IU({type:this.state.isRevealingPassword?"text":d,id:this._id},B$(this.props,I$,["defaultValue","type"])),{"aria-labelledby":this.props["aria-labelledby"]||(u.length>0?u.join(" "):void 0),ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-label":i,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":r,onFocus:this._onFocus,onBlur:this._onBlur}),g=function(t){return e.createElement("input",IU({},t))};return(this.props.onRenderInput||g)(h,g)},i.prototype._validate=function(e){var t=this;if(this._latestValidateValue!==e||!L5(this.props)){this._latestValidateValue=e;var i=this.props.onGetErrorMessage,n=i&&i(e||"");if(void 0!==n)if("string"!=typeof n&&"then"in n){var r=++this._lastValidation;n.then((function(i){r===t._lastValidation&&t.setState({errorMessage:i}),t._notifyAfterValidate(e,i)}))}else this.setState({errorMessage:n}),this._notifyAfterValidate(e,n);else this._notifyAfterValidate(e,"")}},i.prototype._notifyAfterValidate=function(e,t){e===this.value&&this.props.onNotifyValidationResult&&this.props.onNotifyValidationResult(t,e)},i.prototype._adjustInputHeight=function(){var e,t;if(this._textElement.current&&this.props.autoAdjustHeight&&this.props.multiline){var i=null===(t=null===(e=this.props.scrollContainerRef)||void 0===e?void 0:e.current)||void 0===t?void 0:t.scrollTop,n=this._textElement.current;n.style.height="",n.style.height=n.scrollHeight+"px",i&&(this.props.scrollContainerRef.current.scrollTop=i)}},i.defaultProps={resizable:!0,deferredValidationTime:200,validateOnLoad:!0},i}(e.Component);function N5(e,t){var i=e.value,n=void 0===i?t.uncontrolledValue:i;return"number"==typeof n?String(n):n}function L5(e){return!(e.validateOnFocusIn||e.validateOnFocusOut)}var x5={root:"ms-TextField",description:"ms-TextField-description",errorMessage:"ms-TextField-errorMessage",field:"ms-TextField-field",fieldGroup:"ms-TextField-fieldGroup",prefix:"ms-TextField-prefix",suffix:"ms-TextField-suffix",wrapper:"ms-TextField-wrapper",revealButton:"ms-TextField-reveal",multiline:"ms-TextField--multiline",borderless:"ms-TextField--borderless",underlined:"ms-TextField--underlined",unresizable:"ms-TextField--unresizable",required:"is-required",disabled:"is-disabled",active:"is-active"};function F5(e){var t=e.underlined,i=e.disabled,n=e.focused,r=e.theme,s=r.palette,a=r.fonts;return function(){var e;return{root:[t&&i&&{color:s.neutralTertiary},t&&{fontSize:a.medium.fontSize,marginRight:8,paddingLeft:12,paddingRight:0,lineHeight:"22px",height:32},t&&n&&{selectors:(e={},e[UV]={height:31},e)}]}}}var U5=nj(O5,(function(e){var t,i,n,r,s,a,o,l,c,d,u,h,g=e.theme,p=e.className,m=e.disabled,f=e.focused,v=e.required,S=e.multiline,y=e.hasLabel,C=e.borderless,T=e.underlined,E=e.hasIcon,b=e.resizable,_=e.hasErrorMessage,I=e.inputClassName,w=e.autoAdjustHeight,A=e.hasRevealButton,P=g.semanticColors,R=g.effects,M=g.fonts,D=FV(x5,g),k={background:P.disabledBackground,color:m?P.disabledText:P.inputPlaceholderText,display:"flex",alignItems:"center",padding:"0 10px",lineHeight:1,whiteSpace:"nowrap",flexShrink:0,selectors:(t={},t[UV]={background:"Window",color:m?"GrayText":"WindowText"},t)},O=[{color:P.inputPlaceholderText,opacity:1,selectors:(i={},i[UV]={color:"GrayText"},i)}],N={color:P.disabledText,selectors:(n={},n[UV]={color:"GrayText"},n)};return{root:[D.root,M.medium,v&&D.required,m&&D.disabled,f&&D.active,S&&D.multiline,C&&D.borderless,T&&D.underlined,VH,{position:"relative"},p],wrapper:[D.wrapper,T&&[{display:"flex",borderBottom:"1px solid ".concat(_?P.errorText:P.inputBorder),width:"100%"},m&&{borderBottomColor:P.disabledBackground,selectors:(r={},r[UV]=IU({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)},!m&&{selectors:{":hover":{borderBottomColor:_?P.errorText:P.inputBorderHovered,selectors:(s={},s[UV]=IU({borderBottomColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)}}},f&&[{position:"relative"},JV(_?P.errorText:P.inputFocusBorderAlt,0,"borderBottom")]]],fieldGroup:[D.fieldGroup,VH,{border:"1px solid ".concat(P.inputBorder),borderRadius:R.roundedCorner2,background:P.inputBackground,cursor:"text",height:32,display:"flex",flexDirection:"row",alignItems:"stretch",position:"relative"},S&&{minHeight:"60px",height:"auto",display:"flex"},!f&&!m&&{selectors:{":hover":{borderColor:P.inputBorderHovered,selectors:(a={},a[UV]=IU({borderColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),a)}}},f&&!T&&JV(_?P.errorText:P.inputFocusBorderAlt,R.roundedCorner2),m&&{borderColor:P.disabledBackground,selectors:(o={},o[UV]=IU({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o),cursor:"default"},C&&{border:"none"},C&&f&&{border:"none",selectors:{":after":{border:"none"}}},T&&{flex:"1 1 0px",border:"none",textAlign:"left"},T&&m&&{backgroundColor:"transparent"},_&&!T&&{borderColor:P.errorText,selectors:{"&:hover":{borderColor:P.errorText}}},!y&&v&&{selectors:(l={":before":{content:"'*'",color:P.errorText,position:"absolute",top:-5,right:-10}},l[UV]={selectors:{":before":{color:"WindowText",right:-14}}},l)}],field:[M.medium,D.field,VH,{borderRadius:0,border:"none",background:"none",backgroundColor:"transparent",color:P.inputText,padding:"0 8px",width:"100%",minWidth:0,textOverflow:"ellipsis",outline:0,selectors:(c={"&:active, &:focus, &:hover":{outline:0},"::-ms-clear":{display:"none"}},c[UV]={background:"Window",color:m?"GrayText":"WindowText"},c)},$H(O),S&&!b&&[D.unresizable,{resize:"none"}],S&&{minHeight:"inherit",lineHeight:17,flexGrow:1,paddingTop:6,paddingBottom:6,overflow:"auto",width:"100%"},S&&w&&{overflow:"hidden"},E&&!A&&{paddingRight:24},S&&E&&{paddingRight:40},m&&[{backgroundColor:P.disabledBackground,color:P.disabledText,borderColor:P.disabledBackground},$H(N)],T&&{textAlign:"left"},f&&!C&&{selectors:(d={},d[UV]={paddingLeft:11,paddingRight:11},d)},f&&S&&!C&&{selectors:(u={},u[UV]={paddingTop:4},u)},I],icon:[S&&{paddingRight:24,alignItems:"flex-end"},{pointerEvents:"none",position:"absolute",bottom:6,right:8,top:"auto",fontSize:kV.medium,lineHeight:18},m&&{color:P.disabledText}],description:[D.description,{color:P.bodySubtext,fontSize:M.xSmall.fontSize}],errorMessage:[D.errorMessage,OV.slideDownIn20,M.small,{color:P.errorText,margin:0,paddingTop:5,display:"flex",alignItems:"center"}],prefix:[D.prefix,k],suffix:[D.suffix,k],revealButton:[D.revealButton,"ms-Button","ms-Button--icon",KV(g,{inset:1}),{height:30,width:32,border:"none",padding:"0px 4px",backgroundColor:"transparent",color:P.link,selectors:{":hover":{outline:0,color:P.primaryButtonBackgroundHovered,backgroundColor:P.buttonBackgroundHovered,selectors:(h={},h[UV]={borderColor:"Highlight",color:"Highlight"},h)},":focus":{outline:0}}},E&&{marginRight:28}],revealSpan:{display:"flex",height:"100%",alignItems:"center"},revealIcon:{margin:"0px 4px",pointerEvents:"none",bottom:6,right:8,top:"auto",fontSize:kV.medium,lineHeight:18},subComponentStyles:{label:F5(e)}}}),void 0,{scope:"TextField"});const B5=dB({marginRight:vJ(8)}),V5=dB({fontWeight:400,fontSize:vJ(12),lineHeight:vJ(16)}),H5=dB({paddingBottom:vJ(10)}),$5=e=>dB({backgroundColor:e.palette.themeLighter,color:e.palette.themeDarker,borderRadius:vJ(4),marginLeft:vJ(4),fontWeight:400,paddingLeft:vJ(4),paddingRight:vJ(4),fontSize:vJ(11),lineHeight:vJ(16)}),j5=(e,t)=>dB({borderLeft:t?`2px solid ${e.palette.themeLighter}`:"none"}),G5=e=>({root:{marginBottom:vJ(8)},fieldGroup:{borderRadius:vJ(4),borderColor:e.palette.neutralQuaternaryAlt}}),q5=e=>({root:{color:e.palette.neutralPrimary,width:"1rem",height:"1rem"},rootHovered:{color:e.palette.neutralDark}}),z5=dB({fontWeight:400,fontSize:vJ(16),lineHeight:vJ(22),width:"100%"}),W5=dB({height:"100%",margin:0,overflow:"auto",padding:0,overflowX:"hidden"}),K5=dB({marginTop:vJ(6),marginBottom:vJ(6),textAlign:"unset",overflowAnchor:"auto"}),J5={listStyleType:"none",padding:0,margin:0},Y5=(e,t)=>dB(Object.assign(Object.assign({},J5),{overflowX:"hidden",height:"compact"===e?t?"40vh":"4.5rem":"8.75rem",overflowY:"auto"})),Q5=e=>dB(Object.assign(Object.assign({},J5),{overflowX:"hidden",overflowY:"auto",height:"100%",width:"100%",position:"absolute",backgroundColor:e.palette.white,left:0})),Z5=e=>({root:{height:"compact"===e?"4.5rem":"8.75rem"}}),X5=e=>({root:{height:"100%",width:"100%",position:"absolute",left:0,backgroundColor:e.palette.white}}),e4=dB({width:"100%",paddingInlineEnd:vJ(4)}),t4=dB({overflow:"hidden",textOverflow:"ellipsis"}),i4=t=>{const{displayName:i,userId:n,captionText:r,onRenderAvatar:s}=t,a={hidePersonaDetails:!0,size:HZ.size32,text:i,showOverflowTooltip:!1,imageShouldStartVisible:!0,initialsTextColor:"white",styles:{root:{margin:"0.25rem"}}},o=s?s(null!=n?n:"",a):e.createElement(RX,Object.assign({},a));return e.createElement(Y$,{horizontal:!0,verticalAlign:"start",horizontalAlign:"start"},e.createElement(Y$.Item,{className:B5},o),e.createElement(Y$,{verticalAlign:"start",className:e4},e.createElement(Y$.Item,{className:t4},e.createElement(oJ,{className:V5},i)),e.createElement(Y$.Item,{className:z5,dir:"auto"},r)))},n4=t=>{const{displayName:i,userId:n,message:r,onRenderAvatar:s,isTyping:a}=t,o=qK(),l=AK().strings.realTimeText,c=Object.assign(Object.assign({},l),t.strings),d={hidePersonaDetails:!0,size:HZ.size32,text:i,showOverflowTooltip:!1,imageShouldStartVisible:!0,initialsTextColor:"white",styles:{root:{margin:"0.25rem"}}},u=s?s(null!=n?n:"",d):e.createElement(RX,Object.assign({},d));return e.createElement(Y$,{horizontal:!0,verticalAlign:"start",horizontalAlign:"start",className:j5(o,null!=a&&a)},e.createElement(Y$.Item,{className:B5},u),e.createElement(Y$,{verticalAlign:"start",className:e4},e.createElement(Y$,{className:t4,horizontal:!0},e.createElement(oJ,{className:V5},i),a&&e.createElement(oJ,{className:$5(o)},null==c?void 0:c.isTypingText)),e.createElement(Y$.Item,{className:z5,dir:"auto"},r)))},r4=e=>({root:{boxShadow:e.effects.elevation8,width:"fit-content",padding:"0.75rem",borderRadius:"0.25rem",position:"relative",backgroundColor:e.palette.white}}),s4=t=>{var i;const n=t.strings,r=qK();return e.createElement(EJ,{notificationStrings:{title:null!==(i=null==n?void 0:n.bannerTitle)&&void 0!==i?i:"",message:null==n?void 0:n.bannerContent,linkLabel:null==n?void 0:n.bannerLinkLabel},notificationIconProps:{iconName:"RealTimeTextIcon",styles:{root:{fontSize:"1.5rem",paddingRight:"0.5rem"}}},onClickLink:t.onClickLink,styles:{root:r4(r)}})},a4=e=>({main:{borderRadius:e.effects.roundedCorner6,padding:vJ(24),width:vJ(440),height:"fit-content",overflowY:"auto"}}),o4=dB({fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28)}),l4=dB({paddingBottom:vJ(20)}),c4=dB({paddingTop:vJ(16)}),d4=e=>dB({fontWeight:400,fontSize:vJ(12),lineHeight:vJ(16),color:e.palette.neutralSecondary,paddingBottom:vJ(24)}),u4=dB({paddingTop:vJ(16)}),h4=e=>({root:{borderRadius:vJ(2),margin:vJ(8)},rootHovered:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white},rootFocused:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white},rootPressed:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white}}),g4={callout:{height:vJ(300),overflow:"auto"},dropdownOptionText:{textWrap:"auto",overflow:"unset"}},p4=t=>{var i,n,r;const{captions:s,realTimeTexts:a,isCaptionsOn:o,startCaptionsInProgress:l,onRenderAvatar:c,formFactor:d="default",captionsOptions:u,isRealTimeTextOn:h,onSendRealTimeText:g,latestLocalRealTimeText:p}=t,m=AK().strings.captionsBanner,f=Object.assign(Object.assign({},m),t.strings),v=(0,e.useRef)(null),[S,y]=(0,e.useState)(!0),C=qK(),[T,E]=(0,e.useState)(!1),b=(0,e.useMemo)((()=>{var e;return function(e,t){const i=[...Array.isArray(e)?e.map((e=>Object.assign({},e))):[],...t?t.map((e=>Object.assign({},e))):[]];return i.sort(((e,t)=>{var i,n;return("captionText"in e?new Date(null!==(i=e.createdTimeStamp)&&void 0!==i?i:0).getTime():new Date(e.finalizedTimeStamp).getTime())-("captionText"in t?new Date(null!==(n=t.createdTimeStamp)&&void 0!==n?n:0).getTime():new Date(t.finalizedTimeStamp).getTime())})),i}(s,null!==(e=null==a?void 0:a.completedMessages)&&void 0!==e?e:[])}),[s,null==a?void 0:a.completedMessages]),_=(0,e.useMemo)((()=>{var e;return[...b,...null!==(e=null==a?void 0:a.currentInProgress)&&void 0!==e?e:[],null==a?void 0:a.myInProgress].slice(-50)}),[b,a]),I=(0,e.useCallback)((()=>{if(!v.current)return;const e=Math.ceil(v.current.scrollTop)>=v.current.scrollHeight-v.current.clientHeight-20;y(e)}),[]);(0,e.useEffect)((()=>{const e=v.current;return null==e||e.addEventListener("scroll",I),()=>{null==e||e.removeEventListener("scroll",I)}}),[I,o,h]),(0,e.useEffect)((()=>{S&&v.current&&(v.current.scrollTop=v.current.scrollHeight)}),[s,a,S]);const[w,A]=(0,e.useState)("");(0,e.useEffect)((()=>{p&&!p.isTyping&&A("")}),[p]);const P={bannerTitle:null!==(i=f.realTimeTextBannerTitle)&&void 0!==i?i:"",bannerContent:null!==(n=f.realTimeTextBannerContent)&&void 0!==n?n:"",bannerLinkLabel:null!==(r=f.realTimeTextBannerLinkLabel)&&void 0!==r?r:""};return e.createElement(e.Fragment,null,(l||o||h)&&e.createElement(iq,{shouldFocusOnMount:!0,className:W5,"data-ui-id":"captions-banner"},(o||h)&&"compact"===d&&e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:H5},e.createElement(oJ,{className:o4},(()=>{var e,t,i;return o&&h?null!==(e=f.captionsAndRealTimeTextContainerTitle)&&void 0!==e?e:"":o?null!==(t=f.captionsOnlyContainerTitle)&&void 0!==t?t:"":h&&null!==(i=f.realTimeTextOnlyContainerTitle)&&void 0!==i?i:""})()),e.createElement(oK,{iconProps:{iconName:T?"MinimizeIcon":"ExpandIcon"},ariaLabel:T?f.minimizeButtonAriaLabel:f.expandButtonAriaLabel,onClick:()=>E(!T),styles:q5(C)})),(o||h)&&e.createElement("ul",{ref:v,className:"full"===(null==u?void 0:u.height)?Q5(C):Y5(d,T),"data-ui-id":"captions-banner-inner"},h&&e.createElement(Y$,{className:dB({padding:"0.25rem",paddingTop:"0.5rem"})},e.createElement(s4,{strings:P})),e.createElement(e.Fragment,null,_.map((t=>t?"message"in t?e.createElement("li",{key:`RealTimeText - ${t.id}`,className:K5,"data-is-focusable":!0},e.createElement(n4,Object.assign({},t))):e.createElement("li",{key:`Captions - ${t.id}`,className:K5,"data-is-focusable":!0},e.createElement(i4,Object.assign({},t,{onRenderAvatar:c}))):e.createElement(e.Fragment,null))))),h&&g&&e.createElement(U5,{styles:G5(C),placeholder:f.realTimeTextInputBoxDefaultText,value:w,onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),w&&g&&(g(w,!0),A("")))},onChange:(e,t)=>{A(t||""),g(t||"",!1)},maxLength:2e3,errorMessage:w.length>=2e3?f.realTimeTextInputErrorMessage:void 0}),!o&&!h&&e.createElement(Y$,{verticalAlign:"center",styles:"full"===(null==u?void 0:u.height)?X5(C):Z5(d),"data-is-focusable":!0},e.createElement(yZ,{label:null==f?void 0:f.captionsBannerSpinnerText,ariaLive:"assertive",labelPosition:"right"}))))};var m4,f4=SB((function(e,t){var i,n,r;return ZH(rK(e),{root:(i={padding:"0 4px",height:"40px",color:e.palette.neutralPrimary,backgroundColor:"transparent",border:"1px solid transparent"},i[UV]={borderColor:"Window"},i),rootHovered:(n={color:e.palette.themePrimary},n[UV]={color:"Highlight"},n),iconHovered:{color:e.palette.themePrimary},rootPressed:{color:e.palette.black},rootExpanded:{color:e.palette.themePrimary},iconPressed:{color:e.palette.themeDarker},rootDisabled:(r={color:e.palette.neutralTertiary,backgroundColor:"transparent",borderColor:"transparent"},r[UV]={color:"GrayText"},r),rootChecked:{color:e.palette.black},iconChecked:{color:e.palette.themeDarker},flexContainer:{justifyContent:"flex-start"},icon:{color:e.palette.themeDarkAlt},iconDisabled:{color:"inherit"},menuIcon:{color:e.palette.neutralSecondary},textContainer:{flexGrow:0}},t)})),v4=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(KW,IU({},this.props,{variantClassName:"ms-Button--action ms-Button--command",styles:f4(n,i),onRenderDescription:Fj}))},AU([XW("ActionButton",["theme","styles"],!0)],i)}(e.Component),S4=v4;!function(e){e[e.Normal=0]="Normal",e[e.Divider=1]="Divider",e[e.Header=2]="Header",e[e.SelectAll=3]="SelectAll"}(m4||(m4={}));var y4,C4=function(){function e(){this._size=0}return e.prototype.updateOptions=function(e){for(var t=[],i=[],n=0,r=0;r<e.length;r++){var s=e[r],a=s.itemType,o=s.hidden;a===m4.Divider||a===m4.Header?(t.push(r),i.push(r)):o?i.push(r):n++}this._size=n,this._displayOnlyOptionsCache=t,this._notSelectableOptionsCache=i,this._cachedOptions=PU([],e,!0)},Object.defineProperty(e.prototype,"optionSetSize",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cachedOptions",{get:function(){return this._cachedOptions},enumerable:!1,configurable:!0}),e.prototype.positionInSet=function(e){if(void 0!==e){for(var t=0;e>this._notSelectableOptionsCache[t];)t++;if(this._displayOnlyOptionsCache[t]===e)throw new Error("Unexpected: Option at index ".concat(e," is not a selectable element."));if(this._notSelectableOptionsCache[t]!==e)return e-t+1}},e}();!function(e){e[e.smallFluid=0]="smallFluid",e[e.smallFixedFar=1]="smallFixedFar",e[e.smallFixedNear=2]="smallFixedNear",e[e.medium=3]="medium",e[e.large=4]="large",e[e.largeFixed=5]="largeFixed",e[e.extraLarge=6]="extraLarge",e[e.custom=7]="custom",e[e.customNear=8]="customNear"}(y4||(y4={}));var T4,E4=oj();!function(e){e[e.closed=0]="closed",e[e.animatingOpen=1]="animatingOpen",e[e.open=2]="open",e[e.animatingClosed=3]="animatingClosed"}(T4||(T4={}));var b4,_4,I4,w4,A4,P4=function(t){function i(i){var n=t.call(this,i)||this;n._panel=e.createRef(),n._animationCallback=null,n._hasCustomNavigation=!(!n.props.onRenderNavigation&&!n.props.onRenderNavigationContent),n.dismiss=function(e){n.props.onDismiss&&n.isActive&&n.props.onDismiss(e),(!e||e&&!e.defaultPrevented)&&n.close()},n._allowScrollOnPanel=function(e){var t;n._resizeObserver=n._createResizeObserver((function(t){t.length>0&&t[0].target===e&&n._updateFooterPosition()})),e?(null===(t=n._resizeObserver)||void 0===t||t.observe(e),n._allowTouchBodyScroll?UG(e,n._events):FG(e,n._events)):n._events.off(n._scrollableContent),n._scrollableContent=e},n._onRenderNavigation=function(t){if(!n.props.onRenderNavigationContent&&!n.props.onRenderNavigation&&!n.props.hasCloseButton)return null;var i=n.props.onRenderNavigationContent,r=void 0===i?n._onRenderNavigationContent:i;return e.createElement("div",{className:n._classNames.navigation},r(t,n._onRenderNavigationContent))},n._onRenderNavigationContent=function(t){var i,r=t.closeButtonAriaLabel,s=t.hasCloseButton,a=t.onRenderHeader,o=void 0===a?n._onRenderHeader:a;if(s){var l=null===(i=n._classNames.subComponentStyles)||void 0===i?void 0:i.closeButton();return e.createElement(e.Fragment,null,!n._hasCustomNavigation&&o(n.props,n._onRenderHeader,n._headerTextId),e.createElement(oK,{styles:l,className:n._classNames.closeButton,onClick:n._onPanelClick,ariaLabel:r,title:r,"data-is-visible":!0,iconProps:{iconName:"Cancel"}}))}return null},n._onRenderHeader=function(t,i,r){var s=t.headerText,a=t.headerTextProps,o=void 0===a?{}:a;return s?e.createElement("div",{className:n._classNames.header},e.createElement("div",IU({id:r,role:"heading","aria-level":1},o,{className:V$(n._classNames.headerText,o.className)}),s)):null},n._onRenderBody=function(t){return e.createElement("div",{className:n._classNames.content},t.children)},n._onRenderFooter=function(t){var i=n.props.onRenderFooterContent,r=void 0===i?null:i;return r?e.createElement("div",{className:n._classNames.footer},e.createElement("div",{className:n._classNames.footerInner},r())):null},n._animateTo=function(e){e===T4.open&&n.props.onOpen&&n.props.onOpen(),n._animationCallback=n._async.setTimeout((function(){n.setState({visibility:e}),n._onTransitionComplete(e)}),200)},n._clearExistingAnimationTimer=function(){null!==n._animationCallback&&n._async.clearTimeout(n._animationCallback)},n._onPanelClick=function(e){n.dismiss(e)},n._onTransitionComplete=function(e){n._updateFooterPosition(),e===T4.open&&n.props.onOpened&&n.props.onOpened(),e===T4.closed&&n.props.onDismissed&&n.props.onDismissed()};var r=n.props.allowTouchBodyScroll,s=void 0!==r&&r;return n._allowTouchBodyScroll=s,Ij(n),n.state={isFooterSticky:!1,visibility:T4.closed,id:u$("Panel")},n}return _U(i,t),i.getDerivedStateFromProps=function(e,t){return void 0===e.isOpen?null:!e.isOpen||t.visibility!==T4.closed&&t.visibility!==T4.animatingClosed?e.isOpen||t.visibility!==T4.open&&t.visibility!==T4.animatingOpen?null:{visibility:T4.animatingClosed}:{visibility:T4.animatingOpen}},i.prototype.componentDidMount=function(){this._async=new Mj(this),this._events=new Lj(this);var e=rz(this.context),t=nz(this.context);this._events.on(e,"resize",this._updateFooterPosition),this._shouldListenForOuterClick(this.props)&&this._events.on(null==t?void 0:t.body,"mousedown",this._dismissOnOuterClick,!0),this.props.isOpen&&this.setState({visibility:T4.animatingOpen})},i.prototype.componentDidUpdate=function(e,t){var i=this._shouldListenForOuterClick(this.props),n=this._shouldListenForOuterClick(e);this.state.visibility!==t.visibility&&(this._clearExistingAnimationTimer(),this.state.visibility===T4.animatingOpen?this._animateTo(T4.open):this.state.visibility===T4.animatingClosed&&this._animateTo(T4.closed));var r=nz(this.context);i&&!n?this._events.on(null==r?void 0:r.body,"mousedown",this._dismissOnOuterClick,!0):!i&&n&&this._events.off(null==r?void 0:r.body,"mousedown",this._dismissOnOuterClick,!0)},i.prototype.componentWillUnmount=function(){var e;this._async.dispose(),this._events.dispose(),null===(e=this._resizeObserver)||void 0===e||e.disconnect()},i.prototype.render=function(){var t=this.props,i=t.className,n=void 0===i?"":i,r=t.elementToFocusOnDismiss,s=t.firstFocusableSelector,a=t.focusTrapZoneProps,o=t.forceFocusInsideTrap,l=t.hasCloseButton,c=t.headerText,d=t.headerClassName,u=void 0===d?"":d,h=t.ignoreExternalFocusing,g=t.isBlocking,p=t.isFooterAtBottom,m=t.isLightDismiss,f=t.isHiddenOnDismiss,v=t.layerProps,S=t.overlayProps,y=t.popupProps,C=t.type,T=t.styles,E=t.theme,b=t.customWidth,_=t.onLightDismissClick,I=void 0===_?this._onPanelClick:_,w=t.onRenderNavigation,A=void 0===w?this._onRenderNavigation:w,P=t.onRenderHeader,R=void 0===P?this._onRenderHeader:P,M=t.onRenderBody,D=void 0===M?this._onRenderBody:M,k=t.onRenderFooter,O=void 0===k?this._onRenderFooter:k,N=this.state,L=N.isFooterSticky,x=N.visibility,F=N.id,U=C===y4.smallFixedNear||C===y4.customNear,B=PB(E)?U:!U,V=C===y4.custom||C===y4.customNear?{width:b}:{},H=B$(this.props,U$),$=this.isActive,j=x===T4.animatingClosed||x===T4.animatingOpen;if(this._headerTextId=c&&F+"-headerText",!$&&!j&&!f)return null;this._classNames=E4(T,{theme:E,className:n,focusTrapZoneClassName:a?a.className:void 0,hasCloseButton:l,headerClassName:u,isAnimating:j,isFooterSticky:L,isFooterAtBottom:p,isOnRightSide:B,isOpen:$,isHiddenOnDismiss:f,type:C,hasCustomNavigation:this._hasCustomNavigation});var G,q=this._classNames,z=this._allowTouchBodyScroll;return g&&$&&(G=e.createElement(Z2,IU({className:q.overlay,isDarkThemed:!1,onClick:m?I:void 0,allowTouchBodyScroll:z},S))),e.createElement(Hz,IU({},v),e.createElement(Zq,IU({role:"dialog","aria-modal":g?"true":void 0,ariaLabelledBy:this._headerTextId?this._headerTextId:void 0,onDismiss:this.dismiss,className:q.hiddenPanel,enableAriaHiddenSiblings:!!$},y),e.createElement("div",IU({"aria-hidden":!$&&j},H,{ref:this._panel,className:q.root}),G,e.createElement(x0,IU({ignoreExternalFocusing:h,forceFocusInsideTrap:!(!g||f&&!$)&&o,firstFocusableSelector:s,isClickableOutsideFocusTrap:!0},a,{className:q.main,style:V,elementToFocusOnDismiss:r}),e.createElement("div",{className:q.contentInner},e.createElement("div",{ref:this._allowScrollOnPanel,className:q.scrollableContent,"data-is-scrollable":!0},e.createElement("div",{className:q.commands,"data-is-visible":!0},A(this.props,this._onRenderNavigation)),(this._hasCustomNavigation||!l)&&R(this.props,this._onRenderHeader,this._headerTextId),D(this.props,this._onRenderBody),O(this.props,this._onRenderFooter)))))))},i.prototype.open=function(){void 0===this.props.isOpen&&(this.isActive||this.setState({visibility:T4.animatingOpen}))},i.prototype.close=function(){void 0===this.props.isOpen&&this.isActive&&this.setState({visibility:T4.animatingClosed})},Object.defineProperty(i.prototype,"isActive",{get:function(){return this.state.visibility===T4.open||this.state.visibility===T4.animatingOpen},enumerable:!1,configurable:!0}),i.prototype._createResizeObserver=function(e){var t,i=nz(this.context),n=null;return(null===(t=null==i?void 0:i.defaultView)||void 0===t?void 0:t.ResizeObserver)&&(n=new i.defaultView.ResizeObserver(e)),n},i.prototype._shouldListenForOuterClick=function(e){return!!e.isBlocking&&!!e.isOpen},i.prototype._updateFooterPosition=function(){var e=this._scrollableContent;if(e){var t=e.clientHeight,i=e.scrollHeight;this.setState({isFooterSticky:t<i})}},i.prototype._dismissOnOuterClick=function(e){var t=this._panel.current;this.isActive&&t&&!e.defaultPrevented&&(CG(t,e.target)||(this.props.onOuterClick?this.props.onOuterClick(e):this.dismiss(e)))},i.defaultProps={isHiddenOnDismiss:!1,isOpen:void 0,isBlocking:!0,hasCloseButton:!0,type:y4.smallFixedFar},i.contextType=Kq,i}(e.Component),R4={root:"ms-Panel",main:"ms-Panel-main",commands:"ms-Panel-commands",contentInner:"ms-Panel-contentInner",scrollableContent:"ms-Panel-scrollableContent",navigation:"ms-Panel-navigation",closeButton:"ms-Panel-closeButton ms-PanelAction-close",header:"ms-Panel-header",headerText:"ms-Panel-headerText",content:"ms-Panel-content",footer:"ms-Panel-footer",footerInner:"ms-Panel-footerInner",isOpen:"is-open",hasCloseButton:"ms-Panel--hasCloseButton",smallFluid:"ms-Panel--smFluid",smallFixedNear:"ms-Panel--smLeft",smallFixedFar:"ms-Panel--sm",medium:"ms-Panel--md",large:"ms-Panel--lg",largeFixed:"ms-Panel--fixed",extraLarge:"ms-Panel--xl",custom:"ms-Panel--custom",customNear:"ms-Panel--customLeft"},M4="auto",D4=((b4={})["@media (min-width: ".concat(VV,"px)")]={width:340},b4),k4=((_4={})["@media (min-width: ".concat(640,"px)")]={width:592},_4["@media (min-width: ".concat(1024,"px)")]={width:644},_4),O4=((I4={})["@media (min-width: ".concat(768,"px)")]={left:48,width:"auto"},I4["@media (min-width: ".concat(HV,"px)")]={left:428},I4),N4=((w4={})["@media (min-width: ".concat(HV,"px)")]={left:M4,width:940},w4),L4=((A4={})["@media (min-width: ".concat(HV,"px)")]={left:176},A4),x4=function(e){var t;switch(e){case y4.smallFixedFar:t=IU({},D4);break;case y4.medium:t=IU(IU({},D4),k4);break;case y4.large:t=IU(IU(IU({},D4),k4),O4);break;case y4.largeFixed:t=IU(IU(IU(IU({},D4),k4),O4),N4);break;case y4.extraLarge:t=IU(IU(IU(IU({},D4),k4),O4),L4)}return t},F4={paddingLeft:"24px",paddingRight:"24px"},U4=nj(P4,(function(e){var t,i,n,r,s=e.className,a=e.focusTrapZoneClassName,o=e.hasCloseButton,l=e.headerClassName,c=e.isAnimating,d=e.isFooterSticky,u=e.isFooterAtBottom,h=e.isOnRightSide,g=e.isOpen,p=e.isHiddenOnDismiss,m=e.hasCustomNavigation,f=e.theme,v=e.type,S=void 0===v?y4.smallFixedFar:v,y=f.effects,C=f.fonts,T=f.semanticColors,E=FV(R4,f),b=S===y4.custom||S===y4.customNear;return{root:[E.root,f.fonts.medium,g&&E.isOpen,o&&E.hasCloseButton,{pointerEvents:"none",position:"absolute",top:0,left:0,right:0,bottom:0},b&&h&&E.custom,b&&!h&&E.customNear,s],overlay:[{pointerEvents:"auto",cursor:"pointer"},g&&c&&OV.fadeIn100,!g&&c&&OV.fadeOut100],hiddenPanel:[!g&&!c&&p&&{visibility:"hidden"}],main:[E.main,{backgroundColor:T.bodyBackground,boxShadow:y.elevation64,pointerEvents:"auto",position:"absolute",display:"flex",flexDirection:"column",overflowX:"hidden",overflowY:"auto",WebkitOverflowScrolling:"touch",bottom:0,top:0,left:M4,right:0,width:"100%",selectors:IU((t={},t[UV]={borderLeft:"3px solid ".concat(T.variantBorder),borderRight:"3px solid ".concat(T.variantBorder)},t),x4(S))},S===y4.smallFluid&&{left:0},S===y4.smallFixedNear&&{left:0,right:M4,width:272},S===y4.customNear&&{right:"auto",left:0},b&&{maxWidth:"100vw"},g&&c&&!h&&OV.slideRightIn40,g&&c&&h&&OV.slideLeftIn40,!g&&c&&!h&&OV.slideLeftOut40,!g&&c&&h&&OV.slideRightOut40,a],commands:[E.commands,{backgroundColor:T.bodyBackground,paddingTop:18,selectors:(i={},i["@media (min-height: ".concat(VV,"px)")]={position:"sticky",top:0,zIndex:1},i)},m&&{paddingTop:"inherit"}],navigation:[E.navigation,{display:"flex",justifyContent:"flex-end"},m&&{height:"44px"}],contentInner:[E.contentInner,{display:"flex",flexDirection:"column",flexGrow:1,overflowY:"hidden"}],header:[E.header,F4,{alignSelf:"flex-start"},o&&!m&&{flexGrow:1},m&&{flexShrink:0}],headerText:[E.headerText,C.xLarge,{color:T.bodyText,lineHeight:"27px",overflowWrap:"break-word",wordWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},l],scrollableContent:[E.scrollableContent,{overflowY:"auto"},u&&{flexGrow:1,display:"inherit",flexDirection:"inherit"}],content:[E.content,F4,{paddingBottom:20},u&&{selectors:(n={},n["@media (min-height: ".concat(VV,"px)")]={flexGrow:1},n)}],footer:[E.footer,{flexShrink:0,borderTop:"1px solid transparent",transition:"opacity ".concat(TV," ").concat(yV),selectors:(r={},r["@media (min-height: ".concat(VV,"px)")]={position:"sticky",bottom:0},r)},d&&{backgroundColor:T.bodyBackground,borderTopColor:T.variantBorder}],footerInner:[E.footerInner,F4,{paddingBottom:16,paddingTop:16}],subComponentStyles:{closeButton:{root:[E.closeButton,{marginRight:14,color:f.palette.neutralSecondary,fontSize:kV.large},m&&{marginRight:0,height:"auto",width:"44px"}],rootHovered:{color:f.palette.neutralPrimary}}}}}),void 0,{scope:"Panel"});function B4(e,t){for(var i=[],n=0,r=t;n<r.length;n++){var s=e[r[n]];s&&i.push(s)}return i}function V4(t,i,n){var r=e.useState(i),s=r[0],a=r[1],o=Xq(void 0!==t),l=o?t:s,c=e.useRef(l),d=e.useRef(n);e.useEffect((function(){c.current=l,d.current=n}));var u=Xq((function(){return function(e,t){var i="function"==typeof e?e(c.current):e;d.current&&d.current(t,i),o||a(i)}}));return[l,u]}var H4=oj(),$4=e.forwardRef((function(t,i){var n=t.disabled,r=t.required,s=t.inputProps,a=t.name,o=t.ariaLabel,l=t.ariaLabelledBy,c=t.ariaDescribedBy,d=t.ariaPositionInSet,u=t.ariaSetSize,h=t.title,g=t.checkmarkIconProps,p=t.styles,m=t.theme,f=t.className,v=t.boxSide,S=void 0===v?"start":v,y=g$("checkbox-",t.id),C=e.useRef(null),T=nG(C,i),E=e.useRef(null),b=V4(t.checked,t.defaultChecked,t.onChange),_=b[0],I=b[1],w=V4(t.indeterminate,t.defaultIndeterminate),A=w[0],P=w[1];qj(C);var R=H4(p,{theme:m,className:f,disabled:n,indeterminate:A,checked:_,reversed:"start"!==S,isUsingCustomLabelRender:!!t.onRenderLabel}),M=e.useCallback((function(e){A?(I(!!_,e),P(!1)):I(!_,e)}),[I,P,A,_]),D=e.useCallback((function(t){return t&&t.label?e.createElement("span",{className:R.text,title:t.title},t.label):null}),[R.text]),k=e.useCallback((function(e){if(E.current){var t=!!e;E.current.indeterminate=t,P(t)}}),[P]);!function(t,i,n,r,s){e.useImperativeHandle(t.componentRef,(function(){return{get checked(){return!!i},get indeterminate(){return!!n},set indeterminate(e){r(e)},focus:function(){s.current&&s.current.focus()}}}),[s,i,n,r])}(t,_,A,k,E),e.useEffect((function(){return k(A)}),[k,A]);var O=t.onRenderLabel||D,N=A?"mixed":void 0,L=IU(IU({className:R.input,type:"checkbox"},s),{checked:!!_,disabled:n,required:r,name:a,id:y,title:h,onChange:M,"aria-disabled":n,"aria-label":o,"aria-labelledby":l,"aria-describedby":c,"aria-posinset":d,"aria-setsize":u,"aria-checked":N});return e.createElement("div",{className:R.root,title:h,ref:T},e.createElement("input",IU({},L,{ref:E,title:h,"data-ktp-execute-target":!0})),e.createElement("label",{className:R.label,htmlFor:y},e.createElement("div",{className:R.checkbox,"data-ktp-target":!0},e.createElement(mG,IU({iconName:"CheckMark"},g,{className:R.checkmark}))),O(t,D)))}));$4.displayName="CheckboxBase";var j4={root:"ms-Checkbox",label:"ms-Checkbox-label",checkbox:"ms-Checkbox-checkbox",checkmark:"ms-Checkbox-checkmark",text:"ms-Checkbox-text"},G4="20px",q4="200ms",z4="cubic-bezier(.4, 0, .23, 1)",W4=nj($4,(function(e){var t,i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y=e.className,C=e.theme,T=e.reversed,E=e.checked,b=e.disabled,_=e.isUsingCustomLabelRender,I=e.indeterminate,w=C.semanticColors,A=C.effects,P=C.palette,R=C.fonts,M=FV(j4,C),D=w.inputForegroundChecked,k=P.neutralSecondary,O=P.neutralPrimary,N=w.inputBackgroundChecked,L=w.inputBackgroundChecked,x=w.disabledBodySubtext,F=w.inputBorderHovered,U=w.inputBackgroundCheckedHovered,B=w.inputBackgroundChecked,V=w.inputBackgroundCheckedHovered,H=w.inputBackgroundCheckedHovered,$=w.inputTextHovered,j=w.disabledBodySubtext,G=w.bodyText,q=w.disabledText,z=[(t={content:'""',borderRadius:A.roundedCorner2,position:"absolute",width:10,height:10,top:4,left:4,boxSizing:"border-box",borderWidth:5,borderStyle:"solid",borderColor:b?x:N,transitionProperty:"border-width, border, border-color",transitionDuration:q4,transitionTimingFunction:z4},t[UV]={borderColor:"WindowText"},t)];return{root:[M.root,{position:"relative",display:"flex"},T&&"reversed",E&&"is-checked",!b&&"is-enabled",b&&"is-disabled",!b&&[!E&&(i={},i[":hover .".concat(M.checkbox)]=(n={borderColor:F},n[UV]={borderColor:"Highlight"},n),i[":focus .".concat(M.checkbox)]={borderColor:F},i[":hover .".concat(M.checkmark)]=(r={color:k,opacity:"1"},r[UV]={color:"Highlight"},r),i),E&&!I&&(s={},s[":hover .".concat(M.checkbox)]={background:V,borderColor:H},s[":focus .".concat(M.checkbox)]={background:V,borderColor:H},s[UV]=(a={},a[":hover .".concat(M.checkbox)]={background:"Highlight",borderColor:"Highlight"},a[":focus .".concat(M.checkbox)]={background:"Highlight"},a[":focus:hover .".concat(M.checkbox)]={background:"Highlight"},a[":focus:hover .".concat(M.checkmark)]={color:"Window"},a[":hover .".concat(M.checkmark)]={color:"Window"},a),s),I&&(o={},o[":hover .".concat(M.checkbox,", :hover .").concat(M.checkbox,":after")]=(l={borderColor:U},l[UV]={borderColor:"WindowText"},l),o[":focus .".concat(M.checkbox)]={borderColor:U},o[":hover .".concat(M.checkmark)]={opacity:"0"},o),(c={},c[":hover .".concat(M.text,", :focus .").concat(M.text)]=(d={color:$},d[UV]={color:b?"GrayText":"WindowText"},d),c)],y],input:(u={position:"absolute",background:"none",opacity:0},u[".".concat(GV," &:focus + label::before, :host(.").concat(GV,") &:focus + label::before")]=(h={outline:"1px solid "+C.palette.neutralSecondary,outlineOffset:"2px"},h[UV]={outline:"1px solid WindowText"},h),u),label:[M.label,C.fonts.medium,{display:"flex",alignItems:_?"center":"flex-start",cursor:b?"default":"pointer",position:"relative",userSelect:"none"},T&&{flexDirection:"row-reverse",justifyContent:"flex-end"},{"&::before":{position:"absolute",left:0,right:0,top:0,bottom:0,content:'""',pointerEvents:"none"}}],checkbox:[M.checkbox,(g={position:"relative",display:"flex",flexShrink:0,alignItems:"center",justifyContent:"center",height:G4,width:G4,border:"1px solid ".concat(O),borderRadius:A.roundedCorner2,boxSizing:"border-box",transitionProperty:"background, border, border-color",transitionDuration:q4,transitionTimingFunction:z4,overflow:"hidden",":after":I?z:null},g[UV]=IU({borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),g),I&&{borderColor:N},T?{marginLeft:4}:{marginRight:4},!b&&!I&&E&&(p={background:B,borderColor:L},p[UV]={background:"Highlight",borderColor:"Highlight"},p),b&&(m={borderColor:x},m[UV]={borderColor:"GrayText"},m),E&&b&&(f={background:j,borderColor:x},f[UV]={background:"Window"},f)],checkmark:[M.checkmark,(v={opacity:E&&!I?"1":"0",color:D},v[UV]=IU({color:b?"GrayText":"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),v)],text:[M.text,(S={color:b?q:G,fontSize:R.medium.fontSize,lineHeight:"20px"},S[UV]=IU({color:b?"GrayText":"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),S),T?{marginRight:4}:{marginLeft:4}]}}),void 0,{scope:"Checkbox"}),K4=oj(),J4={options:[]},Y4=e.forwardRef((function(t,i){var n=sq(J4,t),r=e.useRef(null),s=nG(i,r),a=_W(r,n.responsiveMode),o=function(t){var i,n=t.defaultSelectedKeys,r=t.selectedKeys,s=t.defaultSelectedKey,a=t.selectedKey,o=t.options,l=t.multiSelect,c=cW(o),d=e.useState([]),u=d[0],h=d[1],g=o!==c,p=cW(i=l?g&&void 0!==n?n:r:g&&void 0!==s?s:a);return e.useEffect((function(){var e=function(e){return function(e,t,i){void 0===i&&(i=0);for(var n=-1,r=i;e&&r<e.length;r++)if(t(e[r],r)){n=r;break}return n}(o,(function(t){return null!=e?t.key===e:!!t.selected||!!t.isSelected}))};void 0===i&&c||i===p&&!g||h(function(){if(void 0===i)return l?o.map((function(e,t){return e.selected?t:-1})).filter((function(e){return-1!==e})):-1!==(s=e(null))?[s]:[];if(!Array.isArray(i))return-1!==(s=e(i))?[s]:[];for(var t=[],n=0,r=i;n<r.length;n++){var s,a=r[n];-1!==(s=e(a))&&t.push(s)}return t}())}),[g,l,c,p,o,i]),[u,h]}(n),l=o[0],c=o[1];return e.createElement(i3,IU({},n,{responsiveMode:a,hoisted:{rootRef:s,selectedIndices:l,setSelectedIndices:c}}))}));Y4.displayName="DropdownBase";var Q4,Z4,X4,e3,t3,i3=function(t){function i(i){var n,r,s=t.call(this,i)||this;s._host=e.createRef(),s._focusZone=e.createRef(),s._dropDown=e.createRef(),s._scrollIdleDelay=250,s._sizePosCache=new C4,s._requestAnimationFrame=(n=s,function(e){r||(r=new Set,_j(n,{componentWillUnmount:function(){r.forEach((function(e){return cancelAnimationFrame(e)}))}}));var t=requestAnimationFrame((function(){r.delete(t),e()}));r.add(t)}),s.dismissMenu=function(){s.state.isOpen&&s.setState({isOpen:!1})},s._onChange=function(e,t,i,n,r){var a=s.props,o=a.onChange,l=a.onChanged;if(o||l){var c=r?IU(IU({},t[i]),{selected:!n}):t[i];o&&o(IU(IU({},e),{target:s._dropDown.current}),c,i),l&&l(c,i)}},s._getPlaceholder=function(){return s.props.placeholder||s.props.placeHolder},s._getTitle=function(e,t){var i=s.props.multiSelectDelimiter,n=void 0===i?", ":i;return e.map((function(e){return e.text})).join(n)},s._onRenderTitle=function(t){return e.createElement(e.Fragment,null,s._getTitle(t))},s._onRenderPlaceholder=function(t){return s._getPlaceholder()?e.createElement(e.Fragment,null,s._getPlaceholder()):null},s._onRenderContainer=function(t){var i=t.calloutProps,n=t.panelProps,r=s.props,a=r.responsiveMode,o=r.dropdownWidth,l=a<=fW.medium,c={firstFocusableTarget:"#".concat(s._listId,"1")},d=s._classNames.subComponentStyles?s._classNames.subComponentStyles.panel:void 0,u=void 0,h=void 0;return"auto"===o?h=s._dropDown.current?s._dropDown.current.clientWidth:0:u=o||(s._dropDown.current?s._dropDown.current.clientWidth:0),l?e.createElement(U4,IU({closeButtonAriaLabel:"Close",focusTrapZoneProps:c,hasCloseButton:!0,isOpen:!0,isLightDismiss:!0,onDismiss:s._onDismiss,styles:d},n),s._renderFocusableList(t)):e.createElement($z,IU({isBeakVisible:!1,gapSpace:0,doNotLayer:!1,directionalHintFixed:!1,directionalHint:4,calloutWidth:u,calloutMinWidth:h},i,{className:s._classNames.callout,target:s._dropDown.current,onDismiss:s._onDismiss,onScroll:s._onScroll,onPositioned:s._onPositioned}),s._renderFocusableList(t))},s._onRenderCaretDown=function(t){return e.createElement(mG,{className:s._classNames.caretDown,iconName:"ChevronDown","aria-hidden":!0})},s._onRenderList=function(t){var i=t.onRenderItem,n=void 0===i?s._onRenderItem:i,r={items:[]},a=[],o=function(){var t=r.id?[e.createElement("div",{role:"group",key:r.id,"aria-labelledby":r.id},r.items)]:r.items;a=PU(PU([],a,!0),t,!0),r={items:[]}};return t.options.forEach((function(e,t){!function(e,t){switch(e.itemType){case m4.Header:r.items.length>0&&o();var i=s._id+e.key;r.items.push(n(IU(IU({id:i},e),{index:t}),s._onRenderItem)),r.id=i;break;case m4.Divider:t>0&&r.items.push(n(IU(IU({},e),{index:t}),s._onRenderItem)),r.items.length>0&&o();break;default:r.items.push(n(IU(IU({},e),{index:t}),s._onRenderItem))}}(e,t)})),r.items.length>0&&o(),e.createElement(e.Fragment,null,a)},s._onRenderItem=function(e){switch(e.itemType){case m4.Divider:return s._renderSeparator(e);case m4.Header:return s._renderHeader(e);default:return s._renderOption(e)}},s._renderOption=function(t){var i,n=s.props,r=n.onRenderOption,a=void 0===r?s._onRenderOption:r,o=n.hoisted.selectedIndices,l=void 0===o?[]:o,c=!(void 0===t.index||!l)&&l.indexOf(t.index)>-1,d=t.hidden?s._classNames.dropdownItemHidden:c&&!0===t.disabled?s._classNames.dropdownItemSelectedAndDisabled:c?s._classNames.dropdownItemSelected:!0===t.disabled?s._classNames.dropdownItemDisabled:s._classNames.dropdownItem,u=t.title,h=s._listId+t.index,g=null!==(i=t.id)&&void 0!==i?i:h+"-label",p=s._classNames.subComponentStyles?s._classNames.subComponentStyles.multiSelectItem:void 0;return s.props.multiSelect?e.createElement(W4,{id:h,key:t.key,disabled:t.disabled,onChange:s._onItemClick(t),inputProps:IU({"aria-selected":c,onMouseEnter:s._onItemMouseEnter.bind(s,t),onMouseLeave:s._onMouseItemLeave.bind(s,t),onMouseMove:s._onItemMouseMove.bind(s,t),role:"option"},{"data-index":t.index,"data-is-focusable":!(t.disabled||t.hidden)}),label:t.text,title:u,onRenderLabel:s._onRenderItemLabel.bind(s,IU(IU({},t),{id:g})),className:V$(d,"is-multi-select"),checked:c,styles:p,ariaPositionInSet:t.hidden?void 0:s._sizePosCache.positionInSet(t.index),ariaSetSize:t.hidden?void 0:s._sizePosCache.optionSetSize,ariaLabel:t.ariaLabel,ariaLabelledBy:t.ariaLabel?void 0:g}):e.createElement(S4,{id:h,key:t.key,"data-index":t.index,"data-is-focusable":!t.disabled,disabled:t.disabled,className:d,onClick:s._onItemClick(t),onMouseEnter:s._onItemMouseEnter.bind(s,t),onMouseLeave:s._onMouseItemLeave.bind(s,t),onMouseMove:s._onItemMouseMove.bind(s,t),role:"option","aria-selected":c?"true":"false",ariaLabel:t.ariaLabel,title:u,"aria-posinset":s._sizePosCache.positionInSet(t.index),"aria-setsize":s._sizePosCache.optionSetSize},a(t,s._onRenderOption))},s._onRenderOption=function(t){return e.createElement("span",{className:s._classNames.dropdownOptionText},t.text)},s._onRenderMultiselectOption=function(t){return e.createElement("span",{id:t.id,"aria-hidden":"true",className:s._classNames.dropdownOptionText},t.text)},s._onRenderItemLabel=function(e){var t=s.props.onRenderOption;return(void 0===t?s._onRenderMultiselectOption:t)(e,s._onRenderMultiselectOption)},s._onPositioned=function(e){s._focusZone.current&&s._requestAnimationFrame((function(){var e=s.props.hoisted.selectedIndices;if(s._focusZone.current)if(!s._hasBeenPositioned&&e&&e[0]&&!s.props.options[e[0]].disabled){var t=EB().getElementById("".concat(s._id,"-list").concat(e[0]));t&&s._focusZone.current.focusElement(t),s._hasBeenPositioned=!0}else s._focusZone.current.focus()})),s.state.calloutRenderEdge&&s.state.calloutRenderEdge===e.targetEdge||s.setState({calloutRenderEdge:e.targetEdge})},s._onItemClick=function(e){return function(t){e.disabled||(s.setSelectedIndex(t,e.index),s.props.multiSelect||s.setState({isOpen:!1}))}},s._onScroll=function(){var e=rz(s.context);s._isScrollIdle||void 0===s._scrollIdleTimeoutId?s._isScrollIdle=!1:(e.clearTimeout(s._scrollIdleTimeoutId),s._scrollIdleTimeoutId=void 0),s._scrollIdleTimeoutId=e.setTimeout((function(){s._isScrollIdle=!0}),s._scrollIdleDelay)},s._onMouseItemLeave=function(e,t){if(!s._shouldIgnoreMouseEvent()&&s._host.current)if(s._host.current.setActive)try{s._host.current.setActive()}catch(e){}else s._host.current.focus()},s._onDismiss=function(){s.setState({isOpen:!1})},s._onDropdownBlur=function(e){s._isDisabled()||s.state.isOpen||(s.setState({hasFocus:!1}),s.props.onBlur&&s.props.onBlur(e))},s._onDropdownKeyDown=function(e){if(!s._isDisabled()&&(s._lastKeyDownWasAltOrMeta=s._isAltOrMeta(e),!s.props.onKeyDown||(s.props.onKeyDown(e),!e.defaultPrevented))){var t,i=s.props.hoisted.selectedIndices.length?s.props.hoisted.selectedIndices[0]:-1,n=e.altKey||e.metaKey,r=s.state.isOpen;switch(e.which){case fj:s.setState({isOpen:!r});break;case vj:if(!r)return;s.setState({isOpen:!1});break;case Cj:if(n){if(r){s.setState({isOpen:!1});break}return}s.props.multiSelect?s.setState({isOpen:!0}):s._isDisabled()||(t=s._moveIndex(e,-1,i-1,i));break;case Ej:n&&(e.stopPropagation(),e.preventDefault()),n&&!r||s.props.multiSelect?s.setState({isOpen:!0}):s._isDisabled()||(t=s._moveIndex(e,1,i+1,i));break;case 36:s.props.multiSelect||(t=s._moveIndex(e,1,0,i));break;case 35:s.props.multiSelect||(t=s._moveIndex(e,-1,s.props.options.length-1,i));break;case Sj:break;default:return}t!==i&&(e.stopPropagation(),e.preventDefault())}},s._onDropdownKeyUp=function(e){if(!s._isDisabled()){var t=s._shouldHandleKeyUp(e),i=s.state.isOpen;s.props.onKeyUp&&(s.props.onKeyUp(e),e.defaultPrevented)||(e.which===Sj?(s.setState({isOpen:!i}),e.stopPropagation(),e.preventDefault()):t&&i&&s.setState({isOpen:!1}))}},s._onZoneKeyDown=function(e){var t,i,n;s._lastKeyDownWasAltOrMeta=s._isAltOrMeta(e);var r=e.altKey||e.metaKey;switch(e.which){case Cj:r?s.setState({isOpen:!1}):s._host.current&&(n=EG(s._host.current,s._host.current.lastChild,!0));break;case 36:case 35:case 33:case 34:break;case Ej:!r&&s._host.current&&(n=TG(s._host.current,s._host.current.firstChild,!0));break;case vj:s.setState({isOpen:!1});break;case 9:s.setState({isOpen:!1});var a=EB();a&&(e.shiftKey?null===(t=bG(a.body,s._dropDown.current,!1,!1,!0,!0))||void 0===t||t.focus():null===(i=_G(a.body,s._dropDown.current,!1,!1,!0,!0))||void 0===i||i.focus());break;default:return}n&&n.focus(),e.stopPropagation(),e.preventDefault()},s._onZoneKeyUp=function(e){s._shouldHandleKeyUp(e)&&s.state.isOpen&&(s.setState({isOpen:!1}),e.preventDefault())},s._onDropdownClick=function(e){if(!s.props.onClick||(s.props.onClick(e),!e.defaultPrevented)){var t=s.state.isOpen;s._isDisabled()||s._shouldOpenOnFocus()||s.setState({isOpen:!t}),s._isFocusedByClick=!1}},s._onDropdownMouseDown=function(){s._isFocusedByClick=!0},s._onFocus=function(e){if(!s._isDisabled()){s.props.onFocus&&s.props.onFocus(e);var t={hasFocus:!0};s._shouldOpenOnFocus()&&(t.isOpen=!0),s.setState(t)}},s._isDisabled=function(){var e=s.props.disabled,t=s.props.isDisabled;return void 0===e&&(e=t),e},s._onRenderLabel=function(t){var i=t.label,n=t.required,r=t.disabled,a=s._classNames.subComponentStyles?s._classNames.subComponentStyles.label:void 0;return i?e.createElement(M5,{className:s._classNames.label,id:s._labelId,required:n,styles:a,disabled:r},i):null},Ij(s),i.multiSelect,i.selectedKey,i.selectedKeys,i.defaultSelectedKey,i.defaultSelectedKeys;var a=i.options;return s._id=i.id||u$("Dropdown"),s._labelId=s._id+"-label",s._listId=s._id+"-list",s._optionId=s._id+"-option",s._isScrollIdle=!0,s._hasBeenPositioned=!1,s._sizePosCache.updateOptions(a),s.state={isOpen:!1,hasFocus:!1,calloutRenderEdge:void 0},s}return _U(i,t),Object.defineProperty(i.prototype,"selectedOptions",{get:function(){var e=this.props;return B4(e.options,e.hoisted.selectedIndices)},enumerable:!1,configurable:!0}),i.prototype.componentWillUnmount=function(){clearTimeout(this._scrollIdleTimeoutId)},i.prototype.componentDidUpdate=function(e,t){!0===t.isOpen&&!1===this.state.isOpen&&(this._gotMouseMove=!1,this._hasBeenPositioned=!1,this.props.onDismiss&&this.props.onDismiss())},i.prototype.render=function(){var t=this._id,i=this.props,n=i.className,r=i.label,s=i.options,a=i.ariaLabel,o=i.required,l=i.errorMessage,c=i.styles,d=i.theme,u=i.panelProps,h=i.calloutProps,g=i.onRenderTitle,p=void 0===g?this._getTitle:g,m=i.onRenderContainer,f=void 0===m?this._onRenderContainer:m,v=i.onRenderCaretDown,S=void 0===v?this._onRenderCaretDown:v,y=i.onRenderLabel,C=void 0===y?this._onRenderLabel:y,T=i.onRenderItem,E=void 0===T?this._onRenderItem:T,b=i.hoisted.selectedIndices,_=this.state,I=_.isOpen,w=_.calloutRenderEdge,A=_.hasFocus,P=i.onRenderPlaceholder||i.onRenderPlaceHolder||this._getPlaceholder;s!==this._sizePosCache.cachedOptions&&this._sizePosCache.updateOptions(s);var R=B4(s,b),M=B$(i,U$),D=this._isDisabled(),k=t+"-errorMessage";this._classNames=K4(c,{theme:d,className:n,hasError:!!(l&&l.length>0),hasLabel:!!r,isOpen:I,required:o,disabled:D,isRenderingPlaceholder:!R.length,panelClassName:u?u.className:void 0,calloutClassName:h?h.className:void 0,calloutRenderEdge:w});var O=!!l&&l.length>0;return e.createElement("div",{className:this._classNames.root,ref:this.props.hoisted.rootRef,"aria-owns":I?this._listId:void 0},C(this.props,this._onRenderLabel),e.createElement("div",IU({"data-is-focusable":!D,"data-ktp-target":!0,ref:this._dropDown,id:t,tabIndex:D?-1:0,role:"combobox","aria-haspopup":"listbox","aria-expanded":I?"true":"false","aria-label":a,"aria-labelledby":r&&!a?tG(this._labelId,this._optionId):void 0,"aria-describedby":O?this._id+"-errorMessage":void 0,"aria-required":o,"aria-disabled":D,"aria-invalid":O,"aria-controls":I?this._listId:void 0},M,{className:this._classNames.dropdown,onBlur:this._onDropdownBlur,onKeyDown:this._onDropdownKeyDown,onKeyUp:this._onDropdownKeyUp,onClick:this._onDropdownClick,onMouseDown:this._onDropdownMouseDown,onFocus:this._onFocus}),e.createElement("span",{id:this._optionId,className:this._classNames.title,"aria-live":A?"polite":void 0,"aria-atomic":!!A||void 0},R.length?p(R,this._onRenderTitle):P(i,this._onRenderPlaceholder)),e.createElement("span",{className:this._classNames.caretDownWrapper},S(i,this._onRenderCaretDown))),I&&f(IU(IU({},i),{onDismiss:this._onDismiss,onRenderItem:E}),this._onRenderContainer),O&&e.createElement("div",{role:"alert",id:k,className:this._classNames.errorMessage},l))},i.prototype.focus=function(e){this._dropDown.current&&(this._dropDown.current.focus(),e&&this.setState({isOpen:!0}))},i.prototype.setSelectedIndex=function(e,t){var i=this.props,n=i.options,r=i.selectedKey,s=i.selectedKeys,a=i.multiSelect,o=i.notifyOnReselect,l=i.hoisted.selectedIndices,c=void 0===l?[]:l,d=!!c&&c.indexOf(t)>-1,u=[];if(t=Math.max(0,Math.min(n.length-1,t)),void 0===r&&void 0===s){if(a||o||t!==c[0]){if(a)if(u=c?this._copyArray(c):[],d){var h=u.indexOf(t);h>-1&&u.splice(h,1)}else u.push(t);else u=[t];e.persist(),this.props.hoisted.setSelectedIndices(u),this._onChange(e,n,t,d,a)}}else this._onChange(e,n,t,d,a)},i.prototype._copyArray=function(e){for(var t=[],i=0,n=e;i<n.length;i++){var r=n[i];t.push(r)}return t},i.prototype._moveIndex=function(e,t,i,n){var r=this.props.options;if(n===i||0===r.length)return n;i>=r.length?i=0:i<0&&(i=r.length-1);for(var s=0;r[i].itemType===m4.Header||r[i].itemType===m4.Divider||r[i].disabled;){if(s>=r.length)return n;i+t<0?i=r.length:i+t>=r.length&&(i=-1),i+=t,s++}return this.setSelectedIndex(e,i),i},i.prototype._renderFocusableList=function(t){var i=t.onRenderList,n=void 0===i?this._onRenderList:i,r=t.label,s=t.ariaLabel,a=t.multiSelect;return e.createElement("div",{className:this._classNames.dropdownItemsWrapper,onKeyDown:this._onZoneKeyDown,onKeyUp:this._onZoneKeyUp,ref:this._host,tabIndex:0},e.createElement(iq,{ref:this._focusZone,direction:yG.vertical,id:this._listId,className:this._classNames.dropdownItems,role:"listbox","aria-label":s,"aria-labelledby":r&&!s?this._labelId:void 0,"aria-multiselectable":a},n(t,this._onRenderList)))},i.prototype._renderSeparator=function(t){var i=t.index,n=t.key,r=t.hidden?this._classNames.dropdownDividerHidden:this._classNames.dropdownDivider;return i>0?e.createElement("div",{role:"presentation",key:n,className:r}):null},i.prototype._renderHeader=function(t){var i=this.props.onRenderOption,n=void 0===i?this._onRenderOption:i,r=t.key,s=t.id,a=t.hidden?this._classNames.dropdownItemHeaderHidden:this._classNames.dropdownItemHeader;return e.createElement("div",{id:s,key:r,className:a},n(t,this._onRenderOption))},i.prototype._onItemMouseEnter=function(e,t){this._shouldIgnoreMouseEvent()||t.currentTarget.focus()},i.prototype._onItemMouseMove=function(e,t){var i=nz(this.context),n=t.currentTarget;this._gotMouseMove=!0,this._isScrollIdle&&i.activeElement!==n&&n.focus()},i.prototype._shouldIgnoreMouseEvent=function(){return!this._isScrollIdle||!this._gotMouseMove},i.prototype._isAltOrMeta=function(e){return 18===e.which||"Meta"===e.key},i.prototype._shouldHandleKeyUp=function(e){var t=this._lastKeyDownWasAltOrMeta&&this._isAltOrMeta(e);return this._lastKeyDownWasAltOrMeta=!1,!!t&&!(nq()||rq())},i.prototype._shouldOpenOnFocus=function(){var e=this.state.hasFocus,t=this.props.openOnKeyboardFocus;return!this._isFocusedByClick&&!0===t&&!e},i.defaultProps={options:[]},i.contextType=Kq,i}(e.Component),n3={root:"ms-Dropdown-container",label:"ms-Dropdown-label",dropdown:"ms-Dropdown",title:"ms-Dropdown-title",caretDownWrapper:"ms-Dropdown-caretDownWrapper",caretDown:"ms-Dropdown-caretDown",callout:"ms-Dropdown-callout",panel:"ms-Dropdown-panel",dropdownItems:"ms-Dropdown-items",dropdownItem:"ms-Dropdown-item",dropdownDivider:"ms-Dropdown-divider",dropdownOptionText:"ms-Dropdown-optionText",dropdownItemHeader:"ms-Dropdown-header",titleIsPlaceHolder:"ms-Dropdown-titleIsPlaceHolder",titleHasError:"ms-Dropdown-title--hasError"},r3=((Q4={})["".concat(UV,", ").concat(BV.replace("@media ",""))]=IU({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),Q4),s3={selectors:IU((Z4={},Z4[UV]=(X4={backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},X4[".".concat(GV," &:focus:after")]={borderColor:"HighlightText"},X4),Z4[".ms-Checkbox-checkbox"]=(e3={},e3[UV]={borderColor:"HighlightText"},e3),Z4),r3)},a3={selectors:(t3={},t3[UV]={borderColor:"Highlight"},t3)},o3=$V(0,VV),l3=nj(Y4,(function(e){var t,i,n,r,s,a,o,l,c,d,u,h,g=e.theme,p=e.hasError,m=e.hasLabel,f=e.className,v=e.isOpen,S=e.disabled,y=e.required,C=e.isRenderingPlaceholder,T=e.panelClassName,E=e.calloutClassName,b=e.calloutRenderEdge;if(!g)throw new Error("theme is undefined or null in base Dropdown getStyles function.");var _=FV(n3,g),I=g.palette,w=g.semanticColors,A=g.effects,P=g.fonts,R={color:w.menuItemTextHovered},M={color:w.menuItemText},D={borderColor:w.errorText},k=[_.dropdownItem,{backgroundColor:"transparent",boxSizing:"border-box",cursor:"pointer",display:"flex",alignItems:"center",padding:"0 8px",width:"100%",minHeight:36,lineHeight:20,height:0,position:"relative",border:"1px solid transparent",borderRadius:0,wordWrap:"break-word",overflowWrap:"break-word",textAlign:"left",".ms-Button-flexContainer":{width:"100%"}}],O=[_.dropdownItemHeader,IU(IU({},P.medium),{fontWeight:DV.semibold,color:w.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:36,lineHeight:36,cursor:"default",padding:"0 8px",userSelect:"none",textAlign:"left",selectors:(t={},t[UV]=IU({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)})],N=w.menuItemBackgroundPressed,L=function(e){var t,i;return void 0===e&&(e=!1),{selectors:(t={"&:hover":[{color:w.menuItemTextHovered,backgroundColor:e?N:w.menuItemBackgroundHovered},s3],"&.is-multi-select:hover":[{backgroundColor:e?N:"transparent"},s3],"&:active:hover":[{color:w.menuItemTextHovered,backgroundColor:e?w.menuItemBackgroundHovered:w.menuItemBackgroundPressed},s3]},t[".".concat(GV," &:focus:after, :host(.").concat(GV,") &:focus:after")]=(i={left:0,top:0,bottom:0,right:0},i[UV]={inset:"2px"},i),t[UV]={border:"none"},t)}},x=PU(PU([],k,!0),[{backgroundColor:N,color:w.menuItemTextHovered},L(!0),s3],!1),F=PU(PU([],k,!0),[{color:w.disabledText,cursor:"default",selectors:(i={},i[UV]={color:"GrayText",border:"none"},i)}],!1),U=b===aq.bottom?"".concat(A.roundedCorner2," ").concat(A.roundedCorner2," 0 0"):"0 0 ".concat(A.roundedCorner2," ").concat(A.roundedCorner2),B=b===aq.bottom?"0 0 ".concat(A.roundedCorner2," ").concat(A.roundedCorner2):"".concat(A.roundedCorner2," ").concat(A.roundedCorner2," 0 0");return{root:[_.root,f],label:_.label,dropdown:[_.dropdown,VH,P.medium,{color:w.menuItemText,borderColor:w.focusBorder,position:"relative",outline:0,userSelect:"none",selectors:(n={},n["&:hover ."+_.title]=[!S&&R,{borderColor:v?I.neutralSecondary:I.neutralPrimary},a3],n["&:focus ."+_.title]=[!S&&R,{selectors:(r={},r[UV]={color:"Highlight"},r)}],n["&:focus:after"]=[{pointerEvents:"none",content:"''",position:"absolute",boxSizing:"border-box",top:"0px",left:"0px",width:"100%",height:"100%",border:S?"none":"2px solid ".concat(I.themePrimary),borderRadius:"2px",selectors:(s={},s[UV]={color:"Highlight"},s)}],n["&:active ."+_.title]=[!S&&R,{borderColor:I.themePrimary},a3],n["&:hover ."+_.caretDown]=!S&&M,n["&:focus ."+_.caretDown]=[!S&&M,{selectors:(a={},a[UV]={color:"Highlight"},a)}],n["&:active ."+_.caretDown]=!S&&M,n["&:hover ."+_.titleIsPlaceHolder]=!S&&M,n["&:focus ."+_.titleIsPlaceHolder]=!S&&M,n["&:active ."+_.titleIsPlaceHolder]=!S&&M,n["&:hover ."+_.titleHasError]=D,n["&:active ."+_.titleHasError]=D,n)},v&&"is-open",S&&"is-disabled",y&&"is-required",y&&!m&&{selectors:(o={":before":{content:"'*'",color:w.errorText,position:"absolute",top:-5,right:-10}},o[UV]={selectors:{":after":{right:-14}}},o)}],title:[_.title,VH,{backgroundColor:w.inputBackground,borderWidth:1,borderStyle:"solid",borderColor:w.inputBorder,borderRadius:v?U:A.roundedCorner2,cursor:"pointer",display:"block",height:32,lineHeight:30,padding:"0 28px 0 8px",position:"relative",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},C&&[_.titleIsPlaceHolder,{color:w.inputPlaceholderText}],p&&[_.titleHasError,D],S&&{backgroundColor:w.disabledBackground,border:"none",color:w.disabledText,cursor:"default",selectors:(l={},l[UV]=IU({border:"1px solid GrayText",color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),l)}],caretDownWrapper:[_.caretDownWrapper,{height:32,lineHeight:30,paddingTop:1,position:"absolute",right:8,top:0},!S&&{cursor:"pointer"}],caretDown:[_.caretDown,{color:I.neutralSecondary,fontSize:P.small.fontSize,pointerEvents:"none"},S&&{color:w.disabledText,selectors:(c={},c[UV]=IU({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),c)}],errorMessage:IU(IU({color:w.errorText},g.fonts.small),{paddingTop:5}),callout:[_.callout,{boxShadow:A.elevation8,borderRadius:B,selectors:(d={},d[".ms-Callout-main"]={borderRadius:B},d)},E],dropdownItemsWrapper:{selectors:{"&:focus":{outline:0}}},dropdownItems:[_.dropdownItems,{display:"block"}],dropdownItem:PU(PU([],k,!0),[L()],!1),dropdownItemSelected:x,dropdownItemDisabled:F,dropdownItemSelectedAndDisabled:[x,F,{backgroundColor:"transparent"}],dropdownItemHidden:PU(PU([],k,!0),[{display:"none"}],!1),dropdownDivider:[_.dropdownDivider,{height:1,backgroundColor:w.bodyDivider}],dropdownDividerHidden:[_.dropdownDivider,{display:"none"}],dropdownOptionText:[_.dropdownOptionText,{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",minWidth:0,maxWidth:"100%",wordWrap:"break-word",overflowWrap:"break-word",margin:"1px"}],dropdownItemHeader:O,dropdownItemHeaderHidden:PU(PU([],O,!0),[{display:"none"}],!1),subComponentStyles:{label:{root:{display:"inline-block"}},multiSelectItem:{root:{padding:0},label:{alignSelf:"stretch",padding:"0 8px",width:"100%"},input:{selectors:(u={},u[".".concat(GV," &:focus + label::before, :host(.").concat(GV,") &:focus + label::before")]={outlineOffset:"0px"},u)}},panel:{root:[T],main:{selectors:(h={},h[o3]={width:272},h)},contentInner:{padding:"0 0 20px"}}}}}),void 0,{scope:"Dropdown"});l3.displayName="Dropdown";var c3=CV,d3={root:"ms-Modal",main:"ms-Dialog-main",scrollableContent:"ms-Modal-scrollableContent",isOpen:"is-open",layer:"ms-Modal-Layer"},u3=SB((function(e,t){return{root:dB(e,t&&{touchAction:"none",selectors:{"& *":{userSelect:"none"}}})}})),h3={start:"touchstart",move:"touchmove",stop:"touchend"},g3={start:"mousedown",move:"mousemove",stop:"mouseup"},p3=function(t){function i(i){var n=t.call(this,i)||this;return n._currentEventType=g3,n._events=[],n._onMouseDown=function(t){var i=e.Children.only(n.props.children).props.onMouseDown;return i&&i(t),n._currentEventType=g3,n._onDragStart(t)},n._onMouseUp=function(t){var i=e.Children.only(n.props.children).props.onMouseUp;return i&&i(t),n._currentEventType=g3,n._onDragStop(t)},n._onTouchStart=function(t){var i=e.Children.only(n.props.children).props.onTouchStart;return i&&i(t),n._currentEventType=h3,n._onDragStart(t)},n._onTouchEnd=function(t){var i=e.Children.only(n.props.children).props.onTouchEnd;i&&i(t),n._currentEventType=h3,n._onDragStop(t)},n._onDragStart=function(e){if("number"==typeof e.button&&0!==e.button)return!1;if(!(n.props.handleSelector&&!n._matchesSelector(e.target,n.props.handleSelector)||n.props.preventDragSelector&&n._matchesSelector(e.target,n.props.preventDragSelector))){n._touchId=n._getTouchId(e);var t=n._getControlPosition(e);if(void 0!==t){var i=n._createDragDataFromPosition(t);n.props.onStart&&n.props.onStart(e,i),n.setState({isDragging:!0,lastPosition:t});var r=nz(n.context);n._events=[pq(r.body,n._currentEventType.move,n._onDrag,!0),pq(r.body,n._currentEventType.stop,n._onDragStop,!0)]}}},n._onDrag=function(e){"touchmove"===e.type&&e.preventDefault();var t=n._getControlPosition(e);if(t){var i=n._createUpdatedDragData(n._createDragDataFromPosition(t)),r=i.position;n.props.onDragChange&&n.props.onDragChange(e,i),n.setState({position:r,lastPosition:t})}},n._onDragStop=function(e){if(n.state.isDragging){var t=n._getControlPosition(e);if(t){var i=n._createDragDataFromPosition(t);n.setState({isDragging:!1,lastPosition:void 0}),n.props.onStop&&n.props.onStop(e,i),n.props.position&&n.setState({position:n.props.position}),n._events.forEach((function(e){return e()}))}}},n.state={isDragging:!1,position:n.props.position||{x:0,y:0},lastPosition:void 0},n}return _U(i,t),i.prototype.componentDidUpdate=function(e){!this.props.position||e.position&&this.props.position===e.position||this.setState({position:this.props.position})},i.prototype.componentWillUnmount=function(){this._events.forEach((function(e){return e()}))},i.prototype.render=function(){var t=e.Children.only(this.props.children),i=t.props,n=this.props.position,r=this.state,s=r.position,a=r.isDragging,o=s.x,l=s.y;return n&&!a&&(o=n.x,l=n.y),e.cloneElement(t,{style:IU(IU({},i.style),{transform:"translate(".concat(o,"px, ").concat(l,"px)")}),className:u3(i.className,this.state.isDragging).root,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onTouchStart:this._onTouchStart,onTouchEnd:this._onTouchEnd})},i.prototype._getControlPosition=function(e){var t=this._getActiveTouch(e);if(void 0===this._touchId||t){var i=t||e;return{x:i.clientX,y:i.clientY}}},i.prototype._getActiveTouch=function(e){return e.targetTouches&&this._findTouchInTouchList(e.targetTouches)||e.changedTouches&&this._findTouchInTouchList(e.changedTouches)},i.prototype._getTouchId=function(e){var t=e.targetTouches&&e.targetTouches[0]||e.changedTouches&&e.changedTouches[0];if(t)return t.identifier},i.prototype._matchesSelector=function(e,t){var i;if(!e||e===(null===(i=nz(this.context))||void 0===i?void 0:i.body))return!1;var n=e.matches||e.webkitMatchesSelector||e.msMatchesSelector;return!!n&&(n.call(e,t)||this._matchesSelector(e.parentElement,t))},i.prototype._findTouchInTouchList=function(e){if(void 0!==this._touchId)for(var t=0;t<e.length;t++)if(e[t].identifier===this._touchId)return e[t]},i.prototype._createDragDataFromPosition=function(e){var t=this.state.lastPosition;return void 0===t?{delta:{x:0,y:0},lastPosition:e,position:e}:{delta:{x:e.x-t.x,y:e.y-t.y},lastPosition:t,position:e}},i.prototype._createUpdatedDragData=function(e){var t=this.state.position;return{position:{x:t.x+e.delta.x,y:t.y+e.delta.y},delta:e.delta,lastPosition:t}},i.contextType=Kq,i}(e.Component),m3={x:0,y:0},f3={isOpen:!1,isDarkOverlay:!0,className:"",containerClassName:"",enableAriaHiddenSiblings:!0},v3=oj(),S3=e.forwardRef((function(t,i){var n,r,s,a,o,l=sq(f3,t),c=l.allowTouchBodyScroll,d=l.className,u=l.children,h=l.containerClassName,g=l.scrollableContentClassName,p=l.elementToFocusOnDismiss,m=l.firstFocusableSelector,f=l.focusTrapZoneProps,v=l.forceFocusInsideTrap,S=l.disableRestoreFocus,y=void 0===S?l.ignoreExternalFocusing:S,C=l.isBlocking,T=l.isAlert,E=l.isClickableOutsideFocusTrap,b=l.isDarkOverlay,_=l.onDismiss,I=l.layerProps,w=l.overlay,A=l.isOpen,P=l.titleAriaId,R=l.styles,M=l.subtitleAriaId,D=l.theme,k=l.topOffsetFixed,O=l.responsiveMode,N=l.onLayerDidMount,L=l.isModeless,x=l.dragOptions,F=l.onDismissed,U=l.enableAriaHiddenSiblings,B=l.popupProps,V=e.useRef(null),H=e.useRef(null),$=nG(H,null==f?void 0:f.componentRef),j=e.useRef(null),G=nG(V,i),q=_W(G),z=g$("ModalFocusTrapZone",null==f?void 0:f.id),W=Jq(),K=K2(),J=K.setTimeout,Y=K.clearTimeout,Q=e.useState(A),Z=Q[0],X=Q[1],ee=e.useState(A),te=ee[0],ie=ee[1],ne=e.useState(m3),re=ne[0],se=ne[1],ae=e.useState(),oe=ae[0],le=ae[1],ce=lK(!1),de=ce[0],ue=ce[1],he=ue.toggle,ge=ue.setFalse,pe=Xq((function(){return{onModalCloseTimer:0,allowTouchBodyScroll:c,scrollableContent:null,lastSetCoordinates:m3,events:new Lj({})}})),me=(x||{}).keepInBounds,fe=null!=T?T:C&&!L,ve=void 0===I?"":I.className,Se=v3(R,{theme:D,className:d,containerClassName:h,scrollableContentClassName:g,isOpen:A,isVisible:te,hasBeenOpened:pe.hasBeenOpened,modalRectangleTop:oe,topOffsetFixed:k,isModeless:L,layerClassName:ve,windowInnerHeight:null==W?void 0:W.innerHeight,isDefaultDragHandle:x&&!x.dragHandleSelector}),ye=IU(IU({eventBubblingEnabled:!1},I),{onLayerDidMount:I&&I.onLayerDidMount?I.onLayerDidMount:N,insertFirst:(null==I?void 0:I.insertFirst)||L,className:Se.layer}),Ce=e.useCallback((function(e){e?pe.allowTouchBodyScroll?UG(e,pe.events):FG(e,pe.events):pe.events.off(pe.scrollableContent),pe.scrollableContent=e}),[pe]),Te=function(){var e=j.current,t=null==e?void 0:e.getBoundingClientRect();t&&(k&&le(t.top),me&&(pe.minPosition={x:-t.left,y:-t.top},pe.maxPosition={x:t.left,y:t.top}))},Ee=e.useCallback((function(e,t){var i=pe.minPosition,n=pe.maxPosition;return me&&i&&n&&(t=Math.max(i[e],t),t=Math.min(n[e],t)),t}),[me,pe]),be=function(){var e;pe.lastSetCoordinates=m3,ge(),pe.isInKeyboardMoveMode=!1,X(!1),se(m3),null===(e=pe.disposeOnKeyUp)||void 0===e||e.call(pe),null==F||F()},_e=e.useCallback((function(){ge(),pe.isInKeyboardMoveMode=!1}),[pe,ge]),Ie=e.useCallback((function(e,t){se((function(e){return{x:Ee("x",e.x+t.delta.x),y:Ee("y",e.y+t.delta.y)}}))}),[Ee]),we=e.useCallback((function(){H.current&&H.current.focus()}),[]);e.useEffect((function(){var e;Y(pe.onModalCloseTimer),A&&(requestAnimationFrame((function(){return J(Te,0)})),X(!0),x&&(e=function(e){e.altKey&&e.ctrlKey&&e.keyCode===Sj&&CG(pe.scrollableContent,e.target)&&(he(),e.preventDefault(),e.stopPropagation())},pe.disposeOnKeyUp||(pe.events.on(W,"keyup",e,!0),pe.disposeOnKeyUp=function(){pe.events.off(W,"keyup",e,!0),pe.disposeOnKeyUp=void 0})),pe.hasBeenOpened=!0,ie(!0)),!A&&Z&&(pe.onModalCloseTimer=J(be,1e3*parseFloat(c3)),ie(!1))}),[Z,A]),_J((function(){pe.events.dispose(),pe.onModalCloseTimer&&(Y(pe.onModalCloseTimer),pe.onModalCloseTimer=0)})),function(t,i){e.useImperativeHandle(t.componentRef,(function(){return{focus:function(){i.current&&i.current.focus()}}}),[i])}(l,H);var Ae=e.createElement(x0,IU({},f,{id:z,ref:j,componentRef:$,className:V$(Se.main,null==f?void 0:f.className),elementToFocusOnDismiss:null!==(n=null==f?void 0:f.elementToFocusOnDismiss)&&void 0!==n?n:p,isClickableOutsideFocusTrap:null!==(r=null==f?void 0:f.isClickableOutsideFocusTrap)&&void 0!==r?r:L||E||!C,disableRestoreFocus:null!==(s=null==f?void 0:f.disableRestoreFocus)&&void 0!==s?s:y,forceFocusInsideTrap:(null!==(a=null==f?void 0:f.forceFocusInsideTrap)&&void 0!==a?a:v)&&!L,firstFocusableSelector:(null==f?void 0:f.firstFocusableSelector)||m,focusPreviouslyFocusedInnerElement:null===(o=null==f?void 0:f.focusPreviouslyFocusedInnerElement)||void 0===o||o,onBlur:pe.isInKeyboardMoveMode?function(e){var t,i;null===(t=null==f?void 0:f.onBlur)||void 0===t||t.call(f,e),pe.lastSetCoordinates=m3,pe.isInKeyboardMoveMode=!1,null===(i=pe.disposeOnKeyDown)||void 0===i||i.call(pe)}:void 0}),x&&pe.isInKeyboardMoveMode&&e.createElement("div",{className:Se.keyboardMoveIconContainer},x.keyboardMoveIconProps?e.createElement(mG,IU({},x.keyboardMoveIconProps)):e.createElement(mG,{iconName:"move",className:Se.keyboardMoveIcon})),e.createElement("div",{ref:Ce,className:Se.scrollableContent,"data-is-scrollable":!0},x&&de&&e.createElement(x.menu,{items:[{key:"move",text:x.moveMenuItemText,onClick:function(){var e=function(e){if(e.altKey&&e.ctrlKey&&e.keyCode===Sj)return e.preventDefault(),void e.stopPropagation();var t=e.altKey||e.keyCode===vj;if(de&&t&&ge(),!pe.isInKeyboardMoveMode||e.keyCode!==vj&&e.keyCode!==fj||(pe.isInKeyboardMoveMode=!1,e.preventDefault(),e.stopPropagation()),pe.isInKeyboardMoveMode){var i=!0,n=function(e){var t=10;return e.shiftKey?e.ctrlKey||(t=50):e.ctrlKey&&(t=1),t}(e);switch(e.keyCode){case vj:se(pe.lastSetCoordinates);case fj:pe.lastSetCoordinates=m3;break;case Cj:se((function(e){return{x:e.x,y:Ee("y",e.y-n)}}));break;case Ej:se((function(e){return{x:e.x,y:Ee("y",e.y+n)}}));break;case yj:se((function(e){return{x:Ee("x",e.x-n),y:e.y}}));break;case Tj:se((function(e){return{x:Ee("x",e.x+n),y:e.y}}));break;default:i=!1}i&&(e.preventDefault(),e.stopPropagation())}};pe.lastSetCoordinates=re,ge(),pe.isInKeyboardMoveMode=!0,pe.events.on(W,"keydown",e,!0),pe.disposeOnKeyDown=function(){pe.events.off(W,"keydown",e,!0),pe.disposeOnKeyDown=void 0}}},{key:"close",text:x.closeMenuItemText,onClick:be}],onDismiss:ge,alignTargetEdge:!0,coverTarget:!0,directionalHint:0,directionalHintFixed:!0,shouldFocusOnMount:!0,target:pe.scrollableContent}),u));return Z&&q>=(O||fW.small)&&e.createElement(Hz,IU({ref:G},ye),e.createElement(Zq,IU({role:fe?"alertdialog":"dialog",ariaLabelledBy:P,ariaDescribedBy:M,onDismiss:_,shouldRestoreFocus:!y,enableAriaHiddenSiblings:U,"aria-modal":!L},B),e.createElement("div",{className:Se.root,role:L?void 0:"document"},!L&&e.createElement(Z2,IU({"aria-hidden":!0,isDarkThemed:b,onClick:C?void 0:_,allowTouchBodyScroll:c},w)),x?e.createElement(p3,{handleSelector:x.dragHandleSelector||"#".concat(z),preventDragSelector:"button",onStart:_e,onDragChange:Ie,onStop:we,position:re},Ae):Ae)))||null}));S3.displayName="Modal";var y3=nj(S3,(function(e){var t,i=e.className,n=e.containerClassName,r=e.scrollableContentClassName,s=e.isOpen,a=e.isVisible,o=e.hasBeenOpened,l=e.modalRectangleTop,c=e.theme,d=e.topOffsetFixed,u=e.isModeless,h=e.layerClassName,g=e.isDefaultDragHandle,p=e.windowInnerHeight,m=c.palette,f=c.effects,v=c.fonts,S=FV(d3,c);return{root:[S.root,v.medium,{backgroundColor:"transparent",position:"fixed",height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",opacity:0,pointerEvents:"none",transition:"opacity ".concat(c3)},d&&"number"==typeof l&&o&&{alignItems:"flex-start"},s&&S.isOpen,a&&{opacity:1},a&&!u&&{pointerEvents:"auto"},i],main:[S.main,{boxShadow:f.elevation64,borderRadius:f.roundedCorner2,backgroundColor:m.white,boxSizing:"border-box",position:"relative",textAlign:"left",outline:"3px solid transparent",maxHeight:"calc(100% - 32px)",maxWidth:"calc(100% - 32px)",minHeight:"176px",minWidth:"288px",overflowY:"auto",zIndex:u?jV.Layer:void 0},u&&{pointerEvents:"auto"},d&&"number"==typeof l&&o&&{top:l},g&&{cursor:"move"},n],scrollableContent:[S.scrollableContent,{overflowY:"auto",flexGrow:1,maxHeight:"100vh",selectors:(t={},t["@supports (-webkit-overflow-scrolling: touch)"]={maxHeight:p},t)},r],layer:u&&[h,S.layer,{pointerEvents:"none"}],keyboardMoveIconContainer:{position:"absolute",display:"flex",justifyContent:"center",width:"100%",padding:"3px 0px"},keyboardMoveIcon:{fontSize:v.xLargePlus.fontSize,width:"24px"}}}),void 0,{scope:"Modal",fields:["theme","styles","enableAriaHiddenSiblings"]});y3.displayName="Modal";const C3={"ar-ae":"ar","ar-sa":"ar","da-dk":"da","de-de":"de","en-au":"en","en-ca":"en","en-gb":"en","en-in":"en","en-nz":"en","en-us":"en","es-es":"es","es-mx":"es","fi-fi":"fi","fr-ca":"fr-ca","fr-fr":"fr","hi-in":"hi","it-it":"it","ja-jp":"ja","ko-kr":"ko","nb-no":"nb","nl-be":"nl","nl-nl":"nl","pl-pl":"pl","pt-br":"pt","ru-ru":"ru","sv-se":"sv","zh-cn":"zh-Hans","zh-hk":"zh-Hant","cs-cz":"cs","pt-pt":"pt-pt","tr-tr":"tr","vi-vn":"vi","th-th":"th","he-il":"he","cy-gb":"cy","uk-ua":"uk","el-gr":"el","hu-hu":"hu","ro-ro":"ro","sk-sk":"sk","zh-tw":"zh-Hant"};const T3=t=>{const{supportedSpokenLanguages:i,supportedCaptionLanguages:n,currentSpokenLanguage:r,currentCaptionLanguage:s,isCaptionsFeatureActive:a,showModal:o,onSetSpokenLanguage:l,onSetCaptionLanguage:c,onDismissCaptionsSettings:d,onStartCaptions:u,changeCaptionLanguage:h=!1}=t,g=qK(),p=AK().strings.captionsSettingsModal,m=AK().strings.spokenLanguages,f=AK().strings.captionLanguages,v=Object.assign(Object.assign({},p),t.strings),S=(0,e.useMemo)((()=>Object.assign(Object.assign({},m),t.spokenLanguageStrings)),[m,t.spokenLanguageStrings]),y=(0,e.useMemo)((()=>Object.assign(Object.assign({},f),t.captionLanguageStrings)),[f,t.captionLanguageStrings]),[C,T]=(0,e.useState)(!1),[E,b]=(0,e.useState)({key:r||UK,text:r||UK}),[_,I]=(0,e.useState)({key:s||C3[E.key],text:s||C3[E.key]});(0,e.useEffect)((()=>{a&&!C&&(l(E.key),T(!0))}),[a,l,E.key,C]);const w=(0,e.useCallback)((()=>{d&&d()}),[d]),A=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){const e=E.key,t=_.key;a?(l(e),h&&c&&c(t)):yield u({spokenLanguage:e}),w()},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[w,a,l,c,u,E.key,_.key,h]),P=(0,e.useMemo)((()=>i.map((e=>({key:e,text:S?S[e]:e})))),[i,S]),R=(0,e.useMemo)((()=>null==n?void 0:n.map((e=>({key:e,text:y?y[e]:e})))),[n,y]),M=(0,e.useMemo)((()=>[...P].sort(((e,t)=>e.text>t.text?1:-1))),[P]),D=(0,e.useMemo)((()=>[...null!=R?R:[]].sort(((e,t)=>e.text>t.text?1:-1))),[R]),k=(0,e.useMemo)((()=>({preventDismissOnEvent:v0})),[]),O=(0,e.useCallback)((()=>{const t=null!=r?r:UK,i=null!=s?s:C3[t];return e.createElement(Y$,null,e.createElement(l3,{label:null==v?void 0:v.captionsSettingsSpokenLanguageDropdownLabel,selectedKey:E?E.key:void 0,onChange:(e,t)=>((e,t)=>{t&&b(t)})(0,t),calloutProps:k,placeholder:t,options:M,styles:g4}),e.createElement(oJ,{className:d4(g)},null==v?void 0:v.captionsSettingsSpokenLanguageDropdownInfoText),h&&e.createElement(e.Fragment,null,e.createElement(l3,{label:null==v?void 0:v.captionsSettingsCaptionLanguageDropdownLabel,selectedKey:_?_.key:void 0,onChange:(e,t)=>((e,t)=>{t&&I(t)})(0,t),calloutProps:k,placeholder:i,options:D,styles:g4}),e.createElement(oJ,{className:d4(g)},null==v?void 0:v.captionsSettingsCaptionLanguageDropdownInfoText)))}),[k,r,s,M,D,_,E,null==v?void 0:v.captionsSettingsSpokenLanguageDropdownInfoText,null==v?void 0:v.captionsSettingsCaptionLanguageDropdownLabel,null==v?void 0:v.captionsSettingsSpokenLanguageDropdownLabel,null==v?void 0:v.captionsSettingsCaptionLanguageDropdownInfoText,g,h]),N=(0,e.useMemo)((()=>a4(g)),[g]);return e.createElement(e.Fragment,null,e.createElement(y3,{titleAriaId:null==v?void 0:v.captionsSettingsModalAriaLabel,isOpen:o,onDismiss:w,isBlocking:!0,styles:N},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:l4},e.createElement(oJ,{className:o4},null==v?void 0:v.captionsSettingsModalTitle),e.createElement(oK,{iconProps:{iconName:"Cancel"},ariaLabel:null==v?void 0:v.captionsSettingsCloseModalButtonAriaLabel,onClick:w,style:{color:g.palette.black}})),e.createElement(Y$,{className:c4},O()),e.createElement(Y$,{horizontal:!0,horizontalAlign:"end",className:u4},e.createElement(mJ,{styles:h4(g),onClick:A},e.createElement("span",null,null==v?void 0:v.captionsSettingsConfirmButtonLabel)),e.createElement(pJ,{onClick:w,styles:h4(g)},e.createElement("span",null,null==v?void 0:v.captionsSettingsCancelButtonLabel)))))},E3={horizontal:{flexFlow:"row nowrap"},vertical:{flexFlow:"column nowrap",width:"fit-content",maxWidth:"8rem"},dockedTop:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:0,left:0,width:"100%",minWidth:"fit-content"},dockedBottom:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",bottom:0,left:0,width:"100%",minWidth:"fit-content"},dockedLeft:{justifyContent:"center",overflow:"hidden",position:"absolute",top:0,left:0,height:"100%"},dockedRight:{justifyContent:"center",overflow:"hidden",position:"absolute",top:0,right:0,height:"100%"},floatingTop:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"1rem",left:"50%",transform:"translateX(-50%)",minWidth:"fit-content",zIndex:10},floatingBottom:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",bottom:"1rem",left:"50%",transform:"translateX(-50%)",minWidth:"fit-content",zIndex:10},floatingLeft:{flexFlow:"column nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"50%",left:"1rem",transform:"translateY(-50%)",zIndex:10},floatingRight:{flexFlow:"column nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"50%",right:"1rem",transform:"translateY(-50%)",zIndex:10}},b3={root:{background:"none",border:"none",borderRadius:0,minHeight:"3.5rem",minWidth:"3.5rem",width:"100%",maxWidth:"8rem",svg:{verticalAlign:"text-top"}},splitButtonMenuButton:{border:"none"},flexContainer:{display:"unset"},label:{fontSize:"0.625rem",fontWeight:"400",lineHeight:"1rem",cursor:"pointer",display:"block",margin:"0rem 0.25rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},_3={title:{background:"initial",paddingLeft:".5rem",fontWeight:600,fontSize:".75rem"}},I3={icon:{lineHeight:0},checkmarkIcon:{lineHeight:0}},w3={root:{display:"inline-block"}},A3=t=>{const i=qK(),n={gapSpace:4,styles:{root:{padding:0},calloutMain:{padding:"0.5rem"},beakCurtain:{marginBottom:"-1rem",backgroundColor:"transparent"}},backgroundColor:LX(i)?i.palette.neutralLighter:""};return e.createElement(YZ,Object.assign({},t,{"data-ui-id":t.id,calloutProps:Object.assign(Object.assign({},n),t.calloutProps),styles:e$(w3,t.styles)}),t.children)},P3=e=>(null==e?void 0:e.checked)?(null==e?void 0:e.onRenderOnIcon)?null==e?void 0:e.onRenderOnIcon():null:(null==e?void 0:e.onRenderOffIcon)?null==e?void 0:e.onRenderOffIcon():null,R3=t=>{var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S;const y=ZH(b3,null!==(i=t.styles)&&void 0!==i?i:{}),C=null!==(s=null!==(n=null==t?void 0:t.text)&&void 0!==n?n:null===(r=null==t?void 0:t.strings)||void 0===r?void 0:r.label)&&void 0!==s?s:(null==t?void 0:t.checked)?null===(a=null==t?void 0:t.strings)||void 0===a?void 0:a.onLabel:null===(o=null==t?void 0:t.strings)||void 0===o?void 0:o.offLabel,T=null!==(c=null===(l=null==t?void 0:t.strings)||void 0===l?void 0:l.tooltipContent)&&void 0!==c?c:(null==t?void 0:t.disabled)?null===(d=null==t?void 0:t.strings)||void 0===d?void 0:d.tooltipDisabledContent:(null==t?void 0:t.checked)?null===(u=null==t?void 0:t.strings)||void 0===u?void 0:u.tooltipOnContent:null===(h=null==t?void 0:t.strings)||void 0===h?void 0:h.tooltipOffContent,E=(null!==(g=t.tooltipId)&&void 0!==g?g:t.labelKey)?t.labelKey+"-tooltip":void 0;return e.createElement(A3,{hidden:t.disableTooltip,content:T,id:E},e.createElement(pJ,Object.assign({},t,{styles:y,onRenderText:t.showLabel&&t.onRenderText?t.onRenderText:void 0,onRenderIcon:null!==(p=t.onRenderIcon)&&void 0!==p?p:P3,ariaLabel:null!==(v=null!==(f=null!==(m=t.splitButtonAriaLabel)&&void 0!==m?m:t.ariaLabel)&&void 0!==f?f:C)&&void 0!==v?v:T,allowDisabledFocus:null===(S=t.allowDisabledFocus)||void 0===S||S,"aria-describedby":E,menuTriggerKeyCode:Ej,text:void 0}),t.showLabel?C:e.createElement(e.Fragment,null)))},M3=t=>{const{iconName:i,disabled:n}=t,r=aJ();return e.createElement(mG,{iconName:i,className:dB({svg:{fill:n?r.palette.neutralTertiary:r.palette.neutralPrimaryAlt,"@media (forced-colors: active) and (prefers-color-scheme: dark)":{fill:n?r.palette.neutralPrimaryAlt:r.palette.neutralTertiary}}})})};var D3=oj(),k3="Toggle",O3=e.forwardRef((function(t,i){var n=t.as,r=void 0===n?"div":n,s=t.ariaLabel,a=t.checked,o=t.className,l=t.defaultChecked,c=void 0!==l&&l,d=t.disabled,u=t.inlineLabel,h=t.label,g=t.offAriaLabel,p=t.offText,m=t.onAriaLabel,f=t.onChange,v=t.onChanged,S=t.onClick,y=t.onText,C=t.role,T=t.styles,E=t.theme,b=V4(a,c,e.useCallback((function(e,t){null==f||f(e,t),null==v||v(t)}),[f,v])),_=b[0],I=b[1],w=D3(T,{theme:E,className:o,disabled:d,checked:_,inlineLabel:u,onOffMissing:!y&&!p}),A=_?m:g,P=g$(k3,t.id),R="".concat(P,"-label"),M="".concat(P,"-stateText"),D=_?y:p,k=B$(t,I$,["defaultChecked"]),O=void 0;s||A||(h&&(O=R),D&&!O&&(O=M));var N=e.useRef(null);qj(N),N3(t,_,N);var L={root:{className:w.root,hidden:k.hidden},label:{children:h,className:w.label,htmlFor:P,id:R},container:{className:w.container},pill:IU(IU({},k),{"aria-disabled":d,"aria-checked":_,"aria-label":s||A,"aria-labelledby":O,className:w.pill,"data-is-focusable":!0,"data-ktp-target":!0,disabled:d,id:P,onClick:function(e){d||(I(!_,e),S&&S(e))},ref:N,role:C||"switch",type:"button"}),thumb:{className:w.thumb},stateText:{children:D,className:w.text,htmlFor:P,id:M}};return e.createElement(r,IU({ref:i},L.root),h&&e.createElement(M5,IU({},L.label)),e.createElement("div",IU({},L.container),e.createElement("button",IU({},L.pill),e.createElement("span",IU({},L.thumb))),(_&&y||p)&&e.createElement(M5,IU({},L.stateText))))}));O3.displayName=k3+"Base";var N3=function(t,i,n){e.useImperativeHandle(t.componentRef,(function(){return{get checked(){return!!i},focus:function(){n.current&&n.current.focus()}}}),[i,n])},L3=nj(O3,(function(e){var t,i,n,r,s,a,o,l=e.theme,c=e.className,d=e.disabled,u=e.checked,h=e.inlineLabel,g=e.onOffMissing,p=l.semanticColors,m=l.palette,f=p.bodyBackground,v=p.inputBackgroundChecked,S=p.inputBackgroundCheckedHovered,y=m.neutralDark,C=p.disabledBodySubtext,T=p.smallInputBorder,E=p.inputForegroundChecked,b=p.disabledBodySubtext,_=p.disabledBackground,I=p.smallInputBorder,w=p.inputBorderHovered,A=p.disabledBodySubtext,P=p.disabledText;return{root:["ms-Toggle",u&&"is-checked",!d&&"is-enabled",d&&"is-disabled",l.fonts.medium,{marginBottom:"8px"},h&&{display:"flex",alignItems:"center"},c],label:["ms-Toggle-label",{display:"inline-block"},d&&{color:P,selectors:(t={},t[UV]={color:"GrayText"},t)},h&&!g&&{marginRight:16},g&&h&&{order:1,marginLeft:16},h&&{wordBreak:"break-word"}],container:["ms-Toggle-innerContainer",{display:"flex",position:"relative"}],pill:["ms-Toggle-background",KV(l,{inset:-3}),{fontSize:"20px",boxSizing:"border-box",width:40,height:20,borderRadius:10,transition:"all 0.1s ease",border:"1px solid ".concat(I),background:f,cursor:"pointer",display:"flex",alignItems:"center",padding:"0 3px",overflow:"visible"},!d&&[!u&&{selectors:{":hover":[{borderColor:w}],":hover .ms-Toggle-thumb":[{backgroundColor:y,selectors:(i={},i[UV]={borderColor:"Highlight"},i)}]}},u&&[{background:v,borderColor:"transparent",justifyContent:"flex-end"},{selectors:(n={":hover":[{backgroundColor:S,borderColor:"transparent",selectors:(r={},r[UV]={backgroundColor:"Highlight"},r)}]},n[UV]=IU({backgroundColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)}]],d&&[{cursor:"default"},!u&&[{borderColor:A}],u&&[{backgroundColor:C,borderColor:"transparent",justifyContent:"flex-end"}]],!d&&{selectors:{"&:hover":{selectors:(s={},s[UV]={borderColor:"Highlight"},s)}}}],thumb:["ms-Toggle-thumb",{display:"block",width:12,height:12,borderRadius:"50%",transition:"all 0.1s ease",backgroundColor:T,borderColor:"transparent",borderWidth:6,borderStyle:"solid",boxSizing:"border-box"},!d&&u&&[{backgroundColor:E,selectors:(a={},a[UV]={backgroundColor:"Window",borderColor:"Window"},a)}],d&&[!u&&[{backgroundColor:b}],u&&[{backgroundColor:_}]]],text:["ms-Toggle-stateText",{selectors:{"&&":{padding:"0",margin:"0 8px",userSelect:"none",fontWeight:DV.regular}}},d&&{selectors:{"&&":{color:P,selectors:(o={},o[UV]={color:"GrayText"},o)}}}]}}),void 0,{scope:"Toggle"});const x3={scalingMode:"Crop",isMirrored:!0},F3=(e,t,i,n=!0,r=!0)=>{var s,a;const{microphones:o,speakers:l,cameras:c,selectedMicrophone:d,selectedSpeaker:u,selectedCamera:h,onSelectCamera:g,onSelectMicrophone:p,onSelectSpeaker:m}=e,f={items:[],styles:e.styles,calloutProps:{styles:{root:{maxWidth:"95%"}},preventDismissOnEvent:v0}},v=PH(I3,null!==(a=null===(s=e.styles)||void 0===s?void 0:s.menuItemStyles)&&void 0!==a?a:{});if(c&&h&&g&&n&&(f.items.push({key:"cameras",itemType:fG.Section,sectionProps:{title:t.cameraMenuTitle,items:[{key:"sectionCamera",title:t.cameraMenuTooltip,subMenuProps:{calloutProps:{preventDismissOnEvent:v0},items:c.map((e=>({key:e.id,text:e.name,title:e.name,iconProps:{iconName:"ContextMenuCameraIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:v},canCheck:!0,isChecked:e.id===(null==h?void 0:h.id),onClick:()=>{e.id!==(null==h?void 0:h.id)&&g(e,x3)}})))},text:h.name}]}}),i&&f.items.push(i)),o&&d&&p&&r){const e=l&&l.length>0,i=e?"sectionMicrophone":"sectionAudioDevice",n=e?t.microphoneMenuTooltip:t.audioDeviceMenuTooltip;f.items.push({key:"microphones",itemType:fG.Section,sectionProps:{title:t.microphoneMenuTitle,items:[{key:i,title:n,subMenuProps:{calloutProps:{preventDismissOnEvent:v0},items:o.map((e=>({key:e.id,text:e.name,title:e.name,itemProps:{styles:v},iconProps:{iconName:"ContextMenuMicIcon",styles:{root:{lineHeight:0}}},canCheck:!0,isChecked:e.id===(null==d?void 0:d.id),onClick:()=>{e.id!==(null==d?void 0:d.id)&&p(e)}})))},text:d.name}]}})}if(l&&u&&m&&f.items.push({key:"speakers",itemType:fG.Section,sectionProps:{title:t.speakerMenuTitle,items:[{key:"sectionSpeaker",subMenuProps:{calloutProps:{preventDismissOnEvent:v0},items:l.map((e=>({key:e.id,text:e.name,title:e.name,itemProps:{styles:v},iconProps:{iconName:"ContextMenuSpeakerIcon",styles:{root:{lineHeight:0}}},canCheck:!0,isChecked:e.id===(null==u?void 0:u.id),onClick:()=>{e.id!==(null==u?void 0:u.id)&&m(e)}})))},text:u.name}]}}),o&&d&&p&&r&&i&&f.items.push(i),0!==f.items.length)return f},U3=t=>{var i,n,r;const{onRenderIcon:s}=t,a=AK().strings.devicesButton,o=Object.assign(Object.assign({},a),t.strings),l=null!==(i=t.menuProps)&&void 0!==i?i:F3(Object.assign(Object.assign({},t),{styles:null===(n=t.styles)||void 0===n?void 0:n.menuStyles}),o);return e.createElement(R3,Object.assign({},t,{menuProps:l,menuIconProps:{hidden:!0},onRenderIcon:null!=s?s:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ControlButtonOptions"}),strings:o,labelKey:null!==(r=t.labelKey)&&void 0!==r?r:"devicesButtonLabel"}))};var B3=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const V3=t=>{var i,n,r,s,a,o,l,c,d,u,h,g;const{onToggleMicrophone:p}=t,m=AK().strings.microphoneButton,f=Object.assign(Object.assign({},m),t.strings),[v,S]=(0,e.useState)(void 0),[y,C]=(0,e.useState)(!1),T=null!==(i=t.split)&&void 0!==i?i:t.enableDeviceSelectionMenu,E=t.primaryDisabled||!(!T||(null===(n=t.microphones)||void 0===n?void 0:n.length))||void 0,b=t.disabled||T&&!(null===(r=t.microphones)||void 0===r?void 0:r.length)&&!(null===(s=t.speakers)||void 0===s?void 0:s.length)||!T&&t.microphones&&0===(null===(a=t.microphones)||void 0===a?void 0:a.length),_=t.checked,I=_?f.onSplitButtonAriaLabel:f.offSplitButtonAriaLabel,w=(0,e.useCallback)((e=>{S(e?f.microphoneActionTurnedOnAnnouncement:f.microphoneActionTurnedOffAnnouncement)}),[f.microphoneActionTurnedOffAnnouncement,f.microphoneActionTurnedOnAnnouncement]),A=(0,e.useCallback)((()=>B3(void 0,void 0,void 0,(function*(){if(p)try{yield p(),w(!_)}finally{}}))),[_,p,w]),P={root:{margin:"4px",padding:"0px 12px",flexFlow:"row-reverse",justifyContent:"space-between"},label:{fontWeight:400}},R=[];t.showNoiseSuppressionButton&&R.push({key:"microphoneDNSToggle",onRender:()=>e.createElement(Y$,{onClick:()=>B3(void 0,void 0,void 0,(function*(){var e;yield null===(e=t.onClickNoiseSuppression)||void 0===e?void 0:e.call(t),S(t.isDeepNoiseSuppressionOn?f.deepNoiseSuppressionOnAnnouncement:f.deepNoiseSuppressionOffAnnouncement)}))},e.createElement(L3,{label:f.deepNoiseSuppressionTitle,checked:t.isDeepNoiseSuppressionOn,inlineLabel:!0,styles:P}))}),R.push({key:"microphonePrimaryAction",text:t.checked?f.onSplitButtonMicrophonePrimaryAction:f.offSplitButtonMicrophonePrimaryAction,onClick:()=>{A()},iconProps:{iconName:t.checked?"SplitButtonPrimaryActionMicUnmuted":"SplitButtonPrimaryActionMicMuted",styles:{root:{lineHeight:0}}}});const M={key:"primaryAction",title:"toggle mic",itemType:fG.Section,sectionProps:{topDivider:!0,items:R}};return e.createElement(e.Fragment,null,y&&e.createElement(J0,{announcementString:v,ariaLive:"polite"}),e.createElement(R3,Object.assign({},t,{onClick:t.onToggleMicrophone?A:t.onClick,onRenderOnIcon:null!==(o=t.onRenderOnIcon)&&void 0!==o?o:()=>e.createElement(M3,{disabled:b,iconName:"ControlButtonMicOn"}),onRenderOffIcon:null!==(l=t.onRenderOffIcon)&&void 0!==l?l:()=>e.createElement(M3,{disabled:b,iconName:"ControlButtonMicOff"}),strings:f,labelKey:null!==(c=t.labelKey)&&void 0!==c?c:"microphoneButtonLabel",menuProps:null!==(d=t.menuProps)&&void 0!==d?d:t.enableDeviceSelectionMenu?F3(Object.assign(Object.assign({},t),{styles:null===(u=t.styles)||void 0===u?void 0:u.menuStyles}),f,M):void 0,menuIconProps:(null!==(h=t.menuIconProps)&&void 0!==h?h:!t.enableDeviceSelectionMenu)?{hidden:!0}:void 0,split:null!==(g=t.split)&&void 0!==g?g:t.enableDeviceSelectionMenu,"aria-roledescription":t.enableDeviceSelectionMenu?f.microphoneButtonSplitRoleDescription:void 0,"aria-description":f.microphoneAriaDescription,splitButtonAriaLabel:t.enableDeviceSelectionMenu?I:void 0,disabled:b,primaryDisabled:E,onFocus:()=>C(!0),onBlur:()=>C(!1)})))};var H3=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const $3={scalingMode:"Crop",isMirrored:!0},j3=t=>{var i,n,r,s,a,o,l,c;const{localVideoViewOptions:d,onToggleCamera:u,onSelectCamera:h}=t,[g,p]=(0,e.useState)(!1),m=AK().strings.cameraButton,f=Object.assign(Object.assign({},m),t.strings),[v,S]=(0,e.useState)(void 0),[y,C]=(0,e.useState)(!1),T=t.disabled||g;g&&f.tooltipVideoLoadingContent&&(f.tooltipDisabledContent=f.tooltipVideoLoadingContent);const E=t.checked,b=g&&!E,_=(null!==(i=t.ariaLabel)&&void 0!==i?i:b)?f.tooltipVideoLoadingContent:void 0,I=b?f.tooltipVideoLoadingContent:E?f.onSplitButtonAriaLabel:f.offSplitButtonAriaLabel,w=(0,e.useCallback)((e=>{S(e?f.cameraActionTurnedOnAnnouncement:f.cameraActionTurnedOffAnnouncement)}),[f.cameraActionTurnedOffAnnouncement,f.cameraActionTurnedOnAnnouncement]),A=(0,e.useCallback)((()=>{E||S(f.tooltipVideoLoadingContent)}),[S,E,f.tooltipVideoLoadingContent]),P=(0,e.useCallback)((()=>H3(void 0,void 0,void 0,(function*(){if(u){p(!0);try{yield u(null!=d?d:$3),w(!E)}finally{p(!1)}}}))),[E,d,u,w]),R=(0,e.useCallback)((()=>{A(),P()}),[A,P]),M=(0,e.useCallback)((e=>H3(void 0,void 0,void 0,(function*(){if(h){p(!0);try{yield h(e)}finally{p(!1)}}}))),[h]),D=[];t.onClickVideoEffects&&D.push({key:"effects","data-ui-id":"camera-split-button-video-effects",text:f.videoEffectsMenuItemTitle,iconProps:{iconName:"ControlButtonVideoEffectsOption",styles:{root:{lineHeight:0}}},onClick:()=>{t.onClickVideoEffects&&t.onClickVideoEffects(!0)}}),D.push({key:"cameraPrimaryAction",text:t.checked?f.onSplitButtonPrimaryActionCamera:f.offSplitButtonPrimaryActionCamera,onClick:()=>{P()},iconProps:{iconName:t.checked?"SplitButtonPrimaryActionCameraOn":"SplitButtonPrimaryActionCameraOff",styles:{root:{lineHeight:0}}}});const k={key:"primaryAction",title:"toggle camera",itemType:fG.Section,sectionProps:{topDivider:!0,items:D}},O=(0,e.useMemo)((()=>Object.assign(Object.assign({},t.splitButtonMenuProps),{className:"camera-split-button"})),[t.splitButtonMenuProps]);return e.createElement(e.Fragment,null,y&&e.createElement(J0,{announcementString:v,ariaLive:"polite"}),e.createElement(R3,Object.assign({},t,{disabled:T,onClick:u?R:t.onClick,onRenderOnIcon:null!==(n=t.onRenderOnIcon)&&void 0!==n?n:()=>e.createElement(M3,{disabled:T,iconName:"ControlButtonCameraOn"}),onRenderOffIcon:null!==(r=t.onRenderOffIcon)&&void 0!==r?r:()=>e.createElement(M3,{disabled:T,iconName:"ControlButtonCameraOff"}),strings:f,labelKey:null!==(s=t.labelKey)&&void 0!==s?s:"cameraButtonLabel",menuProps:null!==(a=t.menuProps)&&void 0!==a?a:t.enableDeviceSelectionMenu?F3(Object.assign(Object.assign({},t),{onSelectCamera:M,styles:null===(o=t.styles)||void 0===o?void 0:o.menuStyles}),f,k):void 0,menuIconProps:(null!==(l=t.menuIconProps)&&void 0!==l?l:!t.enableDeviceSelectionMenu)?{hidden:!0}:void 0,split:null!==(c=t.split)&&void 0!==c?c:t.enableDeviceSelectionMenu,"aria-description":f.cameraButtonAriaDescription,"aria-roledescription":t.enableDeviceSelectionMenu?f.cameraButtonSplitRoleDescription:void 0,ariaLabel:_,splitButtonAriaLabel:t.enableDeviceSelectionMenu?I:void 0,splitButtonMenuProps:O,onFocus:()=>C(!0),onBlur:()=>C(!1)})))},G3=t=>{var i,n,r,s;const a=AK().strings.screenShareButton,o=Object.assign(Object.assign({},a),t.strings),l=qK(),c=q3(l);return e.createElement(R3,Object.assign({},t,{styles:e$(c,t.styles),onClick:null!==(i=t.onToggleScreenShare)&&void 0!==i?i:t.onClick,onRenderOnIcon:null!==(n=t.onRenderOnIcon)&&void 0!==n?n:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ControlButtonScreenShareStop"}),onRenderOffIcon:null!==(r=t.onRenderOffIcon)&&void 0!==r?r:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ControlButtonScreenShareStart"}),strings:o,labelKey:null!==(s=t.labelKey)&&void 0!==s?s:"screenShareButtonLabel",disabled:t.disabled}))},q3=e=>({rootChecked:{background:e.semanticColors.primaryButtonBackground,color:e.semanticColors.primaryButtonText,":focus::after":{outlineColor:`${NV.white} !important`},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},rootCheckedHovered:{background:e.semanticColors.primaryButtonBackgroundHovered,color:e.semanticColors.primaryButtonTextHovered,":focus::after":{outlineColor:`${NV.white} !important`},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},rootCheckedPressed:{background:e.semanticColors.primaryButtonBackgroundPressed,color:e.semanticColors.primaryButtonTextPressed},labelChecked:{color:e.semanticColors.primaryButtonText}}),z3="ms-acs-participant-item-menu-icon",W3=(e,t)=>({paddingTop:"0.25rem",paddingBottom:"0.25rem",display:"flex",maxWidth:"100%",minWidth:"8rem",cursor:e.clickable?"pointer":"default",alignItems:"center",":focus-visible":{[` .${z3}`]:{display:"flex"},outline:`0.1rem solid ${t.palette.themePrimary}`}}),K3={display:"none"},J3={width:"auto"},Y3={maxWidth:"5rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:"normal",marginLeft:"0.5rem",marginRight:0},Q3={display:"flex",alignItems:"center",height:"100%",paddingTop:"0.2rem"},Z3=dB([z3,{display:"flex",lineHeight:0,alignItems:"center"}]),X3={paddingRight:"0.5rem"},e6=t=>{var i,n,r;const{userId:s,displayName:a,onRenderAvatar:o,menuItems:l,onRenderIcon:c,presence:d,styles:u,me:h,onClick:g,showParticipantOverflowTooltip:p}=t,[m,f]=(0,e.useState)(!1),[v,S]=(0,e.useState)(!0),y=(0,e.useRef)(null),C=aJ(),T=AK().strings.participantItem,E=DX(),b=g$(),_=g$(),I=!!(l&&(null==l?void 0:l.length)>0),w=Object.assign(Object.assign({},T),t.strings),A=t6(t,w),P=!A&&(m||!v)&&I,R=(null==a?void 0:a.trim())||"",M={text:h?R:(null==a?void 0:a.trim())||w.displayNamePlaceholder,size:HZ.size32,presence:d,initialsTextColor:"white",showOverflowTooltip:p,showUnknownPersonaCoin:!(h||(null==a?void 0:a.trim())&&a!==w.displayNamePlaceholder)},D=o?o(null!=s?s:"",M):e.createElement(RX,Object.assign({className:dB({lineHeight:"1.15rem"},null==u?void 0:u.avatar)},M)),k=(0,e.useMemo)((()=>dB(X3,{color:C.palette.neutralSecondary},null==u?void 0:u.me)),[C.palette.neutralSecondary,null==u?void 0:u.me]),O=(0,e.useMemo)((()=>dB({background:C.palette.neutralLighterAlt},null==u?void 0:u.menu)),[C.palette.neutralLighterAlt,null==u?void 0:u.menu]),N=(0,e.useMemo)((()=>dB(Q3,{color:C.palette.neutralSecondary,marginLeft:"auto"},null==u?void 0:u.iconContainer)),[C.palette.neutralSecondary,null==u?void 0:u.iconContainer]),L=()=>{f(!1),S(!0)},x=(0,e.useMemo)((()=>e.createElement(Y$,{horizontal:!0,horizontalAlign:"end",className:dB(J3,{color:C.palette.neutralPrimary}),title:w.menuTitle,"aria-controls":_,"data-ui-id":E.participantItemMenuButton},e.createElement(mG,{iconName:"ParticipantItemOptionsHovered",className:dB(Z3,P?{}:K3)}))),[C.palette.neutralPrimary,w.menuTitle,_,E.participantItemMenuButton,P]);return e.createElement("div",{ref:y,role:"menuitem",id:b,"aria-label":null!==(n=I?null===(i=t.strings)||void 0===i?void 0:i.participantItemWithMoreOptionsAriaLabel:void 0)&&void 0!==n?n:null===(r=t.strings)||void 0===r?void 0:r.participantItemAriaLabel,"aria-labelledby":`${t.ariaLabelledBy} ${b}`,"aria-expanded":!v,"aria-disabled":!I&&!t.onClick,"aria-haspopup":!!I||void 0,"aria-controls":_,"data-is-focusable":I,"data-ui-id":"participant-item",className:dB(W3({clickable:I},C),null==u?void 0:u.root),onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),onClick:()=>{A||(f(!0),S(!1),null==g||g(t)),v||L()},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||S(!1)},tabIndex:I?0:void 0},e.createElement(Y$,{horizontal:!0,className:dB({flexGrow:1,maxWidth:"100%",alignItems:"center"})},D,h&&e.createElement(oJ,{className:k},w.isMeText),e.createElement(Y$,{horizontal:!0,className:dB(N)},!P&&c&&c(t),!h&&A?e.createElement(oJ,{"data-ui-id":"participant-item-state-string",className:dB(Y3)},A):e.createElement(e.Fragment,null,I&&e.createElement(e.Fragment,null,x,e.createElement(GW,{id:_,items:l,hidden:v,target:y,onItemClick:L,onDismiss:L,directionalHint:6,className:O,calloutProps:{preventDismissOnEvent:v0}}))))))},t6=(e,t)=>"EarlyMedia"===e.participantState||"Ringing"===e.participantState?null==t?void 0:t.participantStateRinging:"Hold"===e.participantState?null==t?void 0:t.participantStateHold:void 0,i6=dB({height:"100%",padding:"0.125rem"}),n6={root:{paddingLeft:"1rem",paddingRight:"1rem",":focus-visible":{margin:"0.125rem"}}},r6=dB({display:"flex",lineHeight:0,alignItems:"center"}),s6=t=>{var i,n,r,s,a;const{excludeMe:o=!1,myUserId:l,participants:c,onRemoveParticipant:d,onRenderAvatar:u,onRenderParticipant:h,onFetchParticipantMenuItems:g,showParticipantOverflowTooltip:p,totalParticipantCount:m,strings:f,participantAriaLabelledBy:v,pinnedParticipants:S}=t,y=aJ(),C=DX(),T=AK().strings.participantItem,E=AK().strings.ParticipantList,b=(0,e.useMemo)((()=>h?c:((e,t,i)=>{if(!t||!i)return[...e];const n=e.map((e=>e.userId)).indexOf(i);if(-1===n)return[...e];const r=[...e];return r.splice(n,1),r})(c,o,l)),[c,o,l,h]);(e=>{const t=function(e){return"raisedHand"in e};e.sort(((e,i)=>{if(!t(e)||!t(i))return 0;const n=e,r=i;return n.raisedHand&&r.raisedHand?n.raisedHand.raisedHandOrderPosition-r.raisedHand.raisedHandOrderPosition:n.raisedHand?-1:r.raisedHand?1:0}))})(b);const _=(0,e.useCallback)((e=>{var i,n;let r=[];const s=e.isRemovable;return e.userId!==l&&d&&s&&r.push({key:"remove",text:T.removeButtonLabel,onClick:()=>d(e.userId),itemProps:{styles:null===(n=null===(i=t.styles)||void 0===i?void 0:i.participantItemStyles)||void 0===n?void 0:n.participantSubMenuItemsStyles},iconProps:{iconName:"ContextMenuRemoveParticipant",styles:{root:{lineHeight:0}}},"data-ui-id":C.participantListRemoveParticipantButton}),g&&(r=g(e.userId,l,r)),r}),[C.participantListRemoveParticipantButton,l,g,d,null===(n=null===(i=t.styles)||void 0===i?void 0:i.participantItemStyles)||void 0===n?void 0:n.participantSubMenuItemsStyles,T.removeButtonLabel]),I=(0,e.useMemo)((()=>{var e;return PH(n6,null===(e=t.styles)||void 0===e?void 0:e.participantItemStyles)}),[null===(r=t.styles)||void 0===r?void 0:r.participantItemStyles]),w=null!==(s=null==f?void 0:f.overflowParticipantCount)&&void 0!==s?s:null==E?void 0:E.overflowParticipantCount;return e.createElement(Y$,{"data-ui-id":C.participantList,className:dB(i6,null===(a=t.styles)||void 0===a?void 0:a.root),role:"menu"},b.map((i=>h?h(i):((t,i,n,r,s,a,o,l,c,d,u)=>{var h,g,p,m,f,v,S,y,C,T,E,b,_,I;const w=t;let A;w&&(A=$Z.none);const P=s&&s(t),R=(e=>e&&i.attendeeRole?PK(e,{AttendeeRole:i.attendeeRole}):e)(t.displayName),M=d.callingPalette,D=u&&(null==u?void 0:u.includes(t.userId)),k=null==w?void 0:w.isScreenSharing,O=null==w?void 0:w.isMuted,N=null==w?void 0:w.raisedHand,L=!(null==w?void 0:w.mediaAccess)||w.mediaAccess.isAudioPermitted,x=!(null==w?void 0:w.mediaAccess)||w.mediaAccess.isVideoPermitted,F=k||O||N||D||!L||!x?()=>{var t,n;return e.createElement(Y$,{horizontal:!0,tokens:{childrenGap:"0.5rem"}},w.raisedHand&&e.createElement(Y$,{horizontal:!0,tokens:{childrenGap:"0.2rem"},style:{alignItems:"center",padding:"0.1rem 0.2rem",backgroundColor:null==d?void 0:d.palette.neutralLighter,borderRadius:"0.3rem"}},w.raisedHand.raisedHandOrderPosition&&e.createElement(Y$.Item,null,e.createElement(oJ,null,null===(t=w.raisedHand)||void 0===t?void 0:t.raisedHandOrderPosition)),e.createElement(Y$.Item,null,e.createElement(kX,null))),w.isScreenSharing&&e.createElement(mG,{iconName:"ParticipantItemScreenShareStart",className:r6,ariaLabel:i.sharingIconLabel}),w.spotlight&&e.createElement(mG,{iconName:"ParticipantItemSpotlighted",className:r6}),D&&e.createElement(mG,{iconName:"ParticipantItemPinned",className:r6}),w.mediaAccess&&!w.mediaAccess.isVideoPermitted?e.createElement(mG,{iconName:"ControlButtonCameraProhibited",className:r6,ariaLabel:i.mutedIconLabel}):void 0,w.mediaAccess&&!(null===(n=w.mediaAccess)||void 0===n?void 0:n.isAudioPermitted)?e.createElement(mG,{iconName:"ControlButtonMicProhibited",className:r6,ariaLabel:i.mutedIconLabel}):void 0,w.mediaAccess&&!w.mediaAccess.isAudioPermitted||!w.isMuted?void 0:e.createElement(mG,{iconName:"ParticipantItemMicOff",className:r6,ariaLabel:i.mutedIconLabel}))}:()=>null,U=(null==w?void 0:w.raisedHand)&&r?(e,t,i)=>r(e,Object.assign(Object.assign({},t),{styles:{root:{border:M.raiseHandGold}}}),i):r,B=null!==(h=P&&P.length>0?null==i?void 0:i.participantItemWithMoreOptionsAriaLabel:void 0)&&void 0!==h?h:null==i?void 0:i.participantItemAriaLabel,V=PK(null!=B?B:"",{displayName:null!=R?R:"",connectionState:null!==(g=t6(w,i))&&void 0!==g?g:"",mutedState:null!==(p=w.isMuted?null==i?void 0:i.mutedIconLabel:void 0)&&void 0!==p?p:"",micDisabledState:null!==(f=!1===(null===(m=w.mediaAccess)||void 0===m?void 0:m.isAudioPermitted)?null==i?void 0:i.micDisabledIconLabel:void 0)&&void 0!==f?f:"",cameraDisabledState:null!==(S=!1===(null===(v=w.mediaAccess)||void 0===v?void 0:v.isVideoPermitted)?null==i?void 0:i.cameraDisabledIconLabel:void 0)&&void 0!==S?S:"",sharingState:null!==(y=w.isScreenSharing?null==i?void 0:i.sharingIconLabel:void 0)&&void 0!==y?y:"",handRaisedState:null!==(I=(null===(C=w.raisedHand)||void 0===C?void 0:C.raisedHandOrderPosition)?PK(null!==(T=null==i?void 0:i.handRaisedIconLabel)&&void 0!==T?T:"",{position:null!==(_=null===(b=null===(E=w.raisedHand)||void 0===E?void 0:E.raisedHandOrderPosition)||void 0===b?void 0:b.toString())&&void 0!==_?_:""}):void 0)&&void 0!==I?I:""});return e.createElement(e6,{styles:a,key:t.userId,userId:t.userId,displayName:R,me:!!n&&t.userId===n,menuItems:P,presence:A,onRenderIcon:F,onRenderAvatar:U,onClick:o?()=>null==o?void 0:o(t):void 0,showParticipantOverflowTooltip:l,participantState:w.state,ariaLabelledBy:c,strings:{participantItemAriaLabel:V}})})(i,T,l,u,_,I,t.onParticipantClick,p,v,y,S))),w&&m&&m>b.length&&e.createElement(oJ,{style:{fontWeight:400,margin:"0.5rem"}},PK(w,{overflowCount:""+(m-b.length)})))},a6=dB({width:4}),o6=t=>{var i,n;const{styles:r,enableEndCallMenu:s,onHangUp:a}=t,o=AK().strings.endCallButton,l=Object.assign(Object.assign({},o),t.strings),c=aJ(),d=ZH(LX(c)?u6:h6,s?g6:{},null!=r?r:{}),u=(0,e.useCallback)((()=>e.createElement(e.Fragment,null,e.createElement(mG,{iconName:"ControlButtonEndCall"}),s&&e.createElement("span",{className:a6}))),[s]),h={items:[{key:"endForSelf",text:o.leaveOption,title:o.leaveOption,onClick:()=>{a&&a(!1)}},{key:"endForEveryone",text:o.endCallOption,title:o.endCallOption,onClick:()=>{a&&a(!0)}}],styles:t.styles,calloutProps:{styles:{root:{maxWidth:"95%"}},preventDismissOnEvent:v0}};return e.createElement(e.Fragment,null,e.createElement(R3,Object.assign({},t,{menuProps:s?h:t.menuProps,onClick:a?()=>a():t.onClick,styles:d,onRenderIcon:null!==(i=t.onRenderIcon)&&void 0!==i?i:u,strings:l,labelKey:null!==(n=t.labelKey)&&void 0!==n?n:"endCallButtonLabel"})))},l6=e=>{var t;return{regular:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRed,"@media (forced-colors: active)":{forcedColorAdjust:"auto",border:`1px ${null===(t=e.palette)||void 0===t?void 0:t.neutralQuaternaryAlt} solid`}," i":{color:e.callingPalette.iconWhite},":focus::after":{outlineColor:`${e.callingPalette.iconWhite} !important`}},pressed:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRedDarker,border:"none"," i":{color:e.callingPalette.iconWhite},"@media (forced-colors: active)":{forcedColorAdjust:"auto"}},hovered:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRedDark,border:"none"," i":{color:e.callingPalette.iconWhite},"@media (forced-colors: active)":{forcedColorAdjust:"auto"}}}},c6=l6(tJ),d6=l6(eJ),u6={root:c6.regular,rootHovered:c6.hovered,rootPressed:c6.pressed,label:{color:tJ.callingPalette.iconWhite},splitButtonMenuButton:Object.assign(Object.assign({},c6.regular),{borderTop:"none",borderRight:"none",borderBottom:"none","&:hover":c6.hovered}),splitButtonMenuButtonChecked:c6.hovered,splitButtonMenuButtonExpanded:c6.pressed},h6={root:d6.regular,rootHovered:d6.hovered,rootPressed:d6.pressed,splitButtonMenuButton:Object.assign(Object.assign({},d6.regular),{borderTop:"none",borderRight:"none",borderBottom:"none","&:hover":d6.hovered}),splitButtonMenuButtonChecked:d6.hovered,splitButtonMenuButtonExpanded:d6.pressed,splitButtonMenuFocused:d6.pressed,label:{color:eJ.callingPalette.iconWhite}},g6={root:{padding:"0 0.75rem"}};const p6=t=>{const{onStartCaptions:i,onStopCaptions:n,onSetSpokenLanguage:r,currentSpokenLanguage:s}=t,a=AK().strings.startCaptionsButton,o=Object.assign(Object.assign({},a),t.strings),l=(0,e.useMemo)((()=>({spokenLanguage:""===s?UK:s})),[s]),[c,d]=(0,e.useState)(!1),u=(0,e.useCallback)((()=>{return e=void 0,r=void 0,a=function*(){t.checked?n():yield i(l)},new((s=void 0)||(s=Promise))((function(t,i){function n(e){try{l(a.next(e))}catch(e){i(e)}}function o(e){try{l(a.throw(e))}catch(e){i(e)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof s?i:new s((function(e){e(i)}))).then(n,o)}l((a=a.apply(e,r||[])).next())}));var e,r,s,a}),[t.checked,i,n,l]);return(0,e.useEffect)((()=>{t.checked&&!c&&(r(l.spokenLanguage),d(!0))}),[t.checked,r,l.spokenLanguage,c]),e.createElement(R3,Object.assign({},t,{strings:o,onClick:null!=u?u:t.onClick,onRenderOnIcon:()=>e.createElement(M3,{disabled:t.disabled,iconName:"CaptionsIcon"}),onRenderOffIcon:()=>e.createElement(M3,{disabled:t.disabled,iconName:"CaptionsOffIcon"})}))},m6=t=>{var i,n,r,s,a,o,l,c;const{callerName:d,alertText:u,avatarImage:h,onAcceptWithAudio:g,onAcceptWithVideo:p,onReject:m,onDismiss:f,personaSize:v,styles:S,strings:y,acceptOptions:C}=t,T=qK(),E=AK().strings.IncomingCallNotification,b=E.incomingCallNotificationPlaceholderAlert&&d?PK(E.incomingCallNotificationPlaceholderAlert,{callerName:d}):d,_=C.showAcceptWithVideo?{items:[{key:"audio",text:null!==(i=null==y?void 0:y.incomingCallNotificationAcceptButtonLabel)&&void 0!==i?i:E.incomingCallNotificationAcceptButtonLabel,onClick:()=>g()},{key:"video",text:null!==(n=null==y?void 0:y.incomingCallNotificationAccceptWithVideoButtonLabel)&&void 0!==n?n:E.incomingCallNotificationAccceptWithVideoButtonLabel,onClick:()=>p()}]}:void 0;return e.createElement(Y$,{tokens:{childrenGap:"0.5rem"},verticalAlign:"center",styles:(null==S?void 0:S.root)?S.root:f6(T)},e.createElement(Y$,{horizontal:!0,verticalAlign:"center",tokens:{childrenGap:v?"0.5rem":"0rem"}},e.createElement(Y$,{horizontalAlign:"start",styles:(null==S?void 0:S.avatarContainer)?S.avatarContainer:v6},e.createElement(RX,{imageUrl:h,text:d,size:HZ.size24,coinSize:v,hidePersonaDetails:!0,"aria-label":d})),e.createElement(Y$,{grow:!0,horizontalAlign:"center",style:{alignItems:"flex-start",fontFamily:"Segoe UI"}},e.createElement(oJ,{tabIndex:0,"aria-live":"assertive","aria-label":null!=u?u:b},null!==(r=null!=u?u:null==y?void 0:y.incomingCallNotificationPlaceholderAlert)&&void 0!==r?r:b)),e.createElement(oK,{ariaLabel:null!==(s=null==y?void 0:y.incomingCallNotificationDismissButtonAriaLabel)&&void 0!==s?s:E.incomingCallNotificationDismissButtonAriaLabel,iconProps:{iconName:"cancel"},onClick:f,styles:S6(T)})),e.createElement(Y$,{horizontal:!0,horizontalAlign:"center",tokens:{childrenGap:"0.5rem"}},e.createElement(mJ,{styles:(null==S?void 0:S.acceptButton)?S.acceptButton:y6(T),onClick:()=>g(),iconProps:{iconName:"IncomingCallNotificationAcceptIcon",style:{lineHeight:"1rem"}},ariaLabel:null!==(a=null==y?void 0:y.incomingCallNoticicationAcceptWithAudioAriaLabel)&&void 0!==a?a:E.incomingCallNoticicationAcceptWithAudioAriaLabel,menuProps:_},null!==(o=null==y?void 0:y.incomingCallNotificationAcceptButtonLabel)&&void 0!==o?o:E.incomingCallNotificationAcceptButtonLabel),e.createElement(pJ,{styles:(null==S?void 0:S.rejectButton)?S.rejectButton:C6(T),onClick:()=>m(),iconProps:{iconName:"IncomingCallNotificationRejectIcon"},ariaLabel:null!==(l=null==y?void 0:y.incomingCallNoticicationRejectAriaLabel)&&void 0!==l?l:E.incomingCallNoticicationRejectAriaLabel},null!==(c=null==y?void 0:y.incomingCallNotificationRejectButtonLabel)&&void 0!==c?c:E.incomingCallNotificationRejectButtonLabel)))},f6=e=>({root:{width:"20rem",background:e.palette.white,opacity:.95,borderRadius:"0.5rem",boxShadow:e.effects.elevation8,padding:"1rem"}}),v6={root:{marginRight:"0.5rem"}},S6=e=>({root:{color:e.palette.neutralPrimary,width:"1rem",height:"1rem"},rootHovered:{color:e.palette.neutralDark}}),y6=e=>({root:{color:e.palette.white,border:"none",borderRadius:e.effects.roundedCorner4,width:"100%",maxWidth:"8.875rem"},rootHovered:{color:e.palette.white},icon:{height:"1.25rem"}}),C6=e=>({root:{borderRadius:e.effects.roundedCorner4,maxWidth:"8.875rem",width:"100%"},icon:{height:"1.25rem"}}),T6=t=>{const{activeIncomingCalls:i,removedIncomingCalls:n,onAcceptCall:r,onRejectCall:s,styles:a,strings:o,tabIndex:l}=t;return e.createElement(Y$,{tokens:{childrenGap:"0.25rem"},role:"group",tabIndex:l},i.filter((e=>!n.some((t=>t.id===e.id)))).map((t=>e.createElement(m6,{key:t.id,callerName:t.callerInfo.displayName,onAcceptWithAudio:()=>r(t.id),onAcceptWithVideo:()=>r(t.id,!0),onReject:()=>s(t.id),onDismiss:()=>s(t.id),styles:a,strings:o,acceptOptions:{showAcceptWithVideo:t.videoAvailable}}))))},E6=e=>({maxWidth:"16rem",textAlign:"center",background:`${e.palette.white}`,borderRadius:"0.75rem",margin:"auto"}),b6=e=>({fontSize:"1.25rem",fontWeight:e.fonts.medium.fontWeight,color:`${e.palette.themePrimary}`}),_6=(e,t)=>({field:{padding:0,textAlign:"center",fontSize:`${vJ(18)}`,fontWeight:400,width:t?"10rem":"12rem",height:"3rem",borderRadius:"0.5rem",position:"relative",overflowX:"hidden",textOverflow:"clip"},root:{backgroundColor:`${e.palette.neutralLighter}`,marginBottom:"0.625rem",height:"3rem",borderRadius:"0.5rem"},fieldGroup:{border:"none",borderRadius:"0.5rem",width:"12rem",height:"3rem",backgroundColor:`${e.palette.neutralLighter}`,":after":{borderRadius:"0.5rem"}},errorMessage:{color:e.semanticColors.errorText},suffix:{padding:0,position:"absolute",right:"0.25rem",top:"0.55rem",transform:"scale(1.15)",background:"unset"}}),I6=e=>({fontSize:"0.625rem",color:`${e.palette.neutralSecondary}`,fontWeight:400,margin:"0.125rem",minHeight:"0.75rem"}),w6=e=>({root:{color:`${e.palette.black}`,padding:0,background:"transparent"},icon:{height:"auto",background:"transparent","> span":{display:"flex"}}}),A6=(e,t)=>{if(!e)return e;t&&"1"===e[0]&&11===e.length&&(e=`+${e}`);let i="";"1"===e[0]?(i="1 ",e=e.slice(1,e.length)):"+"===e[0]&&(i=e.slice(0,2)+" ",e=e.slice(2,e.length));const n=e.length;return n<4||n>10?i.replace(" ","")+e:n<7?`${i}(${e.slice(0,3)}) ${e.slice(3)}`:`${i}(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6,e.length)}`};class P6{constructor(e,t,i){this.isPlaying=!1,this.play=()=>{if(this.isPlaying)return;const e=this.context.createGain();e.gain.value=.1,e.connect(this.context.destination),this.oscillatorNode1=this.context.createOscillator(),this.oscillatorNode1.frequency.value=this.frequency1,this.oscillatorNode1.connect(e),this.oscillatorNode2=this.context.createOscillator(),this.oscillatorNode2.frequency.value=this.frequency2,this.oscillatorNode2.connect(e),this.oscillatorNode1.start(),this.oscillatorNode2.start(),this.isPlaying=!0},this.stop=()=>{this.oscillatorNode1&&this.oscillatorNode2&&(this.oscillatorNode1.stop(),this.oscillatorNode2.stop(),this.oscillatorNode1.disconnect(),this.oscillatorNode2.disconnect(),this.isPlaying=!1)},this.context=e,this.frequency1=t,this.frequency2=i}}const R6={1:{f1:697,f2:1209},2:{f1:697,f2:1336},3:{f1:697,f2:1477},4:{f1:770,f2:1209},5:{f1:770,f2:1336},6:{f1:770,f2:1477},7:{f1:852,f2:1209},8:{f1:852,f2:1336},9:{f1:852,f2:1477},"*":{f1:941,f2:1209},0:{f1:941,f2:1336},"#":{f1:941,f2:1477}};var M6=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const D6=[[{digit:"1"},{digit:"2",letter:"ABC"},{digit:"3",letter:"DEF"}],[{digit:"4",letter:"GHI"},{digit:"5",letter:"JKL"},{digit:"6",letter:"MNO"}],[{digit:"7",letter:"PQRS"},{digit:"8",letter:"TUV"},{digit:"9",letter:"WXYZ"}],[{digit:"*"},{digit:"0",letter:"+"},{digit:"#"}]],k6=["Num1","Num2","Num3","Num4","Num5","Num6","Num7","Num8","Num9","Star","Num0","Pound"],O6=t=>{var i,n,r,s;const a=qK(),{digit:o,index:l,onClick:c,onLongPress:d,longPressTrigger:u,dtmfToneAudioContext:h,disableDtmfPlayback:g}=t,[p,m]=(0,e.useState)(!1),f=(0,e.useRef)(new P6(h,R6[o].f1,R6[o].f2)),v=XX(e.useMemo((()=>({onClick:()=>M6(void 0,void 0,void 0,(function*(){c(o,l)})),onLongPress:()=>M6(void 0,void 0,void 0,(function*(){d(o,l)})),touchEventsOnly:"touch"===u})),[o,l,u,c,d]));return e.createElement(pJ,Object.assign({"data-test-id":`dialpad-button-${t.index}`,styles:ZH({root:{background:"none",fontWeight:600,fontSize:`${vJ(20)}`,border:"none",borderRadius:0,width:"3rem",height:"3rem",padding:`${vJ(16)}, ${vJ(5)}, ${vJ(16)}, ${vJ(5)}`,minWidth:0,minHeight:0}},null===(i=t.styles)||void 0===i?void 0:i.button)},v,{onKeyDown:e=>{if(("Enter"===e.key||" "===e.key)&&!p)return g||f.current.play(),v.onKeyDown(),void m(!0);"Tab"!==e.key&&"ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"ArrowUp"!==e.key&&"ArrowDown"!==e.key?v.onKeyDown():f.current.stop()},onKeyUp:e=>{"Enter"!==e.key&&" "!==e.key||!p||(f.current.stop(),v.onKeyUp(),m(!1)),v.onKeyUp()},onMouseDown:()=>{g||f.current.play(),v.onMouseDown()},onMouseUp:()=>{f.current.stop(),v.onMouseUp()},onMouseLeave:()=>{f.current.stop()},onTouchStart:()=>{g||f.current.play(),v.onTouchStart()},onTouchEnd:()=>{f.current.stop(),v.onTouchEnd()}}),e.createElement(Y$,null,e.createElement(oJ,{className:dB(b6(a),null===(n=t.styles)||void 0===n?void 0:n.digit)},t.digit),e.createElement(oJ,{className:dB(I6(a),null===(r=t.styles)||void 0===r?void 0:r.letter)},null!==(s=t.letter)&&void 0!==s?s:" ")))},N6=t=>{var i,n;const r=qK(),{onSendDtmfTone:s,onClickDialpadButton:a,textFieldValue:o,onChange:l,showDeleteButton:c=!0,longPressTrigger:d="mouseAndTouch",disableDtmfPlayback:u,dialpadMode:h="dialer",dtmfAudioContext:g}=t,p=(0,e.useRef)(g||new AudioContext),[m,f]=(0,e.useState)(null!=o?o:""),v=(0,e.useRef)(m);(0,e.useEffect)((()=>{v.current!==m&&(null==l||l(m)),v.current=m}),[v,m,l]),(0,e.useEffect)((()=>{C(null!=o?o:"")}),[o]);const S=(e,t)=>{C(m+e);const i=k6[t];s&&i&&s(i),a&&a(e,t)},y=(e,t)=>{C("0"===e&&10===t?m+"+":m+e);const i=k6[t];s&&i&&s(i),a&&a(e,t)},C=e=>{const t=x6(e);f(t)},T=()=>{const e=m.substring(0,m.length-1);C(e)};return e.createElement(Y$,{className:dB(E6(r),null===(i=t.styles)||void 0===i?void 0:i.root),"data-test-id":"dialpadContainer","data-ui-id":"dialpadContainer",horizontalAlign:"center"},"dialer"===h&&e.createElement(U5,{styles:ZH(_6(r,""!==m),null===(n=t.styles)||void 0===n?void 0:n.textField),value:o||A6(m),onChange:e=>{C(e.target.value)},onClick:e=>{e.preventDefault()},placeholder:t.strings.placeholderText,"data-test-id":"dialpad-input",onRenderSuffix:()=>{var i;return e.createElement(e.Fragment,null,c&&0!==m.length&&e.createElement(oK,{ariaLabel:t.strings.deleteButtonAriaLabel,onClick:T,styles:ZH(w6(r),null===(i=t.styles)||void 0===i?void 0:i.deleteIcon),iconProps:{iconName:"DialpadBackspace"}}))}}),e.createElement(iq,null,D6.map(((i,n)=>e.createElement(Y$,{horizontal:!0,key:`row_${n}`,horizontalAlign:"stretch",tokens:{childrenGap:"1rem"}},i.map(((r,s)=>e.createElement(O6,{key:`button_${s}`,index:s+n*i.length,digit:r.digit,letter:r.letter,styles:t.styles,onClick:S,onLongPress:y,longPressTrigger:d,dtmfToneAudioContext:p.current,disableDtmfPlayback:u}))))))))},L6=t=>{const i=AK().strings.dialpad,n=Object.assign(Object.assign({},i),t.strings);return e.createElement(N6,Object.assign({strings:n},t))},x6=e=>e.replace(/[^\d*#+]/g,""),F6=t=>{const{onToggleHold:i,strings:n}=t;return e.createElement(R3,Object.assign({},t,{strings:n,onClick:null!=i?i:t.onClick,onRenderOnIcon:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ResumeCall"}),onRenderOffIcon:()=>e.createElement(M3,{disabled:t.disabled,iconName:"HoldCallButton"})}))},U6=t=>{var i,n,r,s;const a=AK().strings.raiseHandButton,o=Object.assign(Object.assign({},a),t.strings),l=qK(),c=B6(l);return e.createElement(R3,Object.assign({},t,{styles:ZH(c,t.styles),onClick:null!==(i=t.onToggleRaiseHand)&&void 0!==i?i:t.onClick,onRenderOnIcon:null!==(n=t.onRenderOnIcon)&&void 0!==n?n:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ControlButtonLowerHand"}),onRenderOffIcon:null!==(r=t.onRenderOffIcon)&&void 0!==r?r:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ControlButtonRaiseHand"}),strings:o,labelKey:null!==(s=t.labelKey)&&void 0!==s?s:"raiseHandButtonLabel","aria-label":t.checked?o.onLabel:o.offLabel,"aria-description":t.checked?o.tooltipOnContent:o.tooltipOffContent,disabled:t.disabled}))},B6=e=>({rootChecked:{background:e.palette.themePrimary,color:NV.white,":focus::after":{outlineColor:`${NV.white}`}},rootCheckedHovered:{background:e.palette.themePrimary,color:NV.white,":focus::after":{outlineColor:`${NV.white}`}},labelChecked:{color:NV.white}});var V6="NOT_FOUND",H6=function(e,t){return e===t};function $6(e,t){var i,n,r="object"==typeof t?t:{equalityCheck:t},s=r.equalityCheck,a=void 0===s?H6:s,o=r.maxSize,l=void 0===o?1:o,c=r.resultEqualityCheck,d=function(e){return function(t,i){if(null===t||null===i||t.length!==i.length)return!1;for(var n=t.length,r=0;r<n;r++)if(!e(t[r],i[r]))return!1;return!0}}(a),u=1===l?(i=d,{get:function(e){return n&&i(n.key,e)?n.value:V6},put:function(e,t){n={key:e,value:t}},getEntries:function(){return n?[n]:[]},clear:function(){n=void 0}}):function(e,t){var i=[];function n(e){var n=i.findIndex((function(i){return t(e,i.key)}));if(n>-1){var r=i[n];return n>0&&(i.splice(n,1),i.unshift(r)),r.value}return V6}return{get:n,put:function(t,r){n(t)===V6&&(i.unshift({key:t,value:r}),i.length>e&&i.pop())},getEntries:function(){return i},clear:function(){i=[]}}}(l,d);function h(){var t=u.get(arguments);if(t===V6){if(t=e.apply(null,arguments),c){var i=u.getEntries().find((function(e){return c(e.value,t)}));i&&(t=i.value)}u.put(arguments,t)}return t}return h.clearCache=function(){return u.clear()},h}function j6(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var s,a=0,o={memoizeOptions:void 0},l=n.pop();if("object"==typeof l&&(o=l,l=n.pop()),"function"!=typeof l)throw new Error("createSelector expects an output function after the inputs, but received: ["+typeof l+"]");var c=o.memoizeOptions,d=void 0===c?i:c,u=Array.isArray(d)?d:[d],h=function(e){var t=Array.isArray(e[0])?e[0]:e;if(!t.every((function(e){return"function"==typeof e}))){var i=t.map((function(e){return"function"==typeof e?"function "+(e.name||"unnamed")+"()":typeof e})).join(", ");throw new Error("createSelector expects all input-selectors to be functions, but received the following types: ["+i+"]")}return t}(n),g=e.apply(void 0,[function(){return a++,l.apply(null,arguments)}].concat(u)),p=e((function(){for(var e=[],t=h.length,i=0;i<t;i++)e.push(h[i].apply(null,arguments));return s=g.apply(null,e)}));return Object.assign(p,{resultFunc:l,memoizedResultFunc:g,dependencies:h,lastResult:function(){return s},recomputations:function(){return a},resetRecomputations:function(){return a=0}}),p}}var G6=j6($6);const q6=e=>e.deviceManager,z6=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.role},W6=(e,t)=>{var i,n;return null!==(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.hideAttendeeNames)&&void 0!==n&&n},K6=(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.capabilitiesFeature)||void 0===n?void 0:n.capabilities},J6=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.remoteParticipants},Y6=(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.raiseHand)||void 0===n?void 0:n.localParticipantRaisedHand},Q6=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.spotlight},Z6=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.localParticipantReaction},X6=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.isScreenSharingOn},e8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.isMuted},t8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.localVideoStreams},i8=e=>{var t;return null===(t=e.callAgent)||void 0===t?void 0:t.displayName},n8=e=>iL(e.userId),r8=e=>e.latestErrors,s8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.diagnostics},a8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.state},o8=e=>e.environmentInfo,l8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.isCaptionsFeatureActive},c8=(e,t)=>{var i,n;return""===(null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.currentCaptionLanguage)?"en":null===(n=e.calls[t.callId])||void 0===n?void 0:n.captionsFeature.currentCaptionLanguage},d8=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.currentSpokenLanguage},u8=G6([(e,t)=>!!e.calls[t.callId],e8,q6,K6,z6,a8],((e,t,i,n,r,s)=>{const a=!i.deviceAccess||i.deviceAccess.audio,o=!1===(null==n?void 0:n.unmuteMic.isPresent)&&"NotInitialized"!==(null==n?void 0:n.unmuteMic.reason)||"Consumer"===r;return{disabled:!e||!a||o||"LocalHold"===s,checked:!!e&&!t,microphones:i.microphones,speakers:i.speakers,selectedMicrophone:i.selectedMicrophone,selectedSpeaker:i.selectedSpeaker}})),h8=G6([t8,q6,K6,z6,a8],((e,t,i,n,r)=>{const s=cL(t),a=null==e?void 0:e.find((e=>"Video"===e.mediaStreamType)),o=!t.deviceAccess||t.deviceAccess.video,l=!1===(null==i?void 0:i.turnVideoOn.isPresent)&&"NotInitialized"!==(null==i?void 0:i.turnVideoOn.reason)||"Consumer"===n;return{disabled:!t.selectedCamera||!o||!t.cameras.length||l||"LocalHold"===r,checked:void 0!==e&&e.length>0?!!a:s,cameras:t.cameras,selectedCamera:t.selectedCamera}})),g8=G6([Y6,a8],((e,t)=>{var i;return{checked:!!e,disabled:"InLobby"===t||null!==(i="Connecting"===t)&&void 0!==i&&i}})),p8=G6([Z6,a8],((e,t)=>({checked:!!e,disabled:"Connected"!==t}))),m8=G6([X6,a8,K6,z6],((e,t,i,n)=>{let r;return r=r||!1===(null==i?void 0:i.shareScreen.isPresent)&&"NotInitialized"!==(null==i?void 0:i.shareScreen.reason)||"Consumer"===n||"Attendee"===n,r=r||["InLobby","Connecting","LocalHold"].includes(null!=t?t:"None"),{checked:e,disabled:r}})),f8=G6([q6],(e=>({microphones:v8(e.microphones),speakers:v8(e.speakers),cameras:v8(e.cameras),selectedMicrophone:e.selectedMicrophone,selectedSpeaker:e.selectedSpeaker,selectedCamera:e.selectedCamera})));function v8(e){return e.filter((e=>""!==e.name))}const S8=G6([a8],(e=>({checked:"LocalHold"===e}))),y8=e=>e.isSpeaking&&!e.isMuted,C8=sL(((e,t,i,n,r,s,a,o,l,c,d)=>((e,t,i,n,r,s,a,o,l,c,d)=>{const u=nL(e);return{userId:e,displayName:t,state:i,isMuted:n,isScreenSharing:r,isSpeaking:s,raisedHand:a,isRemovable:("communicationUser"===XN(u).kind||"phoneNumber"===XN(u).kind)&&o,reaction:l,spotlight:c,mediaAccess:d}})(e,t,i,n,r,s,a,o,l,c,d))),T8=nU((e=>e&&e.reactionMessage?{reactionType:e.reactionMessage.reactionType,receivedOn:e.receivedOn}:void 0)),E8=nU(((e,t)=>{const i=null==e?void 0:e.find((e=>iL(e.identifier)===t));return i?{spotlightedOrderPosition:i.order}:void 0})),b8=e=>{var t;return null===(t=null==e?void 0:e.speakersList)||void 0===t?void 0:t.map(iL)},_8=(e,t,i)=>e?I8((n=>Object.values(e).filter((e=>!["InLobby","Idle","Connecting","Disconnected"].includes(e.state)||YN(e.identifier))).map((e=>{const r=gL(e),s=pL(e.displayName,i,e.role,t),a=T8(e.reactionState),o=e.spotlight;return n(iL(e.identifier),e.isMuted,y8(e),e.videoStreams,r,s,e.raisedHand,e.contentSharingStream,a,o,e.mediaAccess,e.role)})))):[],I8=sL(((e,t,i,n,r,s,a,o,l,c,d,u,h)=>w8(e,t,i,n,r,s,a,o,l,c,h,d,u))),w8=(e,t,i,n,r,s,a,o,l,c,d,u,h)=>{const g=Object.values(n);let p,m;const f=Object.values(g).findLast((e=>"Video"===e.mediaStreamType&&e.isAvailable))||Object.values(g).findLast((e=>"Video"===e.mediaStreamType)),v=Object.values(g).findLast((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable))||Object.values(g).findLast((e=>"ScreenSharing"===e.mediaStreamType));return f&&(p=A8(f)),v&&(m=A8(v)),o&&(m=P8(o)),{userId:e,displayName:s,isMuted:t,isSpeaking:i,videoStream:p,screenShareStream:m,isScreenSharingOn:void 0!==m&&m.isAvailable,state:r,raisedHand:a,reaction:l,spotlight:c,mediaAccess:u,canAudioBeForbidden:"Attendee"===h,canVideoBeForbidden:"Attendee"===h}},A8=e=>{var t,i,n;return{id:e.id,isAvailable:e.isAvailable,isReceiving:e.isReceiving,isMirrored:null===(t=e.view)||void 0===t?void 0:t.isMirrored,renderElement:null===(i=e.view)||void 0===i?void 0:i.target,scalingMode:null===(n=e.view)||void 0===n?void 0:n.scalingMode,streamSize:e.streamSize}},P8=e=>({isAvailable:!!e,isReceiving:!0,isMirrored:!1,renderElement:e}),R8=nU(((e,t,i,n,r,s,a,o,l,c,d)=>{var u,h,g;return{userId:e,displayName:null!=t?t:"",isMuted:i,isScreenSharingOn:n,videoStream:{isAvailable:!!r,isMirrored:null===(u=null==r?void 0:r.view)||void 0===u?void 0:u.isMirrored,renderElement:null===(h=null==r?void 0:r.view)||void 0===h?void 0:h.target},screenShareStream:{isAvailable:!!s,renderElement:null===(g=null==s?void 0:s.view)||void 0===g?void 0:g.target},role:a,raisedHand:o,reaction:l,spotlight:c,capabilities:d,mediaAccess:{isAudioPermitted:!(null==d?void 0:d.unmuteMic)||d.unmuteMic.isPresent,isVideoPermitted:!(null==d?void 0:d.turnVideoOn)||d.turnVideoOn.isPresent}}})),M8=nU((e=>null==e?void 0:e.map((e=>iL(e.identifier))))),D8=nU((e=>{var t,i,n,r,s,a;return{mainVideoStream:{id:null===(t=null==e?void 0:e.mainVideoStream)||void 0===t?void 0:t.id,isReceiving:null===(i=null==e?void 0:e.mainVideoStream)||void 0===i?void 0:i.isReceiving,isAvailable:null===(n=null==e?void 0:e.mainVideoStream)||void 0===n?void 0:n.isAvailable,renderElement:null===(s=null===(r=null==e?void 0:e.mainVideoStream)||void 0===r?void 0:r.view)||void 0===s?void 0:s.target,streamSize:null===(a=null==e?void 0:e.mainVideoStream)||void 0===a?void 0:a.streamSize}}})),k8=nU((e=>e)),O8=G6([J6],(e=>{{const t=Object.assign({},e);return Object.keys(t).forEach((e=>{var i;"Consumer"===(null===(i=t[e])||void 0===i?void 0:i.role)&&delete t[e]})),t}})),N8=G6([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.screenShareRemoteParticipant},O8,t8,e8,X6,i8,n8,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.dominantSpeakers},(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.optimalVideoCount.maxRemoteVideoStreams},z6,Y6,W6,Z6,Q6,K6,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.togetherMode}],((e,t,i,n,r,s,a,o,l,c,d,u,h,g,p,m)=>{const f=e&&t?t[e]:void 0,v=null==i?void 0:i.find((e=>"Video"===e.mediaStreamType)),S=null==i?void 0:i.find((e=>"ScreenSharing"===e.mediaStreamType)),y=b8(o),C={};null==y||y.forEach(((e,t)=>C[e]=t));const T=T8(h),E=M8(null==g?void 0:g.spotlightedParticipants);return{screenShareParticipant:f?w8(iL(f.identifier),f.isMuted,y8(f),f.videoStreams,f.state,f.displayName,f.raisedHand,f.contentSharingStream,void 0,f.spotlight,void 0,f.mediaAccess,c):void 0,localParticipant:R8(a,s,n,r,v,S,c,d,T,null==g?void 0:g.localParticipantSpotlight,p),remoteParticipants:_8(uL(t?Object.values(t):[]),u,c),dominantSpeakers:y,maxRemoteVideoStreams:l,spotlightedParticipants:E,maxParticipantsToSpotlight:null==g?void 0:g.maxParticipantsToSpotlight,togetherModeStreams:D8(null==m?void 0:m.streams),togetherModeSeatingCoordinates:k8(null==m?void 0:m.seatingPositions),isTogetherModeActive:null==m?void 0:m.isActive,startTogetherModeEnabled:null==p?void 0:p.startTogetherMode.isPresent}})),L8=G6([n8,i8,O8,X6,e8,Y6,z6,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.totalParticipantCount},W6,Z6,Q6,K6],((e,t,i,n,r,s,a,o,l,c,d,u)=>{const h=x8(a),g=i?((e,t,i,n,r)=>C8((s=>e.filter((e=>!ZN(e.identifier))).filter((e=>!["InLobby","Idle","Connecting","Disconnected"].includes(e.state)||YN(e.identifier))).map((e=>{const a=Object.values(e.videoStreams).some((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable)),o=gL(e),l=pL(e.displayName,n,e.role,i),c=T8(e.reactionState),d=E8(r,iL(e.identifier));return s(iL(e.identifier),l,o,e.isMuted,a,e.isSpeaking,e.raisedHand,t,c,d,e.mediaAccess)})).sort(((e,t)=>{var i,n;const r=(null===(i=e.displayName)||void 0===i?void 0:i.toLowerCase())||"",s=(null===(n=t.displayName)||void 0===n?void 0:n.toLowerCase())||"";return r<s?-1:r>s?1:0})))))(uL(Object.values(i)),h,l,a,null==d?void 0:d.spotlightedParticipants):[];return g.push({userId:e,displayName:t,isScreenSharing:n,isMuted:r,raisedHand:s,state:"Connected",isRemovable:!1,reaction:T8(c),spotlight:E8(null==d?void 0:d.spotlightedParticipants,e),mediaAccess:{isAudioPermitted:!(null==u?void 0:u.unmuteMic)||u.unmuteMic.isPresent,isVideoPermitted:!(null==u?void 0:u.turnVideoOn)||u.turnVideoOn.isPresent}}),{participants:g,myUserId:e,totalParticipantCount:o}})),x8=e=>"Presenter"===e||"Unknown"===e||void 0===e,F8=G6([L8],(e=>e));var U8=r(2222),B8=r.n(U8);const V8=t=>{var i,n,r,s;const{callInvitationURL:a,styles:o,onMuteAll:l,onRenderIcon:c,onRenderParticipantList:d,participants:u,myUserId:h,excludeMe:g,onRenderParticipant:p,onRenderAvatar:m,onRemoveParticipant:f,onFetchParticipantMenuItems:v,showParticipantOverflowTooltip:S}=t,y=t.disabled,[C,T]=(0,e.useState)(""),E=DX(),b=(0,e.useCallback)((()=>{l&&l()}),[l]),_=(0,e.useCallback)((()=>{var t;return e.createElement(s6,{participants:u,myUserId:h,excludeMe:g,onRenderParticipant:p,onRenderAvatar:m,onRemoveParticipant:f,onFetchParticipantMenuItems:v,styles:null===(t=null==o?void 0:o.menuStyles)||void 0===t?void 0:t.participantListStyles,showParticipantOverflowTooltip:S})}),[g,h,f,m,p,u,null===(i=null==o?void 0:o.menuStyles)||void 0===i?void 0:i.participantListStyles,v,S]),I=(0,e.useCallback)((()=>!!a&&B8()(a)),[a]),w=AK().strings.participantsButton,A=(0,e.useMemo)((()=>Object.assign(Object.assign({},w),t.strings)),[w,t.strings]),P=u.length,R=(0,e.useCallback)((()=>{T(A.copyInviteLinkActionedAriaLabel),setTimeout((()=>{T("")}),3e3)}),[A.copyInviteLinkActionedAriaLabel]),M=(0,e.useCallback)((()=>{var e;const t=[];return P>0&&(t.push({key:"participantListMenuItemKey",onRender:null!=d?d:_}),t.push({key:"participantsDivider1",itemType:fG.Divider}),l&&t.push({key:"muteAllKey",text:A.muteAllButtonLabel,title:A.muteAllButtonLabel,styles:null===(e=null==o?void 0:o.menuStyles)||void 0===e?void 0:e.menuItemStyles,iconProps:{iconName:"MicOff2"},onClick:b})),t}),[P,d,_,l,A.muteAllButtonLabel,null===(n=null==o?void 0:o.menuStyles)||void 0===n?void 0:n.menuItemStyles,b]),D=(0,e.useMemo)((()=>{var e,t;const i={title:A.menuHeader,ariaLabel:A.menuHeader,styles:PH(_3,null==o?void 0:o.menuStyles),items:[],calloutProps:{preventDismissOnEvent:v0}};if(P>0){let t=u.map((e=>e.userId)).length;g&&(t-=1),i.items.push({key:"participantCountKey",name:PK(A.participantsListButtonLabel,{numParticipants:`${t}`}),itemProps:{styles:null===(e=null==o?void 0:o.menuStyles)||void 0===e?void 0:e.menuItemStyles},iconProps:{iconName:"People"},subMenuProps:{items:M(),calloutProps:{styles:{root:{maxWidth:"100%"}},style:{maxHeight:"20rem"},preventDismissOnEvent:v0}},"data-ui-id":E.participantButtonPeopleMenuItem})}return a&&i.items.push({key:"InviteLinkKey",name:A.copyInviteLinkButtonLabel,title:A.copyInviteLinkButtonLabel,itemProps:{styles:null===(t=null==o?void 0:o.menuStyles)||void 0===t?void 0:t.menuItemStyles},iconProps:{iconName:"Link"},onClick:()=>{I(),R()}}),i}),[A.menuHeader,A.participantsListButtonLabel,A.copyInviteLinkButtonLabel,null==o?void 0:o.menuStyles,P,a,u,g,E.participantButtonPeopleMenuItem,M,I,R]);return e.createElement(e.Fragment,null,e.createElement(J0,{announcementString:C,ariaLive:"polite"}),e.createElement(R3,Object.assign({},t,{disabled:y,menuProps:null!==(r=t.menuProps)&&void 0!==r?r:D,menuIconProps:{hidden:!0},onRenderIcon:null!=c?c:()=>e.createElement(M3,{disabled:y,iconName:"ControlButtonParticipants"}),strings:A,"aria-label":A.ariaLabel,labelKey:null!==(s=t.labelKey)&&void 0!==s?s:"participantsButtonLabel"})))},H8=G6([r8,s8,q6,o8],((e,t,i,n)=>{var r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C,T;const E=[],b=()=>"safari"===(null==n?void 0:n.environment.browser),_=()=>"mac"===(null==n?void 0:n.environment.platform);(null===(r=null==t?void 0:t.network.latest.networkReceiveQuality)||void 0===r?void 0:r.value)!==zb.Bad&&(null===(s=null==t?void 0:t.network.latest.networkReceiveQuality)||void 0===s?void 0:s.value)!==zb.Poor||E.push({type:"callNetworkQualityLow"}),!0===(null===(a=null==t?void 0:t.media.latest.noSpeakerDevicesEnumerated)||void 0===a?void 0:a.value)&&E.push({type:"callNoSpeakerFound"}),!0===(null===(o=null==t?void 0:t.media.latest.noMicrophoneDevicesEnumerated)||void 0===o?void 0:o.value)&&E.push({type:"callNoMicrophoneFound"}),!1===(null===(l=i.deviceAccess)||void 0===l?void 0:l.audio)&&b()&&E.push({type:"callMicrophoneAccessDeniedSafari"}),!0===(null===(c=null==t?void 0:t.media.latest.microphonePermissionDenied)||void 0===c?void 0:c.value)&&_()?E.push({type:"callMacOsMicrophoneAccessDenied"}):(!1===(null===(d=i.deviceAccess)||void 0===d?void 0:d.audio)&&!b()||!0===(null===(u=null==t?void 0:t.media.latest.microphonePermissionDenied)||void 0===u?void 0:u.value)&&!_())&&E.push({type:"callMicrophoneAccessDenied"});const I=(null==t?void 0:t.media.latest.microphoneMuteUnexpectedly)||(null==t?void 0:t.media.latest.microphoneNotFunctioning);I&&(I.value===zb.Bad?E.push({type:"callMicrophoneMutedBySystem"}):I.value===zb.Good&&E.push({type:"callMicrophoneUnmutedBySystem"}));const w=null==t?void 0:t.media.latest.cameraStoppedUnexpectedly;return w&&(w.value===zb.Bad?E.push({type:"callVideoStoppedBySystem"}):w.value===zb.Good&&E.push({type:"callVideoRecoveredBySystem"})),!1===(null===(h=i.deviceAccess)||void 0===h?void 0:h.video)&&b()?E.push({type:"callCameraAccessDeniedSafari"}):!1===(null===(g=i.deviceAccess)||void 0===g?void 0:g.video)?E.push({type:"callCameraAccessDenied"}):!0===(null===(p=null==t?void 0:t.media.latest.cameraFreeze)||void 0===p?void 0:p.value)&&E.push({type:"cameraFrozenForRemoteParticipants"}),!0===(null===(m=null==t?void 0:t.media.latest.cameraPermissionDenied)||void 0===m?void 0:m.value)&&_()&&E.push({type:"callMacOsCameraAccessDenied"}),!0===(null===(f=null==t?void 0:t.media.latest.screenshareRecordingDisabled)||void 0===f?void 0:f.value)&&_()?E.push({type:"callMacOsScreenShareAccessDenied"}):!0===(null===(v=null==t?void 0:t.media.latest.screenshareRecordingDisabled)||void 0===v?void 0:v.value)&&E.push({type:"startScreenShareGeneric"}),$8(E,e,"Call.stopVideo","stopVideoGeneric"),$8(E,e,"Call.mute","muteGeneric"),$8(E,e,"Call.stopScreenSharing","stopScreenShareGeneric"),"Call.startVideo: Video operation failure SourceUnavailableError"===(null===(S=e["Call.startVideo"])||void 0===S?void 0:S.message)?$8(E,e,"Call.startVideo","callCameraAlreadyInUse"):"Call.startVideo: Video operation failure permissionDeniedError"===(null===(y=e["Call.startVideo"])||void 0===y?void 0:y.message)?$8(E,e,"Call.startVideo","callCameraAccessDenied"):$8(E,e,"Call.startVideo","startVideoGeneric"),$8(E,e,"Call.unmute","unmuteGeneric"),$8(E,e,"Call.mutedByOthers","mutedByRemoteParticipant"),$8(E,e,"VideoEffectsFeature.startEffects","unableToStartVideoEffect"),"CallAgent.join: Invalid meeting link"===(null===(C=e["CallAgent.join"])||void 0===C?void 0:C.message)?$8(E,e,"CallAgent.join","failedToJoinCallInvalidMeetingLink"):$8(E,e,"CallAgent.join","failedToJoinCallGeneric"),(null===(T=e["Call.feature"])||void 0===T?void 0:T.message.match(/Call\.feature: startSpotlight failed\. \d+ is the max number of participants that can be Spotlighted/g))&&$8(E,e,"Call.feature","startSpotlightWhileMaxParticipantsAreSpotlighted"),E.splice(j8),{activeErrorMessages:E}})),$8=(e,t,i,n)=>{void 0!==t[i]&&e.push({type:n,timestamp:t[i].timestamp})},j8=3,G8=SB((()=>NB({from:{backgroundPosition:"0px 8568px"},to:{backgroundPosition:"0px 0px"}}))),q8={root:{border:"none",height:"2.75rem",width:"2.75rem"}},z8={container:{},root:{},beak:{},beakCurtain:{},calloutMain:{display:"flex",justifyContent:"center",alignItems:"center",flexDirection:"row",width:"13.75rem",height:"2.625rem",":hover > :not(:hover)":{opacity:"0.5"}}},W8=t=>{var i,n,r,s,a,o,l;const c=AK().strings.reactionButton,d=Object.assign(Object.assign({},c),t.strings),u=qK(),h=(e=>({rootChecked:{background:e.palette.themePrimary,color:e.palette.white},rootCheckedHovered:{background:e.palette.themePrimary,color:e.palette.white},labelChecked:{color:e.palette.white}}))(u),g=new Map([["like",d.likeReactionTooltipContent],["heart",d.heartReactionTooltipContent],["applause",d.applauseReactionTooltipContent],["laugh",d.laughReactionTooltipContent],["surprised",d.surprisedReactionTooltipContent]]),p=new Map([["like",null===(i=t.reactionResources.likeReaction)||void 0===i?void 0:i.url],["heart",null===(n=t.reactionResources.heartReaction)||void 0===n?void 0:n.url],["applause",null===(r=t.reactionResources.applauseReaction)||void 0===r?void 0:r.url],["laugh",null===(s=t.reactionResources.laughReaction)||void 0===s?void 0:s.url],["surprised",null===(a=t.reactionResources.surprisedReaction)||void 0===a?void 0:a.url]]),m={styles:{root:{padding:0},calloutMain:{padding:"0.5rem"}},backgroundColor:LX(u)?u.palette.neutralLighter:""},f=(0,e.useRef)(null),v=(0,e.useRef)(null),[S,y]=(0,e.useState)(!1);return e.createElement(Y$,null,S&&e.createElement($z,{"data-ui-id":"reaction-sub-menu",isBeakVisible:!1,styles:z8,target:f.current,onDismiss:()=>{var e;null===(e=v.current)||void 0===e||e.focus(),y(!1)}},e.createElement(iq,{shouldFocusOnMount:!0,style:{height:"100%"}},e.createElement(Y$,{horizontal:!0,style:{height:"inherit"}},["like","heart","applause","laugh","surprised"].map(((i,n)=>{const r=dB(((e,t)=>{const i=null!=t?t:51;return{display:"flex",flexDirection:"column",height:"100%",width:"100%",backgroundImage:`url(${e})`,justifyContent:"center",alignItems:"center",backgroundSize:"2.75rem 133.875rem",transition:"opacity 2s",minWidth:"2.75rem",backgroundColor:"transparent",transform:"scale(0.6)",":hover":{transform:"scale(0.8)",animationName:G8(),animationDuration:"8.12s",animationTimingFunction:`steps(${i})`,animationIterationCount:"infinite",backgroundColor:"transparent"},":active":{backgroundColor:"transparent"}}})(p.get(i)||"",void 0!==t.reactionResources?p1(i,t.reactionResources):0));return e.createElement(YZ,{key:n,"data-ui-id":n,hidden:t.disableTooltip,content:g.get(i),styles:{root:{display:"flex",flexDirection:"column",height:"100%",width:"2.75rem"}},calloutProps:Object.assign({},m)},e.createElement(pJ,{role:"menuitem",key:n,onClick:()=>{var e;t.onReactionClick(i),null===(e=v.current)||void 0===e||e.focus(),y(!1)},className:r,styles:q8,"aria-label":g.get(i)}))}))))),e.createElement("div",{ref:f},e.createElement(R3,Object.assign({},t,{componentRef:v,styles:ZH(h,t.styles),onClick:()=>y(!S),onRenderIcon:null!==(o=t.onRenderIcon)&&void 0!==o?o:()=>e.createElement(M3,{disabled:t.disabled,iconName:"ReactionButtonIcon"}),strings:d,split:!0,labelKey:null!==(l=t.labelKey)&&void 0!==l?l:"reactionButtonLabel",onRenderMenuIcon:()=>e.createElement("div",null),disabled:t.disabled,ariaLabel:d.ariaLabel}))))},K8=G6([r8,e=>e.latestNotifications,s8,q6,a8,o8,(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.meetingConference)||void 0===n?void 0:n.conferencePhones},(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.breakoutRooms)||void 0===n?void 0:n.assignedBreakoutRoom}],((e,t,i,n,r,s,a,o)=>{var l,c,d,u,h,g,p,m,f,v,S,y,C,T,E,b,_,I,w;const A=[],P=()=>"safari"===(null==s?void 0:s.environment.browser),R=()=>"mac"===(null==s?void 0:s.environment.platform);let M=!1;a&&a.length>0&&(M=!0),(null===(l=null==i?void 0:i.network.latest.networkReceiveQuality)||void 0===l?void 0:l.value)!==zb.Bad&&(null===(c=null==i?void 0:i.network.latest.networkReceiveQuality)||void 0===c?void 0:c.value)!==zb.Poor||(M?A.push({type:"teamsMeetingCallNetworkQualityLow"}):A.push({type:"callNetworkQualityLow"})),!0===(null===(d=null==i?void 0:i.media.latest.noSpeakerDevicesEnumerated)||void 0===d?void 0:d.value)&&A.push({type:"callNoSpeakerFound"}),!0===(null===(u=null==i?void 0:i.media.latest.noMicrophoneDevicesEnumerated)||void 0===u?void 0:u.value)&&A.push({type:"callNoMicrophoneFound"}),!1===(null===(h=n.deviceAccess)||void 0===h?void 0:h.audio)&&P()&&A.push({type:"callMicrophoneAccessDeniedSafari"}),!0===(null===(g=null==i?void 0:i.media.latest.microphonePermissionDenied)||void 0===g?void 0:g.value)&&R()?A.push({type:"callMacOsMicrophoneAccessDenied"}):(!1===(null===(p=n.deviceAccess)||void 0===p?void 0:p.audio)&&!P()||!0===(null===(m=null==i?void 0:i.media.latest.microphonePermissionDenied)||void 0===m?void 0:m.value)&&!R())&&A.push({type:"callMicrophoneAccessDenied"});const D=(null==i?void 0:i.media.latest.microphoneMuteUnexpectedly)||(null==i?void 0:i.media.latest.microphoneNotFunctioning);D&&(D.value===zb.Bad?A.push({type:"callMicrophoneMutedBySystem"}):D.value===zb.Good&&A.push({type:"callMicrophoneUnmutedBySystem"}));const k=null==i?void 0:i.media.latest.cameraStoppedUnexpectedly;k&&(k.value===zb.Bad?A.push({type:"callVideoStoppedBySystem"}):k.value===zb.Good&&A.push({type:"callVideoRecoveredBySystem"})),!1===(null===(f=n.deviceAccess)||void 0===f?void 0:f.video)&&P()?A.push({type:"callCameraAccessDeniedSafari"}):!1===(null===(v=n.deviceAccess)||void 0===v?void 0:v.video)?A.push({type:"callCameraAccessDenied"}):!0===(null===(S=null==i?void 0:i.media.latest.cameraFreeze)||void 0===S?void 0:S.value)&&A.push({type:"cameraFrozenForRemoteParticipants"}),!0===(null===(y=null==i?void 0:i.media.latest.cameraPermissionDenied)||void 0===y?void 0:y.value)&&R()&&A.push({type:"callMacOsCameraAccessDenied"}),!0===(null===(C=null==i?void 0:i.media.latest.screenshareRecordingDisabled)||void 0===C?void 0:C.value)&&R()?A.push({type:"callMacOsScreenShareAccessDenied"}):!0===(null===(T=null==i?void 0:i.media.latest.screenshareRecordingDisabled)||void 0===T?void 0:T.value)&&A.push({type:"startScreenShareGeneric"}),J8(A,e,"Call.stopVideo","stopVideoGeneric"),J8(A,e,"Call.mute","muteGeneric"),J8(A,e,"Call.stopScreenSharing","stopScreenShareGeneric"),"Call.startVideo: Video operation failure SourceUnavailableError"===(null===(E=e["Call.startVideo"])||void 0===E?void 0:E.message)?J8(A,e,"Call.startVideo","callCameraAlreadyInUse"):"Call.startVideo: Video operation failure permissionDeniedError"===(null===(b=e["Call.startVideo"])||void 0===b?void 0:b.message)?J8(A,e,"Call.startVideo","callCameraAccessDenied"):J8(A,e,"Call.startVideo","startVideoGeneric"),J8(A,e,"Call.unmute","unmuteGeneric"),!t||t.capabilityUnmuteMicAbsent||t.capabilityUnmuteMicPresent||J8(A,e,"Call.mutedByOthers","mutedByRemoteParticipant"),J8(A,e,"VideoEffectsFeature.startEffects","unableToStartVideoEffect"),"CallAgent.join: Invalid meeting link"===(null===(_=e["CallAgent.join"])||void 0===_?void 0:_.message)?J8(A,e,"CallAgent.join","failedToJoinCallInvalidMeetingLink"):J8(A,e,"CallAgent.join","failedToJoinCallGeneric"),(null===(I=e["Call.feature"])||void 0===I?void 0:I.message.match(/Call\.feature: startSpotlight failed\. \d+ is the max number of participants that can be Spotlighted/g))&&J8(A,e,"Call.feature","startSpotlightWhileMaxParticipantsAreSpotlighted");const O=[];return(null===(w=null==i?void 0:i.media.latest.speakingWhileMicrophoneIsMuted)||void 0===w?void 0:w.value)&&"Connected"===r&&O.push({type:"speakingWhileMuted",timestamp:new Date(Date.now()),autoDismiss:!0,ariaLive:"off"}),t.assignedBreakoutRoomOpened&&O.push({type:"assignedBreakoutRoomOpened",timestamp:t.assignedBreakoutRoomOpened.timestamp}),t.assignedBreakoutRoomOpenedPromptJoin&&o&&O.push({type:"assignedBreakoutRoomOpenedPromptJoin",timestamp:t.assignedBreakoutRoomOpenedPromptJoin.timestamp,onClickPrimaryButton:()=>o.join()}),t.assignedBreakoutRoomChanged&&O.push({type:"assignedBreakoutRoomChanged",timestamp:t.assignedBreakoutRoomChanged.timestamp}),t.assignedBreakoutRoomClosed&&O.push({type:"assignedBreakoutRoomClosed",timestamp:t.assignedBreakoutRoomClosed.timestamp}),t.breakoutRoomJoined&&O.push({type:"breakoutRoomJoined",timestamp:t.breakoutRoomJoined.timestamp}),t.breakoutRoomClosingSoon&&O.push({type:"breakoutRoomClosingSoon",timestamp:t.breakoutRoomClosingSoon.timestamp}),t.capabilityTurnVideoOnPresent&&O.push({type:"capabilityTurnVideoOnPresent",timestamp:t.capabilityTurnVideoOnPresent.timestamp}),t.capabilityTurnVideoOnAbsent&&O.push({type:"capabilityTurnVideoOnAbsent",timestamp:t.capabilityTurnVideoOnAbsent.timestamp}),t.capabilityUnmuteMicPresent&&O.push({type:"capabilityUnmuteMicPresent",timestamp:t.capabilityUnmuteMicPresent.timestamp}),t.capabilityUnmuteMicAbsent&&O.push({type:"capabilityUnmuteMicAbsent",timestamp:t.capabilityUnmuteMicAbsent.timestamp}),t.togetherModeStarted&&O.push({type:"togetherModeStarted",timestamp:t.togetherModeStarted.timestamp,autoDismiss:!0}),t.togetherModeEnded&&O.push({type:"togetherModeEnded",timestamp:t.togetherModeEnded.timestamp,autoDismiss:!0}),{activeErrorMessages:A,activeNotifications:O}})),J8=(e,t,i,n)=>{void 0!==t[i]&&e.push({type:n,timestamp:t[i].timestamp})},Y8=G6([e=>Object.values(e.incomingCalls),e=>Object.values(e.incomingCallsEnded),q6],((e,t,i)=>({activeIncomingCalls:e.map((e=>Object.assign(Object.assign({},e),{callerInfo:{displayName:e.callerInfo.displayName||"Unknown Caller"},videoAvailable:!(e.callerInfo.identifier&&YN(e.callerInfo.identifier)||0===(null==i?void 0:i.cameras.length))}))),removedIncomingCalls:t.map((e=>Object.assign(Object.assign({},e),{callerInfo:{displayName:e.callerInfo.displayName||"Unknown Caller"},videoAvailable:!(e.callerInfo.identifier&&YN(e.callerInfo.identifier)||0===(null==i?void 0:i.cameras.length))})))}))),Q8=G6([l8,c8,d8],((e,t,i)=>({checked:null!=e&&e,currentCaptionLanguage:null!=t?t:"",currentSpokenLanguage:null!=i?i:"en-us"}))),Z8=G6([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.supportedCaptionLanguages},c8,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.supportedSpokenLanguages},d8,l8],((e,t,i,n,r)=>({supportedCaptionLanguages:null!=e?e:[],currentCaptionLanguage:null!=t?t:"en",supportedSpokenLanguages:null!=i?i:["en-us"],currentSpokenLanguage:null!=n?n:"en-us",isCaptionsFeatureActive:null!=r&&r}))),X8=G6([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.captions},(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.realTimeTextFeature.realTimeTexts},l8,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.realTimeTextFeature.isRealTimeTextFeatureActive},(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.startCaptionsInProgress},J6,i8,n8],((e,t,i,n,r,s,a,o)=>{var l,c;const d=null==e?void 0:e.map(((e,t)=>{const i=e7(e);let n;if(i===o)n=a;else if(s){const e=s[i];e&&(n=e.displayName)}return{id:(null!=n?n:"Unnamed Participant")+t,displayName:null!=n?n:"Unnamed Participant",captionText:e.captionText,userId:i,createdTimeStamp:e.timestamp}})),u=null===(l=null==t?void 0:t.completedMessages)||void 0===l?void 0:l.filter((e=>""!==e.message)).map((e=>{const t=t7(e);return{id:e.sequenceId,displayName:i7(e,o,s,a,t),message:e.message,userId:t,isTyping:"Partial"===e.resultType,isMe:e.isMe,finalizedTimeStamp:e.updatedTimestamp}})),h=null===(c=null==t?void 0:t.currentInProgress)||void 0===c?void 0:c.filter((e=>""!==e.message)).map((e=>{const t=t7(e);return{id:e.sequenceId,displayName:i7(e,o,s,a,t),message:e.message,userId:t,isTyping:"Partial"===e.resultType,isMe:e.isMe,finalizedTimeStamp:e.updatedTimestamp}})),g=(null==t?void 0:t.myInProgress)&&""!==t.myInProgress.message?{id:t.myInProgress.sequenceId,displayName:a,message:t.myInProgress.message,userId:o,isTyping:"Partial"===t.myInProgress.resultType,isMe:!0,finalizedTimeStamp:t.myInProgress.updatedTimestamp}:void 0;let p;return g||(p=t&&t.completedMessages&&t.completedMessages.slice().reverse().find((e=>e.isMe))),{captions:null!=d?d:[],realTimeTexts:{completedMessages:u,currentInProgress:h,myInProgress:g},isCaptionsOn:null!=i&&i,startCaptionsInProgress:null!=r&&r,isRealTimeTextOn:null!=n&&n,latestLocalRealTimeText:null!=g?g:p}})),e7=e=>e.speaker.identifier?iL(e.speaker.identifier):"",t7=e=>e.sender.identifier?iL(e.sender.identifier):"",i7=(e,t,i,n,r)=>{let s;if(r===t)s=n;else if(i){const e=i[r];e&&(s=e.displayName)}return null!=s?s:"Unnamed Participant"},n7=()=>({}),r7=e=>s7(e),s7=e=>{if(e===L6)return n7;switch(e){case w5:return N8;case V3:return u8;case j3:return h8;case G3:return m8;case U3:return f8;case s6:return L8;case V8:return F8;case o6:return n7;case BK:return H8;case U6:return g8;case W8:return p8;case bJ:return K8;case F6:return S8;case T6:return Y8;case p4:return X8;case T3:return Z8;case p6:return Q8}},a7=(e,t)=>o7(e,d7,t),o7=(t,i,n)=>{var r;const s=LZ(),a=(0,e.useRef)(!1);(0,e.useEffect)((()=>(a.current=!0,()=>{a.current=!1})));const o=null===(r=s.getState().call)||void 0===r?void 0:r.id,l=(0,e.useMemo)((()=>({callId:o})),[o]),[c,d]=(0,e.useState)(t(i(s.getState()),null!=n?n:l)),u=(0,e.useRef)(c);return u.current=c,(0,e.useEffect)((()=>{const e=e=>{if(!a.current)return;const r=t(i(e),null!=n?n:l);u.current!==r&&d(r)};return s.onStateChange(e),()=>{s.offStateChange(e)}}),[i,s,t,n,l]),c},l7=nU(((e,t,i,n,r,s,a,o)=>({userId:e,incomingCalls:{},incomingCallsEnded:{},callsEnded:{},deviceManager:t,callAgent:{displayName:s},calls:i,latestErrors:n,latestNotifications:null!=r?r:{},alternateCallerId:a,environmentInfo:o}))),c7=nU((e=>e?{[e.id]:e}:{})),d7=e=>l7(e.userId,e.devices,c7(e.call),e.latestErrors,e.latestNotifications,e.displayName,e.alternateCallerId,e.environmentInfo),u7=(e,t)=>o7(e,(e=>e),t),h7=e=>e.endedCall,g7=e=>{var t,i;return null!==(i=null===(t=e.call)||void 0===t?void 0:t.state)&&void 0!==i?i:"None"},p7=e=>e.devices,m7=e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.capabilities},f7=e=>e.devices.microphones,v7=e=>e.devices.cameras,S7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.role},y7=e=>e.page,C7=e=>e.acceptedTransferCallState,T7=e=>e.isLocalPreviewMicrophoneEnabled,E7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.localVideoStreams},b7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.diagnostics},_7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.remoteParticipants},I7=e=>e.environmentInfo,w7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.captionsFeature.isCaptionsFeatureActive},A7=e=>e.isTeamsCall,P7=e=>e.isTeamsMeeting,R7=e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.meetingConference)||void 0===i?void 0:i.conferencePhones},M7=e=>e.targetCallees,D7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.startTime},k7=e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.breakoutRooms)||void 0===i?void 0:i.assignedBreakoutRoom},O7=e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.breakoutRooms)||void 0===i?void 0:i.breakoutRoomSettings},N7=e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.breakoutRooms)||void 0===i?void 0:i.breakoutRoomDisplayName},L7=e=>e.latestNotifications,x7=e=>e.onResolveVideoEffectDependency,F7=e=>e.onResolveDeepNoiseSuppressionDependency,U7=e=>e.deepNoiseSuppressionOnByDefault,B7=e=>e.hideDeepNoiseSuppressionButton,V7=e=>e.reactions,H7=e=>e.alternateCallerId,$7=e=>e.isRoomsCall,j7=e=>e.videoBackgroundImages,G7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.togetherMode.isActive},q7=e=>e.userId,z7=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.meetingMediaAccess};var W7=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const K7=e=>{const t=LZ(),i=u7(m7);return J7(t,i)},J7=nU(((e,t)=>{var i,n,r,s,a,o,l,c;return{onCreateLocalStreamView:t=>W7(void 0,void 0,void 0,(function*(){return yield e.createStreamView(void 0,t)})),onCreateRemoteStreamView:(t,i)=>W7(void 0,void 0,void 0,(function*(){return yield e.createStreamView(t,i)})),onHangUp:t=>W7(void 0,void 0,void 0,(function*(){yield e.leaveCall(t)})),onToggleHold:()=>W7(void 0,void 0,void 0,(function*(){var t;return"LocalHold"===(null===(t=e.getState().call)||void 0===t?void 0:t.state)?yield e.resumeCall():yield e.holdCall()})),onAddParticipant:(t,i)=>W7(void 0,void 0,void 0,(function*(){return"communicationUserId"in t?yield e.addParticipant(t):"phoneNumber"in t?yield e.addParticipant(t,i):void 0})),onSendDtmfTone:t=>W7(void 0,void 0,void 0,(function*(){yield e.sendDtmfTone(t)})),onRemoveParticipant:t=>W7(void 0,void 0,void 0,(function*(){"string"==typeof t?yield e.removeParticipant(t):yield e.removeParticipant(rL(t))})),onRaiseHand:()=>W7(void 0,void 0,void 0,(function*(){yield e.raiseHand()})),onLowerHand:()=>W7(void 0,void 0,void 0,(function*(){yield e.lowerHand()})),onToggleRaiseHand:()=>W7(void 0,void 0,void 0,(function*(){var t;(null===(t=e.getState().call)||void 0===t?void 0:t.raiseHand.localParticipantRaisedHand)?yield e.lowerHand():yield e.raiseHand()})),onReactionClick:t=>W7(void 0,void 0,void 0,(function*(){yield e.onReactionClick(t)})),onSelectCamera:(t,i)=>W7(void 0,void 0,void 0,(function*(){yield e.setCamera(t,i)})),onSelectMicrophone:t=>W7(void 0,void 0,void 0,(function*(){yield e.setMicrophone(t)})),onSelectSpeaker:t=>W7(void 0,void 0,void 0,(function*(){yield e.setSpeaker(t)})),onStartCall:(t,i)=>{const n=t.map((e=>iL(e)));return e.startCall(n,i)},onStartScreenShare:()=>W7(void 0,void 0,void 0,(function*(){yield e.startScreenShare()})),onStopScreenShare:()=>W7(void 0,void 0,void 0,(function*(){yield e.stopScreenShare()})),onToggleCamera:t=>W7(void 0,void 0,void 0,(function*(){HF(e.getState())?yield e.stopCamera():yield e.startCamera(t)})),onToggleMicrophone:()=>W7(void 0,void 0,void 0,(function*(){var t;return(null===(t=e.getState().call)||void 0===t?void 0:t.isMuted)?yield e.unmute():yield e.mute()})),onToggleScreenShare:()=>W7(void 0,void 0,void 0,(function*(){var t;return(null===(t=e.getState().call)||void 0===t?void 0:t.isScreenSharingOn)?yield e.stopScreenShare():yield e.startScreenShare()})),onStartLocalVideo:()=>W7(void 0,void 0,void 0,(function*(){if(e.getState().call)return e.startCamera()})),onDisposeLocalStreamView:()=>W7(void 0,void 0,void 0,(function*(){return e.disposeLocalVideoStreamView()})),onDisposeRemoteStreamView:t=>W7(void 0,void 0,void 0,(function*(){return e.disposeStreamView(t)})),onDisposeRemoteScreenShareStreamView:t=>W7(void 0,void 0,void 0,(function*(){return e.disposeScreenShareStreamView(t)})),onDisposeLocalScreenShareStreamView:()=>W7(void 0,void 0,void 0,(function*(){return e.disposeScreenShareStreamView("")})),onDisposeRemoteVideoStreamView:t=>W7(void 0,void 0,void 0,(function*(){return e.disposeRemoteVideoStreamView(t)})),askDevicePermission:t=>W7(void 0,void 0,void 0,(function*(){yield e.askDevicePermission(t)})),onRemoveVideoBackgroundEffects:()=>W7(void 0,void 0,void 0,(function*(){return yield e.stopVideoBackgroundEffects()})),onBlurVideoBackground:t=>W7(void 0,void 0,void 0,(function*(){const i=Object.assign({effectName:"blur"},t);return yield e.startVideoBackgroundEffect(i)})),onReplaceVideoBackground:t=>W7(void 0,void 0,void 0,(function*(){const i=Object.assign({effectName:"replacement"},t);return yield e.startVideoBackgroundEffect(i)})),onStartNoiseSuppressionEffect:()=>W7(void 0,void 0,void 0,(function*(){return yield e.startNoiseSuppressionEffect()})),onStopNoiseSuppressionEffect:()=>W7(void 0,void 0,void 0,(function*(){return yield e.stopNoiseSuppressionEffect()})),onStartCaptions:t=>W7(void 0,void 0,void 0,(function*(){yield e.startCaptions(t)})),onStopCaptions:()=>W7(void 0,void 0,void 0,(function*(){yield e.stopCaptions()})),onSetSpokenLanguage:t=>W7(void 0,void 0,void 0,(function*(){yield e.setSpokenLanguage(t)})),onSetCaptionLanguage:t=>W7(void 0,void 0,void 0,(function*(){yield e.setCaptionLanguage(t)})),onSubmitSurvey:t=>W7(void 0,void 0,void 0,(function*(){return yield e.submitSurvey(t)})),onStartSpotlight:t=>W7(void 0,void 0,void 0,(function*(){yield e.startSpotlight(t)})),onStopSpotlight:t=>W7(void 0,void 0,void 0,(function*(){yield e.stopSpotlight(t)})),onStopAllSpotlight:()=>W7(void 0,void 0,void 0,(function*(){yield e.stopAllSpotlight()})),onStartLocalSpotlight:(null==t?void 0:t.spotlightParticipant.isPresent)?()=>W7(void 0,void 0,void 0,(function*(){yield e.startSpotlight()})):void 0,onStopLocalSpotlight:()=>W7(void 0,void 0,void 0,(function*(){yield e.stopSpotlight()})),onStartRemoteSpotlight:(null==t?void 0:t.spotlightParticipant.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.startSpotlight(t)})):void 0,onStopRemoteSpotlight:(null==t?void 0:t.removeParticipantsSpotlight.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.stopSpotlight(t)})):void 0,onMuteParticipant:t=>W7(void 0,void 0,void 0,(function*(){yield e.muteParticipant(t)})),onMuteAllRemoteParticipants:()=>W7(void 0,void 0,void 0,(function*(){yield e.muteAllRemoteParticipants()})),onForbidAudio:(null===(i=null==t?void 0:t.forbidOthersAudio)||void 0===i?void 0:i.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.forbidAudio(t)})):void 0,onPermitAudio:(null===(n=null==t?void 0:t.forbidOthersAudio)||void 0===n?void 0:n.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.permitAudio(t)})):void 0,onForbidOthersAudio:(null===(r=null==t?void 0:t.forbidOthersAudio)||void 0===r?void 0:r.isPresent)?()=>W7(void 0,void 0,void 0,(function*(){yield e.forbidOthersAudio()})):void 0,onPermitOthersAudio:(null===(s=null==t?void 0:t.forbidOthersAudio)||void 0===s?void 0:s.isPresent)?()=>W7(void 0,void 0,void 0,(function*(){yield e.permitOthersAudio()})):void 0,onForbidVideo:(null===(a=null==t?void 0:t.forbidOthersVideo)||void 0===a?void 0:a.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.forbidVideo(t)})):void 0,onPermitVideo:(null===(o=null==t?void 0:t.forbidOthersVideo)||void 0===o?void 0:o.isPresent)?t=>W7(void 0,void 0,void 0,(function*(){yield e.permitVideo(t)})):void 0,onForbidOthersVideo:(null===(l=null==t?void 0:t.forbidOthersVideo)||void 0===l?void 0:l.isPresent)?()=>W7(void 0,void 0,void 0,(function*(){yield e.forbidOthersVideo()})):void 0,onPermitOthersVideo:(null===(c=null==t?void 0:t.forbidOthersVideo)||void 0===c?void 0:c.isPresent)?()=>W7(void 0,void 0,void 0,(function*(){yield e.permitOthersVideo()})):void 0,onCreateTogetherModeStreamView:t=>W7(void 0,void 0,void 0,(function*(){return yield e.createTogetherModeStreamView(t)})),onStartTogetherMode:()=>W7(void 0,void 0,void 0,(function*(){return yield e.startTogetherMode()})),onSetTogetherModeSceneSize:(t,i)=>e.setTogetherModeSceneSize(t,i),onDisposeTogetherModeStreamView:()=>W7(void 0,void 0,void 0,(function*(){return yield e.disposeTogetherModeStreamView()})),onSendRealTimeText:(t,i)=>W7(void 0,void 0,void 0,(function*(){return yield e.sendRealTimeText(t,i)}))}})),Y7=e=>{const t=r7(e);if(!t)throw new Error("Can't find the selector for component, please check supported component list");return Object.assign(Object.assign({},a7(t)),K7())},Q7=t=>{const i=Y7(T3),n=PJ().strings.call,r={captionsSettingsModalTitle:n.captionsSettingsModalTitle,captionsSettingsSpokenLanguageDropdownLabel:n.captionsSettingsSpokenLanguageDropdownLabel,captionsSettingsCaptionLanguageDropdownLabel:n.captionsSettingsCaptionLanguageDropdownLabel,captionsSettingsSpokenLanguageDropdownInfoText:n.captionsSettingsSpokenLanguageDropdownInfoText,captionsSettingsCaptionLanguageDropdownInfoText:n.captionsSettingsCaptionLanguageDropdownInfoText,captionsSettingsConfirmButtonLabel:n.captionsSettingsConfirmButtonLabel,captionsSettingsCancelButtonLabel:n.captionsSettingsCancelButtonLabel,captionsSettingsModalAriaLabel:n.captionsSettingsModalAriaLabel,captionsSettingsCloseModalButtonAriaLabel:n.captionsSettingsCloseModalButtonAriaLabel},s=n.spokenLanguageStrings,a=n.captionLanguageStrings;return e.createElement(T3,Object.assign({},i,{strings:r,spokenLanguageStrings:s,captionLanguageStrings:a,showModal:t.showCaptionsSettingsModal,onDismissCaptionsSettings:t.onDismissCaptionsSettings,changeCaptionLanguage:t.changeCaptionLanguage}))},Z7={root:{border:"0.125rem",borderRadius:2,width:"6.5625rem"},flexContainer:{flexFlow:"row"}},X7={root:{border:"0",borderRadius:"0.5rem"},flexContainer:{flexFlow:"row"}},e9={root:{height:"3rem",lineHeight:"3rem",maxHeight:"unset",overflow:"hidden"},linkContent:{height:"3rem",lineHeight:"3rem",maxHeight:"unset"},icon:{maxHeight:"unset",textAlign:"center"},checkmarkIcon:{lineHeight:"2rem"}},t9={menuStyles:{menuItemStyles:e9,participantListStyles:{participantItemStyles:{root:{height:"3rem"},participantSubMenuItemsStyles:e9}}}},i9={menuStyles:{menuItemStyles:e9}},n9={label:{minWidth:"1.25rem"}},r9=(...e)=>{let t=n9;return e.forEach((e=>{t=ZH(t,e)})),t},s9=()=>e.createElement(TY,{key:"chatOnIconKey",primaryFill:"currentColor"}),a9=t=>e.createElement(R3,Object.assign({},t,{labelKey:"optionsButtonLabelKey",showLabel:t.showLabel,onRenderOnIcon:s9,onRenderOffIcon:s9,onClick:t.onClick,"data-ui-id":t["data-ui-id"]}));var o9=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const l9=t=>{const i=PJ(),n=Y7(p6),r=(0,e.useMemo)((()=>({label:i.strings.call.captionsBannerMoreButtonCallingLabel,tooltipOffContent:i.strings.call.captionsBannerMoreButtonTooltip})),[i]),s=[],a=(0,e.useCallback)((()=>o9(void 0,void 0,void 0,(function*(){yield n.onStartCaptions({spokenLanguage:n.currentSpokenLanguage})}))),[n]),o=(0,e.useCallback)((()=>o9(void 0,void 0,void 0,(function*(){yield n.onStopCaptions()}))),[n]);return s.push({key:"ToggleCaptionsKey",text:n.checked?i.strings.call.startCaptionsButtonTooltipOnContent:i.strings.call.startCaptionsButtonTooltipOffContent,onClick:()=>{n.checked?o():""!==n.currentSpokenLanguage?a():t.onCaptionsSettingsClick&&t.onCaptionsSettingsClick()},iconProps:{iconName:n.checked?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9}}),t.onCaptionsSettingsClick&&s.push({key:"openCaptionsSettingsKey",id:"common-call-composite-captions-settings-button",text:i.strings.call.captionsSettingsLabel,onClick:t.onCaptionsSettingsClick,iconProps:{iconName:"CaptionsSettingsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:!n.checked}),e.createElement(a9,Object.assign({},t,{"data-ui-id":"captions-banner-more-button",strings:r,menuIconProps:{hidden:!0},menuProps:{items:s,calloutProps:{preventDismissOnEvent:v0}}}))},c9=t=>{var i;const n=Y7(p4),[r,s]=(0,e.useState)(!1),a=dB("full"===(null===(i=t.captionsOptions)||void 0===i?void 0:i.height)?dB({position:"absolute",height:"100%",width:"100%"}):{position:"relative"}),o=dB({position:"absolute",right:0,top:0}),l=PJ().strings.call,c={captionsBannerSpinnerText:l.captionsBannerSpinnerText,realTimeTextInputBoxDefaultText:l.realTimeTextInputBoxDefaultText,realTimeTextInputErrorMessage:l.realTimeTextInputErrorMessage,realTimeTextBannerContent:l.realTimeTextBannerContent,realTimeTextBannerTitle:l.realTimeTextBannerTitle,realTimeTextBannerLinkLabel:l.realTimeTextBannerLinkLabel,captionsOnlyContainerTitle:l.captionsOnlyContainerTitle,realTimeTextOnlyContainerTitle:l.realTimeTextOnlyContainerTitle,captionsAndRealTimeTextContainerTitle:l.captionsAndRealTimeTextContainerTitle,expandButtonAriaLabel:l.expandButtonAriaLabel,minimizeButtonAriaLabel:l.minimizeButtonAriaLabel},d=(0,e.useCallback)(((i,n)=>e.createElement(h0,Object.assign({userId:i},n,{dataProvider:t.onFetchAvatarPersonaData}))),[t.onFetchAvatarPersonaData]),{innerWidth:u}=window,[h,g]=(0,e.useState)(u);(0,e.useEffect)((()=>{function e(){g(window.innerWidth)}return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}),[]);const p=h>620?"35rem":"80%";return e.createElement(e.Fragment,null,r&&e.createElement(Q7,{showCaptionsSettingsModal:r,onDismissCaptionsSettings:()=>{s(!1)},changeCaptionLanguage:t.useTeamsCaptions}),e.createElement("div",{className:a,role:"region","aria-label":l.liveCaptionsLabel},e.createElement(Y$,{horizontalAlign:"center"},e.createElement(Y$.Item,{style:{width:t.isMobile?"95%":p}},e.createElement(p4,Object.assign({captionsOptions:t.captionsOptions,onRenderAvatar:d,formFactor:t.isMobile?"compact":"default",strings:c},n,{isRealTimeTextOn:t.isRealTimeTextOn||n.isRealTimeTextOn})))),!t.isMobile&&n.isCaptionsOn&&e.createElement("div",{className:o},e.createElement(l9,{onCaptionsSettingsClick:()=>{s(!0)}}))))},d9={position:"relative",width:"100%",height:"100%"},u9={position:"relative",height:"100%",width:"100%"},h9=t=>{const{styles:i,layout:n}=t,r=aJ(),s=(0,e.useMemo)((()=>dB(E3[null!=n?n:"horizontal"],{background:LX(r)&&(null==n?void 0:n.startsWith("floating"))?r.palette.neutralQuaternaryAlt:r.palette.white},(null==n?void 0:n.startsWith("floating"))?{boxShadow:r.effects.elevation16,borderRadius:r.effects.roundedCorner6}:{},!r.rtl||"floatingTop"!==n&&"floatingBottom"!==n?{}:{transform:"translateX(50%)"},null==i?void 0:i.root)),[n,null==i?void 0:i.root,r]);return e.createElement("div",{className:dB(u9)},e.createElement(Y$,{className:s},t.children))},g9=t=>{var i;const n=Y7(j3),r=(0,e.useMemo)((()=>{var e;return r9(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),s=u7($7),a=u7(S7),o=null===(i=u7(m7))||void 0===i?void 0:i.turnVideoOn;return e.createElement(j3,Object.assign({"data-ui-id":"call-composite-camera-button"},n,{showLabel:"compact"!==t.displayType,styles:r,enableDeviceSelectionMenu:t.splitButtonsForDeviceSelection,disableTooltip:t.disableTooltip,disabled:n.disabled||t.disabled||!(!s||"Unknown"!==a),onRenderOffIcon:o&&!o.isPresent?()=>e.createElement(M3,{disabled:!0,iconName:"ControlButtonCameraProhibited"}):void 0,onClickVideoEffects:t.onClickVideoEffects,componentRef:t.componentRef}))},p9=t=>{var i;const n=Y7(U3),r=null!==(i=u7(S7))&&void 0!==i?i:"Unknown",s=(0,e.useMemo)((()=>Object.assign(Object.assign({},n),{microphones:"Consumer"===r?[]:n.microphones,cameras:"Consumer"===r?[]:n.cameras})),[n,r]),a=(0,e.useMemo)((()=>{var e;return r9(t.increaseFlyoutItemSize?i9:{},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.increaseFlyoutItemSize,t.styles]),o=PJ(),l="Consumer"===r;return e.createElement(U3,Object.assign({persistMenu:!0},s,{showLabel:"compact"!==t.displayType,styles:a,"data-ui-id":"calling-composite-devices-button",disabled:t.disabled,strings:m9(r,o),onRenderIcon:l?()=>e.createElement(M3,{disabled:t.disabled,iconName:"OptionsSpeaker"}):void 0}))},m9=(e,t)=>{if("Consumer"===e)return{label:t.component.strings.microphoneButton.speakerMenuTitle}},f9=t=>{var i;const n=aJ(),r=ZH(S9,null!==(i=t.styles)&&void 0!==i?i:{});return e.createElement(y3,{styles:r,isOpen:t.isOpen,onDismiss:t.onDismiss,isBlocking:!1},e.createElement(Y$,{className:dB({position:"relative"})},e.createElement(oJ,{className:dB({fontWeight:600,fontSize:"1.25rem"})},t.heading),e.createElement(oK,{styles:v9(n),iconProps:{iconName:"Cancel"},onClick:t.onCancel,ariaLabel:t.closeButtonLabel})),e.createElement(Y$,{verticalAlign:"center",className:dB({minHeight:"6rem"})},e.createElement(oJ,{className:dB({fontSize:"0.875rem"})},t.text)),e.createElement(Y$,{horizontal:!0,horizontalAlign:"end",tokens:{childrenGap:"0.5rem"}},e.createElement(mJ,{styles:y9,text:t.confirmButtonLabel,onClick:t.onConfirm}),e.createElement(pJ,{styles:y9,text:t.cancelButtonLabel,onClick:t.onCancel})))},v9=e=>({root:{position:"absolute",top:0,right:0,color:e.palette.neutralPrimary},rootHovered:{color:e.palette.neutralDark}}),S9={main:{padding:"1.5rem ",maxWidth:"30rem"}},y9={label:{fontSize:"0.875rem"}};const C9=t=>{var i;const n="compact"===t.displayType,r=Y7(o6),s=PJ().strings,a=(0,e.useMemo)((()=>({confirmButtonLabel:s.call.endCallConfirmButtonLabel,heading:s.call.endCallConfirmDialogTitle,text:s.call.leaveConfirmDialogContent,closeButtonLabel:s.call.close})),[s.call.endCallConfirmButtonLabel,s.call.endCallConfirmDialogTitle,s.call.leaveConfirmDialogContent,s.call.close]),o=(0,e.useMemo)((()=>({confirmButtonLabel:s.call.leaveConfirmButtonLabel,heading:s.call.leaveConfirmDialogTitle,text:s.call.leaveConfirmDialogContent,closeButtonLabel:s.call.close})),[s.call.leaveConfirmButtonLabel,s.call.leaveConfirmDialogContent,s.call.leaveConfirmDialogTitle,s.call.close]),[l,c]=(0,e.useState)(o),{onHangUp:d}=r,[u,h]=e.useState(!1),g=(0,e.useCallback)((()=>{h(!u)}),[u]),p=(0,e.useCallback)((e=>{d&&d(e),g()}),[d,g]),m=(0,e.useCallback)((e=>{return i=void 0,n=void 0,s=function*(){t.mobileView||!1===e?d():(c(e?a:o),g())},new((r=void 0)||(r=Promise))((function(e,t){function a(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(a,o)}l((s=s.apply(i,n||[])).next())}));var i,n,r,s}),[a,o,d,t.mobileView,g]),f=(0,e.useMemo)((()=>{var e;return ZH(n?X7:Z7,null!==(e=t.styles)&&void 0!==e?e:{})}),[n,t.styles]),v=!!t.returnFromBreakoutRoom,S={items:[{key:"returnToMainMeeting",text:s.call.returnFromBreakoutRoomButtonLabel,title:s.call.returnFromBreakoutRoomButtonLabel,onClick:()=>{var e;null===(e=t.returnFromBreakoutRoom)||void 0===e||e.call(t)}},{key:"leaveRoomAndMainMeeting",text:s.call.leaveBreakoutRoomAndMeetingButtonLabel,title:s.call.leaveBreakoutRoomAndMeetingButtonLabel,onClick:()=>d()}],styles:t.styles};return e.createElement(Y$,null,e.createElement(o6,Object.assign({"data-ui-id":"call-composite-hangup-button"},r,{onHangUp:t.disableEndCallModal?d:m,styles:f,showLabel:!n,enableEndCallMenu:null!==(i=t.enableEndCallMenu)&&void 0!==i&&i,menuProps:v?S:void 0})),e.createElement(f9,Object.assign({},l,{styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},cancelButtonLabel:s.call.hangUpCancelButtonLabel,onConfirm:()=>p(t.enableEndCallMenu),isOpen:u,onCancel:g})))},T9=t=>{var i;const n=Y7(V3),r=u7(g7),s=u7(T7),a=u7($7),o=u7(S7),l=null===(i=u7(m7))||void 0===i?void 0:i.unmuteMic;"Connecting"===r&&(n.checked=s);const c=(0,e.useMemo)((()=>{var e;return r9(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]);return e.createElement(V3,Object.assign({"data-ui-id":"call-composite-microphone-button"},n,{isDeepNoiseSuppressionOn:t.isDeepNoiseSuppressionOn,onClickNoiseSuppression:t.onClickNoiseSuppression,showNoiseSuppressionButton:t.showNoiseSuppressionButton,showLabel:"compact"!==t.displayType,disableTooltip:t.disableTooltip,styles:c,enableDeviceSelectionMenu:t.splitButtonsForDeviceSelection,disabled:n.disabled||t.disabled||!(!a||"Unknown"!==o),onRenderOffIcon:l&&!l.isPresent?()=>e.createElement(M3,{disabled:!0,iconName:"ControlButtonMicProhibited"}):void 0}))},E9=t=>{const i=Y7(V8),n=(0,e.useMemo)((()=>{var e;return r9(t.increaseFlyoutItemSize?t9:{},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.increaseFlyoutItemSize,t.styles]);return e.createElement(V8,Object.assign({"data-ui-id":"call-composite-participants-button"},i,{showLabel:"compact"!==t.displayType,callInvitationURL:t.callInvitationURL,onFetchParticipantMenuItems:t.onFetchParticipantMenuItems,disabled:b9(t.option)||t.disabled,styles:n,showParticipantOverflowTooltip:!t.isMobile}))},b9=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,_9=t=>{const i=Y7(G3),n=(0,e.useMemo)((()=>{var e;return r9(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),r=u7($7),s=u7(S7);return e.createElement(G3,Object.assign({"data-ui-id":"call-composite-screenshare-button"},i,{showLabel:"compact"!==t.displayType,disabled:(()=>{var e;return null!==(e=null==i?void 0:i.disabled)&&void 0!==e?e:I9(t.option)})()||t.disabled||!(!r||"Unknown"!==s),styles:n}))},I9=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,w9=()=>e.createElement(bZ,{iconName:"ControlButtonParticipants"}),A9=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:s}=t,a=aJ(),o=(0,e.useMemo)((()=>{var e;return ZH({rootChecked:{background:a.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{},n9)}),[t.styles,a.palette.neutralLight]);return e.createElement(R3,Object.assign({},t,{"data-ui-id":"call-composite-participants-button",strings:i,labelKey:"peopleButtonLabelKey",onRenderOnIcon:null!=n?n:w9,onRenderOffIcon:null!=r?r:w9,onClick:s,styles:o}))},P9={paddingTop:"0.25rem",paddingBottom:"0.25rem"},R9=Math.max(2,1)+1,M9=R9+1,D9=dB(P9,{zIndex:2}),k9={width:"100%",position:"relative",minHeight:"13rem"},O9=dB(Object.assign(Object.assign({},k9),{minWidth:"30rem"})),N9=dB(Object.assign(Object.assign({},k9),{minWidth:"17.5rem"})),L9={root:{height:"100%",width:"100%"}},x9={root:{width:"100%",position:"absolute",top:0,left:0,padding:"1rem",zIndex:R9,pointerEvents:"none"}},F9={root:{zIndex:R9,pointerEvents:"auto"}},U9={root:{zIndex:R9,pointerEvents:"auto",marginBottom:"0.5rem"}},B9=e=>({root:{width:"100%",height:"100%",flexDirection:e?"unset":"column"}}),V9=t=>{const i=Y7(U6),n=u7(g7),r=(0,e.useMemo)((()=>{var e;return r9(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]);let s=H9(t.option);return lL(n)&&(s=!0),e.createElement(U6,Object.assign({"data-ui-id":"call-composite-raisehand-button"},i,{showLabel:"compact"!==t.displayType,disabled:s||t.disabled,styles:r}))},H9=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,$9=(e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:j9("primary",i),secondary:j9("secondary",i),overflow:j9("overflow",i)}},j9=(t,i)=>i?i.filter((e=>e.placement===t)).map(((t,i)=>n=>{var r,s,a,o,l,c,d,u,h,g;return"onRenderButton"in t?t.onRenderButton(n):e.createElement(R3,{ariaDescription:null!==(s=null===(r=t.strings)||void 0===r?void 0:r.ariaDescription)&&void 0!==s?s:n.ariaDescription,ariaLabel:null!==(c=null!==(o=null===(a=t.strings)||void 0===a?void 0:a.ariaLabel)&&void 0!==o?o:null===(l=t.strings)||void 0===l?void 0:l.tooltipContent)&&void 0!==c?c:n.ariaLabel,disabled:null!==(d=t.disabled)&&void 0!==d?d:n.disabled,id:null!==(u=t.id)&&void 0!==u?u:n.id,key:`${t.placement}_${i}`,onClick:null!==(h=t.onItemClick)&&void 0!==h?h:n.onClick,onRenderIcon:()=>{var i,r,s;return e.createElement(mG,{iconName:null!==(s=null!==(i=t.iconName)&&void 0!==i?i:null===(r=n.iconProps)||void 0===r?void 0:r.iconName)&&void 0!==s?s:"DefaultCustomButton"})},showLabel:null!==(g=t.showLabel)&&void 0!==g?g:n.showLabel,styles:e$(n.styles),strings:t.strings})})):[],G9=(e,t)=>t?t.filter((t=>t.placement===e)).map(((e,t)=>{var i,n;return Object.assign(Object.assign({},e),{disabled:e.disabled,iconProps:{iconName:null!==(i=e.iconName)&&void 0!==i?i:"DefaultCustomButton",styles:{root:{lineHeight:0}}},id:e.id,itemKey:`${e.placement}_${t}`,onItemClick:e.onItemClick,text:null===(n=e.strings)||void 0===n?void 0:n.label})})):[],q9=(e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:G9("primary",i).map(z9),secondary:G9("secondary",i).map(z9),overflow:G9("overflow",i).map(z9)}},z9=e=>Object.assign(Object.assign({},e),{key:e.itemKey,onClick:e.onItemClick?t=>{var i;null===(i=e.onItemClick)||void 0===i||i.call(e,t)}:void 0,subMenuProps:e.subMenuProps?{items:e.subMenuProps.map(z9)}:void 0}),W9=e=>{let t;return t=null==e?void 0:e.onFetchCustomButtonProps,t},K9=t=>{const i=Y7(W8),n=(0,e.useMemo)((()=>{var e;return r9(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),r=J9(t.option)||i.disabled;return e.createElement(W8,Object.assign({"data-ui-id":"call-composite-reaction-button"},i,{showLabel:"compact"!==t.displayType,disabled:r||t.disabled,styles:n,disableTooltip:t.disableTooltip,persistMenu:!0,reactionResources:t.reactionResource}))},J9=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,Y9=G6([m7],(e=>({capabilities:e}))),Q9=G6([g7,e=>{var t,i;return null!==(i=null===(t=e.call)||void 0===t?void 0:t.isScreenSharingOn)&&void 0!==i&&i}],((e,t)=>({callStatus:e,isScreenShareOn:t})));var Z9=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const X9=SB((e=>({root:{background:e}}))),eee=t=>{var i;const n=(0,e.useMemo)((()=>((e,t)=>{if(!1===t)return{};const i=!0===t||void 0===t?{}:t;return e&&(i.screenShareButton=!1),i})(!!t.isMobile,t.options)),[t.isMobile,t.options]),r=PJ(),[s,a]=(0,e.useState)(!1),o=LZ(),l=(0,e.useCallback)((()=>Z9(void 0,void 0,void 0,(function*(){yield o.startNoiseSuppressionEffect()}))),[o]),c=u7(F7),d=u7(U7);(0,e.useEffect)((()=>{c&&d&&(l(),a(!0))}),[c,d,l]);const u=u7(I7),h=JF(u),g=u7(B7),p=!(!c||g||h),m=(0,e.useCallback)((()=>Z9(void 0,void 0,void 0,(function*(){s?(yield o.stopNoiseSuppressionEffect(),a(!1)):(yield o.startNoiseSuppressionEffect(),a(!0))}))),[o,s]),f=(0,e.useMemo)((()=>({label:r.strings.call.peopleButtonLabel,tooltipOffContent:r.strings.call.peopleButtonTooltipOpen,tooltipOnContent:r.strings.call.peopleButtonTooltipClose})),[r]),v=(0,e.useMemo)((()=>({label:r.strings.call.moreButtonCallingLabel,tooltipOffContent:r.strings.callWithChat.moreDrawerButtonTooltip})),[r]),S=Y7(F6),y=Y7(U6),C=u7(Y9),T="Connected"!==u7(Q9).callStatus||!(null==C?void 0:C.capabilities)||C.capabilities.useReactions.isPresent,E=Y7(U3);let b=0;const _=tee(null==n?void 0:n.screenShareButton);_&&b++;const I=tee(null==n?void 0:n.microphoneButton);I&&b++;const w=tee(null==n?void 0:n.cameraButton);w&&b++,tee(null==n?void 0:n.endCallButton)&&b++;const A=tee(null==n?void 0:n.participantsButton)&&!t.isMobile;A&&b++;const P=tee(null==n?void 0:n.reactionButton)&&T&&!t.isMobile;P&&b++;const R=u7($7),M=(0,e.useMemo)((()=>q9(W9("object"==typeof n?n:void 0),"object"==typeof n?n.displayType:void 0)),[n]),D=(()=>{const e=[];return t.isMobile&&t.onPeopleButtonClicked&&tee(null==n?void 0:n.participantsButton)&&e.push({key:"peopleButtonKey",text:r.component.strings.participantsButton.label,onClick:()=>{t.onPeopleButtonClicked&&t.onPeopleButtonClicked()},iconProps:{iconName:"ControlButtonParticipantsContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:WF(null==n?void 0:n.participantsButton),"data-ui-id":"call-composite-more-menu-people-button"}),R||e.push({key:"holdButtonKey",text:r.component.strings.holdButton.tooltipOffContent,onClick:()=>{S.onToggleHold()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:WF(null==n?void 0:n.holdButton),"data-ui-id":"hold-button"}),e})();let k=tee(null==n?void 0:n.moreButton)&&D.length>0;k&&b++;const O=(0,e.useMemo)((()=>$9(W9(n),null==n?void 0:n.displayType)),[n]);b+=e.Children.count(O.primary)+e.Children.count(O.secondary);let N=tee(null==n?void 0:n.devicesButton);N&&(!t.isMobile||b<5)?b++:(N=!1,k=tee(null==n?void 0:n.moreButton));const L=u7(V7);let x=tee(null==n?void 0:n.raiseHandButton);const F=u7(S7),U=R&&F&&["Consumer","Unknown"].includes(F);if(x&&(!t.isMobile||b<5)?b++:(!k&&tee(null==n?void 0:n.moreButton)&&(k=!0,N=!1),x=!1),!N){const e=F3(E,r.component.strings.devicesButton);D.push({key:"devicesButtonKey",text:r.component.strings.devicesButton.label,iconProps:{iconName:"ControlButtonOptions",styles:{root:{lineHeight:0}}},subMenuProps:e,"data-ui-id":"call-composite-more-menu-devices-button"})}x||U||D.push({key:"raiseHandButtonKey",text:y.checked?r.component.strings.raiseHandButton.onLabel:r.component.strings.raiseHandButton.offLabel,onClick:()=>{y.onToggleRaiseHand&&y.onToggleRaiseHand()},iconProps:{iconName:"RaiseHandContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:WF(null==n?void 0:n.raiseHandButton),"data-ui-id":"call-composite-more-menu-raise-hand-button"}),M.primary&&M.primary.slice(t.isMobile?1:3).forEach((e=>{D.push(Object.assign({itemProps:{styles:e9}},e))})),M.secondary&&M.secondary.forEach((e=>{D.push(Object.assign({itemProps:{styles:e9}},e))})),M.overflow&&M.overflow.forEach((e=>{D.push(Object.assign({itemProps:{styles:e9}},e))}));const B=qK();return!1===t.options?e.createElement(e.Fragment,null):e.createElement(Y$,{horizontalAlign:"center",className:D9},e.createElement(Y$.Item,null,e.createElement(h9,{layout:t.displayVertical?"vertical":"horizontal",styles:X9(B.semanticColors.bodyBackground)},I&&e.createElement(T9,{displayType:null==n?void 0:n.displayType,disabled:WF(null==n?void 0:n.microphoneButton),onClickNoiseSuppression:m,isDeepNoiseSuppressionOn:s,showNoiseSuppressionButton:p}),w&&e.createElement(g9,{displayType:null==n?void 0:n.displayType,disabled:WF(null==n?void 0:n.cameraButton)}),P&&L&&e.createElement(K9,{displayType:null==n?void 0:n.displayType,reactionResource:L}),x&&!U&&e.createElement(V9,{displayType:null==n?void 0:n.displayType}),_&&e.createElement(_9,{option:null==n?void 0:n.screenShareButton,displayType:null==n?void 0:n.displayType,disabled:WF(null==n?void 0:n.screenShareButton)}),A&&e.createElement(E9,{option:null==n?void 0:n.participantsButton,callInvitationURL:t.callInvitationURL,onFetchParticipantMenuItems:t.onFetchParticipantMenuItems,displayType:null==n?void 0:n.displayType,increaseFlyoutItemSize:t.increaseFlyoutItemSize,isMobile:t.isMobile,disabled:WF(null==n?void 0:n.participantsButton)})&&e.createElement(A9,{checked:t.peopleButtonChecked,ariaLabel:null==f?void 0:f.label,showLabel:"compact"!==(null==n?void 0:n.displayType),onClick:t.onPeopleButtonClicked,"data-ui-id":"call-composite-people-button",strings:f,disabled:WF(null==n?void 0:n.participantsButton),disableTooltip:t.isMobile}),N&&e.createElement(p9,{displayType:null==n?void 0:n.displayType,increaseFlyoutItemSize:t.increaseFlyoutItemSize,disabled:WF(null==n?void 0:n.devicesButton)}),null===(i=O.primary)||void 0===i?void 0:i.slice(0,t.isMobile?1:3).map(((i,r)=>e.createElement(i,{key:`primary-custom-button-${r}`,showLabel:"compact"!==(null==n?void 0:n.displayType),disableTooltip:t.isMobile}))),k&&e.createElement(a9,{disableTooltip:t.isMobile,"data-ui-id":"common-call-composite-more-button",strings:v,menuIconProps:{hidden:!0},menuProps:{items:D},showLabel:"compact"!==(null==n?void 0:n.displayType)}),tee(null==n?void 0:n.endCallButton)&&e.createElement(C9,{displayType:null==n?void 0:n.displayType}))))},tee=e=>!1!==e,iee=()=>e.createElement(bZ,{iconName:"ControlBarPeopleButton"}),nee=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:s,peoplePaneDismissButtonRef:a,chatButtonPresent:o}=t,l=aJ(),c=(0,e.useMemo)((()=>{var e;return ZH({rootChecked:{background:l.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles,l.palette.neutralLight]),d=(0,e.useCallback)((e=>{"Tab"!==e.key||e.shiftKey||!(null==a?void 0:a.current)||o||(a.current.focus(),e.preventDefault())}),[a,o]),u=(0,e.useCallback)((e=>{var t;null==s||s(e),o&&(null===(t=null==a?void 0:a.current)||void 0===t||t.focus(),e.preventDefault())}),[o,s,a]);return e.createElement(R3,Object.assign({},t,{strings:i,labelKey:"peopleButtonLabelKey",onRenderOnIcon:null!=n?n:iee,onRenderOffIcon:null!=r?r:iee,onClick:u,onKeyDown:d,styles:c}))},ree=()=>PJ().strings.callWithChat,see=G6([E7],(e=>{var t,i;return{isVideoStreamOn:!!(null===(i=null===(t=null==e?void 0:e.find((e=>"Video"===e.mediaStreamType)))||void 0===t?void 0:t.view)||void 0===i?void 0:i.target)}})),aee=G6([_7],(e=>Object.values(null!=e?e:{}).filter((e=>"Connected"===e.state)))),oee=(e,t,i)=>{var n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C;if(0===t.length)return"";const T=t.filter((e=>!e.displayName)),E=t.filter((e=>e.displayName)).concat(T);if(0===E.filter((e=>e.displayName)).length&&E.length>1)return PK("joined"===e?i.manyUnnamedParticipantsJoined:i.manyUnnamedParticipantsLeft,{numOfParticipants:(E.length-1).toString()});switch(E.length){case 1:return PK("joined"===e?i.participantJoinedNoticeString:i.participantLeftNoticeString,{displayName:null!==(r=null===(n=E[0])||void 0===n?void 0:n.displayName)&&void 0!==r?r:i.unnamedParticipantString});case 2:return PK("joined"===e?i.twoParticipantJoinedNoticeString:i.twoParticipantLeftNoticeString,{displayName1:null!==(a=null===(s=E[0])||void 0===s?void 0:s.displayName)&&void 0!==a?a:i.unnamedParticipantString,displayName2:null!==(l=null===(o=E[1])||void 0===o?void 0:o.displayName)&&void 0!==l?l:i.unnamedParticipantString});case 3:return PK("joined"===e?i.threeParticipantJoinedNoticeString:i.threeParticipantLeftNoticeString,{displayName1:null!==(d=null===(c=E[0])||void 0===c?void 0:c.displayName)&&void 0!==d?d:i.unnamedParticipantString,displayName2:null!==(h=null===(u=E[1])||void 0===u?void 0:u.displayName)&&void 0!==h?h:i.unnamedParticipantString,displayName3:null!==(p=null===(g=E[2])||void 0===g?void 0:g.displayName)&&void 0!==p?p:i.unnamedParticipantString})}const b=E.length-3;return PK("joined"===e?i.manyParticipantsJoined:i.manyParticipantsLeft,{displayName1:null!==(f=null===(m=E[0])||void 0===m?void 0:m.displayName)&&void 0!==f?f:i.unnamedParticipantString,displayName2:null!==(S=null===(v=E[1])||void 0===v?void 0:v.displayName)&&void 0!==S?S:i.unnamedParticipantString,displayName3:null!==(C=null===(y=E[2])||void 0===y?void 0:y.displayName)&&void 0!==C?C:i.unnamedParticipantString,numOfParticipants:b.toString()})},lee=(e,t,i)=>{let n=!1;if("object"==typeof i&&"dialerBehavior"in i){const e=i.dialerBehavior&&"alwaysHide"===i.dialerBehavior,t="alwaysShow"===i.dialerBehavior;if(n="autoShow"===i.dialerBehavior,t)return!0;if(e)return!1}let r=!1;return(n||void 0===i||!1===i)&&(null==e||e.forEach((e=>{(ZN(e)||YN(e))&&(r=!0)})),t&&t.forEach((e=>{"phoneNumber"in e.identifier||"teamsAppId"in e.identifier||(r=!1)}))),r};const cee=t=>{var i,n,r,s,a,o,l,c;const d=PJ(),u=Y7(F6),h=Y7(p6),g=Y7(p4),p=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){yield h.onStartCaptions({spokenLanguage:h.currentSpokenLanguage})},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[h]),[m,f]=(0,e.useState)(!1),[v,S]=(0,e.useState)(null!==(i=t.userSetGalleryLayout)&&void 0!==i?i:"floatingLocalVideo"),y=u7(M7),C=lee(y),T=u7(P7),E=u7(R7),b=u7(G7),_=u7(m7),I=u7(q7),w=u7(A7),[A,P]=(0,e.useState)(null!==(n=t.dtmfDialerPresent)&&void 0!==n&&n),R=(0,e.useMemo)((()=>({label:d.strings.call.moreButtonCallingLabel,tooltipOffContent:d.strings.callWithChat.moreDrawerButtonTooltip})),[d]),M=[],D={root:{height:"unset",lineHeight:"100%",width:"1.25rem"}};if(!0!==t.callControls&&!1===(null===(r=t.callControls)||void 0===r?void 0:r.holdButton)||M.push({key:"holdButtonKey",text:d.component.strings.holdButton.tooltipOffContent,onClick:()=>{u.onToggleHold()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:t.disableButtonsForHoldScreen}),t.isCaptionsSupported){const e=[];M.push({key:"liveCaptionsKey",id:"common-call-composite-captions-button",text:d.strings.call.liveCaptionsLabel,iconProps:{iconName:"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:t.disableButtonsForHoldScreen,subMenuProps:{id:"captions-contextual-menu",items:e,calloutProps:{preventDismissOnEvent:v0}},submenuIconProps:{iconName:"HorizontalGalleryRightButton",styles:D}}),e.push({key:"ToggleCaptionsKey",id:"common-call-composite-captions-toggle-button",text:h.checked?d.strings.call.startCaptionsButtonTooltipOnContent:d.strings.call.startCaptionsButtonTooltipOffContent,onClick:()=>{h.checked?h.onStopCaptions():""!==h.currentSpokenLanguage?p():t.onCaptionsSettingsClick&&t.onCaptionsSettingsClick()},iconProps:{iconName:h.checked?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:t.disableButtonsForHoldScreen}),t.onCaptionsSettingsClick&&e.push({key:"openCaptionsSettingsKey",id:"common-call-composite-captions-settings-button",text:d.strings.call.captionsSettingsLabel,onClick:t.onCaptionsSettingsClick,iconProps:{iconName:"CaptionsSettingsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:t.disableButtonsForHoldScreen||!h.checked})}if(t.isRealTimeTextSupported){const e=[],i=t.disableButtonsForHoldScreen||g.isRealTimeTextOn||t.startRealTimeTextButtonChecked;M.push({key:"realTimeTextKey",id:"common-call-composite-captions-button",text:d.strings.call.realTimeTextLabel,iconProps:{iconName:"RealTimeTextIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:t.disableButtonsForHoldScreen,subMenuProps:{id:"rtt-contextual-menu",items:e,calloutProps:{preventDismissOnEvent:v0}},submenuIconProps:{iconName:"HorizontalGalleryRightButton",styles:D}}),e.push({key:"StartRealTimeTextKey",id:"common-call-composite-rtt-start-button",text:d.strings.call.startRealTimeTextLabel,ariaLabel:i?d.strings.call.disabledStartRealTimeTextLabel:d.strings.call.startRealTimeTextLabel,onClick:t.onStartRealTimeTextClick,iconProps:{iconName:"RealTimeTextIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},disabled:i})}const k={key:"dtmfDialerScreenKey",itemProps:{styles:e9},text:A?d.strings.call.dtmfDialerMoreButtonLabelOff:d.strings.call.dtmfDialerMoreButtonLabelOn,onClick:()=>{t.onSetDialpadPage&&t.onSetDialpadPage(),P(!A)},iconProps:{iconName:"DtmfDialpadButton",styles:{root:{lineHeight:0}}}};t.onSetDialpadPage&&C&&(!0!==t.callControls&&!1===(null===(s=t.callControls)||void 0===s?void 0:s.dtmfDialerButton)||M.push(k));const O={key:"phoneCallKey",itemProps:{styles:e9},text:d.strings.call.phoneCallMoreButtonLabel,onClick:()=>{t.onMeetingPhoneInfoClick&&t.onMeetingPhoneInfoClick()},iconProps:{iconName:"PhoneNumberButton",styles:{root:{lineHeight:0}}}};if(t.teamsMeetingPhoneCallEnable&&T&&E&&M.push(O),t.onUserSetOverflowGalleryPositionChange){const e={key:"overflowGalleryPositionKey",iconProps:{iconName:"GalleryOptions",styles:{root:{lineHeight:0}}},itemProps:{styles:e9},submenuIconProps:{styles:D},text:d.strings.call.moreButtonGalleryControlLabel,disabled:t.disableButtonsForHoldScreen,subMenuProps:{items:[{key:"dynamicSelectionKey",text:d.strings.call.moreButtonGalleryFloatingLocalLayoutLabel,canCheck:!0,itemProps:{styles:e9},isChecked:"floatingLocalVideo"===t.userSetGalleryLayout,onClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("floatingLocalVideo"),f(!1)},iconProps:{iconName:"FloatingLocalVideoGalleryLayout",styles:{root:{lineHeight:0}}}},{key:"speakerSelectionKey",text:d.strings.call.moreButtonGallerySpeakerLayoutLabel,canCheck:!0,itemProps:{styles:e9},isChecked:"speaker"===t.userSetGalleryLayout,onClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("speaker"),f(!1)},iconProps:{iconName:"SpeakerGalleryLayout",styles:{root:{lineHeight:0}}}},{key:"focusedContentSelectionKey",text:d.strings.call.moreButtonGalleryFocusedContentLayoutLabel,canCheck:!0,itemProps:{styles:e9},isChecked:m,onClick:()=>{var e;!1===m?(S(null!==(e=t.userSetGalleryLayout)&&void 0!==e?e:"floatingLocalVideo"),t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("focusedContent"),f(!0)):(t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout(v),f(!1))},iconProps:{iconName:"FocusedContentGalleryLayout",styles:{root:{lineHeight:0}}}}],calloutProps:{preventDismissOnEvent:v0}}},i={key:"togetherModeSelectionKey",text:d.strings.call.moreButtonTogetherModeLayoutLabel,canCheck:!0,itemProps:{styles:e9},isChecked:"togetherMode"===t.userSetGalleryLayout,onClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("togetherMode"),f(!1)},disabled:!("microsoftTeamsUser"===(null==I?void 0:I.kind)&&(null===(a=null==_?void 0:_.startTogetherMode)||void 0===a?void 0:a.isPresent)||b),iconProps:{iconName:"TogetherModeLayout",styles:{root:{lineHeight:0}}}};(w||T)&&(null===(l=null===(o=e.subMenuProps)||void 0===o?void 0:o.items)||void 0===l||l.push(i)),!0!==t.callControls&&!1===(null===(c=t.callControls)||void 0===c?void 0:c.galleryControlsButton)||M.push(e)}const N=(0,e.useMemo)((()=>q9(W9("object"==typeof t.callControls?t.callControls:void 0),"object"==typeof t.callControls?t.callControls.displayType:void 0)),[t.callControls]);return N.primary.slice(3).forEach((e=>{M.push(Object.assign({itemProps:{styles:e9}},e))})),N.secondary.slice(2).forEach((e=>{M.push(Object.assign({itemProps:{styles:e9}},e))})),N.overflow.forEach((e=>{M.push(Object.assign({itemProps:{styles:e9}},e))})),e.createElement(a9,Object.assign({},t,{"data-ui-id":"common-call-composite-more-button",strings:R,menuIconProps:{hidden:!0},menuProps:{shouldFocusOnContainer:!1,items:M,calloutProps:{preventDismissOnEvent:v0}}}))},dee=()=>e.createElement(bZ,{iconName:"DtmfDialpadButton"}),uee=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:s,displayType:a}=t,o=qK(),l=PJ(),c={label:l.strings.call.dtmfDialerButtonLabel,tooltipOnContent:l.strings.call.dtmfDialerButtonTooltipOn,tooltipOffContent:l.strings.call.dtmfDialerButtonTooltipOff},d=(0,e.useMemo)((()=>{var e;return ZH({rootChecked:{background:o.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles,o.palette.neutralLight]);return e.createElement(R3,Object.assign({},t,{strings:i||c,showLabel:"compact"!==a,labelKey:"dtmfDialpadButtonLabelKey",onRenderOnIcon:null!=n?n:dee,onRenderOffIcon:null!=r?r:dee,onClick:s,styles:d}))},hee=t=>e.createElement(R3,Object.assign({"data-ui-id":"call-composite-exit-spotlight-button",labelKey:"exitSpotlightButtonLabelKey",showLabel:"compact"!==t.displayType,onRenderIcon:()=>e.createElement(M3,{iconName:"ControlButtonExitSpotlight"}),onClick:t.onClick},t)),gee=16,pee={root:{position:"absolute",width:"100%",height:"100%",pointerEvents:"none",":focus-within":{outline:"1px solid #00000000"}}},mee=ZH(pee,{root:{display:"none"}}),fee={main:{minWidth:"min-content",minHeight:"min-content",position:"absolute",overflow:"hidden",pointerEvents:"auto",touchAction:"none"},root:{width:"100%",height:"100%",pointerEvents:"none",":focus-within":{outline:"3px solid #00000000",outlineOffset:"-3px"}}},vee={display:"flex",position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden",zIndex:"100000",pointerEvents:"none"},See=e=>null!==e&&"boolean"==typeof e,yee=dB({fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28)}),Cee=dB({paddingBottom:vJ(30)}),Tee=dB({fontSize:vJ(14),lineHeight:vJ(40)}),Eee=dB({fontSize:vJ(14),lineHeight:vJ(40),fontWeight:DV.semibold}),bee=e=>dB({background:`${e.palette.themeLighter}`,height:vJ(36),width:vJ(36),marginRight:vJ(12),borderRadius:vJ(18)}),_ee=dB({marginBottom:vJ(20)}),Iee=dB({textAlign:"right"}),wee=e=>dB({padding:vJ(8),color:`${e.palette.themePrimary}`,zIndex:2}),Aee=e=>dB({background:`${e.palette.themeLighter}`,width:vJ(2),position:"relative",left:vJ(19),top:vJ(20),zIndex:1}),Pee=t=>{var i;const{conferencePhoneInfoList:n,showModal:r,onDismissMeetingPhoneInfoSettings:s}=t,a=qK(),o=AK().strings.meetingConferencePhoneInfo,l=(0,e.useCallback)((()=>{s&&s()}),[s]),c=(0,e.useMemo)((()=>(e=>({main:{borderRadius:e.effects.roundedCorner6,padding:vJ(24),width:vJ(600),height:"fit-content",overflow:"hidden"}}))(a)),[a]);return e.createElement(e.Fragment,null,e.createElement(y3,{titleAriaId:null==o?void 0:o.meetingConferencePhoneInfoModalTitle,isOpen:r,onDismiss:l,isBlocking:!0,styles:c},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:Cee},e.createElement(oJ,{role:"heading","aria-level":2,className:yee},null==o?void 0:o.meetingConferencePhoneInfoModalTitle),e.createElement(oK,{iconProps:{iconName:"Cancel"},ariaLabel:null==o?void 0:o.meetingConferencePhoneInfoModalTitle,onClick:l,style:{color:a.palette.black}})),0===n.length&&e.createElement(Y$,{horizontal:!0},e.createElement(oJ,{className:Tee},null==o?void 0:o.meetingConferencePhoneInfoModalNoPhoneAvailable)),n.length>0&&e.createElement(Y$,null,e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",className:_ee},e.createElement(Y$.Item,{style:{display:"flex"}},e.createElement(Y$,{horizontal:!0,className:Iee},e.createElement(Y$,{className:Aee(a)}),e.createElement(Y$.Item,{className:bee(a)},e.createElement(Y$,{verticalAlign:"center",horizontalAlign:"center"},e.createElement(mG,{iconName:"JoinByPhoneDialStepIcon",className:wee(a)}))),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Tee},null==o?void 0:o.meetingConferencePhoneInfoModalDialIn)))),e.createElement(Y$.Item,{className:Iee},n.map(((t,i)=>e.createElement(Y$.Item,{key:i},e.createElement(oJ,{className:Eee},A6(t.phoneNumber,!0)," ",t.isTollFree?o.meetingConferencePhoneInfoModalTollFree:o.meetingConferencePhoneInfoModalToll),e.createElement("br",null),e.createElement(oJ,{className:Eee}," ",Mee(t,o))))))),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:_ee},e.createElement(Y$.Item,{style:{display:"flex"}},e.createElement(Y$,{horizontal:!0},e.createElement(Y$,{className:Aee(a)}),e.createElement(Y$.Item,{className:bee(a)},e.createElement(Y$,{verticalAlign:"center",horizontalAlign:"center"},e.createElement(mG,{iconName:"JoinByPhoneConferenceIdIcon",className:wee(a)}))),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Tee},null==o?void 0:o.meetingConferencePhoneInfoModalMeetingId)))),e.createElement(oJ,{className:Eee},Dee(null===(i=n[0])||void 0===i?void 0:i.conferenceId))),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center"},e.createElement(Y$,{horizontal:!0},e.createElement(Y$.Item,{className:bee(a),style:{marginLeft:vJ(2)}},e.createElement(mG,{iconName:"JoinByPhoneWaitToBeAdmittedIcon",className:wee(a)})),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Tee},null==o?void 0:o.meetingConferencePhoneInfoModalWait)))))))},Ree=e=>`tel:+${e.phoneNumber},,${e.conferenceId}#`,Mee=(e,t)=>{const i=e.country&&e.city?null==t?void 0:t.meetingConferencePhoneInfoModalTollGeoData:"";return(null==i?void 0:i.replace("{country}",e.country||"").replace("{city}",e.city||"").trim())||""},Dee=e=>e?9!==(null==e?void 0:e.length)?e:[e.slice(0,3),e.slice(3,6),e.slice(6,9)].join(" ")+"#":"",kee=e=>Math.floor(Oee(e)/60),Oee=e=>Math.floor(e/1e3),Nee=e=>{const t=(e=>Math.floor(kee(e)/60))(e);return`${t>0?t+":":""}${("0"+kee(e)%60).slice(-2)}:${("0"+Oee(e)%60).slice(-2)}`},Lee=t=>{const{timeStampInfo:i}=t,n=new Date(i).getTime(),r=qK(),[s,a]=(0,e.useState)(0),o=Nee(s);return e.useEffect((()=>{const e=setInterval((()=>{a(Math.max(n-Date.now(),0))}),10);return()=>{clearInterval(e)}}),[n]),e.createElement(Y$,{horizontal:!0,className:xee(r),tokens:{childrenGap:"0.5rem"}},e.createElement(hG,{iconName:"Clock",className:Fee}),e.createElement(oJ,{styles:Uee},o))},xee=e=>dB({backgroundColor:e.palette.neutralLight,display:"flex",alignItems:"center",borderColor:e.palette.neutralQuaternaryAlt,borderWidth:"0.0625rem",borderRadius:"0.25rem",padding:"0.5rem"}),Fee=dB({fontSize:18}),Uee={root:{color:"inherit",fontWeight:400,fontSize:vJ(14),lineHeight:vJ(20),margin:"auto"}};const Bee=t=>{const{showModal:i,onDismissModal:n,onStartRealTimeText:r}=t,s=AK().strings.realTimeTextModal,a=Object.assign(Object.assign({},s),t.strings),o=qK(),l=(0,e.useCallback)((()=>{n&&n()}),[n]),c=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){r&&(yield r()),l()},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[l,r]),d=(0,e.useMemo)((()=>a4(o)),[o]);return e.createElement(e.Fragment,null,e.createElement(y3,{titleAriaId:null==a?void 0:a.realTimeTextModalAriaLabel,isOpen:i,onDismiss:l,isBlocking:!0,styles:d},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:l4},e.createElement(oJ,{className:o4},null==a?void 0:a.realTimeTextModalTitle),e.createElement(oK,{iconProps:{iconName:"Cancel"},ariaLabel:null==a?void 0:a.realTimeTextCloseModalButtonAriaLabel,onClick:l,style:{color:o.palette.black}})),e.createElement(oJ,null,null==a?void 0:a.realTimeTextModalText),e.createElement(Y$,{horizontal:!0,horizontalAlign:"end",className:u4},e.createElement(mJ,{styles:h4(o),onClick:c},e.createElement("span",null,null==a?void 0:a.realTimeTextConfirmButtonLabel)),e.createElement(pJ,{onClick:l,styles:h4(o)},e.createElement("span",null,null==a?void 0:a.realTimeTextCancelButtonLabel)))))},Vee=t=>{const i=PJ().strings.call,n={realTimeTextModalTitle:i.realTimeTextModalTitle,realTimeTextModalText:i.realTimeTextModalText,realTimeTextConfirmButtonLabel:i.realTimeTextConfirmButtonLabel,realTimeTextCancelButtonLabel:i.realTimeTextCancelButtonLabel,realTimeTextModalAriaLabel:i.realTimeTextModalAriaLabel,realTimeTextCloseModalButtonAriaLabel:i.realTimeTextCloseModalButtonAriaLabel};return e.createElement(Bee,{strings:n,showModal:t.showModal,onDismissModal:t.onDismissModal,onStartRealTimeText:t.onStartRealTimeText})};var Hee=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const $ee=t=>{var i,n,r,s,a,o,l,c,d,u,h,g,p;const m=qK(),f=m.rtl,v=(0,e.useRef)(null),S=(0,e.useRef)(null),y=(0,e.useRef)(null),[C,T]=(0,e.useState)(0),[E,b]=(0,e.useState)(0),[_,I]=(0,e.useState)(0),[w,A]=(0,e.useState)(0),[P,R]=(0,e.useState)(!1),M=ree(),D=((e,t)=>{if(!1===t)return!1;const i=!0===t||void 0===t?{}:t;return e&&(i.displayType="compact",i.screenShareButton=!1),i})(t.mobileView,t.callControls),[k,O]=(0,e.useState)(!1),[N,L]=(0,e.useState)(!1),x=null===(i=u7((e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.capabilities.hangUpForEveryOne.isPresent})))||void 0===i||i,F=u7(A7),U=u7(k7),B=u7(O7),V=(0,e.useCallback)((()=>{T(v.current?v.current.offsetWidth:0),b(S.current?S.current.offsetWidth:0),I(y.current?y.current.offsetWidth:0)}),[]);(0,e.useEffect)((()=>{T(v.current?v.current.offsetWidth:0),b(S.current?S.current.offsetWidth:0),I(y.current?y.current.offsetWidth:0)}),[]),(0,e.useEffect)((()=>(window.addEventListener("resize",V),()=>window.removeEventListener("resize",V))),[V]),(0,e.useEffect)((()=>{A((_-C)/2+C+E)}),[C,E,_]),(0,e.useEffect)((()=>{R(w>_)}),[w,_]);const H=(0,e.useCallback)((()=>{O(!0)}),[]),$=(0,e.useCallback)((()=>{L(!0)}),[]),j=(0,e.useCallback)((()=>{L(!1)}),[]),G=(0,e.useCallback)((()=>{O(!1)}),[]),q=(0,e.useMemo)((()=>({label:M.peopleButtonLabel,selectedLabel:M.selectedPeopleButtonLabel,tooltipOpenAriaLabel:M.peopleButtonTooltipOpenAriaLabel,tooltipCloseAriaLabel:M.peopleButtonTooltipCloseAriaLabel,tooltipOffContent:M.peopleButtonTooltipOpen,tooltipOnContent:M.peopleButtonTooltipClose})),[M]),z=(0,e.useMemo)((()=>({label:M.moreDrawerButtonLabel,tooltipContent:M.moreDrawerButtonTooltip})),[M]),W=PJ().strings.call,K=(0,e.useMemo)((()=>({label:W.exitSpotlightButtonLabel,tooltipContent:W.exitSpotlightButtonTooltip})),[W]),[J,Y]=(0,e.useState)(!1),Q=(0,e.useCallback)((()=>Hee(void 0,void 0,void 0,(function*(){yield t.callAdapter.startNoiseSuppressionEffect()}))),[t.callAdapter]),Z=u7(I7),X=JF(Z);(0,e.useEffect)((()=>{t.callAdapter.getState().onResolveDeepNoiseSuppressionDependency&&t.callAdapter.getState().deepNoiseSuppressionOnByDefault&&(Q(),Y(!0))}),[t.callAdapter,Q]);const ee=!(!t.callAdapter.getState().onResolveDeepNoiseSuppressionDependency||t.callAdapter.getState().hideDeepNoiseSuppressionButton||X),te=(0,e.useCallback)((()=>Hee(void 0,void 0,void 0,(function*(){J?(yield t.callAdapter.stopNoiseSuppressionEffect(),Y(!1)):(yield t.callAdapter.startNoiseSuppressionEffect(),Y(!0))}))),[t.callAdapter,J]),ie=(0,e.useMemo)((()=>e$(t.mobileView?{}:Gee,{root:{background:m.semanticColors.bodyBackground}})),[t.mobileView,m.semanticColors.bodyBackground]),ne=(0,e.useMemo)((()=>t.mobileView?void 0:Kee(m)),[t.mobileView,m]),re=(0,e.useMemo)((()=>t.mobileView?void 0:Wee(m)),[t.mobileView,m]),se=(0,e.useMemo)((()=>t.mobileView?void 0:Jee(m)),[t.mobileView,m]),ae=(0,e.useMemo)((()=>t.mobileView||P?{}:f?zee:qee),[t.mobileView,f,P]),oe=(0,e.useMemo)((()=>t.mobileView||P?{}:{position:"relative",minHeight:"4.5rem",width:"100%",display:"flex",alignItems:"center",paddingLeft:"1rem"}),[t.mobileView,P]),le=(0,e.useMemo)((()=>$9(W9(!1!==D?D:void 0),!1!==D?null==D?void 0:D.displayType:void 0)),[D]),ce=u7(Y9),de=u7(Q9),ue="Connected"!==de.callStatus||!(null==ce?void 0:ce.capabilities)||ce.capabilities.useReactions.isPresent,he=B&&!1===B.disableReturnToMainMeeting,ge=(0,e.useCallback)((()=>t.callAdapter.returnFromBreakoutRoom()),[t.callAdapter]);if(!1===D)return e.createElement(e.Fragment,null);const pe=Yee(D.peopleButton)||Yee(D.chatButton)||void 0!==le.secondary,me=Yee(null==D?void 0:D.screenShareButton),fe=Yee(null==D?void 0:D.microphoneButton),ve=Yee(null==D?void 0:D.cameraButton),Se=!1!==(null==D?void 0:D.exitSpotlightButton),ye=t.isCaptionsSupported&&Yee(D.captionsButton),Ce=t.isRealTimeTextSupported,Te=Yee(null==D?void 0:D.teamsMeetingPhoneCallButton),Ee=Yee(null==D?void 0:D.moreButton)&&(Yee(null==D?void 0:D.holdButton)||ye||t.onUserSetGalleryLayout||Ce),be=null===(n=t.callAdapter.getState().call)||void 0===n?void 0:n.role,_e=t.callAdapter.getState().isRoomsCall&&be&&["Consumer","Unknown"].includes(be),Ie=t.callAdapter.getState().reactions;return e.createElement("div",{ref:y},e.createElement(NZ,{adapter:t.callAdapter},k&&e.createElement(Q7,{showCaptionsSettingsModal:k,onDismissCaptionsSettings:G,changeCaptionLanguage:t.isCaptionsOn&&t.useTeamsCaptions}),N&&e.createElement(Vee,{showModal:N,onDismissModal:j,onStartRealTimeText:t.onStartRealTimeText}),t.teamsMeetingConferenceModalPresent&&e.createElement(Pee,{conferencePhoneInfoList:null!==(a=null===(s=null===(r=t.callAdapter.getState().call)||void 0===r?void 0:r.meetingConference)||void 0===s?void 0:s.conferencePhones)&&void 0!==a?a:[],showModal:t.teamsMeetingConferenceModalPresent,onDismissMeetingPhoneInfoSettings:t.onToggleTeamsMeetingConferenceModal})),e.createElement(Y$,{horizontal:!0,reversed:!t.mobileView&&!P,horizontalAlign:"space-between",className:dB(D9,P9,oe)},e.createElement(Y$.Item,{grow:!0,className:dB(ae)},e.createElement(NZ,{adapter:t.callAdapter},e.createElement(Y$,{horizontalAlign:"center"},e.createElement(Y$.Item,null,e.createElement("div",{ref:v},e.createElement(h9,{layout:t.displayVertical?"vertical":"horizontal",styles:ie},!t.mobileView&&U&&"open"===U.state&&!B&&e.createElement(mJ,{text:W.joinBreakoutRoomButtonLabel,onClick:()=>Hee(void 0,void 0,void 0,(function*(){U.join()})),styles:re}),fe&&e.createElement(T9,{displayType:D.displayType,styles:re,splitButtonsForDeviceSelection:!t.mobileView,disabled:t.disableButtonsForHoldScreen||WF(D.microphoneButton),disableTooltip:t.mobileView,onClickNoiseSuppression:te,isDeepNoiseSuppressionOn:J,showNoiseSuppressionButton:ee}),ve&&e.createElement(g9,{displayType:D.displayType,styles:re,splitButtonsForDeviceSelection:!t.mobileView,disabled:t.disableButtonsForHoldScreen||WF(D.cameraButton),onClickVideoEffects:t.onClickVideoEffects,componentRef:t.cameraButtonRef,disableTooltip:t.mobileView}),!t.mobileView&&ue&&Yee(D.reactionButton)&&Ie&&e.createElement(K9,{displayType:D.displayType,styles:re,disabled:t.disableButtonsForHoldScreen,reactionResource:Ie}),!t.mobileView&&Yee(D.raiseHandButton)&&!_e&&e.createElement(V9,{displayType:D.displayType,styles:re,disabled:t.disableButtonsForHoldScreen||WF(D.microphoneButton)}),Qee(D)&&void 0!==t.onSetDialpadPage&&e.createElement(uee,{styles:re,displayType:D.displayType,onClick:()=>{void 0!==t.onSetDialpadPage&&t.onSetDialpadPage()}}),Se&&t.onStopLocalSpotlight&&e.createElement(hee,{displayType:D.displayType,onClick:t.onStopLocalSpotlight,styles:re,strings:K}),me&&e.createElement(_9,{option:D.screenShareButton,displayType:D.displayType,styles:ne,disabled:t.disableButtonsForHoldScreen||WF(D.screenShareButton)}),null===(o=le.primary)||void 0===o?void 0:o.slice(0,t.mobileView?1:3).map(((i,n)=>e.createElement(i,{key:`primary-custom-button-${n}`,styles:re,showLabel:"compact"!==D.displayType,disableTooltip:t.mobileView}))),t.mobileView&&e.createElement(a9,{"data-ui-id":"common-call-composite-more-button",strings:z,onClick:t.onMoreButtonClicked,disabled:t.disableButtonsForLobbyPage,disableTooltip:t.mobileView}),!t.mobileView&&Ee&&e.createElement(cee,{disableButtonsForHoldScreen:t.disableButtonsForHoldScreen,styles:re,onClickShowDialpad:t.onClickShowDialpad,callControls:t.callControls,isCaptionsSupported:ye,isRealTimeTextSupported:Ce,onCaptionsSettingsClick:H,onStartRealTimeTextClick:$,startRealTimeTextButtonChecked:t.startRealTimeTextButtonChecked,onUserSetOverflowGalleryPositionChange:t.onUserSetOverflowGalleryPositionChange,onUserSetGalleryLayout:t.onUserSetGalleryLayout,userSetGalleryLayout:t.userSetGalleryLayout,dtmfDialerPresent:t.dtmfDialerPresent,onSetDialpadPage:t.onSetDialpadPage,teamsMeetingPhoneCallEnable:Te,onMeetingPhoneInfoClick:t.onToggleTeamsMeetingConferenceModal}),e.createElement(C9,{displayType:"compact",mobileView:t.mobileView,styles:se,enableEndCallMenu:!See(t.callControls)&&!See(null===(l=t.callControls)||void 0===l?void 0:l.endCallButton)&&!t.mobileView&&x&&!F&&"endCallOptions"===(null===(d=null===(c=t.callControls)||void 0===c?void 0:c.endCallButton)||void 0===d?void 0:d.hangUpForEveryone)&&"Connected"===de.callStatus&&!he,disableEndCallModal:!See(t.callControls)&&!See(null===(u=t.callControls)||void 0===u?void 0:u.endCallButton)&&(null===(g=null===(h=t.callControls)||void 0===h?void 0:h.endCallButton)||void 0===g?void 0:g.disableEndCallModal),returnFromBreakoutRoom:he?ge:void 0}))))))),!t.mobileView&&pe&&e.createElement(Y$.Item,null,e.createElement("div",{ref:S},e.createElement(Y$,{horizontal:!0,className:t.mobileView?void 0:dB(jee)},Yee(null==D?void 0:D.peopleButton)&&e.createElement(nee,{checked:t.peopleButtonChecked,ariaLabel:q.label,showLabel:"compact"!==D.displayType,onClick:t.onPeopleButtonClicked,"data-ui-id":"common-call-composite-people-button",disabled:t.disableButtonsForLobbyPage||t.disableButtonsForHoldScreen||WF(D.peopleButton),strings:q,styles:re,componentRef:t.peopleButtonRef,chatButtonPresent:Yee(D.chatButton),peoplePaneDismissButtonRef:t.sidePaneDismissButtonRef}),null===(p=le.secondary)||void 0===p?void 0:p.slice(0,2).map(((t,i)=>e.createElement(t,{key:`secondary-custom-button-${i}`,styles:re,showLabel:"compact"!==D.displayType})))))),(null==B?void 0:B.roomEndTime)&&!t.mobileView&&!P&&e.createElement(Y$.Item,null,e.createElement(Lee,{timeStampInfo:null==B?void 0:B.roomEndTime.toString()}))))},jee={padding:"0.75rem",columnGap:"0.5rem"},Gee={root:jee},qee={position:"absolute",left:"50%",transform:"translate(-50%, 0)"},zee={position:"absolute",right:"50%",transform:"translate(-50%, 0)"},Wee=e=>({root:{border:`solid 1px ${e.palette.neutralQuaternaryAlt}`,borderRadius:e.effects.roundedCorner4,minHeight:"2.5rem",maxWidth:"12rem"},flexContainer:{display:"flex",flexFlow:"row nowrap"},textContainer:{display:"inline",maxWidth:"100%"},label:{fontSize:e.fonts.medium.fontSize,marginLeft:"0.625rem",lineHeight:"1.5rem",display:"block",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"},splitButtonMenuButton:{border:`solid 1px ${e.palette.neutralQuaternaryAlt}`,borderTopRightRadius:e.effects.roundedCorner4,borderBottomRightRadius:e.effects.roundedCorner4,borderTopLeftRadius:"0",borderBottomLeftRadius:"0"},splitButtonMenuButtonChecked:{background:"none"}}),Kee=e=>{const t={border:"none",background:e.palette.themePrimary,color:e.palette.white,"* > svg":{fill:e.palette.white},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},i={rootChecked:t,rootCheckedHovered:t};return ZH(Wee(e),i)},Jee=e=>{const t={root:{border:"none"},rootFocused:{"@media (forced-colors: active)":{background:"highlight",color:"highlightText",borderColor:e.palette.black,borderRadius:"unset",outline:`3px solid ${e.palette.black}`}},icon:{"@media (forced-colors: active)":{":focused":{color:e.palette.white}}}};return ZH(Wee(e),t)},Yee=e=>!1!==e,Qee=e=>!1===e.moreButton&&!1!==e.dtmfDialerButton,Zee=t=>{var i,n,r,s,a;const o=aJ(),l=t.reactionResources,c=new Map([["like",null===(i=null==l?void 0:l.likeReaction)||void 0===i?void 0:i.url],["heart",null===(n=null==l?void 0:l.heartReaction)||void 0===n?void 0:n.url],["laugh",null===(r=null==l?void 0:l.laughReaction)||void 0===r?void 0:r.url],["applause",null===(s=null==l?void 0:l.applauseReaction)||void 0===s?void 0:s.url],["surprised",null===(a=null==l?void 0:l.surprisedReaction)||void 0===a?void 0:a.url]]),d=aJ().effects.roundedCorner4,u={root:{borderTopRightRadius:d,borderTopLeftRadius:d,marginTop:"12px"}};return e.createElement(Y$,{"data-ui-id":"reaction-mobile-drawer-menu-item",id:"reaction",role:"menuitem",horizontal:!0,className:dB(Xee(o.palette.neutralLight,o.fonts.small),t.disabled?ete(o.palette.neutralQuaternaryAlt):void 0,u.root)},e.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexDirection:"row",width:"100%",height:"2.625rem"}},["like","heart","laugh","applause","surprised"].map(((i,n)=>{const r=c.get(i.toString());return e.createElement(oK,{key:n,onClick:()=>{var e;null===(e=t.onReactionClick)||void 0===e||e.call(t,i)},style:(s=r||"",a="running",{display:"flex",flexDirection:"column",height:"100%",width:"2.75rem",backgroundImage:`url(${s})`,animationName:G8(),animationDuration:"8.12s",animationTimingFunction:"steps(102)",animationPlayState:a,animationIterationCount:"infinite",justifyContent:"center",alignItems:"center",backgroundPosition:"center",backgroundSize:"2.75rem 133.875rem",transition:"opacity 2s",backgroundColor:"transparent",transform:"scale(0.8)"})});var s,a}))))},Xee=(e,t)=>Object.assign(Object.assign({},t),{height:"3rem",lineHeight:"3rem",padding:"0rem 0.75rem",cursor:"pointer",":hover, :focus":{background:e}}),ete=e=>({pointerEvents:"none",background:e,":hover, :focus":{background:e}}),tte=e=>({root:{overflow:"auto"},drawerSurfaceStyles:{drawerContentContainer:{root:{span:{fontWeight:400,fontSize:vJ(14),lineHeight:vJ(22),color:e.palette.neutralDark}}}}}),ite=t=>{var i;const n=aJ(),r=(0,e.useCallback)((e=>{t.selectLanguage(e)}),[t]),s=(0,e.useMemo)((()=>{var e;return S0(null!==(e=t.supportedLanguageStrings)&&void 0!==e?e:[]).map((e=>({itemKey:e,text:t.supportedLanguageStrings?t.supportedLanguageStrings[e]:e,onItemClick:()=>r(e),secondaryIconProps:t.currentLanguage===e?{iconName:"Accept"}:void 0})))}),[t.currentLanguage,t.supportedLanguageStrings,r]),a=(0,e.useMemo)((()=>[...s].sort(((e,t)=>e.text&&t.text&&e.text>t.text?1:-1))),[s]);return e.createElement(K0,{heading:null===(i=t.strings)||void 0===i?void 0:i.menuTitle,items:null!=a?a:[],onLightDismiss:()=>{t.setCurrentLanguage(t.currentLanguage),t.onLightDismiss()},styles:tte(n)})},nte=(e,t)=>t?{root:{margin:0},pill:{backgroundColor:`${e.palette.themePrimary} !important`},thumb:{backgroundColor:`${e.palette.white} !important`}}:{root:{margin:0}},rte=t=>{var i;const n=aJ(),r=(0,e.useCallback)((e=>{t.selectLanguage(e)}),[t]),s=(0,e.useMemo)((()=>{var e;return S0(null!==(e=t.supportedLanguageStrings)&&void 0!==e?e:[]).map((e=>({itemKey:e,text:t.supportedLanguageStrings?t.supportedLanguageStrings[e]:e,onItemClick:()=>r(e),secondaryIconProps:t.currentLanguage===e?{iconName:"Accept"}:void 0})))}),[t.currentLanguage,t.supportedLanguageStrings,r]),a=(0,e.useMemo)((()=>[...s].sort(((e,t)=>e.text&&t.text&&e.text>t.text?1:-1))),[s]);return e.createElement(K0,{heading:null===(i=t.strings)||void 0===i?void 0:i.menuTitle,items:null!=a?a:[],onLightDismiss:()=>{t.setCurrentLanguage(t.currentLanguage),t.onLightDismiss()},styles:tte(n)})};var ste=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const ate=t=>{var i,n,r,s,a,o,l;const c=qK(),d=LZ(),u=[],{speakers:h,onSelectSpeaker:g,onLightDismiss:p}=t,m=PJ(),f=Y7(F6),v=Y7(p4),S=u7(M7),y=u7(aee),C=lee(S,y,t.dtmfDialerOptions),[T,E]=(0,e.useState)(null!==(i=t.dtmfDialerPresent)&&void 0!==i&&i),b=Y7(U6),_=u7(m7),I=u7(q7),w=u7(G7),A=u7(A7),P=P7(d.getState()),R=(0,e.useCallback)(((e,t)=>{const i=null==h?void 0:h.find((e=>e.id===t));i&&g(i),p()}),[h,g,p]),M=!1!==(D=t.callControls)&&(!0===D||void 0===D?{}:D);var D;const k=t.isCaptionsSupported&&!1!==M&&lte(M.captionsButton),O=t.isRealTimeTextSupported;void 0!==t.reactionResources&&u.push({itemKey:"reactions",onRendererContent:()=>e.createElement(Zee,{onReactionClick:e=>ste(void 0,void 0,void 0,(function*(){var i;null===(i=t.onReactionClick)||void 0===i||i.call(t,e),p()})),reactionResources:t.reactionResources})}),t.speakers&&t.speakers.length>0&&u.push({itemKey:"speakers",disabled:t.disableButtonsForHoldScreen,text:t.strings.speakerMenuTitle,iconProps:{iconName:"MoreDrawerSpeakers"},subMenuProps:t.speakers.map((e=>({itemKey:e.id,iconProps:{iconName:ote(e,t.selectedSpeaker)?"MoreDrawerSelectedSpeaker":"MoreDrawerSpeakers"},text:e.name,onItemClick:R,secondaryIconProps:ote(e,t.selectedSpeaker)?{iconName:"Accept"}:void 0}))),secondaryText:null===(n=t.selectedSpeaker)||void 0===n?void 0:n.name});const{microphones:N,onSelectMicrophone:L}=t,x=(0,e.useCallback)(((e,t)=>{const i=null==N?void 0:N.find((e=>e.id===t));i&&L(i),p()}),[N,L,p]);if(t.microphones&&t.microphones.length>0){const e=t.speakers&&t.speakers.length>0,i=e?"microphones":"audioDevices",n=e?t.strings.microphoneMenuTitle:t.strings.audioDeviceMenuTitle,s=e?"MoreDrawerMicrophones":"MoreDrawerSpeakers",a=e?"MoreDrawerSelectedMicrophone":"MoreDrawerSelectedSpeaker";u.push({itemKey:i,disabled:t.disableButtonsForHoldScreen,text:n,iconProps:{iconName:s},subMenuProps:t.microphones.map((e=>({itemKey:e.id,iconProps:{iconName:ote(e,t.selectedMicrophone)?a:s},text:e.name,onItemClick:x,secondaryIconProps:ote(e,t.selectedMicrophone)?{iconName:"Accept"}:void 0,disabled:!1!==M?WF(M.microphoneButton):void 0}))),secondaryText:null===(r=t.selectedMicrophone)||void 0===r?void 0:r.name})}const F={itemKey:"dtmfDialerScreenKey",text:T?m.strings.call.dtmfDialerMoreButtonLabelOff:m.strings.call.dtmfDialerMoreButtonLabelOn,onItemClick:()=>{t.onSetDialpadPage&&t.onSetDialpadPage(),E(!T),p()},iconProps:{iconName:"DtmfDialpadButton",styles:{root:{lineHeight:0}}}};t.onSetDialpadPage&&C&&!1!==M&&lte(M.dtmfDialerButton)&&u.push(F);const U={itemKey:"galleryPositionKey",iconProps:{iconName:"GalleryOptions",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen,text:m.strings.call.moreButtonGalleryControlLabel,subMenuProps:[{itemKey:"dynamicSelectionKey",text:m.strings.call.moreButtonGalleryFloatingLocalLayoutLabel,onItemClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("floatingLocalVideo"),p()},iconProps:{iconName:"FloatingLocalVideoGalleryLayout",styles:{root:{lineHeight:0}}},secondaryIconProps:"floatingLocalVideo"===t.userSetGalleryLayout?{iconName:"Accept"}:void 0},{itemKey:"focusedContentSelectionKey",text:m.strings.call.moreButtonGalleryFocusedContentLayoutLabel,onItemClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("focusedContent"),p()},iconProps:{iconName:"FocusedContentGalleryLayout",styles:{root:{lineHeight:0}}},secondaryIconProps:"focusedContent"===t.userSetGalleryLayout?{iconName:"Accept"}:void 0}]},B={itemKey:"togetherModeSelectionKey",text:m.strings.call.moreButtonTogetherModeLayoutLabel,onItemClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("togetherMode"),p()},iconProps:{iconName:"TogetherModeLayout",styles:{root:{lineHeight:0}}},disabled:!("microsoftTeamsUser"===(null==I?void 0:I.kind)&&(null===(s=null==_?void 0:_.startTogetherMode)||void 0===s?void 0:s.isPresent)||w),secondaryIconProps:"default"===t.userSetGalleryLayout?{iconName:"Accept"}:void 0};(A||P)&&(null===(a=U.subMenuProps)||void 0===a||a.push(B)),!1!==M&&lte(null==M?void 0:M.galleryControlsButton)&&u.push(U),!1!==M&&lte(null==M?void 0:M.peopleButton)&&u.push({itemKey:"people",id:"call-composite-drawer-people-button",text:t.strings.peopleButtonLabel,iconProps:{iconName:"MoreDrawerPeople"},onItemClick:t.onPeopleButtonClicked,disabled:WF(M.peopleButton)||t.disableButtonsForHoldScreen}),!1!==M&&lte(null==M?void 0:M.holdButton)&&u.push({itemKey:"holdButtonKey",disabled:t.disableButtonsForHoldScreen||WF(M.holdButton),text:m.component.strings.holdButton.tooltipOffContent,onItemClick:()=>{f.onToggleHold(),p()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}}});const V=null===(o=d.getState().call)||void 0===o?void 0:o.role,H=d.getState().isRoomsCall&&V&&["Consumer","Unknown"].includes(V);if(!1!==M&&lte(null==M?void 0:M.raiseHandButton)&&!H){const e=b.checked?"LowerHandContextualMenuItem":"RaiseHandContextualMenuItem";u.push({itemKey:"raiseHandButtonKey",disabled:t.disableButtonsForHoldScreen||WF(M.raiseHandButton),text:b.checked?m.component.strings.raiseHandButton.onLabel:m.component.strings.raiseHandButton.offLabel,onItemClick:()=>{b.onToggleRaiseHand&&b.onToggleRaiseHand(),p()},iconProps:{iconName:e,styles:{root:{lineHeight:0}}}})}const $=R7(d.getState());!1!==M&&lte(null==M?void 0:M.teamsMeetingPhoneCallButton)&&P&&$&&u.push({itemKey:"phoneCallInfoKey",disabled:WF(M.teamsMeetingPhoneCallButton),text:m.strings.call.phoneCallMoreButtonLabel,onItemClick:()=>{var e;null===(e=t.onClickMeetingPhoneInfo)||void 0===e||e.call(t),p()},iconProps:{iconName:"PhoneNumberButton",styles:{root:{lineHeight:0}}}});const j=PJ().strings.call.spokenLanguageStrings,G=PJ().strings.call.captionLanguageStrings,q=Y7(T3),z=Y7(p6),[W,K]=(0,e.useState)(!1),[J,Y]=(0,e.useState)(!1),[Q,Z]=(0,e.useState)(q.currentSpokenLanguage&&""!==q.currentSpokenLanguage?q.currentSpokenLanguage:"en-us"),[X,ee]=(0,e.useState)(null!==(l=q.currentCaptionLanguage)&&void 0!==l?l:C3[Q]),te=(0,e.useCallback)((()=>ste(void 0,void 0,void 0,(function*(){q.isCaptionsFeatureActive?z.onStopCaptions():yield z.onStartCaptions({spokenLanguage:Q})}))),[q.isCaptionsFeatureActive,z,Q]);if(k){const i=[],n=j?j[Q]:Q;if(u.push({itemKey:"captions",id:"common-call-composite-captions-button",disabled:t.disableButtonsForHoldScreen,text:t.strings.captionsMenuTitle,iconProps:{iconName:"CaptionsIcon"},subMenuProps:i}),i.push({itemKey:"ToggleCaptionsKey",text:q.isCaptionsFeatureActive?m.strings.call.startCaptionsButtonTooltipOnContent:m.strings.call.startCaptionsButtonTooltipOffContent,iconProps:{iconName:q.isCaptionsFeatureActive?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},onItemClick:te,disabled:t.disableButtonsForHoldScreen,secondaryComponent:e.createElement(Y$,{verticalFill:!0,verticalAlign:"center"},e.createElement(L3,{id:"common-call-composite-captions-toggle-button",checked:q.isCaptionsFeatureActive,styles:nte(c,q.isCaptionsFeatureActive),onChange:te}))}),i.push({itemKey:"ChangeSpokenLanguage",text:t.strings.spokenLanguageMenuTitle,id:"common-call-composite-captions-spoken-settings-button",secondaryText:n,iconProps:{iconName:"ChangeSpokenLanguageIcon",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen||!q.isCaptionsFeatureActive,onItemClick:()=>{K(!0)},secondaryIconProps:{iconName:"ChevronRight",styles:{root:{lineHeight:0}}}}),t.useTeamsCaptions){const e=G?G[X]:X;i.push({itemKey:"ChangeCaptionLanguage",text:t.strings.captionLanguageMenuTitle,id:"common-call-composite-captions-subtitle-settings-button",secondaryText:e,iconProps:{iconName:"ChangeCaptionLanguageIcon",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen||!q.isCaptionsFeatureActive,onItemClick:()=>{Y(!0)},secondaryIconProps:{iconName:"ChevronRight",styles:{root:{lineHeight:0}}}})}}const ie=t.disableButtonsForHoldScreen||v.isRealTimeTextOn||t.startRealTimeTextButtonChecked;if(O){const i=[];u.push({itemKey:"realTimeText",id:"common-call-composite-rtt-button",disabled:t.disableButtonsForHoldScreen,text:m.strings.call.realTimeTextLabel,iconProps:{iconName:"RealTimeTextIcon"},subMenuProps:i}),i.push({itemKey:"ToggleRTTKey",text:m.strings.call.startRealTimeTextLabel,ariaLabel:ie?m.strings.call.disabledStartRealTimeTextLabel:m.strings.call.startRealTimeTextLabel,iconProps:{iconName:"RealTimeTextIcon",styles:{root:{lineHeight:0}}},onItemClick:t.onStartRealTimeText,disabled:ie,secondaryComponent:e.createElement(Y$,{verticalFill:!0,verticalAlign:"center"},e.createElement(L3,{id:"common-call-composite-rtt-toggle-button",checked:v.isRealTimeTextOn||t.startRealTimeTextButtonChecked,styles:nte(c,v.isRealTimeTextOn||t.startRealTimeTextButtonChecked),onChange:t.onStartRealTimeText}))})}const ne=(0,e.useMemo)((()=>((e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:G9("primary",i),secondary:G9("secondary",i),overflow:G9("overflow",i)}})(W9(!1!==M?M:void 0),!1!==M?null==M?void 0:M.displayType:void 0)),[M]);return ne.primary.slice(1).forEach((e=>{u.push(e)})),ne.secondary.forEach((e=>{u.push(e)})),ne.overflow.forEach((e=>{u.push(e)})),e.createElement(e.Fragment,null,W&&k&&e.createElement(rte,{onLightDismiss:t.onLightDismiss,selectLanguage:Z,setCurrentLanguage:q.onSetSpokenLanguage,currentLanguage:Q,strings:{menuTitle:t.strings.spokenLanguageMenuTitle},supportedLanguageStrings:j}),J&&k&&e.createElement(ite,{onLightDismiss:t.onLightDismiss,selectLanguage:ee,setCurrentLanguage:q.onSetCaptionLanguage,currentLanguage:X,strings:{menuTitle:t.strings.captionLanguageMenuTitle},supportedLanguageStrings:G}),!W&&!J&&e.createElement(K0,{items:u,onLightDismiss:t.onLightDismiss}))},ote=(e,t)=>!!t&&e.id===t.id,lte=e=>!1!==e,cte=G6([p7],(e=>({microphones:e.microphones,speakers:e.speakers,selectedMicrophone:e.selectedMicrophone,selectedSpeaker:e.selectedSpeaker}))),dte=t=>{const i=ree(),n=(0,e.useMemo)((()=>({peopleButtonLabel:i.peopleButtonLabel,audioDeviceMenuTitle:i.moreDrawerAudioDeviceMenuTitle,microphoneMenuTitle:i.moreDrawerMicrophoneMenuTitle,speakerMenuTitle:i.moreDrawerSpeakerMenuTitle,captionsMenuTitle:i.moreDrawerCaptionsMenuTitle,spokenLanguageMenuTitle:i.moreDrawerSpokenLanguageMenuTitle,captionLanguageMenuTitle:i.moreDrawerCaptionLanguageMenuTitle,galleryOptionsMenuTitle:i.moreDrawerGalleryOptionsMenuTitle})),[i]),r=u7(cte),s=K7();return e.createElement(ate,Object.assign({},t,r,s,{strings:n}))},ute={height:"100%",width:"100%"},hte=dB(Object.assign(Object.assign({},ute),{minWidth:"20rem",minHeight:"16rem"})),gte=dB(Object.assign(Object.assign({},ute),{minWidth:"17.5rem",minHeight:"13rem"})),pte=(e=1)=>({root:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:e}}),mte=(Object.assign(Object.assign({},{root:{height:"100%",padding:"0.5rem 0.25rem",width:"21.5rem"}}),{display:"none"}),{root:{lineHeight:"1.5rem",fontSize:"1.125rem",padding:"0.75rem 0.75rem 0.75rem 0.25rem",fontWeight:"600"}}),fte={root:{margin:"0 0.25rem"}},vte={root:{flexDirection:"column",display:"flex"}},Ste={root:{flexBasis:"0",flexGrow:"1",overflowY:"auto"}},yte={root:{flexGrow:"1",flexBasis:"0",maxWidth:"100%",position:"relative"}},Cte={root:{position:"absolute",height:"100%",width:"100%"}},Tte={childrenGap:"0.5rem"},Ete=dB({height:"100%"}),bte=dB({height:"100%",overflowY:"auto",overflowX:"hidden"}),_te={root:{padding:"0rem"},participantItemStyles:{root:{padding:"0.5rem"}}},Ite={root:{padding:"0rem"},participantItemStyles:{root:{padding:"0.5rem 1rem"}}},wte={padding:"0.5rem",textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap"},Ate=e=>({root:{height:"100%",minWidth:"1.5rem",padding:"0.5rem 0.25rem",marginRight:"0.25rem",border:"none",background:"none"},rootHovered:{background:"none"},rootPressed:{background:"none"},rootFocused:{background:"none"},icon:{color:e.palette.neutralSecondary,display:"flex",alignItems:"center"}}),Pte=(ZH({root:{width:"100%",height:"100%"}},{root:{display:"none"}}),{root:{height:"3rem"}}),Rte={root:{border:"none",minWidth:"2.5rem",maxWidth:"2.875rem",height:"100%",background:"none",padding:"0 1rem"},rootChecked:{background:"none"},rootCheckedHovered:{background:"none"}},Mte=ZH(Rte,{root:{visibility:"hidden"}}),Dte={root:{border:"none",borderBottom:"0.125rem solid transparent",width:"8rem",height:"100%",background:"none",padding:"0"},rootChecked:{background:"none"},rootCheckedHovered:{background:"none"},flexContainer:{flexFlow:"column",display:"contents"},label:{fontSize:"1rem",fontWeight:100,lineHeight:"2rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},labelChecked:{fontWeight:600}},kte={root:{display:"none"}},Ote={root:{width:"100%",height:"100%"}},Nte={childrenGap:"0.5rem"},Lte=e=>dB({"@media (forced-colors: active)":{border:`0.125rem solid ${e.palette.black}`,borderRadius:e.effects.roundedCorner4,margin:"0.5rem 0.25rem 0.5rem 0rem"}}),xte=(0,e.createContext)({}),Fte=t=>e.createElement(xte.Provider,{value:t},t.children),Ute=()=>(0,e.useContext)(xte),Bte=()=>{const{sidePaneRenderer:e,overrideSidePane:t}=Ute();return!(!e&&!(null==t?void 0:t.isActive))},Vte=e=>{const t=Bte(),{sidePaneRenderer:i}=Ute();return t&&(null==i?void 0:i.id)===e},Hte=t=>{const{onClose:i,onChatButtonClicked:n,onPeopleButtonClicked:r,activeTab:s}=t,a=aJ(),o=PJ().strings.call,l=n&&r,c=(0,e.useMemo)((()=>ZH(Dte,{root:{width:"100%"},label:{fontSize:a.fonts.medium.fontSize,fontWeight:a.fonts.medium.fontWeight}},l?{rootChecked:{borderBottom:`0.125rem solid ${a.palette.themePrimary}`}}:{})),[a,l]);return e.createElement(Y$,{horizontal:!0,grow:!0,styles:Pte},e.createElement(pJ,{ariaLabel:o.returnToCallButtonAriaLabel,ariaDescription:o.returnToCallButtonAriaDescription,onClick:i,styles:Rte,onRenderIcon:()=>e.createElement(_Z,{iconName:"ChevronLeft"}),autoFocus:!0}),e.createElement(Y$.Item,{grow:!0,role:"tablist"},e.createElement(iq,{direction:yG.horizontal,className:dB(Ote.root)},e.createElement(Y$,{horizontal:!0,styles:Ote},e.createElement(Y$.Item,{grow:!0},n&&e.createElement(pJ,{onClick:n,styles:c,checked:"chat"===s,"aria-selected":"chat"===s,role:"tab",disabled:t.disableChatButton},o.chatButtonLabel)),e.createElement(Y$.Item,{grow:!0},r&&e.createElement(pJ,{onClick:r,styles:c,checked:"people"===s,"aria-selected":"people"===s,role:"tab",disabled:t.disablePeopleButton},o.peopleButtonLabel))))),e.createElement(pJ,{styles:Mte,onRenderIcon:()=>e.createElement(_Z,{iconName:"ChevronLeft"})}))},$te=t=>{var i;const{sidePaneRenderer:n,overrideSidePane:r}=Ute(),s=(null==r?void 0:r.renderer.contentRenderer)&&r.persistRenderingWhenClosed&&!r.isActive&&!n,a=(0,e.useMemo)((()=>{return{root:{height:"auto",width:"100%",padding:"0.5rem 0.25rem",maxWidth:null!=(e=t.maxWidth)?e:"21.5rem",minWidth:null!=(i=t.minWidth)?i:"18rem"}};var e,i}),[t.maxWidth,t.minWidth]),o=s?kte:t.mobileView?Ote:a,l=null!==(i=(null==r?void 0:r.isActive)?r.renderer.headerRenderer:null==n?void 0:n.headerRenderer)&&void 0!==i?i:Gte,c=(null==r?void 0:r.isActive)?r.renderer.id:void 0,{updateSidePaneRenderer:d}=t,u=(0,e.useCallback)((()=>{d(void 0)}),[d]),h=(0,e.useMemo)((()=>{var i;return e.createElement(Hte,{onClose:"chat"===c?null!==(i=t.onChatButtonClicked)&&void 0!==i?i:jte:u,activeTab:"people"===(null==n?void 0:n.id)?"people":"chat",disablePeopleButton:t.disablePeopleButton,disableChatButton:t.disableChatButton,onPeopleButtonClicked:"people"===(null==n?void 0:n.id)?jte:t.onPeopleButtonClicked,onChatButtonClicked:"chat"===c?jte:t.onChatButtonClicked})}),[c,t.onChatButtonClicked,t.onPeopleButtonClicked,t.disablePeopleButton,t.disableChatButton,null==n?void 0:n.id,u]),g=!t.mobileView||"chat"!==c&&"people"!==(null==n?void 0:n.id)?l():h,p=(null==r?void 0:r.isActive)||null==n?void 0:n.contentRenderer,m=(null==r?void 0:r.isActive)||(null==r?void 0:r.persistRenderingWhenClosed)?r.renderer.contentRenderer:void 0,f=aJ();return p||m?e.createElement(Y$,{"aria-label":t.ariaLabel,"data-is-focusable":!!t.ariaLabel,role:t.ariaLabel?"navigation":void 0,tabIndex:t.ariaLabel?0:void 0,verticalFill:!0,grow:!0,styles:o,"aria-modal":!0,"data-ui-id":"SidePane",tokens:t.mobileView||!t.showAddPeopleButton&&"people"===(null==n?void 0:n.id)?{}:Nte,className:Lte(f)},g,e.createElement(Y$.Item,{verticalFill:!0,grow:!0,styles:vte},e.createElement(Y$,{verticalFill:!0,styles:Ste},p&&e.createElement(Y$.Item,{verticalFill:!0,styles:yte},e.createElement(Y$,{styles:Cte},null==p?void 0:p())),m&&e.createElement(Y$.Item,{verticalFill:!0,styles:!(null==r?void 0:r.isActive)&&(null==r?void 0:r.persistRenderingWhenClosed)?kte:yte},e.createElement(Y$,{styles:Cte},null==m?void 0:m()))))):e.createElement(Gte,null)},jte=()=>{},Gte=()=>e.createElement(e.Fragment,null);var qte=SB((function(e,t,i,n){var r,s,a,o,l,c,d,u,h,g,p,m,f,v=rK(e),S=sK(e),y=e.palette,C=e.semanticColors;return ZH(v,S,{root:[KV(e,{inset:2,highContrastStyle:{left:4,top:4,bottom:4,right:4,border:"none"},borderColor:"transparent"}),e.fonts.medium,(r={minWidth:"40px",backgroundColor:y.white,color:y.neutralPrimary,padding:"0 4px",border:"none",borderRadius:0},r[UV]={border:"none"},r)],rootHovered:(s={backgroundColor:y.neutralLighter,color:y.neutralDark},s[UV]={color:"Highlight"},s[".".concat(qW.msButtonIcon)]={color:y.themeDarkAlt},s[".".concat(qW.msButtonMenuIcon)]={color:y.neutralPrimary},s),rootPressed:(a={backgroundColor:y.neutralLight,color:y.neutralDark},a[".".concat(qW.msButtonIcon)]={color:y.themeDark},a[".".concat(qW.msButtonMenuIcon)]={color:y.neutralPrimary},a),rootChecked:(o={backgroundColor:y.neutralLight,color:y.neutralDark},o[".".concat(qW.msButtonIcon)]={color:y.themeDark},o[".".concat(qW.msButtonMenuIcon)]={color:y.neutralPrimary},o),rootCheckedHovered:(l={backgroundColor:y.neutralQuaternaryAlt},l[".".concat(qW.msButtonIcon)]={color:y.themeDark},l[".".concat(qW.msButtonMenuIcon)]={color:y.neutralPrimary},l),rootExpanded:(c={backgroundColor:y.neutralLight,color:y.neutralDark},c[".".concat(qW.msButtonIcon)]={color:y.themeDark},c[".".concat(qW.msButtonMenuIcon)]={color:y.neutralPrimary},c),rootExpandedHovered:{backgroundColor:y.neutralQuaternaryAlt},rootDisabled:(d={backgroundColor:y.white},d[".".concat(qW.msButtonIcon)]=(u={color:C.disabledBodySubtext},u[UV]=IU({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u),d[UV]=IU({color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),d),splitButtonContainer:(h={height:"100%"},h[UV]={border:"none"},h),splitButtonDividerDisabled:(g={},g[UV]={backgroundColor:"Window"},g),splitButtonDivider:{backgroundColor:y.neutralTertiaryAlt},splitButtonMenuButton:{backgroundColor:y.white,border:"none",borderTopRightRadius:"0",borderBottomRightRadius:"0",color:y.neutralSecondary,":hover":(p={backgroundColor:y.neutralLighter,color:y.neutralDark},p[UV]={color:"Highlight"},p[".".concat(qW.msButtonIcon)]={color:y.neutralPrimary},p),":active":(m={backgroundColor:y.neutralLight},m[".".concat(qW.msButtonIcon)]={color:y.neutralPrimary},m)},splitButtonMenuButtonDisabled:(f={backgroundColor:y.white},f[UV]=IU({color:"GrayText",border:"none",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),f),splitButtonMenuButtonChecked:{backgroundColor:y.neutralLight,color:y.neutralDark,":hover":{backgroundColor:y.neutralQuaternaryAlt}},splitButtonMenuButtonExpanded:{backgroundColor:y.neutralLight,color:y.black,":hover":{backgroundColor:y.neutralQuaternaryAlt}},splitButtonMenuIcon:{color:y.neutralPrimary},splitButtonMenuIconDisabled:{color:y.neutralTertiary},label:{fontWeight:"normal"},icon:{color:y.themePrimary},menuIcon:{color:y.neutralSecondary}},t)})),zte=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(KW,IU({},this.props,{variantClassName:"ms-Button--commandBar",styles:qte(n,i),onRenderDescription:Fj}))},AU([XW("CommandBarButton",["theme","styles"],!0)],i)}(e.Component);const Wte=t=>{const i=aJ(),n=(0,e.useMemo)((()=>({root:{minWidth:"1.5rem",padding:"0.5rem 0.25rem",marginRight:"0.25rem",backgroundColor:i.semanticColors.bodyBackground,"@media (forced-colors: active)":{border:`0.1rem solid ${i.palette.neutralSecondary}`,borderRadius:i.effects.roundedCorner4}},icon:{color:i.palette.neutralSecondary},iconHovered:{color:i.palette.neutralSecondary},iconPressed:{color:i.palette.neutralSecondary}})),[i.palette.neutralSecondary,i.semanticColors.bodyBackground,i.effects.roundedCorner4]),r=(0,e.useCallback)((e=>{var i,n;"Tab"===e.key&&e.shiftKey&&!t.chatButtonPresent&&(null===(n=null===(i=t.paneOpenerButton)||void 0===i?void 0:i.current)||void 0===n||n.focus(),e.preventDefault())}),[t.chatButtonPresent,t.paneOpenerButton]);return t.mobileView?e.createElement(Kte,Object.assign({},t)):e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",styles:fte,verticalAlign:"center"},e.createElement(Y$.Item,{role:"heading",styles:mte,"aria-label":t.headingText,"aria-level":2},t.headingText),e.createElement(Y$.Item,null,e.createElement(zte,{ariaLabel:t.dismissSidePaneButtonAriaLabel,styles:n,iconProps:{iconName:"cancel"},onClick:()=>{var e,i;t.onClose(),null===(i=null===(e=t.paneOpenerButton)||void 0===e?void 0:e.current)||void 0===i||i.focus()},onKeyDown:r,componentRef:t.dismissButtonComponentRef})))},Kte=t=>{const{headingText:i,dismissSidePaneButtonAriaLabel:n,dismissSidePaneButtonAriaDescription:r,onClose:s}=t,a=aJ(),o=(0,e.useMemo)((()=>ZH(Dte,{root:{width:"100%"},label:{fontSize:a.fonts.medium.fontSize,fontWeight:a.fonts.medium.fontWeight}})),[a]);return e.createElement(Y$,{horizontal:!0,grow:!0,styles:Pte},e.createElement(pJ,{ariaLabel:n,ariaDescription:r,onClick:s,styles:Rte,onRenderIcon:()=>e.createElement(_Z,{iconName:"ChevronLeft"}),autoFocus:!0}),e.createElement(Y$.Item,{grow:!0},e.createElement(pJ,{checked:!0,styles:o},i)),e.createElement(pJ,{styles:Mte,ariaHidden:!0,onRenderIcon:()=>e.createElement(_Z,{iconName:"ChevronLeft"})}))},Jte=t=>{const{onFetchAvatarPersonaData:i,onFetchParticipantMenuItems:n,title:r,participantListProps:s,headingMoreButtonAriaLabel:a,onClickHeadingMoreButton:o,headingMoreButtonMenuProps:l,pinnedParticipants:c}=t,d=g$(),u=qK(),h=s.totalParticipantCount,g=u$("text-tooltip"),p=(0,e.useMemo)((()=>({root:{h2:{color:u.palette.neutralSecondary,margin:t.isMobile?"0.5rem 1rem":"0.5rem",fontSize:u.fonts.smallPlus.fontSize,fontWeight:"normal"}}})),[u.palette.neutralSecondary,u.fonts.smallPlus.fontSize,t.isMobile]);return e.createElement(Y$,{className:Ete},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center"},e.createElement(Y$.Item,{grow:!0,styles:p,"aria-label":r,id:d},e.createElement("h2",null,Yte(null!=r?r:"",h))),(o||(null==l?void 0:l.items)&&l.items.length>0)&&e.createElement(Y$.Item,null,e.createElement(pJ,{"data-ui-id":"people-pane-header-more-button",ariaLabel:a,styles:Ate(u),iconProps:{iconName:"PeoplePaneMoreButton"},onClick:o?()=>o():void 0,menuProps:t.onClickHeadingMoreButton?void 0:t.headingMoreButtonMenuProps,onRenderMenuIcon:()=>null}))),e.createElement(Y$,{className:bte},e.createElement(s6,Object.assign({},s,{pinnedParticipants:c,styles:t.isMobile?Ite:_te,onRenderAvatar:(t,n)=>e.createElement(e.Fragment,null,e.createElement(h0,Object.assign({"data-ui-id":"chat-composite-participant-custom-avatar",userId:t},n,{hidePersonaDetails:!!(null==n?void 0:n.text),dataProvider:i,allowActiveBorder:!0})),(null==n?void 0:n.text)&&e.createElement("div",{style:wte},e.createElement(YZ,{content:null==n?void 0:n.text,id:g,overflowMode:xZ.Parent},e.createElement(oJ,{nowrap:!1,"aria-labelledby":g},null==n?void 0:n.text)))),onFetchParticipantMenuItems:n,showParticipantOverflowTooltip:!t.isMobile,participantAriaLabelledBy:d}))))},Yte=(e,t)=>PK(e,t?{numberOfPeople:`(${t})`}:{numberOfPeople:" "}),Qte={root:{position:"relative",maxHeight:"100%",overflow:"hidden"}},Zte={root:{overflowY:"scroll"}},Xte={root:{width:"100%",padding:"0.5rem 1rem"}},eie={root:{marginLeft:"0.5rem",marginRight:"0.5rem"}},tie={root:{height:"2.5rem",width:"100%"},textContainer:{display:"contents"}},iie=(e,t)=>({itemKey:e.key,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),t()},iconProps:e.iconProps,text:e.text,disabled:e.disabled}),nie={lineHeight:"0",width:"1.125rem"},rie=t=>{const{strings:i,isMobile:n,showDialpad:r,onDismissDialpad:s,onAddParticipant:a,alternateCallerId:o}=t,[l,c]=(0,e.useState)(""),d=qK(),u=()=>{c(""),s()},h=()=>{if(a){const e={phoneNumber:"+"+l.replace(/\D/g,"").replaceAll(" ","")};a(e,{alternateCallerId:{phoneNumber:o}}),u()}},g=(0,e.useMemo)((()=>(e=>({main:{borderRadius:e.effects.roundedCorner6,padding:"1rem"}}))(d)),[d]),p=(0,e.useMemo)((()=>((e,t)=>({root:{padding:0,marginLeft:0,marginRight:0,maxWidth:"100%"},textField:{root:{borderBottom:`1px solid ${t.palette.neutralTertiaryAlt}`},field:{backgroundColor:t.palette.white,fontSize:t.fonts.large.fontSize,padding:"0 0.5rem",textAlign:e?"center":"left",":active":{padding:"0 0.5rem"}}},deleteIcon:{root:{backgroundColor:t.palette.white}},digit:{color:t.palette.themeDarkAlt}}))(n,d)),[d,n]),m=(0,e.useMemo)((()=>(e=>({root:{fontWeight:e.fonts.medium.fontWeight,fontSize:e.fonts.medium.fontSize,width:"100%",height:"2.5rem",borderRadius:3,padding:"0.625rem"},textContainer:{display:"contents"}}))(d)),[d]),f=()=>e.createElement(e.Fragment,null,e.createElement(L6,{styles:p,onChange:c,longPressTrigger:n?"touch":"mouseAndTouch"}),e.createElement(mJ,{text:i.dialpadStartCallButtonLabel,onRenderIcon:()=>e.createElement(_Z,{iconName:"DialpadStartCall"}),onClick:h,styles:m,disabled:""===l}));return n?e.createElement(Y$,{"data-ui-id":"call-with-chat-composite-dialpad"},r&&e.createElement(Y$,{styles:pte()},e.createElement(j0,{onLightDismiss:u,disableMaxHeight:!0},e.createElement(Y$,{style:{padding:"1rem"}},f())))):e.createElement(e.Fragment,null,e.createElement(y3,{titleAriaId:i.dialpadModalAriaLabel,isOpen:r,onDismiss:u,isBlocking:!0,styles:g,"data-ui-id":"call-with-chat-composite-dialpad"},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center"},e.createElement(oJ,null,i.dialpadModalTitle),e.createElement(oK,{iconProps:{iconName:"Cancel"},ariaLabel:i.dialpadCloseModalButtonAriaLabel,onClick:u,style:{color:d.palette.black}})),e.createElement(Y$,{style:{overflow:"hidden"}},f())))},sie=t=>e.createElement($z,{styles:aie,target:`#${t.targetId}`,directionalHint:1,beakWidth:lie,gapSpace:cie,doNotLayer:t.doNotLayer},e.createElement(Y$,{horizontal:!0,styles:oie,tokens:{childrenGap:"0.375rem"}},e.createElement(hG,{iconName:"Checkmark",className:die}),e.createElement(oJ,null,t.text))),aie={root:{padding:"0.375rem 0.75rem 0.375rem 0.5rem",borderRadius:"0.25rem"},beakCurtain:{borderRadius:"0.25rem"},container:{zIndex:0}},oie={root:{display:"flex",alignItems:"center"}},lie=8,cie=2,die=dB({fontSize:18}),uie=t=>{var i,n;const r=qK(),{inviteLink:s,strings:a,mobileView:o,onAddParticipant:l,alternateCallerId:c,onCopyInviteLink:d,inviteLinkCopiedRecently:u}=t,[h,g]=(0,e.useState)(!1),[p,m]=(0,e.useState)(),f=(0,e.useMemo)((()=>(e=>({root:{borderRadius:e.effects.roundedCorner6}}))(r)),[r]),v=(0,e.useMemo)((()=>((e,t)=>({root:{minHeight:t?"3rem":"2.5rem",borderRadius:t?e.effects.roundedCorner6:e.effects.roundedCorner4,width:"100%"},textContainer:{display:"contents"}}))(r,o)),[o,r]),S=(0,e.useMemo)((()=>{const e={styles:f,items:[],useTargetWidth:!0,calloutProps:{preventDismissOnEvent:v0},onMenuOpened(e){m(void 0)}};return s&&e.items.push({key:"InviteLinkKey",text:a.copyInviteLinkButtonLabel,itemProps:{styles:v},iconProps:{iconName:"Link",style:nie},onClick:()=>{m(a.copyInviteLinkActionedAriaLabel),B8()(s),null==d||d()}}),c&&e.items.push({key:"DialpadKey",text:a.openDialpadButtonLabel,itemProps:{styles:v},iconProps:{iconName:"PeoplePaneOpenDialpad",style:nie},onClick:()=>g(!0),"data-ui-id":"call-dial-phone-number-button"}),e}),[f,s,c,a.copyInviteLinkButtonLabel,a.copyInviteLinkActionedAriaLabel,a.openDialpadButtonLabel,v,d]),y=()=>{g(!1)},[C,T]=(0,e.useState)([]),E=(0,e.useMemo)((()=>()=>{const e=S.items.map((e=>iie(e,(()=>T([])))));T(e)}),[S,T]),b=g$("callout-button");return o?e.createElement(Y$,null,e.createElement(J0,{ariaLive:"assertive",announcementString:p}),S.items.length>0&&e.createElement(Y$.Item,{styles:Xte},e.createElement(mJ,{autoFocus:!0,id:b,onClick:E,styles:v,onRenderIcon:()=>e.createElement(_Z,{iconName:"PeoplePaneAddPerson"}),text:a.peoplePaneAddPeopleButtonLabel,"data-ui-id":"call-add-people-button"}),u&&e.createElement(sie,{targetId:b,text:null!==(i=a.copyInviteLinkButtonActionedLabel)&&void 0!==i?i:"",doNotLayer:!0})),C.length>0&&e.createElement(Y$,{styles:pte(),"data-ui-id":"call-add-people-dropdown"},e.createElement(K0,{disableMaxHeight:!0,onLightDismiss:()=>T([]),items:C})),c&&e.createElement(rie,{isMobile:!0,strings:a,showDialpad:h,onDismissDialpad:y,onAddParticipant:l,alternateCallerId:c})):e.createElement(e.Fragment,null,e.createElement(Y$,null,e.createElement(J0,{ariaLive:"assertive",announcementString:p}),c&&e.createElement(rie,{isMobile:!1,strings:a,showDialpad:h,onDismissDialpad:y,onAddParticipant:l,alternateCallerId:c}),S.items.length>0&&e.createElement(Y$,{styles:eie},e.createElement(pJ,{id:b,onRenderIcon:()=>e.createElement(_Z,{iconName:"PeoplePaneAddPerson"}),text:a.peoplePaneAddPeopleButtonLabel,menuProps:S,styles:v,"data-ui-id":"call-add-people-button"}),u&&e.createElement(sie,{targetId:b,text:null!==(n=a.copyInviteLinkButtonActionedLabel)&&void 0!==n?n:""}))))},hie=t=>{const{inviteLink:i,mobileView:n,strings:r,participantList:s}=t,a=qK(),[o,l]=(0,e.useState)(""),c=((0,e.useMemo)((()=>ZH(tie,((e,t)=>({root:{minHeight:e?"3rem":"2.5rem",borderRadius:e?t.effects.roundedCorner6:t.effects.roundedCorner4}}))(n,a))),[n,a]),(0,e.useCallback)((()=>{l(r.copyInviteLinkActionedAriaLabel),setTimeout((()=>{l("")}),3e3)}),[r.copyInviteLinkActionedAriaLabel]),(0,e.useRef)(void 0)),[d,u]=(0,e.useState)(!1),h=(0,e.useCallback)((()=>{u(!0),c.current=Date.now(),setTimeout((()=>{c.current&&Date.now()-c.current>=2e3&&u(!1)}),2e3)}),[u,c]);return g$("callout-button"),n?e.createElement(uie,{strings:Object.assign({},r),mobileView:n,inviteLink:i,onAddParticipant:t.onAddParticipant,alternateCallerId:t.alternateCallerId,onCopyInviteLink:h,inviteLinkCopiedRecently:d}):e.createElement(Y$,{tokens:Tte,"data-ui-id":"people-pane-content",verticalFill:!0},e.createElement(uie,{strings:r,mobileView:n,inviteLink:i,onAddParticipant:t.onAddParticipant,alternateCallerId:t.alternateCallerId,onCopyInviteLink:h,inviteLinkCopiedRecently:d}),e.createElement(Y$.Item,{grow:!0,styles:{root:{overflowY:"hidden"}}},s))};var gie=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const pie=t=>{const{inviteLink:i,onFetchParticipantMenuItems:n,setDrawerMenuItems:r,setParticipantActioned:s,participantListHeadingMoreButtonProps:a}=t,o=LZ(),l=PJ(),c=l.strings.call,d=(0,e.useCallback)((e=>gie(void 0,void 0,void 0,(function*(){yield o.removeParticipant(e)}))),[o]),u=(0,e.useCallback)(((e,t)=>gie(void 0,void 0,void 0,(function*(){yield o.addParticipant(e,t)}))),[o]),h=Y7(s6),g=fie(t.role),p=(0,e.useMemo)((()=>e=>{if(e){null==s||s(e.userId);let t=mie(e,c,g&&e.isRemovable?h.onRemoveParticipant:void 0,h.myUserId);n&&(t=n(e.userId,h.myUserId,t));const i=t.map((e=>iie(e,(()=>r([])))));r(i)}}),[c,h.onRemoveParticipant,h.myUserId,g,n,r,s]),m=(0,e.useMemo)((()=>{const e=null==a?void 0:a.items.map((e=>iie(e,(()=>r([])))));return e&&e.length>0?()=>r(e):void 0}),[null==a?void 0:a.items,r]),f=(0,e.useMemo)((()=>Object.assign(Object.assign({},h),{onRemoveParticipant:t.mobileView?void 0:e=>gie(void 0,void 0,void 0,(function*(){return d(e)})),onParticipantClick:t.mobileView?p:void 0})),[h,t.mobileView,p,d]),v=e.createElement(Jte,{isMobile:t.mobileView,participantListProps:f,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,onFetchParticipantMenuItems:t.mobileView?void 0:n,title:c.peoplePaneSubTitle,headingMoreButtonAriaLabel:l.strings.call.peoplePaneMoreButtonAriaLabel,onClickHeadingMoreButton:t.mobileView?m:void 0,headingMoreButtonMenuProps:t.participantListHeadingMoreButtonProps,pinnedParticipants:t.pinnedParticipants});return t.mobileView?e.createElement(Y$,{verticalFill:!0,styles:Qte,tokens:Tte,"data-ui-id":"people-pane-content"},e.createElement(Y$.Item,{grow:!0,styles:Zte},v),e.createElement(hie,{inviteLink:i,mobileView:t.mobileView,participantList:v,strings:c,onAddParticipant:u,alternateCallerId:t.alternateCallerId})):e.createElement(hie,{inviteLink:i,mobileView:t.mobileView,participantList:v,strings:c,onAddParticipant:u,alternateCallerId:t.alternateCallerId})},mie=(e,t,i,n)=>{const r=[];return i&&(null==e?void 0:e.userId)!==n&&r.push({key:"remove",text:t.removeMenuLabel,role:"menuitem",onClick:()=>{(null==e?void 0:e.userId)&&(null==i||i(null==e?void 0:e.userId))},iconProps:{iconName:"ContextMenuRemoveParticipant",styles:{root:{lineHeight:0}}},"data-ui-id":"participant-list-remove-participant-button"}),r},fie=e=>"Presenter"===e||"Unknown"===e||void 0===e,vie="people",Sie={childrenGap:"0.5rem"},yie={root:{position:"relative",maxHeight:"100%",overflow:"hidden"}},Cie=dB({fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28)}),Tie=dB({paddingBottom:vJ(20)}),Eie=dB({fontSize:vJ(14),lineHeight:vJ(40)}),bie=dB({fontSize:vJ(14),lineHeight:vJ(40),fontWeight:DV.semibold}),_ie=e=>dB({background:`${e.palette.themeLighter}`,height:vJ(36),width:vJ(36),marginRight:vJ(12),borderRadius:vJ(18)}),Iie=dB({padding:"0.5rem 1rem"}),wie=dB({minWidth:vJ(150),textAlign:"right"}),Aie=e=>dB({padding:vJ(8),color:`${e.palette.themePrimary}`,zIndex:2}),Pie=e=>dB({background:`${e.palette.themeLighter}`,width:vJ(2),position:"relative",left:vJ(19),top:vJ(20),zIndex:1}),Rie=t=>{const{conferencePhoneInfoList:i}=t,n=qK(),r=PJ().component.strings.meetingConferencePhoneInfo;return t.mobileView?e.createElement(Y$,{verticalFill:!0,styles:yie,tokens:Sie,"data-ui-id":"phone-info-pane-content"},(void 0===i||0===i.length)&&e.createElement(Y$,{horizontal:!0},e.createElement(oJ,{className:bie},r.meetingConferencePhoneInfoModalNoPhoneAvailable)),i&&i[0]&&e.createElement(Y$,null,e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",className:Iie},e.createElement(Y$.Item,null,e.createElement(Y$,{horizontal:!0,className:wie},e.createElement(Y$.Item,{className:_ie(n)},e.createElement(Y$,{verticalAlign:"center",horizontalAlign:"center"},e.createElement(mG,{iconName:"JoinByPhoneDialStepIcon",className:Aie(n)}))),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},r.meetingConferencePhoneInfoModalDialIn)))),e.createElement(Y$.Item,{className:wie},i.map(((t,i)=>e.createElement(Y$.Item,{key:i},e.createElement(hJ,{className:bie,href:Ree(t)},A6(t.phoneNumber,!0)),e.createElement(oJ,{className:bie}," ",t.isTollFree?r.meetingConferencePhoneInfoModalTollFree:r.meetingConferencePhoneInfoModalToll),e.createElement("br",null),e.createElement(oJ,{className:bie}," ",Mee(t,r))))))),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:Iie},e.createElement(Y$.Item,null,e.createElement(Y$,{horizontal:!0},e.createElement(Y$.Item,{className:_ie(n)},e.createElement(mG,{iconName:"JoinByPhoneConferenceIdIcon",className:Aie(n)})),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},r.meetingConferencePhoneInfoModalMeetingId)))),e.createElement(oJ,{className:bie},i[0].conferenceId,"#")),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:Iie},e.createElement(Y$,{horizontal:!0},e.createElement(Y$.Item,{className:_ie(n)},e.createElement(mG,{iconName:"JoinByPhoneWaitToBeAdmittedIcon",className:Aie(n)})),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},r.meetingConferencePhoneInfoModalWait)))))):e.createElement(Y$,{verticalFill:!0,styles:yie,tokens:Sie,"data-ui-id":"phone-info-pane-content"})},Mie="Meeting Phone Info",Die="3.375rem",kie="4.83rem",Oie={root:{visibility:"hidden",height:Die,width:kie,border:"2px"}},Nie=t=>{var i,n,r,s,a,o,l,c,d;const u=qK(),h=null!==(i=t.isSelected)&&void 0!==i&&i,g=null!==(n=t.disabled)&&void 0!==n&&n,p=null===(r=t.backgroundProps)||void 0===r?void 0:r.url,m=dB({height:"1.25rem"},null===(s=t.styles)||void 0===s?void 0:s.iconContainer),f=dB({height:"1.25rem",maxWidth:"4.5rem",overflow:"hidden"},null===(a=t.styles)||void 0===a?void 0:a.textContainer),v=(0,e.useCallback)((()=>{return{root:{background:(e={theme:u,isSelected:h,disabled:g,backgroundImage:p}).disabled?e.theme.palette.neutralQuaternaryAlt:void 0,backgroundImage:e.backgroundImage?`url(${e.backgroundImage})`:void 0,backgroundPosition:"center",backgroundSize:"cover",borderRadius:"0.25rem",color:e.theme.palette.neutralPrimary,cursor:e.disabled?"default":"pointer",height:Die,width:kie,outlineOffset:"-1px",outline:e.isSelected?`2px solid ${e.theme.palette.themePrimary}`:`1px solid ${e.theme.palette.neutralQuaternaryAlt}`,":hover":{boxSizing:"border-box",width:"4.85rem",height:"3.373rem",outlineOffset:"-1px",outline:e.disabled&&!e.isSelected?`1px solid ${e.theme.palette.neutralQuaternaryAlt}`:`2px solid ${e.theme.palette.themePrimary}`},padding:"0.5rem"}};var e}),[p,g,h,u]);return e.createElement(YZ,Object.assign({},t.tooltipProps),e.createElement(Y$,{key:t.itemKey,className:dB(null===(o=t.styles)||void 0===o?void 0:o.root),verticalAlign:"center",horizontalAlign:"center","data-ui-id":"video-effects-item"},e.createElement(pJ,{styles:v(),onClick:g?void 0:()=>{var e;return null===(e=t.onSelect)||void 0===e?void 0:e.call(t,t.itemKey)},componentRef:t.componentRef,ariaLabel:null!==(d=null!==(l=t.ariaLabel)&&void 0!==l?l:`${t.title}, ${null===(c=t.tooltipProps)||void 0===c?void 0:c.content}`)&&void 0!==d?d:t.itemKey,"aria-disabled":t.disabled,role:"radio","aria-checked":h},e.createElement(Y$,{horizontalAlign:"center",className:dB({width:"100%"})},t.iconProps&&e.createElement(Y$.Item,{className:m},e.createElement(mG,Object.assign({},t.iconProps))),t.title&&e.createElement(Y$.Item,{className:f},e.createElement(oJ,{variant:"small",styles:{root:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}},t.title))))))},Lie=t=>{var i,n,r,s,a;const[o,l]=e.useState(t.defaultSelectedEffectKey),c=null!==(i=t.selectedEffectKey)&&void 0!==i?i:o,d=t.options.map((e=>Object.assign({isSelected:e.itemKey===c,onSelect:()=>(e=>{var i;l(e),null===(i=t.onChange)||void 0===i||i.call(t,e)})(e.itemKey)},e))),u=null!==(n=t.itemsPerRow)&&void 0!==n?n:3,h="wrap"===u?[d]:function(e,t){const i=[];let n=[];for(const r of e)n.push(r),n.length===t&&(i.push(n),n=[]);return n.length>0&&i.push(n),i}(d,u),g="wrap"===u?0:u-(null!==(s=null===(r=h[h.length-1])||void 0===r?void 0:r.length)&&void 0!==s?s:0),p=g$("effects-radio-label");return e.createElement(iq,null,e.createElement(Y$,{tokens:{childrenGap:"0.5rem"},role:"radiogroup","aria-labelledby":p},e.createElement(M5,{id:p,className:dB(null===(a=t.styles)||void 0===a?void 0:a.label)},t.label),h.map(((i,n)=>{var r;return e.createElement(Y$,{className:dB(null===(r=t.styles)||void 0===r?void 0:r.rowRoot),wrap:"wrap"===t.itemsPerRow,horizontal:!0,key:n,tokens:{childrenGap:"0.5rem"},"data-ui-id":"video-effects-picker-row"},i.map(((i,r)=>0===r&&0===n?e.createElement(Nie,Object.assign({},i,{itemKey:i.itemKey,key:i.itemKey,componentRef:t.componentRef})):e.createElement(Nie,Object.assign({},i,{itemKey:i.itemKey,key:i.itemKey})))),g>0&&n===h.length-1&&Array.from({length:g}).map(((t,i)=>e.createElement(Y$,{key:i,styles:Oie,"data-ui-id":"video-effects-hidden-item"}))))}))))},xie=G6([e=>e.selectedVideoBackgroundEffect],(e=>!e||"blur"!==e.effectName&&"none"!==e.effectName?e&&"replacement"===e.effectName?null==e?void 0:e.key:"none":e.effectName)),Fie=G6([Q9,p7,E7],((e,t,i)=>{var n,r;let s;return oL(e.callStatus)?s=null==i?void 0:i.find((e=>"Video"===e.mediaStreamType)):cL(t)&&(s=t.unparentedViews[0]),{isAvailable:!!s,isMirrored:null===(n=null==s?void 0:s.view)||void 0===n?void 0:n.isMirrored,renderElement:null===(r=null==s?void 0:s.view)||void 0===r?void 0:r.target,activeVideoEffects:null==s?void 0:s.videoEffects}}));const Uie=t=>{var i;const{onDismissError:n,activeVideoEffectError:r,activeVideoEffectChange:s}=t,a=PJ(),o=LZ(),l=a.strings.call,c=null===(i=u7(Fie).activeVideoEffects)||void 0===i?void 0:i.activeEffects,d=(0,e.useMemo)((()=>{const e=[{itemKey:"none",iconProps:{iconName:"RemoveVideoBackgroundEffect"},title:l.removeBackgroundEffectButtonLabel,tooltipProps:{content:l.removeBackgroundTooltip}},{itemKey:"blur",iconProps:{iconName:"BlurVideoBackground"},title:l.blurBackgroundEffectButtonLabel,tooltipProps:{content:l.blurBackgroundTooltip}}];return t.backgroundImages&&t.backgroundImages.forEach((t=>{var i;e.push({itemKey:t.key,backgroundProps:{url:t.url},tooltipProps:{content:null!==(i=t.tooltipText)&&void 0!==i?i:""}})})),e}),[l.removeBackgroundEffectButtonLabel,l.removeBackgroundTooltip,l.blurBackgroundEffectButtonLabel,l.blurBackgroundTooltip,t.backgroundImages]),u=(0,e.useCallback)((e=>{return t=void 0,i=void 0,r=function*(){if("blur"===e){const t={effectName:e};s({type:"blur",timestamp:new Date(Date.now())}),yield o.startVideoBackgroundEffect(t),o.updateSelectedVideoBackgroundEffect(t)}else if("none"===e){const t={effectName:e};yield o.stopVideoBackgroundEffects(),o.updateSelectedVideoBackgroundEffect(t)}else{const t=d.find((t=>t.itemKey===e));if(t&&t.backgroundProps){const i={effectName:"replacement",key:e,backgroundImageUrl:t.backgroundProps.url};s({type:"replacement",timestamp:new Date(Date.now())}),yield o.startVideoBackgroundEffect(i),o.updateSelectedVideoBackgroundEffect(i)}}},new((n=void 0)||(n=Promise))((function(e,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(a,o)}l((r=r.apply(t,i||[])).next())}));var t,i,n,r}),[o,s,d]);if(r&&c&&0===c.length){const e={effectName:"none"};o.updateSelectedVideoBackgroundEffect(e)}return Bie(n,t.updateFocusHandle,r,d,u)},Bie=(t,i,n,r,s)=>{const a=u7(xie),o=u7(Fie).isAvailable,l=!o&&"none"!==a,c=PJ();return e.createElement(Y$,{tokens:{childrenGap:"0.75rem"},className:dB({paddingLeft:"0.5rem"})},n&&o&&e.createElement(bK,{messageBarType:eK.error,onDismiss:()=>t(n),role:"alert","aria-live":"assertive"},c.strings.call.unableToStartVideoEffect),l&&e.createElement(bK,{messageBarType:eK.warning,role:"alert","aria-live":"assertive"},c.strings.call.cameraOffBackgroundEffectWarningText),e.createElement(Lie,{label:c.strings.call.videoEffectsPaneBackgroundSelectionTitle,styles:Vie,options:null!=r?r:[],onChange:s,selectedEffectKey:a,componentRef:i}))},Vie={label:{fontSize:"0.75rem",lineHeight:"0.5rem",fontWeight:"400"}},Hie="videoeffects",$ie=(t,i,n,r,s)=>{const a=(0,e.useCallback)((()=>{var e;t(void 0),null===(e=null==s?void 0:s.current)||void 0===e||e.focus()}),[s,t]),o=PJ(),l=(0,e.useCallback)((()=>{var t,n;return e.createElement(Wte,{onClose:a,headingText:o.strings.call.videoEffectsPaneTitle,dismissSidePaneButtonAriaLabel:null!==(n=null!==(t=o.strings.call.dismissSidePaneButtonLabel)&&void 0!==t?t:o.strings.callWithChat.dismissSidePaneButtonLabel)&&void 0!==n?n:"Close",mobileView:i})}),[a,o.strings,i]),c=n.find((e=>"unableToStartVideoEffect"===e.type)),d=(0,e.useMemo)((()=>(0,e.createRef)()),[]),u=u7(j7),h=(0,e.useCallback)((()=>e.createElement(Uie,{onDismissError:r,activeVideoEffectError:c,activeVideoEffectChange:()=>{c&&(null==r||r(c))},updateFocusHandle:d,backgroundImages:u})),[c,r,d,u]),g=(0,e.useMemo)((()=>({headerRenderer:l,contentRenderer:h,id:Hie})),[h,l]),p=(0,e.useCallback)((()=>{t(g),setTimeout((()=>{var e;return null===(e=d.current)||void 0===e?void 0:e.focus()}),0)}),[g,t,d]),m=Vte(Hie);(0,e.useEffect)((()=>{m&&p()}),[m,p]);const f=(0,e.useCallback)((()=>{m?a():p()}),[a,m,p]);return{openVideoEffectsPane:p,closeVideoEffectsPane:a,toggleVideoEffectsPane:f,isVideoEffectsPaneOpen:m}},jie=t=>{const i=aJ().effects.elevation8;return e.createElement(qie,{styles:zie(t.orientation,i)},t.children)},Gie=t=>e.createElement(qie,{styles:Wie(t.orientation)},t.children),qie=t=>e.createElement(Y$,{styles:t.styles},t.children),zie=SB(((e,t)=>({root:{borderRadius:"0.25rem",height:"landscape"===e?"5.5rem":"8rem",width:"landscape"===e?"8rem":"5.5rem",boxShadow:t,overflow:"hidden"}}))),Wie=SB((e=>({root:{borderRadius:"0.25rem",height:"landscape"===e?"1.625rem":"2rem",width:"landscape"===e?"2rem":"1.625rem",overflow:"hidden"}}))),Kie=t=>e.createElement(Jie,{onClick:t.onClick,primaryView:e.createElement(jie,Object.assign({},t.primaryTile)),secondaryView:t.secondaryTile&&e.createElement(Gie,Object.assign({},t.secondaryTile)),ariaLabel:t.strings.rootAriaLabel}),Jie=t=>e.createElement("aside",{style:Yie,onClick:t.onClick,onKeyPress:e=>t.onClick&&b0(e,t.onClick),"aria-label":t.ariaLabel,tabIndex:t.onClick?0:-1,"data-ui-id":"picture-in-picture-in-picture-root"},t.primaryView,e.createElement("div",{style:Qie},t.secondaryView)),Yie={display:"flex",width:"min-content",position:"relative",cursor:"pointer"},Qie={position:"absolute",bottom:"0.125rem",right:"0.125rem"},Zie=t=>{var i,n;const{localParticipant:r,remoteParticipant:s,onCreateLocalStreamView:a,onDisposeLocalStreamView:o,onCreateRemoteStreamView:l,onDisposeRemoteStreamView:c}=t,d=(0,e.useMemo)((()=>{var e,t;return{onCreateLocalStreamView:a,onDisposeLocalStreamView:o,localVideoViewOptions:Xie,displayName:r.displayName,showLabel:!1,showMuteIndicator:!1,showCameraSwitcherInLocalPreview:!1,isAvailable:null===(e=r.videoStream)||void 0===e?void 0:e.isAvailable,renderElement:null===(t=r.videoStream)||void 0===t?void 0:t.renderElement,raisedHand:r.raisedHand}}),[r.displayName,null===(i=r.videoStream)||void 0===i?void 0:i.isAvailable,null===(n=r.videoStream)||void 0===n?void 0:n.renderElement,a,o,r.raisedHand]),u=(0,e.useMemo)((()=>{var e,t,i;return s?{remoteParticipant:s,onCreateRemoteStreamView:l,onDisposeRemoteStreamView:c,remoteVideoViewOptions:ene,displayName:null==s?void 0:s.displayName,showLabel:!1,showMuteIndicator:!1,isAvailable:null===(e=s.videoStream)||void 0===e?void 0:e.isAvailable,isReceiving:null===(t=s.videoStream)||void 0===t?void 0:t.isReceiving,renderElement:null===(i=s.videoStream)||void 0===i?void 0:i.renderElement,userId:s.userId,key:s.userId}:void 0}),[s,l,c]),h=PJ(),g=h.strings.callWithChat.pictureInPictureTileAriaLabel,p=(0,e.useMemo)((()=>({rootAriaLabel:g})),[g]),m=(0,e.useMemo)((()=>({children:u?e.createElement(L1,Object.assign({},u,{strings:h.component.strings.videoGallery,onLongTouch:()=>{}})):e.createElement(Q1,Object.assign({},d)),orientation:"portrait"})),[d,u,h.component.strings.videoGallery]),f=(0,e.useMemo)((()=>u?{children:e.createElement(Q1,Object.assign({},d,{personaMinSize:20})),orientation:"portrait"}:void 0),[d,u]);return e.createElement(Kie,{onClick:t.onClick,strings:p,primaryTile:m,secondaryTile:f})},Xie={scalingMode:"Crop",isMirrored:!0},ene={scalingMode:"Crop",isMirrored:!1},tne=G6([_7,e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.dominantSpeakers}],((e,t)=>{const i=b8(t);return e&&Object.keys(e).length>0?ine(e,null!=i?i:[]):void 0})),ine=(e,t)=>{let i=t[0];const n=Object.keys(e);return i&&n.includes(i)||(i=n[0]),i?e[i]:void 0},nne=G6([_7,e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.spotlight)||void 0===i?void 0:i.spotlightedParticipants}],((e,t)=>{const i=t?t.map((e=>iL(e.identifier))):[];return e?rne(e,i):void 0})),rne=(e,t)=>{const i=Object.keys(e),n=t.filter((e=>i.includes(e)));return n[0]?e[n[0]]:void 0},sne=G6([e=>e.displayName,tne,Fie,e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.raiseHand.localParticipantRaisedHand},nne],((e,t,i,n,r)=>{let s=t;return r&&(s=r),{localParticipant:{displayName:e,videoStream:i,raisedHand:n},remoteParticipant:s?_8(uL([s]))[0]:void 0}})),ane={moveMenuItemText:"Move",closeMenuItemText:"Close",menu:GW,keepInBounds:!0},one=t=>{var i;const n=t.hidden?mee:pee,r=u7(S7),s=PJ(),a=u7(sne),[o,l]=(0,e.useState)(null),c=(0,e.useCallback)((e=>{var i;if(o&&o[0]&&1===o.length&&e.changedTouches[0]&&1===e.changedTouches.length){const n=o[0],r=e.changedTouches[0];Math.abs(n.clientX-r.clientX)<10&&Math.abs(n.clientY-r.clientY)<10&&(null===(i=t.onDismissSidePane)||void 0===i||i.call(t))}}),[t,o]),d=(0,e.useCallback)((e=>{l(e.touches)}),[]),u=(0,e.useCallback)((e=>{var i;"Enter"!==e.key&&" "!==e.key||null===(i=t.onDismissSidePane)||void 0===i||i.call(t)}),[t]),h=K7(),g=a.remoteParticipant,p=(0,e.useMemo)((()=>{var i,n,o,l;return"Consumer"===r&&(null==g?void 0:g.userId)?e.createElement(Y$,{tabIndex:0,"aria-label":null!==(n=null===(i=t.strings)||void 0===i?void 0:i.dismissModalAriaLabel)&&void 0!==n?n:"",onKeyDown:u},e.createElement(L1,Object.assign({strings:s.component.strings.videoGallery},g,{remoteParticipant:g}))):e.createElement(Y$,{tabIndex:0,"aria-label":null!==(l=null===(o=t.strings)||void 0===o?void 0:o.dismissModalAriaLabel)&&void 0!==l?l:"",onKeyDown:u},e.createElement(Zie,Object.assign({},a,h,{remoteParticipant:g})))}),[r,u,a,t,h,s.component.strings.videoGallery,g]);if("Consumer"===r&&!g)return null;const m=ZH(fee,null===(i=t.styles)||void 0===i?void 0:i.modal);return e.createElement(Y$,{styles:n},e.createElement(Y$,{onTouchStart:d,onTouchEnd:c},e.createElement(c5,{isOpen:!0,isModeless:!0,dragOptions:ane,styles:m,layerProps:{hostId:t.modalLayerHostId},minDragPosition:t.minDragPosition,maxDragPosition:t.maxDragPosition},!t.hidden&&p)))},lne=t=>{const i=PJ();return e.createElement(Y$,{"data-ui-id":"capabilities-changed-notification-bar-stack"},t.capabilitiesChangedNotifications.map((n=>{const r=cne(n,i.strings.call.capabilityChangedNotification);if(!r)return null;const s=dne(n);return e.createElement(bK,{key:n.capabilityName,styles:une,messageBarType:eK.warning,dismissIconProps:{iconName:"ErrorBarClear"},onDismiss:()=>t.onDismissNotification(n),messageBarIconProps:s},r)})))},cne=(e,t)=>{var i,n,r,s;switch(e.capabilityName){case"shareScreen":if(e.isPresent&&"RoleChanged"===e.changedReason&&"Presenter"===e.role)return null===(i=null==t?void 0:t.shareScreen)||void 0===i?void 0:i.grantedDueToRoleChangeToPresenter;if(!e.isPresent&&"RoleChanged"===e.changedReason&&"Attendee"===e.role)return null===(n=null==t?void 0:t.shareScreen)||void 0===n?void 0:n.lostDueToRoleChangeToAttendee;break;case"viewAttendeeNames":if(!e.isPresent&&"MeetingOptionOrOrganizerPolicyChanged"===e.changedReason&&"Attendee"===e.role)return null===(r=null==t?void 0:t.hideAttendeeNames)||void 0===r?void 0:r.hideAttendeeNameAttendee;if(!e.isPresent&&"MeetingOptionOrOrganizerPolicyChanged"===e.changedReason&&"Presenter"===e.role)return null===(s=null==t?void 0:t.hideAttendeeNames)||void 0===s?void 0:s.hideAttendeeNamePresenter}},dne=e=>{let t;switch(e.capabilityName){case"turnVideoOn":t=e.isPresent?"ControlButtonCameraOn":"ControlButtonCameraProhibited";break;case"unmuteMic":t=e.isPresent?"ControlButtonMicOn":"ControlButtonMicProhibited";break;default:return}return{iconName:t,styles:{root:{"> *":{height:"1rem",width:"1rem"}}}}},une={innerText:{alignSelf:"center"},icon:{height:0},content:{lineHeight:"inherit"},dismissal:{height:0,paddingTop:"0.8rem"}};var hne=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const gne=(t,i,n,r)=>{const s=PJ().strings.call;return(0,e.useMemo)((()=>n&&r?{onStartLocalSpotlightWithPrompt:t?pne(t,n,r,s):void 0,onStopLocalSpotlightWithPrompt:i?mne(i,n,r,s):void 0}:{onStartLocalSpotlightWithPrompt:t,onStopLocalSpotlightWithPrompt:i}),[t,i,n,r,s])},pne=(e,t,i,n)=>()=>hne(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.startSpotlightHeading,text:n.spotlightPrompt.startSpotlightOnSelfText,confirmButtonLabel:n.spotlightPrompt.startSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.startSpotlightCancelButtonLabel,closeButtonLabel:n.spotlightPrompt.closeSpotlightPromptButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),mne=(e,t,i,n)=>()=>hne(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.stopSpotlightOnSelfHeading,text:n.spotlightPrompt.stopSpotlightOnSelfText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightOnSelfConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),fne=(t,i,n,r)=>{const s=PJ().strings.call;return(0,e.useMemo)((()=>n&&r?{onStartRemoteSpotlightWithPrompt:t?vne(t,n,r,s):void 0,onStopRemoteSpotlightWithPrompt:i?Sne(i,n,r,s):void 0}:{onStartRemoteSpotlightWithPrompt:t,onStopRemoteSpotlightWithPrompt:i}),[t,i,n,r,s])},vne=(e,t,i,n)=>r=>hne(void 0,void 0,void 0,(function*(){r.length>1&&e(r),i({heading:n.spotlightPrompt.startSpotlightHeading,text:n.spotlightPrompt.startSpotlightText,confirmButtonLabel:n.spotlightPrompt.startSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.startSpotlightCancelButtonLabel,closeButtonLabel:n.spotlightPrompt.closeSpotlightPromptButtonLabel,onConfirm:()=>{e(r),t(!1)},onCancel:()=>t(!1)}),t(!0)})),Sne=(e,t,i,n)=>r=>hne(void 0,void 0,void 0,(function*(){r.length>1&&e(r),i({heading:n.spotlightPrompt.stopSpotlightHeading,text:n.spotlightPrompt.stopSpotlightText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,closeButtonLabel:n.spotlightPrompt.closeSpotlightPromptButtonLabel,onConfirm:()=>{e(r),t(!1)},onCancel:()=>t(!1)}),t(!0)})),yne=(e,t,i,n)=>()=>hne(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.stopAllSpotlightHeading,text:n.spotlightPrompt.stopAllSpotlightText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,closeButtonLabel:n.spotlightPrompt.closeSpotlightPromptButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),Cne=t=>{var i,n;const r=t.strings,s=qK();return e.createElement(Y$,{horizontalAlign:"center"},e.createElement(Y$,{"data-ui-id":"banner",className:Ene(s)},e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between"},e.createElement(Y$,{horizontal:!0},(null===(i=t.iconProps)||void 0===i?void 0:i.iconName)&&e.createElement(mG,Object.assign({className:bne,iconName:null===(n=t.iconProps)||void 0===n?void 0:n.iconName},t.iconProps)),e.createElement(oJ,{className:Tne},null==r?void 0:r.title)),t.primaryButton?e.createElement(mJ,{text:null==r?void 0:r.primaryButtonLabel,ariaLabel:null==r?void 0:r.primaryButtonLabel,onClick:t.onClickButton}):e.createElement(pJ,{text:null==r?void 0:r.primaryButtonLabel,ariaLabel:null==r?void 0:r.primaryButtonLabel,onClick:t.onClickButton}))))},Tne=dB({fontWeight:400,fontSize:vJ(14),lineHeight:vJ(16),alignSelf:"center"}),Ene=e=>dB({boxShadow:e.effects.elevation8,width:"20rem",padding:"0.75rem",borderRadius:"0.25rem",position:"relative",backgroundColor:e.palette.white}),bne=dB({fontSize:"1.25rem",alignSelf:"center",marginRight:"0.5rem",svg:{width:"1.25rem",height:"1.25rem"}}),_ne=t=>{const{locale:i,adapter:n}=t,r=u7(k7),s=u7(O7),a=u7(L7);return!r||"open"!==r.state||s||a.assignedBreakoutRoomOpened?s&&!0!==s.disableReturnToMainMeeting?e.createElement(Y$,{styles:F9},e.createElement(Cne,{strings:{title:i.strings.call.returnFromBreakoutRoomBannerTitle,primaryButtonLabel:i.strings.call.returnFromBreakoutRoomBannerButtonLabel},onClickButton:()=>n.returnFromBreakoutRoom(),iconProps:{iconName:"NotificationBarBreakoutRoomClosingSoon"}})):null:e.createElement(Y$,{styles:F9},e.createElement(Cne,{strings:{title:r.displayName?i.strings.call.joinBreakoutRoomBannerTitle.replace("{roomName}",r.displayName):i.strings.call.joinBreakoutRoomBannerTitle,primaryButtonLabel:i.strings.call.joinBreakoutRoomBannerButtonLabel},onClickButton:()=>r.join(),iconProps:{iconName:"NotificationBarBreakoutRoomPromptJoin"},primaryButton:!0}))},Ine=t=>{var i,n,r,s,a,o,l,c,d,u,h,g,p;const m=(0,e.useMemo)((()=>t.mobileView?N9:O9),[t.mobileView]),f=aJ(),v=(0,e.useMemo)((()=>(e=>({root:{zIndex:1,width:"100%",background:e}}))(f.palette.neutralLighterAlt)),[f.palette.neutralLighterAlt]),S=(0,e.useRef)(null),y=(0,e.useRef)(null),C=(0,e.useRef)(null),T=(0,e.useRef)(null),E=y0(T),b=C0(T),_=lL(u7(Q9).callStatus),{updateSidePaneRenderer:I}=t,w="hold"===u7(y7),A=u7(m7),P=LZ(),[R,M]=(0,e.useState)(),D=u7(_7),[k,O]=(0,e.useState)([]);(0,e.useEffect)((()=>{R&&void 0===(null==D?void 0:D[R])&&O([])}),[R,D]);const N=u7(R7),L={updateSidePaneRenderer:I,mobileView:t.mobileView,conferencePhoneInfo:N},x=(0,e.useMemo)((()=>{var e;return{updateSidePaneRenderer:I,setDrawerMenuItems:O,inviteLink:t.callControlProps.callInvitationURL,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,onFetchParticipantMenuItems:null===(e=t.callControlProps)||void 0===e?void 0:e.onFetchParticipantMenuItems,mobileView:t.mobileView,peopleButtonRef:S,setParticipantActioned:M,sidePaneDismissButtonRef:C,chatButtonPresent:!!t.onCloseChatPane}}),[I,t.callControlProps.callInvitationURL,null===(i=t.callControlProps)||void 0===i?void 0:i.onFetchParticipantMenuItems,t.onFetchAvatarPersonaData,t.mobileView,S,M,C,t.onCloseChatPane]),F=PJ(),U=u7(S7),B=Y7(w5),V=K7(),{setPromptProps:H,setIsPromptOpen:$,hideSpotlightButtons:j}=t,{onStartLocalSpotlight:G,onStopLocalSpotlight:q,onStartRemoteSpotlight:z,onStopRemoteSpotlight:W,onMuteParticipant:K,spotlightedParticipants:J,maxParticipantsToSpotlight:Y,localParticipant:Q,onForbidAudio:Z,onPermitAudio:X,onForbidVideo:ee,onPermitVideo:te}=B,[ie,ne]=(0,e.useState)(!1),re=(0,e.useCallback)((()=>{ne(!ie)}),[ie]),{isMeetingPhoneInfoPaneOpen:se,openMeetingPhoneInfoPane:ae,closeMeetingPhoneInfoPane:oe}=(t=>{const{updateSidePaneRenderer:i,mobileView:n,conferencePhoneInfo:r}=t,s=(0,e.useCallback)((()=>{i(void 0)}),[i]),a=PJ().component.strings.meetingConferencePhoneInfo,o=PJ().strings.call,l=(0,e.useCallback)((()=>e.createElement(Wte,{onClose:s,headingText:a.meetingConferencePhoneInfoModalTitle,dismissSidePaneButtonAriaLabel:o.dismissSidePaneButtonLabel,mobileView:null!=n&&n})),[n,s,a,o]),c=(0,e.useCallback)((()=>e.createElement(Rie,{mobileView:n,conferencePhoneInfoList:r})),[n,r]),d=(0,e.useMemo)((()=>({headerRenderer:l,contentRenderer:c,id:Mie})),[c,l]),u=(0,e.useCallback)((()=>{i(d)}),[d,i]),h=Vte(Mie);return(0,e.useEffect)((()=>{h&&u()}),[h,u]),{openMeetingPhoneInfoPane:u,closeMeetingPhoneInfoPane:s,isMeetingPhoneInfoPaneOpen:h}})(Object.assign({},L)),le=(0,e.useCallback)((()=>{se?oe():ae()}),[oe,se,ae]),ce=(0,e.useCallback)((()=>{$e(!1),le()}),[le]),{pinnedParticipants:de,setPinnedParticipants:ue}=t,he=(0,e.useCallback)((e=>{de&&de.length>=4||de&&ue&&!de.includes(e)&&ue(de.concat(e))}),[de,ue]),ge=(0,e.useCallback)((e=>{de&&ue&&ue(de.filter((t=>t!==e)))}),[ue,de]),pe=(0,e.useMemo)((()=>({pinnedParticipants:de,onPinParticipant:he,onUnpinParticipant:ge,disablePinMenuItem:de&&de.length>=4})),[he,ge,de]),{onStartLocalSpotlightWithPrompt:me,onStopLocalSpotlightWithPrompt:fe}=gne(G,q,$,H),{onStartRemoteSpotlightWithPrompt:ve,onStopRemoteSpotlightWithPrompt:Se}=fne(z,W,$,H),ye=null==A?void 0:A.removeParticipantsSpotlight.isPresent,Ce=(0,e.useMemo)((()=>ye?()=>P.stopAllSpotlight():void 0),[ye,P]),{stopAllSpotlightWithPrompt:Te}=((t,i,n)=>{const r=PJ().strings.call;return(0,e.useMemo)((()=>i&&n?{stopAllSpotlightWithPrompt:t?yne(t,i,n,r):void 0}:{stopAllSpotlightWithPrompt:t}),[t,i,n,r])})(Ce,$,H),Ee=(0,e.useMemo)((()=>{var e,t;return{onMuteParticipant:(null===(e=null==A?void 0:A.muteOthers)||void 0===e?void 0:e.isPresent)||"Unknown"===U?K:void 0,onMuteAllRemoteParticipants:(null===(t=null==A?void 0:A.muteOthers)||void 0===t?void 0:t.isPresent)||"Unknown"===U?V.onMuteAllRemoteParticipants:void 0}}),[K,U,null==A?void 0:A.muteOthers,V.onMuteAllRemoteParticipants]),be=(0,e.useMemo)((()=>({spotlightedParticipantUserIds:J,onStartLocalSpotlight:j?void 0:me,onStopLocalSpotlight:j?void 0:fe,onStartRemoteSpotlight:j?void 0:ve,onStopRemoteSpotlight:j?void 0:Se,onStopAllSpotlight:j?void 0:Te,maxParticipantsToSpotlight:Y})),[j,Y,me,ve,fe,Se,Te,J]),_e=u7(z7),Ie=!!(null===(n=null==A?void 0:A.forbidOthersAudio)||void 0===n?void 0:n.isPresent),we=!!(null===(r=null==A?void 0:A.forbidOthersVideo)||void 0===r?void 0:r.isPresent),Ae=(0,e.useMemo)((()=>({onForbidAudio:Ie?Z:void 0,onPermitAudio:Ie?X:void 0,onForbidOthersAudio:Ie?V.onForbidOthersAudio:void 0,onPermitOthersAudio:Ie?V.onPermitOthersAudio:void 0,onForbidVideo:we?ee:void 0,onPermitVideo:we?te:void 0,onForbidOthersVideo:we?V.onForbidOthersVideo:void 0,onPermitOthersVideo:we?V.onPermitOthersVideo:void 0,meetingMediaAccess:_e})),[Ie,Z,X,V.onForbidOthersAudio,V.onPermitOthersAudio,V.onForbidOthersVideo,V.onPermitOthersVideo,we,ee,te,_e]),{isPeoplePaneOpen:Pe,openPeoplePane:Re,closePeoplePane:Me}=(t=>{const{updateSidePaneRenderer:i,inviteLink:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:s,setDrawerMenuItems:a,mobileView:o,peopleButtonRef:l,setParticipantActioned:c,spotlightedParticipantUserIds:d,onStartLocalSpotlight:u,onStopLocalSpotlight:h,onStartRemoteSpotlight:g,onStopRemoteSpotlight:p,onStopAllSpotlight:m,maxParticipantsToSpotlight:f,onMuteParticipant:v,pinnedParticipants:S,onPinParticipant:y,onUnpinParticipant:C,disablePinMenuItem:T,onMuteAllRemoteParticipants:E,onForbidAudio:b,onPermitAudio:_,onForbidOthersAudio:I,onPermitOthersAudio:w,onForbidVideo:A,onPermitVideo:P,onForbidOthersVideo:R,onPermitOthersVideo:M,meetingMediaAccess:D,sidePaneDismissButtonRef:k,chatButtonPresent:O}=t,N=(0,e.useCallback)((()=>{var e;i(void 0),null===(e=null==l?void 0:l.current)||void 0===e||e.focus()}),[l,i]),L=PJ().strings.call,x=u7(_7),[F,U]=(0,e.useState)(!1),B=(0,e.useMemo)((()=>({confirmButtonLabel:L.muteAllConfirmButtonLabel,heading:L.muteAllDialogTitle,text:L.muteAllDialogContent,cancelButtonLabel:L.muteAllCancelButtonLabel})),[L.muteAllConfirmButtonLabel,L.muteAllDialogTitle,L.muteAllDialogContent,L.muteAllCancelButtonLabel]),V=(0,e.useCallback)((()=>{E&&E(),U(!1)}),[E,U]),[H,$]=(0,e.useState)(!1),[j,G]=(0,e.useState)(!1),[q,z]=(0,e.useState)(!1),[W,K]=(0,e.useState)(!1),J=(0,e.useCallback)((()=>{I&&I(),$(!1)}),[I,$]),Y=(0,e.useCallback)((()=>{w&&w(),G(!1)}),[w,G]),Q=(0,e.useCallback)((()=>{R&&R(),z(!1)}),[R,z]),Z=(0,e.useCallback)((()=>{M&&M(),K(!1)}),[M,K]),X=(0,e.useMemo)((()=>{const e=[];if(E&&x){let t=!0;if(x)for(const e of Object.values(x))if(!e.isMuted){t=!1;break}e.push({"data-ui-id":"people-pane-mute-all-remote-participants",key:"muteAllRemoteParticipants",text:L.muteAllMenuLabel,iconProps:{iconName:"ContextualMenuMicMutedIcon",styles:{root:{lineHeight:0}}},onClick:()=>{U(!0)},ariaLabel:L.muteAllMenuLabel,disabled:t})}let t=!1;if(x)for(const e of Object.values(x))if(e.role&&"Attendee"===e.role){t=!0;break}const i=!D||D.isAudioPermitted,n=!D||D.isVideoPermitted;return I&&x&&t&&i&&e.push({"data-ui-id":"people-pane-forbid-all-attendees-audio",key:"forbidOthersAudio",text:L.forbidOthersAudioMenuLabel,iconProps:{iconName:"ControlButtonMicProhibited",styles:{root:{lineHeight:0}}},onClick:()=>{$(!0)},ariaLabel:L.forbidOthersAudioMenuLabel,disabled:!t}),w&&x&&t&&!i&&e.push({"data-ui-id":"people-pane-permit-all-attendees-audio",key:"permitOthersAudio",text:L.permitOthersAudioMenuLabel,iconProps:{iconName:"ControlButtonMicOn",styles:{root:{lineHeight:0}}},onClick:()=>{G(!0)},ariaLabel:L.permitOthersAudioMenuLabel,disabled:!t}),R&&x&&t&&n&&e.push({"data-ui-id":"people-pane-forbid-all-attendees-video",key:"forbidOthersVideo",text:L.forbidOthersVideoMenuLabel,iconProps:{iconName:"ControlButtonCameraProhibitedSmall",styles:{root:{lineHeight:0}}},onClick:()=>{z(!0)},ariaLabel:L.forbidOthersVideoMenuLabel,disabled:!t}),M&&x&&t&&!n&&e.push({"data-ui-id":"people-pane-permit-all-attendees-video",key:"permitOthersVideo",text:L.permitOthersVideoMenuLabel,iconProps:{iconName:"ControlButtonCameraOn",styles:{root:{lineHeight:0}}},onClick:()=>{K(!0)},ariaLabel:L.permitOthersVideoMenuLabel,disabled:!t}),m&&d&&d.length>0&&e.push({key:"stopAllSpotlightKey",text:L.stopAllSpotlightMenuLabel,iconProps:{iconName:"StopAllSpotlightMenuButton",styles:{root:{lineHeight:0}}},onClick:()=>{m()},ariaLabel:L.stopAllSpotlightMenuLabel}),{items:e}}),[E,x,D,I,w,R,M,m,d,L.muteAllMenuLabel,L.forbidOthersAudioMenuLabel,L.permitOthersAudioMenuLabel,L.forbidOthersVideoMenuLabel,L.permitOthersVideoMenuLabel,L.stopAllSpotlightMenuLabel]),ee=(0,e.useCallback)((()=>e.createElement(Wte,{onClose:N,paneOpenerButton:l,headingText:L.peoplePaneTitle,dismissSidePaneButtonAriaLabel:L.dismissSidePaneButtonLabel,mobileView:null!=o&&o,dismissButtonComponentRef:k,chatButtonPresent:O})),[N,l,L.peoplePaneTitle,L.dismissSidePaneButtonLabel,o,k,O]),te=(0,e.useCallback)(((e,t,i)=>{var n,r;let a=null==S?void 0:S.includes(e);const o=[],l=null==d?void 0:d.includes(e),c=t===e;if(a=!l&&a,v&&!c&&x&&x[e]){const t=x[e],i=!!(null==t?void 0:t.isMuted);o.push({key:"mute",text:"Mute",role:"menuitem",iconProps:{iconName:"ContextualMenuMicMutedIcon",styles:{root:{lineHeight:0}}},onClick:()=>{v(e)},"data-ui-id":"participant-item-mute-participant",ariaLabel:"Mute",disabled:i})}const m=null==x?void 0:x[e];if((null==m?void 0:m.mediaAccess)&&!m.mediaAccess.isAudioPermitted&&"Attendee"===(null==m?void 0:m.role)&&_&&o.push({key:"permit-audio",text:L.permitAudioMenuLabel,role:"menuitem",iconProps:{iconName:"ControlButtonMicOn",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{_([e])},"data-ui-id":"participant-item-permit-microphone-button",ariaLabel:L.permitAudioMenuLabel}),(null===(n=null==m?void 0:m.mediaAccess)||void 0===n?void 0:n.isAudioPermitted)&&"Attendee"===(null==m?void 0:m.role)&&b&&o.push({key:"forbid-audio",text:L.forbidAudioMenuLabel,role:"menuitem",iconProps:{iconName:"ControlButtonMicProhibited",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{b([e])},"data-ui-id":"participant-item-forbid-microphone-button",ariaLabel:L.forbidAudioMenuLabel}),(null==m?void 0:m.mediaAccess)&&!m.mediaAccess.isVideoPermitted&&"Attendee"===(null==m?void 0:m.role)&&P&&o.push({key:"permit-video",text:L.permitVideoMenuLabel,role:"menuitem",iconProps:{iconName:"ControlButtonCameraOn",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{P([e])},"data-ui-id":"participant-item-permit-camera-button",ariaLabel:L.permitVideoMenuLabel}),(null===(r=null==m?void 0:m.mediaAccess)||void 0===r?void 0:r.isVideoPermitted)&&"Attendee"===(null==m?void 0:m.role)&&A&&o.push({key:"forbid-video",text:L.forbidVideoMenuLabel,role:"menuitem",iconProps:{iconName:"ControlButtonCameraProhibitedSmall",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{A([e])},"data-ui-id":"participant-item-forbid-camera-button",ariaLabel:L.forbidVideoMenuLabel}),l){const t=c?L.stopSpotlightOnSelfMenuLabel:L.stopSpotlightMenuLabel,i=c?h:p?()=>{p([e])}:void 0;i&&t&&o.push({key:"stop-spotlight",text:t,role:"menuitem",onClick:i,iconProps:{iconName:"StopSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},ariaLabel:t})}else{const t=d&&d.length>0?L.addSpotlightMenuLabel:L.startSpotlightMenuLabel,i=!!f&&!!d&&d.length>=f,n=c?u:g?()=>{g([e])}:void 0;n&&t&&o.push({key:"start-spotlight",text:t,role:"menuitem",onClick:n,iconProps:{iconName:"StartSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},ariaLabel:t,disabled:i,title:i?L.spotlightLimitReachedMenuTitle:void 0})}return c||void 0===a||(a&&C&&(null==L?void 0:L.unpinParticipantMenuLabel)&&o.push({key:"unpin",text:null==L?void 0:L.unpinParticipantMenuLabel,role:"menuitem",iconProps:{iconName:"UnpinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{null==C||C(e)},"data-ui-id":"participant-item-unpin-participant-button",ariaLabel:L.unpinParticipantMenuItemAriaLabel}),!a&&y&&(null==L?void 0:L.pinParticipantMenuLabel)&&o.push({key:"pin",text:T?L.pinParticipantLimitReachedMenuLabel:L.pinParticipantMenuLabel,role:"menuitem",iconProps:{iconName:"PinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{y(e)},"data-ui-id":"participant-item-pin-participant-button",disabled:T||l,ariaLabel:L.pinParticipantMenuItemAriaLabel})),i&&o.push(...i),s?s(e,t,o):o}),[S,d,v,x,_,b,P,A,s,L.permitAudioMenuLabel,L.forbidAudioMenuLabel,L.permitVideoMenuLabel,L.forbidVideoMenuLabel,L.stopSpotlightOnSelfMenuLabel,L.stopSpotlightMenuLabel,L.addSpotlightMenuLabel,L.startSpotlightMenuLabel,L.spotlightLimitReachedMenuTitle,null==L?void 0:L.unpinParticipantMenuLabel,L.pinParticipantMenuLabel,L.unpinParticipantMenuItemAriaLabel,L.pinParticipantLimitReachedMenuLabel,L.pinParticipantMenuItemAriaLabel,h,p,f,u,g,C,y,T]),ie=u7(S7),ne=u7(H7),re=(0,e.useCallback)((()=>e.createElement(e.Fragment,null,e.createElement(f9,Object.assign({},B,{styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},onConfirm:()=>V(),isOpen:F,onCancel:()=>U(!1)})),e.createElement(f9,{heading:L.forbidOthersAudioDialogTitle,text:L.forbidOthersAudioDialogContent,confirmButtonLabel:L.forbidOthersAudioConfirmButtonLabel,cancelButtonLabel:L.forbidOthersAudioCancelButtonLabel,styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},onConfirm:()=>J(),isOpen:H,onCancel:()=>$(!1)}),e.createElement(f9,{heading:L.permitOthersAudioDialogTitle,text:L.permitOthersAudioDialogContent,confirmButtonLabel:L.permitOthersAudioConfirmButtonLabel,cancelButtonLabel:L.permitOthersAudioCancelButtonLabel,styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},onConfirm:()=>Y(),isOpen:j,onCancel:()=>$(!1)}),e.createElement(f9,{heading:L.forbidOthersVideoDialogTitle,text:L.forbidOthersVideoDialogContent,confirmButtonLabel:L.forbidOthersVideoConfirmButtonLabel,cancelButtonLabel:L.forbidOthersVideoCancelButtonLabel,styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},onConfirm:()=>Q(),isOpen:q,onCancel:()=>z(!1)}),e.createElement(f9,{heading:L.permitOthersVideoDialogTitle,text:L.permitOthersVideoDialogContent,confirmButtonLabel:L.permitOthersVideoConfirmButtonLabel,cancelButtonLabel:L.permitOthersVideoCancelButtonLabel,styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},onConfirm:()=>Z(),isOpen:W,onCancel:()=>z(!1)}),e.createElement(pie,{inviteLink:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:te,setDrawerMenuItems:a,mobileView:o,setParticipantActioned:c,participantListHeadingMoreButtonProps:X,pinnedParticipants:S,role:ie,alternateCallerId:ne}))),[B,F,L.forbidOthersAudioDialogTitle,L.forbidOthersAudioDialogContent,L.forbidOthersAudioConfirmButtonLabel,L.forbidOthersAudioCancelButtonLabel,L.permitOthersAudioDialogTitle,L.permitOthersAudioDialogContent,L.permitOthersAudioConfirmButtonLabel,L.permitOthersAudioCancelButtonLabel,L.forbidOthersVideoDialogTitle,L.forbidOthersVideoDialogContent,L.forbidOthersVideoConfirmButtonLabel,L.forbidOthersVideoCancelButtonLabel,L.permitOthersVideoDialogTitle,L.permitOthersVideoDialogContent,L.permitOthersVideoConfirmButtonLabel,L.permitOthersVideoCancelButtonLabel,H,j,q,W,n,r,te,a,o,c,X,S,ie,ne,V,J,Y,Q,Z]),se=(0,e.useMemo)((()=>({headerRenderer:ee,contentRenderer:re,id:vie})),[re,ee]),ae=(0,e.useCallback)((()=>{i(se)}),[se,i]),oe=Vte(vie);return(0,e.useEffect)((()=>{oe&&ae()}),[oe,ae]),{openPeoplePane:ae,closePeoplePane:N,isPeoplePaneOpen:oe}})(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},x),be),Ee),pe),Ae)),De=(0,e.useCallback)((()=>{Pe?Me():Re()}),[Me,Pe,Re]);(0,e.useEffect)((()=>{w&&I(void 0)}),[I,w,Pe,Me]);const ke=Bte(),[Oe,Ne]=(0,e.useState)(!ke&&t.mobileView);(0,e.useEffect)((()=>{ke&&t.mobileView?Ne(!1):Ne(!0)}),[t.mobileView,ke]);const Le={dismissModalAriaLabel:F.strings.call.dismissModalAriaLabel},xe=t.mobileView&&ke,Fe=(0,e.useMemo)((()=>({display:xe?"none":"flex",minWidth:t.mobileView?"unset":"30rem",width:"100%",height:"100%",position:"relative"})),[xe,t.mobileView]),Ue=u7(x7),{openVideoEffectsPane:Be,isVideoEffectsPaneOpen:Ve}=$ie(t.updateSidePaneRenderer,t.mobileView,t.latestErrors,t.onDismissError,y),[He,$e]=(0,e.useState)(!1),je=(0,e.useCallback)((()=>{$e(!0)}),[]),Ge=(0,e.useCallback)((()=>{$e(!1)}),[]),qe=(0,e.useCallback)((()=>{$e(!1),De()}),[De]),ze=(0,e.useMemo)((()=>pte(M9)),[]);let We=t.showErrorNotifications?t.latestErrors:[];const Ke=u7(Fie).isAvailable;"Consumer"===U&&(t.errorBarProps||t.showErrorNotifications)&&(We=We.filter((e=>"callCameraAccessDenied"!==e.type&&"callCameraAccessDeniedSafari"!==e.type))),t.doNotShowCameraAccessNotifications&&(We=We.filter((e=>"callCameraAccessDenied"!==e.type&&"callCameraAccessDeniedSafari"!==e.type)));const Je=Vte(Hie);!Je&&Ke||!t.errorBarProps&&!t.showErrorNotifications||(We=We.filter((e=>"unableToStartVideoEffect"!==e.type)));const Ye=u7(P7),Qe=u7(A7),Ze=Ye&&(null===(s=null==A?void 0:A.setCaptionLanguage)||void 0===s?void 0:s.isPresent)||Qe,Xe="Connected"===u7(g7),et=u7(w7),tt=((t,i)=>{const n=(0,e.useRef)(document.getElementById(t)),r=y0(n),s=C0(n);return{minDragPosition:(0,e.useMemo)((()=>void 0===r||void 0===s?void 0:{x:gee-r+88,y:-1*s+128+64}),[s,r,i]),maxDragPosition:(0,e.useMemo)((()=>void 0===r?void 0:{x:gee,y:64}),[r,i])}})(t.modalLayerHostId),it=(0,e.useMemo)((()=>(e=>({modal:{main:Object.assign(Object.assign({borderRadius:e.effects.roundedCorner4,boxShadow:e.effects.elevation8,zIndex:2},e.rtl?{left:vJ(gee)}:{right:vJ(gee)}),{bottom:vJ(64)})}}))(f)),[f]),nt=(0,e.useMemo)((()=>{var e;return Object.assign(Object.assign({},L9),"full"===(null===(e=null==t?void 0:t.captionsOptions)||void 0===e?void 0:e.height)?{root:{postion:"absolute"}}:{})}),[null===(a=null==t?void 0:t.captionsOptions)||void 0===a?void 0:a.height]);Ye&&We.filter((e=>"teamsMeetingCallNetworkQualityLow"===e.type)).forEach((e=>{e.onClickPrimaryButton=t.mobileView?le:re}));const rt=!!(t.mobileView&&E&&b&&E/b>1),st=t.mobileView?null===(o=t.capabilitiesChangedNotificationBarProps)||void 0===o?void 0:o.capabilitiesChangedNotifications.filter((e=>"shareScreen"!==e.capabilityName)):null===(l=t.capabilitiesChangedNotificationBarProps)||void 0===l?void 0:l.capabilitiesChangedNotifications,at=(e=>{const t=u7(N7),i=e.component.strings.notificationStack;return i.breakoutRoomJoined&&e.strings.call.breakoutRoomJoinedNotificationTitle&&t&&(i.breakoutRoomJoined.title=e.strings.call.breakoutRoomJoinedNotificationTitle.replace("{roomName}",t)),i})(F);let ot=t.latestNotifications;ot=t.mobileView?(null!=ot?ot:[]).filter((e=>"assignedBreakoutRoomOpenedPromptJoin"!==e.type)):ot;const lt=u7(V7),[ct,dt]=(0,e.useState)(!1),ut=(0,e.useCallback)((()=>{dt(!0)}),[]);return e.createElement("div",{ref:T,className:dB(d9),id:t.id},e.createElement(Y$,{verticalFill:!0,horizontalAlign:"stretch",className:m,"data-ui-id":t.dataUiId},e.createElement(Y$,{reversed:!0,horizontal:rt,grow:!0,styles:B9(rt)},e.createElement(Y$,{horizontal:!0,grow:!0},e.createElement(Y$.Item,{style:Fe},e.createElement(Y$.Item,{styles:v,grow:!0},e.createElement(Y$,{verticalFill:!0,styles:nt},e.createElement(Y$.Item,{styles:x9},t.mobileView&&e.createElement(_ne,{locale:F,adapter:P}),t.showErrorNotifications&&e.createElement(Y$,{styles:U9,horizontalAlign:"center",verticalAlign:"center"},e.createElement(bJ,{onDismissNotification:t.onDismissError,activeNotifications:We})),ot&&e.createElement(Y$,{styles:U9,horizontalAlign:"center",verticalAlign:"center"},e.createElement(bJ,{activeNotifications:ot,onDismissNotification:t.onDismissNotification,strings:at})),t.capabilitiesChangedNotificationBarProps&&t.capabilitiesChangedNotificationBarProps.capabilitiesChangedNotifications.length>0&&e.createElement(Y$,{styles:F9},e.createElement(lne,Object.assign({},t.capabilitiesChangedNotificationBarProps,{capabilitiesChangedNotifications:null!=st?st:[]})))),Oe&&t.onRenderGalleryContent&&t.onRenderGalleryContent(),!w&&e.createElement(c9,{captionsOptions:t.captionsOptions,isMobile:t.mobileView,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,useTeamsCaptions:Ze,isRealTimeTextOn:ct})))),e.createElement($te,{mobileView:t.mobileView,maxWidth:Je?"17.5rem":void 0,minWidth:Je?"17.5rem":void 0,updateSidePaneRenderer:t.updateSidePaneRenderer,onPeopleButtonClicked:t.mobileView&&!Ane(t.callControlProps.options)?void 0:De,disablePeopleButton:"boolean"!=typeof t.callControlProps.options&&WF(null===(c=t.callControlProps.options)||void 0===c?void 0:c.participantsButton),onChatButtonClicked:null===(d=t.mobileChatTabHeader)||void 0===d?void 0:d.onClick,disableChatButton:null===(u=t.mobileChatTabHeader)||void 0===u?void 0:u.disabled,showAddPeopleButton:!!t.callControlProps.callInvitationURL,ariaLabel:Ve?F.strings.call.videoEffectsPaneAriaLabel:void 0}),t.mobileView&&e.createElement(one,{modalLayerHostId:t.modalLayerHostId,hidden:!ke,styles:it,strings:Le,minDragPosition:tt.minDragPosition,maxDragPosition:tt.maxDragPosition,onDismissSidePane:()=>{Me(),t.onCloseChatPane&&t.onCloseChatPane()}}),k.length>0&&e.createElement(Y$,{styles:pte()},e.createElement(K0,{onLightDismiss:()=>O([]),items:k}))),!1!==(null===(h=t.callControlProps)||void 0===h?void 0:h.options)&&!xe&&e.createElement(Y$,{verticalAlign:"center",className:dB({zIndex:2,padding:rt?"0.25rem":"unset"})},wne(null===(g=t.callControlProps)||void 0===g?void 0:g.options)?e.createElement(eee,Object.assign({},t.callControlProps,{containerWidth:E,containerHeight:b,isMobile:t.mobileView,peopleButtonChecked:Pe,onPeopleButtonClicked:De,displayVertical:rt})):e.createElement($ee,Object.assign({},t.callControlProps,{callControls:t.callControlProps.options,callAdapter:P,mobileView:t.mobileView,disableButtonsForLobbyPage:_,disableButtonsForHoldScreen:w,peopleButtonChecked:Pe,onPeopleButtonClicked:De,onMoreButtonClicked:je,isCaptionsSupported:Ze&&Xe||Xe,isRealTimeTextSupported:Xe,onStartRealTimeText:ut,startRealTimeTextButtonChecked:ct,useTeamsCaptions:Ze,isCaptionsOn:et,onClickVideoEffects:Ue?Be:void 0,displayVertical:rt,onUserSetOverflowGalleryPositionChange:t.onUserSetOverflowGalleryPositionChange,onUserSetGalleryLayout:t.onUserSetGalleryLayoutChange,userSetGalleryLayout:t.userSetGalleryLayout,onSetDialpadPage:t.onSetDialpadPage,dtmfDialerPresent:t.dtmfDialerPresent,peopleButtonRef:S,cameraButtonRef:y,onStopLocalSpotlight:!j&&Q.spotlight?fe:void 0,onToggleTeamsMeetingConferenceModal:re,teamsMeetingConferenceModalPresent:ie,sidePaneDismissButtonRef:C}))),!1!==(null===(p=t.callControlProps)||void 0===p?void 0:p.options)&&He&&e.createElement(Y$,{styles:ze},e.createElement(dte,{callControls:t.callControlProps.options,onLightDismiss:Ge,onPeopleButtonClicked:qe,disableButtonsForHoldScreen:w,isCaptionsSupported:Ze&&Xe||Xe,isRealTimeTextSupported:Xe,onStartRealTimeText:ut,startRealTimeTextButtonChecked:ct,useTeamsCaptions:Ze,onUserSetGalleryLayout:t.onUserSetGalleryLayoutChange,userSetGalleryLayout:t.userSetGalleryLayout,onSetDialpadPage:t.onSetDialpadPage,dtmfDialerPresent:t.dtmfDialerPresent,dtmfDialerOptions:t.dtmfDialerOptions,reactionResources:lt,onClickMeetingPhoneInfo:ce})))))},wne=e=>!!e&&!0!==e&&!0===(null==e?void 0:e.legacyControlBarExperience),Ane=e=>void 0===e||!0===e||!1!==e&&!1!==e.participantsButton&&!1!==e.peopleButton,Pne=G6([p7],(e=>({cameras:e.cameras,selectedCamera:e.selectedCamera}))),Rne={root:{height:"100%",minHeight:"10rem",minWidth:"6rem"}},Mne={scalingMode:"Crop",isMirrored:!0},Dne={scalingMode:"Crop"},kne=t=>{var i,n;const{pinnedParticipants:r=[],setPinnedParticipants:s,setIsPromptOpen:a,setPromptProps:o,hideSpotlightButtons:l,videoTilesOptions:c,captionsOptions:d}=t,u=Y7(w5),h=u7(Pne),g=K7(),p=(()=>{const t=PJ().strings.call,i=(0,e.useMemo)((()=>({participantJoinedNoticeString:t.participantJoinedNoticeString,twoParticipantJoinedNoticeString:t.twoParticipantJoinedNoticeString,threeParticipantJoinedNoticeString:t.threeParticipantJoinedNoticeString,participantLeftNoticeString:t.participantLeftNoticeString,twoParticipantLeftNoticeString:t.twoParticipantLeftNoticeString,threeParticipantLeftNoticeString:t.threeParticipantLeftNoticeString,unnamedParticipantString:t.unnamedParticipantString,manyParticipantsJoined:t.manyParticipantsJoined,manyParticipantsLeft:t.manyParticipantsLeft,manyUnnamedParticipantsJoined:t.manyUnnamedParticipantsJoined,manyUnnamedParticipantsLeft:t.manyUnnamedParticipantsLeft})),[t]),[n,r]=(0,e.useState)(""),s=u7(aee),a=(0,e.useRef)(s),o=e=>{r(e)};return(0,e.useMemo)((()=>{const e=s.map((e=>iL(e.identifier))),t=a.current.map((e=>iL(e.identifier))),n=s.filter((e=>!t.includes(iL(e.identifier)))),r=a.current.filter((t=>!e.includes(iL(t.identifier))));n.length>0&&o(oee("joined",n,i)),r.length>0&&o(oee("left",r,i)),a.current=s}),[s,i]),n})(),m=u7(S7),f=u7(m7),v=u7($7),S=(0,e.useRef)(null),y=y0(S),C=C0(S),T=y&&C?y/C:0,E=u7(V7),b=Nne(null===(i=t.localVideoTileOptions)||void 0===i?void 0:i.position),_=(0,e.useMemo)((()=>Object.assign(Object.assign({},g),h)),[g,h]),I=(0,e.useCallback)(((i,n)=>e.createElement(Y$,{className:dB({position:"absolute",height:"100%",width:"100%"})},e.createElement(Y$,{styles:{root:{margin:"auto",maxHeight:"100%"}}},(null==n?void 0:n.coinSize)&&e.createElement(h0,Object.assign({userId:i},n,{dataProvider:t.onFetchAvatarPersonaData}))))),[t.onFetchAvatarPersonaData]),w=(0,e.useMemo)((()=>{var e;return!(null===(e=t.remoteVideoTileMenuOptions)||void 0===e?void 0:e.isHidden)&&(t.isMobile?{kind:"drawer",hostId:t.drawerMenuHostId}:{kind:"contextual"})}),[null===(n=t.remoteVideoTileMenuOptions)||void 0===n?void 0:n.isHidden,t.isMobile,t.drawerMenuHostId]),A=(0,e.useMemo)((()=>y&&C&&y/C>=16/9?"verticalRight":"horizontalBottom"),[y,C]),{onStartLocalSpotlight:P,onStopLocalSpotlight:R,onStartRemoteSpotlight:M,onStopRemoteSpotlight:D}=u,{onStartLocalSpotlightWithPrompt:k,onStopLocalSpotlightWithPrompt:O}=gne(P,R,a,o),{onStartRemoteSpotlightWithPrompt:N,onStopRemoteSpotlightWithPrompt:L}=fne(M,D,a,o),x=(0,e.useMemo)((()=>Object.assign(Object.assign({},Rne),"full"===(null==d?void 0:d.height)?{root:{postion:"absolute"}}:{})),[null==d?void 0:d.height]),F=(0,e.useMemo)((()=>s?e=>{r.includes(e)||s(r.concat(e))}:void 0),[s,r]),U=(0,e.useMemo)((()=>s?e=>{s(r.filter((t=>t!==e)))}:void 0),[s,r]),B=(0,e.useMemo)((()=>{var i;return e.createElement(w5,Object.assign({},u,{videoTilesOptions:c,localVideoViewOptions:Mne,remoteVideoViewOptions:Dne,styles:x,layout:t.localVideoTileOptions?b:t.userSetGalleryLayout,showCameraSwitcherInLocalPreview:t.isMobile,localVideoCameraCycleButtonProps:_,onRenderAvatar:I,remoteVideoTileMenu:w,overflowGalleryPosition:A,localVideoTileSize:!1===t.localVideoTileOptions||"Consumer"===m||v&&"Unknown"===m?"hidden":t.isMobile&&T<1?"9:16":"16:9",pinnedParticipants:r,onPinParticipant:F,onUnpinParticipant:U,reactionResources:E,onStartLocalSpotlight:l?void 0:k,onStopLocalSpotlight:l?void 0:O,onStartRemoteSpotlight:l?void 0:N,onStopRemoteSpotlight:l?void 0:L,onMuteParticipant:(null===(i=null==f?void 0:f.muteOthers)||void 0===i?void 0:i.isPresent)||"Unknown"===m?u.onMuteParticipant:void 0,localScreenShareView:t.localScreenShareView}))}),[u,c,x,t.isMobile,t.localVideoTileOptions,t.userSetGalleryLayout,_,I,w,A,m,v,T,r,F,U,E,l,k,O,N,L,b,null==f?void 0:f.muteOthers,t.localScreenShareView]);return e.createElement("div",{ref:S,style:One},e.createElement(J0,{announcementString:p,ariaLive:"polite"}),B)},One={width:"100%",height:"100%"},Nne=e=>"grid"===e?"default":"floatingLocalVideo",Lne={root:{height:"100%",width:"100%",position:"relative",padding:"0.5rem"}},xne=e=>({position:"absolute",height:"100%",width:"100%",background:e?"black":void 0,opacity:e?.6:void 0,zIndex:0}),Fne={height:"100%",width:"100%",zIndex:1},Une={root:{height:"100%",width:"100%"}},Bne=()=>e.createElement(e.Fragment,null),Vne={scalingMode:"Crop",isMirrored:!0},Hne=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,s=null==n?void 0:n.renderElement;return(0,e.useEffect)((()=>{n&&r&&t.onCreateLocalStreamView&&t.onCreateLocalStreamView(Vne).catch((e=>console.log("Can not render video",e)))}),[r,n,t,s]),e.createElement(Y$,{horizontalAlign:"center",verticalAlign:"center",styles:Lne,grow:!0},e.createElement(o0,{styles:Une,renderElement:s?e.createElement(e1,{videoStreamElement:s}):void 0,onRenderPlaceholder:Bne},t.overlayContent&&e.createElement(e.Fragment,null,e.createElement(Y$,{className:dB(xne(r))}),e.createElement(Y$,{horizontalAlign:"center",verticalAlign:"center",className:dB(Fne)},t.overlayContent))))},$ne={margin:"1rem",gap:"1.5rem"},jne={gap:"1.5rem",height:"auto"},Gne={gap:"1rem"},qne=(e,t)=>({fontSize:"1.25rem",fontWeight:DV.semibold,color:t?"white":e.neutralPrimary,textAlign:"center"}),zne=(e,t)=>({fontSize:"1rem",color:t?"white":e.neutralPrimary,textAlign:"center"}),Wne=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,s=aJ().palette,a=PJ().strings.call,o=PJ().component.strings.meetingConferencePhoneInfo,l=aJ(),c=K7(),d=u7(P7),u=u7(R7);return e.createElement(Hne,Object.assign({localParticipantVideoStream:t.localParticipantVideoStream,overlayContent:e.createElement(Y$,{verticalFill:!0,horizontalAlign:"center",verticalAlign:"center",className:dB($ne),"aria-atomic":!0},e.createElement(Y$,{role:"alert",verticalFill:!0,horizontalAlign:"center",verticalAlign:"center",className:dB(jne)},e.createElement(Y$,{horizontal:!0,className:dB(Gne)},e.createElement(bZ,{iconName:"NetworkReconnectIcon",className:dB(qne(s,r))}),e.createElement(oJ,{className:dB(qne(s,r))},a.networkReconnectTitle)),e.createElement(oJ,{className:dB(zne(s,r))},a.networkReconnectMoreDetails)),d&&u&&u[0]&&e.createElement(Y$,null,e.createElement(Y$,{horizontal:!0,horizontalAlign:"center",verticalAlign:"center",className:Tie},e.createElement(oJ,{className:Cie},o.meetingConferencePhoneInfoModalTitle)),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",className:Iie},e.createElement(Y$,{className:Pie(l)}),e.createElement(Y$.Item,null,e.createElement(Y$,{horizontal:!0,className:wie},e.createElement(Y$.Item,{className:_ie(l)},e.createElement(Y$,{verticalAlign:"center",horizontalAlign:"center"},e.createElement(mG,{iconName:"JoinByPhoneDialStepIcon",className:Aie(l)}))),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},o.meetingConferencePhoneInfoModalDialIn)))),e.createElement(Y$.Item,{className:wie},u.map(((i,n)=>e.createElement(Y$.Item,{key:n},e.createElement(oJ,{className:bie},t.isMobile&&e.createElement(hJ,{className:bie,href:Ree(i)},A6(i.phoneNumber,!0)),!t.isMobile&&e.createElement(oJ,{className:bie},A6(i.phoneNumber,!0))," ",i.isTollFree?o.meetingConferencePhoneInfoModalTollFree:o.meetingConferencePhoneInfoModalToll),e.createElement("br",null),e.createElement(oJ,{className:bie}," ",Mee(i,o))))))),e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:Iie},e.createElement(Y$.Item,null,e.createElement(Y$,{horizontal:!0},!t.isMobile&&e.createElement(Y$,{className:Pie(l)}),e.createElement(Y$.Item,{className:_ie(l)},e.createElement(mG,{iconName:"JoinByPhoneConferenceIdIcon",className:Aie(l)})),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},o.meetingConferencePhoneInfoModalMeetingId)))),e.createElement(oJ,{className:bie},u[0].conferenceId,"#")),!t.isMobile&&e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:Iie},e.createElement(Y$,{horizontal:!0},e.createElement(Y$.Item,{className:_ie(l),style:{marginLeft:vJ(2)}},e.createElement(mG,{iconName:"JoinByPhoneWaitToBeAdmittedIcon",className:Aie(l)})),e.createElement(Y$.Item,null,e.createElement(oJ,{className:Eie},o.meetingConferencePhoneInfoModalWait))))))},c))},Kne=G6([e=>{var t;return!!(null===(t=e.call)||void 0===t?void 0:t.transcription.isTranscriptionActive)},e=>{var t;return!!(null===(t=e.call)||void 0===t?void 0:t.recording.isRecordingActive)}],((e,t)=>({callTranscribeState:e,callRecordState:t}))),Jne=G6([b7],(e=>{var t;return{speakingWhileMuted:!!(null===(t=null==e?void 0:e.media.latest.speakingWhileMicrophoneIsMuted)||void 0===t?void 0:t.value)}})),Yne=G6([Fie],(e=>({localParticipantVideoStream:e}))),Qne=G6([b7,Yne],((e,t)=>{var i;return{networkReconnectValue:null===(i=null==e?void 0:e.network.latest.networkReconnect)||void 0===i?void 0:i.value,localParticipantVideoStream:t.localParticipantVideoStream}})),Zne={root:{color:"inherit",fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28),margin:"auto"}};const Xne=t=>{const i=qK(),n=u7(M7),r=u7(_7),s=null==n?void 0:n[0];let a;if(r){const e=Object.values(r);a=s&&YN(s)?s.phoneNumber:e.find((e=>e.identifier===s))}const o=LZ();return e.createElement(Y$,{style:{height:"100%",width:"100%",background:i.palette.white}},e.createElement(Y$,{verticalAlign:"center",style:{margin:"auto"}},e.createElement(ere,null),e.createElement(oJ,{style:{margin:"auto"}},a&&"Unnamed participant"!==a?null==a?void 0:a.toString():""),e.createElement(L6,{onSendDtmfTone:e=>{return t=void 0,i=void 0,r=function*(){yield o.sendDtmfTone(e)},new((n=void 0)||(n=Promise))((function(e,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(a,o)}l((r=r.apply(t,i||[])).next())}));var t,i,n,r},longPressTrigger:t.mobileView?"touch":"mouseAndTouch",dialpadMode:"dtmf",dtmfAudioContext:t.compositeAudioContext})))},ere=()=>{const[t,i]=(0,e.useState)(0),n=Nee(t),r=u7(D7),s=(0,e.useMemo)((()=>null!=r?r:new Date(Date.now())),[r]);return(0,e.useEffect)((()=>{const e=setInterval((()=>{var e;i(null!==(e=new Date(Date.now()).getTime()-(null==s?void 0:s.getTime()))&&void 0!==e?e:0)}),10);return()=>{clearInterval(e)}}),[s]),e.createElement(oJ,{styles:Zne},n)},tre=t=>e.createElement(Xne,Object.assign({},t,{mobileView:t.mobileView})),ire=t=>{var i,n,r,s;const{callInvitationURL:a,onFetchAvatarPersonaData:o,onFetchParticipantMenuItems:l,options:c,mobileView:d,galleryLayout:u="floatingLocalVideo",onUserSetGalleryLayoutChange:h,userSetOverflowGalleryPosition:g="Responsive",onSetUserSetOverflowGalleryPosition:p,onCloseChatPane:m,pinnedParticipants:f=[],setPinnedParticipants:v,compositeAudioContext:S,disableAutoShowDtmfDialer:y={dialerBehavior:"autoShow"},latestNotifications:C,onDismissNotification:T}=t,{callStatus:E}=u7(Q9),b=u7(see),_=K7(),I=u7(Kne),w=Y7(BK),A=u7(Jne),P=u7(Qne),R=u7(aee),M=u7(M7),D=lee(M,R,y),[k,O]=(0,e.useState)(D),N=PJ().strings.call,L=(0,e.useMemo)((()=>f.filter((e=>R.find((t=>iL(t.identifier)===e))))),[f,R]),x=d?$F(null==c?void 0:c.callControls):null==c?void 0:c.callControls,F=g$("drawerMenuHost"),[U,B]=(0,e.useState)(!1),[V,H]=(0,e.useState)(),$=u7((e=>e.page)),j=u7((e=>e.userId)),G=u7((e=>e.displayName)),q=(0,e.useCallback)(((i,n)=>e.createElement(Y$,{className:dB({position:"absolute",height:"100%",width:"100%"})},e.createElement(Y$,{styles:{root:{margin:"auto",maxHeight:"100%"}}},(null==n?void 0:n.coinSize)&&e.createElement(h0,Object.assign({userId:i},n,{dataProvider:t.onFetchAvatarPersonaData}))))),[t.onFetchAvatarPersonaData]);let z=e.createElement(e.Fragment,null);return oL(E)||"returningFromBreakoutRoom"!==$||(z=e.createElement(o0,{userId:iL(j),displayName:G,initialsName:G,onRenderPlaceholder:q})),e.createElement(e.Fragment,null,e.createElement(Ine,{id:F,complianceBannerProps:Object.assign(Object.assign({},I),{strings:N}),errorBarProps:!1!==(null==c?void 0:c.errorBar)&&w,showErrorNotifications:null===(i=null==c?void 0:c.errorBar)||void 0===i||i,mutedNotificationProps:A,callControlProps:{callInvitationURL:a,onFetchParticipantMenuItems:l,options:x,increaseFlyoutItemSize:d},onFetchAvatarPersonaData:o,mobileView:d,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>oL(E)?nre(P.networkReconnectValue)?(()=>{var i,n;return k?e.createElement(tre,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError,capabilitiesChangedNotificationBarProps:t.capabilitiesChangedNotificationBarProps,onSetDialpadPage:()=>O(!k),dtmfDialerPresent:k,compositeAudioContext:S}):e.createElement(kne,Object.assign({isMobile:d},b,_,{onFetchAvatarPersonaData:o,remoteVideoTileMenuOptions:null==c?void 0:c.remoteVideoTileMenuOptions,drawerMenuHostId:F,localVideoTileOptions:null==c?void 0:c.localVideoTile,userSetOverflowGalleryPosition:g,userSetGalleryLayout:u,pinnedParticipants:L,setPinnedParticipants:v,setIsPromptOpen:B,setPromptProps:H,hideSpotlightButtons:null===(i=null==c?void 0:c.spotlight)||void 0===i?void 0:i.hideSpotlightButtons,videoTilesOptions:null==c?void 0:c.videoTilesOptions,captionsOptions:null==c?void 0:c.captionsBanner,localScreenShareView:null===(n=null==c?void 0:c.galleryOptions)||void 0===n?void 0:n.localScreenShareView}))})():e.createElement(Wne,Object.assign({},P,{isMobile:d})):z,updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:m,dataUiId:"call-page",latestErrors:t.latestErrors,latestNotifications:C,onDismissError:t.onDismissError,onDismissNotification:T,onUserSetOverflowGalleryPositionChange:p,onUserSetGalleryLayoutChange:h,userSetGalleryLayout:u,capabilitiesChangedNotificationBarProps:t.capabilitiesChangedNotificationBarProps,onSetDialpadPage:()=>O(!k),dtmfDialerPresent:k,setIsPromptOpen:B,setPromptProps:H,hideSpotlightButtons:null===(n=null==c?void 0:c.spotlight)||void 0===n?void 0:n.hideSpotlightButtons,pinnedParticipants:L,setPinnedParticipants:v,doNotShowCameraAccessNotifications:"doNotPrompt"===(null===(s=null===(r=t.options)||void 0===r?void 0:r.deviceChecks)||void 0===s?void 0:s.camera),captionsOptions:null==c?void 0:c.captionsBanner,dtmfDialerOptions:y}),e.createElement(f9,Object.assign({isOpen:U,onDismiss:()=>B(!1)},V)))},nre=e=>!0===e||!1===e||void 0===e||e===zb.Good,rre=t=>{const{icon:i,askDevicePermission:n,onClick:r,constrain:s,strings:a,options:o}=t,l=!o&&!!n,c=e$(l?{title:{paddingRight:"0.625rem"}}:{},t.styles),d=()=>{n&&n(null!=s?s:{video:!0,audio:!0}),null==r||r()};return e.createElement(l3,{role:l?"button":void 0,"data-ui-id":"permission-dropdown",placeholder:null==a?void 0:a.placeHolderText,label:null==a?void 0:a.label,"aria-labelledby":t.ariaLabelledby,onRenderPlaceholder:()=>e.createElement(Y$,{horizontal:!0,verticalAlign:"center",horizontalAlign:"space-between"},i,e.createElement(Y$.Item,{styles:{root:{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",flex:1}}},e.createElement(oJ,null,null==a?void 0:a.placeHolderText)),e.createElement(Y$.Item,{shrink:0,styles:{root:{paddingLeft:"0.5rem"}}},e.createElement(oJ,null,null==a?void 0:a.actionButtonContent))),onRenderCaretDown:l?()=>e.createElement(e.Fragment,null):void 0,onClick:l?d:void 0,onKeyDown:l?e=>{"Enter"!==e.key&&" "!==e.key||d()}:void 0,options:null!=o?o:[],styles:c})},sre={childrenGap:"0.5rem"},are={childrenGap:"0.5rem"},ore=e=>({caretDownWrapper:{height:"2.25rem",lineHeight:"2.25rem"},dropdownItem:{fontSize:"0.875rem",height:"2.25rem",background:e.palette.white},dropdown:{height:"2.25rem",width:"100%",svg:{verticalAlign:"top"}},title:{fontSize:"0.875rem",height:"2.25rem",lineHeight:"2rem",borderRadius:"0.25rem",border:`1px solid ${e.palette.neutralQuaternaryAlt}`},label:{fontWeight:600,fontSize:"0.875rem",zIndex:1},errorMessage:{fontSize:"0.875rem"}}),lre=dB({overflow:"hidden",textOverflow:"ellipsis",minWidth:"0",maxWidth:"100%",overflowWrap:"break-word",margin:".063rem"}),cre=dB({marginRight:"8px",verticalAlign:"text-top"}),dre={root:{zIndex:1}},ure=t=>{const i=aJ(),n=e.createElement(rre,Object.assign({},t.dropdownProps,{styles:ore(i),constrain:{video:!0,audio:!1},strings:{placeHolderText:"Enable Camera (optional)",actionButtonContent:"Allow"},icon:e.createElement(bZ,{iconName:"ControlButtonCameraOn",style:{height:"1.25rem",marginRight:"0.625rem"}}),onClick:t.onClickEnableDevicePermission,ariaLabelledby:t.ariaLabelledby}));return t.cameraPermissionGranted?t.cameraGrantedDropdown:n},hre=t=>{const i=aJ(),n=e.createElement(rre,Object.assign({},t.dropdownProps,{styles:ore(i),constrain:{video:!1,audio:!0},strings:{placeHolderText:"Enable Microphone (required)",actionButtonContent:"Allow"},icon:e.createElement(bZ,{iconName:"ControlButtonMicOn",style:{height:"1.25rem",marginRight:"0.625rem"}}),onClick:t.onClickEnableDevicePermission,ariaLabelledby:t.ariaLabelledby}));return t.micPermissionGranted?t.micGrantedDropdown:n},gre={childrenGap:"1.5rem"},pre={childrenGap:"0.5rem"},mre={childrenGap:"1.5rem"},fre={root:{width:"100%",minWidth:"11rem",maxWidth:"20.625rem"}},vre=(e,t)=>dB({width:"100%",minHeight:t?"auto":"13.625rem",padding:"1rem",borderRadius:e.effects.roundedCorner6,border:`0.0625rem solid ${e.palette.neutralLight}`,overflow:"hidden",boxShadow:e.effects.elevation4,position:"relative",":before":{content:'""',position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:0,background:e.palette.white,opacity:.9}}),Sre=e=>dB({fontSize:"1.2rem",lineHeight:"1rem",fontWeight:600},Cre(e)),yre=e=>dB({fontSize:"1.0625rem",lineHeight:"1.375rem",fontWeight:600,textAlign:"center"},Cre(e)),Cre=e=>({textShadow:`0px 0px 8px ${e.palette.whiteTranslucent40}`,fill:e.semanticColors.bodyText,svg:{fill:"currentColor"},stroke:e.palette.whiteTranslucent40,paintOrder:"stroke fill",strokeWidth:vJ(1.5),text:{letterSpacing:"-0.02rem"},"@media (forced-colors: active)":{textShadow:"none",stroke:"none"}}),Tre={root:{textAlign:"center",maxWidth:vJ(700),alignSelf:"center"}},Ere=e=>({fontSize:"0.9375",lineHeight:"1.25rem",textShadow:`0px 0px 8px ${e.palette.whiteTranslucent40}`,marginTop:"-0.33rem"}),bre=e=>dB(Ere(e)),_re=e=>dB(Ere(e),{marginBottom:"0.5rem",textAlign:"center"}),Ire={root:{paddingTop:"1.125rem"}},wre={root:{textAlign:"center"}},Are=dB({width:"100%",maxWidth:"unset",borderRadius:"0.25rem",height:"3.25rem"}),Pre=dB({borderRadius:"0.25rem",width:"auto",height:"2.25rem"}),Rre={root:{alignItems:"center"}},Mre=(e,t)=>({root:{background:"transparent",border:"none",color:e.palette.themePrimary,padding:"5px 0.25rem",":hover, :focus":t?{}:{color:e.palette.themePrimary},svg:{height:"1rem",width:"1rem"}},labelHovered:t?{}:{color:e.palette.themePrimary},rootChecked:t?{}:{color:e.palette.themePrimary},rootHovered:t?{}:{color:e.palette.themePrimary},rootPressed:t?{}:{color:e.palette.themePrimary},rootFocused:t?{}:{color:e.palette.themePrimary}}),Dre=dB({width:"100%",position:"relative"}),kre={content:{display:"flex",flexBasis:"100%",paddingLeft:"0rem",paddingRight:"0rem"},commands:{paddingTop:"0rem"},scrollableContent:{display:"flex",flexDirection:"column",height:"100%"}},Ore={forceFocusInsideTrap:!1};const Nre=e=>{const t=new Map;for(const i of e)t.set(i.id,i);const i=[];for(const e of t.values())i.push({key:e.id,text:""===e.name?e.deviceType:e.name});return i},Lre=(t,i)=>{var n,r;return i?e.createElement("div",{className:lre},"Camera"===(r=t)?e.createElement(bZ,{iconName:"LocalDeviceSettingsCamera",className:cre}):"Microphone"===r?e.createElement(bZ,{iconName:"LocalDeviceSettingsMic",className:cre}):"Speaker"===r?e.createElement(bZ,{iconName:"LocalDeviceSettingsSpeaker",className:cre}):void 0,e.createElement("span",null,null===(n=i[0])||void 0===n?void 0:n.text)):e.createElement(e.Fragment,null)},xre={scalingMode:"Crop",isMirrored:!0},Fre=t=>{var i;const n=aJ(),r=PJ(),s=LZ(),a=u7(x7),o=r.strings.call.defaultPlaceHolder,l=r.strings.call.cameraLabel,c=r.strings.call.soundLabel,d=r.strings.call.noSpeakersLabel,u=r.strings.call.noCamerasLabel,h=r.strings.call.noMicrophonesLabel,g=u7(S7),p=t.cameraPermissionGranted,m=t.microphonePermissionGranted,f="Consumer"!==g,v="Consumer"!==g;(0,e.useEffect)((()=>{p&&s.queryCameras(),m&&s.queryMicrophones(),s.querySpeakers()}),[s,p,m]);const S=K7(),y=t.cameras.length>0,C=t.microphones.length>0,T=t.speakers.length>0,E=u7(I7),b=JF(E)&&!T,_=g$("camera-label"),I=g$("sound-label"),w=e.createElement(l3,{"data-ui-id":"call-composite-local-camera-settings","aria-labelledby":_,placeholder:y?o:u,options:p?Nre(t.cameras):[{key:"deniedOrUnknown",text:""}],styles:ore(n),disabled:!p||!y,errorMessage:void 0===t.cameraPermissionGranted||t.cameraPermissionGranted?void 0:r.strings.call.cameraPermissionDenied,defaultSelectedKey:m?t.selectedCamera?t.selectedCamera.id:t.cameras?null===(i=t.cameras[0])||void 0===i?void 0:i.id:"":"deniedOrUnknown",onChange:(e,i,n)=>{return r=void 0,s=void 0,o=function*(){const e=t.cameras[null!=n?n:0];e?yield t.onSelectCamera(e,xre):console.error("No cameras available")},new((a=void 0)||(a=Promise))((function(e,t){function i(e){try{l(o.next(e))}catch(e){t(e)}}function n(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a((function(e){e(r)}))).then(i,n)}l((o=o.apply(r,s||[])).next())}));var r,s,a,o},onRenderTitle:e=>Lre("Camera",e)}),A=e.createElement(e.Fragment,null,v&&e.createElement(l3,{"aria-labelledby":I,placeholder:C?o:h,styles:ore(n),disabled:!m||!C,errorMessage:void 0===t.microphonePermissionGranted||t.microphonePermissionGranted?void 0:r.strings.call.microphonePermissionDenied,options:m?Nre(t.microphones):[{key:"deniedOrUnknown",text:""}],defaultSelectedKey:m?t.selectedMicrophone?t.selectedMicrophone.id:Ure(t.microphones):"deniedOrUnknown",onChange:(e,i,n)=>{const r=t.microphones[null!=n?n:0];r?t.onSelectMicrophone(r):console.error("No microphones available")},onRenderTitle:e=>Lre("Microphone",e)})),P=e.createElement(l3,{"aria-labelledby":I,placeholder:T?o:d,styles:ore(n),disabled:0===t.speakers.length,options:Nre(t.speakers),defaultSelectedKey:t.selectedSpeaker?t.selectedSpeaker.id:Ure(t.speakers),onChange:(e,i,n)=>{const r=t.speakers[null!=n?n:0];r?t.onSelectSpeaker(r):console.error("No speakers available")},onRenderTitle:e=>Lre("Speaker",e)});return e.createElement(Y$,{"data-ui-id":"call-composite-device-settings",tokens:sre,styles:dre},f&&e.createElement(Y$,null,e.createElement(Y$,{horizontal:!0,horizontalAlign:"space-between",styles:Rre},e.createElement(M5,{id:_,className:dB(ore(n).label)},l),a&&e.createElement(pJ,{iconProps:{iconName:"ConfigurationScreenVideoEffectsButton"},styles:Mre(n,!p),onClick:t.onClickVideoEffects,disabled:!p,"data-ui-id":"call-config-video-effects-button"},r.strings.call.configurationPageVideoEffectsButtonLabel)),e.createElement(ure,{cameraGrantedDropdown:w,cameraPermissionGranted:null!=p&&p,dropdownProps:S,onClickEnableDevicePermission:t.onClickEnableDevicePermission,ariaLabelledby:_})),e.createElement(Y$,null,e.createElement(M5,{id:I,className:dB(ore(n).label)},c),e.createElement(Y$,{"data-ui-id":"call-composite-sound-settings",tokens:are},e.createElement(hre,{micGrantedDropdown:A,micPermissionGranted:null!=m&&m,dropdownProps:S,onClickEnableDevicePermission:t.onClickEnableDevicePermission,ariaLabelledby:I}),b?e.createElement(e.Fragment,null):P)))},Ure=e=>{var t;if(0===e.length)return;const i=e.find((e=>e.isSystemDefault));return i?i.id:null===(t=e[0])||void 0===t?void 0:t.id},Bre=dB({marginRight:"0.375rem",fontSize:"1.375rem"}),Vre=dB({fontWeight:600,fontSize:"0.875rem",height:"2.75rem",width:"100%"}),Hre={textContainer:{display:"contents"}},$re=t=>{const{rejoinCall:i}=t,n=PJ();return e.createElement(mJ,Object.assign({},t,{"data-ui-id":"call-composite-start-call-button",className:dB(Vre,t.className),styles:Hre,text:i?n.strings.call.rejoinCallButtonLabel:n.strings.call.startCallButtonLabel,onRenderIcon:t.hideIcon?void 0:()=>e.createElement(aY,{className:Bre})}))},jre=G6([p7],(e=>({video:e.deviceAccess?e.deviceAccess.video:void 0,audio:e.deviceAccess?e.deviceAccess.audio:void 0}))),Gre=G6([p7],(e=>{var t;const i=e.cameras.length>0&&e.unparentedViews.length>0&&(null===(t=e.unparentedViews[0])||void 0===t?void 0:t.view);return{videoStreamElement:i?i.target:null}})),qre=e=>({borderRadius:e.effects.roundedCorner6,overflow:"hidden"}),zre=e=>dB(qre(e),{width:"100%",height:"13.625rem",minWidth:"11rem",maxWidth:"20.625rem",border:`0.0625rem solid ${e.palette.neutralLight}`,borderRadius:e.effects.roundedCorner6,boxShadow:e.effects.elevation4}),Wre=e=>dB(qre(e),{width:"100%",height:"100%",minHeight:"13.625rem"}),Kre=dB({fontSize:"0.75rem"}),Jre={root:{"@media (forced-colors: active)":{borderColor:"#FFFFFF",border:"1px solid"}}},Yre=e=>({root:{minWidth:e?"unset":vJ(75),"@media (forced-colors: active)":{":focus":{border:"1px solid !important"},":focus::after":{border:"unset !important",outline:"unset !important"}}}});const Qre=t=>{var i;const n=PJ(),r=Y7(j3),s=u7(Gre),a=Y7(U3),{audio:o,video:l}=u7(jre),c=u7(T7),d=LZ(),u=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){c?d.mute():d.unmute()},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[d,c]),h=!a.speakers.length,g=0===a.cameras.length&&0===a.microphones.length&&0===a.speakers.length,p=a.cameras.length>0,m=a.microphones.length>0,f=null!==(i=n.strings.call.configurationPageCameraIsLoadingLabel)&&void 0!==i?i:n.strings.call.cameraTurnedOff,v=t.cameraLoading?f:n.strings.call.cameraTurnedOff,S=aJ(),y=(0,e.useCallback)((()=>e.createElement(Y$,{className:dB({width:"100%",height:"100%",marginTop:"-0.8rem"}),verticalAlign:"center"},e.createElement(Y$.Item,{align:"center"},e.createElement(bZ,{iconName:"LocalPreviewPlaceholder",className:dB(Kre,{color:S.palette.neutralTertiary})})),e.createElement(Y$.Item,{align:"center"},e.createElement(oJ,{className:dB(Kre,{color:S.palette.neutralSecondary})},v)))),[S,v]),C=t.mobileView?{menuStyles:{menuItemStyles:e9}}:void 0;return e.createElement(Y$,{"data-ui-id":"call-composite-local-preview",className:t.mobileView?Wre(S):zre(S)},e.createElement(o0,{styles:Jre,renderElement:(null==s?void 0:s.videoStreamElement)?e.createElement(e1,{videoStreamElement:s.videoStreamElement}):void 0,onRenderPlaceholder:y},e.createElement(h9,{layout:"floatingBottom"},e.createElement(V3,{"data-ui-id":"call-composite-local-device-settings-microphone-button",checked:c,onToggleMicrophone:u,disabled:!o||!m,showLabel:!0,strings:t.mobileView?{tooltipOnContent:"",tooltipOffContent:"",tooltipDisabledContent:""}:{},styles:Yre(t.mobileView)}),e.createElement(j3,Object.assign({"data-ui-id":"call-composite-local-device-settings-camera-button"},r,{onToggleCamera:t.onToggleCamera,showLabel:!0,disabled:!l||!p||t.cameraLoading,strings:t.mobileView?{tooltipOnContent:"",tooltipOffContent:"",tooltipDisabledContent:"",tooltipVideoLoadingContent:""}:{},styles:Yre(t.mobileView)})),t.showDevicesButton&&e.createElement(U3,Object.assign({"data-ui-id":"call-composite-local-device-settings-options-button"},a,{disabled:!o&&!l&&h||g,showLabel:!0,strings:t.mobileView?{tooltipContent:""}:{},styles:C})))))};var Zre=SB((function(e,t){return ZH({root:[KV(e,{inset:1,highContrastStyle:{outlineOffset:"-4px",outline:"1px solid Window"},borderColor:"transparent"}),{height:24}]},t)})),Xre=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return _U(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(pJ,IU({},this.props,{styles:Zre(n,i),onRenderDescription:Fj}))},AU([XW("MessageBarButton",["theme","styles"],!0)],i)}(e.Component);const ese=e=>({root:{padding:"0.375rem 1.25rem",width:"3.75rem",height:"2rem",background:e.palette.white,border:`1px solid ${e.palette.neutralQuaternaryAlt}`,borderRadius:"0.063rem",color:e.palette.black}}),tse=(e,t)=>dB({textDecoration:t?"underline":"none",color:e.palette.themeDarkAlt,textDecorationColor:e.palette.themeDarkAlt,"@media (forced-colors: active)":{color:"LinkText",textDecorationColor:"LinkText"}}),ise=t=>{var i;const n=qK(),r=AK().strings.errorBar,s=null!==(i=t.strings)&&void 0!==i?i:r,[a,o]=(0,e.useState)([]),{onPermissionsTroubleshootingClick:l,onNetworkingTroubleshootingClick:c,permissionsState:d={camera:"denied",microphone:"denied"},troubleshootingGuideStrings:u}=t;(0,e.useEffect)((()=>o(MK(t.activeErrorMessages,a))),[t.activeErrorMessages,a]);const h=DK(t.activeErrorMessages,a);return e.createElement(Y$,{"data-ui-id":"notifications-stack"},h.map(((i,r)=>{const h=e.createElement("div",null,s[i.type]," ",l&&e.createElement(hJ,{onClick:()=>{l(d)}},e.createElement("span",{className:tse(n,!0)},u.devicePermissionLinkText))),g=e.createElement("div",null,s[i.type]," ",c&&e.createElement(hJ,{onClick:c,underline:!0},e.createElement("span",{className:tse(n,!0)},u.networkTroubleshootingLinkText)));return e.createElement(bK,Object.assign({},t,{styles:(p=kK(i.type),{innerText:{paddingTop:p===eK.warning?"0.15rem":"0.1rem",lineHeight:"none",alignSelf:"center",whiteSpace:"normal"},icon:{marginTop:"0.375rem",marginBottom:"0.375rem",paddingTop:"0.25rem"},content:{lineHeight:"inherit"},dismissal:{height:0,paddingTop:"0.8rem"}}),key:`${i.type} ${r}`,messageBarType:kK(i.type),messageBarIconProps:OK(i.type),actions:e.createElement(Xre,{text:u.dismissButtonText,styles:ese(n),onClick:()=>{o(RK(a,i))},ariaLabel:u.dismissButtonText}),isMultiline:!1,"aria-role":"alert","aria-live":"assertive"}),nse(i.type,h,g));var p})))},nse=(e,t,i)=>"callNetworkQualityLow"===e?i:t,rse=t=>{const{errorBarProps:i,showTroubleShootingErrorBar:n=!1,onPermissionsTroubleshootingClick:r,onNetworkingTroubleShootingClick:s,permissionsState:a}=t;return n?e.createElement(ise,Object.assign({troubleshootingGuideStrings:{devicePermissionLinkText:"Troubleshooting Camera and Microphone Permissions",networkTroubleshootingLinkText:"Troubleshooting Network Connection",dismissButtonText:"OK"},onPermissionsTroubleshootingClick:r,onNetworkingTroubleshootingClick:s,permissionsState:a},i,{onDismissError:t.onDismissError})):0===i.activeErrorMessages.length?e.createElement(e.Fragment,null):e.createElement(iq,{shouldFocusOnMount:!0},e.createElement(BK,Object.assign({},i,{onDismissError:t.onDismissError})))},sse={root:{marginTop:"auto",marginBottom:"auto",position:"relative"}},ase={root:{paddingBottom:"1rem"}},ose={root:{margin:"auto",textAlign:"center"}},lse={root:{zIndex:1,margin:"auto"}},cse=e=>({root:{color:e.palette.themeLighterAlt}}),dse={root:{fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28),paddingBottom:"1rem"}},use={root:{margin:"auto",fontWeight:400,paddingBottom:vJ(22)}},hse={root:{margin:"auto",fontWeight:600,textAlign:"inherit"}},gse={root:{paddingTop:"1.5rem",paddingBottom:"1.5rem",borderRadius:"0.5rem",marginBottom:vJ(22)},flexContainer:{position:"absolute",left:"1rem",right:"1rem",top:"0",bottom:"0"}},pse={childrenGap:"2rem"},mse=t=>{var i,n;const{appName:r,onTroubleshootingClick:s,onPrimaryButtonClick:a,strings:o}=t,l=qK(),c=a&&FK(null==o?void 0:o.primaryButtonText);return e.createElement(Y$,{style:{padding:"2rem",maxWidth:"25.375rem",alignSelf:"center"},"aria-label":null==o?void 0:o.ariaLabel},e.createElement(Y$,{styles:ase,horizontal:!0,horizontalAlign:"center",verticalFill:!0,tokens:pse},t.cameraIconName&&e.createElement(Y$,null,e.createElement(mG,{styles:lse,iconName:t.cameraIconName})),t.connectorIconName&&e.createElement(Y$,{styles:sse,horizontal:!0},e.createElement(mG,{styles:cse(l),iconName:t.connectorIconName})),t.microphoneIconName&&e.createElement(Y$,null,e.createElement(mG,{styles:lse,iconName:t.microphoneIconName}))),e.createElement(Y$,{styles:ose},o&&FK(null==o?void 0:o.primaryText)&&e.createElement(oJ,{styles:dse,role:"alert","aria-live":"assertive"},r?PK(o.primaryText,{appName:r}):o.primaryText),o&&FK(null==o?void 0:o.secondaryText)&&e.createElement(oJ,{styles:use},null==o?void 0:o.secondaryText),c&&e.createElement(mJ,{styles:e$(gse,null===(i=t.styles)||void 0===i?void 0:i.primaryButton),text:null==o?void 0:o.primaryButtonText,onClick:a,autoFocus:!0}),s&&FK(null==o?void 0:o.linkText)&&e.createElement(hJ,{styles:e$(hse,null===(n=t.styles)||void 0===n?void 0:n.troubleshootingLink),onClick:s,autoFocus:!c},null==o?void 0:o.linkText)))};function fse(t,i){const n=(0,e.useMemo)((()=>Object.assign(Object.assign({},t||{}),i||{})),[t,i]);if(t||i)return n}const vse=t=>{var i,n,r;const s=AK().strings,a=fse("denied"===t.kind?"safari"===t.browserHint?s.CameraAndMicrophoneSitePermissionsDeniedSafari:s.CameraAndMicrophoneSitePermissionsDenied:"request"===t.kind?s.CameraAndMicrophoneSitePermissionsRequest:s.CameraAndMicrophoneSitePermissionsCheck,t.strings),o=(null!==(i=t.microphoneIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionCameraDenied":"SitePermissionCamera",l=(null!==(n=t.microphoneIconName)&&void 0!==n?n:"denied"===t.kind)?"SitePermissionMicDenied":"SitePermissionMic",c=null!==(r=t.microphoneIconName)&&void 0!==r?r:"SitePermissionsSparkle";return e.createElement(mse,Object.assign({},t,{strings:a,cameraIconName:o,connectorIconName:c,microphoneIconName:l,onPrimaryButtonClick:t.onContinueAnywayClick}))},Sse=t=>{var i;const n=AK().strings,r=fse("denied"===t.kind?"safari"===t.browserHint?n.MicrophoneSitePermissionsDeniedSafari:n.MicrophoneSitePermissionsDenied:"request"===t.kind?n.MicrophoneSitePermissionsRequest:n.MicrophoneSitePermissionsCheck,t.strings),s=(null!==(i=t.microphoneIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionMicDenied":"SitePermissionMic";return e.createElement(mse,Object.assign({},t,{strings:r,cameraIconName:s,onPrimaryButtonClick:t.onContinueAnywayClick}))},yse=t=>{var i;const n=AK().strings,r=fse("denied"===t.kind?"safari"===t.browserHint?n.CameraSitePermissionsDeniedSafari:n.CameraSitePermissionsDenied:"request"===t.kind?n.CameraSitePermissionsRequest:n.CameraSitePermissionsCheck,t.strings),s=(null!==(i=t.cameraIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionCameraDenied":"SitePermissionCamera";return e.createElement(mse,Object.assign({},t,{strings:r,microphoneIconName:s,onPrimaryButtonClick:t.onContinueAnywayClick}))},Cse=t=>{const{mobileView:i,permissionsState:n,environmentInfo:r,isPermissionsModalDismissed:s,setIsPermissionsModalDismissed:a,onPermissionsTroubleshootingClick:o}=t,l=n.camera,c=n.microphone,d=!t.doNotPromptCamera&&"denied"===l||!t.doNotPromptCamera&&"prompt"===l||"denied"===c||"prompt"===c,u=JF(r),h=d?()=>"prompt"!==l||t.doNotPromptCamera||"prompt"!==c?"prompt"!==l||t.doNotPromptCamera?"prompt"===c?e.createElement(Sse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"request"}):"denied"!==l||t.doNotPromptCamera||"denied"!==c?"denied"!==l||t.doNotPromptCamera?e.createElement(Sse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"denied"}):e.createElement(yse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,onContinueAnywayClick:()=>{a(!1)},kind:"denied"}):e.createElement(vse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"denied"}):e.createElement(yse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,onContinueAnywayClick:()=>{a(!1)},kind:"request"}):e.createElement(vse,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"request"}):void 0;return i&&void 0!==h?e.createElement(e.Fragment,null,s&&e.createElement(j0,{disableMaxHeight:!0,onLightDismiss:()=>{},styles:pte(99)},h())):i||void 0===h?e.createElement(e.Fragment,null):e.createElement(c5,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:s,isBlocking:!1,onDismiss:()=>{a(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}},forceFocusInsideTrap:!0,focusTrapZoneProps:{disabled:!1,onKeyDown:e=>{"Escape"===e.key&&a(!1)}}},h())},Tse=t=>{const{mobileView:i,checkPermissionModalShowing:n,permissionsState:r,environmentInfo:s,isPermissionsModalDismissed:a,setIsPermissionsModalDismissed:o,onPermissionsTroubleshootingClick:l}=t,c=()=>{},d=r.camera,u=r.microphone,h="denied"===d||"denied"===u,g=JF(s),p=h?()=>"denied"===d&&"denied"===u?e.createElement(vse,{appName:"app",browserHint:g?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"denied"}):"denied"===d&&"granted"===u?e.createElement(yse,{appName:"app",browserHint:g?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,onContinueAnywayClick:()=>{o(!1)},kind:"denied"}):e.createElement(Sse,{appName:"app",browserHint:g?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"denied"}):void 0;return i?e.createElement(e.Fragment,null,(n||"prompt"===u||"prompt"===d)&&e.createElement(j0,{disableMaxHeight:!0,onLightDismiss:c,styles:pte(99)},e.createElement(vse,{appName:"app",browserHint:g?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"check"})),a&&!n&&void 0!==p&&e.createElement(j0,{disableMaxHeight:!0,onLightDismiss:c,styles:pte(99)},p())):e.createElement(e.Fragment,null,(n||"prompt"===u||"prompt"===d)&&e.createElement(c5,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:a,isBlocking:!1,onDismiss:()=>{o(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}}},e.createElement(vse,{appName:"app",browserHint:g?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"check"})),!n&&void 0!==p&&e.createElement(c5,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:a,isBlocking:!1,onDismiss:()=>{o(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}}},p()))},Ese=t=>{const{width:i,text:n,lineHeightPx:r,bufferHeightPx:s,role:a}=t,o=(0,e.useRef)(null),l=(0,e.useRef)(null),c=(0,e.useRef)(null),[d,u]=(0,e.useState)(0);return(0,e.useLayoutEffect)((()=>{if(n&&l.current&&c.current){const e=bse(l.current,c.current,i,r);u(e*r)}}),[i,r,n]),e.createElement("svg",{"aria-level":1,role:a,width:i,height:d+s,ref:o,xmlns:"http://www.w3.org/2000/svg"},e.createElement("text",{height:0,ref:l,style:{visibility:"hidden"}},n),e.createElement("text",{ref:c,x:"0",y:s/4,role:"heading","aria-level":1}))},bse=(e,t,i,n)=>{var r,s;const a=null!==(s=null===(r=e.textContent)||void 0===r?void 0:r.split(" "))&&void 0!==s?s:[];if(0===a.length||""===a[0])throw new Error("Text element must contain text");let o="",l=0;t.textContent="";for(let r=0;r<a.length;r++){const s=o+a[r]+" ";if(e.getSubStringLength(0,s.length)>i&&r>0){const e=_se(o,n);t.appendChild(e),o=a[r]+" ",l++}else o=s}const c=_se(o,n);return t.appendChild(c),l++,l},_se=(e,t)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","tspan");return i.textContent=e,i.setAttribute("x","50%"),i.setAttribute("dy",`${t}px`),i.setAttribute("text-anchor","middle"),i};var Ise=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};const wse=t=>{var i;const{startCallHandler:n,mobileView:r,modalLayerHostId:s,deviceChecks:a,onPermissionsTroubleshootingClick:o,onNetworkingTroubleShootingClick:l,joinCallOptions:c={microphoneCheck:"requireMicrophoneAvailable"}}=t,d=aJ(),u=a7(r7(U3)),h=K7(),{video:g,audio:p}=u7(jre),[m,f]=(0,e.useState)(void 0),[v,S]=(0,e.useState)(void 0);((e,t)=>{UF(void 0,void 0,void 0,(function*(){const[i,n]=yield Promise.all([UF(void 0,void 0,void 0,(function*(){try{return(yield navigator.permissions.query({name:"camera"})).state}catch(e){return console.info("permissions API is not supported by browser",e),"unsupported"}})),UF(void 0,void 0,void 0,(function*(){try{return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){return console.info("permissions API is not supported by browser",e),"unsupported"}}))]);e(i),t(n)}))})(f,S);const y=(0,e.useRef)(null),C=y0(y),T=!!C&&C<450,E=Y7(BK),b=u7(f7),_=u7(I7);let I=(!p||0===(null==b?void 0:b.length))&&"requireMicrophoneAvailable"===c.microphoneCheck;const w=u7(S7),A=u7(Fie).isAvailable,[P,R]=(0,e.useState)(!1),M=(0,e.useCallback)(((e,t)=>Ise(void 0,void 0,void 0,(function*(){R(A);try{yield h.onSelectCamera(e,t)}finally{R(!1)}}))),[h,A]),{onToggleCamera:D}=Y7(j3),k=(0,e.useCallback)((e=>Ise(void 0,void 0,void 0,(function*(){R(!A);try{yield D(e)}finally{R(!1)}}))),[A,D]);let O=t.latestErrors;"Consumer"!==w&&(O=O.filter((e=>"callCameraAccessDenied"!==e.type&&"callCameraAccessDeniedSafari"!==e.type))),!Vte("videoeffects")&&A||!E||(O=O.filter((e=>"unableToStartVideoEffect"!==e.type))),"Consumer"===w&&(I=!1);const N=u7(v7);a&&(["doNotPrompt","optional"].includes(a.camera)&&["doNotPrompt","optional"].includes(a.microphone)?I=!1:"required"===a.camera&&(I=!g||0===(null==N?void 0:N.length)));const L=PJ(),x=L.strings.call.configurationPageTitle.length>0?e.createElement(Y$.Item,{className:r?yre(d):Sre(d)},e.createElement(Ese,{width:r?325:445,lineHeightPx:24,bufferHeightPx:16,text:L.strings.call.configurationPageTitle,role:"heading"})):e.createElement(e.Fragment,null),F=L.strings.call.configurationPageCallDetails&&e.createElement(Y$.Item,{className:r?_re(d):bre(d)},L.strings.call.configurationPageCallDetails),U=r&&"Consumer"!==w,B={camera:m&&"unsupported"!==m?!1!==g?m:"denied":!1!==g?g?"granted":"prompt":"denied",microphone:v&&"unsupported"!==v?!1!==p?v:"denied":!1!==p?p?"granted":"prompt":"denied"},V=E.activeErrorMessages.filter((e=>"callNetworkQualityLow"===e.type)),[H,$]=(0,e.useState)(!0),[j,G]=(0,e.useState)(!1);setTimeout((()=>{G(!0)}),2e3);const q=!j,{toggleVideoEffectsPane:z,closeVideoEffectsPane:W,isVideoEffectsPaneOpen:K}=$ie(t.updateSidePaneRenderer,r,t.latestErrors,t.onDismissError),J=(0,e.useCallback)((()=>Ise(void 0,void 0,void 0,(function*(){W(),n()}))),[n,W]),Y=(0,e.useMemo)((()=>({hostId:s})),[s]),Q=(0,e.useMemo)((()=>Object.assign(Object.assign({},E),{activeErrorMessages:O})),[E,O]),Z=(0,e.useMemo)((()=>{var e,i,n;return{display:"flex",flexFlow:"column",height:"100%",position:"relative",width:"100%",padding:(i=!r)?"2rem 1rem 2rem 1rem":"1rem 1rem 2rem 1rem",minWidth:i?"20rem":"16rem",minHeight:i?"22rem":"13rem","::before":(n=null===(e=t.backgroundImage)||void 0===e?void 0:e.url)?Object.assign({content:'""',position:"absolute",top:0,left:0,zIndex:0,width:"100%",height:"100%",backgroundImage:`url(${n})`,backgroundSize:"cover",backgroundPosition:"center"},EV.fadeIn500):void 0}}),[r,null===(i=t.backgroundImage)||void 0===i?void 0:i.url]);return e.createElement("div",{ref:y,className:dB(Z)},e.createElement(Y$,{styles:F9},e.createElement(rse,{showTroubleShootingErrorBar:!g||!p||V.length>0,permissionsState:B,onNetworkingTroubleShootingClick:l,onPermissionsTroubleshootingClick:o,errorBarProps:Q,onDismissError:t.onDismissError})),m&&"unsupported"!==m&&v&&"unsupported"!==v&&e.createElement(Cse,{modalLayerHostId:s,mobileView:r,environmentInfo:_,permissionsState:B,isPermissionsModalDismissed:H,setIsPermissionsModalDismissed:$,onPermissionsTroubleshootingClick:o,doNotPromptCamera:"doNotPrompt"===(null==a?void 0:a.camera)}),m&&v&&("unsupported"===m||"unsupported"===v)&&e.createElement(Tse,{modalLayerHostId:s,mobileView:r,checkPermissionModalShowing:q,permissionsState:B,isPermissionsModalDismissed:H,environmentInfo:_,setIsPermissionsModalDismissed:$,onPermissionsTroubleshootingClick:o}),e.createElement(Y$,{verticalFill:!0,grow:!0,horizontal:!0,className:Dre},e.createElement(Y$,{className:(X=U,ee=!!t.logo,dB({width:"100%",position:"relative",height:`calc(100% - ${!X&&ee?"3rem":"0rem"})`})),verticalAlign:T&&!r?void 0:"center",verticalFill:U,tokens:U?pre:gre},e.createElement(Y$.Item,{styles:Tre},e.createElement(Rse,{logo:t.logo}),x,F),e.createElement(Y$,{horizontal:Mse(U,r,T),horizontalAlign:U?"stretch":"center",verticalFill:U,tokens:mre},"Consumer"!==w&&e.createElement(Qre,{mobileView:U,showDevicesButton:r,onToggleCamera:k,cameraLoading:P&&!A}),e.createElement(Y$,{styles:r?void 0:fre},!U&&e.createElement(Y$,{className:r?void 0:vre(d,JF(_))},e.createElement(Fre,Object.assign({},u,h,{onSelectCamera:M,cameraPermissionGranted:Ase(g,m),microphonePermissionGranted:Pse(p,v),onClickEnableDevicePermission:()=>{$(!0)},onClickVideoEffects:z}))),e.createElement(Y$,{styles:U?wre:Ire,horizontalAlign:U?"stretch":"end"},e.createElement($re,{className:U?Are:Pre,onClick:J,disabled:I,hideIcon:!0}))))),e.createElement(U4,{isOpen:K,hasCloseButton:!1,isBlocking:!1,isHiddenOnDismiss:!1,styles:kre,focusTrapZoneProps:Ore,layerProps:Y,type:y4.custom,customWidth:"17.5rem"},e.createElement($te,{ariaLabel:K?L.strings.call.videoEffectsPaneAriaLabel:void 0,mobileView:t.mobileView,updateSidePaneRenderer:t.updateSidePaneRenderer,maxWidth:"17.5rem",minWidth:"17.5rem"}))));var X,ee},Ase=(e,t)=>t&&"unsupported"!==t?"granted"===t:e,Pse=(e,t)=>t&&"unsupported"!==t?"granted"===t:e,Rse=t=>{return t.logo?e.createElement(lG,{styles:(i=t.logo.shape,{root:{overflow:"initial",display:"flex",justifyContent:"center"},image:{height:"3rem",borderRadius:"circle"===i?"100%":void 0,aspectRatio:"circle"===i?"1 / 1":void 0,objectFit:"circle"===i?"cover":void 0}}),src:t.logo.url,alt:t.logo.alt}):e.createElement(e.Fragment,null);var i},Mse=(e,t,i)=>!(i&&!t||e),Dse={maxWidth:"22.5rem",margin:"1rem"},kse={childrenGap:"0.5rem"},Ose={root:{paddingTop:"1.125rem",borderRadius:"0.25rem"}},Nse={fontSize:"1.25rem",fontWeight:600},Lse={fontSize:"1rem"};function xse(t){const i=LZ(),n=u7(M7);return e.createElement(Y$,{className:dB(t.pageStyle),verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":t.dataUiId,"aria-atomic":!0},e.createElement(Y$,{className:dB(Dse),tokens:kse},t.iconName&&e.createElement(bZ,{iconName:t.iconName}),e.createElement(oJ,{className:dB(Nse),"aria-live":"assertive",role:"alert"},t.title),e.createElement(oJ,{className:dB(Lse),"aria-live":"assertive"},t.moreDetails),!t.disableStartCallButton&&e.createElement(Y$,{styles:Ose},e.createElement($re,{onClick:()=>{n&&n.length>0?i.startCall(n):i.joinCall()},disabled:!1,rejoinCall:!0,autoFocus:!0}))))}const Fse={margin:"1rem"},Use=(e,t)=>({fontSize:"1rem",color:t?"white":e.themePrimary,textAlign:"center"}),Bse=(e,t)=>({fontSize:"0.75rem",color:t?"white":e.themePrimary,textAlign:"center"}),Vse={root:{position:"absolute",top:"0rem",right:"0rem"}},Hse=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,s=u7(Pne),a=K7(),o=aJ().palette,l=K7();return e.createElement(Hne,Object.assign({localParticipantVideoStream:t.localParticipantVideoStream,overlayContent:t.overlayProps?e.createElement(Y$,{verticalFill:!0,horizontalAlign:"center",verticalAlign:"center",className:dB(Fse),"aria-atomic":!0},t.showLocalVideoCameraCycleButton&&r&&e.createElement(Y$.Item,{styles:Vse},e.createElement(Y1,Object.assign({},a,s,{size:"large"}))),e.createElement(Y$.Item,{className:dB(Use(o,r))},t.overlayProps.overlayIcon),e.createElement(oJ,{className:dB(Use(o,r)),"aria-live":"assertive","data-ui-id":"lobbyScreenTitle",role:"alert"},t.overlayProps.title),t.overlayProps.moreDetails&&e.createElement(oJ,{className:dB(Bse(o,r)),"aria-live":"assertive"},t.overlayProps.moreDetails)):void 0},l))},$se=t=>{var i,n,r,s,a,o,l,c;const d=Y7(BK),u=u7(Yne),h=PJ().strings.call,g="InLobby"===u7(g7),p=null!==(i=u7(_7))&&void 0!==i?i:{};let m=t.mobileView?$F(null===(n=t.options)||void 0===n?void 0:n.callControls):null===(r=t.options)||void 0===r?void 0:r.callControls;return m=zF(m,["screenShareButton","participantsButton"]),e.createElement(Ine,{complianceBannerProps:{strings:h},errorBarProps:!1!==(null===(s=t.options)||void 0===s?void 0:s.errorBar)&&d,showErrorNotifications:null===(o=null===(a=t.options)||void 0===a?void 0:a.errorBar)||void 0===o||o,callControlProps:{options:m,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(Hse,Object.assign({},u,{showLocalVideoCameraCycleButton:t.mobileView,overlayProps:jse(h,g,Object.values(p))})),dataUiId:"lobby-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError,latestNotifications:t.latestNotifications,onDismissNotification:t.onDismissNotification,doNotShowCameraAccessNotifications:"doNotPrompt"===(null===(c=null===(l=t.options)||void 0===l?void 0:l.deviceChecks)||void 0===c?void 0:c.camera)})},jse=(e,t,i)=>{const n=i[0]&&["Ringing","Connecting"].includes(i[0].state)&&1===i.length?i[0]:void 0;return t?qse(e):n?zse(e,n):Gse(e)},Gse=t=>({title:t.lobbyScreenConnectingToCallTitle,moreDetails:t.lobbyScreenConnectingToCallMoreDetails,overlayIcon:e.createElement(bZ,{iconName:"LobbyScreenConnectingToCall"})}),qse=t=>({title:t.lobbyScreenWaitingToBeAdmittedTitle,moreDetails:t.lobbyScreenWaitingToBeAdmittedMoreDetails,overlayIcon:e.createElement(bZ,{iconName:"LobbyScreenWaitingToBeAdmitted"})}),zse=(e,t)=>{var i;return YN(t.identifier)?{title:t.identifier.phoneNumber,moreDetails:e.outboundCallingNoticeString}:{title:null!==(i=e.outboundCallingNoticeString)&&void 0!==i?i:""}},Wse={width:"100%",height:"100%"},Kse={opacity:.4},Jse={position:"absolute",top:"0",left:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",objectPosition:"center",objectFit:"cover",zIndex:0},Yse={width:"100%",position:"absolute",top:"50%",transform:"translate(0, -50%)",display:"flex",justifyContent:"center"},Qse={root:{margin:"auto"}},Zse={textAlign:"center",fontSize:"1.5rem",fontWeight:400},Xse={circle:{borderWidth:"0.125rem"}},eae={textAlign:"center",fontSize:"1rem"},tae=t=>{var i,n,r,s,a,o,l,c,d;const u=Y7(BK),h=PJ().strings.call,g=u7(_7),p=u7(C7),[m,f]=(0,e.useState)(void 0),v=t.mobileView?$F(null===(i=t.options)||void 0===i?void 0:i.callControls):null===(n=t.options)||void 0===n?void 0:n.callControls,S=(0,e.useMemo)((()=>{var e;return g?null===(e=Object.values(g))||void 0===e?void 0:e[0]:void 0}),[g]),y=(0,e.useMemo)((()=>{var e;return(null==p?void 0:p.remoteParticipants)?null===(e=Object.values(p.remoteParticipants))||void 0===e?void 0:e[0]:void 0}),[p]),C=(0,e.useMemo)((()=>p&&(null==y?void 0:y.displayName)?"transferTarget":"transferor"),[p,null==y?void 0:y.displayName]);(0,e.useEffect)((()=>{f(h.transferPageNoticeString)}),[h.transferPageNoticeString]);let T=S;"transferTarget"===C&&(T=y);let E=null!==(r=null==S?void 0:S.displayName)&&void 0!==r?r:h.transferPageUnknownTransferorDisplayName;return"transferTarget"===C&&(E=null!==(s=null==y?void 0:y.displayName)&&void 0!==s?s:h.transferPageUnknownTransferTargetDisplayName),e.createElement(Y$,{className:dB(Wse)},e.createElement(J0,{announcementString:m,ariaLive:"polite"}),e.createElement(Ine,{complianceBannerProps:{strings:h},errorBarProps:!1!==(null===(a=t.options)||void 0===a?void 0:a.errorBar)&&u,showErrorNotifications:null===(l=null===(o=t.options)||void 0===o?void 0:o.errorBar)||void 0===l||l,callControlProps:{options:v,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(iae,{userId:T?iL(null==T?void 0:T.identifier):void 0,displayName:E,initialsName:E,statusText:"transferTarget"===C?h.transferPageTransferTargetText:h.transferPageTransferorText,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData}),dataUiId:"transfer-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError,onDismissNotification:t.onDismissNotification,latestNotifications:t.latestNotifications,doNotShowCameraAccessNotifications:"doNotPrompt"===(null===(d=null===(c=t.options)||void 0===c?void 0:c.deviceChecks)||void 0===d?void 0:d.camera)}))},iae=t=>{const{displayName:i,initialsName:n,userId:r,onFetchAvatarPersonaData:s,statusText:a}=t,[o,l]=(0,e.useState)(),c=(0,e.useRef)(null),d=(0,e.useRef)(new ResizeObserver((e=>{if(!e[0])return;const{width:t,height:i}=e[0].contentRect,n=Math.min(t,i)/2;l(Math.max(Math.min(n,150),32))})));(0,e.useLayoutEffect)((()=>{c.current&&d.current.observe(c.current);const e=d.current;return()=>e.disconnect()}),[d,c]);const u=(0,e.useMemo)((()=>({userId:r,text:null!=n?n:i,coinSize:o,styles:Qse,hidePersonaDetails:!0})),[r,n,i,o]),h=(0,e.useCallback)((()=>o?e.createElement(h0,Object.assign({},u,{dataProvider:s,className:dB(Kse)})):e.createElement(e.Fragment,null)),[u,s,o]),g=(0,e.useMemo)((()=>h()),[h]);return e.createElement("div",{ref:c,className:dB(Jse),"data-is-focusable":!0},e.createElement(Y$,{className:dB(Yse),tokens:{childrenGap:"1rem"}},e.createElement(Y$,{horizontalAlign:"center",tokens:{childrenGap:"0.5rem"}},g,e.createElement(oJ,{className:dB(Zse)},i)),e.createElement(Y$,{horizontal:!0,horizontalAlign:"center",verticalAlign:"center",tokens:{childrenGap:"0.5rem"}},e.createElement(yZ,{size:gZ.large,className:dB(Xse)}),e.createElement(oJ,{className:dB(eae)},a))))},nae={root:{borderRadius:vJ(4),padding:`${vJ(6)} ${vJ(20)} `},label:{fontWeight:400,display:"flex",fontSize:vJ(14)},labelDisabled:{fontWeight:400,display:"flex",fontSize:vJ(14)}},rae={root:{color:"inherit",fontWeight:600,fontHeight:vJ(22),fontSize:vJ(16),marginTop:"0.5rem",marginBottom:"1.5rem"}},sae={root:{color:"inherit",fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28),margin:"auto"}},aae={root:{width:"100%",height:"100%",background:"inherit"}},oae={root:{display:"flex",margin:"auto",flexDirection:"column",justifyContent:"center",alignContent:"center",alignItems:"center"}};const lae=()=>{var t,i,n,r,s;const a=Y7(F6),o=PJ(),l={holdScreenLabel:null!==(t=o.strings.call.holdScreenLabel)&&void 0!==t?t:"",resumeCallButtonLabel:null!==(i=o.strings.call.resumeCallButtonLabel)&&void 0!==i?i:"",resumeCallButtonAriaLabel:null!==(n=o.strings.call.resumeCallButtonAriaLabel)&&void 0!==n?n:"",resumingCallButtonLabel:null!==(r=o.strings.call.resumingCallButtonLabel)&&void 0!==r?r:"",resumingCallButtonAriaLabel:null!==(s=o.strings.call.resumingCallButtonAriaLabel)&&void 0!==s?s:""},[c,d]=(0,e.useState)(0),u=uae(c),h=(0,e.useRef)(performance.now()),[g,p]=(0,e.useState)(!1);return e.useEffect((()=>{const e=setInterval((()=>{d(performance.now()-h.current)}),10);return()=>{clearInterval(e)}}),[h]),e.createElement(Y$,{styles:aae},e.createElement(Y$,{horizontal:!0,styles:oae},e.createElement(oJ,{styles:sae},u),e.createElement(oJ,{styles:rae,role:"alert","aria-live":"assertive"},l.holdScreenLabel),e.createElement(mJ,{text:g?l.resumingCallButtonLabel:l.resumeCallButtonLabel,ariaLabel:g?l.resumingCallButtonAriaLabel:l.resumeCallButtonAriaLabel,styles:nae,disabled:g,onClick:()=>{return e=void 0,t=void 0,n=function*(){p(!0);try{yield a.onToggleHold()}catch(e){throw p(!1),e}},new((i=void 0)||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n},"data-ui-id":"hold-page-resume-call-button",autoFocus:!0})))},cae=e=>Math.floor(dae(e)/60),dae=e=>Math.floor(e/1e3),uae=e=>{const t=(e=>Math.floor(cae(e)/60))(e);return`${t>0?t+":":""}${("0"+cae(e)%60).slice(-2)}:${("0"+dae(e)%60).slice(-2)}`},hae=t=>{var i,n,r,s,a,o,l;const c=Y7(BK),d=PJ().strings.call;let u=t.mobileView?$F(null===(i=t.options)||void 0===i?void 0:i.callControls):null===(n=t.options)||void 0===n?void 0:n.callControls;return u=zF(u,["cameraButton","microphoneButton","devicesButton","screenShareButton","holdButton"]),e.createElement(Ine,{complianceBannerProps:{strings:d},errorBarProps:!1!==(null===(r=t.options)||void 0===r?void 0:r.errorBar)&&c,showErrorNotifications:null===(a=null===(s=t.options)||void 0===s?void 0:s.errorBar)||void 0===a||a,callControlProps:{options:u,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(lae,null),dataUiId:"hold-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,latestNotifications:t.latestNotifications,onDismissError:t.onDismissError,onDismissNotification:t.onDismissNotification,doNotShowCameraAccessNotifications:"doNotPrompt"===(null===(l=null===(o=t.options)||void 0===o?void 0:o.deviceChecks)||void 0===l?void 0:l.camera)})},gae={root:{fontWeight:600,fontSize:vJ(20),lineHeight:vJ(28),margin:"auto",textAlign:"center",padding:"0.5rem"}},pae={root:{margin:"auto",fontWeight:400,textAlign:"center"}},mae={root:{margin:"auto"}},fae={root:{margin:"auto",fontWeight:600,textAlign:"center"}},vae={root:{maxWidth:vJ(375),padding:"2rem"}},Sae=e=>({root:{backgroundColor:"#C4314B",borderColor:e.palette.neutralLight,color:e.palette.white,padding:"1rem",height:"32px"}}),yae=t=>{const{onTroubleshootingClick:i,strings:n,onContinueAnywayClick:r}=t,s=aJ();return e.createElement(Y$,{styles:vae,tokens:{childrenGap:"2rem"}},e.createElement(mG,{iconName:"UnsupportedEnvironmentWarning","data-ui-id":"unsupported-environment-icon"}),e.createElement(Y$,{styles:mae,tokens:{childrenGap:"0.25rem"}},e.createElement(oJ,{styles:gae},null==n?void 0:n.primaryText),e.createElement(oJ,{styles:pae},null==n?void 0:n.secondaryText)),i&&e.createElement(hJ,{styles:fae,onClick:i,"data-ui-id":"unsupported-environment-link"},null==n?void 0:n.moreHelpLinkText),r&&e.createElement(pJ,{"data-ui-id":"allowUnsupportedBrowserButton",styles:Sae(s),onClick:r},null==n?void 0:n.continueAnywayButtonText))},Cae=t=>e.createElement(yae,Object.assign({},t)),Tae=t=>{const{onTroubleshootingClick:i,strings:n}=t,r=AK();return e.createElement(Cae,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},Eae(r)),n)})},Eae=e=>e.strings.UnsupportedOperatingSystem,bae=t=>{const{onTroubleshootingClick:i,strings:n}=t,r=AK();return e.createElement(Cae,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},_ae(r)),n)})},_ae=e=>e.strings.UnsupportedBrowser,Iae=t=>{const{onTroubleshootingClick:i,strings:n,onContinueAnywayClick:r}=t,s=AK();return e.createElement(Cae,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},wae(s)),n),onContinueAnywayClick:r})},wae=e=>e.strings.UnsupportedBrowserVersion,Aae=t=>{const{onTroubleshootingClick:i,environmentInfo:n}=t,r=LZ(),s=()=>{r.allowUnsupportedBrowserVersion()},a=PJ(),o=a.component.strings.UnsupportedBrowser,l=a.component.strings.UnsupportedBrowserVersion,c=a.component.strings.UnsupportedOperatingSystem;let d=e.createElement(e.Fragment,null);if(null==n?void 0:n.isSupportedPlatform)if(null==n?void 0:n.isSupportedBrowser){if(null==n?void 0:n.isSupportedBrowserVersion)throw new Error("There was a problem with your environment info");d=e.createElement(Iae,{onTroubleshootingClick:i,strings:l,onContinueAnywayClick:s})}else d=e.createElement(bae,{onTroubleshootingClick:i,strings:o});else d=e.createElement(Tae,{onTroubleshootingClick:i,strings:c});return e.createElement(Y$,{styles:Pae},d)},Pae={root:{margin:"auto",paddingTop:"3rem"}},Rae=(e,t)=>e.filter((e=>{const i=t[e.type];return!i||!i.lastDismissedAt||i.lastDismissedAt<i.mostRecentlyActive})),Mae=(e,t)=>{var i,n;const r={};for(const s of t){const t=e[s.type];r[s.type]={mostRecentlyActive:null!==(n=null!==(i=s.timestamp)&&void 0!==i?i:null==t?void 0:t.mostRecentlyActive)&&void 0!==n?n:new Date(Date.now()),lastDismissedAt:null==t?void 0:t.lastDismissedAt}}return r},Dae=(e,t)=>{const i=new Date(Date.now()),n=t[e];return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},n||{}),{lastDismissedAt:i})})},kae=G6([v7,f7],((e,t)=>({camerasCount:e.length,microphonesCount:t.length}))),Oae=G6([e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.latestCapabilitiesChangeInfo},S7],((e,t)=>({capabilitiesChangeInfo:e,participantRole:t})));var Nae={root:"ms-RatingStar-root",rootIsSmall:"ms-RatingStar-root--small",rootIsLarge:"ms-RatingStar-root--large",ratingStar:"ms-RatingStar-container",ratingStarBack:"ms-RatingStar-back",ratingStarFront:"ms-RatingStar-front",ratingButton:"ms-Rating-button",ratingStarIsSmall:"ms-Rating--small",ratingStartIsLarge:"ms-Rating--large",labelText:"ms-Rating-labelText",ratingFocusZone:"ms-Rating-focuszone"};function Lae(e,t){var i;return{color:e,selectors:(i={},i[UV]={color:t},i)}}var xae,Fae=/[\{\}]/g,Uae=/\{\d+\}/g;!function(e){e[e.Small=0]="Small",e[e.Large=1]="Large"}(xae||(xae={}));var Bae=oj(),Vae=function(t){return e.createElement("div",{className:t.classNames.ratingStar},e.createElement(mG,{className:t.classNames.ratingStarBack,iconName:0===t.fillPercentage||100===t.fillPercentage?t.icon:t.unselectedIcon}),!t.disabled&&e.createElement(mG,{className:t.classNames.ratingStarFront,iconName:t.icon,style:{width:t.fillPercentage+"%"}}))},Hae=function(e,t){return"".concat(e,"-star-").concat(t-1)},$ae=e.forwardRef((function(t,i){var n=g$("Rating"),r=g$("RatingLabel"),s=t.ariaLabel,a=t.ariaLabelFormat,o=t.disabled,l=t.getAriaLabel,c=t.styles,d=t.min,u=void 0===d?t.allowZeroStars?0:1:d,h=t.max,g=void 0===h?5:h,p=t.readOnly,m=t.size,f=t.theme,v=t.icon,S=void 0===v?"FavoriteStarFill":v,y=t.unselectedIcon,C=void 0===y?"FavoriteStar":y,T=t.onRenderStar,E=Math.max(u,0),b=V4(t.rating,t.defaultRating,t.onChange),_=b[0],I=b[1],w=function(e,t,i){return Math.min(Math.max(null!=e?e:t,t),i)}(_,E,g);!function(t,i){e.useImperativeHandle(t,(function(){return{rating:i}}),[i])}(t.componentRef,w);var A=e.useRef(null),P=nG(A,i);qj(A);for(var R=B$(t,U$),M=Bae(c,{disabled:o,readOnly:p,theme:f}),D=null==l?void 0:l(w,g),k=s||D,O=[],N=function(t){var i,s,l=function(e,t){var i=Math.ceil(t),n=100;return e===t?n=100:e===i?n=t%1*100:e>i&&(n=0),n}(t,w);O.push(e.createElement("button",IU({className:V$(M.ratingButton,m===xae.Large?M.ratingStarIsLarge:M.ratingStarIsSmall),id:Hae(n,t),key:t},t===Math.ceil(w)&&{"data-is-current":!0},{onKeyDown:function(e){var i=e.which,n=t;switch(i){case Tj:case Ej:n=Math.min(g,n+1);break;case yj:case Cj:n=Math.max(1,n-1);break;case 36:case 33:n=1;break;case 35:case 34:n=g}n===t||void 0!==_&&Math.ceil(_)===n||I(n,e)},onClick:function(e){void 0!==_&&Math.ceil(_)===t||I(t,e)},disabled:!(!o&&!p),role:"radio","aria-hidden":p?"true":void 0,type:"button","aria-checked":t===Math.ceil(w)}),e.createElement("span",{id:"".concat(r,"-").concat(t),className:M.labelText},function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=t;return e.replace(Uae,(function(e){var t=n[e.replace(Fae,"")];return null==t&&(t=""),t}))}(a||"",t,g)),(i={fillPercentage:l,disabled:o,classNames:M,icon:l>0?S:C,starNum:t,unselectedIcon:C},(s=T)?s(i):e.createElement(Vae,IU({},i)))))},L=1;L<=g;L++)N(L);var x=m===xae.Large?M.rootIsLarge:M.rootIsSmall;return e.createElement("div",IU({ref:P,className:V$("ms-Rating-star",M.root,x),"aria-label":p?void 0:k,id:n,role:p?void 0:"radiogroup"},R),e.createElement(iq,IU({direction:yG.bidirectional,className:V$(M.ratingFocusZone,x),defaultActiveElement:"#"+Hae(n,Math.ceil(w))},p&&{allowFocusRoot:!0,disabled:!0,role:"textbox","aria-label":D,"aria-readonly":!0,"data-is-focusable":!0,tabIndex:0}),O))}));$ae.displayName="RatingBase";var jae=nj($ae,(function(e){var t=e.disabled,i=e.readOnly,n=e.theme,r=n.semanticColors,s=n.palette,a=FV(Nae,n),o=s.neutralSecondary,l=s.themePrimary,c=s.themeDark,d=s.neutralPrimary,u=r.disabledBodySubtext;return{root:[a.root,n.fonts.medium,!t&&!i&&{selectors:{"&:hover":{selectors:{".ms-RatingStar-back":Lae(d,"Highlight")}}}}],rootIsSmall:[a.rootIsSmall,{height:"32px"}],rootIsLarge:[a.rootIsLarge,{height:"36px"}],ratingStar:[a.ratingStar,{display:"inline-block",position:"relative",height:"inherit"}],ratingStarBack:[a.ratingStarBack,{color:o,width:"100%"},t&&Lae(u,"GrayText")],ratingStarFront:[a.ratingStarFront,{position:"absolute",height:"100 %",left:"0",top:"0",textAlign:"center",verticalAlign:"middle",overflow:"hidden"},Lae(d,"Highlight")],ratingButton:[KV(n),a.ratingButton,{backgroundColor:"transparent",padding:"".concat(8,"px ").concat(2,"px"),boxSizing:"content-box",margin:"0px",border:"none",cursor:"pointer",selectors:{"&:disabled":{cursor:"default"},"&[disabled]":{cursor:"default"}}},!t&&!i&&{selectors:{"&:hover ~ .ms-Rating-button":{selectors:{".ms-RatingStar-back":Lae(o,"WindowText"),".ms-RatingStar-front":Lae(o,"WindowText")}},"&:hover":{selectors:{".ms-RatingStar-back":{color:l},".ms-RatingStar-front":{color:c}}}}},t&&{cursor:"default"}],ratingStarIsSmall:[a.ratingStarIsSmall,{fontSize:"16px",lineHeight:"16px",height:"16px"}],ratingStarIsLarge:[a.ratingStartIsLarge,{fontSize:"20px",lineHeight:"20px",height:"20px"}],labelText:[a.labelText,LV],ratingFocusZone:[KV(n),a.ratingFocusZone,{display:"inline-block"}]}}),void 0,{scope:"Rating"});const Gae=e=>dB({fontWeight:600,fontSize:vJ(16),lineHeight:vJ(20),color:e.palette.neutralPrimary,paddingTop:vJ(24)}),qae=e=>dB({fontWeight:400,fontSize:vJ(12),lineHeight:vJ(12),color:e.palette.themePrimary,marginBottom:vJ(8),marginTop:vJ(8),textAlign:"center"}),zae=e=>({root:{textAlign:"center",height:"auto",marginTop:vJ(8)},ratingStarIsLarge:{height:"auto",padding:0},ratingStar:{transform:"scale(1.4)",margin:vJ(6),height:"auto"},ratingStarFront:{color:e.palette.themePrimary}}),Wae=dB({paddingBottom:vJ(6)}),Kae=t=>{const{onStarRatingSelected:i,selectedIcon:n,unselectedIcon:r,strings:s}=t,[a,o]=(0,e.useState)(0),[l,c]=(0,e.useState)(""),d=qK(),u=(0,e.useCallback)(((e,t)=>{if(t){switch(o(t),t){case 1:c(null==s?void 0:s.starSurveyOneStarText);break;case 2:c(null==s?void 0:s.starSurveyTwoStarText);break;case 3:c(null==s?void 0:s.starSurveyThreeStarText);break;case 4:c(null==s?void 0:s.starSurveyFourStarText);break;case 5:c(null==s?void 0:s.starSurveyFiveStarText)}null==i||i(t)}}),[null==s?void 0:s.starSurveyOneStarText,null==s?void 0:s.starSurveyTwoStarText,null==s?void 0:s.starSurveyThreeStarText,null==s?void 0:s.starSurveyFourStarText,null==s?void 0:s.starSurveyFiveStarText,i]);return e.createElement(Y$,{verticalAlign:"center"},e.createElement(Y$,{className:Wae},e.createElement(oJ,{className:Gae(d)},null==s?void 0:s.starSurveyHelperText)),e.createElement(jae,{max:5,size:xae.Large,defaultRating:0,allowZeroStars:!0,rating:a,onChange:u,styles:zae(d),icon:null!=n?n:"SurveyStarIconFilled",unselectedIcon:null!=r?r:"SurveyStarIcon",ariaLabelFormat:null==s?void 0:s.starRatingAriaLabel}),e.createElement(oJ,{className:qae(d)},l))},Jae=t=>{const{onStarRatingSelected:i}=t,n=PJ().strings.call,r={starSurveyHelperText:n.starSurveyHelperText,starSurveyOneStarText:n.starSurveyOneStarText,starSurveyTwoStarText:n.starSurveyTwoStarText,starSurveyThreeStarText:n.starSurveyThreeStarText,starSurveyFourStarText:n.starSurveyFourStarText,starSurveyFiveStarText:n.starSurveyFiveStarText,starRatingAriaLabel:n.starRatingAriaLabel};return e.createElement(Kae,{strings:r,onStarRatingSelected:i})};function Yae(t,i){void 0===i&&(i=null);var n,r=e.useRef({ref:(n=function(e){r.ref.current!==e&&(r.cleanup&&(r.cleanup(),r.cleanup=void 0),r.ref.current=e,null!==e&&(r.cleanup=r.callback(e)))},n.current=i,n),callback:t}).current;return r.callback=t,r.ref}var Qae=function(t){function i(e){var i=t.call(this,e)||this;return Ij(i),i}return _U(i,t),i.prototype.render=function(){return e.createElement("div",IU({},B$(this.props,U$)),this.props.children)},i}(e.Component),Zae=oj(),Xae=function(t,i){var n={links:[],keyToIndexMapping:{},keyToTabIdMapping:{}};return e.Children.forEach(e.Children.toArray(t.children),(function(e,r){if(eoe(e)){var s=e.props,a=s.linkText,o=wU(s,["linkText"]),l=e.props.itemKey||r.toString();n.links.push(IU(IU({headerText:a},o),{itemKey:l})),n.keyToIndexMapping[l]=r,n.keyToTabIdMapping[l]=function(e,t,i,n){return e.getTabId?e.getTabId(i,n):t+"-Tab".concat(n)}(t,i,l,r)}else e&&jH("The children of a Pivot component must be of type PivotItem to be rendered.")})),n},eoe=function(t){var i;return e.isValidElement(t)&&(null===(i=t.type)||void 0===i?void 0:i.name)===Qae.name},toe=e.forwardRef((function(t,i){var n,r=e.useRef(null),s=e.useRef(null),a=g$("Pivot"),o=V4(t.selectedKey,t.defaultSelectedKey),l=o[0],c=o[1],d=t.componentRef,u=t.theme,h=t.linkSize,g=t.linkFormat,p=t.overflowBehavior,m=t.overflowAriaLabel,f=t.focusZoneProps,v=t.overflowButtonAs,S={"aria-label":t["aria-label"],"aria-labelledby":t["aria-labelledby"]},y=B$(t,U$,["aria-label","aria-labelledby"]),C=Xae(t,a);e.useImperativeHandle(d,(function(){return{focus:function(){var e;null===(e=r.current)||void 0===e||e.focus()}}}));var T=function(t){if(!t)return null;var i=t.itemCount,r=t.itemIcon,s=t.headerText;return e.createElement("span",{className:n.linkContent},void 0!==r&&e.createElement("span",{className:n.icon},e.createElement(mG,{iconName:r})),void 0!==s&&e.createElement("span",{className:n.text}," ",t.headerText),void 0!==i&&e.createElement("span",{className:n.count}," (",i,")"))},E=function(t,i,r,s){var a,o=i.itemKey,l=i.headerButtonProps,c=i.onRenderItemLink,d=t.keyToTabIdMapping[o],u=r===o;a=c?c(i,T):T(i);var h=i.headerText||"";h+=i.itemCount?" ("+i.itemCount+")":"",h+=i.itemIcon?" xx":"";var g=i.role&&"tab"!==i.role?{role:i.role}:{role:"tab","aria-selected":u};return e.createElement(S4,IU({},l,g,{id:d,key:o,className:V$(s,u&&n.linkIsSelected),onClick:function(e){return b(o,e)},onKeyDown:function(e){return _(o,e)},"aria-label":i.ariaLabel,name:i.headerText,keytipProps:i.keytipProps,"data-content":h}),a)},b=function(e,t){t.preventDefault(),I(e,t)},_=function(e,t){t.which===fj&&(t.preventDefault(),I(e))},I=function(i,n){var r;if(c(i),C=Xae(t,a),t.onLinkClick&&C.keyToIndexMapping[i]>=0){var o=C.keyToIndexMapping[i],l=e.Children.toArray(t.children)[o];eoe(l)&&t.onLinkClick(l,n)}null===(r=s.current)||void 0===r||r.dismissMenu()};n=Zae(t.styles,{theme:u,linkSize:h,linkFormat:g});var w,A=null===(w=l)||void 0!==w&&void 0!==C.keyToIndexMapping[w]?l:C.links.length?C.links[0].itemKey:void 0,P=A?C.keyToIndexMapping[A]:0,R=C.links.map((function(e){return E(C,e,A,n.link)})),M=e.useMemo((function(){return{items:[],alignTargetEdge:!0,directionalHint:6}}),[]),D=function(t){var i=t.onOverflowItemsChanged,n=t.rtl,r=t.pinnedIndex,s=e.useRef(),a=e.useRef(),o=Yae((function(e){var t=function(e,t){if("undefined"!=typeof ResizeObserver){var i=new ResizeObserver(t);return Array.isArray(e)?e.forEach((function(e){return i.observe(e)})):i.observe(e),function(){return i.disconnect()}}var n=function(){return t(void 0)},r=_B(Array.isArray(e)?e[0]:e);if(!r)return function(){};var s=r.requestAnimationFrame(n);return r.addEventListener("resize",n,!1),function(){r.cancelAnimationFrame(s),r.removeEventListener("resize",n,!1)}}(e,(function(t){a.current=t?t[0].contentRect.width:e.clientWidth,s.current&&s.current()}));return function(){t(),a.current=void 0}})),l=Yae((function(e){return o(e.parentElement),function(){return o(null)}}));return iG((function(){var e=o.current,t=l.current;if(e&&t){for(var c=[],d=0;d<e.children.length;d++){var u=e.children[d];u instanceof HTMLElement&&u!==t&&c.push(u)}var h=[],g=0;s.current=function(){var e=a.current;if(void 0!==e){for(var i=c.length-1;i>=0;i--){if(void 0===h[i]){var s=n?e-c[i].offsetLeft:c[i].offsetLeft+c[i].offsetWidth;i+1<c.length&&i+1===r&&(g=h[i+1]-s),i===c.length-2&&(g+=t.offsetWidth),h[i]=s+g}if(e>h[i])return void m(i+1)}m(0)}};var p=c.length,m=function(e){p!==e&&(p=e,i(e,c.map((function(t,i){return{ele:t,isOverflowing:i>=e&&i!==r}}))))},f=void 0;if(void 0!==a.current){var v=_B(e);if(v){var S=v.requestAnimationFrame(s.current);f=function(){return v.cancelAnimationFrame(S)}}}return function(){f&&f(),m(c.length),s.current=void 0}}})),{menuButtonRef:l}}({onOverflowItemsChanged:function(e,t){t.forEach((function(e){var t=e.ele,i=e.isOverflowing;return t.dataset.isOverflowing="".concat(i)})),M.items=C.links.slice(e).filter((function(e){return e.itemKey!==A})).map((function(t,i){return t.role="menuitem",{key:t.itemKey||"".concat(e+i),onRender:function(){return E(C,t,A,n.linkInMenu)}}}))},rtl:PB(u),pinnedIndex:P}).menuButtonRef,k=v||S4;return e.createElement("div",IU({ref:i},y),e.createElement(iq,IU({componentRef:r,role:"tablist"},S,{direction:yG.horizontal},f,{className:V$(n.root,null==f?void 0:f.className)}),R,"menu"===p&&e.createElement(k,{className:V$(n.link,n.overflowMenuButton),elementRef:D,componentRef:s,menuProps:M,menuIconProps:{iconName:"More",style:{color:"inherit"}},ariaLabel:m,role:"tab"})),A&&C.links.map((function(i){return(!0===i.alwaysRender||A===i.itemKey)&&function(i,r){if(t.headersOnly||!i)return null;var s=C.keyToIndexMapping[i],a=C.keyToTabIdMapping[i];return e.createElement("div",{role:"tabpanel",hidden:!r,key:i,"aria-hidden":!r,"aria-labelledby":a,className:n.itemContainer},e.Children.toArray(t.children)[s])}(i.itemKey,A===i.itemKey)})))}));toe.displayName="Pivot";var ioe={count:"ms-Pivot-count",icon:"ms-Pivot-icon",linkIsSelected:"is-selected",link:"ms-Pivot-link",linkContent:"ms-Pivot-linkContent",root:"ms-Pivot",rootIsLarge:"ms-Pivot--large",rootIsTabs:"ms-Pivot--tabs",text:"ms-Pivot-text",linkInMenu:"ms-Pivot-linkInMenu",overflowMenuButton:"ms-Pivot-overflowMenuButton"},noe=function(e,t,i){var n,r,s;void 0===i&&(i=!1);var a=e.linkSize,o=e.linkFormat,l=e.theme,c=l.semanticColors,d=l.fonts,u="large"===a,h="tabs"===o;return[d.medium,{color:c.actionLink,padding:"0 8px",position:"relative",backgroundColor:"transparent",border:0,borderRadius:0,selectors:{":hover":{backgroundColor:c.buttonBackgroundHovered,color:c.buttonTextHovered,cursor:"pointer"},":active":{backgroundColor:c.buttonBackgroundPressed,color:c.buttonTextHovered},":focus":{outline:"none"}}},!i&&[{display:"inline-block",lineHeight:44,height:44,marginRight:8,textAlign:"center",selectors:(n={},n[".".concat(GV," &:focus, :host(.").concat(GV,") &:focus")]={outline:"1px solid ".concat(c.focusBorder)},n[".".concat(GV," &:focus:after, :host(.").concat(GV,") &:focus:after")]={content:"attr(data-content)",position:"relative",border:0},n[":before"]={backgroundColor:"transparent",bottom:0,content:'""',height:2,left:8,position:"absolute",right:8,transition:"left ".concat(CV," ").concat(yV,",\n right ").concat(CV," ").concat(yV)},n[":after"]={color:"transparent",content:"attr(data-content)",display:"block",fontWeight:DV.bold,height:1,overflow:"hidden",visibility:"hidden"},n)},u&&{fontSize:d.large.fontSize},h&&[{marginRight:0,height:44,lineHeight:44,backgroundColor:c.buttonBackground,padding:"0 10px",verticalAlign:"top",selectors:(r={":focus":{outlineOffset:"-2px"}},r[".".concat(GV," &:focus::before, :host(.").concat(GV,") &:focus::before")]={height:"auto",background:"transparent",transition:"none"},r["&:hover, &:focus"]={color:c.buttonTextCheckedHovered},r["&:active, &:hover"]={color:c.primaryButtonText,backgroundColor:c.primaryButtonBackground},r["&.".concat(t.linkIsSelected)]={backgroundColor:c.primaryButtonBackground,color:c.primaryButtonText,fontWeight:DV.regular,selectors:(s={":before":{backgroundColor:"transparent",transition:"none",position:"absolute",top:0,left:0,right:0,bottom:0,content:'""',height:0},":hover":{backgroundColor:c.primaryButtonBackgroundHovered,color:c.primaryButtonText},":active":{backgroundColor:c.primaryButtonBackgroundPressed,color:c.primaryButtonText}},s[UV]=IU({fontWeight:DV.semibold,color:"HighlightText",background:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)},r[".".concat(GV," &.").concat(t.linkIsSelected,":focus, :host(.").concat(GV,") &.").concat(t.linkIsSelected,":focus")]={outlineColor:c.primaryButtonText},r)}]]]},roe=nj(toe,(function(e){var t,i,n,r,s=e.className,a=e.linkSize,o=e.linkFormat,l=e.theme,c=l.semanticColors,d=l.fonts,u=FV(ioe,l),h="large"===a,g="tabs"===o;return{root:[u.root,d.medium,VH,{position:"relative",color:c.link,whiteSpace:"nowrap"},h&&u.rootIsLarge,g&&u.rootIsTabs,s],itemContainer:{selectors:{"&[hidden]":{display:"none"}}},link:PU(PU([u.link],noe(e,u),!0),[(t={},t["&[data-is-overflowing='true']"]={display:"none"},t)],!1),overflowMenuButton:[u.overflowMenuButton,(i={visibility:"hidden",position:"absolute",right:0},i[".".concat(u.link,"[data-is-overflowing='true'] ~ &")]={visibility:"visible",position:"relative"},i)],linkInMenu:PU(PU([u.linkInMenu],noe(e,u,!0),!0),[{justifyContent:"start",height:36,lineHeight:36,width:"100%"}],!1),linkIsSelected:[u.link,u.linkIsSelected,{fontWeight:DV.semibold,selectors:(n={":before":{backgroundColor:c.inputBackgroundChecked,selectors:(r={},r[UV]={backgroundColor:"Highlight"},r)},":hover::before":{left:0,right:0}},n[UV]={color:"Highlight"},n)}],linkContent:[u.linkContent,{flex:"0 1 100%",selectors:{"& > * ":{marginLeft:4},"& > *:first-child":{marginLeft:0}}}],text:[u.text,{display:"inline-block",verticalAlign:"top"}],count:[u.count,{display:"inline-block",verticalAlign:"top"}],icon:u.icon}}),void 0,{scope:"Pivot"});const soe=e=>dB({fontWeight:600,fontSize:vJ(16),lineHeight:vJ(20),color:e.palette.neutralPrimary,marginTop:vJ(8),marginBottom:vJ(4)}),aoe=e=>dB({fontWeight:400,fontSize:vJ(12),lineHeight:vJ(16),marginTop:vJ(4),color:e.palette.neutralSecondary}),ooe=dB({padding:vJ(8),paddingLeft:0}),loe={root:{paddingBottom:vJ(8),width:"100%"},label:{width:"100%"}},coe=dB({width:"100%",marginLeft:vJ(4),input:{padding:0}}),doe=t=>{const{callIssuesToTag:i,categoryHeadings:n,onConfirm:r,strings:s,showFreeFormTextField:a}=t,[o,l]=(0,e.useState)({}),[c,d]=(0,e.useState)({}),[u,h]=(0,e.useState)({}),[g,p]=(0,e.useState)([]),m=(0,e.useMemo)((()=>{const e={overallRating:[],audioRating:[],videoRating:[],screenshareRating:[]};return S0(i).forEach((t=>{S0(i[t]).map((n=>{const r=(null==n?void 0:n.charAt(0).toUpperCase())+(null==n?void 0:n.slice(1)),s=i[t];e[t]?e[t].push({message:s[n],issue:r}):e[t]=[{message:s[n],issue:r}]}))})),e}),[i]),f=e.useCallback(((e,t,i)=>{t?i?l((t=>{const n=null==t?void 0:t[e];return n&&n.issues?n.issues=[n.issues,i]:t[e]={issues:[i]},t})):(p([...g,e]),h((t=>(t[e]=c[e],t)))):i?l((t=>{var n,r;const s=null===(r=null===(n=t[e])||void 0===n?void 0:n.issues)||void 0===r?void 0:r.filter((e=>e!==i));return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},t[e]||{}),{issues:s})})})):(p(g.filter((t=>t!==e))),h((t=>(delete t[e],t))))}),[c,g]),v=qK(),S=(0,e.useCallback)((t=>e.createElement(U5,{key:t,className:coe,underlined:!0,placeholder:null==s?void 0:s.tagsSurveyTextFieldDefaultText,onChange:(e,i)=>{i&&(p([...g,t]),d((e=>(e[t]=i,e))),h((e=>(e[t]=i,e))))}})),[null==s?void 0:s.tagsSurveyTextFieldDefaultText,g]);return(0,e.useEffect)((()=>{r&&r(o,u)}),[o,u,r]),e.createElement(e.Fragment,null,e.createElement(Y$,{verticalAlign:"center"},e.createElement(oJ,{className:soe(v)},null==s?void 0:s.tagsSurveyQuestion)),e.createElement(roe,null,S0(m).map(((t,i)=>e.createElement(Qae,{key:`key-${i}`,headerText:n[t],headerButtonProps:{"data-order":i,"data-title":t},alwaysRender:!0},m[t].map(((i,n)=>e.createElement(W4,{className:ooe,key:`checkBox_${n}`,label:i.message,onChange:(e,n)=>f(t,null!=n&&n,i.issue)}))),a&&e.createElement(W4,{checked:g.includes(t),styles:loe,onChange:(e,i)=>f(t,null!=i&&i),onRenderLabel:()=>S(t)}))))),e.createElement(oJ,{className:aoe(v)},null==s?void 0:s.tagsSurveyHelperText))},uoe=t=>{const i=PJ().strings.call,n={tagsSurveyQuestion:i.tagsSurveyQuestion,tagsSurveyHelperText:i.tagsSurveyHelperText,tagsSurveyTextFieldDefaultText:i.tagsSurveyTextFieldDefaultText};return e.createElement(doe,{callIssuesToTag:i.surveyIssues,categoryHeadings:i.surveyIssuesHeadingStrings,onConfirm:t.onConfirm,strings:n,showFreeFormTextField:t.showFreeFormTextField})},hoe=t=>{const[i,n]=(0,e.useState)(!1);return e.createElement(Y$,{"data-ui-id":"call-composite-survey"},e.createElement(Jae,{onStarRatingSelected:e=>{e<5?(n(!0),t.setShowSubmitFeedbackButton(!0)):t.setShowSubmitFeedbackButton(!0),t.setRatings(e)}}),i&&e.createElement(uoe,{onConfirm:(e,i)=>{t.setIssuesSelected(e),t.setShowSubmitFeedbackButton(!0),i&&t.setImprovementSuggestions&&t.setImprovementSuggestions(i)},showFreeFormTextField:!(void 0===t.setImprovementSuggestions)}))};function goe(t){const i=PJ().strings.call;return e.createElement(Y$,{verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":"thank-you-page","aria-atomic":!0},e.createElement(Y$,{className:dB(Dse),tokens:kse},t.iconName&&e.createElement(bZ,{iconName:t.iconName}),e.createElement(oJ,{className:dB(Nse),"aria-live":"assertive"},i.endOfSurveyText)))}const poe=e=>dB({fontWeight:600,fontSize:vJ(20),lineHeight:vJ(20),color:e.palette.neutralPrimary}),moe=e=>dB(e?{width:"20rem",position:"absolute",top:"10%",left:"50%",transform:"translateX(-50%)"}:{width:"24rem",position:"absolute",top:"20%",left:"50%",transform:"translateX(-50%)"});const foe=t=>{const{onSubmitSurvey:i,onSurveySubmittedCustom:n,onSurveyClosed:r,iconName:s,title:a,moreDetails:o,disableStartCallButton:l,isMobile:c}=t,d=PJ().strings.call,[u,h]=(0,e.useState)(0),[g,p]=(0,e.useState)(),[m,f]=(0,e.useState)(!1),[v,S]=(0,e.useState)({}),[y,C]=(0,e.useState)(!1),[T,E]=(0,e.useState)(!1),[b,_]=(0,e.useState)(!1),I=qK();return e.createElement(e.Fragment,null,y&&e.createElement(goe,{iconName:s}),T&&e.createElement(xse,{iconName:s,title:a,moreDetails:o,dataUiId:"left-call-page",disableStartCallButton:l}),!y&&!T&&e.createElement(Y$,{verticalAlign:"center",className:moe(!!c)},e.createElement(oJ,{className:poe(I)},d.surveyTitle),e.createElement(hoe,{setShowSubmitFeedbackButton:e=>{f(e)},setRatings:e=>{h(e)},setIssuesSelected:e=>{p(e)},setImprovementSuggestions:n?e=>{S(e)}:void 0}),e.createElement(Y$,{horizontal:!0,horizontalAlign:"end"},e.createElement(pJ,{style:{marginTop:"1rem",marginRight:"0.5rem"},onClick:()=>{r?r("skipped"):E(!0)}},d.surveySkipButtonLabel),m&&e.createElement(mJ,{disabled:b,style:{marginTop:"1rem",marginLeft:"0.5rem"},onClick:()=>{return e=void 0,t=void 0,a=function*(){const e={overallRating:{score:u}};(null==g?void 0:g.overallRating)&&(e.overallRating={score:u,issues:g.overallRating.issues}),(null==g?void 0:g.audioRating)&&(e.audioRating={score:u,issues:g.audioRating.issues}),(null==g?void 0:g.screenshareRating)&&(e.screenshareRating={score:u,issues:g.screenshareRating.issues}),(null==g?void 0:g.videoRating)&&(e.videoRating={score:u,issues:g.videoRating.issues}),i&&(_(!0),i(e).then((t=>{var i,s;n?n(null!==(i=null==t?void 0:t.callId)&&void 0!==i?i:"",null!==(s=null==t?void 0:t.id)&&void 0!==s?s:"",e,v).then((()=>_(!1))):_(!1),r?r("sent"):C(!0)})).catch((e=>{console.log("error when submitting survey: "+e),r&&r("error",e)})))},new((s=void 0)||(s=Promise))((function(i,n){function r(e){try{l(a.next(e))}catch(e){n(e)}}function o(e){try{l(a.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,o)}l((a=a.apply(e,t||[])).next())}));var e,t,s,a}},d.surveyConfirmButtonLabel))))};function voe(t){var i,n;const r=K7();return e.createElement(Y$,{verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":t.dataUiId,"aria-atomic":!0},e.createElement(Y$,{className:dB($ne),tokens:kse},e.createElement(foe,Object.assign({},r,t,{onSurveySubmittedCustom:null===(i=t.surveyOptions)||void 0===i?void 0:i.onSurveySubmitted,onSurveyClosed:null===(n=t.surveyOptions)||void 0===n?void 0:n.onSurveyClosed,isMobile:t.mobileView}))))}const Soe=e=>!!(null==e?void 0:e.isActive),yoe=t=>{var i,n,r,s,a,o,l,c,d,u,h,g,p,m,f,v,S,y,C;const T=LZ(),{camerasCount:E,microphonesCount:b}=u7(kae),_=E>0,I=b>0,w=u7(S7),{video:A,audio:P}=u7(jre);(0,e.useEffect)((()=>{var e,i,n,r;e=void 0,i=void 0,r=function*(){var e,i,n,r;const s=Eoe({role:w});s.audio="doNotPrompt"!==(null===(i=null===(e=t.options)||void 0===e?void 0:e.deviceChecks)||void 0===i?void 0:i.microphone)&&s.audio,s.video="doNotPrompt"!==(null===(r=null===(n=t.options)||void 0===n?void 0:n.deviceChecks)||void 0===r?void 0:r.camera)&&s.video;const a=yield T.askDevicePermission(s);(null==a?void 0:a.audio)&&T.queryMicrophones(),(null==a?void 0:a.video)&&T.queryCameras(),T.querySpeakers()},new((n=void 0)||(n=Promise))((function(t,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n((function(e){e(i)}))).then(a,o)}l((r=r.apply(e,i||[])).next())}))}),[T,w,null===(i=t.options)||void 0===i?void 0:i.deviceChecks,_,I,A,P]);const{callInvitationUrl:R,onFetchAvatarPersonaData:M,onFetchParticipantMenuItems:D}=t,k=u7(y7),O=u7(h7),[N,L]=e.useState(),[x,F]=e.useState(),[U,B]=(0,e.useState)(null!==(s=null===(r=null===(n=t.options)||void 0===n?void 0:n.galleryOptions)||void 0===r?void 0:r.layout)&&void 0!==s?s:"floatingLocalVideo"),[V,H]=(0,e.useState)("Responsive"),$=(0,e.useRef)(t.overrideSidePane);(0,e.useEffect)((()=>{F(t.overrideSidePane),!Soe($.current)&&Soe(t.overrideSidePane)&&L(void 0),$.current=t.overrideSidePane}),[t.overrideSidePane]);const j=t.onSidePaneIdChange;(0,e.useEffect)((()=>{null==j||j(null==N?void 0:N.id)}),[null==N?void 0:N.id,j]),(0,e.useEffect)((()=>{const e=()=>{L(void 0)};return T.on("callEnded",e),()=>{T.off("callEnded",e)}}),[T]);const G=PZ(),q=(t=>{const[i,n]=(0,e.useState)({}),r=(0,e.useRef)({});(0,e.useEffect)((()=>{r.current=((e,t)=>{var i,n;if(!e.capabilitiesChangeInfo)return t;for(const[r,s]of Object.entries(e.capabilitiesChangeInfo.newValue)){const a=r;if(t[a]&&s.isPresent===(null===(i=t[a])||void 0===i?void 0:i.isPresent)&&e.capabilitiesChangeInfo.reason===(null===(n=t[a])||void 0===n?void 0:n.changedReason))continue;const o=e.capabilitiesChangeInfo.oldValue[a];if(!0===s.isPresent&&!1===(null==o?void 0:o.isPresent)&&"FeatureNotSupported"===(null==o?void 0:o.reason)&&"MeetingOptionOrOrganizerPolicyChanged"===e.capabilitiesChangeInfo.reason)continue;if("shareScreen"===a&&void 0===t.shareScreen&&!0===s.isPresent&&!1===(null==o?void 0:o.isPresent)&&"RoleChanged"===e.capabilitiesChangeInfo.reason)continue;const l={capabilityName:a,isPresent:s.isPresent,changedReason:e.capabilitiesChangeInfo.reason,role:e.participantRole,timestamp:new Date(Date.now())};t[a]=l}return t})(t,r.current),n((e=>((e,t)=>{var i,n;const r={};for(const s of t){const t=e[s.capabilityName];r[s.capabilityName]={mostRecentlyActive:null!==(n=null!==(i=s.timestamp)&&void 0!==i?i:null==t?void 0:t.mostRecentlyActive)&&void 0!==n?n:new Date(Date.now()),lastDismissedAt:null==t?void 0:t.lastDismissedAt}}return r})(e,Object.values(r.current))))}),[t]);const s=(0,e.useCallback)((e=>{n((t=>((e,t)=>{const i=new Date(Date.now()),n=t[e];return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},n||{}),{lastDismissedAt:i})})})(e.capabilityName,t)))}),[]);return{capabilitiesChangedNotifications:(0,e.useMemo)((()=>((e,t)=>e.filter((e=>{const i=t[e.capabilityName];return!i||!i.lastDismissedAt||i.lastDismissedAt<i.mostRecentlyActive})))(Object.values(r.current),i)),[i]),onDismissNotification:s}})(u7(Oae)),z=Y7(BK).activeErrorMessages,W=Y7(bJ).activeErrorMessages,K=Y7(bJ).activeNotifications,J=u7(Kne),Y=(0,e.useRef)({latestBooleanState:{callTranscribeState:!1,callRecordState:!1},latestStringState:{callTranscribeState:"off",callRecordState:"off"},lastUpdated:Date.now()}),Q=(0,e.useMemo)((()=>function(e,t){const i=e.callRecordState!==t.current.latestBooleanState.callRecordState||e.callTranscribeState!==t.current.latestBooleanState.callTranscribeState;i&&(t.current={latestBooleanState:e,latestStringState:{callRecordState:ZF(t.current.latestStringState.callRecordState,e.callRecordState),callTranscribeState:ZF(t.current.latestStringState.callTranscribeState,e.callTranscribeState)},lastUpdated:Date.now()}),i&&"stopped"===t.current.latestStringState.callRecordState&&"stopped"===t.current.latestStringState.callTranscribeState&&Date.now()-t.current.lastUpdated>2e3&&(t.current.latestStringState.callRecordState="off",t.current.latestStringState.callTranscribeState="off");const n=(r=t.current.latestStringState.callRecordState,s=t.current.latestStringState.callTranscribeState,"on"===r&&"on"===s?"recordingAndTranscriptionStarted":"on"===r&&"off"===s?"recordingStarted":"off"===r&&"on"===s?"transcriptionStarted":"on"===r&&"stopped"===s?"transcriptionStoppedStillRecording":"stopped"===r&&"on"===s?"recordingStoppedStillTranscribing":"off"===r&&"stopped"===s?"transcriptionStopped":"stopped"===r&&"off"===s?"recordingStopped":"stopped"===r&&"stopped"===s?"recordingAndTranscriptionStopped":"noState");var r,s;return"noState"!==n?{type:n,timestamp:new Date(Date.now())}:void 0}(J,Y)),[J,Y]);(0,e.useEffect)((()=>{Q&&(K.forEach(((e,t)=>{["recordingStarted","transcriptionStarted","recordingStopped","transcriptionStopped","recordingAndTranscriptionStarted","recordingAndTranscriptionStopped","recordingStoppedStillTranscribing","transcriptionStoppedStillRecording"].includes(e.type)&&K.splice(t,1)})),K.push(Q)),ne((e=>Mae(e,K)))}),[Q,K]);const[Z,X]=(0,e.useState)({}),[ee,te]=(0,e.useState)({}),[ie,ne]=(0,e.useState)({});(0,e.useEffect)((()=>{X((e=>Mae(e,z))),te((e=>Mae(e,W)))}),[z,W]);const re=(0,e.useCallback)((e=>{X((t=>Dae(e.type,t))),te((t=>Dae(e.type,t)))}),[]),se=(0,e.useCallback)((e=>{ne((t=>Dae(e.type,t)))}),[]),ae=(0,e.useMemo)((()=>Rae(z,Z)),[z,Z]),oe=(0,e.useMemo)((()=>Rae(W,ee)),[W,ee]),le=(0,e.useMemo)((()=>{const e=Rae(K,ie);return e.sort(((e,t)=>{var i,n;return(null!==(i=e.timestamp)&&void 0!==i?i:new Date(Date.now())).getTime()-(null!==(n=t.timestamp)&&void 0!==n?n:new Date(Date.now())).getTime()})),e}),[K,ie]),ce=u7(M7),de=PJ(),ue=aJ().palette,he=u7(H7),ge=(0,e.useMemo)((()=>(e=>({background:e.neutralLighterAlt}))(ue)),[ue]);let pe;const[me,fe]=(0,e.useState)([]);switch(k){case"configuration":pe=e.createElement(wse,{joinCallOptions:null===(a=t.options)||void 0===a?void 0:a.joinCallOptions,mobileView:t.mobileView,startCallHandler:()=>{ce?T.startCall(ce,he?{alternateCallerId:{phoneNumber:he}}:{}):T.joinCall({microphoneOn:"keep",cameraOn:"keep"})},updateSidePaneRenderer:L,latestErrors:ae,onDismissError:re,modalLayerHostId:t.modalLayerHostId,deviceChecks:null===(o=t.options)||void 0===o?void 0:o.deviceChecks,onPermissionsTroubleshootingClick:null===(l=t.options)||void 0===l?void 0:l.onPermissionsTroubleshootingClick,onNetworkingTroubleShootingClick:null===(c=t.options)||void 0===c?void 0:c.onNetworkingTroubleShootingClick,capabilitiesChangedNotificationBarProps:q,logo:null===(u=null===(d=t.options)||void 0===d?void 0:d.branding)||void 0===u?void 0:u.logo,backgroundImage:null===(g=null===(h=t.options)||void 0===h?void 0:h.branding)||void 0===g?void 0:g.backgroundImage});break;case"accessDeniedTeamsMeeting":pe=e.createElement(xse,{iconName:"NoticePageAccessDeniedTeamsMeeting",title:de.strings.call.failedToJoinTeamsMeetingReasonAccessDeniedTitle,moreDetails:de.strings.call.failedToJoinTeamsMeetingReasonAccessDeniedMoreDetails,dataUiId:"access-denied-teams-meeting-page"});break;case"removedFromCall":pe=e.createElement(xse,{iconName:"NoticePageRemovedFromCall",title:de.strings.call.removedFromCallTitle,moreDetails:de.strings.call.removedFromCallMoreDetails,dataUiId:"removed-from-call-page"});break;case"joinCallFailedDueToNoNetwork":pe=e.createElement(xse,{iconName:"NoticePageJoinCallFailedDueToNoNetwork",title:de.strings.call.failedToJoinCallDueToNoNetworkTitle,moreDetails:de.strings.call.failedToJoinCallDueToNoNetworkMoreDetails,dataUiId:"join-call-failed-due-to-no-network-page"});break;case"leaving":pe=e.createElement(xse,{title:null!==(p=de.strings.call.leavingCallTitle)&&void 0!==p?p:"Leaving...",dataUiId:"leaving-page",pageStyle:ge,disableStartCallButton:!0});break;case"badRequest":{const{title:t,moreDetails:i,disableStartCallButton:n,iconName:r}=GF(de,O);pe=e.createElement(xse,{iconName:r,title:t,moreDetails:ce?"":i,dataUiId:"left-call-page",disableStartCallButton:n});break}case"leftCall":{const{title:i,moreDetails:n,disableStartCallButton:r,iconName:s}=GF(de,O);if(!(null===(f=null===(m=t.options)||void 0===m?void 0:m.surveyOptions)||void 0===f?void 0:f.disableSurvey)){pe=e.createElement(voe,{dataUiId:"left-call-page",surveyOptions:null===(v=t.options)||void 0===v?void 0:v.surveyOptions,iconName:s,title:i,moreDetails:n,disableStartCallButton:r,mobileView:t.mobileView});break}pe=e.createElement(xse,{iconName:s,title:i,moreDetails:ce?"":n,dataUiId:"left-call-page",disableStartCallButton:r});break}case"lobby":pe=e.createElement($se,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:L,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:oe,latestNotifications:le,onDismissError:re,onDismissNotification:se,capabilitiesChangedNotificationBarProps:q});break;case"transferring":pe=e.createElement(tae,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:L,mobileChatTabHeader:t.mobileChatTabHeader,onFetchAvatarPersonaData:M,latestErrors:oe,latestNotifications:le,onDismissError:re,onDismissNotification:se,capabilitiesChangedNotificationBarProps:q});break;case"call":pe=e.createElement(ire,{callInvitationURL:R,onFetchAvatarPersonaData:M,onFetchParticipantMenuItems:D,mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:L,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:t.onCloseChatPane,latestErrors:oe,latestNotifications:le,onDismissError:re,onDismissNotification:se,galleryLayout:U,onUserSetGalleryLayoutChange:B,onSetUserSetOverflowGalleryPosition:H,userSetOverflowGalleryPosition:V,capabilitiesChangedNotificationBarProps:q,pinnedParticipants:me,setPinnedParticipants:fe,compositeAudioContext:G,disableAutoShowDtmfDialer:null===(S=t.options)||void 0===S?void 0:S.disableAutoShowDtmfDialer});break;case"hold":pe=e.createElement(e.Fragment,null,e.createElement(hae,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:L,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:oe,latestNotifications:le,onDismissError:re,onDismissNotification:se,capabilitiesChangedNotificationBarProps:q}))}"returningFromBreakoutRoom"===k&&(pe=e.createElement(ire,{callInvitationURL:R,onFetchAvatarPersonaData:M,onFetchParticipantMenuItems:D,mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:L,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:t.onCloseChatPane,latestErrors:oe,latestNotifications:le,onDismissError:re,onDismissNotification:se,galleryLayout:U,onUserSetGalleryLayoutChange:B,onSetUserSetOverflowGalleryPosition:H,userSetOverflowGalleryPosition:V,capabilitiesChangedNotificationBarProps:q,pinnedParticipants:me,setPinnedParticipants:fe,compositeAudioContext:G,disableAutoShowDtmfDialer:null===(y=t.options)||void 0===y?void 0:y.disableAutoShowDtmfDialer})),(t=>{var i;(0,e.useEffect)((()=>{var e;switch(null===(e=null==t?void 0:t.callEndReason)||void 0===e?void 0:e.subCode){case 5732:console.error("Call ended because the room id provided through the adapter locator could not be found");break;case 5829:console.error("Call ended because this room is currently not valid.");break;case 5828:console.error("Call ended because you are not invited to this room.");break;case 5317:console.error("Call ended because your invite to this room has been removed.")}}),[null===(i=null==t?void 0:t.callEndReason)||void 0===i?void 0:i.subCode])})(O);const ve=u7(I7);if("unsupportedEnvironment"===k&&(pe=e.createElement(e.Fragment,null,e.createElement(Aae,{onTroubleshootingClick:null===(C=t.options)||void 0===C?void 0:C.onEnvironmentInfoTroubleshootingClick,environmentInfo:ve}))),!pe)throw new Error("Invalid call composite page");return e.createElement(Fte,{sidePaneRenderer:N,overrideSidePane:x},pe)},Coe=t=>e.createElement(Toe,Object.assign({},t)),Toe=t=>{const{adapter:i,callInvitationUrl:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:s,options:a,formFactor:o="desktop"}=t,l="mobile"===o,c=g$("modalLayerhost"),d=(0,e.useMemo)((()=>l?gte:hte),[l]);return e.createElement("div",{className:d},e.createElement(RZ,Object.assign({},t),e.createElement(NZ,{adapter:i},e.createElement(yoe,{callInvitationUrl:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:s,mobileView:l,modalLayerHostId:c,options:a,onSidePaneIdChange:t.onSidePaneIdChange,overrideSidePane:t.overrideSidePane,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:t.onCloseChatPane}),e.createElement(IJ,{id:c,className:dB(vee)}))))},Eoe=e=>"Consumer"===e.role?{video:!1,audio:!0}:{video:!0,audio:!0};function boe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons"',src:"url('".concat(e,"fabric-icons-a13498cf.woff') format('woff')")},icons:{GlobalNavButton:"",ChevronDown:"",ChevronUp:"",Edit:"",Add:"",Cancel:"",More:"",Settings:"",Mail:"",Filter:"",Search:"",Share:"",BlockedSite:"",FavoriteStar:"",FavoriteStarFill:"",CheckMark:"",Delete:"",ChevronLeft:"",ChevronRight:"",Calendar:"",Megaphone:"",Undo:"",Flag:"",Page:"",Pinned:"",View:"",Clear:"",Download:"",Upload:"",Folder:"",Sort:"",AlignRight:"",AlignLeft:"",Tag:"",AddFriend:"",Info:"",SortLines:"",List:"",CircleRing:"",Heart:"",HeartFill:"",Tiles:"",Embed:"",Glimmer:"",Ascending:"",Descending:"",SortUp:"",SortDown:"",SyncToPC:"",LargeGrid:"",SkypeCheck:"",SkypeClock:"",SkypeMinus:"",ClearFilter:"",Flow:"",StatusCircleCheckmark:"",MoreVertical:""}},t)}function _oe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-0"',src:"url('".concat(e,"fabric-icons-0-467ee27f.woff') format('woff')")},icons:{PageLink:"",CommentSolid:"",ChangeEntitlements:"",Installation:"",WebAppBuilderModule:"",WebAppBuilderFragment:"",WebAppBuilderSlot:"",BullseyeTargetEdit:"",WebAppBuilderFragmentCreate:"",PageData:"",PageHeaderEdit:"",ProductList:"",UnpublishContent:"",DependencyAdd:"",DependencyRemove:"",EntitlementPolicy:"",EntitlementRedemption:"",SchoolDataSyncLogo:"",PinSolid12:"",PinSolidOff12:"",AddLink:"",SharepointAppIcon16:"",DataflowsLink:"",TimePicker:"",UserWarning:"",ComplianceAudit:"",InternetSharing:"",Brightness:"",MapPin:"",Airplane:"",Tablet:"",QuickNote:"",Video:"",People:"",Phone:"",Pin:"",Shop:"",Stop:"",Link:"",AllApps:"",Zoom:"",ZoomOut:"",Microphone:"",Camera:"",Attach:"",Send:"",FavoriteList:"",PageSolid:"",Forward:"",Back:"",Refresh:"",Lock:"",ReportHacked:"",EMI:"",MiniLink:"",Blocked:"",ReadingMode:"",Favicon:"",Remove:"",Checkbox:"",CheckboxComposite:"",CheckboxFill:"",CheckboxIndeterminate:"",CheckboxCompositeReversed:"",BackToWindow:"",FullScreen:"",Print:"",Up:"",Down:"",OEM:"",Save:"",ReturnKey:"",Cloud:"",Flashlight:"",CommandPrompt:"",Sad:"",RealEstate:"",SIPMove:"",EraseTool:"",GripperTool:"",Dialpad:"",PageLeft:"",PageRight:"",MultiSelect:"",KeyboardClassic:"",Play:"",Pause:"",InkingTool:"",Emoji2:"",GripperBarHorizontal:"",System:"",Personalize:"",SearchAndApps:"",Globe:"",EaseOfAccess:"",ContactInfo:"",Unpin:"",Contact:"",Memo:"",IncomingCall:""}},t)}function Ioe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-1"',src:"url('".concat(e,"fabric-icons-1-4d521695.woff') format('woff')")},icons:{Paste:"",WindowsLogo:"",Error:"",GripperBarVertical:"",Unlock:"",Slideshow:"",Trim:"",AutoEnhanceOn:"",AutoEnhanceOff:"",Color:"",SaveAs:"",Light:"",Filters:"",AspectRatio:"",Contrast:"",Redo:"",Crop:"",PhotoCollection:"",Album:"",Rotate:"",PanoIndicator:"",Translate:"",RedEye:"",ViewOriginal:"",ThumbnailView:"",Package:"",Telemarketer:"",Warning:"",Financial:"",Education:"",ShoppingCart:"",Train:"",Move:"",TouchPointer:"",Merge:"",TurnRight:"",Ferry:"",Highlight:"",PowerButton:"",Tab:"",Admin:"",TVMonitor:"",Speakers:"",Game:"",HorizontalTabKey:"",UnstackSelected:"",StackIndicator:"",Nav2DMapView:"",StreetsideSplitMinimize:"",Car:"",Bus:"",EatDrink:"",SeeDo:"",LocationCircle:"",Home:"",SwitcherStartEnd:"",ParkingLocation:"",IncidentTriangle:"",Touch:"",MapDirections:"",CaretHollow:"",CaretSolid:"",History:"",Location:"",MapLayers:"",SearchNearby:"",Work:"",Recent:"",Hotel:"",Bank:"",LocationDot:"",Dictionary:"",ChromeBack:"",FolderOpen:"",PinnedFill:"",RevToggleKey:"",USB:"",Previous:"",Next:"",Sync:"",Help:"",Emoji:"",MailForward:"",ClosePane:"",OpenPane:"",PreviewLink:"",ZoomIn:"",Bookmarks:"",Document:"",ProtectedDocument:"",OpenInNewWindow:"",MailFill:"",ViewAll:"",Switch:"",Rename:"",Go:"",Remote:"",SelectAll:"",Orientation:"",Import:""}},t)}function woe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-2"',src:"url('".concat(e,"fabric-icons-2-63c99abf.woff') format('woff')")},icons:{Picture:"",ChromeClose:"",ShowResults:"",Message:"",CalendarDay:"",CalendarWeek:"",MailReplyAll:"",Read:"",Cut:"",PaymentCard:"",Copy:"",Important:"",MailReply:"",GotoToday:"",Font:"",FontColor:"",FolderFill:"",Permissions:"",DisableUpdates:"",Unfavorite:"",Italic:"",Underline:"",Bold:"",MoveToFolder:"",Dislike:"",Like:"",AlignCenter:"",OpenFile:"",ClearSelection:"",FontDecrease:"",FontIncrease:"",FontSize:"",CellPhone:"",RepeatOne:"",RepeatAll:"",Calculator:"",Library:"",PostUpdate:"",NewFolder:"",CalendarReply:"",UnsyncFolder:"",SyncFolder:"",BlockContact:"",Accept:"",BulletedList:"",Preview:"",News:"",Chat:"",Group:"",World:"",Comment:"",DockLeft:"",DockRight:"",Repair:"",Accounts:"",Street:"",RadioBullet:"",Stopwatch:"",Clock:"",WorldClock:"",AlarmClock:"",Photo:"",ActionCenter:"",Hospital:"",Timer:"",FullCircleMask:"",LocationFill:"",ChromeMinimize:"",ChromeRestore:"",Annotation:"",Fingerprint:"",Handwriting:"",ChromeFullScreen:"",Completed:"",Label:"",FlickDown:"",FlickUp:"",FlickLeft:"",FlickRight:"",MiniExpand:"",MiniContract:"",Streaming:"",MusicInCollection:"",OneDriveLogo:"",CompassNW:"",Code:"",LightningBolt:"",CalculatorMultiply:"",CalculatorAddition:"",CalculatorSubtract:"",CalculatorPercentage:"",CalculatorEqualTo:"",PrintfaxPrinterFile:"",StorageOptical:"",Communications:"",Headset:"",Health:"",Webcam2:"",FrontCamera:"",ChevronUpSmall:""}},t)}function Aoe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-3"',src:"url('".concat(e,"fabric-icons-3-089e217a.woff') format('woff')")},icons:{ChevronDownSmall:"",ChevronLeftSmall:"",ChevronRightSmall:"",ChevronUpMed:"",ChevronDownMed:"",ChevronLeftMed:"",ChevronRightMed:"",Devices2:"",PC1:"",PresenceChickletVideo:"",Reply:"",HalfAlpha:"",ConstructionCone:"",DoubleChevronLeftMed:"",Volume0:"",Volume1:"",Volume2:"",Volume3:"",Chart:"",Robot:"",Manufacturing:"",LockSolid:"",FitPage:"",FitWidth:"",BidiLtr:"",BidiRtl:"",RightDoubleQuote:"",Sunny:"",CloudWeather:"",Cloudy:"",PartlyCloudyDay:"",PartlyCloudyNight:"",ClearNight:"",RainShowersDay:"",Rain:"",Thunderstorms:"",RainSnow:"",Snow:"",BlowingSnow:"",Frigid:"",Fog:"",Squalls:"",Duststorm:"",Unknown:"",Precipitation:"",Ribbon:"",AreaChart:"",Assign:"",FlowChart:"",CheckList:"",Diagnostic:"",Generate:"",LineChart:"",Equalizer:"",BarChartHorizontal:"",BarChartVertical:"",Freezing:"",FunnelChart:"",Processing:"",Quantity:"",ReportDocument:"",StackColumnChart:"",SnowShowerDay:"",HailDay:"",WorkFlow:"",HourGlass:"",StoreLogoMed20:"",TimeSheet:"",TriangleSolid:"",UpgradeAnalysis:"",VideoSolid:"",RainShowersNight:"",SnowShowerNight:"",Teamwork:"",HailNight:"",PeopleAdd:"",Glasses:"",DateTime2:"",Shield:"",Header1:"",PageAdd:"",NumberedList:"",PowerBILogo:"",Info2:"",MusicInCollectionFill:"",Asterisk:"",ErrorBadge:"",CircleFill:"",Record2:"",AllAppsMirrored:"",BookmarksMirrored:"",BulletedListMirrored:"",CaretHollowMirrored:"",CaretSolidMirrored:"",ChromeBackMirrored:"",ClearSelectionMirrored:"",ClosePaneMirrored:"",DockLeftMirrored:"",DoubleChevronLeftMedMirrored:"",GoMirrored:""}},t)}function Poe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-4"',src:"url('".concat(e,"fabric-icons-4-a656cc0a.woff') format('woff')")},icons:{HelpMirrored:"",ImportMirrored:"",ImportAllMirrored:"",ListMirrored:"",MailForwardMirrored:"",MailReplyMirrored:"",MailReplyAllMirrored:"",MiniContractMirrored:"",MiniExpandMirrored:"",OpenPaneMirrored:"",ParkingLocationMirrored:"",SendMirrored:"",ShowResultsMirrored:"",ThumbnailViewMirrored:"",Media:"",Devices3:"",Focus:"",VideoLightOff:"",Lightbulb:"",StatusTriangle:"",VolumeDisabled:"",Puzzle:"",EmojiNeutral:"",EmojiDisappointed:"",HomeSolid:"",Ringer:"",PDF:"",HeartBroken:"",StoreLogo16:"",MultiSelectMirrored:"",Broom:"",AddToShoppingList:"",Cocktails:"",Wines:"",Articles:"",Cycling:"",DietPlanNotebook:"",Pill:"",ExerciseTracker:"",HandsFree:"",Medical:"",Running:"",Weights:"",Trackers:"",AddNotes:"",AllCurrency:"",BarChart4:"",CirclePlus:"",Coffee:"",Cotton:"",Market:"",Money:"",PieDouble:"",PieSingle:"",RemoveFilter:"",Savings:"",Sell:"",StockDown:"",StockUp:"",Lamp:"",Source:"",MSNVideos:"",Cricket:"",Golf:"",Baseball:"",Soccer:"",MoreSports:"",AutoRacing:"",CollegeHoops:"",CollegeFootball:"",ProFootball:"",ProHockey:"",Rugby:"",SubstitutionsIn:"",Tennis:"",Arrivals:"",Design:"",Website:"",Drop:"",HistoricalWeather:"",SkiResorts:"",Snowflake:"",BusSolid:"",FerrySolid:"",AirplaneSolid:"",TrainSolid:"",Ticket:"",WifiWarning4:"",Devices4:"",AzureLogo:"",BingLogo:"",MSNLogo:"",OutlookLogoInverse:"",OfficeLogo:"",SkypeLogo:"",Door:"",EditMirrored:"",GiftCard:"",DoubleBookmark:"",StatusErrorFull:""}},t)}function Roe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-5"',src:"url('".concat(e,"fabric-icons-5-f95ba260.woff') format('woff')")},icons:{Certificate:"",FastForward:"",Rewind:"",Photo2:"",OpenSource:"",Movers:"",CloudDownload:"",Family:"",WindDirection:"",Bug:"",SiteScan:"",BrowserScreenShot:"",F12DevTools:"",CSS:"",JS:"",DeliveryTruck:"",ReminderPerson:"",ReminderGroup:"",ReminderTime:"",TabletMode:"",Umbrella:"",NetworkTower:"",CityNext:"",CityNext2:"",Section:"",OneNoteLogoInverse:"",ToggleFilled:"",ToggleBorder:"",SliderThumb:"",ToggleThumb:"",Documentation:"",Badge:"",Giftbox:"",VisualStudioLogo:"",HomeGroup:"",ExcelLogoInverse:"",WordLogoInverse:"",PowerPointLogoInverse:"",Cafe:"",SpeedHigh:"",Commitments:"",ThisPC:"",MusicNote:"",MicOff:"",PlaybackRate1x:"",EdgeLogo:"",CompletedSolid:"",AlbumRemove:"",MessageFill:"",TabletSelected:"",MobileSelected:"",LaptopSelected:"",TVMonitorSelected:"",DeveloperTools:"",Shapes:"",InsertTextBox:"",LowerBrightness:"",WebComponents:"",OfflineStorage:"",DOM:"",CloudUpload:"",ScrollUpDown:"",DateTime:"",Event:"",Cake:"",Org:"",PartyLeader:"",DRM:"",CloudAdd:"",AppIconDefault:"",Photo2Add:"",Photo2Remove:"",Calories:"",POI:"",AddTo:"",RadioBtnOff:"",RadioBtnOn:"",ExploreContent:"",Product:"",ProgressLoopInner:"",ProgressLoopOuter:"",Blocked2:"",FangBody:"",Toolbox:"",PageHeader:"",ChatInviteFriend:"",Brush:"",Shirt:"",Crown:"",Diamond:"",ScaleUp:"",QRCode:"",Feedback:"",SharepointLogoInverse:"",YammerLogo:"",Hide:"",Uneditable:"",ReturnToSession:"",OpenFolderHorizontal:"",CalendarMirrored:""}},t)}function Moe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-6"',src:"url('".concat(e,"fabric-icons-6-ef6fd590.woff') format('woff')")},icons:{SwayLogoInverse:"",OutOfOffice:"",Trophy:"",ReopenPages:"",EmojiTabSymbols:"",AADLogo:"",AccessLogo:"",AdminALogoInverse32:"",AdminCLogoInverse32:"",AdminDLogoInverse32:"",AdminELogoInverse32:"",AdminLLogoInverse32:"",AdminMLogoInverse32:"",AdminOLogoInverse32:"",AdminPLogoInverse32:"",AdminSLogoInverse32:"",AdminYLogoInverse32:"",DelveLogoInverse:"",ExchangeLogoInverse:"",LyncLogo:"",OfficeVideoLogoInverse:"",SocialListeningLogo:"",VisioLogoInverse:"",Balloons:"",Cat:"",MailAlert:"",MailCheck:"",MailLowImportance:"",MailPause:"",MailRepeat:"",SecurityGroup:"",Table:"",VoicemailForward:"",VoicemailReply:"",Waffle:"",RemoveEvent:"",EventInfo:"",ForwardEvent:"",WipePhone:"",AddOnlineMeeting:"",JoinOnlineMeeting:"",RemoveLink:"",PeopleBlock:"",PeopleRepeat:"",PeopleAlert:"",PeoplePause:"",TransferCall:"",AddPhone:"",UnknownCall:"",NoteReply:"",NoteForward:"",NotePinned:"",RemoveOccurrence:"",Timeline:"",EditNote:"",CircleHalfFull:"",Room:"",Unsubscribe:"",Subscribe:"",HardDrive:"",RecurringTask:"",TaskManager:"",TaskManagerMirrored:"",Combine:"",Split:"",DoubleChevronUp:"",DoubleChevronLeft:"",DoubleChevronRight:"",TextBox:"",TextField:"",NumberField:"",Dropdown:"",PenWorkspace:"",BookingsLogo:"",ClassNotebookLogoInverse:"",DelveAnalyticsLogo:"",DocsLogoInverse:"",Dynamics365Logo:"",DynamicSMBLogo:"",OfficeAssistantLogo:"",OfficeStoreLogo:"",OneNoteEduLogoInverse:"",PlannerLogo:"",PowerApps:"",Suitcase:"",ProjectLogoInverse:"",CaretLeft8:"",CaretRight8:"",CaretUp8:"",CaretDown8:"",CaretLeftSolid8:"",CaretRightSolid8:"",CaretUpSolid8:"",CaretDownSolid8:"",ClearFormatting:"",Superscript:"",Subscript:"",Strikethrough:"",Export:"",ExportMirrored:""}},t)}function Doe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-7"',src:"url('".concat(e,"fabric-icons-7-2b97bb99.woff') format('woff')")},icons:{SingleBookmark:"",SingleBookmarkSolid:"",DoubleChevronDown:"",FollowUser:"",ReplyAll:"",WorkforceManagement:"",RecruitmentManagement:"",Questionnaire:"",ManagerSelfService:"",ProductionFloorManagement:"",ProductRelease:"",ProductVariant:"",ReplyMirrored:"",ReplyAllMirrored:"",Medal:"",AddGroup:"",QuestionnaireMirrored:"",CloudImportExport:"",TemporaryUser:"",CaretSolid16:"",GroupedDescending:"",GroupedAscending:"",AwayStatus:"",MyMoviesTV:"",GenericScan:"",AustralianRules:"",WifiEthernet:"",TrackersMirrored:"",DateTimeMirrored:"",StopSolid:"",DoubleChevronUp12:"",DoubleChevronDown12:"",DoubleChevronLeft12:"",DoubleChevronRight12:"",CalendarAgenda:"",ConnectVirtualMachine:"",AddEvent:"",AssetLibrary:"",DataConnectionLibrary:"",DocLibrary:"",FormLibrary:"",FormLibraryMirrored:"",ReportLibrary:"",ReportLibraryMirrored:"",ContactCard:"",CustomList:"",CustomListMirrored:"",IssueTracking:"",IssueTrackingMirrored:"",PictureLibrary:"",OfficeAddinsLogo:"",OfflineOneDriveParachute:"",OfflineOneDriveParachuteDisabled:"",TriangleSolidUp12:"",TriangleSolidDown12:"",TriangleSolidLeft12:"",TriangleSolidRight12:"",TriangleUp12:"",TriangleDown12:"",TriangleLeft12:"",TriangleRight12:"",ArrowUpRight8:"",ArrowDownRight8:"",DocumentSet:"",GoToDashboard:"",DelveAnalytics:"",ArrowUpRightMirrored8:"",ArrowDownRightMirrored8:"",CompanyDirectory:"",OpenEnrollment:"",CompanyDirectoryMirrored:"",OneDriveAdd:"",ProfileSearch:"",Header2:"",Header3:"",Header4:"",RingerSolid:"",Eyedropper:"",MarketDown:"",CalendarWorkWeek:"",SidePanel:"",GlobeFavorite:"",CaretTopLeftSolid8:"",CaretTopRightSolid8:"",ViewAll2:"",DocumentReply:"",PlayerSettings:"",ReceiptForward:"",ReceiptReply:"",ReceiptCheck:"",Fax:"",RecurringEvent:"",ReplyAlt:"",ReplyAllAlt:"",EditStyle:"",EditMail:"",Lifesaver:"",LifesaverLock:"",InboxCheck:"",FolderSearch:""}},t)}function koe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-8"',src:"url('".concat(e,"fabric-icons-8-6fdf1528.woff') format('woff')")},icons:{CollapseMenu:"",ExpandMenu:"",Boards:"",SunAdd:"",SunQuestionMark:"",LandscapeOrientation:"",DocumentSearch:"",PublicCalendar:"",PublicContactCard:"",PublicEmail:"",PublicFolder:"",WordDocument:"",PowerPointDocument:"",ExcelDocument:"",GroupedList:"",ClassroomLogo:"",Sections:"",EditPhoto:"",Starburst:"",ShareiOS:"",AirTickets:"",PencilReply:"",Tiles2:"",SkypeCircleCheck:"",SkypeCircleClock:"",SkypeCircleMinus:"",SkypeMessage:"",ClosedCaption:"",ATPLogo:"",OfficeFormsLogoInverse:"",RecycleBin:"",EmptyRecycleBin:"",Hide2:"",Breadcrumb:"",BirthdayCake:"",TimeEntry:"",CRMProcesses:"",PageEdit:"",PageArrowRight:"",PageRemove:"",Database:"",DataManagementSettings:"",CRMServices:"",EditContact:"",ConnectContacts:"",AppIconDefaultAdd:"",AppIconDefaultList:"",ActivateOrders:"",DeactivateOrders:"",ProductCatalog:"",ScatterChart:"",AccountActivity:"",DocumentManagement:"",CRMReport:"",KnowledgeArticle:"",Relationship:"",HomeVerify:"",ZipFolder:"",SurveyQuestions:"",TextDocument:"",TextDocumentShared:"",PageCheckedOut:"",PageShared:"",SaveAndClose:"",Script:"",Archive:"",ActivityFeed:"",Compare:"",EventDate:"",ArrowUpRight:"",CaretRight:"",SetAction:"",ChatBot:"",CaretSolidLeft:"",CaretSolidDown:"",CaretSolidRight:"",CaretSolidUp:"",PowerAppsLogo:"",PowerApps2Logo:"",SearchIssue:"",SearchIssueMirrored:"",FabricAssetLibrary:"",FabricDataConnectionLibrary:"",FabricDocLibrary:"",FabricFormLibrary:"",FabricFormLibraryMirrored:"",FabricReportLibrary:"",FabricReportLibraryMirrored:"",FabricPublicFolder:"",FabricFolderSearch:"",FabricMovetoFolder:"",FabricUnsyncFolder:"",FabricSyncFolder:"",FabricOpenFolderHorizontal:"",FabricFolder:"",FabricFolderFill:"",FabricNewFolder:"",FabricPictureLibrary:"",PhotoVideoMedia:"",AddFavorite:""}},t)}function Ooe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-9"',src:"url('".concat(e,"fabric-icons-9-c6162b42.woff') format('woff')")},icons:{AddFavoriteFill:"",BufferTimeBefore:"",BufferTimeAfter:"",BufferTimeBoth:"",PublishContent:"",ClipboardList:"",ClipboardListMirrored:"",CannedChat:"",SkypeForBusinessLogo:"",TabCenter:"",PageCheckedin:"",PageList:"",ReadOutLoud:"",CaretBottomLeftSolid8:"",CaretBottomRightSolid8:"",FolderHorizontal:"",MicrosoftStaffhubLogo:"",GiftboxOpen:"",StatusCircleOuter:"",StatusCircleInner:"",StatusCircleRing:"",StatusTriangleOuter:"",StatusTriangleInner:"",StatusTriangleExclamation:"",StatusCircleExclamation:"",StatusCircleErrorX:"",StatusCircleInfo:"",StatusCircleBlock:"",StatusCircleBlock2:"",StatusCircleQuestionMark:"",StatusCircleSync:"",Toll:"",ExploreContentSingle:"",CollapseContent:"",CollapseContentSingle:"",InfoSolid:"",GroupList:"",ProgressRingDots:"",CaloriesAdd:"",BranchFork:"",MuteChat:"",AddHome:"",AddWork:"",MobileReport:"",ScaleVolume:"",HardDriveGroup:"",FastMode:"",ToggleLeft:"",ToggleRight:"",TriangleShape:"",RectangleShape:"",CubeShape:"",Trophy2:"",BucketColor:"",BucketColorFill:"",Taskboard:"",SingleColumn:"",DoubleColumn:"",TripleColumn:"",ColumnLeftTwoThirds:"",ColumnRightTwoThirds:"",AccessLogoFill:"",AnalyticsLogo:"",AnalyticsQuery:"",NewAnalyticsQuery:"",AnalyticsReport:"",WordLogo:"",WordLogoFill:"",ExcelLogo:"",ExcelLogoFill:"",OneNoteLogo:"",OneNoteLogoFill:"",OutlookLogo:"",OutlookLogoFill:"",PowerPointLogo:"",PowerPointLogoFill:"",PublisherLogo:"",PublisherLogoFill:"",ScheduleEventAction:"",FlameSolid:"",ServerProcesses:"",Server:"",SaveAll:"",LinkedInLogo:"",Decimals:"",SidePanelMirrored:"",ProtectRestrict:"",Blog:"",UnknownMirrored:"",PublicContactCardMirrored:"",GridViewSmall:"",GridViewMedium:"",GridViewLarge:"",Step:"",StepInsert:"",StepShared:"",StepSharedAdd:"",StepSharedInsert:"",ViewDashboard:"",ViewList:""}},t)}function Noe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-10"',src:"url('".concat(e,"fabric-icons-10-c4ded8e4.woff') format('woff')")},icons:{ViewListGroup:"",ViewListTree:"",TriggerAuto:"",TriggerUser:"",PivotChart:"",StackedBarChart:"",StackedLineChart:"",BuildQueue:"",BuildQueueNew:"",UserFollowed:"",ContactLink:"",Stack:"",Bullseye:"",VennDiagram:"",FiveTileGrid:"",FocalPoint:"",Insert:"",RingerRemove:"",TeamsLogoInverse:"",TeamsLogo:"",TeamsLogoFill:"",SkypeForBusinessLogoFill:"",SharepointLogo:"",SharepointLogoFill:"",DelveLogo:"",DelveLogoFill:"",OfficeVideoLogo:"",OfficeVideoLogoFill:"",ExchangeLogo:"",ExchangeLogoFill:"",Signin:"",DocumentApproval:"",CloneToDesktop:"",InstallToDrive:"",Blur:"",Build:"",ProcessMetaTask:"",BranchFork2:"",BranchLocked:"",BranchCommit:"",BranchCompare:"",BranchMerge:"",BranchPullRequest:"",BranchSearch:"",BranchShelveset:"",RawSource:"",MergeDuplicate:"",RowsGroup:"",RowsChild:"",Deploy:"",Redeploy:"",ServerEnviroment:"",VisioDiagram:"",HighlightMappedShapes:"",TextCallout:"",IconSetsFlag:"",VisioLogo:"",VisioLogoFill:"",VisioDocument:"",TimelineProgress:"",TimelineDelivery:"",Backlog:"",TeamFavorite:"",TaskGroup:"",TaskGroupMirrored:"",ScopeTemplate:"",AssessmentGroupTemplate:"",NewTeamProject:"",CommentAdd:"",CommentNext:"",CommentPrevious:"",ShopServer:"",LocaleLanguage:"",QueryList:"",UserSync:"",UserPause:"",StreamingOff:"",ArrowTallUpLeft:"",ArrowTallUpRight:"",ArrowTallDownLeft:"",ArrowTallDownRight:"",FieldEmpty:"",FieldFilled:"",FieldChanged:"",FieldNotChanged:"",RingerOff:"",PlayResume:"",BulletedList2:"",BulletedList2Mirrored:"",ImageCrosshair:"",GitGraph:"",Repo:"",RepoSolid:"",FolderQuery:"",FolderList:"",FolderListMirrored:"",LocationOutline:"",POISolid:"",CalculatorNotEqualTo:"",BoxSubtractSolid:""}},t)}function Loe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-11"',src:"url('".concat(e,"fabric-icons-11-2a8393d6.woff') format('woff')")},icons:{BoxAdditionSolid:"",BoxMultiplySolid:"",BoxPlaySolid:"",BoxCheckmarkSolid:"",CirclePauseSolid:"",CirclePause:"",MSNVideosSolid:"",CircleStopSolid:"",CircleStop:"",NavigateBack:"",NavigateBackMirrored:"",NavigateForward:"",NavigateForwardMirrored:"",UnknownSolid:"",UnknownMirroredSolid:"",CircleAddition:"",CircleAdditionSolid:"",FilePDB:"",FileTemplate:"",FileSQL:"",FileJAVA:"",FileASPX:"",FileCSS:"",FileSass:"",FileLess:"",FileHTML:"",JavaScriptLanguage:"",CSharpLanguage:"",CSharp:"",VisualBasicLanguage:"",VB:"",CPlusPlusLanguage:"",CPlusPlus:"",FSharpLanguage:"",FSharp:"",TypeScriptLanguage:"",PythonLanguage:"",PY:"",CoffeeScript:"",MarkDownLanguage:"",FullWidth:"",FullWidthEdit:"",Plug:"",PlugSolid:"",PlugConnected:"",PlugDisconnected:"",UnlockSolid:"",Variable:"",Parameter:"",CommentUrgent:"",Storyboard:"",DiffInline:"",DiffSideBySide:"",ImageDiff:"",ImagePixel:"",FileBug:"",FileCode:"",FileComment:"",BusinessHoursSign:"",FileImage:"",FileSymlink:"",AutoFillTemplate:"",WorkItem:"",WorkItemBug:"",LogRemove:"",ColumnOptions:"",Packages:"",BuildIssue:"",AssessmentGroup:"",VariableGroup:"",FullHistory:"",Wheelchair:"",SingleColumnEdit:"",DoubleColumnEdit:"",TripleColumnEdit:"",ColumnLeftTwoThirdsEdit:"",ColumnRightTwoThirdsEdit:"",StreamLogo:"",PassiveAuthentication:"",AlertSolid:"",MegaphoneSolid:"",TaskSolid:"",ConfigurationSolid:"",BugSolid:"",CrownSolid:"",Trophy2Solid:"",QuickNoteSolid:"",ConstructionConeSolid:"",PageListSolid:"",PageListMirroredSolid:"",StarburstSolid:"",ReadingModeSolid:"",SadSolid:"",HealthSolid:"",ShieldSolid:"",GiftBoxSolid:"",ShoppingCartSolid:"",MailSolid:"",ChatSolid:"",RibbonSolid:""}},t)}function xoe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-12"',src:"url('".concat(e,"fabric-icons-12-7e945a1e.woff') format('woff')")},icons:{FinancialSolid:"",FinancialMirroredSolid:"",HeadsetSolid:"",PermissionsSolid:"",ParkingSolid:"",ParkingMirroredSolid:"",DiamondSolid:"",AsteriskSolid:"",OfflineStorageSolid:"",BankSolid:"",DecisionSolid:"",Parachute:"",ParachuteSolid:"",FiltersSolid:"",ColorSolid:"",ReviewSolid:"",ReviewRequestSolid:"",ReviewRequestMirroredSolid:"",ReviewResponseSolid:"",FeedbackRequestSolid:"",FeedbackRequestMirroredSolid:"",FeedbackResponseSolid:"",WorkItemBar:"",WorkItemBarSolid:"",Separator:"",NavigateExternalInline:"",PlanView:"",TimelineMatrixView:"",EngineeringGroup:"",ProjectCollection:"",CaretBottomRightCenter8:"",CaretBottomLeftCenter8:"",CaretTopRightCenter8:"",CaretTopLeftCenter8:"",DonutChart:"",ChevronUnfold10:"",ChevronFold10:"",DoubleChevronDown8:"",DoubleChevronUp8:"",DoubleChevronLeft8:"",DoubleChevronRight8:"",ChevronDownEnd6:"",ChevronUpEnd6:"",ChevronLeftEnd6:"",ChevronRightEnd6:"",ContextMenu:"",AzureAPIManagement:"",AzureServiceEndpoint:"",VSTSLogo:"",VSTSAltLogo1:"",VSTSAltLogo2:"",FileTypeSolution:"",WordLogoInverse16:"",WordLogo16:"",WordLogoFill16:"",PowerPointLogoInverse16:"",PowerPointLogo16:"",PowerPointLogoFill16:"",ExcelLogoInverse16:"",ExcelLogo16:"",ExcelLogoFill16:"",OneNoteLogoInverse16:"",OneNoteLogo16:"",OneNoteLogoFill16:"",OutlookLogoInverse16:"",OutlookLogo16:"",OutlookLogoFill16:"",PublisherLogoInverse16:"",PublisherLogo16:"",PublisherLogoFill16:"",VisioLogoInverse16:"",VisioLogo16:"",VisioLogoFill16:"",TestBeaker:"",TestBeakerSolid:"",TestExploreSolid:"",TestAutoSolid:"",TestUserSolid:"",TestImpactSolid:"",TestPlan:"",TestStep:"",TestParameter:"",TestSuite:"",TestCase:"",Sprint:"",SignOut:"",TriggerApproval:"",Rocket:"",AzureKeyVault:"",Onboarding:"",Transition:"",LikeSolid:"",DislikeSolid:"",CRMCustomerInsightsApp:"",EditCreate:"",PlayReverseResume:"",PlayReverse:"",SearchData:"",UnSetColor:"",DeclineCall:""}},t)}function Foe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-13"',src:"url('".concat(e,"fabric-icons-13-c3989a02.woff') format('woff')")},icons:{RectangularClipping:"",TeamsLogo16:"",TeamsLogoFill16:"",Spacer:"",SkypeLogo16:"",SkypeForBusinessLogo16:"",SkypeForBusinessLogoFill16:"",FilterSolid:"",MailUndelivered:"",MailTentative:"",MailTentativeMirrored:"",MailReminder:"",ReceiptUndelivered:"",ReceiptTentative:"",ReceiptTentativeMirrored:"",Inbox:"",IRMReply:"",IRMReplyMirrored:"",IRMForward:"",IRMForwardMirrored:"",VoicemailIRM:"",EventAccepted:"",EventTentative:"",EventTentativeMirrored:"",EventDeclined:"",IDBadge:"",BackgroundColor:"",OfficeFormsLogoInverse16:"",OfficeFormsLogo:"",OfficeFormsLogoFill:"",OfficeFormsLogo16:"",OfficeFormsLogoFill16:"",OfficeFormsLogoInverse24:"",OfficeFormsLogo24:"",OfficeFormsLogoFill24:"",PageLock:"",NotExecuted:"",NotImpactedSolid:"",FieldReadOnly:"",FieldRequired:"",BacklogBoard:"",ExternalBuild:"",ExternalTFVC:"",ExternalXAML:"",IssueSolid:"",DefectSolid:"",LadybugSolid:"",NugetLogo:"",TFVCLogo:"",ProjectLogo32:"",ProjectLogoFill32:"",ProjectLogo16:"",ProjectLogoFill16:"",SwayLogo32:"",SwayLogoFill32:"",SwayLogo16:"",SwayLogoFill16:"",ClassNotebookLogo32:"",ClassNotebookLogoFill32:"",ClassNotebookLogo16:"",ClassNotebookLogoFill16:"",ClassNotebookLogoInverse32:"",ClassNotebookLogoInverse16:"",StaffNotebookLogo32:"",StaffNotebookLogoFill32:"",StaffNotebookLogo16:"",StaffNotebookLogoFill16:"",StaffNotebookLogoInverted32:"",StaffNotebookLogoInverted16:"",KaizalaLogo:"",TaskLogo:"",ProtectionCenterLogo32:"",GallatinLogo:"",Globe2:"",Guitar:"",Breakfast:"",Brunch:"",BeerMug:"",Vacation:"",Teeth:"",Taxi:"",Chopsticks:"",SyncOccurence:"",UnsyncOccurence:"",GIF:"",PrimaryCalendar:"",SearchCalendar:"",VideoOff:"",MicrosoftFlowLogo:"",BusinessCenterLogo:"",ToDoLogoBottom:"",ToDoLogoTop:"",EditSolid12:"",EditSolidMirrored12:"",UneditableSolid12:"",UneditableSolidMirrored12:"",UneditableMirrored:"",AdminALogo32:"",AdminALogoFill32:"",ToDoLogoInverse:""}},t)}function Uoe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-14"',src:"url('".concat(e,"fabric-icons-14-5cf58db8.woff') format('woff')")},icons:{Snooze:"",WaffleOffice365:"",ImageSearch:"",NewsSearch:"",VideoSearch:"",R:"",FontColorA:"",FontColorSwatch:"",LightWeight:"",NormalWeight:"",SemiboldWeight:"",GroupObject:"",UngroupObject:"",AlignHorizontalLeft:"",AlignHorizontalCenter:"",AlignHorizontalRight:"",AlignVerticalTop:"",AlignVerticalCenter:"",AlignVerticalBottom:"",HorizontalDistributeCenter:"",VerticalDistributeCenter:"",Ellipse:"",Line:"",Octagon:"",Hexagon:"",Pentagon:"",RightTriangle:"",HalfCircle:"",QuarterCircle:"",ThreeQuarterCircle:"","6PointStar":"","12PointStar":"",ArrangeBringToFront:"",ArrangeSendToBack:"",ArrangeSendBackward:"",ArrangeBringForward:"",BorderDash:"",BorderDot:"",LineStyle:"",LineThickness:"",WindowEdit:"",HintText:"",MediaAdd:"",AnchorLock:"",AutoHeight:"",ChartSeries:"",ChartXAngle:"",ChartYAngle:"",Combobox:"",LineSpacing:"",Padding:"",PaddingTop:"",PaddingBottom:"",PaddingLeft:"",PaddingRight:"",NavigationFlipper:"",AlignJustify:"",TextOverflow:"",VisualsFolder:"",VisualsStore:"",PictureCenter:"",PictureFill:"",PicturePosition:"",PictureStretch:"",PictureTile:"",Slider:"",SliderHandleSize:"",DefaultRatio:"",NumberSequence:"",GUID:"",ReportAdd:"",DashboardAdd:"",MapPinSolid:"",WebPublish:"",PieSingleSolid:"",BlockedSolid:"",DrillDown:"",DrillDownSolid:"",DrillExpand:"",DrillShow:"",SpecialEvent:"",OneDriveFolder16:"",FunctionalManagerDashboard:"",BIDashboard:"",CodeEdit:"",RenewalCurrent:"",RenewalFuture:"",SplitObject:"",BulkUpload:"",DownloadDocument:"",GreetingCard:"",Flower:"",WaitlistConfirm:"",WaitlistConfirmMirrored:"",LaptopSecure:"",DragObject:"",EntryView:"",EntryDecline:"",ContactCardSettings:"",ContactCardSettingsMirrored:""}},t)}function Boe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-15"',src:"url('".concat(e,"fabric-icons-15-3807251b.woff') format('woff')")},icons:{CalendarSettings:"",CalendarSettingsMirrored:"",HardDriveLock:"",HardDriveUnlock:"",AccountManagement:"",ReportWarning:"",TransitionPop:"",TransitionPush:"",TransitionEffect:"",LookupEntities:"",ExploreData:"",AddBookmark:"",SearchBookmark:"",DrillThrough:"",MasterDatabase:"",CertifiedDatabase:"",MaximumValue:"",MinimumValue:"",VisualStudioIDELogo32:"",PasteAsText:"",PasteAsCode:"",BrowserTab:"",BrowserTabScreenshot:"",DesktopScreenshot:"",FileYML:"",ClipboardSolid:"",FabricUserFolder:"",FabricNetworkFolder:"",BullseyeTarget:"",AnalyticsView:"",Video360Generic:"",Untag:"",Leave:"",Trending12:"",Blocked12:"",Warning12:"",CheckedOutByOther12:"",CheckedOutByYou12:"",CircleShapeSolid:"",SquareShapeSolid:"",TriangleShapeSolid:"",DropShapeSolid:"",RectangleShapeSolid:"",ZoomToFit:"",InsertColumnsLeft:"",InsertColumnsRight:"",InsertRowsAbove:"",InsertRowsBelow:"",DeleteColumns:"",DeleteRows:"",DeleteRowsMirrored:"",DeleteTable:"",AccountBrowser:"",VersionControlPush:"",StackedColumnChart2:"",TripleColumnWide:"",QuadColumn:"",WhiteBoardApp16:"",WhiteBoardApp32:"",PinnedSolid:"",InsertSignatureLine:"",ArrangeByFrom:"",Phishing:"",CreateMailRule:"",PublishCourse:"",DictionaryRemove:"",UserRemove:"",UserEvent:"",Encryption:"",PasswordField:"",OpenInNewTab:"",Hide3:"",VerifiedBrandSolid:"",MarkAsProtected:"",AuthenticatorApp:"",WebTemplate:"",DefenderTVM:"",MedalSolid:"",D365TalentLearn:"",D365TalentInsight:"",D365TalentHRCore:"",BacklogList:"",ButtonControl:"",TableGroup:"",MountainClimbing:"",TagUnknown:"",TagUnknownMirror:"",TagUnknown12:"",TagUnknown12Mirror:"",Link12:"",Presentation:"",Presentation12:"",Lock12:"",BuildDefinition:"",ReleaseDefinition:"",SaveTemplate:"",UserGauge:"",BlockedSiteSolid12:"",TagSolid:"",OfficeChat:""}},t)}function Voe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-16"',src:"url('".concat(e,"fabric-icons-16-9cf93f3b.woff') format('woff')")},icons:{OfficeChatSolid:"",MailSchedule:"",WarningSolid:"",Blocked2Solid:"",SkypeCircleArrow:"",SkypeArrow:"",SyncStatus:"",SyncStatusSolid:"",ProjectDocument:"",ToDoLogoOutline:"",VisioOnlineLogoFill32:"",VisioOnlineLogo32:"",VisioOnlineLogoCloud32:"",VisioDiagramSync:"",Event12:"",EventDateMissed12:"",UserOptional:"",ResponsesMenu:"",DoubleDownArrow:"",DistributeDown:"",BookmarkReport:"",FilterSettings:"",GripperDotsVertical:"",MailAttached:"",AddIn:"",LinkedDatabase:"",TableLink:"",PromotedDatabase:"",BarChartVerticalFilter:"",BarChartVerticalFilterSolid:"",MicOff2:"",MicrosoftTranslatorLogo:"",ShowTimeAs:"",FileRequest:"",WorkItemAlert:"",PowerBILogo16:"",PowerBILogoBackplate16:"",BulletedListText:"",BulletedListBullet:"",BulletedListTextMirrored:"",BulletedListBulletMirrored:"",NumberedListText:"",NumberedListNumber:"",NumberedListTextMirrored:"",NumberedListNumberMirrored:"",RemoveLinkChain:"",RemoveLinkX:"",FabricTextHighlight:"",ClearFormattingA:"",ClearFormattingEraser:"",Photo2Fill:"",IncreaseIndentText:"",IncreaseIndentArrow:"",DecreaseIndentText:"",DecreaseIndentArrow:"",IncreaseIndentTextMirrored:"",IncreaseIndentArrowMirrored:"",DecreaseIndentTextMirrored:"",DecreaseIndentArrowMirrored:"",CheckListText:"",CheckListCheck:"",CheckListTextMirrored:"",CheckListCheckMirrored:"",NumberSymbol:"",Coupon:"",VerifiedBrand:"",ReleaseGate:"",ReleaseGateCheck:"",ReleaseGateError:"",M365InvoicingLogo:"",RemoveFromShoppingList:"",ShieldAlert:"",FabricTextHighlightComposite:"",Dataflows:"",GenericScanFilled:"",DiagnosticDataBarTooltip:"",SaveToMobile:"",Orientation2:"",ScreenCast:"",ShowGrid:"",SnapToGrid:"",ContactList:"",NewMail:"",EyeShadow:"",FabricFolderConfirm:"",InformationBarriers:"",CommentActive:"",ColumnVerticalSectionEdit:"",WavingHand:"",ShakeDevice:"",SmartGlassRemote:"",Rotate90Clockwise:"",Rotate90CounterClockwise:"",CampaignTemplate:"",ChartTemplate:"",PageListFilter:"",SecondaryNav:"",ColumnVerticalSection:"",SkypeCircleSlash:"",SkypeSlash:""}},t)}function Hoe(e,t){void 0===e&&(e=""),WH({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-17"',src:"url('".concat(e,"fabric-icons-17-0c4ed701.woff') format('woff')")},icons:{CustomizeToolbar:"",DuplicateRow:"",RemoveFromTrash:"",MailOptions:"",Childof:"",Footer:"",Header:"",BarChartVerticalFill:"",StackedColumnChart2Fill:"",PlainText:"",AccessibiltyChecker:"",DatabaseSync:"",ReservationOrders:"",TabOneColumn:"",TabTwoColumn:"",TabThreeColumn:"",BulletedTreeList:"",MicrosoftTranslatorLogoGreen:"",MicrosoftTranslatorLogoBlue:"",InternalInvestigation:"",AddReaction:"",ContactHeart:"",VisuallyImpaired:"",EventToDoLogo:"",Variable2:"",ModelingView:"",DisconnectVirtualMachine:"",ReportLock:"",Uneditable2:"",Uneditable2Mirrored:"",BarChartVerticalEdit:"",GlobalNavButtonActive:"",PollResults:"",Rerun:"",QandA:"",QandAMirror:"",BookAnswers:"",AlertSettings:"",TrimStart:"",TrimEnd:"",TableComputed:"",DecreaseIndentLegacy:"",IncreaseIndentLegacy:"",SizeLegacy:""}},t)}r$("@fluentui/font-icons-mdl2","8.5.58");var $oe="".concat("https://res.cdn.office.net/files/fabric-cdn-prod_20241209.001","/assets/icons/"),joe=_B();!function(e){var t,i;void 0===e&&(e=(null===(t=null==joe?void 0:joe.FabricConfig)||void 0===t?void 0:t.iconBaseUrl)||(null===(i=null==joe?void 0:joe.FabricConfig)||void 0===i?void 0:i.fontBaseUrl)||$oe),[boe,_oe,Ioe,woe,Aoe,Poe,Roe,Moe,Doe,koe,Ooe,Noe,Loe,xoe,Foe,Uoe,Boe,Voe,Hoe].forEach((function(t){return t(e,undefined)})),KH("trash","delete"),KH("onedrive","onedrivelogo"),KH("alertsolid12","eventdatemissed12"),KH("sixpointstar","6pointstar"),KH("twelvepointstar","12pointstar"),KH("toggleon","toggleleft"),KH("toggleoff","toggleright")}();const Goe=async function(t,n,r){const{userId:s,token:a,groupId:o,displayName:l,locator:c,options:u}=t,h=await function(e){return mU(this,void 0,void 0,(function*(){if(QN(e.userId))throw new Error("Microsoft Teams user identifier is not supported by AzureCommunicationCallAdapter. Instead use TeamsCallAdapter.");return CU({userId:e.userId,displayName:e.displayName,credential:e.credential,locator:e.locator,targetCallees:e.targetCallees,options:e.options})}))}({userId:s,displayName:l??"anonymous",credential:new d(a),locator:c||{groupId:o},options:u});if(!n)throw new Error("Failed to find the root element");return(0,i.H)(n).render(e.createElement(Coe,{...r,adapter:h},null)),h}})(),s})()));